blob: 3a6f5cacc1157959d9a6be79d1780c36d093dacf [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
Douglas Gregor5101c242008-12-05 18:15:24 +0000459/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
460/// that the template parameter 'PrevDecl' is being shadowed by a new
461/// declaration at location Loc. Returns true to indicate that this is
462/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000463void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000464 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000465
466 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000467 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000468 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000469
470 // C++ [temp.local]p4:
471 // A template-parameter shall not be redeclared within its
472 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000473 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000474 << cast<NamedDecl>(PrevDecl)->getDeclName();
475 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregor5101c242008-12-05 18:15:24 +0000476}
477
Douglas Gregor463421d2009-03-03 04:44:36 +0000478/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000479/// the parameter D to reference the templated declaration and return a pointer
480/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000481TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
482 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
483 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000484 return Temp;
485 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000486 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000487}
488
Douglas Gregoreb29d182011-01-05 17:40:24 +0000489ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
490 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000492 "Only template template arguments can be pack expansions here");
493 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
494 "Template template argument pack expansion without packs");
495 ParsedTemplateArgument Result(*this);
496 Result.EllipsisLoc = EllipsisLoc;
497 return Result;
498}
499
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000500static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
501 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000503 switch (Arg.getKind()) {
504 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000505 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000506 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000508 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000509 return TemplateArgumentLoc(TemplateArgument(T), DI);
510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000512 case ParsedTemplateArgument::NonType: {
513 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
514 return TemplateArgumentLoc(TemplateArgument(E), E);
515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000516
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000517 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000518 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000519 TemplateArgument TArg;
520 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000521 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000522 else
523 TArg = Template;
524 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000525 Arg.getScopeSpec().getWithLocInContext(
526 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000527 Arg.getLocation(),
528 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000529 }
530 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000531
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000532 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000533}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000535/// \brief Translates template arguments as provided by the parser
536/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000537void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
538 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000539 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000540 TemplateArgs.addArgument(translateTemplateArgument(*this,
541 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000542}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
Richard Smithb80d5402013-06-25 22:21:36 +0000544static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
545 SourceLocation Loc,
546 IdentifierInfo *Name) {
547 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
548 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
549 if (PrevDecl && PrevDecl->isTemplateParameter())
550 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
551}
552
Douglas Gregor5101c242008-12-05 18:15:24 +0000553/// ActOnTypeParameter - Called when a C++ template type parameter
554/// (e.g., "typename T") has been parsed. Typename specifies whether
555/// the keyword "typename" was used to declare the type parameter
556/// (otherwise, "class" was used), and KeyLoc is the location of the
557/// "class" or "typename" keyword. ParamName is the name of the
558/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000559/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000560/// If the type parameter has a default argument, it will be added
561/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000562Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000563 SourceLocation EllipsisLoc,
564 SourceLocation KeyLoc,
565 IdentifierInfo *ParamName,
566 SourceLocation ParamNameLoc,
567 unsigned Depth, unsigned Position,
568 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000569 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000570 assert(S->isTemplateParamScope() &&
571 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000572
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000573 SourceLocation Loc = ParamNameLoc;
574 if (!ParamName)
575 Loc = KeyLoc;
576
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000577 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000578 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000579 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000580 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000581 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000582 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000583
584 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000585 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
586
Douglas Gregor5101c242008-12-05 18:15:24 +0000587 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000588 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000589 IdResolver.AddDecl(Param);
590 }
591
Douglas Gregorf5500772011-01-05 15:48:55 +0000592 // C++0x [temp.param]p9:
593 // A default template-argument may be specified for any kind of
594 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000595 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000596 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
David Blaikieefdccaa2016-01-15 23:43:34 +0000597 DefaultArg = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000598 }
599
Douglas Gregordc13ded2010-07-01 00:00:45 +0000600 // Handle the default argument, if provided.
601 if (DefaultArg) {
602 TypeSourceInfo *DefaultTInfo;
603 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604
Douglas Gregordc13ded2010-07-01 00:00:45 +0000605 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000607 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000608 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000609 UPPC_DefaultArgument))
610 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611
Douglas Gregordc13ded2010-07-01 00:00:45 +0000612 // Check the template argument itself.
613 if (CheckTemplateArgument(Param, DefaultTInfo)) {
614 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000615 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000616 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
Richard Smith1469b912015-06-10 00:29:03 +0000618 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620
John McCall48871652010-08-21 09:40:31 +0000621 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000622}
623
Douglas Gregor463421d2009-03-03 04:44:36 +0000624/// \brief Check that the type of a non-type template parameter is
625/// well-formed.
626///
627/// \returns the (possibly-promoted) parameter type if valid;
628/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000629QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000630Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000631 // We don't allow variably-modified types as the type of non-type template
632 // parameters.
633 if (T->isVariablyModifiedType()) {
634 Diag(Loc, diag::err_variably_modified_nontype_template_param)
635 << T;
636 return QualType();
637 }
638
Douglas Gregor463421d2009-03-03 04:44:36 +0000639 // C++ [temp.param]p4:
640 //
641 // A non-type template-parameter shall have one of the following
642 // (optionally cv-qualified) types:
643 //
644 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000645 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000646 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000647 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000648 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000649 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000650 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000651 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000652 // -- std::nullptr_t.
653 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000654 // If T is a dependent type, we can't do the check now, so we
655 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000656 T->isDependentType()) {
657 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
658 // are ignored when determining its type.
659 return T.getUnqualifiedType();
660 }
661
Douglas Gregor463421d2009-03-03 04:44:36 +0000662 // C++ [temp.param]p8:
663 //
664 // A non-type template-parameter of type "array of T" or
665 // "function returning T" is adjusted to be of type "pointer to
666 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000667 else if (T->isArrayType() || T->isFunctionType())
668 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor463421d2009-03-03 04:44:36 +0000670 Diag(Loc, diag::err_template_nontype_parm_bad_type)
671 << T;
672
673 return QualType();
674}
675
John McCall48871652010-08-21 09:40:31 +0000676Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
677 unsigned Depth,
678 unsigned Position,
679 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000680 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000681 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
682 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000683
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000684 assert(S->isTemplateParamScope() &&
685 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000686 bool Invalid = false;
687
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000688 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
689 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000690 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000691 Invalid = true;
692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000693
Richard Smithb80d5402013-06-25 22:21:36 +0000694 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000695 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000696 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000697 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000698 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000699 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000701 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000702 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000703
Douglas Gregor5101c242008-12-05 18:15:24 +0000704 if (Invalid)
705 Param->setInvalidDecl();
706
Richard Smithb80d5402013-06-25 22:21:36 +0000707 if (ParamName) {
708 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
709 ParamName);
710
Douglas Gregor5101c242008-12-05 18:15:24 +0000711 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000712 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000713 IdResolver.AddDecl(Param);
714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715
Douglas Gregorf5500772011-01-05 15:48:55 +0000716 // C++0x [temp.param]p9:
717 // A default template-argument may be specified for any kind of
718 // template-parameter that is not a template parameter pack.
719 if (Default && IsParameterPack) {
720 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000721 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000722 }
723
Douglas Gregordc13ded2010-07-01 00:00:45 +0000724 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000725 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000726 // Check for unexpanded parameter packs.
727 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
728 return Param;
729
Douglas Gregordc13ded2010-07-01 00:00:45 +0000730 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000731 ExprResult DefaultRes =
732 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000733 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000734 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000735 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000736 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000737 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738
Richard Smith1469b912015-06-10 00:29:03 +0000739 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741
John McCall48871652010-08-21 09:40:31 +0000742 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000743}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000744
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000745/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000746/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000747/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000748Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
749 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000750 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000751 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000752 IdentifierInfo *Name,
753 SourceLocation NameLoc,
754 unsigned Depth,
755 unsigned Position,
756 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000757 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000758 assert(S->isTemplateParamScope() &&
759 "Template template parameter not in template parameter scope!");
760
761 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000762 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000763 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000764 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000765 NameLoc.isInvalid()? TmpLoc : NameLoc,
766 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000767 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000768 Param->setAccess(AS_public);
769
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000770 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000771 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000772 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000773 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
774
John McCall48871652010-08-21 09:40:31 +0000775 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000776 IdResolver.AddDecl(Param);
777 }
778
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000779 if (Params->size() == 0) {
780 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
781 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
782 Param->setInvalidDecl();
783 }
784
Douglas Gregorf5500772011-01-05 15:48:55 +0000785 // C++0x [temp.param]p9:
786 // A default template-argument may be specified for any kind of
787 // template-parameter that is not a template parameter pack.
788 if (IsParameterPack && !Default.isInvalid()) {
789 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
790 Default = ParsedTemplateArgument();
791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000792
Douglas Gregordc13ded2010-07-01 00:00:45 +0000793 if (!Default.isInvalid()) {
794 // Check only that we have a template template argument. We don't want to
795 // try to check well-formedness now, because our template template parameter
796 // might have dependent types in its template parameters, which we wouldn't
797 // be able to match now.
798 //
799 // If none of the template template parameter's template arguments mention
800 // other template parameters, we could actually perform more checking here.
801 // However, it isn't worth doing.
802 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
803 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
Faisal Valib8b04f82016-03-26 20:46:45 +0000804 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
Douglas Gregordc13ded2010-07-01 00:00:45 +0000805 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000806 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000808
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000809 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000811 DefaultArg.getArgument().getAsTemplate(),
812 UPPC_DefaultArgument))
813 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
Richard Smith1469b912015-06-10 00:29:03 +0000815 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
John McCall48871652010-08-21 09:40:31 +0000818 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000819}
820
Hubert Tongf608c052016-04-29 18:05:37 +0000821/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
822/// constrained by RequiresClause, that contains the template parameters in
823/// Params.
Richard Trieu9becef62011-09-09 03:18:59 +0000824TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000825Sema::ActOnTemplateParameterList(unsigned Depth,
826 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000827 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000828 SourceLocation LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000829 ArrayRef<Decl *> Params,
Hubert Tongf608c052016-04-29 18:05:37 +0000830 SourceLocation RAngleLoc,
831 Expr *RequiresClause) {
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000832 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000833 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000834
Hubert Tongf608c052016-04-29 18:05:37 +0000835 // FIXME: store RequiresClause
David Majnemer902f8c62015-12-27 07:16:27 +0000836 return TemplateParameterList::Create(
837 Context, TemplateLoc, LAngleLoc,
838 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
839 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000840}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000841
John McCall3e11ebe2010-03-15 10:12:16 +0000842static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
843 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000844 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000845}
846
John McCallfaf5fb42010-08-26 23:41:50 +0000847DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000848Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000849 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000850 IdentifierInfo *Name, SourceLocation NameLoc,
851 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000852 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000853 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000854 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000855 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000856 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000857 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000858 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000859 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000860 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000861 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000862
863 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000864 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000865 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000866
Abramo Bagnara6150c882010-05-11 21:36:43 +0000867 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
868 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000869
870 // There is no such thing as an unnamed class template.
871 if (!Name) {
872 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000873 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000874 }
875
Richard Smith6483d222012-04-21 01:27:54 +0000876 // Find any previous declaration with this name. For a friend with no
877 // scope explicitly specified, we only look for tag declarations (per
878 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000879 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000880 LookupResult Previous(*this, Name, NameLoc,
881 (SS.isEmpty() && TUK == TUK_Friend)
882 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000883 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000884 if (SS.isNotEmpty() && !SS.isInvalid()) {
885 SemanticContext = computeDeclContext(SS, true);
886 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000887 // FIXME: Horrible, horrible hack! We can't currently represent this
888 // in the AST, and historically we have just ignored such friend
889 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000890 Diag(NameLoc, TUK == TUK_Friend
891 ? diag::warn_template_qualified_friend_ignored
892 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000893 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000894 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000895 }
Mike Stump11289f42009-09-09 15:08:12 +0000896
John McCall0b66eb32010-05-01 00:40:08 +0000897 if (RequireCompleteDeclContext(SS, SemanticContext))
898 return true;
899
Douglas Gregor041b0842011-10-14 15:31:12 +0000900 // If we're adding a template to a dependent context, we may need to
901 // rebuilding some of the types used within the template parameter list,
902 // now that we know what the current instantiation is.
903 if (SemanticContext->isDependentContext()) {
904 ContextRAII SavedContext(*this, SemanticContext);
905 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
906 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000907 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
908 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000909
John McCall27b18f82009-11-17 02:14:36 +0000910 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000911 } else {
912 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000913
914 // C++14 [class.mem]p14:
915 // If T is the name of a class, then each of the following shall have a
916 // name different from T:
917 // -- every member template of class T
918 if (TUK != TUK_Friend &&
919 DiagnoseClassNameShadow(SemanticContext,
920 DeclarationNameInfo(Name, NameLoc)))
921 return true;
922
John McCall27b18f82009-11-17 02:14:36 +0000923 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000926 if (Previous.isAmbiguous())
927 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000928
Craig Topperc3ec1492014-05-26 06:22:03 +0000929 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000930 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000931 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000932
Serge Pavlove50bf752016-06-10 04:39:07 +0000933 if (PrevDecl && PrevDecl->isTemplateParameter()) {
934 // Maybe we will complain about the shadowed template parameter.
935 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
936 // Just pretend that we didn't see the previous declaration.
937 PrevDecl = nullptr;
938 }
939
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000940 // If there is a previous declaration with the same name, check
941 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000942 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000943 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000944
945 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000947 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000948 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000949 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
950 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000952 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
953 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
954 PrevClassTemplate
955 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
956 ->getSpecializedTemplate();
957 }
958 }
959
John McCalld43784f2009-12-18 11:25:59 +0000960 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000961 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000962 // [...] When looking for a prior declaration of a class or a function
963 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000964 // function is neither a qualified name nor a template-id, scopes outside
965 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000966 if (!SS.isSet()) {
967 DeclContext *OutermostContext = CurContext;
968 while (!OutermostContext->isFileContext())
969 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000970
Richard Smith61e582f2012-04-20 07:12:26 +0000971 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000972 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
973 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
974 SemanticContext = PrevDecl->getDeclContext();
975 } else {
976 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000977 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000978 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000979 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000980 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000981
982 // Check that the chosen semantic context doesn't already contain a
983 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +0000984 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +0000985 DeclContext *LookupContext = SemanticContext;
986 while (LookupContext->isTransparentContext())
987 LookupContext = LookupContext->getLookupParent();
988 LookupQualifiedName(Previous, LookupContext);
989
990 if (Previous.isAmbiguous())
991 return true;
992
993 if (Previous.begin() != Previous.end())
994 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000995 }
John McCall90d3bb92009-12-17 23:21:11 +0000996 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000997 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +0000998 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
999 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +00001000 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001
Richard Smithfc805ca2015-07-06 04:43:58 +00001002 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1003 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1004 if (SS.isEmpty() &&
1005 !(PrevClassTemplate &&
1006 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1007 SemanticContext->getRedeclContext()))) {
1008 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1009 Diag(Shadow->getTargetDecl()->getLocation(),
1010 diag::note_using_decl_target);
1011 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1012 // Recover by ignoring the old declaration.
1013 PrevDecl = PrevClassTemplate = nullptr;
1014 }
1015 }
1016
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001017 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +00001018 // Ensure that the template parameter lists are compatible. Skip this check
1019 // for a friend in a dependent context: the template parameter list itself
1020 // could be dependent.
1021 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1022 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001023 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001024 /*Complain=*/true,
1025 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001026 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001027
1028 // C++ [temp.class]p4:
1029 // In a redeclaration, partial specialization, explicit
1030 // specialization or explicit instantiation of a class template,
1031 // the class-key shall agree in kind with the original class
1032 // template declaration (7.1.5.3).
1033 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001034 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001035 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001036 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001037 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001038 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001039 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001040 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001041 }
1042
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001043 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001044 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001045 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001046 // If we have a prior definition that is not visible, treat this as
1047 // simply making that previous definition visible.
1048 NamedDecl *Hidden = nullptr;
1049 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001050 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001051 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1052 assert(Tmpl && "original definition of a class template is not a "
1053 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001054 makeMergedDefinitionVisible(Hidden, KWLoc);
1055 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001056 return Def;
1057 }
1058
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001059 Diag(NameLoc, diag::err_redefinition) << Name;
1060 Diag(Def->getLocation(), diag::note_previous_definition);
1061 // FIXME: Would it make sense to try to "forget" the previous
1062 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001063 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001064 }
Serge Pavlove50bf752016-06-10 04:39:07 +00001065 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001066 } else if (PrevDecl) {
1067 // C++ [temp]p5:
1068 // A class template shall not have the same name as any other
1069 // template, class, function, object, enumeration, enumerator,
1070 // namespace, or type in the same scope (3.3), except as specified
1071 // in (14.5.4).
1072 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1073 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001074 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001075 }
1076
Douglas Gregordba32632009-02-10 19:49:53 +00001077 // Check the template parameter list of this declaration, possibly
1078 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001079 // template declaration. Skip this check for a friend in a dependent
1080 // context, because the template parameter list might be dependent.
1081 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001082 CheckTemplateParameterList(
1083 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001084 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1085 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001086 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1087 SemanticContext->isDependentContext())
1088 ? TPC_ClassTemplateMember
1089 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1090 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001091 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001092
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001093 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001095 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001096 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1097 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001098 : diag::err_member_decl_does_not_match)
1099 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001100 Invalid = true;
1101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001102 }
1103
Mike Stump11289f42009-09-09 15:08:12 +00001104 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001105 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001106 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001107 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001108 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001109 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001110 if (NumOuterTemplateParamLists > 0)
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001111 NewClass->setTemplateParameterListsInfo(
1112 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1113 NumOuterTemplateParamLists));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001114
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001115 // Add alignment attributes if necessary; these attributes are checked when
1116 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001117 if (TUK == TUK_Definition) {
1118 AddAlignmentAttributesForRecord(NewClass);
1119 AddMsStructLayoutForRecord(NewClass);
1120 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001121
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001122 ClassTemplateDecl *NewTemplate
1123 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1124 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001125 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001126 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001127
Douglas Gregor21823bf2011-12-20 18:11:52 +00001128 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001129 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001130
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001131 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001132 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001133 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001134 assert(T->isDependentType() && "Class template type is not dependent?");
1135 (void)T;
1136
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001137 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001138 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001139 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001140 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1141 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001142
Anders Carlsson137108d2009-03-26 01:24:28 +00001143 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001144 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001145 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001146
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001147 // Set the lexical context of these templates
1148 NewClass->setLexicalDeclContext(CurContext);
1149 NewTemplate->setLexicalDeclContext(CurContext);
1150
John McCall9bb74a52009-07-31 02:45:11 +00001151 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001152 NewClass->startDefinition();
1153
1154 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001155 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001156
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001157 if (PrevClassTemplate)
1158 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1159
Rafael Espindola385c0422012-07-13 18:04:45 +00001160 AddPushedVisibilityAttribute(NewClass);
1161
Richard Smith234ff472014-08-23 00:49:01 +00001162 if (TUK != TUK_Friend) {
1163 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1164 Scope *Outer = S;
1165 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1166 Outer = Outer->getParent();
1167 PushOnScopeChains(NewTemplate, Outer);
1168 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001169 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001170 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001171 NewClass->setAccess(PrevClassTemplate->getAccess());
1172 }
John McCall27b5c252009-09-14 21:59:20 +00001173
Richard Smith64017682013-07-17 23:53:16 +00001174 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
John McCall27b5c252009-09-14 21:59:20 +00001176 // Friend templates are visible in fairly strange ways.
1177 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001178 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001179 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001180 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1181 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001184
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001185 FriendDecl *Friend = FriendDecl::Create(
1186 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001187 Friend->setAccess(AS_public);
1188 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001189 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001190
Douglas Gregordba32632009-02-10 19:49:53 +00001191 if (Invalid) {
1192 NewTemplate->setInvalidDecl();
1193 NewClass->setInvalidDecl();
1194 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001195
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001196 ActOnDocumentableDecl(NewTemplate);
1197
John McCall48871652010-08-21 09:40:31 +00001198 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001199}
1200
Douglas Gregored5731f2009-11-25 17:50:39 +00001201/// \brief Diagnose the presence of a default template argument on a
1202/// template parameter, which is ill-formed in certain contexts.
1203///
1204/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001205static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001206 Sema::TemplateParamListContext TPC,
1207 SourceLocation ParamLoc,
1208 SourceRange DefArgRange) {
1209 switch (TPC) {
1210 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001211 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001212 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001213 return false;
1214
1215 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001216 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001218 // A default template-argument shall not be specified in a
1219 // function template declaration or a function template
1220 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001221 // If a friend function template declaration specifies a default
1222 // template-argument, that declaration shall be a definition and shall be
1223 // the only declaration of the function template in the translation unit.
1224 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001225 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001226 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1227 : diag::ext_template_parameter_default_in_function_template)
1228 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001229 return false;
1230
1231 case Sema::TPC_ClassTemplateMember:
1232 // C++0x [temp.param]p9:
1233 // A default template-argument shall not be specified in the
1234 // template-parameter-lists of the definition of a member of a
1235 // class template that appears outside of the member's class.
1236 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1237 << DefArgRange;
1238 return true;
1239
David Majnemerba8f17a2013-06-25 22:08:55 +00001240 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001241 case Sema::TPC_FriendFunctionTemplate:
1242 // C++ [temp.param]p9:
1243 // A default template-argument shall not be specified in a
1244 // friend template declaration.
1245 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1246 << DefArgRange;
1247 return true;
1248
1249 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1250 // for friend function templates if there is only a single
1251 // declaration (and it is a definition). Strange!
1252 }
1253
David Blaikie8a40f702012-01-17 06:56:22 +00001254 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001255}
1256
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001257/// \brief Check for unexpanded parameter packs within the template parameters
1258/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001259static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1260 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001261 // A template template parameter which is a parameter pack is also a pack
1262 // expansion.
1263 if (TTP->isParameterPack())
1264 return false;
1265
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001266 TemplateParameterList *Params = TTP->getTemplateParameters();
1267 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1268 NamedDecl *P = Params->getParam(I);
1269 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001270 if (!NTTP->isParameterPack() &&
1271 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001272 NTTP->getTypeSourceInfo(),
1273 Sema::UPPC_NonTypeTemplateParameterType))
1274 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001275
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001276 continue;
1277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278
1279 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001280 = dyn_cast<TemplateTemplateParmDecl>(P))
1281 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1282 return true;
1283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001284
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001285 return false;
1286}
1287
Douglas Gregordba32632009-02-10 19:49:53 +00001288/// \brief Checks the validity of a template parameter list, possibly
1289/// considering the template parameter list from a previous
1290/// declaration.
1291///
1292/// If an "old" template parameter list is provided, it must be
1293/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1294/// template parameter list.
1295///
1296/// \param NewParams Template parameter list for a new template
1297/// declaration. This template parameter list will be updated with any
1298/// default arguments that are carried through from the previous
1299/// template parameter list.
1300///
1301/// \param OldParams If provided, template parameter list from a
1302/// previous declaration of the same template. Default template
1303/// arguments will be merged from the old template parameter list to
1304/// the new template parameter list.
1305///
Douglas Gregored5731f2009-11-25 17:50:39 +00001306/// \param TPC Describes the context in which we are checking the given
1307/// template parameter list.
1308///
Douglas Gregordba32632009-02-10 19:49:53 +00001309/// \returns true if an error occurred, false otherwise.
1310bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001311 TemplateParameterList *OldParams,
1312 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001313 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001314
Douglas Gregordba32632009-02-10 19:49:53 +00001315 // C++ [temp.param]p10:
1316 // The set of default template-arguments available for use with a
1317 // template declaration or definition is obtained by merging the
1318 // default arguments from the definition (if in scope) and all
1319 // declarations in scope in the same way default function
1320 // arguments are (8.3.6).
1321 bool SawDefaultArgument = false;
1322 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001323
Mike Stumpc89c8e32009-02-11 23:03:27 +00001324 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001325 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001326 if (OldParams)
1327 OldParam = OldParams->begin();
1328
Douglas Gregor0693def2011-01-27 01:40:17 +00001329 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001330 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1331 NewParamEnd = NewParams->end();
1332 NewParam != NewParamEnd; ++NewParam) {
1333 // Variables used to diagnose redundant default arguments
1334 bool RedundantDefaultArg = false;
1335 SourceLocation OldDefaultLoc;
1336 SourceLocation NewDefaultLoc;
1337
David Blaikie651c73c2011-10-19 05:19:50 +00001338 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001339 bool MissingDefaultArg = false;
1340
David Blaikie651c73c2011-10-19 05:19:50 +00001341 // Variable used to diagnose non-final parameter packs
1342 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001343
Douglas Gregordba32632009-02-10 19:49:53 +00001344 if (TemplateTypeParmDecl *NewTypeParm
1345 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001346 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347 if (NewTypeParm->hasDefaultArgument() &&
1348 DiagnoseDefaultTemplateArgument(*this, TPC,
1349 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001350 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001351 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001352 NewTypeParm->removeDefaultArgument();
1353
1354 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001355 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001356 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001357 if (NewTypeParm->isParameterPack()) {
1358 assert(!NewTypeParm->hasDefaultArgument() &&
1359 "Parameter packs can't have a default argument!");
1360 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001361 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001362 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001363 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1364 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1365 SawDefaultArgument = true;
1366 RedundantDefaultArg = true;
1367 PreviousDefaultArgLoc = NewDefaultLoc;
1368 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1369 // Merge the default argument from the old declaration to the
1370 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001371 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001372 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1373 } else if (NewTypeParm->hasDefaultArgument()) {
1374 SawDefaultArgument = true;
1375 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1376 } else if (SawDefaultArgument)
1377 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001378 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001379 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001380 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001381 if (!NewNonTypeParm->isParameterPack() &&
1382 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001384 UPPC_NonTypeTemplateParameterType)) {
1385 Invalid = true;
1386 continue;
1387 }
1388
Douglas Gregored5731f2009-11-25 17:50:39 +00001389 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001390 if (NewNonTypeParm->hasDefaultArgument() &&
1391 DiagnoseDefaultTemplateArgument(*this, TPC,
1392 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001393 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001394 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001395 }
1396
Mike Stump12b8ce12009-08-04 21:02:39 +00001397 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001398 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001399 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001400 if (NewNonTypeParm->isParameterPack()) {
1401 assert(!NewNonTypeParm->hasDefaultArgument() &&
1402 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001403 if (!NewNonTypeParm->isPackExpansion())
1404 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001405 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001406 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001407 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1408 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1409 SawDefaultArgument = true;
1410 RedundantDefaultArg = true;
1411 PreviousDefaultArgLoc = NewDefaultLoc;
1412 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1413 // Merge the default argument from the old declaration to the
1414 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001415 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001416 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1417 } else if (NewNonTypeParm->hasDefaultArgument()) {
1418 SawDefaultArgument = true;
1419 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1420 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001421 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001422 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001423 TemplateTemplateParmDecl *NewTemplateParm
1424 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001425
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001426 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001427 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001428 Invalid = true;
1429 continue;
1430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001431
David Blaikie651c73c2011-10-19 05:19:50 +00001432 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433 if (NewTemplateParm->hasDefaultArgument() &&
1434 DiagnoseDefaultTemplateArgument(*this, TPC,
1435 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001436 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001437 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001438
1439 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001440 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001441 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001442 if (NewTemplateParm->isParameterPack()) {
1443 assert(!NewTemplateParm->hasDefaultArgument() &&
1444 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001445 if (!NewTemplateParm->isPackExpansion())
1446 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001447 } else if (OldTemplateParm &&
1448 hasVisibleDefaultArgument(OldTemplateParm) &&
1449 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001450 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1451 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001452 SawDefaultArgument = true;
1453 RedundantDefaultArg = true;
1454 PreviousDefaultArgLoc = NewDefaultLoc;
1455 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1456 // Merge the default argument from the old declaration to the
1457 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001458 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001459 PreviousDefaultArgLoc
1460 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001461 } else if (NewTemplateParm->hasDefaultArgument()) {
1462 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001463 PreviousDefaultArgLoc
1464 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001465 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001466 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001467 }
1468
Richard Smith1fde8ec2012-09-07 02:06:42 +00001469 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001470 // If a template parameter of a primary class template or alias template
1471 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001472 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001473 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1474 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001475 Diag((*NewParam)->getLocation(),
1476 diag::err_template_param_pack_must_be_last_template_parameter);
1477 Invalid = true;
1478 }
1479
Douglas Gregordba32632009-02-10 19:49:53 +00001480 if (RedundantDefaultArg) {
1481 // C++ [temp.param]p12:
1482 // A template-parameter shall not be given default arguments
1483 // by two different declarations in the same scope.
1484 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1485 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1486 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001487 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001488 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489 // If a template-parameter of a class template has a default
1490 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001491 // have a default template-argument supplied or be a template parameter
1492 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001493 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001494 diag::err_template_param_default_arg_missing);
1495 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1496 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001497 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001498 }
1499
1500 // If we have an old template parameter list that we're merging
1501 // in, move on to the next parameter.
1502 if (OldParams)
1503 ++OldParam;
1504 }
1505
Douglas Gregor0693def2011-01-27 01:40:17 +00001506 // We were missing some default arguments at the end of the list, so remove
1507 // all of the default arguments.
1508 if (RemoveDefaultArguments) {
1509 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1510 NewParamEnd = NewParams->end();
1511 NewParam != NewParamEnd; ++NewParam) {
1512 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1513 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001514 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001515 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1516 NTTP->removeDefaultArgument();
1517 else
1518 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1519 }
1520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001521
Douglas Gregordba32632009-02-10 19:49:53 +00001522 return Invalid;
1523}
Douglas Gregord32e0282009-02-09 23:23:08 +00001524
John McCalla020a012010-10-20 05:44:58 +00001525namespace {
1526
1527/// A class which looks for a use of a certain level of template
1528/// parameter.
1529struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1530 typedef RecursiveASTVisitor<DependencyChecker> super;
1531
1532 unsigned Depth;
1533 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001534 SourceLocation MatchLoc;
1535
1536 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001537
1538 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1539 NamedDecl *ND = Params->getParam(0);
1540 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1541 Depth = PD->getDepth();
1542 } else if (NonTypeTemplateParmDecl *PD =
1543 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1544 Depth = PD->getDepth();
1545 } else {
1546 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1547 }
1548 }
1549
Richard Smith6056d5e2014-02-09 00:54:43 +00001550 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001551 if (ParmDepth >= Depth) {
1552 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001553 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001554 return true;
1555 }
1556 return false;
1557 }
1558
Richard Smith6056d5e2014-02-09 00:54:43 +00001559 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1560 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1561 }
1562
John McCalla020a012010-10-20 05:44:58 +00001563 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1564 return !Matches(T->getDepth());
1565 }
1566
1567 bool TraverseTemplateName(TemplateName N) {
1568 if (TemplateTemplateParmDecl *PD =
1569 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001570 if (Matches(PD->getDepth()))
1571 return false;
John McCalla020a012010-10-20 05:44:58 +00001572 return super::TraverseTemplateName(N);
1573 }
1574
1575 bool VisitDeclRefExpr(DeclRefExpr *E) {
1576 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001577 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1578 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001579 return false;
John McCalla020a012010-10-20 05:44:58 +00001580 return super::VisitDeclRefExpr(E);
1581 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001582
1583 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1584 return TraverseType(T->getReplacementType());
1585 }
1586
1587 bool
1588 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1589 return TraverseTemplateArgument(T->getArgumentPack());
1590 }
1591
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001592 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1593 return TraverseType(T->getInjectedSpecializationType());
1594 }
John McCalla020a012010-10-20 05:44:58 +00001595};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001596} // end anonymous namespace
John McCalla020a012010-10-20 05:44:58 +00001597
Douglas Gregor972fe532011-05-10 18:27:06 +00001598/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001599/// list.
1600static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001601DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001602 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001603 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001604 return Checker.Match;
1605}
1606
Douglas Gregor972fe532011-05-10 18:27:06 +00001607// Find the source range corresponding to the named type in the given
1608// nested-name-specifier, if any.
1609static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1610 QualType T,
1611 const CXXScopeSpec &SS) {
1612 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1613 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1614 if (const Type *CurType = NNS->getAsType()) {
1615 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1616 return NNSLoc.getTypeLoc().getSourceRange();
1617 } else
1618 break;
1619
1620 NNSLoc = NNSLoc.getPrefix();
1621 }
1622
1623 return SourceRange();
1624}
1625
Mike Stump11289f42009-09-09 15:08:12 +00001626/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001627/// specifier, returning the template parameter list that applies to the
1628/// name.
1629///
1630/// \param DeclStartLoc the start of the declaration that has a scope
1631/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001632///
Douglas Gregor972fe532011-05-10 18:27:06 +00001633/// \param DeclLoc The location of the declaration itself.
1634///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001635/// \param SS the scope specifier that will be matched to the given template
1636/// parameter lists. This scope specifier precedes a qualified name that is
1637/// being declared.
1638///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001639/// \param TemplateId The template-id following the scope specifier, if there
1640/// is one. Used to check for a missing 'template<>'.
1641///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001642/// \param ParamLists the template parameter lists, from the outermost to the
1643/// innermost template parameter lists.
1644///
John McCalle820e5e2010-04-13 20:37:33 +00001645/// \param IsFriend Whether to apply the slightly different rules for
1646/// matching template parameters to scope specifiers in friend
1647/// declarations.
1648///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001649/// \param IsExplicitSpecialization will be set true if the entity being
1650/// declared is an explicit specialization, false otherwise.
1651///
Mike Stump11289f42009-09-09 15:08:12 +00001652/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001653/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001654/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001655/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001656/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001657/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001658TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1659 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001660 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001661 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1662 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001663 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001664 Invalid = false;
1665
1666 // The sequence of nested types to which we will match up the template
1667 // parameter lists. We first build this list by starting with the type named
1668 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001669 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001670 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001671 if (SS.getScopeRep()) {
1672 if (CXXRecordDecl *Record
1673 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1674 T = Context.getTypeDeclType(Record);
1675 else
1676 T = QualType(SS.getScopeRep()->getAsType(), 0);
1677 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001678
1679 // If we found an explicit specialization that prevents us from needing
1680 // 'template<>' headers, this will be set to the location of that
1681 // explicit specialization.
1682 SourceLocation ExplicitSpecLoc;
1683
1684 while (!T.isNull()) {
1685 NestedTypes.push_back(T);
1686
1687 // Retrieve the parent of a record type.
1688 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1689 // If this type is an explicit specialization, we're done.
1690 if (ClassTemplateSpecializationDecl *Spec
1691 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1692 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1693 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1694 ExplicitSpecLoc = Spec->getLocation();
1695 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001696 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001697 } else if (Record->getTemplateSpecializationKind()
1698 == TSK_ExplicitSpecialization) {
1699 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001700 break;
1701 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001702
1703 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1704 T = Context.getTypeDeclType(Parent);
1705 else
1706 T = QualType();
1707 continue;
1708 }
1709
1710 if (const TemplateSpecializationType *TST
1711 = T->getAs<TemplateSpecializationType>()) {
1712 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1713 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1714 T = Context.getTypeDeclType(Parent);
1715 else
1716 T = QualType();
1717 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001718 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001719 }
1720
1721 // Look one step prior in a dependent template specialization type.
1722 if (const DependentTemplateSpecializationType *DependentTST
1723 = T->getAs<DependentTemplateSpecializationType>()) {
1724 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1725 T = QualType(NNS->getAsType(), 0);
1726 else
1727 T = QualType();
1728 continue;
1729 }
1730
1731 // Look one step prior in a dependent name type.
1732 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1733 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1734 T = QualType(NNS->getAsType(), 0);
1735 else
1736 T = QualType();
1737 continue;
1738 }
1739
1740 // Retrieve the parent of an enumeration type.
1741 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1742 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1743 // check here.
1744 EnumDecl *Enum = EnumT->getDecl();
1745
1746 // Get to the parent type.
1747 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1748 T = Context.getTypeDeclType(Parent);
1749 else
1750 T = QualType();
1751 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001752 }
Mike Stump11289f42009-09-09 15:08:12 +00001753
Douglas Gregor972fe532011-05-10 18:27:06 +00001754 T = QualType();
1755 }
1756 // Reverse the nested types list, since we want to traverse from the outermost
1757 // to the innermost while checking template-parameter-lists.
1758 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001759
Douglas Gregor972fe532011-05-10 18:27:06 +00001760 // C++0x [temp.expl.spec]p17:
1761 // A member or a member template may be nested within many
1762 // enclosing class templates. In an explicit specialization for
1763 // such a member, the member declaration shall be preceded by a
1764 // template<> for each enclosing class template that is
1765 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001766 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001767
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001768 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001769 if (SawNonEmptyTemplateParameterList) {
1770 Diag(DeclLoc, diag::err_specialize_member_of_template)
1771 << !Recovery << Range;
1772 Invalid = true;
1773 IsExplicitSpecialization = false;
1774 return true;
1775 }
1776
1777 return false;
1778 };
1779
1780 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1781 // Check that we can have an explicit specialization here.
1782 if (CheckExplicitSpecialization(Range, true))
1783 return true;
1784
1785 // We don't have a template header, but we should.
1786 SourceLocation ExpectedTemplateLoc;
1787 if (!ParamLists.empty())
1788 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1789 else
1790 ExpectedTemplateLoc = DeclStartLoc;
1791
1792 Diag(DeclLoc, diag::err_template_spec_needs_header)
1793 << Range
1794 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1795 return false;
1796 };
1797
Douglas Gregor972fe532011-05-10 18:27:06 +00001798 unsigned ParamIdx = 0;
1799 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1800 ++TypeIdx) {
1801 T = NestedTypes[TypeIdx];
1802
1803 // Whether we expect a 'template<>' header.
1804 bool NeedEmptyTemplateHeader = false;
1805
1806 // Whether we expect a template header with parameters.
1807 bool NeedNonemptyTemplateHeader = false;
1808
1809 // For a dependent type, the set of template parameters that we
1810 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001811 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001812
Douglas Gregor373af9b2011-05-11 23:26:17 +00001813 // C++0x [temp.expl.spec]p15:
1814 // A member or a member template may be nested within many enclosing
1815 // class templates. In an explicit specialization for such a member, the
1816 // member declaration shall be preceded by a template<> for each
1817 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001818 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1819 if (ClassTemplatePartialSpecializationDecl *Partial
1820 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1821 ExpectedTemplateParams = Partial->getTemplateParameters();
1822 NeedNonemptyTemplateHeader = true;
1823 } else if (Record->isDependentType()) {
1824 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001825 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001826 ->getTemplateParameters();
1827 NeedNonemptyTemplateHeader = true;
1828 }
1829 } else if (ClassTemplateSpecializationDecl *Spec
1830 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1831 // C++0x [temp.expl.spec]p4:
1832 // Members of an explicitly specialized class template are defined
1833 // in the same manner as members of normal classes, and not using
1834 // the template<> syntax.
1835 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1836 NeedEmptyTemplateHeader = true;
1837 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001838 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001839 } else if (Record->getTemplateSpecializationKind()) {
1840 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001841 != TSK_ExplicitSpecialization &&
1842 TypeIdx == NumTypes - 1)
1843 IsExplicitSpecialization = true;
1844
1845 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001846 }
1847 } else if (const TemplateSpecializationType *TST
1848 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001849 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001850 ExpectedTemplateParams = Template->getTemplateParameters();
1851 NeedNonemptyTemplateHeader = true;
1852 }
1853 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1854 // FIXME: We actually could/should check the template arguments here
1855 // against the corresponding template parameter list.
1856 NeedNonemptyTemplateHeader = false;
1857 }
1858
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001859 // C++ [temp.expl.spec]p16:
1860 // In an explicit specialization declaration for a member of a class
1861 // template or a member template that ap- pears in namespace scope, the
1862 // member template and some of its enclosing class templates may remain
1863 // unspecialized, except that the declaration shall not explicitly
1864 // specialize a class member template if its en- closing class templates
1865 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001866 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001867 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001868 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1869 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001870 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001871 } else
1872 SawNonEmptyTemplateParameterList = true;
1873 }
1874
Douglas Gregor972fe532011-05-10 18:27:06 +00001875 if (NeedEmptyTemplateHeader) {
1876 // If we're on the last of the types, and we need a 'template<>' header
1877 // here, then it's an explicit specialization.
1878 if (TypeIdx == NumTypes - 1)
1879 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001880
1881 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001882 if (ParamLists[ParamIdx]->size() > 0) {
1883 // The header has template parameters when it shouldn't. Complain.
1884 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1885 diag::err_template_param_list_matches_nontemplate)
1886 << T
1887 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1888 ParamLists[ParamIdx]->getRAngleLoc())
1889 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1890 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001891 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001892 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001893
Douglas Gregor972fe532011-05-10 18:27:06 +00001894 // Consume this template header.
1895 ++ParamIdx;
1896 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001897 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001898
1899 if (!IsFriend)
1900 if (DiagnoseMissingExplicitSpecialization(
1901 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001902 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001903
Douglas Gregor972fe532011-05-10 18:27:06 +00001904 continue;
1905 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001906
Douglas Gregor972fe532011-05-10 18:27:06 +00001907 if (NeedNonemptyTemplateHeader) {
1908 // In friend declarations we can have template-ids which don't
1909 // depend on the corresponding template parameter lists. But
1910 // assume that empty parameter lists are supposed to match this
1911 // template-id.
1912 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001913 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001914 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001915 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001916 else
1917 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001918 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001919
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001920 if (ParamIdx < ParamLists.size()) {
1921 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001922 if (ExpectedTemplateParams &&
1923 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1924 ExpectedTemplateParams,
1925 true, TPL_TemplateMatch))
1926 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001927
Douglas Gregor972fe532011-05-10 18:27:06 +00001928 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001929 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001930 TPC_ClassTemplateMember))
1931 Invalid = true;
1932
1933 ++ParamIdx;
1934 continue;
1935 }
1936
1937 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1938 << T
1939 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1940 Invalid = true;
1941 continue;
1942 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001943 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001944
Douglas Gregord8d297c2009-07-21 23:53:31 +00001945 // If there were at least as many template-ids as there were template
1946 // parameter lists, then there are no template parameter lists remaining for
1947 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001948 if (ParamIdx >= ParamLists.size()) {
1949 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001950 // We don't have a template header for the declaration itself, but we
1951 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001952 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001953 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1954 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001955
1956 // Fabricate an empty template parameter list for the invented header.
1957 return TemplateParameterList::Create(Context, SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +00001958 SourceLocation(), None,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001959 SourceLocation());
1960 }
1961
Craig Topperc3ec1492014-05-26 06:22:03 +00001962 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001963 }
Mike Stump11289f42009-09-09 15:08:12 +00001964
Douglas Gregord8d297c2009-07-21 23:53:31 +00001965 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001966 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001967 bool HasAnyExplicitSpecHeader = false;
1968 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001969 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001970 if (ParamLists[I]->size() == 0)
1971 HasAnyExplicitSpecHeader = true;
1972 else
1973 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001974 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001975
Douglas Gregor972fe532011-05-10 18:27:06 +00001976 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001977 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1978 : diag::err_template_spec_extra_headers)
1979 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1980 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001981
1982 // If there was a specialization somewhere, such that 'template<>' is
1983 // not required, and there were any 'template<>' headers, note where the
1984 // specialization occurred.
1985 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1986 Diag(ExplicitSpecLoc,
1987 diag::note_explicit_template_spec_does_not_need_header)
1988 << NestedTypes.back();
1989
1990 // We have a template parameter list with no corresponding scope, which
1991 // means that the resulting template declaration can't be instantiated
1992 // properly (we'll end up with dependent nodes when we shouldn't).
1993 if (!AllExplicitSpecHeaders)
1994 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001997 // C++ [temp.expl.spec]p16:
1998 // In an explicit specialization declaration for a member of a class
1999 // template or a member template that ap- pears in namespace scope, the
2000 // member template and some of its enclosing class templates may remain
2001 // unspecialized, except that the declaration shall not explicitly
2002 // specialize a class member template if its en- closing class templates
2003 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00002004 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00002005 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2006 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00002007 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00002008
Douglas Gregord8d297c2009-07-21 23:53:31 +00002009 // Return the last template parameter list, which corresponds to the
2010 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00002011 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00002012}
2013
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002014void Sema::NoteAllFoundTemplates(TemplateName Name) {
2015 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2016 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00002017 << (isa<FunctionTemplateDecl>(Template)
2018 ? 0
2019 : isa<ClassTemplateDecl>(Template)
2020 ? 1
2021 : isa<VarTemplateDecl>(Template)
2022 ? 2
2023 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2024 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002025 return;
2026 }
2027
2028 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2029 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2030 IEnd = OST->end();
2031 I != IEnd; ++I)
2032 Diag((*I)->getLocation(), diag::note_template_declared_here)
2033 << 0 << (*I)->getDeclName();
2034
2035 return;
2036 }
2037}
2038
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002039static QualType
2040checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2041 const SmallVectorImpl<TemplateArgument> &Converted,
2042 SourceLocation TemplateLoc,
2043 TemplateArgumentListInfo &TemplateArgs) {
2044 ASTContext &Context = SemaRef.getASTContext();
2045 switch (BTD->getBuiltinTemplateKind()) {
Eric Fiselier6ad68552016-07-01 01:24:09 +00002046 case BTK__make_integer_seq: {
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002047 // Specializations of __make_integer_seq<S, T, N> are treated like
2048 // S<T, 0, ..., N-1>.
2049
2050 // C++14 [inteseq.intseq]p1:
2051 // T shall be an integer type.
2052 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2053 SemaRef.Diag(TemplateArgs[1].getLocation(),
2054 diag::err_integer_sequence_integral_element_type);
2055 return QualType();
2056 }
2057
2058 // C++14 [inteseq.make]p1:
2059 // If N is negative the program is ill-formed.
2060 TemplateArgument NumArgsArg = Converted[2];
2061 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2062 if (NumArgs < 0) {
2063 SemaRef.Diag(TemplateArgs[2].getLocation(),
2064 diag::err_integer_sequence_negative_length);
2065 return QualType();
2066 }
2067
2068 QualType ArgTy = NumArgsArg.getIntegralType();
2069 TemplateArgumentListInfo SyntheticTemplateArgs;
2070 // The type argument gets reused as the first template argument in the
2071 // synthetic template argument list.
2072 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2073 // Expand N into 0 ... N-1.
2074 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2075 I < NumArgs; ++I) {
2076 TemplateArgument TA(Context, I, ArgTy);
2077 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2078 TA, TemplateArgs[2].getLocation())
2079 .getAs<Expr>();
2080 SyntheticTemplateArgs.addArgument(
2081 TemplateArgumentLoc(TemplateArgument(E), E));
2082 }
2083 // The first template argument will be reused as the template decl that
2084 // our synthetic template arguments will be applied to.
2085 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2086 TemplateLoc, SyntheticTemplateArgs);
2087 }
Eric Fiselier6ad68552016-07-01 01:24:09 +00002088
2089 case BTK__type_pack_element:
2090 // Specializations of
2091 // __type_pack_element<Index, T_1, ..., T_N>
2092 // are treated like T_Index.
2093 assert(Converted.size() == 2 &&
2094 "__type_pack_element should be given an index and a parameter pack");
2095
2096 // If the Index is out of bounds, the program is ill-formed.
2097 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2098 llvm::APSInt Index = IndexArg.getAsIntegral();
2099 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2100 "type std::size_t, and hence be non-negative");
2101 if (Index >= Ts.pack_size()) {
2102 SemaRef.Diag(TemplateArgs[0].getLocation(),
2103 diag::err_type_pack_element_out_of_bounds);
2104 return QualType();
2105 }
2106
2107 // We simply return the type at index `Index`.
2108 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2109 return Nth->getAsType();
2110 }
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002111 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2112}
2113
Douglas Gregordc572a32009-03-30 22:58:21 +00002114QualType Sema::CheckTemplateIdType(TemplateName Name,
2115 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002116 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002117 DependentTemplateName *DTN
2118 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002119 if (DTN && DTN->isIdentifier())
2120 // When building a template-id where the template-name is dependent,
2121 // assume the template is a type template. Either our assumption is
2122 // correct, or the code is ill-formed and will be diagnosed when the
2123 // dependent name is substituted.
2124 return Context.getDependentTemplateSpecializationType(ETK_None,
2125 DTN->getQualifier(),
2126 DTN->getIdentifier(),
2127 TemplateArgs);
2128
Douglas Gregordc572a32009-03-30 22:58:21 +00002129 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002130 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2131 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002132 // We might have a substituted template template parameter pack. If so,
2133 // build a template specialization type for it.
2134 if (Name.getAsSubstTemplateTemplateParmPack())
2135 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002136
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002137 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2138 << Name;
2139 NoteAllFoundTemplates(Name);
2140 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002141 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002142
Douglas Gregorc40290e2009-03-09 23:48:35 +00002143 // Check that the template argument list is well-formed for this
2144 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002145 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002146 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002147 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002148 return QualType();
2149
Douglas Gregorc40290e2009-03-09 23:48:35 +00002150 QualType CanonType;
2151
Douglas Gregor678d76c2011-07-01 01:22:09 +00002152 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002153 if (TypeAliasTemplateDecl *AliasTemplate =
2154 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002155 // Find the canonical type for this type alias template specialization.
2156 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2157 if (Pattern->isInvalidDecl())
2158 return QualType();
2159
2160 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2161 Converted.data(), Converted.size());
2162
2163 // Only substitute for the innermost template argument list.
2164 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002165 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002166 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2167 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002168 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002169
Richard Smith802c4b72012-08-23 06:16:52 +00002170 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002171 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002172 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002173 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002174
Richard Smith3f1b5d02011-05-05 21:57:07 +00002175 CanonType = SubstType(Pattern->getUnderlyingType(),
2176 TemplateArgLists, AliasTemplate->getLocation(),
2177 AliasTemplate->getDeclName());
2178 if (CanonType.isNull())
2179 return QualType();
2180 } else if (Name.isDependent() ||
2181 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002182 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002183 // This class template specialization is a dependent
2184 // type. Therefore, its canonical type is another class template
2185 // specialization type that contains all of the converted
2186 // arguments in canonical form. This ensures that, e.g., A<T> and
2187 // A<T, T> have identical types when A is declared as:
2188 //
2189 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002190 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002191 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002192 Converted.data(),
2193 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002194
Douglas Gregora8e02e72009-07-28 23:00:59 +00002195 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002196 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002197 // In the future, we need to teach getTemplateSpecializationType to only
2198 // build the canonical type and return that to us.
2199 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002200
2201 // This might work out to be a current instantiation, in which
2202 // case the canonical type needs to be the InjectedClassNameType.
2203 //
2204 // TODO: in theory this could be a simple hashtable lookup; most
2205 // changes to CurContext don't change the set of current
2206 // instantiations.
2207 if (isa<ClassTemplateDecl>(Template)) {
2208 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2209 // If we get out to a namespace, we're done.
2210 if (Ctx->isFileContext()) break;
2211
2212 // If this isn't a record, keep looking.
2213 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2214 if (!Record) continue;
2215
2216 // Look for one of the two cases with InjectedClassNameTypes
2217 // and check whether it's the same template.
2218 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2219 !Record->getDescribedClassTemplate())
2220 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002221
John McCall2408e322010-04-27 00:57:59 +00002222 // Fetch the injected class name type and check whether its
2223 // injected type is equal to the type we just built.
2224 QualType ICNT = Context.getTypeDeclType(Record);
2225 QualType Injected = cast<InjectedClassNameType>(ICNT)
2226 ->getInjectedSpecializationType();
2227
2228 if (CanonType != Injected->getCanonicalTypeInternal())
2229 continue;
2230
2231 // If so, the canonical type of this TST is the injected
2232 // class name type of the record we just found.
2233 assert(ICNT.isCanonical());
2234 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002235 break;
2236 }
2237 }
Mike Stump11289f42009-09-09 15:08:12 +00002238 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002239 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002240 // Find the class template specialization declaration that
2241 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002242 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002243 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002244 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002245 if (!Decl) {
2246 // This is the first time we have referenced this class template
2247 // specialization. Create the canonical declaration and add it to
2248 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002249 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002250 ClassTemplate->getTemplatedDecl()->getTagKind(),
2251 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002252 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002253 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002254 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002255 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002256 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002257 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002258 if (ClassTemplate->isOutOfLine())
2259 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002260 }
2261
Chandler Carruth2acfb222013-09-27 22:14:40 +00002262 // Diagnose uses of this specialization.
2263 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2264
Douglas Gregorc40290e2009-03-09 23:48:35 +00002265 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002266 assert(isa<RecordType>(CanonType) &&
2267 "type of non-dependent specialization is not a RecordType");
David Majnemerd9b1a4f2015-11-04 03:40:30 +00002268 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2269 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2270 TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002271 }
Mike Stump11289f42009-09-09 15:08:12 +00002272
Douglas Gregorc40290e2009-03-09 23:48:35 +00002273 // Build the fully-sugared type for this class template
2274 // specialization, which refers back to the class template
2275 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002276 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002277}
2278
John McCallfaf5fb42010-08-26 23:41:50 +00002279TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002280Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002281 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002282 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002283 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002284 SourceLocation RAngleLoc,
2285 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002286 if (SS.isInvalid())
2287 return true;
2288
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002289 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002290
Douglas Gregorc40290e2009-03-09 23:48:35 +00002291 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002292 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002293 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002294
Douglas Gregor5a064722011-02-28 17:23:35 +00002295 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002296 QualType T
2297 = Context.getDependentTemplateSpecializationType(ETK_None,
2298 DTN->getQualifier(),
2299 DTN->getIdentifier(),
2300 TemplateArgs);
2301 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002302 TypeLocBuilder TLB;
2303 DependentTemplateSpecializationTypeLoc SpecTL
2304 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002305 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2306 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002307 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002308 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002309 SpecTL.setLAngleLoc(LAngleLoc);
2310 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002311 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2312 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2313 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2314 }
2315
John McCall6b51f282009-11-23 01:53:49 +00002316 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002317
2318 if (Result.isNull())
2319 return true;
2320
Douglas Gregore7c20652011-03-02 00:47:37 +00002321 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002322 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002323 TemplateSpecializationTypeLoc SpecTL
2324 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002325 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002326 SpecTL.setTemplateNameLoc(TemplateLoc);
2327 SpecTL.setLAngleLoc(LAngleLoc);
2328 SpecTL.setRAngleLoc(RAngleLoc);
2329 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2330 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002331
Abramo Bagnara4244b432012-01-27 08:46:19 +00002332 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2333 // constructor or destructor name (in such a case, the scope specifier
2334 // will be attached to the enclosing Decl or Expr node).
2335 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002336 // Create an elaborated-type-specifier containing the nested-name-specifier.
2337 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2338 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002339 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002340 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2341 }
2342
2343 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002344}
John McCall06f6fe8d2009-09-04 01:14:41 +00002345
Douglas Gregore7c20652011-03-02 00:47:37 +00002346TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002347 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002348 SourceLocation TagLoc,
2349 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002350 SourceLocation TemplateKWLoc,
2351 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002352 SourceLocation TemplateLoc,
2353 SourceLocation LAngleLoc,
2354 ASTTemplateArgsPtr TemplateArgsIn,
2355 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002356 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002357
2358 // Translate the parser's template argument list in our AST format.
2359 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2360 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2361
2362 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002363 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002364 ElaboratedTypeKeyword Keyword
2365 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002366
Douglas Gregore7c20652011-03-02 00:47:37 +00002367 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2368 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2369 DTN->getQualifier(),
2370 DTN->getIdentifier(),
2371 TemplateArgs);
2372
2373 // Build type-source information.
2374 TypeLocBuilder TLB;
2375 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002376 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2377 SpecTL.setElaboratedKeywordLoc(TagLoc);
2378 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002379 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002380 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002381 SpecTL.setLAngleLoc(LAngleLoc);
2382 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002383 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2384 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2385 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2386 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002387
2388 if (TypeAliasTemplateDecl *TAT =
2389 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2390 // C++0x [dcl.type.elab]p2:
2391 // If the identifier resolves to a typedef-name or the simple-template-id
2392 // resolves to an alias template specialization, the
2393 // elaborated-type-specifier is ill-formed.
2394 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2395 Diag(TAT->getLocation(), diag::note_declared_at);
2396 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002397
2398 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2399 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002400 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002401
2402 // Check the tag kind
2403 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002404 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002405
John McCalld8fe9af2009-09-08 17:47:29 +00002406 IdentifierInfo *Id = D->getIdentifier();
2407 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002408
Richard Trieucaa33d32011-06-10 03:11:26 +00002409 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002410 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002411 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002412 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002413 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002414 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002415 }
2416 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002417
Douglas Gregore7c20652011-03-02 00:47:37 +00002418 // Provide source-location information for the template specialization.
2419 TypeLocBuilder TLB;
2420 TemplateSpecializationTypeLoc SpecTL
2421 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002422 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002423 SpecTL.setTemplateNameLoc(TemplateLoc);
2424 SpecTL.setLAngleLoc(LAngleLoc);
2425 SpecTL.setRAngleLoc(RAngleLoc);
2426 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2427 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002428
Douglas Gregore7c20652011-03-02 00:47:37 +00002429 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002430 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002431 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2432 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002433 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002434 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2435 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002436}
2437
Larisse Voufo39a1e502013-08-06 01:03:05 +00002438static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002439 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2440 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002441
2442static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2443 NamedDecl *PrevDecl,
2444 SourceLocation Loc,
2445 bool IsPartialSpecialization);
2446
2447static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002448
Richard Smith300e0c32013-09-24 04:49:23 +00002449static bool isTemplateArgumentTemplateParameter(
2450 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2451 switch (Arg.getKind()) {
2452 case TemplateArgument::Null:
2453 case TemplateArgument::NullPtr:
2454 case TemplateArgument::Integral:
2455 case TemplateArgument::Declaration:
2456 case TemplateArgument::Pack:
2457 case TemplateArgument::TemplateExpansion:
2458 return false;
2459
2460 case TemplateArgument::Type: {
2461 QualType Type = Arg.getAsType();
2462 const TemplateTypeParmType *TPT =
2463 Arg.getAsType()->getAs<TemplateTypeParmType>();
2464 return TPT && !Type.hasQualifiers() &&
2465 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2466 }
2467
2468 case TemplateArgument::Expression: {
2469 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2470 if (!DRE || !DRE->getDecl())
2471 return false;
2472 const NonTypeTemplateParmDecl *NTTP =
2473 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2474 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2475 }
2476
2477 case TemplateArgument::Template:
2478 const TemplateTemplateParmDecl *TTP =
2479 dyn_cast_or_null<TemplateTemplateParmDecl>(
2480 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2481 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2482 }
2483 llvm_unreachable("unexpected kind of template argument");
2484}
2485
2486static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2487 ArrayRef<TemplateArgument> Args) {
2488 if (Params->size() != Args.size())
2489 return false;
2490
2491 unsigned Depth = Params->getDepth();
2492
2493 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2494 TemplateArgument Arg = Args[I];
2495
2496 // If the parameter is a pack expansion, the argument must be a pack
2497 // whose only element is a pack expansion.
2498 if (Params->getParam(I)->isParameterPack()) {
2499 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2500 !Arg.pack_begin()->isPackExpansion())
2501 return false;
2502 Arg = Arg.pack_begin()->getPackExpansionPattern();
2503 }
2504
2505 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2506 return false;
2507 }
2508
2509 return true;
2510}
2511
Richard Smith4b55a9c2014-04-17 03:29:33 +00002512/// Convert the parser's template argument list representation into our form.
2513static TemplateArgumentListInfo
2514makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2515 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2516 TemplateId.RAngleLoc);
2517 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2518 TemplateId.NumArgs);
2519 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2520 return TemplateArgs;
2521}
2522
Larisse Voufo39a1e502013-08-06 01:03:05 +00002523DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002524 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002525 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002526 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002527 // D must be variable template id.
2528 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2529 "Variable template specialization is declared with a template it.");
2530
2531 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002532 TemplateArgumentListInfo TemplateArgs =
2533 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002534 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2535 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2536 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002537
Richard Smithbeef3452014-01-16 23:39:20 +00002538 TemplateName Name = TemplateId->Template.get();
2539
2540 // The template-id must name a variable template.
2541 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002542 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2543 if (!VarTemplate) {
2544 NamedDecl *FnTemplate;
2545 if (auto *OTS = Name.getAsOverloadedTemplate())
2546 FnTemplate = *OTS->begin();
2547 else
2548 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2549 if (FnTemplate)
2550 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2551 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002552 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2553 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002554 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002555
2556 // Check for unexpanded parameter packs in any of the template arguments.
2557 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2558 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2559 UPPC_PartialSpecialization))
2560 return true;
2561
2562 // Check that the template argument list is well-formed for this
2563 // template.
2564 SmallVector<TemplateArgument, 4> Converted;
2565 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2566 false, Converted))
2567 return true;
2568
Larisse Voufo39a1e502013-08-06 01:03:05 +00002569 // Find the variable template (partial) specialization declaration that
2570 // corresponds to these arguments.
2571 if (IsPartialSpecialization) {
2572 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002573 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2574 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002575 return true;
2576
2577 bool InstantiationDependent;
2578 if (!Name.isDependent() &&
2579 !TemplateSpecializationType::anyDependentTemplateArguments(
2580 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2581 InstantiationDependent)) {
2582 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2583 << VarTemplate->getDeclName();
2584 IsPartialSpecialization = false;
2585 }
Richard Smith300e0c32013-09-24 04:49:23 +00002586
2587 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2588 Converted)) {
2589 // C++ [temp.class.spec]p9b3:
2590 //
2591 // -- The argument list of the specialization shall not be identical
2592 // to the implicit argument list of the primary template.
2593 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2594 << /*variable template*/ 1
2595 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2596 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2597 // FIXME: Recover from this by treating the declaration as a redeclaration
2598 // of the primary template.
2599 return true;
2600 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002601 }
2602
Craig Topperc3ec1492014-05-26 06:22:03 +00002603 void *InsertPos = nullptr;
2604 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002605
2606 if (IsPartialSpecialization)
2607 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002608 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002609 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002610 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002611
Craig Topperc3ec1492014-05-26 06:22:03 +00002612 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002613
2614 // Check whether we can declare a variable template specialization in
2615 // the current scope.
2616 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2617 TemplateNameLoc,
2618 IsPartialSpecialization))
2619 return true;
2620
2621 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2622 // Since the only prior variable template specialization with these
2623 // arguments was referenced but not declared, reuse that
2624 // declaration node as our own, updating its source location and
2625 // the list of outer template parameters to reflect our new declaration.
2626 Specialization = PrevDecl;
2627 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002628 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002629 } else if (IsPartialSpecialization) {
2630 // Create a new class template partial specialization declaration node.
2631 VarTemplatePartialSpecializationDecl *PrevPartial =
2632 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002633 VarTemplatePartialSpecializationDecl *Partial =
2634 VarTemplatePartialSpecializationDecl::Create(
2635 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2636 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002637 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002638
2639 if (!PrevPartial)
2640 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2641 Specialization = Partial;
2642
2643 // If we are providing an explicit specialization of a member variable
2644 // template specialization, make a note of that.
2645 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002646 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002647
2648 // Check that all of the template parameters of the variable template
2649 // partial specialization are deducible from the template
2650 // arguments. If not, this variable template partial specialization
2651 // will never be used.
2652 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2653 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2654 TemplateParams->getDepth(), DeducibleParams);
2655
2656 if (!DeducibleParams.all()) {
2657 unsigned NumNonDeducible =
2658 DeducibleParams.size() - DeducibleParams.count();
2659 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002660 << /*variable template*/ 1 << (NumNonDeducible > 1)
2661 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002662 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2663 if (!DeducibleParams[I]) {
2664 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2665 if (Param->getDeclName())
2666 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2667 << Param->getDeclName();
2668 else
2669 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002670 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002671 }
2672 }
2673 }
2674 } else {
2675 // Create a new class template specialization declaration node for
2676 // this explicit specialization or friend declaration.
2677 Specialization = VarTemplateSpecializationDecl::Create(
2678 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2679 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2680 Specialization->setTemplateArgsInfo(TemplateArgs);
2681
2682 if (!PrevDecl)
2683 VarTemplate->AddSpecialization(Specialization, InsertPos);
2684 }
2685
2686 // C++ [temp.expl.spec]p6:
2687 // If a template, a member template or the member of a class template is
2688 // explicitly specialized then that specialization shall be declared
2689 // before the first use of that specialization that would cause an implicit
2690 // instantiation to take place, in every translation unit in which such a
2691 // use occurs; no diagnostic is required.
2692 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2693 bool Okay = false;
2694 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2695 // Is there any previous explicit specialization declaration?
2696 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2697 Okay = true;
2698 break;
2699 }
2700 }
2701
2702 if (!Okay) {
2703 SourceRange Range(TemplateNameLoc, RAngleLoc);
2704 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2705 << Name << Range;
2706
2707 Diag(PrevDecl->getPointOfInstantiation(),
2708 diag::note_instantiation_required_here)
2709 << (PrevDecl->getTemplateSpecializationKind() !=
2710 TSK_ImplicitInstantiation);
2711 return true;
2712 }
2713 }
2714
2715 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2716 Specialization->setLexicalDeclContext(CurContext);
2717
2718 // Add the specialization into its lexical context, so that it can
2719 // be seen when iterating through the list of declarations in that
2720 // context. However, specializations are not found by name lookup.
2721 CurContext->addDecl(Specialization);
2722
2723 // Note that this is an explicit specialization.
2724 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2725
2726 if (PrevDecl) {
2727 // Check that this isn't a redefinition of this specialization,
2728 // merging with previous declarations.
2729 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2730 ForRedeclaration);
2731 PrevSpec.addDecl(PrevDecl);
2732 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002733 } else if (Specialization->isStaticDataMember() &&
2734 Specialization->isOutOfLine()) {
2735 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002736 }
2737
2738 // Link instantiations of static data members back to the template from
2739 // which they were instantiated.
2740 if (Specialization->isStaticDataMember())
2741 Specialization->setInstantiationOfStaticDataMember(
2742 VarTemplate->getTemplatedDecl(),
2743 Specialization->getSpecializationKind());
2744
2745 return Specialization;
2746}
2747
2748namespace {
2749/// \brief A partial specialization whose template arguments have matched
2750/// a given template-id.
2751struct PartialSpecMatchResult {
2752 VarTemplatePartialSpecializationDecl *Partial;
2753 TemplateArgumentList *Args;
2754};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002755} // end anonymous namespace
Larisse Voufo39a1e502013-08-06 01:03:05 +00002756
2757DeclResult
2758Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2759 SourceLocation TemplateNameLoc,
2760 const TemplateArgumentListInfo &TemplateArgs) {
2761 assert(Template && "A variable template id without template?");
2762
2763 // Check that the template argument list is well-formed for this template.
2764 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002765 if (CheckTemplateArgumentList(
2766 Template, TemplateNameLoc,
2767 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002768 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002769 return true;
2770
2771 // Find the variable template specialization declaration that
2772 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002773 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002774 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Richard Smith6739a102016-05-05 00:56:12 +00002775 Converted, InsertPos)) {
2776 checkSpecializationVisibility(TemplateNameLoc, Spec);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002777 // If we already have a variable template specialization, return it.
2778 return Spec;
Richard Smith6739a102016-05-05 00:56:12 +00002779 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002780
2781 // This is the first time we have referenced this variable template
2782 // specialization. Create the canonical declaration and add it to
2783 // the set of specializations, based on the closest partial specialization
2784 // that it represents. That is,
2785 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2786 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2787 Converted.data(), Converted.size());
2788 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2789 bool AmbiguousPartialSpec = false;
2790 typedef PartialSpecMatchResult MatchResult;
2791 SmallVector<MatchResult, 4> Matched;
2792 SourceLocation PointOfInstantiation = TemplateNameLoc;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002793 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2794 /*ForTakingAddress=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002795
2796 // 1. Attempt to find the closest partial specialization that this
2797 // specializes, if any.
2798 // If any of the template arguments is dependent, then this is probably
2799 // a placeholder for an incomplete declarative context; which must be
2800 // complete by instantiation time. Thus, do not search through the partial
2801 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002802 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2803 // Perhaps better after unification of DeduceTemplateArguments() and
2804 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002805 bool InstantiationDependent = false;
2806 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2807 TemplateArgs, InstantiationDependent)) {
2808
2809 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2810 Template->getPartialSpecializations(PartialSpecs);
2811
2812 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2813 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2814 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2815
2816 if (TemplateDeductionResult Result =
2817 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2818 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002819 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002820 FailedCandidates.addCandidate().set(
2821 DeclAccessPair::make(Template, AS_public), Partial,
2822 MakeDeductionFailureInfo(Context, Result, Info));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002823 (void)Result;
2824 } else {
2825 Matched.push_back(PartialSpecMatchResult());
2826 Matched.back().Partial = Partial;
2827 Matched.back().Args = Info.take();
2828 }
2829 }
2830
Larisse Voufo39a1e502013-08-06 01:03:05 +00002831 if (Matched.size() >= 1) {
2832 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2833 if (Matched.size() == 1) {
2834 // -- If exactly one matching specialization is found, the
2835 // instantiation is generated from that specialization.
2836 // We don't need to do anything for this.
2837 } else {
2838 // -- If more than one matching specialization is found, the
2839 // partial order rules (14.5.4.2) are used to determine
2840 // whether one of the specializations is more specialized
2841 // than the others. If none of the specializations is more
2842 // specialized than all of the other matching
2843 // specializations, then the use of the variable template is
2844 // ambiguous and the program is ill-formed.
2845 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2846 PEnd = Matched.end();
2847 P != PEnd; ++P) {
2848 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2849 PointOfInstantiation) ==
2850 P->Partial)
2851 Best = P;
2852 }
2853
2854 // Determine if the best partial specialization is more specialized than
2855 // the others.
2856 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2857 PEnd = Matched.end();
2858 P != PEnd; ++P) {
2859 if (P != Best && getMoreSpecializedPartialSpecialization(
2860 P->Partial, Best->Partial,
2861 PointOfInstantiation) != Best->Partial) {
2862 AmbiguousPartialSpec = true;
2863 break;
2864 }
2865 }
2866 }
2867
2868 // Instantiate using the best variable template partial specialization.
2869 InstantiationPattern = Best->Partial;
2870 InstantiationArgs = Best->Args;
2871 } else {
2872 // -- If no match is found, the instantiation is generated
2873 // from the primary template.
2874 // InstantiationPattern = Template->getTemplatedDecl();
2875 }
2876 }
2877
Larisse Voufo39a1e502013-08-06 01:03:05 +00002878 // 2. Create the canonical declaration.
Richard Smith6739a102016-05-05 00:56:12 +00002879 // Note that we do not instantiate a definition until we see an odr-use
2880 // in DoMarkVarDeclReferenced().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002881 // FIXME: LateAttrs et al.?
2882 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2883 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2884 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2885 if (!Decl)
2886 return true;
2887
2888 if (AmbiguousPartialSpec) {
2889 // Partial ordering did not produce a clear winner. Complain.
2890 Decl->setInvalidDecl();
2891 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2892 << Decl;
2893
2894 // Print the matching partial specializations.
2895 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2896 PEnd = Matched.end();
2897 P != PEnd; ++P)
2898 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2899 << getTemplateArgumentBindingsText(
2900 P->Partial->getTemplateParameters(), *P->Args);
2901 return true;
2902 }
2903
2904 if (VarTemplatePartialSpecializationDecl *D =
2905 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2906 Decl->setInstantiationOf(D, InstantiationArgs);
2907
Richard Smith6739a102016-05-05 00:56:12 +00002908 checkSpecializationVisibility(TemplateNameLoc, Decl);
2909
Larisse Voufo39a1e502013-08-06 01:03:05 +00002910 assert(Decl && "No variable template specialization?");
2911 return Decl;
2912}
2913
2914ExprResult
2915Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2916 const DeclarationNameInfo &NameInfo,
2917 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2918 const TemplateArgumentListInfo *TemplateArgs) {
2919
2920 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2921 *TemplateArgs);
2922 if (Decl.isInvalid())
2923 return ExprError();
2924
2925 VarDecl *Var = cast<VarDecl>(Decl.get());
2926 if (!Var->getTemplateSpecializationKind())
2927 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2928 NameInfo.getLoc());
2929
2930 // Build an ordinary singleton decl ref.
2931 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002932 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002933}
2934
John McCalldadc5752010-08-24 06:29:42 +00002935ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002936 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002937 LookupResult &R,
2938 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002939 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002940 // FIXME: Can we do any checking at this point? I guess we could check the
2941 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002942 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002943 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002944 // foo<int> could identify a single function unambiguously
2945 // This approach does NOT work, since f<int>(1);
2946 // gets resolved prior to resorting to overload resolution
2947 // i.e., template<class T> void f(double);
2948 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002949
2950 // These should be filtered out by our callers.
2951 assert(!R.empty() && "empty lookup results when building templateid");
2952 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2953
Larisse Voufo39a1e502013-08-06 01:03:05 +00002954 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002955 bool InstantiationDependent;
2956 if (R.getAsSingle<VarTemplateDecl>() &&
2957 !TemplateSpecializationType::anyDependentTemplateArguments(
2958 *TemplateArgs, InstantiationDependent)) {
2959 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2960 R.getAsSingle<VarTemplateDecl>(),
2961 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002962 }
2963
John McCall58cc69d2010-01-27 01:50:18 +00002964 // We don't want lookup warnings at this point.
2965 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002966
John McCalle66edc12009-11-24 19:00:30 +00002967 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002968 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002969 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002970 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002971 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002972 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002973 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002974
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002975 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002976}
2977
John McCalle66edc12009-11-24 19:00:30 +00002978// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002979ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002980Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002981 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002982 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002983 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002984
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002985 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002986 DeclContext *DC;
2987 if (!(DC = computeDeclContext(SS, false)) ||
2988 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002989 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002990 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002991
Douglas Gregor786123d2010-05-21 23:18:07 +00002992 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002993 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002994 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002995 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002996
John McCalle66edc12009-11-24 19:00:30 +00002997 if (R.isAmbiguous())
2998 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002999
John McCalle66edc12009-11-24 19:00:30 +00003000 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003001 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3002 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003003 return ExprError();
3004 }
3005
3006 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003007 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00003008 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00003009 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00003010 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3011 return ExprError();
3012 }
3013
Abramo Bagnara7945c982012-01-27 09:46:47 +00003014 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00003015}
3016
Douglas Gregorb67535d2009-03-31 00:43:58 +00003017/// \brief Form a dependent template name.
3018///
3019/// This action forms a dependent template name given the template
3020/// name and its (presumably dependent) scope specifier. For
3021/// example, given "MetaFun::template apply", the scope specifier \p
3022/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3023/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003024TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00003025 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003026 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00003027 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00003028 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00003029 bool EnteringContext,
3030 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00003031 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3032 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003033 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00003034 diag::warn_cxx98_compat_template_outside_of_template :
3035 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036 << FixItHint::CreateRemoval(TemplateKWLoc);
3037
Craig Topperc3ec1492014-05-26 06:22:03 +00003038 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00003039 if (SS.isSet())
3040 LookupCtx = computeDeclContext(SS, EnteringContext);
3041 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00003042 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00003043 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00003044 // C++0x [temp.names]p5:
3045 // If a name prefixed by the keyword template is not the name of
3046 // a template, the program is ill-formed. [Note: the keyword
3047 // template may not be applied to non-template members of class
3048 // templates. -end note ] [ Note: as is the case with the
3049 // typename prefix, the template prefix is allowed in cases
3050 // where it is not strictly necessary; i.e., when the
3051 // nested-name-specifier or the expression on the left of the ->
3052 // or . is not dependent on a template-parameter, or the use
3053 // does not appear in the scope of a template. -end note]
3054 //
3055 // Note: C++03 was more strict here, because it banned the use of
3056 // the "template" keyword prior to a template-name that was not a
3057 // dependent name. C++ DR468 relaxed this requirement (the
3058 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00003059 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00003060 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00003061 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00003062 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00003063 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00003064 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3065 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00003066 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3067 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00003068 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00003069 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003070 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003071 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003072 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003073 << Name.getSourceRange()
3074 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003075 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00003076 } else {
3077 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00003078 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003079 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00003080 }
3081
Aaron Ballman4a979672014-01-03 13:56:08 +00003082 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003083
Douglas Gregor3cf81312009-11-03 23:16:33 +00003084 switch (Name.getKind()) {
3085 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003086 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003087 Name.Identifier));
3088 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089
Douglas Gregor71395fa2009-11-04 00:56:37 +00003090 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003091 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003092 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003093 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003094
3095 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003096 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003097
Douglas Gregor3cf81312009-11-03 23:16:33 +00003098 default:
3099 break;
3100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003102 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003103 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003104 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003105 << Name.getSourceRange()
3106 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003107 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003108}
3109
Mike Stump11289f42009-09-09 15:08:12 +00003110bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003111 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003112 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003113 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003114 QualType ArgType;
3115 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003116
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003117 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003118 switch(Arg.getKind()) {
3119 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003120 // C++ [temp.arg.type]p1:
3121 // A template-argument for a template-parameter which is a
3122 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003123 ArgType = Arg.getAsType();
3124 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003125 break;
3126 case TemplateArgument::Template: {
3127 // We have a template type parameter but the template argument
3128 // is a template without any arguments.
3129 SourceRange SR = AL.getSourceRange();
3130 TemplateName Name = Arg.getAsTemplate();
3131 Diag(SR.getBegin(), diag::err_template_missing_args)
3132 << Name << SR;
3133 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3134 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003135
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003136 return true;
3137 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003138 case TemplateArgument::Expression: {
3139 // We have a template type parameter but the template argument is an
3140 // expression; see if maybe it is missing the "typename" keyword.
3141 CXXScopeSpec SS;
3142 DeclarationNameInfo NameInfo;
3143
3144 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3145 SS.Adopt(ArgExpr->getQualifierLoc());
3146 NameInfo = ArgExpr->getNameInfo();
3147 } else if (DependentScopeDeclRefExpr *ArgExpr =
3148 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3149 SS.Adopt(ArgExpr->getQualifierLoc());
3150 NameInfo = ArgExpr->getNameInfo();
3151 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3152 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003153 if (ArgExpr->isImplicitAccess()) {
3154 SS.Adopt(ArgExpr->getQualifierLoc());
3155 NameInfo = ArgExpr->getMemberNameInfo();
3156 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003157 }
3158
Reid Kleckner377c1592014-06-10 23:29:48 +00003159 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003160 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3161 LookupParsedName(Result, CurScope, &SS);
3162
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003163 if (Result.getAsSingle<TypeDecl>() ||
3164 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003165 LookupResult::NotFoundInCurrentInstantiation) {
3166 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003167 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003168 Diag(Loc, getLangOpts().MSVCCompat
3169 ? diag::ext_ms_template_type_arg_missing_typename
3170 : diag::err_template_arg_must_be_type_suggest)
3171 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003172 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003173
3174 // Recover by synthesizing a type using the location information that we
3175 // already have.
3176 ArgType =
3177 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3178 TypeLocBuilder TLB;
3179 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3180 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3181 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3182 TL.setNameLoc(NameInfo.getLoc());
3183 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3184
3185 // Overwrite our input TemplateArgumentLoc so that we can recover
3186 // properly.
3187 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3188 TemplateArgumentLocInfo(TSI));
3189
3190 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003191 }
3192 }
3193 // fallthrough
3194 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003195 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003196 // We have a template type parameter but the template argument
3197 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003198 SourceRange SR = AL.getSourceRange();
3199 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003200 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003201
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003202 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003203 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003204 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003205
Reid Kleckner377c1592014-06-10 23:29:48 +00003206 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003207 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003208
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003209 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003210 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003211
3212 // Objective-C ARC:
3213 // If an explicitly-specified template argument type is a lifetime type
3214 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003215 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003216 ArgType->isObjCLifetimeType() &&
3217 !ArgType.getObjCLifetime()) {
3218 Qualifiers Qs;
3219 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3220 ArgType = Context.getQualifiedType(ArgType, Qs);
3221 }
3222
3223 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003224 return false;
3225}
3226
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003227/// \brief Substitute template arguments into the default template argument for
3228/// the given template type parameter.
3229///
3230/// \param SemaRef the semantic analysis object for which we are performing
3231/// the substitution.
3232///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003233/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003234/// for.
3235///
3236/// \param TemplateLoc the location of the template name that started the
3237/// template-id we are checking.
3238///
3239/// \param RAngleLoc the location of the right angle bracket ('>') that
3240/// terminates the template-id.
3241///
3242/// \param Param the template template parameter whose default we are
3243/// substituting into.
3244///
3245/// \param Converted the list of template arguments provided for template
3246/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003247/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003248static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003249SubstDefaultTemplateArgument(Sema &SemaRef,
3250 TemplateDecl *Template,
3251 SourceLocation TemplateLoc,
3252 SourceLocation RAngleLoc,
3253 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003254 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003255 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003256
3257 // If the argument type is dependent, instantiate it now based
3258 // on the previously-computed template arguments.
3259 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003260 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003261 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003262 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003263 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003264 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265
David Majnemer89189202013-08-28 23:48:32 +00003266 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3267 Converted.data(), Converted.size());
3268
3269 // Only substitute for the innermost template argument list.
3270 MultiLevelTemplateArgumentList TemplateArgLists;
3271 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3272 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3273 TemplateArgLists.addOuterTemplateArguments(None);
3274
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003275 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003276 ArgType =
3277 SemaRef.SubstType(ArgType, TemplateArgLists,
3278 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003279 }
3280
3281 return ArgType;
3282}
3283
3284/// \brief Substitute template arguments into the default template argument for
3285/// the given non-type template parameter.
3286///
3287/// \param SemaRef the semantic analysis object for which we are performing
3288/// the substitution.
3289///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003291/// for.
3292///
3293/// \param TemplateLoc the location of the template name that started the
3294/// template-id we are checking.
3295///
3296/// \param RAngleLoc the location of the right angle bracket ('>') that
3297/// terminates the template-id.
3298///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003299/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003300/// substituting into.
3301///
3302/// \param Converted the list of template arguments provided for template
3303/// parameters that precede \p Param in the template parameter list.
3304///
3305/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003306static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003307SubstDefaultTemplateArgument(Sema &SemaRef,
3308 TemplateDecl *Template,
3309 SourceLocation TemplateLoc,
3310 SourceLocation RAngleLoc,
3311 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003312 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003313 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003314 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003315 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003316 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003317 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003318
David Majnemer89189202013-08-28 23:48:32 +00003319 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3320 Converted.data(), Converted.size());
3321
3322 // Only substitute for the innermost template argument list.
3323 MultiLevelTemplateArgumentList TemplateArgLists;
3324 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3325 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3326 TemplateArgLists.addOuterTemplateArguments(None);
3327
Faisal Vali48401eb2015-11-19 19:20:17 +00003328 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3329 Sema::ConstantEvaluated);
David Majnemer89189202013-08-28 23:48:32 +00003330 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003331}
3332
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003333/// \brief Substitute template arguments into the default template argument for
3334/// the given template template parameter.
3335///
3336/// \param SemaRef the semantic analysis object for which we are performing
3337/// the substitution.
3338///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003339/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003340/// for.
3341///
3342/// \param TemplateLoc the location of the template name that started the
3343/// template-id we are checking.
3344///
3345/// \param RAngleLoc the location of the right angle bracket ('>') that
3346/// terminates the template-id.
3347///
3348/// \param Param the template template parameter whose default we are
3349/// substituting into.
3350///
3351/// \param Converted the list of template arguments provided for template
3352/// parameters that precede \p Param in the template parameter list.
3353///
Douglas Gregordf846d12011-03-02 18:46:51 +00003354/// \param QualifierLoc Will be set to the nested-name-specifier (with
3355/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003356///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003357/// \returns the substituted template argument, or NULL if an error occurred.
3358static TemplateName
3359SubstDefaultTemplateArgument(Sema &SemaRef,
3360 TemplateDecl *Template,
3361 SourceLocation TemplateLoc,
3362 SourceLocation RAngleLoc,
3363 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003364 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003365 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003366 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003367 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003368 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003369 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003370
David Majnemer89189202013-08-28 23:48:32 +00003371 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3372 Converted.data(), Converted.size());
3373
3374 // Only substitute for the innermost template argument list.
3375 MultiLevelTemplateArgumentList TemplateArgLists;
3376 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3377 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3378 TemplateArgLists.addOuterTemplateArguments(None);
3379
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003380 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003381 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003382 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003383 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003384 QualifierLoc =
3385 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003386 if (!QualifierLoc)
3387 return TemplateName();
3388 }
David Majnemer89189202013-08-28 23:48:32 +00003389
3390 return SemaRef.SubstTemplateName(
3391 QualifierLoc,
3392 Param->getDefaultArgument().getArgument().getAsTemplate(),
3393 Param->getDefaultArgument().getTemplateNameLoc(),
3394 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003395}
3396
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003397/// \brief If the given template parameter has a default template
3398/// argument, substitute into that default template argument and
3399/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003401Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3402 SourceLocation TemplateLoc,
3403 SourceLocation RAngleLoc,
3404 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003405 SmallVectorImpl<TemplateArgument>
3406 &Converted,
3407 bool &HasDefaultArg) {
3408 HasDefaultArg = false;
3409
3410 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003411 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003412 return TemplateArgumentLoc();
3413
Richard Smithc87b9382013-07-04 01:01:24 +00003414 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003415 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003416 TemplateLoc,
3417 RAngleLoc,
3418 TypeParm,
3419 Converted);
3420 if (DI)
3421 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3422
3423 return TemplateArgumentLoc();
3424 }
3425
3426 if (NonTypeTemplateParmDecl *NonTypeParm
3427 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003428 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003429 return TemplateArgumentLoc();
3430
Richard Smithc87b9382013-07-04 01:01:24 +00003431 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003432 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003433 TemplateLoc,
3434 RAngleLoc,
3435 NonTypeParm,
3436 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003437 if (Arg.isInvalid())
3438 return TemplateArgumentLoc();
3439
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003440 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003441 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3442 }
3443
3444 TemplateTemplateParmDecl *TempTempParm
3445 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003446 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003447 return TemplateArgumentLoc();
3448
Richard Smithc87b9382013-07-04 01:01:24 +00003449 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003450 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003451 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003453 RAngleLoc,
3454 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003455 Converted,
3456 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003457 if (TName.isNull())
3458 return TemplateArgumentLoc();
3459
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003461 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003462 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3463}
3464
Douglas Gregorda0fb532009-11-11 19:31:23 +00003465/// \brief Check that the given template argument corresponds to the given
3466/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003467///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003469/// checked.
3470///
Richard Trieu15b66532015-01-24 02:48:32 +00003471/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003472///
3473/// \param Template The template in which the template argument resides.
3474///
3475/// \param TemplateLoc The location of the template name for the template
3476/// whose argument list we're matching.
3477///
3478/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3479/// the template argument list.
3480///
3481/// \param ArgumentPackIndex The index into the argument pack where this
3482/// argument will be placed. Only valid if the parameter is a parameter pack.
3483///
3484/// \param Converted The checked, converted argument will be added to the
3485/// end of this small vector.
3486///
3487/// \param CTAK Describes how we arrived at this particular template argument:
3488/// explicitly written, deduced, etc.
3489///
3490/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003491bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003492 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003493 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003494 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003495 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003496 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003497 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003498 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003499 // Check template type parameters.
3500 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003501 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregoreebed722009-11-11 19:41:09 +00003503 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003505 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003506 // with the template arguments we've seen thus far. But if the
3507 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003508 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003509 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3510 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511
Peter Collingbourne01687632010-12-10 17:08:53 +00003512 if (NTTPType->isDependentType() &&
3513 !isa<TemplateTemplateParmDecl>(Template) &&
3514 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003515 // Do substitution on the type of the non-type template parameter.
3516 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003517 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003518 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003519 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003520 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
3522 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003523 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003524 NTTPType = SubstType(NTTPType,
3525 MultiLevelTemplateArgumentList(TemplateArgs),
3526 NTTP->getLocation(),
3527 NTTP->getDeclName());
3528 // If that worked, check the non-type template parameter type
3529 // for validity.
3530 if (!NTTPType.isNull())
3531 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3532 NTTP->getLocation());
3533 if (NTTPType.isNull())
3534 return true;
3535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536
Douglas Gregorda0fb532009-11-11 19:31:23 +00003537 switch (Arg.getArgument().getKind()) {
3538 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003539 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540
Douglas Gregorda0fb532009-11-11 19:31:23 +00003541 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003542 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003543 ExprResult Res =
3544 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3545 Result, CTAK);
3546 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003547 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548
Richard Trieu15b66532015-01-24 02:48:32 +00003549 // If the resulting expression is new, then use it in place of the
3550 // old expression in the template argument.
3551 if (Res.get() != Arg.getArgument().getAsExpr()) {
3552 TemplateArgument TA(Res.get());
3553 Arg = TemplateArgumentLoc(TA, Res.get());
3554 }
3555
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003556 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003557 break;
3558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559
Douglas Gregorda0fb532009-11-11 19:31:23 +00003560 case TemplateArgument::Declaration:
3561 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003562 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003563 // We've already checked this template argument, so just copy
3564 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003565 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003566 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567
Douglas Gregorda0fb532009-11-11 19:31:23 +00003568 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003569 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003570 // We were given a template template argument. It may not be ill-formed;
3571 // see below.
3572 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003573 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3574 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003575 // We have a template argument such as \c T::template X, which we
3576 // parsed as a template template argument. However, since we now
3577 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003578 // template name into an expression.
3579
3580 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3581 Arg.getTemplateNameLoc());
3582
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003583 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003584 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003585 // FIXME: the template-template arg was a DependentTemplateName,
3586 // so it was provided with a template keyword. However, its source
3587 // location is not stored in the template argument structure.
3588 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003589 ExprResult E = DependentScopeDeclRefExpr::Create(
3590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3591 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003593 // If we parsed the template argument as a pack expansion, create a
3594 // pack expansion expression.
3595 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003596 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003597 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003598 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregorda0fb532009-11-11 19:31:23 +00003601 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003602 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003603 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003604 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003605
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003606 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003607 break;
3608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003609
Douglas Gregorda0fb532009-11-11 19:31:23 +00003610 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003611 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003612 // therefore cannot be a non-type template argument.
3613 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3614 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Douglas Gregorda0fb532009-11-11 19:31:23 +00003616 Diag(Param->getLocation(), diag::note_template_param_here);
3617 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618
Douglas Gregorda0fb532009-11-11 19:31:23 +00003619 case TemplateArgument::Type: {
3620 // We have a non-type template parameter but the template
3621 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622
Douglas Gregorda0fb532009-11-11 19:31:23 +00003623 // C++ [temp.arg]p2:
3624 // In a template-argument, an ambiguity between a type-id and
3625 // an expression is resolved to a type-id, regardless of the
3626 // form of the corresponding template-parameter.
3627 //
3628 // We warn specifically about this case, since it can be rather
3629 // confusing for users.
3630 QualType T = Arg.getArgument().getAsType();
3631 SourceRange SR = Arg.getSourceRange();
3632 if (T->isFunctionType())
3633 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3634 else
3635 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3636 Diag(Param->getLocation(), diag::note_template_param_here);
3637 return true;
3638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639
Douglas Gregorda0fb532009-11-11 19:31:23 +00003640 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003641 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003642 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003643
Douglas Gregorda0fb532009-11-11 19:31:23 +00003644 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645 }
3646
3647
Douglas Gregorda0fb532009-11-11 19:31:23 +00003648 // Check template template parameters.
3649 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003650
Douglas Gregorda0fb532009-11-11 19:31:23 +00003651 // Substitute into the template parameter list of the template
3652 // template parameter, since previously-supplied template arguments
3653 // may appear within the template template parameter.
3654 {
3655 // Set up a template instantiation context.
3656 LocalInstantiationScope Scope(*this);
3657 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003658 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003659 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003660 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003661 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
3663 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003664 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003665 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003666 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003667 MultiLevelTemplateArgumentList(TemplateArgs)));
3668 if (!TempParm)
3669 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregorda0fb532009-11-11 19:31:23 +00003672 switch (Arg.getArgument().getKind()) {
3673 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003674 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675
Douglas Gregorda0fb532009-11-11 19:31:23 +00003676 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003677 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003678 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003679 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003681 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003682 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683
Douglas Gregorda0fb532009-11-11 19:31:23 +00003684 case TemplateArgument::Expression:
3685 case TemplateArgument::Type:
3686 // We have a template template parameter but the template
3687 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003688 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003689 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003690 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691
Douglas Gregorda0fb532009-11-11 19:31:23 +00003692 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003693 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003694 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003695 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003696 case TemplateArgument::NullPtr:
3697 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698
Douglas Gregorda0fb532009-11-11 19:31:23 +00003699 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003700 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003702
Douglas Gregorda0fb532009-11-11 19:31:23 +00003703 return false;
3704}
3705
Douglas Gregor8e072612012-02-03 07:34:46 +00003706/// \brief Diagnose an arity mismatch in the
3707static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3708 SourceLocation TemplateLoc,
3709 TemplateArgumentListInfo &TemplateArgs) {
3710 TemplateParameterList *Params = Template->getTemplateParameters();
3711 unsigned NumParams = Params->size();
3712 unsigned NumArgs = TemplateArgs.size();
3713
3714 SourceRange Range;
3715 if (NumArgs > NumParams)
3716 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3717 TemplateArgs.getRAngleLoc());
3718 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3719 << (NumArgs > NumParams)
3720 << (isa<ClassTemplateDecl>(Template)? 0 :
3721 isa<FunctionTemplateDecl>(Template)? 1 :
3722 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3723 << Template << Range;
3724 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3725 << Params->getSourceRange();
3726 return true;
3727}
3728
Richard Smith1fde8ec2012-09-07 02:06:42 +00003729/// \brief Check whether the template parameter is a pack expansion, and if so,
3730/// determine the number of parameters produced by that expansion. For instance:
3731///
3732/// \code
3733/// template<typename ...Ts> struct A {
3734/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3735/// };
3736/// \endcode
3737///
3738/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3739/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003740static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003741 if (NonTypeTemplateParmDecl *NTTP
3742 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3743 if (NTTP->isExpandedParameterPack())
3744 return NTTP->getNumExpansionTypes();
3745 }
3746
3747 if (TemplateTemplateParmDecl *TTP
3748 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3749 if (TTP->isExpandedParameterPack())
3750 return TTP->getNumExpansionTemplateParameters();
3751 }
3752
David Blaikie7a30dc52013-02-21 01:47:18 +00003753 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003754}
3755
Richard Smith35c1df52015-06-17 20:16:32 +00003756/// Diagnose a missing template argument.
3757template<typename TemplateParmDecl>
3758static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3759 TemplateDecl *TD,
3760 const TemplateParmDecl *D,
3761 TemplateArgumentListInfo &Args) {
3762 // Dig out the most recent declaration of the template parameter; there may be
3763 // declarations of the template that are more recent than TD.
3764 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3765 ->getTemplateParameters()
3766 ->getParam(D->getIndex()));
3767
3768 // If there's a default argument that's not visible, diagnose that we're
3769 // missing a module import.
3770 llvm::SmallVector<Module*, 8> Modules;
3771 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3772 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3773 D->getDefaultArgumentLoc(), Modules,
3774 Sema::MissingImportKind::DefaultArgument,
Richard Smith6739a102016-05-05 00:56:12 +00003775 /*Recover*/true);
Richard Smith35c1df52015-06-17 20:16:32 +00003776 return true;
3777 }
3778
3779 // FIXME: If there's a more recent default argument that *is* visible,
3780 // diagnose that it was declared too late.
3781
3782 return diagnoseArityMismatch(S, TD, Loc, Args);
3783}
3784
Douglas Gregord32e0282009-02-09 23:23:08 +00003785/// \brief Check that the given template argument list is well-formed
3786/// for specializing the given template.
3787bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3788 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003789 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003790 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003791 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003792 // Make a copy of the template arguments for processing. Only make the
3793 // changes at the end when successful in matching the arguments to the
3794 // template.
3795 TemplateArgumentListInfo NewArgs = TemplateArgs;
3796
Douglas Gregord32e0282009-02-09 23:23:08 +00003797 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003798
Richard Trieu15b66532015-01-24 02:48:32 +00003799 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003800
Mike Stump11289f42009-09-09 15:08:12 +00003801 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003802 // [...] The type and form of each template-argument specified in
3803 // a template-id shall match the type and form specified for the
3804 // corresponding parameter declared by the template in its
3805 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003806 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003807 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003808 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003809 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003810 for (TemplateParameterList::iterator Param = Params->begin(),
3811 ParamEnd = Params->end();
3812 Param != ParamEnd; /* increment in loop */) {
3813 // If we have an expanded parameter pack, make sure we don't have too
3814 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003815 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003816 if (*Expansions == ArgumentPack.size()) {
3817 // We're done with this parameter pack. Pack up its arguments and add
3818 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003819 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003820 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003821 ArgumentPack.clear();
3822
Richard Smith1fde8ec2012-09-07 02:06:42 +00003823 // This argument is assigned to the next parameter.
3824 ++Param;
3825 continue;
3826 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3827 // Not enough arguments for this parameter pack.
3828 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3829 << false
3830 << (isa<ClassTemplateDecl>(Template)? 0 :
3831 isa<FunctionTemplateDecl>(Template)? 1 :
3832 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3833 << Template;
3834 Diag(Template->getLocation(), diag::note_template_decl_here)
3835 << Params->getSourceRange();
3836 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003837 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Richard Smith1fde8ec2012-09-07 02:06:42 +00003840 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003841 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003842 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003844 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003845 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Richard Smith96d71c32014-11-12 23:38:38 +00003847 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003848 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003849 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3850 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003851 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003852 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003853 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003854 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003855 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003856 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003857 Diag((*Param)->getLocation(), diag::note_template_param_here);
3858 return true;
3859 }
3860
Richard Smith1fde8ec2012-09-07 02:06:42 +00003861 // We're now done with this argument.
3862 ++ArgIdx;
3863
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003864 if ((*Param)->isTemplateParameterPack()) {
3865 // The template parameter was a template parameter pack, so take the
3866 // deduced argument and place it on the argument pack. Note that we
3867 // stay on the same template parameter so that we can deduce more
3868 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003869 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003870 } else {
3871 // Move to the next template parameter.
3872 ++Param;
3873 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003874
Richard Smith96d71c32014-11-12 23:38:38 +00003875 // If we just saw a pack expansion into a non-pack, then directly convert
3876 // the remaining arguments, because we don't know what parameters they'll
3877 // match up with.
3878 if (PackExpansionIntoNonPack) {
3879 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003880 // If we were part way through filling in an expanded parameter pack,
3881 // fall back to just producing individual arguments.
3882 Converted.insert(Converted.end(),
3883 ArgumentPack.begin(), ArgumentPack.end());
3884 ArgumentPack.clear();
3885 }
3886
3887 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003888 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003889 ++ArgIdx;
3890 }
3891
Richard Smith1fde8ec2012-09-07 02:06:42 +00003892 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003893 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003894
Douglas Gregor84d49a22009-11-11 21:54:23 +00003895 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897
Douglas Gregor2f157c92011-06-03 02:59:40 +00003898 // If we're checking a partial template argument list, we're done.
3899 if (PartialTemplateArgs) {
3900 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003901 Converted.push_back(
3902 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3903
Richard Smith1fde8ec2012-09-07 02:06:42 +00003904 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003905 }
3906
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003907 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003908 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003909 if ((*Param)->isTemplateParameterPack()) {
3910 assert(!getExpandedPackSize(*Param) &&
3911 "Should have dealt with this already");
3912
3913 // A non-expanded parameter pack before the end of the parameter list
3914 // only occurs for an ill-formed template parameter list, unless we've
3915 // got a partial argument list for a function template, so just bail out.
3916 if (Param + 1 != ParamEnd)
3917 return true;
3918
Benjamin Kramercce63472015-08-05 09:40:22 +00003919 Converted.push_back(
3920 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003921 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003922
3923 ++Param;
3924 continue;
3925 }
3926
Douglas Gregor8e072612012-02-03 07:34:46 +00003927 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003928 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929
Douglas Gregor84d49a22009-11-11 21:54:23 +00003930 // Retrieve the default template argument from the template
3931 // parameter. For each kind of template parameter, we substitute the
3932 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003933 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003934 // the default argument.
3935 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003936 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003937 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3938 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003939
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003940 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003941 Template,
3942 TemplateLoc,
3943 RAngleLoc,
3944 TTP,
3945 Converted);
3946 if (!ArgType)
3947 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948
Douglas Gregor84d49a22009-11-11 21:54:23 +00003949 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3950 ArgType);
3951 } else if (NonTypeTemplateParmDecl *NTTP
3952 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003953 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003954 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3955 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003956
John McCalldadc5752010-08-24 06:29:42 +00003957 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958 TemplateLoc,
3959 RAngleLoc,
3960 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003961 Converted);
3962 if (E.isInvalid())
3963 return true;
3964
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003965 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003966 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3967 } else {
3968 TemplateTemplateParmDecl *TempParm
3969 = cast<TemplateTemplateParmDecl>(*Param);
3970
Richard Smith95d83952015-06-10 20:36:34 +00003971 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003972 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3973 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003974
Douglas Gregordf846d12011-03-02 18:46:51 +00003975 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003976 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977 TemplateLoc,
3978 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003979 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003980 Converted,
3981 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003982 if (Name.isNull())
3983 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003984
Douglas Gregor9d802122011-03-02 17:09:35 +00003985 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3986 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988
Douglas Gregor84d49a22009-11-11 21:54:23 +00003989 // Introduce an instantiation record that describes where we are using
3990 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003991 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3992 SourceRange(TemplateLoc, RAngleLoc));
3993 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003994 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003995
Douglas Gregor84d49a22009-11-11 21:54:23 +00003996 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003997 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003998 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003999 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004000
Richard Trieu15b66532015-01-24 02:48:32 +00004001 // Core issue 150 (assumed resolution): if this is a template template
4002 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00004003 // template definition.
4004 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00004005 NewArgs.addArgument(Arg);
4006
Douglas Gregor9abeaf52010-12-20 16:57:52 +00004007 // Move to the next template parameter and argument.
4008 ++Param;
4009 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00004010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004011
Richard Smith07f79912014-06-06 16:00:50 +00004012 // If we're performing a partial argument substitution, allow any trailing
4013 // pack expansions; they might be empty. This can happen even if
4014 // PartialTemplateArgs is false (the list of arguments is complete but
4015 // still dependent).
4016 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4017 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00004018 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4019 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00004020 }
4021
Douglas Gregor8e072612012-02-03 07:34:46 +00004022 // If we have any leftover arguments, then there were too many arguments.
4023 // Complain and fail.
4024 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00004025 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4026
4027 // No problems found with the new argument list, propagate changes back
4028 // to caller.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00004029 TemplateArgs = std::move(NewArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004030
Richard Smith1fde8ec2012-09-07 02:06:42 +00004031 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00004032}
4033
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004034namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035 class UnnamedLocalNoLinkageFinder
4036 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004037 {
4038 Sema &S;
4039 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004041 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004043 public:
4044 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4045
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004046 bool Visit(QualType T) {
4047 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004048 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004050#define TYPE(Class, Parent) \
4051 bool Visit##Class##Type(const Class##Type *);
4052#define ABSTRACT_TYPE(Class, Parent) \
4053 bool Visit##Class##Type(const Class##Type *) { return false; }
4054#define NON_CANONICAL_TYPE(Class, Parent) \
4055 bool Visit##Class##Type(const Class##Type *) { return false; }
4056#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004058 bool VisitTagDecl(const TagDecl *Tag);
4059 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4060 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004061} // end anonymous namespace
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004062
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004063bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004064 return false;
4065}
4066
4067bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4068 return Visit(T->getElementType());
4069}
4070
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004071bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004072 return Visit(T->getPointeeType());
4073}
4074
4075bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004077 return Visit(T->getPointeeType());
4078}
4079
4080bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004082 return Visit(T->getPointeeType());
4083}
4084
4085bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004086 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004087 return Visit(T->getPointeeType());
4088}
4089
4090bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004091 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004092 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4093}
4094
4095bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004097 return Visit(T->getElementType());
4098}
4099
4100bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004102 return Visit(T->getElementType());
4103}
4104
4105bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004106 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004107 return Visit(T->getElementType());
4108}
4109
4110bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004112 return Visit(T->getElementType());
4113}
4114
4115bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004117 return Visit(T->getElementType());
4118}
4119
4120bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4121 return Visit(T->getElementType());
4122}
4123
4124bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4125 return Visit(T->getElementType());
4126}
4127
4128bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4129 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004130 for (const auto &A : T->param_types()) {
4131 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004132 return true;
4133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134
Alp Toker314cc812014-01-25 16:55:45 +00004135 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004136}
4137
4138bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4139 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004140 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004141}
4142
4143bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4144 const UnresolvedUsingType*) {
4145 return false;
4146}
4147
4148bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4149 return false;
4150}
4151
4152bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4153 return Visit(T->getUnderlyingType());
4154}
4155
4156bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4157 return false;
4158}
4159
Alexis Hunte852b102011-05-24 22:41:36 +00004160bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4161 const UnaryTransformType*) {
4162 return false;
4163}
4164
Richard Smith30482bc2011-02-20 03:19:35 +00004165bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4166 return Visit(T->getDeducedType());
4167}
4168
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004169bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4170 return VisitTagDecl(T->getDecl());
4171}
4172
4173bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4174 return VisitTagDecl(T->getDecl());
4175}
4176
4177bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4178 const TemplateTypeParmType*) {
4179 return false;
4180}
4181
Douglas Gregorada4b792011-01-14 02:55:32 +00004182bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4183 const SubstTemplateTypeParmPackType *) {
4184 return false;
4185}
4186
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004187bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4188 const TemplateSpecializationType*) {
4189 return false;
4190}
4191
4192bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4193 const InjectedClassNameType* T) {
4194 return VisitTagDecl(T->getDecl());
4195}
4196
4197bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4198 const DependentNameType* T) {
4199 return VisitNestedNameSpecifier(T->getQualifier());
4200}
4201
4202bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4203 const DependentTemplateSpecializationType* T) {
4204 return VisitNestedNameSpecifier(T->getQualifier());
4205}
4206
Douglas Gregord2fa7662010-12-20 02:24:11 +00004207bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4208 const PackExpansionType* T) {
4209 return Visit(T->getPattern());
4210}
4211
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004212bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4213 return false;
4214}
4215
4216bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4217 const ObjCInterfaceType *) {
4218 return false;
4219}
4220
4221bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4222 const ObjCObjectPointerType *) {
4223 return false;
4224}
4225
Eli Friedman0dfb8892011-10-06 23:00:33 +00004226bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4227 return Visit(T->getValueType());
4228}
4229
Xiuli Pan9c14e282016-01-09 12:53:17 +00004230bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4231 return false;
4232}
4233
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004234bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4235 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004236 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004237 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004238 diag::warn_cxx98_compat_template_arg_local_type :
4239 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004240 << S.Context.getTypeDeclType(Tag) << SR;
4241 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242 }
4243
John McCall5ea95772013-03-09 00:54:27 +00004244 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004245 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004246 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004247 diag::warn_cxx98_compat_template_arg_unnamed_type :
4248 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004249 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4250 return true;
4251 }
4252
4253 return false;
4254}
4255
4256bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4257 NestedNameSpecifier *NNS) {
4258 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4259 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004261 switch (NNS->getKind()) {
4262 case NestedNameSpecifier::Identifier:
4263 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004264 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004265 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004266 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004267 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004269 case NestedNameSpecifier::TypeSpec:
4270 case NestedNameSpecifier::TypeSpecWithTemplate:
4271 return Visit(QualType(NNS->getAsType(), 0));
4272 }
David Blaikie8a40f702012-01-17 06:56:22 +00004273 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004274}
4275
Douglas Gregord32e0282009-02-09 23:23:08 +00004276/// \brief Check a template argument against its corresponding
4277/// template type parameter.
4278///
4279/// This routine implements the semantics of C++ [temp.arg.type]. It
4280/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004281bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004282 TypeSourceInfo *ArgInfo) {
4283 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004284 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004285 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004286
4287 if (Arg->isVariablyModifiedType()) {
4288 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004289 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004290 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004291 }
4292
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004293 // C++03 [temp.arg.type]p2:
4294 // A local type, a type with no linkage, an unnamed type or a type
4295 // compounded from any of these types shall not be used as a
4296 // template-argument for a template type-parameter.
4297 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004298 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004299 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004300 bool NeedsCheck;
4301 if (LangOpts.CPlusPlus11)
4302 NeedsCheck =
4303 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4304 SR.getBegin()) ||
4305 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4306 SR.getBegin());
4307 else
4308 NeedsCheck = Arg->hasUnnamedOrLocalType();
4309
4310 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004311 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4312 (void)Finder.Visit(Context.getCanonicalType(Arg));
4313 }
4314
Douglas Gregord32e0282009-02-09 23:23:08 +00004315 return false;
4316}
4317
Douglas Gregor20fdef32012-04-10 17:08:25 +00004318enum NullPointerValueKind {
4319 NPV_NotNullPointer,
4320 NPV_NullPointer,
4321 NPV_Error
4322};
4323
4324/// \brief Determine whether the given template argument is a null pointer
4325/// value of the appropriate type.
4326static NullPointerValueKind
4327isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4328 QualType ParamType, Expr *Arg) {
4329 if (Arg->isValueDependent() || Arg->isTypeDependent())
4330 return NPV_NotNullPointer;
David Majnemer69c3ddc2015-09-11 20:18:09 +00004331
Richard Smithdb0ac552015-12-18 22:40:25 +00004332 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
David Majnemerb54368c2015-09-11 20:55:29 +00004333 llvm_unreachable(
4334 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
David Majnemer69c3ddc2015-09-11 20:18:09 +00004335
David Majnemer5c734ad2014-08-14 00:49:23 +00004336 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004337 return NPV_NotNullPointer;
4338
4339 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004340 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4341 if (ArgRV.isInvalid())
4342 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004343 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004344
Douglas Gregor20fdef32012-04-10 17:08:25 +00004345 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004346 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004347 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004348 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004349 EvalResult.HasSideEffects) {
4350 SourceLocation DiagLoc = Arg->getExprLoc();
4351
4352 // If our only note is the usual "invalid subexpression" note, just point
4353 // the caret at its location rather than producing an essentially
4354 // redundant note.
4355 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4356 diag::note_invalid_subexpr_in_const_expr) {
4357 DiagLoc = Notes[0].first;
4358 Notes.clear();
4359 }
4360
4361 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4362 << Arg->getType() << Arg->getSourceRange();
4363 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4364 S.Diag(Notes[I].first, Notes[I].second);
4365
4366 S.Diag(Param->getLocation(), diag::note_template_param_here);
4367 return NPV_Error;
4368 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004369
4370 // C++11 [temp.arg.nontype]p1:
4371 // - an address constant expression of type std::nullptr_t
4372 if (Arg->getType()->isNullPtrType())
4373 return NPV_NullPointer;
4374
4375 // - a constant expression that evaluates to a null pointer value (4.10); or
4376 // - a constant expression that evaluates to a null member pointer value
4377 // (4.11); or
4378 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4379 (EvalResult.Val.isMemberPointer() &&
4380 !EvalResult.Val.getMemberPointerDecl())) {
4381 // If our expression has an appropriate type, we've succeeded.
4382 bool ObjCLifetimeConversion;
4383 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4384 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4385 ObjCLifetimeConversion))
4386 return NPV_NullPointer;
4387
4388 // The types didn't match, but we know we got a null pointer; complain,
4389 // then recover as if the types were correct.
4390 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4391 << Arg->getType() << ParamType << Arg->getSourceRange();
4392 S.Diag(Param->getLocation(), diag::note_template_param_here);
4393 return NPV_NullPointer;
4394 }
4395
4396 // If we don't have a null pointer value, but we do have a NULL pointer
4397 // constant, suggest a cast to the appropriate type.
4398 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4399 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4400 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004401 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4402 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4403 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004404 S.Diag(Param->getLocation(), diag::note_template_param_here);
4405 return NPV_NullPointer;
4406 }
4407
4408 // FIXME: If we ever want to support general, address-constant expressions
4409 // as non-type template arguments, we should return the ExprResult here to
4410 // be interpreted by the caller.
4411 return NPV_NotNullPointer;
4412}
4413
David Majnemer61c39a12013-08-23 05:39:39 +00004414/// \brief Checks whether the given template argument is compatible with its
4415/// template parameter.
4416static bool CheckTemplateArgumentIsCompatibleWithParameter(
4417 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4418 Expr *Arg, QualType ArgType) {
4419 bool ObjCLifetimeConversion;
4420 if (ParamType->isPointerType() &&
4421 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4422 S.IsQualificationConversion(ArgType, ParamType, false,
4423 ObjCLifetimeConversion)) {
4424 // For pointer-to-object types, qualification conversions are
4425 // permitted.
4426 } else {
4427 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4428 if (!ParamRef->getPointeeType()->isFunctionType()) {
4429 // C++ [temp.arg.nontype]p5b3:
4430 // For a non-type template-parameter of type reference to
4431 // object, no conversions apply. The type referred to by the
4432 // reference may be more cv-qualified than the (otherwise
4433 // identical) type of the template- argument. The
4434 // template-parameter is bound directly to the
4435 // template-argument, which shall be an lvalue.
4436
4437 // FIXME: Other qualifiers?
4438 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4439 unsigned ArgQuals = ArgType.getCVRQualifiers();
4440
4441 if ((ParamQuals | ArgQuals) != ParamQuals) {
4442 S.Diag(Arg->getLocStart(),
4443 diag::err_template_arg_ref_bind_ignores_quals)
4444 << ParamType << Arg->getType() << Arg->getSourceRange();
4445 S.Diag(Param->getLocation(), diag::note_template_param_here);
4446 return true;
4447 }
4448 }
4449 }
4450
4451 // At this point, the template argument refers to an object or
4452 // function with external linkage. We now need to check whether the
4453 // argument and parameter types are compatible.
4454 if (!S.Context.hasSameUnqualifiedType(ArgType,
4455 ParamType.getNonReferenceType())) {
4456 // We can't perform this conversion or binding.
4457 if (ParamType->isReferenceType())
4458 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4459 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4460 else
4461 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4462 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4463 S.Diag(Param->getLocation(), diag::note_template_param_here);
4464 return true;
4465 }
4466 }
4467
4468 return false;
4469}
4470
Douglas Gregorccb07762009-02-11 19:52:55 +00004471/// \brief Checks whether the given template argument is the address
4472/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004474CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4475 NonTypeTemplateParmDecl *Param,
4476 QualType ParamType,
4477 Expr *ArgIn,
4478 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004479 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004480 Expr *Arg = ArgIn;
4481 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004482
Douglas Gregorb242683d2010-04-01 18:32:35 +00004483 bool AddressTaken = false;
4484 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004485 if (S.getLangOpts().MicrosoftExt) {
4486 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4487 // dereference and address-of operators.
4488 Arg = Arg->IgnoreParenCasts();
4489
4490 bool ExtWarnMSTemplateArg = false;
4491 UnaryOperatorKind FirstOpKind;
4492 SourceLocation FirstOpLoc;
4493 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4494 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4495 if (UnOpKind == UO_Deref)
4496 ExtWarnMSTemplateArg = true;
4497 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4498 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4499 if (!AddrOpLoc.isValid()) {
4500 FirstOpKind = UnOpKind;
4501 FirstOpLoc = UnOp->getOperatorLoc();
4502 }
4503 } else
4504 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004505 }
David Majnemer61c39a12013-08-23 05:39:39 +00004506 if (FirstOpLoc.isValid()) {
4507 if (ExtWarnMSTemplateArg)
4508 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4509 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004510
David Majnemer61c39a12013-08-23 05:39:39 +00004511 if (FirstOpKind == UO_AddrOf)
4512 AddressTaken = true;
4513 else if (Arg->getType()->isPointerType()) {
4514 // We cannot let pointers get dereferenced here, that is obviously not a
4515 // constant expression.
4516 assert(FirstOpKind == UO_Deref);
4517 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4518 << Arg->getSourceRange();
4519 }
4520 }
4521 } else {
4522 // See through any implicit casts we added to fix the type.
4523 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004524
David Majnemer61c39a12013-08-23 05:39:39 +00004525 // C++ [temp.arg.nontype]p1:
4526 //
4527 // A template-argument for a non-type, non-template
4528 // template-parameter shall be one of: [...]
4529 //
4530 // -- the address of an object or function with external
4531 // linkage, including function templates and function
4532 // template-ids but excluding non-static class members,
4533 // expressed as & id-expression where the & is optional if
4534 // the name refers to a function or array, or if the
4535 // corresponding template-parameter is a reference; or
4536
4537 // In C++98/03 mode, give an extension warning on any extra parentheses.
4538 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4539 bool ExtraParens = false;
4540 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4541 if (!Invalid && !ExtraParens) {
4542 S.Diag(Arg->getLocStart(),
4543 S.getLangOpts().CPlusPlus11
4544 ? diag::warn_cxx98_compat_template_arg_extra_parens
4545 : diag::ext_template_arg_extra_parens)
4546 << Arg->getSourceRange();
4547 ExtraParens = true;
4548 }
4549
4550 Arg = Parens->getSubExpr();
4551 }
4552
4553 while (SubstNonTypeTemplateParmExpr *subst =
4554 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4555 Arg = subst->getReplacement()->IgnoreImpCasts();
4556
4557 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4558 if (UnOp->getOpcode() == UO_AddrOf) {
4559 Arg = UnOp->getSubExpr();
4560 AddressTaken = true;
4561 AddrOpLoc = UnOp->getOperatorLoc();
4562 }
4563 }
4564
4565 while (SubstNonTypeTemplateParmExpr *subst =
4566 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4567 Arg = subst->getReplacement()->IgnoreImpCasts();
4568 }
John McCall7c454bb2011-07-15 05:09:51 +00004569
David Majnemer07910d62014-06-26 07:48:46 +00004570 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4571 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4572
4573 // If our parameter has pointer type, check for a null template value.
4574 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4575 NullPointerValueKind NPV;
4576 // dllimport'd entities aren't constant but are available inside of template
4577 // arguments.
4578 if (Entity && Entity->hasAttr<DLLImportAttr>())
4579 NPV = NPV_NotNullPointer;
4580 else
4581 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4582 switch (NPV) {
4583 case NPV_NullPointer:
4584 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004585 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4586 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004587 return false;
4588
4589 case NPV_Error:
4590 return true;
4591
4592 case NPV_NotNullPointer:
4593 break;
4594 }
4595 }
4596
Chandler Carruth724a8a12010-01-31 10:01:20 +00004597 // Stop checking the precise nature of the argument if it is value dependent,
4598 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004599 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004600 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004601 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004602 }
David Majnemer61c39a12013-08-23 05:39:39 +00004603
4604 if (isa<CXXUuidofExpr>(Arg)) {
4605 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4606 ArgIn, Arg, ArgType))
4607 return true;
4608
4609 Converted = TemplateArgument(ArgIn);
4610 return false;
4611 }
4612
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004613 if (!DRE) {
4614 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4615 << Arg->getSourceRange();
4616 S.Diag(Param->getLocation(), diag::note_template_param_here);
4617 return true;
4618 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004619
Douglas Gregorccb07762009-02-11 19:52:55 +00004620 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004621 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004622 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004623 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004624 S.Diag(Param->getLocation(), diag::note_template_param_here);
4625 return true;
4626 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004627
4628 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004629 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004630 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004631 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004632 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004633 S.Diag(Param->getLocation(), diag::note_template_param_here);
4634 return true;
4635 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004636 }
Mike Stump11289f42009-09-09 15:08:12 +00004637
Richard Smith9380e0e2012-04-04 21:11:30 +00004638 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4639 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004640
Richard Smith9380e0e2012-04-04 21:11:30 +00004641 // A non-type template argument must refer to an object or function.
4642 if (!Func && !Var) {
4643 // We found something, but we don't know specifically what it is.
4644 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4645 << Arg->getSourceRange();
4646 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4647 return true;
4648 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004649
Richard Smith9380e0e2012-04-04 21:11:30 +00004650 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004651 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004652 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004653 diag::warn_cxx98_compat_template_arg_object_internal :
4654 diag::ext_template_arg_object_internal)
4655 << !Func << Entity << Arg->getSourceRange();
4656 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4657 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004658 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004659 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4660 << !Func << Entity << Arg->getSourceRange();
4661 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4662 << !Func;
4663 return true;
4664 }
4665
4666 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004667 // If the template parameter has pointer type, the function decays.
4668 if (ParamType->isPointerType() && !AddressTaken)
4669 ArgType = S.Context.getPointerType(Func->getType());
4670 else if (AddressTaken && ParamType->isReferenceType()) {
4671 // If we originally had an address-of operator, but the
4672 // parameter has reference type, complain and (if things look
4673 // like they will work) drop the address-of operator.
4674 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4675 ParamType.getNonReferenceType())) {
4676 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4677 << ParamType;
4678 S.Diag(Param->getLocation(), diag::note_template_param_here);
4679 return true;
4680 }
4681
4682 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4683 << ParamType
4684 << FixItHint::CreateRemoval(AddrOpLoc);
4685 S.Diag(Param->getLocation(), diag::note_template_param_here);
4686
4687 ArgType = Func->getType();
4688 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004689 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004690 // A value of reference type is not an object.
4691 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004692 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004693 diag::err_template_arg_reference_var)
4694 << Var->getType() << Arg->getSourceRange();
4695 S.Diag(Param->getLocation(), diag::note_template_param_here);
4696 return true;
4697 }
4698
Richard Smith9380e0e2012-04-04 21:11:30 +00004699 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004700 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004701 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4702 << Arg->getSourceRange();
4703 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4704 return true;
4705 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004706
4707 // If the template parameter has pointer type, we must have taken
4708 // the address of this object.
4709 if (ParamType->isReferenceType()) {
4710 if (AddressTaken) {
4711 // If we originally had an address-of operator, but the
4712 // parameter has reference type, complain and (if things look
4713 // like they will work) drop the address-of operator.
4714 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4715 ParamType.getNonReferenceType())) {
4716 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4717 << ParamType;
4718 S.Diag(Param->getLocation(), diag::note_template_param_here);
4719 return true;
4720 }
4721
4722 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4723 << ParamType
4724 << FixItHint::CreateRemoval(AddrOpLoc);
4725 S.Diag(Param->getLocation(), diag::note_template_param_here);
4726
4727 ArgType = Var->getType();
4728 }
4729 } else if (!AddressTaken && ParamType->isPointerType()) {
4730 if (Var->getType()->isArrayType()) {
4731 // Array-to-pointer decay.
4732 ArgType = S.Context.getArrayDecayedType(Var->getType());
4733 } else {
4734 // If the template parameter has pointer type but the address of
4735 // this object was not taken, complain and (possibly) recover by
4736 // taking the address of the entity.
4737 ArgType = S.Context.getPointerType(Var->getType());
4738 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4739 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4740 << ParamType;
4741 S.Diag(Param->getLocation(), diag::note_template_param_here);
4742 return true;
4743 }
4744
4745 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4746 << ParamType
4747 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4748
4749 S.Diag(Param->getLocation(), diag::note_template_param_here);
4750 }
4751 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753
David Majnemer61c39a12013-08-23 05:39:39 +00004754 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4755 Arg, ArgType))
4756 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004757
4758 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004759 Converted =
4760 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004761 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004762 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004763}
4764
4765/// \brief Checks whether the given template argument is a pointer to
4766/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004767static bool CheckTemplateArgumentPointerToMember(Sema &S,
4768 NonTypeTemplateParmDecl *Param,
4769 QualType ParamType,
4770 Expr *&ResultArg,
4771 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004772 bool Invalid = false;
4773
Douglas Gregor20fdef32012-04-10 17:08:25 +00004774 // Check for a null pointer value.
4775 Expr *Arg = ResultArg;
4776 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4777 case NPV_Error:
4778 return true;
4779 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004780 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004781 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4782 /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004783 return false;
4784 case NPV_NotNullPointer:
4785 break;
4786 }
4787
4788 bool ObjCLifetimeConversion;
4789 if (S.IsQualificationConversion(Arg->getType(),
4790 ParamType.getNonReferenceType(),
4791 false, ObjCLifetimeConversion)) {
4792 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004793 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004794 ResultArg = Arg;
4795 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4796 ParamType.getNonReferenceType())) {
4797 // We can't perform this conversion.
4798 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4799 << Arg->getType() << ParamType << Arg->getSourceRange();
4800 S.Diag(Param->getLocation(), diag::note_template_param_here);
4801 return true;
4802 }
4803
Douglas Gregorccb07762009-02-11 19:52:55 +00004804 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004805 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004806 Arg = Cast->getSubExpr();
4807
4808 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004809 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004810 // A template-argument for a non-type, non-template
4811 // template-parameter shall be one of: [...]
4812 //
4813 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004814 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004815
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004816 // In C++98/03 mode, give an extension warning on any extra parentheses.
4817 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4818 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004819 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004820 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004821 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004822 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004823 diag::warn_cxx98_compat_template_arg_extra_parens :
4824 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004825 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004826 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004827 }
4828
4829 Arg = Parens->getSubExpr();
4830 }
4831
John McCall7c454bb2011-07-15 05:09:51 +00004832 while (SubstNonTypeTemplateParmExpr *subst =
4833 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4834 Arg = subst->getReplacement()->IgnoreImpCasts();
4835
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004836 // A pointer-to-member constant written &Class::member.
4837 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004838 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004839 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4840 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004841 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004844 // A constant of pointer-to-member type.
4845 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4846 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4847 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004848 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004849 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004850 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004851 } else {
4852 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004853 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004854 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004855 return Invalid;
4856 }
4857 }
4858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859
Craig Topperc3ec1492014-05-26 06:22:03 +00004860 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004862
Douglas Gregorccb07762009-02-11 19:52:55 +00004863 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004864 return S.Diag(Arg->getLocStart(),
4865 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004866 << Arg->getSourceRange();
4867
David Majnemer3ac84e62013-10-22 21:56:38 +00004868 if (isa<FieldDecl>(DRE->getDecl()) ||
4869 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4870 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004871 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004872 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004873 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4874 "Only non-static member pointers can make it here");
4875
4876 // Okay: this is the address of a non-static member, and therefore
4877 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004878 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004879 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004880 } else {
4881 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004882 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004883 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004884 return Invalid;
4885 }
4886
4887 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004888 S.Diag(Arg->getLocStart(),
4889 diag::err_template_arg_not_pointer_to_member_form)
4890 << Arg->getSourceRange();
4891 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004892 return true;
4893}
4894
Douglas Gregord32e0282009-02-09 23:23:08 +00004895/// \brief Check a template argument against its corresponding
4896/// non-type template parameter.
4897///
Douglas Gregor463421d2009-03-03 04:44:36 +00004898/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004899/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004900/// returns the converted template argument. \p ParamType is the
4901/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004902ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004903 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004904 TemplateArgument &Converted,
4905 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004906 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004907
Douglas Gregor86560402009-02-10 23:36:10 +00004908 // If either the parameter has a dependent type or the argument is
4909 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004910 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004911 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004912 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004913 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004914 }
Douglas Gregor86560402009-02-10 23:36:10 +00004915
Richard Smithd663fdd2014-12-17 20:42:37 +00004916 // We should have already dropped all cv-qualifiers by now.
4917 assert(!ParamType.hasQualifiers() &&
4918 "non-type template parameter type cannot be qualified");
4919
4920 if (CTAK == CTAK_Deduced &&
4921 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4922 // C++ [temp.deduct.type]p17:
4923 // If, in the declaration of a function template with a non-type
4924 // template-parameter, the non-type template-parameter is used
4925 // in an expression in the function parameter-list and, if the
4926 // corresponding template-argument is deduced, the
4927 // template-argument type shall match the type of the
4928 // template-parameter exactly, except that a template-argument
4929 // deduced from an array bound may be of any integral type.
4930 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4931 << Arg->getType().getUnqualifiedType()
4932 << ParamType.getUnqualifiedType();
4933 Diag(Param->getLocation(), diag::note_template_param_here);
4934 return ExprError();
4935 }
4936
Richard Smith410cc892014-11-26 03:26:53 +00004937 if (getLangOpts().CPlusPlus1z) {
4938 // FIXME: We can do some limited checking for a value-dependent but not
4939 // type-dependent argument.
4940 if (Arg->isValueDependent()) {
4941 Converted = TemplateArgument(Arg);
4942 return Arg;
4943 }
4944
4945 // C++1z [temp.arg.nontype]p1:
4946 // A template-argument for a non-type template parameter shall be
4947 // a converted constant expression of the type of the template-parameter.
4948 APValue Value;
4949 ExprResult ArgResult = CheckConvertedConstantExpression(
4950 Arg, ParamType, Value, CCEK_TemplateArg);
4951 if (ArgResult.isInvalid())
4952 return ExprError();
4953
Richard Smithd663fdd2014-12-17 20:42:37 +00004954 QualType CanonParamType = Context.getCanonicalType(ParamType);
4955
Richard Smith410cc892014-11-26 03:26:53 +00004956 // Convert the APValue to a TemplateArgument.
4957 switch (Value.getKind()) {
4958 case APValue::Uninitialized:
4959 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004960 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004961 break;
4962 case APValue::Int:
4963 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004964 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004965 break;
4966 case APValue::MemberPointer: {
4967 assert(ParamType->isMemberPointerType());
4968
4969 // FIXME: We need TemplateArgument representation and mangling for these.
4970 if (!Value.getMemberPointerPath().empty()) {
4971 Diag(Arg->getLocStart(),
4972 diag::err_template_arg_member_ptr_base_derived_not_supported)
4973 << Value.getMemberPointerDecl() << ParamType
4974 << Arg->getSourceRange();
4975 return ExprError();
4976 }
4977
4978 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004979 Converted = VD ? TemplateArgument(VD, CanonParamType)
4980 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004981 break;
4982 }
4983 case APValue::LValue: {
4984 // For a non-type template-parameter of pointer or reference type,
4985 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004986 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4987 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004988 // -- a temporary object
4989 // -- a string literal
4990 // -- the result of a typeid expression, or
4991 // -- a predefind __func__ variable
4992 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4993 if (isa<CXXUuidofExpr>(E)) {
4994 Converted = TemplateArgument(const_cast<Expr*>(E));
4995 break;
4996 }
4997 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4998 << Arg->getSourceRange();
4999 return ExprError();
5000 }
5001 auto *VD = const_cast<ValueDecl *>(
5002 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5003 // -- a subobject
5004 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5005 VD && VD->getType()->isArrayType() &&
5006 Value.getLValuePath()[0].ArrayIndex == 0 &&
5007 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5008 // Per defect report (no number yet):
5009 // ... other than a pointer to the first element of a complete array
5010 // object.
5011 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5012 Value.isLValueOnePastTheEnd()) {
5013 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5014 << Value.getAsString(Context, ParamType);
5015 return ExprError();
5016 }
Richard Smithd663fdd2014-12-17 20:42:37 +00005017 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00005018 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00005019 assert((!VD || !ParamType->isNullPtrType()) &&
5020 "non-null value of type nullptr_t?");
5021 Converted = VD ? TemplateArgument(VD, CanonParamType)
5022 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00005023 break;
5024 }
5025 case APValue::AddrLabelDiff:
5026 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5027 case APValue::Float:
5028 case APValue::ComplexInt:
5029 case APValue::ComplexFloat:
5030 case APValue::Vector:
5031 case APValue::Array:
5032 case APValue::Struct:
5033 case APValue::Union:
5034 llvm_unreachable("invalid kind for template argument");
5035 }
5036
5037 return ArgResult.get();
5038 }
5039
Douglas Gregor86560402009-02-10 23:36:10 +00005040 // C++ [temp.arg.nontype]p5:
5041 // The following conversions are performed on each expression used
5042 // as a non-type template-argument. If a non-type
5043 // template-argument cannot be converted to the type of the
5044 // corresponding template-parameter then the program is
5045 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00005046 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005047 // C++11:
5048 // -- for a non-type template-parameter of integral or
5049 // enumeration type, conversions permitted in a converted
5050 // constant expression are applied.
5051 //
5052 // C++98:
5053 // -- for a non-type template-parameter of integral or
5054 // enumeration type, integral promotions (4.5) and integral
5055 // conversions (4.7) are applied.
5056
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005057 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00005058 // We can't check arbitrary value-dependent arguments.
5059 // FIXME: If there's no viable conversion to the template parameter type,
5060 // we should be able to diagnose that prior to instantiation.
5061 if (Arg->isValueDependent()) {
5062 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005063 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00005064 }
5065
5066 // C++ [temp.arg.nontype]p1:
5067 // A template-argument for a non-type, non-template template-parameter
5068 // shall be one of:
5069 //
5070 // -- for a non-type template-parameter of integral or enumeration
5071 // type, a converted constant expression of the type of the
5072 // template-parameter; or
5073 llvm::APSInt Value;
5074 ExprResult ArgResult =
5075 CheckConvertedConstantExpression(Arg, ParamType, Value,
5076 CCEK_TemplateArg);
5077 if (ArgResult.isInvalid())
5078 return ExprError();
5079
5080 // Widen the argument value to sizeof(parameter type). This is almost
5081 // always a no-op, except when the parameter type is bool. In
5082 // that case, this may extend the argument from 1 bit to 8 bits.
5083 QualType IntegerType = ParamType;
5084 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5085 IntegerType = Enum->getDecl()->getIntegerType();
5086 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5087
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005088 Converted = TemplateArgument(Context, Value,
5089 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005090 return ArgResult;
5091 }
5092
Richard Smith08b12f12011-10-27 22:11:44 +00005093 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5094 if (ArgResult.isInvalid())
5095 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005096 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005097
5098 QualType ArgType = Arg->getType();
5099
Douglas Gregor86560402009-02-10 23:36:10 +00005100 // C++ [temp.arg.nontype]p1:
5101 // A template-argument for a non-type, non-template
5102 // template-parameter shall be one of:
5103 //
5104 // -- an integral constant-expression of integral or enumeration
5105 // type; or
5106 // -- the name of a non-type template-parameter; or
5107 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005108 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005109 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005110 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005111 diag::err_template_arg_not_integral_or_enumeral)
5112 << ArgType << Arg->getSourceRange();
5113 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005114 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005115 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005116 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5117 QualType T;
5118
5119 public:
5120 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005121
5122 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5123 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005124 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5125 }
5126 } Diagnoser(ArgType);
5127
5128 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005129 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005130 if (!Arg)
5131 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005132 }
5133
Richard Smithd663fdd2014-12-17 20:42:37 +00005134 // From here on out, all we care about is the unqualified form
5135 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005136 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005137
5138 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005139 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005140 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005141 } else if (ParamType->isBooleanType()) {
5142 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005143 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005144 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5145 !ParamType->isEnumeralType()) {
5146 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005147 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005148 } else {
5149 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005150 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005151 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005152 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005153 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005154 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005155 }
5156
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005157 // Add the value of this argument to the list of converted
5158 // arguments. We use the bitwidth and signedness of the template
5159 // parameter.
5160 if (Arg->isValueDependent()) {
5161 // The argument is value-dependent. Create a new
5162 // TemplateArgument with the converted expression.
5163 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005164 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005165 }
5166
Douglas Gregor52aba872009-03-14 00:20:21 +00005167 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005168 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005169 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005170
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005171 if (ParamType->isBooleanType()) {
5172 // Value must be zero or one.
5173 Value = Value != 0;
5174 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5175 if (Value.getBitWidth() != AllowedBits)
5176 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005177 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005178 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005179 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005180
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005181 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005182 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005183 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005184 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005185 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005186 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005187
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005188 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005189 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005190 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005191 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005192 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5193 << Arg->getSourceRange();
5194 Diag(Param->getLocation(), diag::note_template_param_here);
5195 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005196
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005197 // Complain if we overflowed the template parameter's type.
5198 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005199 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005200 RequiredBits = OldValue.getActiveBits();
5201 else if (OldValue.isUnsigned())
5202 RequiredBits = OldValue.getActiveBits() + 1;
5203 else
5204 RequiredBits = OldValue.getMinSignedBits();
5205 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005206 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005207 diag::warn_template_arg_too_large)
5208 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5209 << Arg->getSourceRange();
5210 Diag(Param->getLocation(), diag::note_template_param_here);
5211 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005212 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005213
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005214 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005215 ParamType->isEnumeralType()
5216 ? Context.getCanonicalType(ParamType)
5217 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005218 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005219 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005220
Richard Smith08b12f12011-10-27 22:11:44 +00005221 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005222 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5223
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005224 // Handle pointer-to-function, reference-to-function, and
5225 // pointer-to-member-function all in (roughly) the same way.
5226 if (// -- For a non-type template-parameter of type pointer to
5227 // function, only the function-to-pointer conversion (4.3) is
5228 // applied. If the template-argument represents a set of
5229 // overloaded functions (or a pointer to such), the matching
5230 // function is selected from the set (13.4).
5231 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005232 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005233 // -- For a non-type template-parameter of type reference to
5234 // function, no conversions apply. If the template-argument
5235 // represents a set of overloaded functions, the matching
5236 // function is selected from the set (13.4).
5237 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005238 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005239 // -- For a non-type template-parameter of type pointer to
5240 // member function, no conversions apply. If the
5241 // template-argument represents a set of overloaded member
5242 // functions, the matching member function is selected from
5243 // the set (13.4).
5244 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005245 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005246 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005247
Douglas Gregor064fdb22010-04-14 23:11:21 +00005248 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005249 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005250 true,
5251 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005252 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005253 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005254
5255 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5256 ArgType = Arg->getType();
5257 } else
John Wiegley01296292011-04-08 18:41:53 +00005258 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005260
John Wiegley01296292011-04-08 18:41:53 +00005261 if (!ParamType->isMemberPointerType()) {
5262 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5263 ParamType,
5264 Arg, Converted))
5265 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005266 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005267 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005268
Douglas Gregor20fdef32012-04-10 17:08:25 +00005269 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5270 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005271 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005272 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005273 }
5274
Chris Lattner696197c2009-02-20 21:37:53 +00005275 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005276 // -- for a non-type template-parameter of type pointer to
5277 // object, qualification conversions (4.4) and the
5278 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005279 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005280 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005281 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005282
John Wiegley01296292011-04-08 18:41:53 +00005283 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5284 ParamType,
5285 Arg, Converted))
5286 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005287 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005288 }
Mike Stump11289f42009-09-09 15:08:12 +00005289
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005290 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005291 // -- For a non-type template-parameter of type reference to
5292 // object, no conversions apply. The type referred to by the
5293 // reference may be more cv-qualified than the (otherwise
5294 // identical) type of the template-argument. The
5295 // template-parameter is bound directly to the
5296 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005297 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005298 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005299
Douglas Gregor064fdb22010-04-14 23:11:21 +00005300 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005301 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5302 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005303 true,
5304 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005305 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005306 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005307
5308 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5309 ArgType = Arg->getType();
5310 } else
John Wiegley01296292011-04-08 18:41:53 +00005311 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005313
John Wiegley01296292011-04-08 18:41:53 +00005314 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5315 ParamType,
5316 Arg, Converted))
5317 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005318 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005319 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005320
Douglas Gregor20fdef32012-04-10 17:08:25 +00005321 // Deal with parameters of type std::nullptr_t.
5322 if (ParamType->isNullPtrType()) {
5323 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5324 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005325 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005326 }
5327
5328 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5329 case NPV_NotNullPointer:
5330 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5331 << Arg->getType() << ParamType;
5332 Diag(Param->getLocation(), diag::note_template_param_here);
5333 return ExprError();
5334
5335 case NPV_Error:
5336 return ExprError();
5337
5338 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005339 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005340 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5341 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005342 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005343 }
5344 }
5345
Douglas Gregor0e558532009-02-11 16:16:59 +00005346 // -- For a non-type template-parameter of type pointer to data
5347 // member, qualification conversions (4.4) are applied.
5348 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5349
Douglas Gregor20fdef32012-04-10 17:08:25 +00005350 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5351 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005352 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005353 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005354}
5355
5356/// \brief Check a template argument against its corresponding
5357/// template template parameter.
5358///
5359/// This routine implements the semantics of C++ [temp.arg.template].
5360/// It returns true if an error occurred, and false otherwise.
5361bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005362 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005363 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005364 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005365 TemplateDecl *Template = Name.getAsTemplateDecl();
5366 if (!Template) {
5367 // Any dependent template name is fine.
5368 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5369 return false;
5370 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005371
Richard Smith3f1b5d02011-05-05 21:57:07 +00005372 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005373 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005374 // the name of a class template or an alias template, expressed as an
5375 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005376 // primary class templates are considered when matching the
5377 // template template argument with the corresponding parameter;
5378 // partial specializations are not considered even if their
5379 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005380 //
5381 // Note that we also allow template template parameters here, which
5382 // will happen when we are dealing with, e.g., class template
5383 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005384 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005385 !isa<TemplateTemplateParmDecl>(Template) &&
5386 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005387 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005388 "Only function templates are possible here");
Faisal Valib8b04f82016-03-26 20:46:45 +00005389 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005390 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005391 << Template;
5392 }
5393
Richard Smith1fde8ec2012-09-07 02:06:42 +00005394 TemplateParameterList *Params = Param->getTemplateParameters();
5395 if (Param->isExpandedParameterPack())
5396 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5397
Douglas Gregor85e0f662009-02-10 00:24:35 +00005398 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005399 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005400 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005401 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005402 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005403}
5404
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005405/// \brief Given a non-type template argument that refers to a
5406/// declaration and the type of its corresponding non-type template
5407/// parameter, produce an expression that properly refers to that
5408/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005409ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005410Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5411 QualType ParamType,
5412 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005413 // C++ [temp.param]p8:
5414 //
5415 // A non-type template-parameter of type "array of T" or
5416 // "function returning T" is adjusted to be of type "pointer to
5417 // T" or "pointer to function returning T", respectively.
5418 if (ParamType->isArrayType())
5419 ParamType = Context.getArrayDecayedType(ParamType);
5420 else if (ParamType->isFunctionType())
5421 ParamType = Context.getPointerType(ParamType);
5422
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005423 // For a NULL non-type template argument, return nullptr casted to the
5424 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005425 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005426 return ImpCastExprToType(
5427 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5428 ParamType,
5429 ParamType->getAs<MemberPointerType>()
5430 ? CK_NullToMemberPointer
5431 : CK_NullToPointer);
5432 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005433 assert(Arg.getKind() == TemplateArgument::Declaration &&
5434 "Only declaration template arguments permitted here");
5435
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005436 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5437
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005439 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5440 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005441 // If the value is a class member, we might have a pointer-to-member.
5442 // Determine whether the non-type template template parameter is of
5443 // pointer-to-member type. If so, we need to build an appropriate
5444 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5445 // would refer to the member itself.
5446 if (ParamType->isMemberPointerType()) {
5447 QualType ClassType
5448 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5449 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005450 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005451 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005452 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005453 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005454
5455 // The actual value-ness of this is unimportant, but for
5456 // internal consistency's sake, references to instance methods
5457 // are r-values.
5458 ExprValueKind VK = VK_LValue;
5459 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5460 VK = VK_RValue;
5461
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005463 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005464 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005465 Loc,
5466 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005467 if (RefExpr.isInvalid())
5468 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469
John McCalle3027922010-08-25 11:45:40 +00005470 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005471
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005472 // We might need to perform a trailing qualification conversion, since
5473 // the element type on the parameter could be more qualified than the
5474 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005475 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005476 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005477 ParamType.getUnqualifiedType(), false,
5478 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005479 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005481 assert(!RefExpr.isInvalid() &&
5482 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005483 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005484 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005485 }
5486 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005487
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005488 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005489
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005490 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005491 // When the non-type template parameter is a pointer, take the
5492 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005493 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005494 if (RefExpr.isInvalid())
5495 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005496
5497 if (T->isFunctionType() || T->isArrayType()) {
5498 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005499 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005500 if (RefExpr.isInvalid())
5501 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005502
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005503 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
Douglas Gregorb242683d2010-04-01 18:32:35 +00005506 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005507 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005508 }
5509
John McCall7decc9e2010-11-18 06:31:45 +00005510 ExprValueKind VK = VK_RValue;
5511
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005512 // If the non-type template parameter has reference type, qualify the
5513 // resulting declaration reference with the extra qualifiers on the
5514 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005515 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5516 VK = VK_LValue;
5517 T = Context.getQualifiedType(T,
5518 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005519 } else if (isa<FunctionDecl>(VD)) {
5520 // References to functions are always lvalues.
5521 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005523
John McCall7decc9e2010-11-18 06:31:45 +00005524 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005525}
5526
5527/// \brief Construct a new expression that refers to the given
5528/// integral template argument with the given source-location
5529/// information.
5530///
5531/// This routine takes care of the mapping from an integral template
5532/// argument (which may have any integral type) to the appropriate
5533/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005535Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5536 SourceLocation Loc) {
5537 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005538 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005539 QualType OrigT = Arg.getIntegralType();
5540
5541 // If this is an enum type that we're instantiating, we need to use an integer
5542 // type the same size as the enumerator. We don't want to build an
5543 // IntegerLiteral with enum type. The integer type of an enum type can be of
5544 // any integral type with C++11 enum classes, make sure we create the right
5545 // type of literal for it.
5546 QualType T = OrigT;
5547 if (const EnumType *ET = OrigT->getAs<EnumType>())
5548 T = ET->getDecl()->getIntegerType();
5549
5550 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005551 if (T->isAnyCharacterType()) {
Aaron Ballman9a17c852016-01-07 20:59:26 +00005552 // This does not need to handle u8 character literals because those are
5553 // of type char, and so can also be covered by an ASCII character literal.
Douglas Gregorfb65e592011-07-27 05:40:30 +00005554 CharacterLiteral::CharacterKind Kind;
5555 if (T->isWideCharType())
5556 Kind = CharacterLiteral::Wide;
5557 else if (T->isChar16Type())
5558 Kind = CharacterLiteral::UTF16;
5559 else if (T->isChar32Type())
5560 Kind = CharacterLiteral::UTF32;
5561 else
5562 Kind = CharacterLiteral::Ascii;
5563
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005564 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5565 Kind, T, Loc);
5566 } else if (T->isBooleanType()) {
5567 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5568 T, Loc);
5569 } else if (T->isNullPtrType()) {
5570 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5571 } else {
5572 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005573 }
5574
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005575 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005576 // FIXME: This is a hack. We need a better way to handle substituted
5577 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005578 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5579 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005580 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005581 Loc, Loc);
5582 }
5583
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005584 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005585}
5586
Douglas Gregor641040a2011-01-12 23:45:44 +00005587/// \brief Match two template parameters within template parameter lists.
5588static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5589 bool Complain,
5590 Sema::TemplateParameterListEqualKind Kind,
5591 SourceLocation TemplateArgLoc) {
5592 // Check the actual kind (type, non-type, template).
5593 if (Old->getKind() != New->getKind()) {
5594 if (Complain) {
5595 unsigned NextDiag = diag::err_template_param_different_kind;
5596 if (TemplateArgLoc.isValid()) {
5597 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5598 NextDiag = diag::note_template_param_different_kind;
5599 }
5600 S.Diag(New->getLocation(), NextDiag)
5601 << (Kind != Sema::TPL_TemplateMatch);
5602 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5603 << (Kind != Sema::TPL_TemplateMatch);
5604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005605
Douglas Gregor641040a2011-01-12 23:45:44 +00005606 return false;
5607 }
5608
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609 // Check that both are parameter packs are neither are parameter packs.
5610 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005611 // template template parameter, the template template parameter can have
5612 // a parameter pack where the template template argument does not.
5613 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5614 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5615 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005616 if (Complain) {
5617 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5618 if (TemplateArgLoc.isValid()) {
5619 S.Diag(TemplateArgLoc,
5620 diag::err_template_arg_template_params_mismatch);
5621 NextDiag = diag::note_template_parameter_pack_non_pack;
5622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623
Douglas Gregor641040a2011-01-12 23:45:44 +00005624 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5625 : isa<NonTypeTemplateParmDecl>(New)? 1
5626 : 2;
5627 S.Diag(New->getLocation(), NextDiag)
5628 << ParamKind << New->isParameterPack();
5629 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5630 << ParamKind << Old->isParameterPack();
5631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005632
Douglas Gregor641040a2011-01-12 23:45:44 +00005633 return false;
5634 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005635
Douglas Gregor641040a2011-01-12 23:45:44 +00005636 // For non-type template parameters, check the type of the parameter.
5637 if (NonTypeTemplateParmDecl *OldNTTP
5638 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5639 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005640
Douglas Gregor641040a2011-01-12 23:45:44 +00005641 // If we are matching a template template argument to a template
5642 // template parameter and one of the non-type template parameter types
5643 // is dependent, then we must wait until template instantiation time
5644 // to actually compare the arguments.
5645 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5646 (OldNTTP->getType()->isDependentType() ||
5647 NewNTTP->getType()->isDependentType()))
5648 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649
Douglas Gregor641040a2011-01-12 23:45:44 +00005650 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5651 if (Complain) {
5652 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5653 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005654 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005655 diag::err_template_arg_template_params_mismatch);
5656 NextDiag = diag::note_template_nontype_parm_different_type;
5657 }
5658 S.Diag(NewNTTP->getLocation(), NextDiag)
5659 << NewNTTP->getType()
5660 << (Kind != Sema::TPL_TemplateMatch);
5661 S.Diag(OldNTTP->getLocation(),
5662 diag::note_template_nontype_parm_prev_declaration)
5663 << OldNTTP->getType();
5664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005665
Douglas Gregor641040a2011-01-12 23:45:44 +00005666 return false;
5667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005668
Douglas Gregor641040a2011-01-12 23:45:44 +00005669 return true;
5670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671
Douglas Gregor641040a2011-01-12 23:45:44 +00005672 // For template template parameters, check the template parameter types.
5673 // The template parameter lists of template template
5674 // parameters must agree.
5675 if (TemplateTemplateParmDecl *OldTTP
5676 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005677 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005678 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5679 OldTTP->getTemplateParameters(),
5680 Complain,
5681 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005682 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005683 : Kind),
5684 TemplateArgLoc);
5685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686
Douglas Gregor641040a2011-01-12 23:45:44 +00005687 return true;
5688}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005689
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005690/// \brief Diagnose a known arity mismatch when comparing template argument
5691/// lists.
5692static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005693void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005694 TemplateParameterList *New,
5695 TemplateParameterList *Old,
5696 Sema::TemplateParameterListEqualKind Kind,
5697 SourceLocation TemplateArgLoc) {
5698 unsigned NextDiag = diag::err_template_param_list_different_arity;
5699 if (TemplateArgLoc.isValid()) {
5700 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5701 NextDiag = diag::note_template_param_list_different_arity;
5702 }
5703 S.Diag(New->getTemplateLoc(), NextDiag)
5704 << (New->size() > Old->size())
5705 << (Kind != Sema::TPL_TemplateMatch)
5706 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5707 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5708 << (Kind != Sema::TPL_TemplateMatch)
5709 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5710}
5711
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005712/// \brief Determine whether the given template parameter lists are
5713/// equivalent.
5714///
Mike Stump11289f42009-09-09 15:08:12 +00005715/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005716/// source code as part of a new template declaration.
5717///
5718/// \param Old The old template parameter list, typically found via
5719/// name lookup of the template declared with this template parameter
5720/// list.
5721///
5722/// \param Complain If true, this routine will produce a diagnostic if
5723/// the template parameter lists are not equivalent.
5724///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005725/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005726///
5727/// \param TemplateArgLoc If this source location is valid, then we
5728/// are actually checking the template parameter list of a template
5729/// argument (New) against the template parameter list of its
5730/// corresponding template template parameter (Old). We produce
5731/// slightly different diagnostics in this scenario.
5732///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005733/// \returns True if the template parameter lists are equal, false
5734/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005735bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005736Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5737 TemplateParameterList *Old,
5738 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005739 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005740 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005741 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5742 if (Complain)
5743 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5744 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005745
5746 return false;
5747 }
5748
Douglas Gregor641040a2011-01-12 23:45:44 +00005749 // C++0x [temp.arg.template]p3:
5750 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005751 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005752 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005753 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005754 // template-parameter-list of P. [...]
5755 TemplateParameterList::iterator NewParm = New->begin();
5756 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005757 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005758 OldParmEnd = Old->end();
5759 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005760 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5761 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005762 if (NewParm == NewParmEnd) {
5763 if (Complain)
5764 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5765 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005766
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005767 return false;
5768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005769
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005770 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5771 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772 return false;
5773
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005774 ++NewParm;
5775 continue;
5776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005777
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005778 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005779 // [...] When P's template- parameter-list contains a template parameter
5780 // pack (14.5.3), the template parameter pack will match zero or more
5781 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005782 // template-parameter-list of A with the same type and form as the
5783 // template parameter pack in P (ignoring whether those template
5784 // parameters are template parameter packs).
5785 for (; NewParm != NewParmEnd; ++NewParm) {
5786 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5787 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005788 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005789 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005791
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005792 // Make sure we exhausted all of the arguments.
5793 if (NewParm != NewParmEnd) {
5794 if (Complain)
5795 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5796 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005797
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005798 return false;
5799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005800
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005801 return true;
5802}
5803
5804/// \brief Check whether a template can be declared within this scope.
5805///
5806/// If the template declaration is valid in this scope, returns
5807/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005808bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005809Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005810 if (!S)
5811 return false;
5812
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005813 // Find the nearest enclosing declaration scope.
5814 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5815 (S->getFlags() & Scope::TemplateParamScope) != 0)
5816 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005817
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005818 // C++ [temp]p4:
5819 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005820 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005821 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005822 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005823 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005824
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005825 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005826 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005827
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005828 // C++ [temp]p2:
5829 // A template-declaration can appear only as a namespace scope or
5830 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005831 if (Ctx) {
5832 if (Ctx->isFileContext())
5833 return false;
5834 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5835 // C++ [temp.mem]p2:
5836 // A local class shall not have member templates.
5837 if (RD->isLocalClass())
5838 return Diag(TemplateParams->getTemplateLoc(),
5839 diag::err_template_inside_local_class)
5840 << TemplateParams->getSourceRange();
5841 else
5842 return false;
5843 }
5844 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005845
Mike Stump11289f42009-09-09 15:08:12 +00005846 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005847 diag::err_template_outside_namespace_or_class_scope)
5848 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005849}
Douglas Gregor67a65642009-02-17 23:15:12 +00005850
Douglas Gregor54888652009-10-07 00:13:32 +00005851/// \brief Determine what kind of template specialization the given declaration
5852/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005853static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005854 if (!D)
5855 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005856
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005857 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5858 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005859 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5860 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005861 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5862 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005863
Douglas Gregor54888652009-10-07 00:13:32 +00005864 return TSK_Undeclared;
5865}
5866
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005867/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005868/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005869///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005870/// This routine determines whether a template specialization can be declared
5871/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005872///
5873/// \param S the semantic analysis object for which this check is being
5874/// performed.
5875///
5876/// \param Specialized the entity being specialized or instantiated, which
5877/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005878/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005879/// member class).
5880///
5881/// \param PrevDecl the previous declaration of this entity, if any.
5882///
5883/// \param Loc the location of the explicit specialization or instantiation of
5884/// this entity.
5885///
5886/// \param IsPartialSpecialization whether this is a partial specialization of
5887/// a class template.
5888///
Douglas Gregor54888652009-10-07 00:13:32 +00005889/// \returns true if there was an error that we cannot recover from, false
5890/// otherwise.
5891static bool CheckTemplateSpecializationScope(Sema &S,
5892 NamedDecl *Specialized,
5893 NamedDecl *PrevDecl,
5894 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005895 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005896 // Keep these "kind" numbers in sync with the %select statements in the
5897 // various diagnostics emitted by this routine.
5898 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005899 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005900 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005901 else if (isa<VarTemplateDecl>(Specialized))
5902 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005903 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005904 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005905 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005906 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005907 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005908 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005909 else if (isa<RecordDecl>(Specialized))
5910 EntityKind = 7;
5911 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5912 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005913 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005914 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005915 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005916 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005917 return true;
5918 }
5919
Douglas Gregorf47b9112009-02-25 22:02:03 +00005920 // C++ [temp.expl.spec]p2:
5921 // An explicit specialization shall be declared in the namespace
5922 // of which the template is a member, or, for member templates, in
5923 // the namespace of which the enclosing class or enclosing class
5924 // template is a member. An explicit specialization of a member
5925 // function, member class or static data member of a class
5926 // template shall be declared in the namespace of which the class
5927 // template is a member. Such a declaration may also be a
5928 // definition. If the declaration is not a definition, the
5929 // specialization may be defined later in the name- space in which
5930 // the explicit specialization was declared, or in a namespace
5931 // that encloses the one in which the explicit specialization was
5932 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005933 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005934 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005935 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005936 return true;
5937 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005938
Douglas Gregor40fb7442009-10-07 17:30:37 +00005939 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005940 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005941 // Do not warn for class scope explicit specialization during
5942 // instantiation, warning was already emitted during pattern
5943 // semantic analysis.
5944 if (!S.ActiveTemplateInstantiations.size())
5945 S.Diag(Loc, diag::ext_function_specialization_in_class)
5946 << Specialized;
5947 } else {
5948 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5949 << Specialized;
5950 return true;
5951 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005953
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005954 if (S.CurContext->isRecord() &&
5955 !S.CurContext->Equals(Specialized->getDeclContext())) {
5956 // Make sure that we're specializing in the right record context.
5957 // Otherwise, things can go horribly wrong.
5958 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5959 << Specialized;
5960 return true;
5961 }
5962
Douglas Gregore4b05162009-10-07 17:21:34 +00005963 // C++ [temp.class.spec]p6:
5964 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005965 // in any namespace scope in which its definition may be defined (14.5.1
5966 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005967 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005968 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005969 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005970
5971 // Make sure that this redeclaration (or definition) occurs in an enclosing
5972 // namespace.
5973 // Note that HandleDeclarator() performs this check for explicit
5974 // specializations of function templates, static data members, and member
5975 // functions, so we skip the check here for those kinds of entities.
5976 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5977 // Should we refactor that check, so that it occurs later?
5978 if (!DC->Encloses(SpecializedContext) &&
5979 !(isa<FunctionTemplateDecl>(Specialized) ||
5980 isa<FunctionDecl>(Specialized) ||
5981 isa<VarTemplateDecl>(Specialized) ||
5982 isa<VarDecl>(Specialized))) {
5983 if (isa<TranslationUnitDecl>(SpecializedContext))
5984 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5985 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005986 else if (isa<NamespaceDecl>(SpecializedContext)) {
5987 int Diag = diag::err_template_spec_redecl_out_of_scope;
5988 if (S.getLangOpts().MicrosoftExt)
5989 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5990 S.Diag(Loc, Diag) << EntityKind << Specialized
5991 << cast<NamedDecl>(SpecializedContext);
5992 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005993 llvm_unreachable("unexpected namespace context for specialization");
5994
5995 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5996 } else if ((!PrevDecl ||
5997 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5998 getTemplateSpecializationKind(PrevDecl) ==
5999 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00006000 // C++ [temp.exp.spec]p2:
6001 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006002 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00006003 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006004 // An explicit specialization of a member function, member class or
6005 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00006006 // namespace of which the class template is a member.
6007 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00006008 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006009 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00006010 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00006011 // C++11 [temp.explicit]p3:
6012 // An explicit instantiation shall appear in an enclosing namespace of its
6013 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006014 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006015 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00006016 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006017 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00006018 "DC encloses TU but isn't in enclosing namespace set");
6019 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00006020 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00006021 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6022 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006023 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006024 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006025 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00006026 Diag = diag::ext_template_spec_decl_out_of_scope;
6027 else
6028 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6029 S.Diag(Loc, Diag)
6030 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006032
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006033 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00006034 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006036
Douglas Gregorf47b9112009-02-25 22:02:03 +00006037 return false;
6038}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006039
Richard Smith6056d5e2014-02-09 00:54:43 +00006040static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6041 if (!E->isInstantiationDependent())
6042 return SourceLocation();
6043 DependencyChecker Checker(Depth);
6044 Checker.TraverseStmt(E);
6045 if (Checker.Match && Checker.MatchLoc.isInvalid())
6046 return E->getSourceRange();
6047 return Checker.MatchLoc;
6048}
6049
6050static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6051 if (!TL.getType()->isDependentType())
6052 return SourceLocation();
6053 DependencyChecker Checker(Depth);
6054 Checker.TraverseTypeLoc(TL);
6055 if (Checker.Match && Checker.MatchLoc.isInvalid())
6056 return TL.getSourceRange();
6057 return Checker.MatchLoc;
6058}
6059
Larisse Voufo39a1e502013-08-06 01:03:05 +00006060/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006061/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006062static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006063 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6064 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006065 for (unsigned I = 0; I != NumArgs; ++I) {
6066 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006067 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006068 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6069 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006070 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006071
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006072 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006074
Eli Friedmanb826a002012-09-26 02:36:12 +00006075 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006076 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00006077
6078 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006079
Douglas Gregor98318c22011-01-03 21:37:45 +00006080 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006081 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6082 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00006083
6084 // Strip off any implicit casts we added as part of type checking.
6085 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6086 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006087
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006088 // C++ [temp.class.spec]p8:
6089 // A non-type argument is non-specialized if it is the name of a
6090 // non-type parameter. All other non-type arguments are
6091 // specialized.
6092 //
6093 // Below, we check the two conditions that only apply to
6094 // specialized non-type arguments, so skip any non-specialized
6095 // arguments.
6096 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006097 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006098 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006099
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006100 // C++ [temp.class.spec]p9:
6101 // Within the argument list of a class template partial
6102 // specialization, the following restrictions apply:
6103 // -- A partially specialized non-type argument expression
6104 // shall not involve a template parameter of the partial
6105 // specialization except when the argument expression is a
6106 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006107 SourceRange ParamUseRange =
6108 findTemplateParameter(Param->getDepth(), ArgExpr);
6109 if (ParamUseRange.isValid()) {
6110 if (IsDefaultArgument) {
6111 S.Diag(TemplateNameLoc,
6112 diag::err_dependent_non_type_arg_in_partial_spec);
6113 S.Diag(ParamUseRange.getBegin(),
6114 diag::note_dependent_non_type_default_arg_in_partial_spec)
6115 << ParamUseRange;
6116 } else {
6117 S.Diag(ParamUseRange.getBegin(),
6118 diag::err_dependent_non_type_arg_in_partial_spec)
6119 << ParamUseRange;
6120 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006121 return true;
6122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006123
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006124 // -- The type of a template parameter corresponding to a
6125 // specialized non-type argument shall not be dependent on a
6126 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006127 //
6128 // FIXME: We need to delay this check until instantiation in some cases:
6129 //
6130 // template<template<typename> class X> struct A {
6131 // template<typename T, X<T> N> struct B;
6132 // template<typename T> struct B<T, 0>;
6133 // };
6134 // template<typename> using X = int;
6135 // A<X>::B<int, 0> b;
6136 ParamUseRange = findTemplateParameter(
6137 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6138 if (ParamUseRange.isValid()) {
6139 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6140 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6141 << Param->getType() << ParamUseRange;
6142 S.Diag(Param->getLocation(), diag::note_template_param_here)
6143 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006144 return true;
6145 }
6146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006147
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006148 return false;
6149}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006150
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006151/// \brief Check the non-type template arguments of a class template
6152/// partial specialization according to C++ [temp.class.spec]p9.
6153///
Richard Smith6056d5e2014-02-09 00:54:43 +00006154/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006155/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006156/// template.
6157/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006158/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006159/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006160///
Richard Smith6056d5e2014-02-09 00:54:43 +00006161/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006162static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006163 Sema &S, SourceLocation TemplateNameLoc,
6164 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006165 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006166 const TemplateArgument *ArgList = TemplateArgs.data();
6167
6168 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6169 NonTypeTemplateParmDecl *Param
6170 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6171 if (!Param)
6172 continue;
6173
Richard Smith6056d5e2014-02-09 00:54:43 +00006174 if (CheckNonTypeTemplatePartialSpecializationArgs(
6175 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006176 return true;
6177 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006178
6179 return false;
6180}
6181
John McCall48871652010-08-21 09:40:31 +00006182DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006183Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6184 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006185 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006186 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006187 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006188 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006189 MultiTemplateParamsArg
6190 TemplateParameterLists,
6191 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006192 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006193
Richard Smith4b55a9c2014-04-17 03:29:33 +00006194 CXXScopeSpec &SS = TemplateId.SS;
6195
Abramo Bagnara60804e12011-03-18 15:16:37 +00006196 // NOTE: KWLoc is the location of the tag keyword. This will instead
6197 // store the location of the outermost template keyword in the declaration.
6198 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006199 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6200 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6201 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6202 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006203
Douglas Gregor67a65642009-02-17 23:15:12 +00006204 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006205 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006206 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006207 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6208
6209 if (!ClassTemplate) {
6210 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006211 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006212 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6213 return true;
6214 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006215
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006216 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006217 bool isPartialSpecialization = false;
6218
Douglas Gregorf47b9112009-02-25 22:02:03 +00006219 // Check the validity of the template headers that introduce this
6220 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006221 // FIXME: We probably shouldn't complain about these headers for
6222 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006223 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006224 TemplateParameterList *TemplateParams =
6225 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006226 KWLoc, TemplateNameLoc, SS, &TemplateId,
6227 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6228 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006229 if (Invalid)
6230 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006231
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006232 if (TemplateParams && TemplateParams->size() > 0) {
6233 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006234
Douglas Gregorec9518b2010-12-21 08:14:57 +00006235 if (TUK == TUK_Friend) {
6236 Diag(KWLoc, diag::err_partial_specialization_friend)
6237 << SourceRange(LAngleLoc, RAngleLoc);
6238 return true;
6239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006240
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006241 // C++ [temp.class.spec]p10:
6242 // The template parameter list of a specialization shall not
6243 // contain default template argument values.
6244 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6245 Decl *Param = TemplateParams->getParam(I);
6246 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6247 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006248 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006249 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006250 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006251 }
6252 } else if (NonTypeTemplateParmDecl *NTTP
6253 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6254 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006255 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006256 diag::err_default_arg_in_partial_spec)
6257 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006258 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006259 }
6260 } else {
6261 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006262 if (TTP->hasDefaultArgument()) {
6263 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006264 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006265 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006266 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006267 }
6268 }
6269 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006270 } else if (TemplateParams) {
6271 if (TUK == TUK_Friend)
6272 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006273 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006274 SourceRange(TemplateParams->getTemplateLoc(),
6275 TemplateParams->getRAngleLoc()))
6276 << SourceRange(LAngleLoc, RAngleLoc);
6277 else
6278 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006279 } else {
6280 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006281 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006282
Douglas Gregor67a65642009-02-17 23:15:12 +00006283 // Check that the specialization uses the same tag kind as the
6284 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006285 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6286 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006287 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006288 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006289 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006290 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006291 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006292 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006293 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006294 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006295 diag::note_previous_use);
6296 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6297 }
6298
Douglas Gregorc40290e2009-03-09 23:48:35 +00006299 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006300 TemplateArgumentListInfo TemplateArgs =
6301 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006302
Douglas Gregor14406932011-01-03 20:35:03 +00006303 // Check for unexpanded parameter packs in any of the template arguments.
6304 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006305 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006306 UPPC_PartialSpecialization))
6307 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006308
Douglas Gregor67a65642009-02-17 23:15:12 +00006309 // Check that the template argument list is well-formed for this
6310 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006311 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006312 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6313 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006314 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006315
Douglas Gregor2373c592009-05-31 09:31:02 +00006316 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006317 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006318 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006319 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006320 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6321 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006322 return true;
6323
Douglas Gregor678d76c2011-07-01 01:22:09 +00006324 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006325 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006326 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006327 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006328 TemplateArgs.size(),
6329 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006330 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6331 << ClassTemplate->getDeclName();
6332 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006333 }
6334 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006335
Craig Topperc3ec1492014-05-26 06:22:03 +00006336 void *InsertPos = nullptr;
6337 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006338
6339 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006340 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006341 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006342 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006343 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006344
Craig Topperc3ec1492014-05-26 06:22:03 +00006345 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006346
Douglas Gregorf47b9112009-02-25 22:02:03 +00006347 // Check whether we can declare a class template specialization in
6348 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006349 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006350 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6351 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006352 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006353 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006354
Douglas Gregor15301382009-07-30 17:40:51 +00006355 // The canonical type
6356 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006357 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006358 // Build the canonical type that describes the converted template
6359 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006360 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6361 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006362 Converted.data(),
6363 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006364
6365 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006366 ClassTemplate->getInjectedClassNameSpecialization())) {
6367 // C++ [temp.class.spec]p9b3:
6368 //
6369 // -- The argument list of the specialization shall not be identical
6370 // to the implicit argument list of the primary template.
6371 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006372 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006373 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006374 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6375 ClassTemplate->getIdentifier(),
6376 TemplateNameLoc,
6377 Attr,
6378 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006379 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006380 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006381 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006382 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006383 }
Douglas Gregor15301382009-07-30 17:40:51 +00006384
Douglas Gregor2373c592009-05-31 09:31:02 +00006385 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006386 ClassTemplatePartialSpecializationDecl *PrevPartial
6387 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006388 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006389 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006390 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006391 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006392 TemplateParams,
6393 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006394 Converted.data(),
6395 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006396 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006397 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006398 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006399 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006400 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006401 Partial->setTemplateParameterListsInfo(
6402 Context, TemplateParameterLists.drop_back(1));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006403 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006404
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006405 if (!PrevPartial)
6406 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006407 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006408
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006409 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006410 // template specialization, make a note of that.
6411 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6412 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006413
Douglas Gregor91772d12009-06-13 00:26:55 +00006414 // Check that all of the template parameters of the class template
6415 // partial specialization are deducible from the template
6416 // arguments. If not, this class template partial specialization
6417 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006418 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006419 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006420 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006421 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006422
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006423 if (!DeducibleParams.all()) {
6424 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006425 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006426 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006427 << SourceRange(TemplateNameLoc, RAngleLoc);
6428 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6429 if (!DeducibleParams[I]) {
6430 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6431 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006432 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006433 diag::note_partial_spec_unused_parameter)
6434 << Param->getDeclName();
6435 else
Mike Stump11289f42009-09-09 15:08:12 +00006436 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006437 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006438 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006439 }
6440 }
6441 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006442 } else {
6443 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006444 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006445 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006446 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006447 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006448 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006449 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006450 Converted.data(),
6451 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006452 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006453 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006454 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006455 Specialization->setTemplateParameterListsInfo(Context,
Benjamin Kramer9cc210652015-08-05 09:40:49 +00006456 TemplateParameterLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006457 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006458
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006459 if (!PrevDecl)
6460 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006461
David Majnemer678f50b2015-11-18 19:49:19 +00006462 if (CurContext->isDependentContext()) {
6463 // -fms-extensions permits specialization of nested classes without
6464 // fully specializing the outer class(es).
6465 assert(getLangOpts().MicrosoftExt &&
6466 "Only possible with -fms-extensions!");
6467 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6468 CanonType = Context.getTemplateSpecializationType(
6469 CanonTemplate, Converted.data(), Converted.size());
6470 } else {
6471 CanonType = Context.getTypeDeclType(Specialization);
6472 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006473 }
6474
Douglas Gregor06db9f52009-10-12 20:18:28 +00006475 // C++ [temp.expl.spec]p6:
6476 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006478 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006479 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006480 // use occurs; no diagnostic is required.
6481 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006482 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006483 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006484 // Is there any previous explicit specialization declaration?
6485 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6486 Okay = true;
6487 break;
6488 }
6489 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006490
Douglas Gregorc854c662010-02-26 06:03:23 +00006491 if (!Okay) {
6492 SourceRange Range(TemplateNameLoc, RAngleLoc);
6493 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6494 << Context.getTypeDeclType(Specialization) << Range;
6495
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006496 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006497 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006498 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006499 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006500 return true;
6501 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006503
Douglas Gregor2208a292009-09-26 20:57:03 +00006504 // If this is not a friend, note that this is an explicit specialization.
6505 if (TUK != TUK_Friend)
6506 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006507
6508 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006509 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006510 RecordDecl *Def = Specialization->getDefinition();
6511 NamedDecl *Hidden = nullptr;
6512 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6513 SkipBody->ShouldSkip = true;
6514 makeMergedDefinitionVisible(Hidden, KWLoc);
6515 // From here on out, treat this as just a redeclaration.
6516 TUK = TUK_Declaration;
6517 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006518 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006519 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006520 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006521 Diag(Def->getLocation(), diag::note_previous_definition);
6522 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006523 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006524 }
6525 }
6526
John McCall659a3372010-12-18 03:30:47 +00006527 if (Attr)
6528 ProcessDeclAttributeList(S, Specialization, Attr);
6529
Richard Smith034b94a2012-08-17 03:20:55 +00006530 // Add alignment attributes if necessary; these attributes are checked when
6531 // the ASTContext lays out the structure.
6532 if (TUK == TUK_Definition) {
6533 AddAlignmentAttributesForRecord(Specialization);
6534 AddMsStructLayoutForRecord(Specialization);
6535 }
6536
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006537 if (ModulePrivateLoc.isValid())
6538 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6539 << (isPartialSpecialization? 1 : 0)
6540 << FixItHint::CreateRemoval(ModulePrivateLoc);
6541
Douglas Gregord56a91e2009-02-26 22:19:44 +00006542 // Build the fully-sugared type for this class template
6543 // specialization as the user wrote in the specialization
6544 // itself. This means that we'll pretty-print the type retrieved
6545 // from the specialization's declaration the way that the user
6546 // actually wrote the specialization, rather than formatting the
6547 // name based on the "canonical" representation used to store the
6548 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006549 TypeSourceInfo *WrittenTy
6550 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6551 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006552 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006553 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006554 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006555 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006556
Douglas Gregor1e249f82009-02-25 22:18:32 +00006557 // C++ [temp.expl.spec]p9:
6558 // A template explicit specialization is in the scope of the
6559 // namespace in which the template was defined.
6560 //
6561 // We actually implement this paragraph where we set the semantic
6562 // context (in the creation of the ClassTemplateSpecializationDecl),
6563 // but we also maintain the lexical context where the actual
6564 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006565 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006566
Douglas Gregor67a65642009-02-17 23:15:12 +00006567 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006568 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006569 Specialization->startDefinition();
6570
Douglas Gregor2208a292009-09-26 20:57:03 +00006571 if (TUK == TUK_Friend) {
6572 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6573 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006574 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006575 /*FIXME:*/KWLoc);
6576 Friend->setAccess(AS_public);
6577 CurContext->addDecl(Friend);
6578 } else {
6579 // Add the specialization into its lexical context, so that it can
6580 // be seen when iterating through the list of declarations in that
6581 // context. However, specializations are not found by name lookup.
6582 CurContext->addDecl(Specialization);
6583 }
John McCall48871652010-08-21 09:40:31 +00006584 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006585}
Douglas Gregor333489b2009-03-27 23:10:48 +00006586
John McCall48871652010-08-21 09:40:31 +00006587Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006588 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006589 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006590 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006591 ActOnDocumentableDecl(NewDecl);
6592 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006593}
6594
John McCall4f7ced62010-02-11 01:33:53 +00006595/// \brief Strips various properties off an implicit instantiation
6596/// that has just been explicitly specialized.
6597static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006598 D->dropAttr<DLLImportAttr>();
6599 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006600
Nico Webere4974382014-12-19 23:52:45 +00006601 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006602 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006603}
6604
Nico Webera8f80b32012-01-09 19:52:25 +00006605/// \brief Compute the diagnostic location for an explicit instantiation
6606// declaration or definition.
6607static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006608 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006609 // Explicit instantiations following a specialization have no effect and
6610 // hence no PointOfInstantiation. In that case, walk decl backwards
6611 // until a valid name loc is found.
6612 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006613 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6614 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006615 PrevDiagLoc = Prev->getLocation();
6616 }
6617 assert(PrevDiagLoc.isValid() &&
6618 "Explicit instantiation without point of instantiation?");
6619 return PrevDiagLoc;
6620}
6621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006623/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006624/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006625/// new specialization/instantiation will have any effect.
6626///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006627/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006628/// instantiation.
6629///
6630/// \param NewTSK the kind of the new explicit specialization or instantiation.
6631///
6632/// \param PrevDecl the previous declaration of the entity.
6633///
6634/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6635///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006637/// declaration was instantiated (either implicitly or explicitly).
6638///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006640/// specialization or instantiation has no effect and should be ignored.
6641///
6642/// \returns true if there was an error that should prevent the introduction of
6643/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006644bool
6645Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6646 TemplateSpecializationKind NewTSK,
6647 NamedDecl *PrevDecl,
6648 TemplateSpecializationKind PrevTSK,
6649 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006650 bool &HasNoEffect) {
6651 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006652
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006653 switch (NewTSK) {
6654 case TSK_Undeclared:
6655 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006656 assert(
6657 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6658 "previous declaration must be implicit!");
6659 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006660
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006661 case TSK_ExplicitSpecialization:
6662 switch (PrevTSK) {
6663 case TSK_Undeclared:
6664 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006665 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006666 // explicitly specialized or has merely been mentioned without any
6667 // instantiation.
6668 return false;
6669
6670 case TSK_ImplicitInstantiation:
6671 if (PrevPointOfInstantiation.isInvalid()) {
6672 // The declaration itself has not actually been instantiated, so it is
6673 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006674 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006675 return false;
6676 }
6677 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006678
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006679 case TSK_ExplicitInstantiationDeclaration:
6680 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681 assert((PrevTSK == TSK_ImplicitInstantiation ||
6682 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006683 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006684
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006685 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006686 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006687 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006688 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006689 // implicit instantiation to take place, in every translation unit in
6690 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006691 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006692 // Is there any previous explicit specialization declaration?
6693 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6694 return false;
6695 }
6696
Douglas Gregor1d957a32009-10-27 18:42:08 +00006697 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006698 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006699 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006700 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006702 return true;
6703 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006704
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006705 case TSK_ExplicitInstantiationDeclaration:
6706 switch (PrevTSK) {
6707 case TSK_ExplicitInstantiationDeclaration:
6708 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006709 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006710 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006711
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006712 case TSK_Undeclared:
6713 case TSK_ImplicitInstantiation:
6714 // We're explicitly instantiating something that may have already been
6715 // implicitly instantiated; that's fine.
6716 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006717
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006718 case TSK_ExplicitSpecialization:
6719 // C++0x [temp.explicit]p4:
6720 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006722 // specialization for that template, the explicit instantiation has no
6723 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006724 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006725 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006727 case TSK_ExplicitInstantiationDefinition:
6728 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006729 // If an entity is the subject of both an explicit instantiation
6730 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006731 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006732 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006733 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006734
6735 // Explicit instantiations following a specialization have no effect and
6736 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6737 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006738 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6739 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006740 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006741 return false;
6742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006744 case TSK_ExplicitInstantiationDefinition:
6745 switch (PrevTSK) {
6746 case TSK_Undeclared:
6747 case TSK_ImplicitInstantiation:
6748 // We're explicitly instantiating something that may have already been
6749 // implicitly instantiated; that's fine.
6750 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006751
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006752 case TSK_ExplicitSpecialization:
6753 // C++ DR 259, C++0x [temp.explicit]p4:
6754 // For a given set of template parameters, if an explicit
6755 // instantiation of a template appears after a declaration of
6756 // an explicit specialization for that template, the explicit
6757 // instantiation has no effect.
6758 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006759 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006760 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006761 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006762 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006763 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6764 diag::ext_explicit_instantiation_after_specialization)
6765 << PrevDecl;
6766 Diag(PrevDecl->getLocation(),
6767 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006768 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006769 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006770
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006771 case TSK_ExplicitInstantiationDeclaration:
6772 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006773 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006774
6775 // C++0x [temp.explicit]p4:
6776 // For a given set of template parameters, if an explicit instantiation
6777 // of a template appears after a declaration of an explicit
6778 // specialization for that template, the explicit instantiation has no
6779 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006780 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006781 // Is there any previous explicit specialization declaration?
6782 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6783 HasNoEffect = true;
6784 break;
6785 }
6786 }
6787
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006788 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006789
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006790 case TSK_ExplicitInstantiationDefinition:
6791 // C++0x [temp.spec]p5:
6792 // For a given template and a given set of template-arguments,
6793 // - an explicit instantiation definition shall appear at most once
6794 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006795
6796 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6797 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006798 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006799 : diag::err_explicit_instantiation_duplicate)
6800 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006801 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006802 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006803 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006804 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006805 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006807
David Blaikie83d382b2011-09-23 05:06:16 +00006808 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006809}
6810
John McCallb9c78482010-04-08 09:05:18 +00006811/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006812/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006813///
James Dennettf14a6e52012-06-15 22:23:43 +00006814/// The only possible way to get a dependent function template specialization
6815/// is with a friend declaration, like so:
6816///
6817/// \code
6818/// template \<class T> void foo(T);
6819/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006820/// friend void foo<>(T);
6821/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006822/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006823///
6824/// There really isn't any useful analysis we can do here, so we
6825/// just store the information.
6826bool
6827Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6828 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6829 LookupResult &Previous) {
6830 // Remove anything from Previous that isn't a function template in
6831 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006832 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006833 LookupResult::Filter F = Previous.makeFilter();
6834 while (F.hasNext()) {
6835 NamedDecl *D = F.next()->getUnderlyingDecl();
6836 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006837 !FDLookupContext->InEnclosingNamespaceSetOf(
6838 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006839 F.erase();
6840 }
6841 F.done();
6842
6843 // Should this be diagnosed here?
6844 if (Previous.empty()) return true;
6845
6846 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6847 ExplicitTemplateArgs);
6848 return false;
6849}
6850
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006851/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006852/// specialization.
6853///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006854/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006855/// explicit function template specialization. On successful completion,
6856/// the function declaration \p FD will become a function template
6857/// specialization.
6858///
6859/// \param FD the function declaration, which will be updated to become a
6860/// function template specialization.
6861///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006862/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6863/// if any. Note that this may be valid info even when 0 arguments are
6864/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6865/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006866///
Francois Pichet3a44e432011-07-08 06:21:47 +00006867/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006868/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006869bool Sema::CheckFunctionTemplateSpecialization(
6870 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6871 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006872 // The set of function template specializations that could match this
6873 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006874 UnresolvedSet<8> Candidates;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006875 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6876 /*ForTakingAddress=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006877
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006878 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6879 ConvertedTemplateArgs;
6880
Sebastian Redl50c68252010-08-31 00:36:30 +00006881 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006882 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6883 I != E; ++I) {
6884 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6885 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006886 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006887 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006888 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6889 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006890 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891
Richard Smith574f4f62013-01-14 05:37:29 +00006892 // When matching a constexpr member function template specialization
6893 // against the primary template, we don't yet know whether the
6894 // specialization has an implicit 'const' (because we don't know whether
6895 // it will be a static member function until we know which template it
6896 // specializes), so adjust it now assuming it specializes this template.
6897 QualType FT = FD->getType();
6898 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006899 CXXMethodDecl *OldMD =
6900 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006901 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006902 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006903 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6904 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006905 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006906 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006907 }
6908 }
6909
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006910 TemplateArgumentListInfo Args;
6911 if (ExplicitTemplateArgs)
6912 Args = *ExplicitTemplateArgs;
6913
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006914 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006915 // A trailing template-argument can be left unspecified in the
6916 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006917 // provided it can be deduced from the function argument type.
6918 // Perform template argument deduction to determine whether we may be
6919 // specializing this template.
6920 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006921 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006922 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006923 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6924 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
Richard Smithc2bebe92016-05-11 20:37:46 +00006925 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
6926 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006927 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006928 // that we can provide nifty diagnostics.
Richard Smithc2bebe92016-05-11 20:37:46 +00006929 FailedCandidates.addCandidate().set(
6930 I.getPair(), FunTmpl->getTemplatedDecl(),
6931 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006932 (void)TDK;
6933 continue;
6934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006935
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006936 // Record this candidate.
Richard Smith7d3c3ef2015-10-02 00:49:37 +00006937 if (ExplicitTemplateArgs)
6938 ConvertedTemplateArgs[Specialization] = std::move(Args);
John McCall58cc69d2010-01-27 01:50:18 +00006939 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006940 }
6941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006942
Douglas Gregor5de279c2009-09-26 03:41:46 +00006943 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006944 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006945 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006946 FD->getLocation(),
6947 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6948 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006949 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006950 PDiag(diag::note_function_template_spec_matched));
6951
John McCall58cc69d2010-01-27 01:50:18 +00006952 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006953 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006954
6955 // Ignore access information; it doesn't figure into redeclaration checking.
6956 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006957
Nathan Wilson83839122016-04-09 02:55:27 +00006958 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6959 // an explicit specialization (14.8.3) [...] of a concept definition.
6960 if (Specialization->getPrimaryTemplate()->isConcept()) {
6961 Diag(FD->getLocation(), diag::err_concept_specialized)
6962 << 0 /*function*/ << 1 /*explicitly specialized*/;
6963 Diag(Specialization->getLocation(), diag::note_previous_declaration);
6964 return true;
6965 }
6966
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006967 FunctionTemplateSpecializationInfo *SpecInfo
6968 = Specialization->getTemplateSpecializationInfo();
6969 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006970
6971 // Note: do not overwrite location info if previous template
6972 // specialization kind was explicit.
6973 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006974 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006975 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006976 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6977 // function can differ from the template declaration with respect to
6978 // the constexpr specifier.
6979 Specialization->setConstexpr(FD->isConstexpr());
6980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006981
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006982 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006983 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006984
6985 // If this is a friend declaration, then we're not really declaring
6986 // an explicit specialization.
6987 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006988
Douglas Gregor54888652009-10-07 00:13:32 +00006989 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006990 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006991 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006992 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006994 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006995 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006996
6997 // C++ [temp.expl.spec]p6:
6998 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006999 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007000 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007001 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007002 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007003 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00007004 if (!isFriend &&
7005 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00007006 TSK_ExplicitSpecialization,
7007 Specialization,
7008 SpecInfo->getTemplateSpecializationKind(),
7009 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007010 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007011 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007012
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007013 // Mark the prior declaration as an explicit specialization, so that later
7014 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007015 if (!isFriend) {
Faisal Vali81a88be2016-06-14 03:23:15 +00007016 // Since explicit specializations do not inherit '=delete' from their
7017 // primary function template - check if the 'specialization' that was
7018 // implicitly generated (during template argument deduction for partial
7019 // ordering) from the most specialized of all the function templates that
7020 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7021 // first check that it was implicitly generated during template argument
7022 // deduction by making sure it wasn't referenced, and then reset the deleted
7023 // flag to not-deleted, so that we can inherit that information from 'FD'.
7024 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7025 !Specialization->getCanonicalDecl()->isReferenced()) {
7026 assert(
7027 Specialization->getCanonicalDecl() == Specialization &&
7028 "This must be the only existing declaration of this specialization");
7029 Specialization->setDeletedAsWritten(false);
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007030 }
John McCall816d75b2010-03-24 07:46:06 +00007031 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007032 MarkUnusedFileScopedDecl(Specialization);
7033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007034
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007035 // Turn the given function declaration into a function template
7036 // specialization, with the template arguments from the previous
7037 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00007038 // Take copies of (semantic and syntactic) template argument lists.
7039 const TemplateArgumentList* TemplArgs = new (Context)
7040 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Richard Smith7d3c3ef2015-10-02 00:49:37 +00007041 FD->setFunctionTemplateSpecialization(
7042 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7043 SpecInfo->getTemplateSpecializationKind(),
7044 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007045
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007046 // The "previous declaration" for this function template specialization is
7047 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00007048 Previous.clear();
7049 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00007050 return false;
7051}
7052
Douglas Gregor86d142a2009-10-08 07:24:58 +00007053/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007054/// specialization.
7055///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007056/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007057/// explicit member function specialization. On successful completion,
7058/// the function declaration \p FD will become a member function
7059/// specialization.
7060///
Douglas Gregor86d142a2009-10-08 07:24:58 +00007061/// \param Member the member declaration, which will be updated to become a
7062/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007063///
John McCall1f82f242009-11-18 22:49:29 +00007064/// \param Previous the set of declarations, one of which may be specialized
7065/// by this function specialization; the set will be modified to contain the
7066/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007067bool
John McCall1f82f242009-11-18 22:49:29 +00007068Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007069 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00007070
Douglas Gregor86d142a2009-10-08 07:24:58 +00007071 // Try to find the member we are instantiating.
Richard Smith22e7cc62016-05-24 00:01:49 +00007072 NamedDecl *FoundInstantiation = nullptr;
Craig Topperc3ec1492014-05-26 06:22:03 +00007073 NamedDecl *Instantiation = nullptr;
7074 NamedDecl *InstantiatedFrom = nullptr;
7075 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00007076
John McCall1f82f242009-11-18 22:49:29 +00007077 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007078 // Nowhere to look anyway.
7079 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007080 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7081 I != E; ++I) {
7082 NamedDecl *D = (*I)->getUnderlyingDecl();
7083 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00007084 QualType Adjusted = Function->getType();
7085 if (!hasExplicitCallingConv(Adjusted))
7086 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7087 if (Context.hasSameType(Adjusted, Method->getType())) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007088 FoundInstantiation = *I;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007089 Instantiation = Method;
7090 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007091 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007092 break;
7093 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007094 }
7095 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00007096 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007097 VarDecl *PrevVar;
7098 if (Previous.isSingleResult() &&
7099 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00007100 if (PrevVar->isStaticDataMember()) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007101 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007102 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007103 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007104 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007105 }
7106 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00007107 CXXRecordDecl *PrevRecord;
7108 if (Previous.isSingleResult() &&
7109 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007110 FoundInstantiation = Previous.getRepresentativeDecl();
John McCall1f82f242009-11-18 22:49:29 +00007111 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00007112 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007113 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00007114 }
Richard Smith7d137e32012-03-23 03:33:32 +00007115 } else if (isa<EnumDecl>(Member)) {
7116 EnumDecl *PrevEnum;
7117 if (Previous.isSingleResult() &&
7118 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
Richard Smith22e7cc62016-05-24 00:01:49 +00007119 FoundInstantiation = Previous.getRepresentativeDecl();
Richard Smith7d137e32012-03-23 03:33:32 +00007120 Instantiation = PrevEnum;
7121 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7122 MSInfo = PrevEnum->getMemberSpecializationInfo();
7123 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007125
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007126 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007127 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007128 // specializations are always out-of-line, the caller will complain about
7129 // this mismatch later.
7130 return false;
7131 }
John McCalle820e5e2010-04-13 20:37:33 +00007132
7133 // If this is a friend, just bail out here before we start turning
7134 // things into explicit specializations.
7135 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7136 // Preserve instantiation information.
7137 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7138 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7139 cast<CXXMethodDecl>(InstantiatedFrom),
7140 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7141 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7142 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7143 cast<CXXRecordDecl>(InstantiatedFrom),
7144 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7145 }
7146
7147 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007148 Previous.addDecl(FoundInstantiation);
John McCalle820e5e2010-04-13 20:37:33 +00007149 return false;
7150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007151
Douglas Gregor86d142a2009-10-08 07:24:58 +00007152 // Make sure that this is a specialization of a member.
7153 if (!InstantiatedFrom) {
7154 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7155 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007156 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7157 return true;
7158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007159
Douglas Gregor06db9f52009-10-12 20:18:28 +00007160 // C++ [temp.expl.spec]p6:
7161 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007162 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007163 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007164 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007165 // use occurs; no diagnostic is required.
7166 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007167
Abramo Bagnara8075c852010-06-12 07:44:57 +00007168 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007169 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7170 TSK_ExplicitSpecialization,
7171 Instantiation,
7172 MSInfo->getTemplateSpecializationKind(),
7173 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007174 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007175 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007176
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007177 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007178 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007179 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007180 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007181 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007182 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007183
Douglas Gregor86d142a2009-10-08 07:24:58 +00007184 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007185 // the original declaration to note that it is an explicit specialization
7186 // (if it was previously an implicit instantiation). This latter step
7187 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007188 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007189 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7190 if (InstantiationFunction->getTemplateSpecializationKind() ==
7191 TSK_ImplicitInstantiation) {
7192 InstantiationFunction->setTemplateSpecializationKind(
7193 TSK_ExplicitSpecialization);
7194 InstantiationFunction->setLocation(Member->getLocation());
Faisal Vali5e9e8ac2016-04-17 17:32:04 +00007195 // Explicit specializations of member functions of class templates do not
7196 // inherit '=delete' from the member function they are specializing.
7197 if (InstantiationFunction->isDeleted()) {
7198 assert(InstantiationFunction->getCanonicalDecl() ==
7199 InstantiationFunction);
7200 InstantiationFunction->setDeletedAsWritten(false);
7201 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007203
Douglas Gregor86d142a2009-10-08 07:24:58 +00007204 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7205 cast<CXXMethodDecl>(InstantiatedFrom),
7206 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007207 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007208 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007209 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7210 if (InstantiationVar->getTemplateSpecializationKind() ==
7211 TSK_ImplicitInstantiation) {
7212 InstantiationVar->setTemplateSpecializationKind(
7213 TSK_ExplicitSpecialization);
7214 InstantiationVar->setLocation(Member->getLocation());
7215 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007216
Larisse Voufo39a1e502013-08-06 01:03:05 +00007217 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7218 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007219 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007220 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007221 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7222 if (InstantiationClass->getTemplateSpecializationKind() ==
7223 TSK_ImplicitInstantiation) {
7224 InstantiationClass->setTemplateSpecializationKind(
7225 TSK_ExplicitSpecialization);
7226 InstantiationClass->setLocation(Member->getLocation());
7227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007228
Douglas Gregor86d142a2009-10-08 07:24:58 +00007229 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007230 cast<CXXRecordDecl>(InstantiatedFrom),
7231 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007232 } else {
7233 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7234 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7235 if (InstantiationEnum->getTemplateSpecializationKind() ==
7236 TSK_ImplicitInstantiation) {
7237 InstantiationEnum->setTemplateSpecializationKind(
7238 TSK_ExplicitSpecialization);
7239 InstantiationEnum->setLocation(Member->getLocation());
7240 }
7241
7242 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7243 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007244 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007245
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007246 // Save the caller the trouble of having to figure out which declaration
7247 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007248 Previous.clear();
Richard Smith22e7cc62016-05-24 00:01:49 +00007249 Previous.addDecl(FoundInstantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007250 return false;
7251}
7252
Douglas Gregore47f5a72009-10-14 23:41:34 +00007253/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007254///
7255/// \returns true if a serious error occurs, false otherwise.
7256static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007257 SourceLocation InstLoc,
7258 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007259 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7260 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007261
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007262 if (CurContext->isRecord()) {
7263 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7264 << D;
7265 return true;
7266 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007267
Richard Smith050d2612011-10-18 02:28:33 +00007268 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007269 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007270 // template. If the name declared in the explicit instantiation is an
7271 // unqualified name, the explicit instantiation shall appear in the
7272 // namespace where its template is declared or, if that namespace is inline
7273 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007274 //
7275 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007276 if (WasQualifiedName) {
7277 if (CurContext->Encloses(OrigContext))
7278 return false;
7279 } else {
7280 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7281 return false;
7282 }
7283
7284 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7285 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007286 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007287 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007288 diag::err_explicit_instantiation_out_of_scope :
7289 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007290 << D << NS;
7291 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007292 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007293 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007294 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7295 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7296 << D << NS;
7297 } else
7298 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007299 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007300 diag::err_explicit_instantiation_must_be_global :
7301 diag::warn_explicit_instantiation_must_be_global_0x)
7302 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007303 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007304 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007305}
7306
7307/// \brief Determine whether the given scope specifier has a template-id in it.
7308static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7309 if (!SS.isSet())
7310 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007311
Richard Smith050d2612011-10-18 02:28:33 +00007312 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007313 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007314 // or a static data member of a class template specialization, the name of
7315 // the class template specialization in the qualified-id for the member
7316 // name shall be a simple-template-id.
7317 //
7318 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007319 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7320 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007321 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007322 if (isa<TemplateSpecializationType>(T))
7323 return true;
7324
7325 return false;
7326}
7327
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007328// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007329DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007330Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007331 SourceLocation ExternLoc,
7332 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007333 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007334 SourceLocation KWLoc,
7335 const CXXScopeSpec &SS,
7336 TemplateTy TemplateD,
7337 SourceLocation TemplateNameLoc,
7338 SourceLocation LAngleLoc,
7339 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007340 SourceLocation RAngleLoc,
7341 AttributeList *Attr) {
7342 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007343 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007344 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007345 // Check that the specialization uses the same tag kind as the
7346 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007347 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7348 assert(Kind != TTK_Enum &&
7349 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007350
Richard Trieu265c3442016-04-05 21:13:54 +00007351 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7352
7353 if (!ClassTemplate) {
7354 unsigned ErrorKind = 0;
7355 if (isa<TypeAliasTemplateDecl>(TD)) {
7356 ErrorKind = 4;
7357 } else if (isa<TemplateTemplateParmDecl>(TD)) {
7358 ErrorKind = 5;
7359 }
7360
7361 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << ErrorKind;
7362 Diag(TD->getLocation(), diag::note_previous_use);
Richard Smith392497b2013-06-22 22:03:31 +00007363 return true;
7364 }
7365
Douglas Gregord9034f02009-05-14 16:41:31 +00007366 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007367 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007368 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007369 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007370 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007371 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007372 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007373 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007374 diag::note_previous_use);
7375 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7376 }
7377
Douglas Gregore47f5a72009-10-14 23:41:34 +00007378 // C++0x [temp.explicit]p2:
7379 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007380 // definition and an explicit instantiation declaration. An explicit
7381 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007382 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7383 ? TSK_ExplicitInstantiationDefinition
7384 : TSK_ExplicitInstantiationDeclaration;
7385
7386 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7387 // Check for dllexport class template instantiation declarations.
7388 for (AttributeList *A = Attr; A; A = A->getNext()) {
7389 if (A->getKind() == AttributeList::AT_DLLExport) {
7390 Diag(ExternLoc,
7391 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7392 Diag(A->getLoc(), diag::note_attribute);
7393 break;
7394 }
7395 }
7396
7397 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7398 Diag(ExternLoc,
7399 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7400 Diag(A->getLocation(), diag::note_attribute);
7401 }
7402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007403
Hans Wennborga86a83b2016-05-26 19:42:56 +00007404 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7405 // instantiation declarations for most purposes.
7406 bool DLLImportExplicitInstantiationDef = false;
7407 if (TSK == TSK_ExplicitInstantiationDefinition &&
7408 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7409 // Check for dllimport class template instantiation definitions.
7410 bool DLLImport =
7411 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7412 for (AttributeList *A = Attr; A; A = A->getNext()) {
7413 if (A->getKind() == AttributeList::AT_DLLImport)
7414 DLLImport = true;
7415 if (A->getKind() == AttributeList::AT_DLLExport) {
7416 // dllexport trumps dllimport here.
7417 DLLImport = false;
7418 break;
7419 }
7420 }
7421 if (DLLImport) {
7422 TSK = TSK_ExplicitInstantiationDeclaration;
7423 DLLImportExplicitInstantiationDef = true;
7424 }
7425 }
7426
Douglas Gregora1f49972009-05-13 00:25:59 +00007427 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007428 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007429 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007430
7431 // Check that the template argument list is well-formed for this
7432 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007433 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007434 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7435 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007436 return true;
7437
Douglas Gregora1f49972009-05-13 00:25:59 +00007438 // Find the class template specialization declaration that
7439 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007440 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007441 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007442 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007443
Abramo Bagnara8075c852010-06-12 07:44:57 +00007444 TemplateSpecializationKind PrevDecl_TSK
7445 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7446
Douglas Gregor54888652009-10-07 00:13:32 +00007447 // C++0x [temp.explicit]p2:
7448 // [...] An explicit instantiation shall appear in an enclosing
7449 // namespace of its template. [...]
7450 //
7451 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007452 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7453 SS.isSet()))
7454 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007455
Craig Topperc3ec1492014-05-26 06:22:03 +00007456 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007457
Abramo Bagnara8075c852010-06-12 07:44:57 +00007458 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007459 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007460 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007461 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007462 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007463 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007464 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007465
Abramo Bagnara8075c852010-06-12 07:44:57 +00007466 // Even though HasNoEffect == true means that this explicit instantiation
7467 // has no effect on semantics, we go on to put its syntax in the AST.
7468
7469 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7470 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007471 // Since the only prior class template specialization with these
7472 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007473 // declaration node as our own, updating the source location
7474 // for the template name to reflect our new declaration.
7475 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007476 Specialization = PrevDecl;
7477 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007478 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007479 }
Hans Wennborga86a83b2016-05-26 19:42:56 +00007480
7481 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7482 DLLImportExplicitInstantiationDef) {
7483 // The new specialization might add a dllimport attribute.
7484 HasNoEffect = false;
7485 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007486 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007487
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007488 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007489 // Create a new class template specialization declaration node for
7490 // this explicit specialization.
7491 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007492 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007493 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007494 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007495 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007496 Converted.data(),
7497 Converted.size(),
7498 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007499 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007500
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007501 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007502 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007503 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007504 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007505 }
7506
7507 // Build the fully-sugared type for this explicit instantiation as
7508 // the user wrote in the explicit instantiation itself. This means
7509 // that we'll pretty-print the type retrieved from the
7510 // specialization's declaration the way that the user actually wrote
7511 // the explicit instantiation, rather than formatting the name based
7512 // on the "canonical" representation used to store the template
7513 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007514 TypeSourceInfo *WrittenTy
7515 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7516 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007517 Context.getTypeDeclType(Specialization));
7518 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007519
Abramo Bagnara8075c852010-06-12 07:44:57 +00007520 // Set source locations for keywords.
7521 Specialization->setExternLoc(ExternLoc);
7522 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007523 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007524
Rafael Espindola0b062072012-01-03 06:04:21 +00007525 if (Attr)
7526 ProcessDeclAttributeList(S, Specialization, Attr);
7527
Abramo Bagnara8075c852010-06-12 07:44:57 +00007528 // Add the explicit instantiation into its lexical context. However,
7529 // since explicit instantiations are never found by name lookup, we
7530 // just put it into the declaration context directly.
7531 Specialization->setLexicalDeclContext(CurContext);
7532 CurContext->addDecl(Specialization);
7533
7534 // Syntax is now OK, so return if it has no other effect on semantics.
7535 if (HasNoEffect) {
7536 // Set the template specialization kind.
7537 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007538 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007539 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007540
7541 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007542 // A definition of a class template or class member template
7543 // shall be in scope at the point of the explicit instantiation of
7544 // the class template or class member template.
7545 //
7546 // This check comes when we actually try to perform the
7547 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007548 ClassTemplateSpecializationDecl *Def
7549 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007550 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007551 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007552 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007553 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007554 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007555 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7556 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007557
Douglas Gregor1d957a32009-10-27 18:42:08 +00007558 // Instantiate the members of this class template specialization.
7559 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007560 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007561 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007562 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007563 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7564 // TSK_ExplicitInstantiationDefinition
7565 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00007566 (TSK == TSK_ExplicitInstantiationDefinition ||
7567 DLLImportExplicitInstantiationDef)) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007568 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007569 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007570
Hans Wennborgc0875502015-06-09 00:39:05 +00007571 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7572 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7573 // In the MS ABI, an explicit instantiation definition can add a dll
7574 // attribute to a template with a previous instantiation declaration.
7575 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007576 auto *A = cast<InheritableAttr>(
7577 getDLLAttr(Specialization)->clone(getASTContext()));
7578 A->setInherited(true);
7579 Def->addAttr(A);
Reid Kleckner5b640342016-02-26 19:51:02 +00007580
7581 // We reject explicit instantiations in class scope, so there should
7582 // never be any delayed exported classes to worry about.
7583 assert(DelayedDllExportClasses.empty() &&
7584 "delayed exports present at explicit instantiation");
Hans Wennborg17f9b442015-05-27 00:06:45 +00007585 checkClassLevelDLLAttribute(Def);
Reid Kleckner5b640342016-02-26 19:51:02 +00007586 referenceDLLExportedClassMethods();
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007587
7588 // Propagate attribute to base class templates.
7589 for (auto &B : Def->bases()) {
7590 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7591 B.getType()->getAsCXXRecordDecl()))
7592 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7593 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007594 }
7595 }
7596
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007597 // Set the template specialization kind. Make sure it is set before
7598 // instantiating the members which will trigger ASTConsumer callbacks.
7599 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor12e49d32009-10-15 22:53:21 +00007600 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Argyrios Kyrtzidis322d8532015-09-11 01:44:56 +00007601 } else {
7602
7603 // Set the template specialization kind.
7604 Specialization->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007605 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007606
John McCall48871652010-08-21 09:40:31 +00007607 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007608}
7609
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007610// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007611DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007612Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007613 SourceLocation ExternLoc,
7614 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007615 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007616 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007617 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007618 IdentifierInfo *Name,
7619 SourceLocation NameLoc,
7620 AttributeList *Attr) {
7621
Douglas Gregord6ab8742009-05-28 23:31:59 +00007622 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007623 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007624 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007625 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007626 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007627 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007628 SourceLocation(), false, TypeResult(),
7629 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007630 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7631
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007632 if (!TagD)
7633 return true;
7634
John McCall48871652010-08-21 09:40:31 +00007635 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007636 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007637
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007638 if (Tag->isInvalidDecl())
7639 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007640
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007641 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7642 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7643 if (!Pattern) {
7644 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7645 << Context.getTypeDeclType(Record);
7646 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7647 return true;
7648 }
7649
Douglas Gregore47f5a72009-10-14 23:41:34 +00007650 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007651 // If the explicit instantiation is for a class or member class, the
7652 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007653 // simple-template-id.
7654 //
7655 // C++98 has the same restriction, just worded differently.
7656 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007657 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007658 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007659
Douglas Gregore47f5a72009-10-14 23:41:34 +00007660 // C++0x [temp.explicit]p2:
7661 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007662 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007663 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007664 TemplateSpecializationKind TSK
7665 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7666 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007667
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007668 // C++0x [temp.explicit]p2:
7669 // [...] An explicit instantiation shall appear in an enclosing
7670 // namespace of its template. [...]
7671 //
7672 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007673 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007674
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007675 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007676 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007677 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007678 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007679 PrevDecl = Record;
7680 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007681 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007682 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007683 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007684 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007685 PrevDecl,
7686 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007687 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007688 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007689 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007690 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007691 return TagD;
7692 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007693
Douglas Gregor12e49d32009-10-15 22:53:21 +00007694 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007695 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007696 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007697 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007698 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007699 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007700 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007701 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007702 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007703 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7704 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007705 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7706 << Pattern;
7707 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007708 } else {
7709 if (InstantiateClass(NameLoc, Record, Def,
7710 getTemplateInstantiationArgs(Record),
7711 TSK))
7712 return true;
7713
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007714 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007715 if (!RecordDef)
7716 return true;
7717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007718 }
7719
Douglas Gregor1d957a32009-10-27 18:42:08 +00007720 // Instantiate all of the members of the class.
7721 InstantiateClassMembers(NameLoc, RecordDef,
7722 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007723
Douglas Gregor88d292c2010-05-13 16:44:06 +00007724 if (TSK == TSK_ExplicitInstantiationDefinition)
7725 MarkVTableUsed(NameLoc, RecordDef, true);
7726
Mike Stump87c57ac2009-05-16 07:39:55 +00007727 // FIXME: We don't have any representation for explicit instantiations of
7728 // member classes. Such a representation is not needed for compilation, but it
7729 // should be available for clients that want to see all of the declarations in
7730 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007731 return TagD;
7732}
7733
John McCallfaf5fb42010-08-26 23:41:50 +00007734DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7735 SourceLocation ExternLoc,
7736 SourceLocation TemplateLoc,
7737 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007738 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007739 // TODO: check if/when DNInfo should replace Name.
7740 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7741 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007742 if (!Name) {
7743 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007744 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007745 diag::err_explicit_instantiation_requires_name)
7746 << D.getDeclSpec().getSourceRange()
7747 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007748
Douglas Gregor450f00842009-09-25 18:43:00 +00007749 return true;
7750 }
7751
7752 // The scope passed in may not be a decl scope. Zip up the scope tree until
7753 // we find one that is.
7754 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7755 (S->getFlags() & Scope::TemplateParamScope) != 0)
7756 S = S->getParent();
7757
7758 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007759 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7760 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007761 if (R.isNull())
7762 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007763
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007764 // C++ [dcl.stc]p1:
7765 // A storage-class-specifier shall not be specified in [...] an explicit
7766 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007767 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007768 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7769 << Name;
7770 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007771 } else if (D.getDeclSpec().getStorageClassSpec()
7772 != DeclSpec::SCS_unspecified) {
7773 // Complain about then remove the storage class specifier.
7774 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7775 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7776
7777 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007778 }
7779
Douglas Gregor3c74d412009-10-14 20:14:33 +00007780 // C++0x [temp.explicit]p1:
7781 // [...] An explicit instantiation of a function template shall not use the
7782 // inline or constexpr specifiers.
7783 // Presumably, this also applies to member functions of class templates as
7784 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007785 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007786 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007787 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007788 diag::err_explicit_instantiation_inline :
7789 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007790 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007791 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007792 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7793 // not already specified.
7794 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7795 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007796
Nathan Wilsonde498452016-02-08 05:34:00 +00007797 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7798 // applied only to the definition of a function template or variable template,
7799 // declared in namespace scope.
7800 if (D.getDeclSpec().isConceptSpecified()) {
7801 Diag(D.getDeclSpec().getConceptSpecLoc(),
7802 diag::err_concept_specified_specialization) << 0;
7803 return true;
7804 }
7805
Douglas Gregore47f5a72009-10-14 23:41:34 +00007806 // C++0x [temp.explicit]p2:
7807 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007808 // definition and an explicit instantiation declaration. An explicit
7809 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007810 TemplateSpecializationKind TSK
7811 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7812 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007813
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007814 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007815 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007816
7817 if (!R->isFunctionType()) {
7818 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007819 // A [...] static data member of a class template can be explicitly
7820 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007821 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007822 // C++1y [temp.explicit]p1:
7823 // A [...] variable [...] template specialization can be explicitly
7824 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007825 if (Previous.isAmbiguous())
7826 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007827
John McCall67c00872009-12-02 08:25:40 +00007828 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007829 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007830
Larisse Voufo39a1e502013-08-06 01:03:05 +00007831 if (!PrevTemplate) {
7832 if (!Prev || !Prev->isStaticDataMember()) {
7833 // We expect to see a data data member here.
7834 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7835 << Name;
7836 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7837 P != PEnd; ++P)
7838 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7839 return true;
7840 }
7841
7842 if (!Prev->getInstantiatedFromStaticDataMember()) {
7843 // FIXME: Check for explicit specialization?
7844 Diag(D.getIdentifierLoc(),
7845 diag::err_explicit_instantiation_data_member_not_instantiated)
7846 << Prev;
7847 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7848 // FIXME: Can we provide a note showing where this was declared?
7849 return true;
7850 }
7851 } else {
7852 // Explicitly instantiate a variable template.
7853
7854 // C++1y [dcl.spec.auto]p6:
7855 // ... A program that uses auto or decltype(auto) in a context not
7856 // explicitly allowed in this section is ill-formed.
7857 //
7858 // This includes auto-typed variable template instantiations.
7859 if (R->isUndeducedType()) {
7860 Diag(T->getTypeLoc().getLocStart(),
7861 diag::err_auto_not_allowed_var_inst);
7862 return true;
7863 }
7864
Richard Smithef985ac2013-09-18 02:10:12 +00007865 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7866 // C++1y [temp.explicit]p3:
7867 // If the explicit instantiation is for a variable, the unqualified-id
7868 // in the declaration shall be a template-id.
7869 Diag(D.getIdentifierLoc(),
7870 diag::err_explicit_instantiation_without_template_id)
7871 << PrevTemplate;
7872 Diag(PrevTemplate->getLocation(),
7873 diag::note_explicit_instantiation_here);
7874 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007875 }
7876
Nathan Wilson83839122016-04-09 02:55:27 +00007877 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7878 // explicit instantiation (14.8.2) [...] of a concept definition.
7879 if (PrevTemplate->isConcept()) {
7880 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7881 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7882 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7883 return true;
7884 }
7885
Richard Smithef985ac2013-09-18 02:10:12 +00007886 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007887 TemplateArgumentListInfo TemplateArgs =
7888 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007889
Larisse Voufo39a1e502013-08-06 01:03:05 +00007890 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7891 D.getIdentifierLoc(), TemplateArgs);
7892 if (Res.isInvalid())
7893 return true;
7894
7895 // Ignore access control bits, we don't need them for redeclaration
7896 // checking.
7897 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007899
Douglas Gregore47f5a72009-10-14 23:41:34 +00007900 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007901 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007902 // or a static data member of a class template specialization, the name of
7903 // the class template specialization in the qualified-id for the member
7904 // name shall be a simple-template-id.
7905 //
7906 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007907 //
Richard Smith5977d872013-09-18 21:55:14 +00007908 // This does not apply to variable template specializations, where the
7909 // template-id is in the unqualified-id instead.
7910 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007911 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007912 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007913 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007914
Douglas Gregore47f5a72009-10-14 23:41:34 +00007915 // Check the scope of this explicit instantiation.
7916 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007917
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007918 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007919 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7920 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007921 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007922 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007923 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007924 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007925
Larisse Voufo39a1e502013-08-06 01:03:05 +00007926 if (!HasNoEffect) {
7927 // Instantiate static data member or variable template.
7928
7929 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7930 if (PrevTemplate) {
7931 // Merge attributes.
7932 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7933 ProcessDeclAttributeList(S, Prev, Attr);
7934 }
7935 if (TSK == TSK_ExplicitInstantiationDefinition)
7936 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7937 }
7938
7939 // Check the new variable specialization against the parsed input.
7940 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7941 Diag(T->getTypeLoc().getLocStart(),
7942 diag::err_invalid_var_template_spec_type)
7943 << 0 << PrevTemplate << R << Prev->getType();
7944 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7945 << 2 << PrevTemplate->getDeclName();
7946 return true;
7947 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007948
Douglas Gregor450f00842009-09-25 18:43:00 +00007949 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007950 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007952
7953 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007954 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007955 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007956 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007957 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007958 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007959 HasExplicitTemplateArgs = true;
7960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007961
Douglas Gregor450f00842009-09-25 18:43:00 +00007962 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007963 // A [...] function [...] can be explicitly instantiated from its template.
7964 // A member function [...] of a class template can be explicitly
7965 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007966 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007967 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007968 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007969 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7970 P != PEnd; ++P) {
7971 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007972 if (!HasExplicitTemplateArgs) {
7973 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007974 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7975 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007976 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007977
John McCall58cc69d2010-01-27 01:50:18 +00007978 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007979 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7980 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007981 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007982 }
7983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007984
Douglas Gregor450f00842009-09-25 18:43:00 +00007985 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7986 if (!FunTmpl)
7987 continue;
7988
Larisse Voufo98b20f12013-07-19 23:00:19 +00007989 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007990 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007991 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007992 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007993 (HasExplicitTemplateArgs ? &TemplateArgs
7994 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007995 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007996 // Keep track of almost-matches.
7997 FailedCandidates.addCandidate()
Richard Smithc2bebe92016-05-11 20:37:46 +00007998 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
Larisse Voufo98b20f12013-07-19 23:00:19 +00007999 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00008000 (void)TDK;
8001 continue;
8002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008003
John McCall58cc69d2010-01-27 01:50:18 +00008004 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00008005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008006
Douglas Gregor450f00842009-09-25 18:43:00 +00008007 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008008 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00008009 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00008010 D.getIdentifierLoc(),
8011 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8012 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8013 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00008014
John McCall58cc69d2010-01-27 01:50:18 +00008015 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00008016 return true;
John McCall58cc69d2010-01-27 01:50:18 +00008017
8018 // Ignore access control bits, we don't need them for redeclaration checking.
8019 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020
Alexey Bataev73983912014-11-06 10:10:50 +00008021 // C++11 [except.spec]p4
8022 // In an explicit instantiation an exception-specification may be specified,
8023 // but is not required.
8024 // If an exception-specification is specified in an explicit instantiation
8025 // directive, it shall be compatible with the exception-specifications of
8026 // other declarations of that function.
8027 if (auto *FPT = R->getAs<FunctionProtoType>())
8028 if (FPT->hasExceptionSpec()) {
8029 unsigned DiagID =
8030 diag::err_mismatched_exception_spec_explicit_instantiation;
8031 if (getLangOpts().MicrosoftExt)
8032 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8033 bool Result = CheckEquivalentExceptionSpec(
8034 PDiag(DiagID) << Specialization->getType(),
8035 PDiag(diag::note_explicit_instantiation_here),
8036 Specialization->getType()->getAs<FunctionProtoType>(),
8037 Specialization->getLocation(), FPT, D.getLocStart());
8038 // In Microsoft mode, mismatching exception specifications just cause a
8039 // warning.
8040 if (!getLangOpts().MicrosoftExt && Result)
8041 return true;
8042 }
8043
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008044 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008045 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00008046 diag::err_explicit_instantiation_member_function_not_instantiated)
8047 << Specialization
8048 << (Specialization->getTemplateSpecializationKind() ==
8049 TSK_ExplicitSpecialization);
8050 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8051 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008052 }
8053
Douglas Gregorec9fd132012-01-14 16:38:05 +00008054 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00008055 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8056 PrevDecl = Specialization;
8057
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008058 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00008059 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00008060 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008061 PrevDecl,
8062 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008063 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00008064 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008065 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008066
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008067 // FIXME: We may still want to build some representation of this
8068 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00008069 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00008070 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008071 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00008072
8073 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00008074 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8075 if (Attr)
8076 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008077
Richard Smitheb36ddf2014-04-24 22:45:46 +00008078 if (Specialization->isDefined()) {
8079 // Let the ASTConsumer know that this function has been explicitly
8080 // instantiated now, and its linkage might have changed.
8081 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8082 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00008083 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008084
Douglas Gregore47f5a72009-10-14 23:41:34 +00008085 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008086 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00008087 // or a static data member of a class template specialization, the name of
8088 // the class template specialization in the qualified-id for the member
8089 // name shall be a simple-template-id.
8090 //
8091 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00008092 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00008093 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008094 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00008095 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008096 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00008097 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00008098 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008099
Nathan Wilson83839122016-04-09 02:55:27 +00008100 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8101 // explicit instantiation (14.8.2) [...] of a concept definition.
8102 if (FunTmpl && FunTmpl->isConcept() &&
8103 !D.getDeclSpec().isConceptSpecified()) {
8104 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8105 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8106 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8107 return true;
8108 }
8109
Douglas Gregore47f5a72009-10-14 23:41:34 +00008110 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008111 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00008112 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008113 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00008114 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008115
Douglas Gregor450f00842009-09-25 18:43:00 +00008116 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00008117 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00008118}
8119
John McCallfaf5fb42010-08-26 23:41:50 +00008120TypeResult
John McCall7f41d982009-09-11 04:59:25 +00008121Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8122 const CXXScopeSpec &SS, IdentifierInfo *Name,
8123 SourceLocation TagLoc, SourceLocation NameLoc) {
8124 // This has to hold, because SS is expected to be defined.
8125 assert(Name && "Expected a name in a dependent tag");
8126
Aaron Ballman4a979672014-01-03 13:56:08 +00008127 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00008128 if (!NNS)
8129 return true;
8130
Abramo Bagnara6150c882010-05-11 21:36:43 +00008131 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00008132
Douglas Gregorba41d012010-04-24 16:38:41 +00008133 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8134 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00008135 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00008136 return true;
8137 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00008138
Douglas Gregore7c20652011-03-02 00:47:37 +00008139 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00008140 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00008141 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8142
8143 // Create type-source location information for this type.
8144 TypeLocBuilder TLB;
8145 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008146 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00008147 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8148 TL.setNameLoc(NameLoc);
8149 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00008150}
8151
John McCallfaf5fb42010-08-26 23:41:50 +00008152TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008153Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8154 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00008155 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008156 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00008157 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008158
Richard Smith0bf8a4922011-10-18 20:49:44 +00008159 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8160 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008161 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008162 diag::warn_cxx98_compat_typename_outside_of_template :
8163 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164 << FixItHint::CreateRemoval(TypenameLoc);
8165
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008166 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00008167 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8168 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00008169 if (T.isNull())
8170 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008171
8172 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8173 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00008174 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008175 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008176 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00008177 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008178 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00008179 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008180 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008181 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00008182 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00008183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008184
John McCallba7bf592010-08-24 05:47:05 +00008185 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00008186}
8187
John McCallfaf5fb42010-08-26 23:41:50 +00008188TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008189Sema::ActOnTypenameType(Scope *S,
8190 SourceLocation TypenameLoc,
8191 const CXXScopeSpec &SS,
8192 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00008193 TemplateTy TemplateIn,
8194 SourceLocation TemplateNameLoc,
8195 SourceLocation LAngleLoc,
8196 ASTTemplateArgsPtr TemplateArgsIn,
8197 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00008198 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8199 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008200 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008201 diag::warn_cxx98_compat_typename_outside_of_template :
8202 diag::ext_typename_outside_of_template)
8203 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008204
8205 // Translate the parser's template argument list in our AST format.
8206 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8207 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8208
8209 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008210 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8211 // Construct a dependent template specialization type.
8212 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008213 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008214 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8215 DTN->getQualifier(),
8216 DTN->getIdentifier(),
8217 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008218
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008219 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008220 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008221 DependentTemplateSpecializationTypeLoc SpecTL
8222 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008223 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8224 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008225 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008226 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008227 SpecTL.setLAngleLoc(LAngleLoc);
8228 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008229 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8230 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008231 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008232 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008233
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008234 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8235 if (T.isNull())
8236 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008237
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008238 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008239 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008240 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008241 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008242 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8243 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008244 SpecTL.setLAngleLoc(LAngleLoc);
8245 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008246 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8247 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8248
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008249 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8250 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008251 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008252 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8253
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008254 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8255 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008256}
8257
Douglas Gregorb09518c2011-02-27 22:46:49 +00008258
Richard Smith6f8d2c62012-05-09 05:17:00 +00008259/// Determine whether this failed name lookup should be treated as being
8260/// disabled by a usage of std::enable_if.
8261static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8262 SourceRange &CondRange) {
8263 // We must be looking for a ::type...
8264 if (!II.isStr("type"))
8265 return false;
8266
8267 // ... within an explicitly-written template specialization...
8268 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8269 return false;
8270 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008271 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8272 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8273 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008274 return false;
8275 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008276 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008277
8278 // ... which names a complete class template declaration...
8279 const TemplateDecl *EnableIfDecl =
8280 EnableIfTST->getTemplateName().getAsTemplateDecl();
8281 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8282 return false;
8283
8284 // ... called "enable_if".
8285 const IdentifierInfo *EnableIfII =
8286 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8287 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8288 return false;
8289
8290 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008291 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008292 return true;
8293}
8294
Douglas Gregor333489b2009-03-27 23:10:48 +00008295/// \brief Build the type that describes a C++ typename specifier,
8296/// e.g., "typename T::type".
8297QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008298Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8299 SourceLocation KeywordLoc,
8300 NestedNameSpecifierLoc QualifierLoc,
8301 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008302 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008303 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008304 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008305
John McCall0b66eb32010-05-01 00:40:08 +00008306 DeclContext *Ctx = computeDeclContext(SS);
8307 if (!Ctx) {
8308 // If the nested-name-specifier is dependent and couldn't be
8309 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008310 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8311 return Context.getDependentNameType(Keyword,
8312 QualifierLoc.getNestedNameSpecifier(),
8313 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008314 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008315
John McCall0b66eb32010-05-01 00:40:08 +00008316 // If the nested-name-specifier refers to the current instantiation,
8317 // the "typename" keyword itself is superfluous. In C++03, the
8318 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8319 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008320 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008321
John McCall0b66eb32010-05-01 00:40:08 +00008322 if (RequireCompleteDeclContext(SS, Ctx))
8323 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008324
8325 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008326 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008327 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008328 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008329 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008330 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008331 case LookupResult::NotFound: {
8332 // If we're looking up 'type' within a template named 'enable_if', produce
8333 // a more specific diagnostic.
8334 SourceRange CondRange;
8335 if (isEnableIf(QualifierLoc, II, CondRange)) {
8336 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8337 << Ctx << CondRange;
8338 return QualType();
8339 }
8340
Douglas Gregore40876a2009-10-13 21:16:44 +00008341 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008342 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008343 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008344
8345 case LookupResult::FoundUnresolvedValue: {
8346 // We found a using declaration that is a value. Most likely, the using
8347 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008348 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008349 IILoc);
8350 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8351 << Name << Ctx << FullRange;
8352 if (UnresolvedUsingValueDecl *Using
8353 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008354 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008355 Diag(Loc, diag::note_using_value_decl_missing_typename)
8356 << FixItHint::CreateInsertion(Loc, "typename ");
8357 }
8358 }
8359 // Fall through to create a dependent typename type, from which we can recover
8360 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008361
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008362 case LookupResult::NotFoundInCurrentInstantiation:
8363 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008364 return Context.getDependentNameType(Keyword,
8365 QualifierLoc.getNestedNameSpecifier(),
8366 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008367
8368 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008369 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008370 // We found a type. Build an ElaboratedType, since the
8371 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008372 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008373 return Context.getElaboratedType(ETK_Typename,
8374 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008375 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008376 }
8377
8378 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008379 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008380 break;
8381
8382 case LookupResult::FoundOverloaded:
8383 DiagID = diag::err_typename_nested_not_type;
8384 Referenced = *Result.begin();
8385 break;
8386
John McCall6538c932009-10-10 05:48:19 +00008387 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008388 return QualType();
8389 }
8390
8391 // If we get here, it's because name lookup did not find a
8392 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008393 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008394 IILoc);
8395 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008396 if (Referenced)
8397 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8398 << Name;
8399 return QualType();
8400}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008401
8402namespace {
8403 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008404 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008405 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008406 SourceLocation Loc;
8407 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008408
Douglas Gregor15acfb92009-08-06 16:20:37 +00008409 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008410 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008411
Mike Stump11289f42009-09-09 15:08:12 +00008412 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008413 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008414 DeclarationName Entity)
8415 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008416 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008417
8418 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008419 /// transformed.
8420 ///
8421 /// For the purposes of type reconstruction, a type has already been
8422 /// transformed if it is NULL or if it is not dependent.
8423 bool AlreadyTransformed(QualType T) {
8424 return T.isNull() || !T->isDependentType();
8425 }
Mike Stump11289f42009-09-09 15:08:12 +00008426
8427 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008428 /// rebuilt.
8429 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008430
Douglas Gregor15acfb92009-08-06 16:20:37 +00008431 /// \brief Returns the name of the entity whose type is being rebuilt.
8432 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008433
Douglas Gregoref6ab412009-10-27 06:26:26 +00008434 /// \brief Sets the "base" location and entity when that
8435 /// information is known based on another transformation.
8436 void setBase(SourceLocation Loc, DeclarationName Entity) {
8437 this->Loc = Loc;
8438 this->Entity = Entity;
8439 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008440
8441 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8442 // Lambdas never need to be transformed.
8443 return E;
8444 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008445 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008446} // end anonymous namespace
Douglas Gregor15acfb92009-08-06 16:20:37 +00008447
Douglas Gregor15acfb92009-08-06 16:20:37 +00008448/// \brief Rebuilds a type within the context of the current instantiation.
8449///
Mike Stump11289f42009-09-09 15:08:12 +00008450/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008451/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008452/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008453/// partial specialization thereof). This routine will rebuild that type now
8454/// that we have entered the declarator's scope, which may produce different
8455/// canonical types, e.g.,
8456///
8457/// \code
8458/// template<typename T>
8459/// struct X {
8460/// typedef T* pointer;
8461/// pointer data();
8462/// };
8463///
8464/// template<typename T>
8465/// typename X<T>::pointer X<T>::data() { ... }
8466/// \endcode
8467///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008468/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008469/// since we do not know that we can look into X<T> when we parsed the type.
8470/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008471/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008472/// as the canonical type of T*, allowing the return types of the out-of-line
8473/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008474TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8475 SourceLocation Loc,
8476 DeclarationName Name) {
8477 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008478 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008479
Douglas Gregor15acfb92009-08-06 16:20:37 +00008480 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8481 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008482}
Douglas Gregorbe999392009-09-15 16:23:51 +00008483
John McCalldadc5752010-08-24 06:29:42 +00008484ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008485 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8486 DeclarationName());
8487 return Rebuilder.TransformExpr(E);
8488}
8489
John McCall99b2fe52010-04-29 23:50:39 +00008490bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008491 if (SS.isInvalid())
8492 return true;
John McCall2408e322010-04-27 00:57:59 +00008493
Douglas Gregor10176412011-02-25 16:07:42 +00008494 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008495 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8496 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008497 NestedNameSpecifierLoc Rebuilt
8498 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8499 if (!Rebuilt)
8500 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008501
Douglas Gregor10176412011-02-25 16:07:42 +00008502 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008503 return false;
John McCall2408e322010-04-27 00:57:59 +00008504}
8505
Douglas Gregor041b0842011-10-14 15:31:12 +00008506/// \brief Rebuild the template parameters now that we know we're in a current
8507/// instantiation.
8508bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8509 TemplateParameterList *Params) {
8510 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8511 Decl *Param = Params->getParam(I);
8512
8513 // There is nothing to rebuild in a type parameter.
8514 if (isa<TemplateTypeParmDecl>(Param))
8515 continue;
8516
8517 // Rebuild the template parameter list of a template template parameter.
8518 if (TemplateTemplateParmDecl *TTP
8519 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8520 if (RebuildTemplateParamsInCurrentInstantiation(
8521 TTP->getTemplateParameters()))
8522 return true;
8523
8524 continue;
8525 }
8526
8527 // Rebuild the type of a non-type template parameter.
8528 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8529 TypeSourceInfo *NewTSI
8530 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8531 NTTP->getLocation(),
8532 NTTP->getDeclName());
8533 if (!NewTSI)
8534 return true;
8535
8536 if (NewTSI != NTTP->getTypeSourceInfo()) {
8537 NTTP->setTypeSourceInfo(NewTSI);
8538 NTTP->setType(NewTSI->getType());
8539 }
8540 }
8541
8542 return false;
8543}
8544
Douglas Gregorbe999392009-09-15 16:23:51 +00008545/// \brief Produces a formatted string that describes the binding of
8546/// template parameters to template arguments.
8547std::string
8548Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8549 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008550 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008551}
8552
8553std::string
8554Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8555 const TemplateArgument *Args,
8556 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008557 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008558 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008559
Douglas Gregore62e6a02009-11-11 19:13:48 +00008560 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008561 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008562
Douglas Gregorbe999392009-09-15 16:23:51 +00008563 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008564 if (I >= NumArgs)
8565 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008566
Douglas Gregorbe999392009-09-15 16:23:51 +00008567 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008568 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008569 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008570 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008571
Douglas Gregorbe999392009-09-15 16:23:51 +00008572 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008573 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008574 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008575 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008577
Douglas Gregor0192c232010-12-20 16:52:59 +00008578 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008579 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008580 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008581
8582 Out << ']';
8583 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008584}
Francois Pichet1c229c02011-04-22 22:18:13 +00008585
Richard Smithe40f2ba2013-08-07 21:41:30 +00008586void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8587 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008588 if (!FD)
8589 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008590
8591 LateParsedTemplate *LPT = new LateParsedTemplate;
8592
8593 // Take tokens to avoid allocations
8594 LPT->Toks.swap(Toks);
8595 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008596 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008597
8598 FD->setLateTemplateParsed(true);
8599}
8600
8601void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8602 if (!FD)
8603 return;
8604 FD->setLateTemplateParsed(false);
8605}
Francois Pichet1c229c02011-04-22 22:18:13 +00008606
8607bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8608 DeclContext *DC = CurContext;
8609
8610 while (DC) {
8611 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8612 const FunctionDecl *FD = RD->isLocalClass();
8613 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8614 } else if (DC->isTranslationUnit() || DC->isNamespace())
8615 return false;
8616
8617 DC = DC->getParent();
8618 }
8619 return false;
8620}
Richard Smith6739a102016-05-05 00:56:12 +00008621
8622/// \brief Walk the path from which a declaration was instantiated, and check
8623/// that every explicit specialization along that path is visible. This enforces
8624/// C++ [temp.expl.spec]/6:
8625///
8626/// If a template, a member template or a member of a class template is
8627/// explicitly specialized then that specialization shall be declared before
8628/// the first use of that specialization that would cause an implicit
8629/// instantiation to take place, in every translation unit in which such a
8630/// use occurs; no diagnostic is required.
8631///
8632/// and also C++ [temp.class.spec]/1:
8633///
8634/// A partial specialization shall be declared before the first use of a
8635/// class template specialization that would make use of the partial
8636/// specialization as the result of an implicit or explicit instantiation
8637/// in every translation unit in which such a use occurs; no diagnostic is
8638/// required.
8639class ExplicitSpecializationVisibilityChecker {
8640 Sema &S;
8641 SourceLocation Loc;
8642 llvm::SmallVector<Module *, 8> Modules;
8643
8644public:
8645 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8646 : S(S), Loc(Loc) {}
8647
8648 void check(NamedDecl *ND) {
8649 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8650 return checkImpl(FD);
8651 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8652 return checkImpl(RD);
8653 if (auto *VD = dyn_cast<VarDecl>(ND))
8654 return checkImpl(VD);
8655 if (auto *ED = dyn_cast<EnumDecl>(ND))
8656 return checkImpl(ED);
8657 }
8658
8659private:
8660 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8661 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8662 : Sema::MissingImportKind::ExplicitSpecialization;
8663 const bool Recover = true;
8664
8665 // If we got a custom set of modules (because only a subset of the
8666 // declarations are interesting), use them, otherwise let
8667 // diagnoseMissingImport intelligently pick some.
8668 if (Modules.empty())
8669 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8670 else
8671 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8672 }
8673
8674 // Check a specific declaration. There are three problematic cases:
8675 //
8676 // 1) The declaration is an explicit specialization of a template
8677 // specialization.
8678 // 2) The declaration is an explicit specialization of a member of an
8679 // templated class.
8680 // 3) The declaration is an instantiation of a template, and that template
8681 // is an explicit specialization of a member of a templated class.
8682 //
8683 // We don't need to go any deeper than that, as the instantiation of the
8684 // surrounding class / etc is not triggered by whatever triggered this
8685 // instantiation, and thus should be checked elsewhere.
8686 template<typename SpecDecl>
8687 void checkImpl(SpecDecl *Spec) {
8688 bool IsHiddenExplicitSpecialization = false;
8689 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8690 IsHiddenExplicitSpecialization =
8691 Spec->getMemberSpecializationInfo()
8692 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8693 : !S.hasVisibleDeclaration(Spec);
8694 } else {
8695 checkInstantiated(Spec);
8696 }
8697
8698 if (IsHiddenExplicitSpecialization)
8699 diagnose(Spec->getMostRecentDecl(), false);
8700 }
8701
8702 void checkInstantiated(FunctionDecl *FD) {
8703 if (auto *TD = FD->getPrimaryTemplate())
8704 checkTemplate(TD);
8705 }
8706
8707 void checkInstantiated(CXXRecordDecl *RD) {
8708 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8709 if (!SD)
8710 return;
8711
8712 auto From = SD->getSpecializedTemplateOrPartial();
8713 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8714 checkTemplate(TD);
8715 else if (auto *TD =
8716 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8717 if (!S.hasVisibleDeclaration(TD))
8718 diagnose(TD, true);
8719 checkTemplate(TD);
8720 }
8721 }
8722
8723 void checkInstantiated(VarDecl *RD) {
8724 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8725 if (!SD)
8726 return;
8727
8728 auto From = SD->getSpecializedTemplateOrPartial();
8729 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8730 checkTemplate(TD);
8731 else if (auto *TD =
8732 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8733 if (!S.hasVisibleDeclaration(TD))
8734 diagnose(TD, true);
8735 checkTemplate(TD);
8736 }
8737 }
8738
8739 void checkInstantiated(EnumDecl *FD) {}
8740
8741 template<typename TemplDecl>
8742 void checkTemplate(TemplDecl *TD) {
8743 if (TD->isMemberSpecialization()) {
8744 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8745 diagnose(TD->getMostRecentDecl(), false);
8746 }
8747 }
8748};
8749
8750void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8751 if (!getLangOpts().Modules)
8752 return;
8753
8754 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8755}
8756
8757/// \brief Check whether a template partial specialization that we've discovered
8758/// is hidden, and produce suitable diagnostics if so.
8759void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8760 NamedDecl *Spec) {
8761 llvm::SmallVector<Module *, 8> Modules;
8762 if (!hasVisibleDeclaration(Spec, &Modules))
8763 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8764 MissingImportKind::PartialSpecialization,
8765 /*Recover*/true);
8766}