blob: 40eab8cf999db5fba0cd709e1601741bbbc780e3 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +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.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +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"
Douglas Gregor5101c242008-12-05 18:15:24 +000021#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000022#include "clang/Basic/PartialDiagnostic.h"
David Majnemer763584d2014-02-06 10:59:19 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/ParsedTemplate.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000031#include "llvm/ADT/SmallBitVector.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000032#include "llvm/ADT/SmallString.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000033#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000034using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5101c242008-12-05 18:15:24 +000036
John McCall9b72f892010-11-10 02:40:36 +000037// Exported for use by Parser.
38SourceRange
39clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
40 unsigned N) {
41 if (!N) return SourceRange();
42 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
43}
44
Douglas Gregorb7bfe792009-09-02 22:59:36 +000045/// \brief Determine whether the declaration found is acceptable as the name
46/// of a template and, if so, return that template declaration. Otherwise,
47/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000048static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000049 NamedDecl *Orig,
50 bool AllowFunctionTemplates) {
John McCalle9cccd82010-06-16 08:42:20 +000051 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000052
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000053 if (isa<TemplateDecl>(D)) {
54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +000055 return nullptr;
56
John McCalle9cccd82010-06-16 08:42:20 +000057 return Orig;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000058 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregorb7bfe792009-09-02 22:59:36 +000060 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
61 // C++ [temp.local]p1:
62 // Like normal (non-template) classes, class templates have an
63 // injected-class-name (Clause 9). The injected-class-name
64 // can be used with or without a template-argument-list. When
65 // it is used without a template-argument-list, it is
66 // equivalent to the injected-class-name followed by the
67 // template-parameters of the class template enclosed in
68 // <>. When it is used with a template-argument-list, it
69 // refers to the specified class template specialization,
70 // which could be the current specialization or another
71 // specialization.
72 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000073 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000074 if (Record->getDescribedClassTemplate())
75 return Record->getDescribedClassTemplate();
76
77 if (ClassTemplateSpecializationDecl *Spec
78 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
79 return Spec->getSpecializedTemplate();
80 }
Mike Stump11289f42009-09-09 15:08:12 +000081
Craig Topperc3ec1492014-05-26 06:22:03 +000082 return nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +000083 }
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}
87
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000088void Sema::FilterAcceptableTemplateNames(LookupResult &R,
89 bool AllowFunctionTemplates) {
Douglas Gregor41f90302010-04-12 20:54:26 +000090 // The set of class templates we've already seen.
91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000092 LookupResult::Filter filter = R.makeFilter();
93 while (filter.hasNext()) {
94 NamedDecl *Orig = filter.next();
Douglas Gregor50a3cdd2012-03-10 23:52:41 +000095 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
96 AllowFunctionTemplates);
John McCalle66edc12009-11-24 19:00:30 +000097 if (!Repl)
98 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000099 else if (Repl != Orig) {
100
101 // C++ [temp.local]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000102 // A lookup that finds an injected-class-name (10.2) can result in an
Douglas Gregor41f90302010-04-12 20:54:26 +0000103 // ambiguity in certain cases (for example, if it is found in more than
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000104 // one base class). If all of the injected-class-names that are found
105 // refer to specializations of the same class template, and if the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000106 // is used as a template-name, the reference refers to the class
107 // template itself and not a specialization thereof, and is not
Douglas Gregor41f90302010-04-12 20:54:26 +0000108 // ambiguous.
Douglas Gregor41f90302010-04-12 20:54:26 +0000109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
David Blaikie82e95a32014-11-19 07:49:47 +0000110 if (!ClassTemplates.insert(ClassTmpl).second) {
Douglas Gregor41f90302010-04-12 20:54:26 +0000111 filter.erase();
112 continue;
113 }
John McCallbd8062d2010-08-13 07:02:08 +0000114
115 // FIXME: we promote access to public here as a workaround to
116 // the fact that LookupResult doesn't let us remember that we
117 // found this template through a particular injected class name,
118 // which means we end up doing nasty things to the invariants.
119 // Pretending that access is public is *much* safer.
120 filter.replace(Repl, AS_public);
Douglas Gregor41f90302010-04-12 20:54:26 +0000121 }
John McCalle66edc12009-11-24 19:00:30 +0000122 }
123 filter.done();
124}
125
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000126bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
127 bool AllowFunctionTemplates) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000130 return true;
131
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000132 return false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000133}
134
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000135TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000136 CXXScopeSpec &SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000137 bool hasTemplateKeyword,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000138 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +0000139 ParsedType ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000140 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000141 TemplateTy &TemplateResult,
142 bool &MemberOfUnknownSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000143 assert(getLangOpts().CPlusPlus && "No template names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000144
Douglas Gregor3cf81312009-11-03 23:16:33 +0000145 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000146 MemberOfUnknownSpecialization = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000147
Douglas Gregor3cf81312009-11-03 23:16:33 +0000148 switch (Name.getKind()) {
149 case UnqualifiedId::IK_Identifier:
150 TName = DeclarationName(Name.Identifier);
151 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000152
Douglas Gregor3cf81312009-11-03 23:16:33 +0000153 case UnqualifiedId::IK_OperatorFunctionId:
154 TName = Context.DeclarationNames.getCXXOperatorName(
155 Name.OperatorFunctionId.Operator);
156 break;
157
Alexis Hunted0530f2009-11-28 08:58:14 +0000158 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
160 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000161
Douglas Gregor3cf81312009-11-03 23:16:33 +0000162 default:
163 return TNK_Non_template;
164 }
Mike Stump11289f42009-09-09 15:08:12 +0000165
John McCallba7bf592010-08-24 05:47:05 +0000166 QualType ObjectType = ObjectTypePtr.get();
Mike Stump11289f42009-09-09 15:08:12 +0000167
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +0000169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
170 MemberOfUnknownSpecialization);
John McCallfb3f9ba2010-08-28 20:17:00 +0000171 if (R.empty()) return TNK_Non_template;
172 if (R.isAmbiguous()) {
173 // Suppress diagnostics; we'll redo this lookup later.
John McCalldcc71402010-08-13 02:23:42 +0000174 R.suppressDiagnostics();
John McCallfb3f9ba2010-08-28 20:17:00 +0000175
176 // FIXME: we might have ambiguous templates, in which case we
177 // should at least parse them properly!
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000178 return TNK_Non_template;
John McCalldcc71402010-08-13 02:23:42 +0000179 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000180
John McCalld28ae272009-12-02 08:04:21 +0000181 TemplateName Template;
182 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000183
John McCalld28ae272009-12-02 08:04:21 +0000184 unsigned ResultCount = R.end() - R.begin();
185 if (ResultCount > 1) {
186 // We assume that we'll preserve the qualifier from a function
187 // template name in other ways.
188 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
189 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000193 } else {
John McCalld28ae272009-12-02 08:04:21 +0000194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
195
196 if (SS.isSet() && !SS.isInvalid()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000197 NestedNameSpecifier *Qualifier = SS.getScopeRep();
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
John McCalld28ae272009-12-02 08:04:21 +0000200 } else {
201 Template = TemplateName(TD);
202 }
203
John McCalldcc71402010-08-13 02:23:42 +0000204 if (isa<FunctionTemplateDecl>(TD)) {
John McCalld28ae272009-12-02 08:04:21 +0000205 TemplateKind = TNK_Function_template;
John McCalldcc71402010-08-13 02:23:42 +0000206
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
209 } else {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
Larisse Voufo39a1e502013-08-06 01:03:05 +0000211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
212 TemplateKind =
213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
John McCalld28ae272009-12-02 08:04:21 +0000214 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
John McCalld28ae272009-12-02 08:04:21 +0000217 TemplateResult = TemplateTy::make(Template);
218 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000219}
220
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
Douglas Gregor18473f32010-01-12 21:28:44 +0000222 SourceLocation IILoc,
223 Scope *S,
224 const CXXScopeSpec *SS,
225 TemplateTy &SuggestedTemplate,
226 TemplateNameKind &SuggestedKind) {
227 // We can't recover unless there's a dependent scope specifier preceding the
228 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000229 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
231 computeDeclContext(*SS))
232 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233
Douglas Gregor18473f32010-01-12 21:28:44 +0000234 // The code is missing a 'template' keyword prior to the dependent template
235 // name.
236 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
237 Diag(IILoc, diag::err_template_kw_missing)
238 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000239 << FixItHint::CreateInsertion(IILoc, "template ");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240 SuggestedTemplate
Douglas Gregor18473f32010-01-12 21:28:44 +0000241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
242 SuggestedKind = TNK_Dependent_template_name;
243 return true;
244}
245
John McCalle66edc12009-11-24 19:00:30 +0000246void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000247 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000248 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000249 bool EnteringContext,
250 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000251 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000252 MemberOfUnknownSpecialization = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000253 DeclContext *LookupCtx = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000254 bool isDependent = false;
255 if (!ObjectType.isNull()) {
256 // This nested-name-specifier occurs in a member access expression, e.g.,
257 // x->B::f, and we are looking into the type of the object.
258 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
259 LookupCtx = computeDeclContext(ObjectType);
260 isDependent = ObjectType->isDependentType();
Richard Smith5ed79562013-06-07 20:03:01 +0000261 assert((isDependent || !ObjectType->isIncompleteType() ||
262 ObjectType->castAs<TagType>()->isBeingDefined()) &&
John McCalle66edc12009-11-24 19:00:30 +0000263 "Caller should have completed object type");
Douglas Gregorbf3a8262012-01-12 16:11:24 +0000264
265 // Template names cannot appear inside an Objective-C class or object type.
266 if (ObjectType->isObjCObjectOrInterfaceType()) {
267 Found.clear();
268 return;
269 }
John McCalle66edc12009-11-24 19:00:30 +0000270 } else if (SS.isSet()) {
271 // This nested-name-specifier occurs after another nested-name-specifier,
272 // so long into the context associated with the prior nested-name-specifier.
273 LookupCtx = computeDeclContext(SS, EnteringContext);
274 isDependent = isDependentScopeSpecifier(SS);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275
John McCalle66edc12009-11-24 19:00:30 +0000276 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000278 return;
279 }
280
281 bool ObjectTypeSearchedInScope = false;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000282 bool AllowFunctionTemplatesInLookup = true;
John McCalle66edc12009-11-24 19:00:30 +0000283 if (LookupCtx) {
284 // Perform "qualified" name lookup into the declaration context we
285 // computed, which is either the type of the base of a member access
286 // expression or the declaration context associated with a prior
287 // nested-name-specifier.
288 LookupQualifiedName(Found, LookupCtx);
John McCalle66edc12009-11-24 19:00:30 +0000289 if (!ObjectType.isNull() && Found.empty()) {
290 // C++ [basic.lookup.classref]p1:
291 // In a class member access expression (5.2.5), if the . or -> token is
292 // immediately followed by an identifier followed by a <, the
293 // identifier must be looked up to determine whether the < is the
294 // beginning of a template argument list (14.2) or a less-than operator.
295 // The identifier is first looked up in the class of the object
296 // expression. If the identifier is not found, it is then looked up in
297 // the context of the entire postfix-expression and shall name a class
298 // or function template.
John McCalle66edc12009-11-24 19:00:30 +0000299 if (S) LookupName(Found, S);
300 ObjectTypeSearchedInScope = true;
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000301 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000302 }
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000303 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000304 // We cannot look into a dependent object type or nested nme
305 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000306 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000307 return;
308 } else {
309 // Perform unqualified name lookup in the current scope.
310 LookupName(Found, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000311
312 if (!ObjectType.isNull())
313 AllowFunctionTemplatesInLookup = false;
John McCalle66edc12009-11-24 19:00:30 +0000314 }
315
Douglas Gregorc119dd52010-01-12 17:06:20 +0000316 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000317 // If we did not find any names, attempt to correct any typos.
318 DeclarationName Name = Found.getLookupName();
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000319 Found.clear();
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000320 // Simple filter callback that, for keywords, only accepts the C++ *_cast
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000321 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
322 FilterCCC->WantTypeSpecifiers = false;
323 FilterCCC->WantExpressionKeywords = false;
324 FilterCCC->WantRemainingKeywords = false;
325 FilterCCC->WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(
327 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
328 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000329 Found.setLookupName(Corrected.getCorrection());
330 if (Corrected.getCorrectionDecl())
331 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000332 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000333 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000334 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000335 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
336 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000337 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000338 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
339 << Name << LookupCtx << DroppedSpecifier
340 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000341 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000342 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000343 }
John McCalle9cccd82010-06-16 08:42:20 +0000344 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000345 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000346 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000347 }
348 }
349
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000351 if (Found.empty()) {
352 if (isDependent)
353 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000354 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000355 }
John McCalle66edc12009-11-24 19:00:30 +0000356
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000358 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000359 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000360 // [...] If the lookup in the class of the object expression finds a
361 // template, the name is also looked up in the context of the entire
362 // postfix-expression and [...]
363 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000364 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000365 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
366 LookupOrdinaryName);
367 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000368 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
John McCalle66edc12009-11-24 19:00:30 +0000370 if (FoundOuter.empty()) {
371 // - if the name is not found, the name found in the class of the
372 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000373 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
374 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000375 // - if the name is found in the context of the entire
376 // postfix-expression and does not name a class template, the name
377 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000378 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000379 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000380 // - if the name found is a class template, it must refer to the same
381 // entity as the one found in the class of the object expression,
382 // otherwise the program is ill-formed.
383 if (!Found.isSingleResult() ||
384 Found.getFoundDecl()->getCanonicalDecl()
385 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000387 diag::ext_nested_name_member_ref_lookup_ambiguous)
388 << Found.getLookupName()
389 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000390 Diag(Found.getRepresentativeDecl()->getLocation(),
391 diag::note_ambig_member_ref_object_type)
392 << ObjectType;
393 Diag(FoundOuter.getFoundDecl()->getLocation(),
394 diag::note_ambig_member_ref_scope);
395
396 // Recover by taking the template that we found in the object
397 // expression's type.
398 }
399 }
400 }
401}
402
John McCallcd4b4772009-12-02 03:53:29 +0000403/// ActOnDependentIdExpression - Handle a dependent id-expression that
404/// was just parsed. This is only possible with an explicit scope
405/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000406ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000407Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000408 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000409 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000410 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000411 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000412 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
John McCallcd4b4772009-12-02 03:53:29 +0000414 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000415 isa<CXXMethodDecl>(DC) &&
416 cast<CXXMethodDecl>(DC)->isInstance()) {
417 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418
John McCalle66edc12009-11-24 19:00:30 +0000419 // Since the 'this' expression is synthesized, we don't need to
420 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000421 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000422
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000423 return CXXDependentScopeMemberExpr::Create(
424 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
425 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
426 FirstQualifierInScope, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000427 }
428
Abramo Bagnara7945c982012-01-27 09:46:47 +0000429 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000430}
431
John McCalldadc5752010-08-24 06:29:42 +0000432ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000433Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000434 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000435 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000436 const TemplateArgumentListInfo *TemplateArgs) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000437 return DependentScopeDeclRefExpr::Create(
438 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
439 TemplateArgs);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000440}
441
Douglas Gregor5101c242008-12-05 18:15:24 +0000442/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
443/// that the template parameter 'PrevDecl' is being shadowed by a new
444/// declaration at location Loc. Returns true to indicate that this is
445/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000446void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000447 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000448
449 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000450 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000451 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000452
453 // C++ [temp.local]p4:
454 // A template-parameter shall not be redeclared within its
455 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000456 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000457 << cast<NamedDecl>(PrevDecl)->getDeclName();
458 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000459 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000460}
461
Douglas Gregor463421d2009-03-03 04:44:36 +0000462/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000463/// the parameter D to reference the templated declaration and return a pointer
464/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000465TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
466 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
467 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000468 return Temp;
469 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000470 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000471}
472
Douglas Gregoreb29d182011-01-05 17:40:24 +0000473ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
474 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000475 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000476 "Only template template arguments can be pack expansions here");
477 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
478 "Template template argument pack expansion without packs");
479 ParsedTemplateArgument Result(*this);
480 Result.EllipsisLoc = EllipsisLoc;
481 return Result;
482}
483
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000484static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
485 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000487 switch (Arg.getKind()) {
488 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000489 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000490 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000492 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000493 return TemplateArgumentLoc(TemplateArgument(T), DI);
494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000495
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000496 case ParsedTemplateArgument::NonType: {
497 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
498 return TemplateArgumentLoc(TemplateArgument(E), E);
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000501 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000502 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000503 TemplateArgument TArg;
504 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000505 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000506 else
507 TArg = Template;
508 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000509 Arg.getScopeSpec().getWithLocInContext(
510 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000511 Arg.getLocation(),
512 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000513 }
514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000516 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000517}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000519/// \brief Translates template arguments as provided by the parser
520/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000521void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
522 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000523 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000524 TemplateArgs.addArgument(translateTemplateArgument(*this,
525 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000526}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000527
Richard Smithb80d5402013-06-25 22:21:36 +0000528static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
529 SourceLocation Loc,
530 IdentifierInfo *Name) {
531 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
532 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
533 if (PrevDecl && PrevDecl->isTemplateParameter())
534 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
535}
536
Douglas Gregor5101c242008-12-05 18:15:24 +0000537/// ActOnTypeParameter - Called when a C++ template type parameter
538/// (e.g., "typename T") has been parsed. Typename specifies whether
539/// the keyword "typename" was used to declare the type parameter
540/// (otherwise, "class" was used), and KeyLoc is the location of the
541/// "class" or "typename" keyword. ParamName is the name of the
542/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000543/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000544/// If the type parameter has a default argument, it will be added
545/// later via ActOnTypeParameterDefault.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000546Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
John McCall48871652010-08-21 09:40:31 +0000547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000553 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000556 bool Invalid = false;
557
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000558 SourceLocation Loc = ParamNameLoc;
559 if (!ParamName)
560 Loc = KeyLoc;
561
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000562 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregor5101c242008-12-05 18:15:24 +0000563 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000564 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000565 KeyLoc, Loc, Depth, Position, ParamName,
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000566 Typename, IsParameterPack);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000567 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000568 if (Invalid)
569 Param->setInvalidDecl();
570
571 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000572 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
573
Douglas Gregor5101c242008-12-05 18:15:24 +0000574 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000575 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000576 IdResolver.AddDecl(Param);
577 }
578
Douglas Gregorf5500772011-01-05 15:48:55 +0000579 // C++0x [temp.param]p9:
580 // A default template-argument may be specified for any kind of
581 // template-parameter that is not a template parameter pack.
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000582 if (DefaultArg && IsParameterPack) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000583 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
584 DefaultArg = ParsedType();
585 }
586
Douglas Gregordc13ded2010-07-01 00:00:45 +0000587 // Handle the default argument, if provided.
588 if (DefaultArg) {
589 TypeSourceInfo *DefaultTInfo;
590 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregordc13ded2010-07-01 00:00:45 +0000592 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000594 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000596 UPPC_DefaultArgument))
597 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregordc13ded2010-07-01 00:00:45 +0000599 // Check the template argument itself.
600 if (CheckTemplateArgument(Param, DefaultTInfo)) {
601 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000602 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604
Richard Smith1469b912015-06-10 00:29:03 +0000605 Param->setDefaultArgument(DefaultTInfo);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
John McCall48871652010-08-21 09:40:31 +0000608 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000609}
610
Douglas Gregor463421d2009-03-03 04:44:36 +0000611/// \brief Check that the type of a non-type template parameter is
612/// well-formed.
613///
614/// \returns the (possibly-promoted) parameter type if valid;
615/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000616QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000617Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000618 // We don't allow variably-modified types as the type of non-type template
619 // parameters.
620 if (T->isVariablyModifiedType()) {
621 Diag(Loc, diag::err_variably_modified_nontype_template_param)
622 << T;
623 return QualType();
624 }
625
Douglas Gregor463421d2009-03-03 04:44:36 +0000626 // C++ [temp.param]p4:
627 //
628 // A non-type template-parameter shall have one of the following
629 // (optionally cv-qualified) types:
630 //
631 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000632 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000633 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000634 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000635 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000636 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000637 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000639 // -- std::nullptr_t.
640 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 // If T is a dependent type, we can't do the check now, so we
642 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000643 T->isDependentType()) {
644 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
645 // are ignored when determining its type.
646 return T.getUnqualifiedType();
647 }
648
Douglas Gregor463421d2009-03-03 04:44:36 +0000649 // C++ [temp.param]p8:
650 //
651 // A non-type template-parameter of type "array of T" or
652 // "function returning T" is adjusted to be of type "pointer to
653 // T" or "pointer to function returning T", respectively.
Richard Smithd663fdd2014-12-17 20:42:37 +0000654 else if (T->isArrayType() || T->isFunctionType())
655 return Context.getDecayedType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor463421d2009-03-03 04:44:36 +0000657 Diag(Loc, diag::err_template_nontype_parm_bad_type)
658 << T;
659
660 return QualType();
661}
662
John McCall48871652010-08-21 09:40:31 +0000663Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
664 unsigned Depth,
665 unsigned Position,
666 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000667 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000668 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
669 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000670
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000671 assert(S->isTemplateParamScope() &&
672 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000673 bool Invalid = false;
674
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000675 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
676 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000677 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000678 Invalid = true;
679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Richard Smithb80d5402013-06-25 22:21:36 +0000681 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000682 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000683 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000684 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000685 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000686 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000688 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000689 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000690
Douglas Gregor5101c242008-12-05 18:15:24 +0000691 if (Invalid)
692 Param->setInvalidDecl();
693
Richard Smithb80d5402013-06-25 22:21:36 +0000694 if (ParamName) {
695 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
696 ParamName);
697
Douglas Gregor5101c242008-12-05 18:15:24 +0000698 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000699 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000700 IdResolver.AddDecl(Param);
701 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000702
Douglas Gregorf5500772011-01-05 15:48:55 +0000703 // C++0x [temp.param]p9:
704 // A default template-argument may be specified for any kind of
705 // template-parameter that is not a template parameter pack.
706 if (Default && IsParameterPack) {
707 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000708 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000709 }
710
Douglas Gregordc13ded2010-07-01 00:00:45 +0000711 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000712 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000713 // Check for unexpanded parameter packs.
714 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
715 return Param;
716
Douglas Gregordc13ded2010-07-01 00:00:45 +0000717 TemplateArgument Converted;
Richard Smithd663fdd2014-12-17 20:42:37 +0000718 ExprResult DefaultRes =
719 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
John Wiegley01296292011-04-08 18:41:53 +0000720 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000721 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000722 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000723 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000724 Default = DefaultRes.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
Richard Smith1469b912015-06-10 00:29:03 +0000726 Param->setDefaultArgument(Default);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
John McCall48871652010-08-21 09:40:31 +0000729 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000730}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000731
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000732/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000733/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000734/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000735Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
736 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000737 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000738 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000739 IdentifierInfo *Name,
740 SourceLocation NameLoc,
741 unsigned Depth,
742 unsigned Position,
743 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000744 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000745 assert(S->isTemplateParamScope() &&
746 "Template template parameter not in template parameter scope!");
747
748 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000749 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000750 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000751 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000752 NameLoc.isInvalid()? TmpLoc : NameLoc,
753 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000754 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000755 Param->setAccess(AS_public);
756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000758 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000759 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000760 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
761
John McCall48871652010-08-21 09:40:31 +0000762 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000763 IdResolver.AddDecl(Param);
764 }
765
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000766 if (Params->size() == 0) {
767 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
768 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
769 Param->setInvalidDecl();
770 }
771
Douglas Gregorf5500772011-01-05 15:48:55 +0000772 // C++0x [temp.param]p9:
773 // A default template-argument may be specified for any kind of
774 // template-parameter that is not a template parameter pack.
775 if (IsParameterPack && !Default.isInvalid()) {
776 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
777 Default = ParsedTemplateArgument();
778 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779
Douglas Gregordc13ded2010-07-01 00:00:45 +0000780 if (!Default.isInvalid()) {
781 // Check only that we have a template template argument. We don't want to
782 // try to check well-formedness now, because our template template parameter
783 // might have dependent types in its template parameters, which we wouldn't
784 // be able to match now.
785 //
786 // If none of the template template parameter's template arguments mention
787 // other template parameters, we could actually perform more checking here.
788 // However, it isn't worth doing.
789 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
790 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
791 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
792 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000793 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000796 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000798 DefaultArg.getArgument().getAsTemplate(),
799 UPPC_DefaultArgument))
800 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801
Richard Smith1469b912015-06-10 00:29:03 +0000802 Param->setDefaultArgument(Context, DefaultArg);
Douglas Gregordba32632009-02-10 19:49:53 +0000803 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000804
John McCall48871652010-08-21 09:40:31 +0000805 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000806}
807
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000808/// ActOnTemplateParameterList - Builds a TemplateParameterList that
809/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000810TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000811Sema::ActOnTemplateParameterList(unsigned Depth,
812 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000813 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000814 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000815 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000816 SourceLocation RAngleLoc) {
817 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000818 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000819
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821 (NamedDecl**)Params, NumParams,
Douglas Gregorbe999392009-09-15 16:23:51 +0000822 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000823}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000824
John McCall3e11ebe2010-03-15 10:12:16 +0000825static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
826 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000828}
829
John McCallfaf5fb42010-08-26 23:41:50 +0000830DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000831Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000832 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000833 IdentifierInfo *Name, SourceLocation NameLoc,
834 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000835 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Nikola Smiljanic4fc91532014-07-17 01:59:34 +0000837 SourceLocation FriendLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000838 unsigned NumOuterTemplateParamLists,
Richard Smithbe3980b2015-03-27 00:41:57 +0000839 TemplateParameterList** OuterTemplateParamLists,
Richard Smithd9ba2242015-05-07 03:54:19 +0000840 SkipBodyInfo *SkipBody) {
Mike Stump11289f42009-09-09 15:08:12 +0000841 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000842 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000843 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000844 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000845
846 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000847 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000848 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849
Abramo Bagnara6150c882010-05-11 21:36:43 +0000850 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
851 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000852
853 // There is no such thing as an unnamed class template.
854 if (!Name) {
855 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857 }
858
Richard Smith6483d222012-04-21 01:27:54 +0000859 // Find any previous declaration with this name. For a friend with no
860 // scope explicitly specified, we only look for tag declarations (per
861 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000862 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000863 LookupResult Previous(*this, Name, NameLoc,
864 (SS.isEmpty() && TUK == TUK_Friend)
865 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000866 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000867 if (SS.isNotEmpty() && !SS.isInvalid()) {
868 SemanticContext = computeDeclContext(SS, true);
869 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000870 // FIXME: Horrible, horrible hack! We can't currently represent this
871 // in the AST, and historically we have just ignored such friend
872 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000873 Diag(NameLoc, TUK == TUK_Friend
874 ? diag::warn_template_qualified_friend_ignored
875 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000876 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000877 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000878 }
Mike Stump11289f42009-09-09 15:08:12 +0000879
John McCall0b66eb32010-05-01 00:40:08 +0000880 if (RequireCompleteDeclContext(SS, SemanticContext))
881 return true;
882
Douglas Gregor041b0842011-10-14 15:31:12 +0000883 // If we're adding a template to a dependent context, we may need to
884 // rebuilding some of the types used within the template parameter list,
885 // now that we know what the current instantiation is.
886 if (SemanticContext->isDependentContext()) {
887 ContextRAII SavedContext(*this, SemanticContext);
888 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
889 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000890 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
891 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000892
John McCall27b18f82009-11-17 02:14:36 +0000893 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000894 } else {
895 SemanticContext = CurContext;
Richard Smith88fe69c2015-07-06 01:45:27 +0000896
897 // C++14 [class.mem]p14:
898 // If T is the name of a class, then each of the following shall have a
899 // name different from T:
900 // -- every member template of class T
901 if (TUK != TUK_Friend &&
902 DiagnoseClassNameShadow(SemanticContext,
903 DeclarationNameInfo(Name, NameLoc)))
904 return true;
905
John McCall27b18f82009-11-17 02:14:36 +0000906 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000907 }
Mike Stump11289f42009-09-09 15:08:12 +0000908
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000909 if (Previous.isAmbiguous())
910 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000911
Craig Topperc3ec1492014-05-26 06:22:03 +0000912 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000913 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000914 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000915
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000916 // If there is a previous declaration with the same name, check
917 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000918 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000919 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000920
921 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000922 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000923 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000924 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000925 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
926 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000927 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000928 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
929 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
930 PrevClassTemplate
931 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
932 ->getSpecializedTemplate();
933 }
934 }
935
John McCalld43784f2009-12-18 11:25:59 +0000936 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000937 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938 // [...] When looking for a prior declaration of a class or a function
939 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000940 // function is neither a qualified name nor a template-id, scopes outside
941 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000942 if (!SS.isSet()) {
943 DeclContext *OutermostContext = CurContext;
944 while (!OutermostContext->isFileContext())
945 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000946
Richard Smith61e582f2012-04-20 07:12:26 +0000947 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000948 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
949 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
950 SemanticContext = PrevDecl->getDeclContext();
951 } else {
952 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000953 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000954 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000955 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000956 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000957
958 // Check that the chosen semantic context doesn't already contain a
959 // declaration of this name as a non-tag type.
Richard Smithfc805ca2015-07-06 04:43:58 +0000960 Previous.clear(LookupOrdinaryName);
Richard Smith6483d222012-04-21 01:27:54 +0000961 DeclContext *LookupContext = SemanticContext;
962 while (LookupContext->isTransparentContext())
963 LookupContext = LookupContext->getLookupParent();
964 LookupQualifiedName(Previous, LookupContext);
965
966 if (Previous.isAmbiguous())
967 return true;
968
969 if (Previous.begin() != Previous.end())
970 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000971 }
John McCall90d3bb92009-12-17 23:21:11 +0000972 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000973 } else if (PrevDecl &&
Richard Smithfc805ca2015-07-06 04:43:58 +0000974 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
975 S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000976 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000977
Richard Smithfc805ca2015-07-06 04:43:58 +0000978 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
979 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
980 if (SS.isEmpty() &&
981 !(PrevClassTemplate &&
982 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
983 SemanticContext->getRedeclContext()))) {
984 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
985 Diag(Shadow->getTargetDecl()->getLocation(),
986 diag::note_using_decl_target);
987 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
988 // Recover by ignoring the old declaration.
989 PrevDecl = PrevClassTemplate = nullptr;
990 }
991 }
992
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000993 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000994 // Ensure that the template parameter lists are compatible. Skip this check
995 // for a friend in a dependent context: the template parameter list itself
996 // could be dependent.
997 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
998 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000999 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00001000 /*Complain=*/true,
1001 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +00001002 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001003
1004 // C++ [temp.class]p4:
1005 // In a redeclaration, partial specialization, explicit
1006 // specialization or explicit instantiation of a class template,
1007 // the class-key shall agree in kind with the original class
1008 // template declaration (7.1.5.3).
1009 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +00001010 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001011 TUK == TUK_Definition, KWLoc, Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00001012 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00001013 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00001014 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001015 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001016 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001017 }
1018
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001019 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001020 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001021 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001022 // If we have a prior definition that is not visible, treat this as
1023 // simply making that previous definition visible.
1024 NamedDecl *Hidden = nullptr;
1025 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001026 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001027 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1028 assert(Tmpl && "original definition of a class template is not a "
1029 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001030 makeMergedDefinitionVisible(Hidden, KWLoc);
1031 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001032 return Def;
1033 }
1034
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001035 Diag(NameLoc, diag::err_redefinition) << Name;
1036 Diag(Def->getLocation(), diag::note_previous_definition);
1037 // FIXME: Would it make sense to try to "forget" the previous
1038 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001039 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001040 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001041 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001042 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1043 // Maybe we will complain about the shadowed template parameter.
1044 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1045 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001046 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001047 } else if (PrevDecl) {
1048 // C++ [temp]p5:
1049 // A class template shall not have the same name as any other
1050 // template, class, function, object, enumeration, enumerator,
1051 // namespace, or type in the same scope (3.3), except as specified
1052 // in (14.5.4).
1053 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1054 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001055 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001056 }
1057
Douglas Gregordba32632009-02-10 19:49:53 +00001058 // Check the template parameter list of this declaration, possibly
1059 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001060 // template declaration. Skip this check for a friend in a dependent
1061 // context, because the template parameter list might be dependent.
1062 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001063 CheckTemplateParameterList(
1064 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001065 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1066 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001067 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1068 SemanticContext->isDependentContext())
1069 ? TPC_ClassTemplateMember
1070 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1071 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001072 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001073
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001074 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001075 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001076 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001077 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1078 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001079 : diag::err_member_decl_does_not_match)
1080 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001081 Invalid = true;
1082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083 }
1084
Mike Stump11289f42009-09-09 15:08:12 +00001085 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001086 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001087 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001088 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001089 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001090 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001091 if (NumOuterTemplateParamLists > 0)
1092 NewClass->setTemplateParameterListsInfo(Context,
1093 NumOuterTemplateParamLists,
1094 OuterTemplateParamLists);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001095
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001096 // Add alignment attributes if necessary; these attributes are checked when
1097 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001098 if (TUK == TUK_Definition) {
1099 AddAlignmentAttributesForRecord(NewClass);
1100 AddMsStructLayoutForRecord(NewClass);
1101 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001102
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001103 ClassTemplateDecl *NewTemplate
1104 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1105 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001106 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001107 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001108
Douglas Gregor21823bf2011-12-20 18:11:52 +00001109 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001110 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001111
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001112 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001113 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001114 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001115 assert(T->isDependentType() && "Class template type is not dependent?");
1116 (void)T;
1117
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001118 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001119 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001120 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001121 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1122 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123
Anders Carlsson137108d2009-03-26 01:24:28 +00001124 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001125 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001126 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001127
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001128 // Set the lexical context of these templates
1129 NewClass->setLexicalDeclContext(CurContext);
1130 NewTemplate->setLexicalDeclContext(CurContext);
1131
John McCall9bb74a52009-07-31 02:45:11 +00001132 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001133 NewClass->startDefinition();
1134
1135 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001136 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001137
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001138 if (PrevClassTemplate)
1139 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1140
Rafael Espindola385c0422012-07-13 18:04:45 +00001141 AddPushedVisibilityAttribute(NewClass);
1142
Richard Smith234ff472014-08-23 00:49:01 +00001143 if (TUK != TUK_Friend) {
1144 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1145 Scope *Outer = S;
1146 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1147 Outer = Outer->getParent();
1148 PushOnScopeChains(NewTemplate, Outer);
1149 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001150 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001151 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001152 NewClass->setAccess(PrevClassTemplate->getAccess());
1153 }
John McCall27b5c252009-09-14 21:59:20 +00001154
Richard Smith64017682013-07-17 23:53:16 +00001155 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001156
John McCall27b5c252009-09-14 21:59:20 +00001157 // Friend templates are visible in fairly strange ways.
1158 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001159 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001160 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001161 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1162 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001163 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001166 FriendDecl *Friend = FriendDecl::Create(
1167 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001168 Friend->setAccess(AS_public);
1169 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001170 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001171
Douglas Gregordba32632009-02-10 19:49:53 +00001172 if (Invalid) {
1173 NewTemplate->setInvalidDecl();
1174 NewClass->setInvalidDecl();
1175 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001176
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001177 ActOnDocumentableDecl(NewTemplate);
1178
John McCall48871652010-08-21 09:40:31 +00001179 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001180}
1181
Douglas Gregored5731f2009-11-25 17:50:39 +00001182/// \brief Diagnose the presence of a default template argument on a
1183/// template parameter, which is ill-formed in certain contexts.
1184///
1185/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001187 Sema::TemplateParamListContext TPC,
1188 SourceLocation ParamLoc,
1189 SourceRange DefArgRange) {
1190 switch (TPC) {
1191 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001192 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001193 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001194 return false;
1195
1196 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001197 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001198 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001199 // A default template-argument shall not be specified in a
1200 // function template declaration or a function template
1201 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001202 // If a friend function template declaration specifies a default
1203 // template-argument, that declaration shall be a definition and shall be
1204 // the only declaration of the function template in the translation unit.
1205 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001206 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001207 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1208 : diag::ext_template_parameter_default_in_function_template)
1209 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001210 return false;
1211
1212 case Sema::TPC_ClassTemplateMember:
1213 // C++0x [temp.param]p9:
1214 // A default template-argument shall not be specified in the
1215 // template-parameter-lists of the definition of a member of a
1216 // class template that appears outside of the member's class.
1217 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1218 << DefArgRange;
1219 return true;
1220
David Majnemerba8f17a2013-06-25 22:08:55 +00001221 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001222 case Sema::TPC_FriendFunctionTemplate:
1223 // C++ [temp.param]p9:
1224 // A default template-argument shall not be specified in a
1225 // friend template declaration.
1226 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1227 << DefArgRange;
1228 return true;
1229
1230 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1231 // for friend function templates if there is only a single
1232 // declaration (and it is a definition). Strange!
1233 }
1234
David Blaikie8a40f702012-01-17 06:56:22 +00001235 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001236}
1237
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001238/// \brief Check for unexpanded parameter packs within the template parameters
1239/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001240static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1241 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001242 // A template template parameter which is a parameter pack is also a pack
1243 // expansion.
1244 if (TTP->isParameterPack())
1245 return false;
1246
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001247 TemplateParameterList *Params = TTP->getTemplateParameters();
1248 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1249 NamedDecl *P = Params->getParam(I);
1250 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001251 if (!NTTP->isParameterPack() &&
1252 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001253 NTTP->getTypeSourceInfo(),
1254 Sema::UPPC_NonTypeTemplateParameterType))
1255 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001256
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001257 continue;
1258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001259
1260 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001261 = dyn_cast<TemplateTemplateParmDecl>(P))
1262 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1263 return true;
1264 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001266 return false;
1267}
1268
Douglas Gregordba32632009-02-10 19:49:53 +00001269/// \brief Checks the validity of a template parameter list, possibly
1270/// considering the template parameter list from a previous
1271/// declaration.
1272///
1273/// If an "old" template parameter list is provided, it must be
1274/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1275/// template parameter list.
1276///
1277/// \param NewParams Template parameter list for a new template
1278/// declaration. This template parameter list will be updated with any
1279/// default arguments that are carried through from the previous
1280/// template parameter list.
1281///
1282/// \param OldParams If provided, template parameter list from a
1283/// previous declaration of the same template. Default template
1284/// arguments will be merged from the old template parameter list to
1285/// the new template parameter list.
1286///
Douglas Gregored5731f2009-11-25 17:50:39 +00001287/// \param TPC Describes the context in which we are checking the given
1288/// template parameter list.
1289///
Douglas Gregordba32632009-02-10 19:49:53 +00001290/// \returns true if an error occurred, false otherwise.
1291bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001292 TemplateParameterList *OldParams,
1293 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001294 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001295
Douglas Gregordba32632009-02-10 19:49:53 +00001296 // C++ [temp.param]p10:
1297 // The set of default template-arguments available for use with a
1298 // template declaration or definition is obtained by merging the
1299 // default arguments from the definition (if in scope) and all
1300 // declarations in scope in the same way default function
1301 // arguments are (8.3.6).
1302 bool SawDefaultArgument = false;
1303 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001304
Mike Stumpc89c8e32009-02-11 23:03:27 +00001305 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001306 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001307 if (OldParams)
1308 OldParam = OldParams->begin();
1309
Douglas Gregor0693def2011-01-27 01:40:17 +00001310 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001311 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1312 NewParamEnd = NewParams->end();
1313 NewParam != NewParamEnd; ++NewParam) {
1314 // Variables used to diagnose redundant default arguments
1315 bool RedundantDefaultArg = false;
1316 SourceLocation OldDefaultLoc;
1317 SourceLocation NewDefaultLoc;
1318
David Blaikie651c73c2011-10-19 05:19:50 +00001319 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001320 bool MissingDefaultArg = false;
1321
David Blaikie651c73c2011-10-19 05:19:50 +00001322 // Variable used to diagnose non-final parameter packs
1323 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001324
Douglas Gregordba32632009-02-10 19:49:53 +00001325 if (TemplateTypeParmDecl *NewTypeParm
1326 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001327 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328 if (NewTypeParm->hasDefaultArgument() &&
1329 DiagnoseDefaultTemplateArgument(*this, TPC,
1330 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001331 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001332 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001333 NewTypeParm->removeDefaultArgument();
1334
1335 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001336 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001337 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001338 if (NewTypeParm->isParameterPack()) {
1339 assert(!NewTypeParm->hasDefaultArgument() &&
1340 "Parameter packs can't have a default argument!");
1341 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001342 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001343 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001344 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1345 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1346 SawDefaultArgument = true;
1347 RedundantDefaultArg = true;
1348 PreviousDefaultArgLoc = NewDefaultLoc;
1349 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1350 // Merge the default argument from the old declaration to the
1351 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001352 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001353 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1354 } else if (NewTypeParm->hasDefaultArgument()) {
1355 SawDefaultArgument = true;
1356 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1357 } else if (SawDefaultArgument)
1358 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001359 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001360 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001361 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001362 if (!NewNonTypeParm->isParameterPack() &&
1363 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001365 UPPC_NonTypeTemplateParameterType)) {
1366 Invalid = true;
1367 continue;
1368 }
1369
Douglas Gregored5731f2009-11-25 17:50:39 +00001370 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001371 if (NewNonTypeParm->hasDefaultArgument() &&
1372 DiagnoseDefaultTemplateArgument(*this, TPC,
1373 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001374 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001375 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001376 }
1377
Mike Stump12b8ce12009-08-04 21:02:39 +00001378 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001379 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001380 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001381 if (NewNonTypeParm->isParameterPack()) {
1382 assert(!NewNonTypeParm->hasDefaultArgument() &&
1383 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001384 if (!NewNonTypeParm->isPackExpansion())
1385 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001386 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001387 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001388 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1389 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1390 SawDefaultArgument = true;
1391 RedundantDefaultArg = true;
1392 PreviousDefaultArgLoc = NewDefaultLoc;
1393 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1394 // Merge the default argument from the old declaration to the
1395 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001396 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001397 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1398 } else if (NewNonTypeParm->hasDefaultArgument()) {
1399 SawDefaultArgument = true;
1400 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1401 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001402 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001403 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001404 TemplateTemplateParmDecl *NewTemplateParm
1405 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001406
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001407 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001408 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001409 Invalid = true;
1410 continue;
1411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001412
David Blaikie651c73c2011-10-19 05:19:50 +00001413 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414 if (NewTemplateParm->hasDefaultArgument() &&
1415 DiagnoseDefaultTemplateArgument(*this, TPC,
1416 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001417 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001418 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001419
1420 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001421 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001422 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001423 if (NewTemplateParm->isParameterPack()) {
1424 assert(!NewTemplateParm->hasDefaultArgument() &&
1425 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001426 if (!NewTemplateParm->isPackExpansion())
1427 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001428 } else if (OldTemplateParm &&
1429 hasVisibleDefaultArgument(OldTemplateParm) &&
1430 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001431 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1432 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001433 SawDefaultArgument = true;
1434 RedundantDefaultArg = true;
1435 PreviousDefaultArgLoc = NewDefaultLoc;
1436 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1437 // Merge the default argument from the old declaration to the
1438 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001439 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001440 PreviousDefaultArgLoc
1441 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001442 } else if (NewTemplateParm->hasDefaultArgument()) {
1443 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001444 PreviousDefaultArgLoc
1445 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001446 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001447 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001448 }
1449
Richard Smith1fde8ec2012-09-07 02:06:42 +00001450 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001451 // If a template parameter of a primary class template or alias template
1452 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001453 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001454 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1455 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001456 Diag((*NewParam)->getLocation(),
1457 diag::err_template_param_pack_must_be_last_template_parameter);
1458 Invalid = true;
1459 }
1460
Douglas Gregordba32632009-02-10 19:49:53 +00001461 if (RedundantDefaultArg) {
1462 // C++ [temp.param]p12:
1463 // A template-parameter shall not be given default arguments
1464 // by two different declarations in the same scope.
1465 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1466 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1467 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001468 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001469 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 // If a template-parameter of a class template has a default
1471 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001472 // have a default template-argument supplied or be a template parameter
1473 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001474 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001475 diag::err_template_param_default_arg_missing);
1476 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1477 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001478 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001479 }
1480
1481 // If we have an old template parameter list that we're merging
1482 // in, move on to the next parameter.
1483 if (OldParams)
1484 ++OldParam;
1485 }
1486
Douglas Gregor0693def2011-01-27 01:40:17 +00001487 // We were missing some default arguments at the end of the list, so remove
1488 // all of the default arguments.
1489 if (RemoveDefaultArguments) {
1490 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1491 NewParamEnd = NewParams->end();
1492 NewParam != NewParamEnd; ++NewParam) {
1493 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1494 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001496 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1497 NTTP->removeDefaultArgument();
1498 else
1499 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1500 }
1501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001502
Douglas Gregordba32632009-02-10 19:49:53 +00001503 return Invalid;
1504}
Douglas Gregord32e0282009-02-09 23:23:08 +00001505
John McCalla020a012010-10-20 05:44:58 +00001506namespace {
1507
1508/// A class which looks for a use of a certain level of template
1509/// parameter.
1510struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1511 typedef RecursiveASTVisitor<DependencyChecker> super;
1512
1513 unsigned Depth;
1514 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001515 SourceLocation MatchLoc;
1516
1517 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001518
1519 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1520 NamedDecl *ND = Params->getParam(0);
1521 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1522 Depth = PD->getDepth();
1523 } else if (NonTypeTemplateParmDecl *PD =
1524 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1525 Depth = PD->getDepth();
1526 } else {
1527 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1528 }
1529 }
1530
Richard Smith6056d5e2014-02-09 00:54:43 +00001531 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001532 if (ParmDepth >= Depth) {
1533 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001534 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001535 return true;
1536 }
1537 return false;
1538 }
1539
Richard Smith6056d5e2014-02-09 00:54:43 +00001540 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1541 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1542 }
1543
John McCalla020a012010-10-20 05:44:58 +00001544 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1545 return !Matches(T->getDepth());
1546 }
1547
1548 bool TraverseTemplateName(TemplateName N) {
1549 if (TemplateTemplateParmDecl *PD =
1550 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001551 if (Matches(PD->getDepth()))
1552 return false;
John McCalla020a012010-10-20 05:44:58 +00001553 return super::TraverseTemplateName(N);
1554 }
1555
1556 bool VisitDeclRefExpr(DeclRefExpr *E) {
1557 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001558 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1559 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001560 return false;
John McCalla020a012010-10-20 05:44:58 +00001561 return super::VisitDeclRefExpr(E);
1562 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001563
1564 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1565 return TraverseType(T->getReplacementType());
1566 }
1567
1568 bool
1569 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1570 return TraverseTemplateArgument(T->getArgumentPack());
1571 }
1572
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001573 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1574 return TraverseType(T->getInjectedSpecializationType());
1575 }
John McCalla020a012010-10-20 05:44:58 +00001576};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001577}
John McCalla020a012010-10-20 05:44:58 +00001578
Douglas Gregor972fe532011-05-10 18:27:06 +00001579/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001580/// list.
1581static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001582DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001583 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001584 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001585 return Checker.Match;
1586}
1587
Douglas Gregor972fe532011-05-10 18:27:06 +00001588// Find the source range corresponding to the named type in the given
1589// nested-name-specifier, if any.
1590static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1591 QualType T,
1592 const CXXScopeSpec &SS) {
1593 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1594 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1595 if (const Type *CurType = NNS->getAsType()) {
1596 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1597 return NNSLoc.getTypeLoc().getSourceRange();
1598 } else
1599 break;
1600
1601 NNSLoc = NNSLoc.getPrefix();
1602 }
1603
1604 return SourceRange();
1605}
1606
Mike Stump11289f42009-09-09 15:08:12 +00001607/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001608/// specifier, returning the template parameter list that applies to the
1609/// name.
1610///
1611/// \param DeclStartLoc the start of the declaration that has a scope
1612/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001613///
Douglas Gregor972fe532011-05-10 18:27:06 +00001614/// \param DeclLoc The location of the declaration itself.
1615///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001616/// \param SS the scope specifier that will be matched to the given template
1617/// parameter lists. This scope specifier precedes a qualified name that is
1618/// being declared.
1619///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001620/// \param TemplateId The template-id following the scope specifier, if there
1621/// is one. Used to check for a missing 'template<>'.
1622///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001623/// \param ParamLists the template parameter lists, from the outermost to the
1624/// innermost template parameter lists.
1625///
John McCalle820e5e2010-04-13 20:37:33 +00001626/// \param IsFriend Whether to apply the slightly different rules for
1627/// matching template parameters to scope specifiers in friend
1628/// declarations.
1629///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001630/// \param IsExplicitSpecialization will be set true if the entity being
1631/// declared is an explicit specialization, false otherwise.
1632///
Mike Stump11289f42009-09-09 15:08:12 +00001633/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001634/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001635/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001636/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001637/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001638/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001639TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1640 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001641 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001642 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1643 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001644 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001645 Invalid = false;
1646
1647 // The sequence of nested types to which we will match up the template
1648 // parameter lists. We first build this list by starting with the type named
1649 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001650 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001651 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001652 if (SS.getScopeRep()) {
1653 if (CXXRecordDecl *Record
1654 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1655 T = Context.getTypeDeclType(Record);
1656 else
1657 T = QualType(SS.getScopeRep()->getAsType(), 0);
1658 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001659
1660 // If we found an explicit specialization that prevents us from needing
1661 // 'template<>' headers, this will be set to the location of that
1662 // explicit specialization.
1663 SourceLocation ExplicitSpecLoc;
1664
1665 while (!T.isNull()) {
1666 NestedTypes.push_back(T);
1667
1668 // Retrieve the parent of a record type.
1669 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1670 // If this type is an explicit specialization, we're done.
1671 if (ClassTemplateSpecializationDecl *Spec
1672 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1673 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1674 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1675 ExplicitSpecLoc = Spec->getLocation();
1676 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001677 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001678 } else if (Record->getTemplateSpecializationKind()
1679 == TSK_ExplicitSpecialization) {
1680 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001681 break;
1682 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001683
1684 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1685 T = Context.getTypeDeclType(Parent);
1686 else
1687 T = QualType();
1688 continue;
1689 }
1690
1691 if (const TemplateSpecializationType *TST
1692 = T->getAs<TemplateSpecializationType>()) {
1693 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1694 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1695 T = Context.getTypeDeclType(Parent);
1696 else
1697 T = QualType();
1698 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001699 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001700 }
1701
1702 // Look one step prior in a dependent template specialization type.
1703 if (const DependentTemplateSpecializationType *DependentTST
1704 = T->getAs<DependentTemplateSpecializationType>()) {
1705 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1706 T = QualType(NNS->getAsType(), 0);
1707 else
1708 T = QualType();
1709 continue;
1710 }
1711
1712 // Look one step prior in a dependent name type.
1713 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1714 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1715 T = QualType(NNS->getAsType(), 0);
1716 else
1717 T = QualType();
1718 continue;
1719 }
1720
1721 // Retrieve the parent of an enumeration type.
1722 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1723 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1724 // check here.
1725 EnumDecl *Enum = EnumT->getDecl();
1726
1727 // Get to the parent type.
1728 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1729 T = Context.getTypeDeclType(Parent);
1730 else
1731 T = QualType();
1732 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001733 }
Mike Stump11289f42009-09-09 15:08:12 +00001734
Douglas Gregor972fe532011-05-10 18:27:06 +00001735 T = QualType();
1736 }
1737 // Reverse the nested types list, since we want to traverse from the outermost
1738 // to the innermost while checking template-parameter-lists.
1739 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001740
Douglas Gregor972fe532011-05-10 18:27:06 +00001741 // C++0x [temp.expl.spec]p17:
1742 // A member or a member template may be nested within many
1743 // enclosing class templates. In an explicit specialization for
1744 // such a member, the member declaration shall be preceded by a
1745 // template<> for each enclosing class template that is
1746 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001747 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001748
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001749 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001750 if (SawNonEmptyTemplateParameterList) {
1751 Diag(DeclLoc, diag::err_specialize_member_of_template)
1752 << !Recovery << Range;
1753 Invalid = true;
1754 IsExplicitSpecialization = false;
1755 return true;
1756 }
1757
1758 return false;
1759 };
1760
1761 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1762 // Check that we can have an explicit specialization here.
1763 if (CheckExplicitSpecialization(Range, true))
1764 return true;
1765
1766 // We don't have a template header, but we should.
1767 SourceLocation ExpectedTemplateLoc;
1768 if (!ParamLists.empty())
1769 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1770 else
1771 ExpectedTemplateLoc = DeclStartLoc;
1772
1773 Diag(DeclLoc, diag::err_template_spec_needs_header)
1774 << Range
1775 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1776 return false;
1777 };
1778
Douglas Gregor972fe532011-05-10 18:27:06 +00001779 unsigned ParamIdx = 0;
1780 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1781 ++TypeIdx) {
1782 T = NestedTypes[TypeIdx];
1783
1784 // Whether we expect a 'template<>' header.
1785 bool NeedEmptyTemplateHeader = false;
1786
1787 // Whether we expect a template header with parameters.
1788 bool NeedNonemptyTemplateHeader = false;
1789
1790 // For a dependent type, the set of template parameters that we
1791 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001792 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001793
Douglas Gregor373af9b2011-05-11 23:26:17 +00001794 // C++0x [temp.expl.spec]p15:
1795 // A member or a member template may be nested within many enclosing
1796 // class templates. In an explicit specialization for such a member, the
1797 // member declaration shall be preceded by a template<> for each
1798 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001799 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1800 if (ClassTemplatePartialSpecializationDecl *Partial
1801 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1802 ExpectedTemplateParams = Partial->getTemplateParameters();
1803 NeedNonemptyTemplateHeader = true;
1804 } else if (Record->isDependentType()) {
1805 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001806 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001807 ->getTemplateParameters();
1808 NeedNonemptyTemplateHeader = true;
1809 }
1810 } else if (ClassTemplateSpecializationDecl *Spec
1811 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1812 // C++0x [temp.expl.spec]p4:
1813 // Members of an explicitly specialized class template are defined
1814 // in the same manner as members of normal classes, and not using
1815 // the template<> syntax.
1816 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1817 NeedEmptyTemplateHeader = true;
1818 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001819 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001820 } else if (Record->getTemplateSpecializationKind()) {
1821 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001822 != TSK_ExplicitSpecialization &&
1823 TypeIdx == NumTypes - 1)
1824 IsExplicitSpecialization = true;
1825
1826 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001827 }
1828 } else if (const TemplateSpecializationType *TST
1829 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001830 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001831 ExpectedTemplateParams = Template->getTemplateParameters();
1832 NeedNonemptyTemplateHeader = true;
1833 }
1834 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1835 // FIXME: We actually could/should check the template arguments here
1836 // against the corresponding template parameter list.
1837 NeedNonemptyTemplateHeader = false;
1838 }
1839
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001840 // C++ [temp.expl.spec]p16:
1841 // In an explicit specialization declaration for a member of a class
1842 // template or a member template that ap- pears in namespace scope, the
1843 // member template and some of its enclosing class templates may remain
1844 // unspecialized, except that the declaration shall not explicitly
1845 // specialize a class member template if its en- closing class templates
1846 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001847 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001848 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001849 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1850 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001851 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001852 } else
1853 SawNonEmptyTemplateParameterList = true;
1854 }
1855
Douglas Gregor972fe532011-05-10 18:27:06 +00001856 if (NeedEmptyTemplateHeader) {
1857 // If we're on the last of the types, and we need a 'template<>' header
1858 // here, then it's an explicit specialization.
1859 if (TypeIdx == NumTypes - 1)
1860 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001861
1862 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001863 if (ParamLists[ParamIdx]->size() > 0) {
1864 // The header has template parameters when it shouldn't. Complain.
1865 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1866 diag::err_template_param_list_matches_nontemplate)
1867 << T
1868 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1869 ParamLists[ParamIdx]->getRAngleLoc())
1870 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1871 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001872 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001873 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001874
Douglas Gregor972fe532011-05-10 18:27:06 +00001875 // Consume this template header.
1876 ++ParamIdx;
1877 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001878 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001879
1880 if (!IsFriend)
1881 if (DiagnoseMissingExplicitSpecialization(
1882 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001883 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001884
Douglas Gregor972fe532011-05-10 18:27:06 +00001885 continue;
1886 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001887
Douglas Gregor972fe532011-05-10 18:27:06 +00001888 if (NeedNonemptyTemplateHeader) {
1889 // In friend declarations we can have template-ids which don't
1890 // depend on the corresponding template parameter lists. But
1891 // assume that empty parameter lists are supposed to match this
1892 // template-id.
1893 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001894 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001895 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001896 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001897 else
1898 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001899 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001900
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001901 if (ParamIdx < ParamLists.size()) {
1902 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001903 if (ExpectedTemplateParams &&
1904 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1905 ExpectedTemplateParams,
1906 true, TPL_TemplateMatch))
1907 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001908
Douglas Gregor972fe532011-05-10 18:27:06 +00001909 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001910 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001911 TPC_ClassTemplateMember))
1912 Invalid = true;
1913
1914 ++ParamIdx;
1915 continue;
1916 }
1917
1918 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1919 << T
1920 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1921 Invalid = true;
1922 continue;
1923 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001924 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001925
Douglas Gregord8d297c2009-07-21 23:53:31 +00001926 // If there were at least as many template-ids as there were template
1927 // parameter lists, then there are no template parameter lists remaining for
1928 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001929 if (ParamIdx >= ParamLists.size()) {
1930 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001931 // We don't have a template header for the declaration itself, but we
1932 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001933 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001934 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1935 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001936
1937 // Fabricate an empty template parameter list for the invented header.
1938 return TemplateParameterList::Create(Context, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001939 SourceLocation(), nullptr, 0,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001940 SourceLocation());
1941 }
1942
Craig Topperc3ec1492014-05-26 06:22:03 +00001943 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
Douglas Gregord8d297c2009-07-21 23:53:31 +00001946 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001947 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001948 bool HasAnyExplicitSpecHeader = false;
1949 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001950 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001951 if (ParamLists[I]->size() == 0)
1952 HasAnyExplicitSpecHeader = true;
1953 else
1954 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001955 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001956
Douglas Gregor972fe532011-05-10 18:27:06 +00001957 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001958 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1959 : diag::err_template_spec_extra_headers)
1960 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1961 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001962
1963 // If there was a specialization somewhere, such that 'template<>' is
1964 // not required, and there were any 'template<>' headers, note where the
1965 // specialization occurred.
1966 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1967 Diag(ExplicitSpecLoc,
1968 diag::note_explicit_template_spec_does_not_need_header)
1969 << NestedTypes.back();
1970
1971 // We have a template parameter list with no corresponding scope, which
1972 // means that the resulting template declaration can't be instantiated
1973 // properly (we'll end up with dependent nodes when we shouldn't).
1974 if (!AllExplicitSpecHeaders)
1975 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001976 }
Mike Stump11289f42009-09-09 15:08:12 +00001977
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001978 // C++ [temp.expl.spec]p16:
1979 // In an explicit specialization declaration for a member of a class
1980 // template or a member template that ap- pears in namespace scope, the
1981 // member template and some of its enclosing class templates may remain
1982 // unspecialized, except that the declaration shall not explicitly
1983 // specialize a class member template if its en- closing class templates
1984 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001985 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001986 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1987 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001988 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001989
Douglas Gregord8d297c2009-07-21 23:53:31 +00001990 // Return the last template parameter list, which corresponds to the
1991 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001992 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001993}
1994
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001995void Sema::NoteAllFoundTemplates(TemplateName Name) {
1996 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1997 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001998 << (isa<FunctionTemplateDecl>(Template)
1999 ? 0
2000 : isa<ClassTemplateDecl>(Template)
2001 ? 1
2002 : isa<VarTemplateDecl>(Template)
2003 ? 2
2004 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2005 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002006 return;
2007 }
2008
2009 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2010 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2011 IEnd = OST->end();
2012 I != IEnd; ++I)
2013 Diag((*I)->getLocation(), diag::note_template_declared_here)
2014 << 0 << (*I)->getDeclName();
2015
2016 return;
2017 }
2018}
2019
Douglas Gregordc572a32009-03-30 22:58:21 +00002020QualType Sema::CheckTemplateIdType(TemplateName Name,
2021 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002022 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002023 DependentTemplateName *DTN
2024 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002025 if (DTN && DTN->isIdentifier())
2026 // When building a template-id where the template-name is dependent,
2027 // assume the template is a type template. Either our assumption is
2028 // correct, or the code is ill-formed and will be diagnosed when the
2029 // dependent name is substituted.
2030 return Context.getDependentTemplateSpecializationType(ETK_None,
2031 DTN->getQualifier(),
2032 DTN->getIdentifier(),
2033 TemplateArgs);
2034
Douglas Gregordc572a32009-03-30 22:58:21 +00002035 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002036 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2037 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002038 // We might have a substituted template template parameter pack. If so,
2039 // build a template specialization type for it.
2040 if (Name.getAsSubstTemplateTemplateParmPack())
2041 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002042
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002043 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2044 << Name;
2045 NoteAllFoundTemplates(Name);
2046 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002047 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002048
Douglas Gregorc40290e2009-03-09 23:48:35 +00002049 // Check that the template argument list is well-formed for this
2050 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002051 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002052 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002053 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002054 return QualType();
2055
Douglas Gregorc40290e2009-03-09 23:48:35 +00002056 QualType CanonType;
2057
Douglas Gregor678d76c2011-07-01 01:22:09 +00002058 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002059 if (TypeAliasTemplateDecl *AliasTemplate =
2060 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002061 // Find the canonical type for this type alias template specialization.
2062 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2063 if (Pattern->isInvalidDecl())
2064 return QualType();
2065
2066 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2067 Converted.data(), Converted.size());
2068
2069 // Only substitute for the innermost template argument list.
2070 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002071 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002072 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2073 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002074 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002075
Richard Smith802c4b72012-08-23 06:16:52 +00002076 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002077 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002078 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002079 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002080
Richard Smith3f1b5d02011-05-05 21:57:07 +00002081 CanonType = SubstType(Pattern->getUnderlyingType(),
2082 TemplateArgLists, AliasTemplate->getLocation(),
2083 AliasTemplate->getDeclName());
2084 if (CanonType.isNull())
2085 return QualType();
2086 } else if (Name.isDependent() ||
2087 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002088 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002089 // This class template specialization is a dependent
2090 // type. Therefore, its canonical type is another class template
2091 // specialization type that contains all of the converted
2092 // arguments in canonical form. This ensures that, e.g., A<T> and
2093 // A<T, T> have identical types when A is declared as:
2094 //
2095 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002096 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002097 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002098 Converted.data(),
2099 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002100
Douglas Gregora8e02e72009-07-28 23:00:59 +00002101 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002102 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002103 // In the future, we need to teach getTemplateSpecializationType to only
2104 // build the canonical type and return that to us.
2105 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002106
2107 // This might work out to be a current instantiation, in which
2108 // case the canonical type needs to be the InjectedClassNameType.
2109 //
2110 // TODO: in theory this could be a simple hashtable lookup; most
2111 // changes to CurContext don't change the set of current
2112 // instantiations.
2113 if (isa<ClassTemplateDecl>(Template)) {
2114 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2115 // If we get out to a namespace, we're done.
2116 if (Ctx->isFileContext()) break;
2117
2118 // If this isn't a record, keep looking.
2119 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2120 if (!Record) continue;
2121
2122 // Look for one of the two cases with InjectedClassNameTypes
2123 // and check whether it's the same template.
2124 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2125 !Record->getDescribedClassTemplate())
2126 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127
John McCall2408e322010-04-27 00:57:59 +00002128 // Fetch the injected class name type and check whether its
2129 // injected type is equal to the type we just built.
2130 QualType ICNT = Context.getTypeDeclType(Record);
2131 QualType Injected = cast<InjectedClassNameType>(ICNT)
2132 ->getInjectedSpecializationType();
2133
2134 if (CanonType != Injected->getCanonicalTypeInternal())
2135 continue;
2136
2137 // If so, the canonical type of this TST is the injected
2138 // class name type of the record we just found.
2139 assert(ICNT.isCanonical());
2140 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002141 break;
2142 }
2143 }
Mike Stump11289f42009-09-09 15:08:12 +00002144 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002145 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002146 // Find the class template specialization declaration that
2147 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002148 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002149 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002150 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002151 if (!Decl) {
2152 // This is the first time we have referenced this class template
2153 // specialization. Create the canonical declaration and add it to
2154 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002155 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002156 ClassTemplate->getTemplatedDecl()->getTagKind(),
2157 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002158 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002159 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002160 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002161 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002162 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002163 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002164 if (ClassTemplate->isOutOfLine())
2165 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002166 }
2167
Chandler Carruth2acfb222013-09-27 22:14:40 +00002168 // Diagnose uses of this specialization.
2169 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2170
Douglas Gregorc40290e2009-03-09 23:48:35 +00002171 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002172 assert(isa<RecordType>(CanonType) &&
2173 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00002174 }
Mike Stump11289f42009-09-09 15:08:12 +00002175
Douglas Gregorc40290e2009-03-09 23:48:35 +00002176 // Build the fully-sugared type for this class template
2177 // specialization, which refers back to the class template
2178 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002179 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002180}
2181
John McCallfaf5fb42010-08-26 23:41:50 +00002182TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002183Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002184 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002185 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002186 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002187 SourceLocation RAngleLoc,
2188 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002189 if (SS.isInvalid())
2190 return true;
2191
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002192 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002193
Douglas Gregorc40290e2009-03-09 23:48:35 +00002194 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002195 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002196 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002197
Douglas Gregor5a064722011-02-28 17:23:35 +00002198 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002199 QualType T
2200 = Context.getDependentTemplateSpecializationType(ETK_None,
2201 DTN->getQualifier(),
2202 DTN->getIdentifier(),
2203 TemplateArgs);
2204 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002205 TypeLocBuilder TLB;
2206 DependentTemplateSpecializationTypeLoc SpecTL
2207 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002208 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2209 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002210 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002211 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002212 SpecTL.setLAngleLoc(LAngleLoc);
2213 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002214 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2215 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2216 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2217 }
2218
John McCall6b51f282009-11-23 01:53:49 +00002219 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002220
2221 if (Result.isNull())
2222 return true;
2223
Douglas Gregore7c20652011-03-02 00:47:37 +00002224 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002225 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002226 TemplateSpecializationTypeLoc SpecTL
2227 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002228 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002229 SpecTL.setTemplateNameLoc(TemplateLoc);
2230 SpecTL.setLAngleLoc(LAngleLoc);
2231 SpecTL.setRAngleLoc(RAngleLoc);
2232 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2233 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002234
Abramo Bagnara4244b432012-01-27 08:46:19 +00002235 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2236 // constructor or destructor name (in such a case, the scope specifier
2237 // will be attached to the enclosing Decl or Expr node).
2238 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002239 // Create an elaborated-type-specifier containing the nested-name-specifier.
2240 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2241 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002242 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002243 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2244 }
2245
2246 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002247}
John McCall06f6fe8d2009-09-04 01:14:41 +00002248
Douglas Gregore7c20652011-03-02 00:47:37 +00002249TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002250 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002251 SourceLocation TagLoc,
2252 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002253 SourceLocation TemplateKWLoc,
2254 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002255 SourceLocation TemplateLoc,
2256 SourceLocation LAngleLoc,
2257 ASTTemplateArgsPtr TemplateArgsIn,
2258 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002259 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002260
2261 // Translate the parser's template argument list in our AST format.
2262 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2263 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2264
2265 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002266 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002267 ElaboratedTypeKeyword Keyword
2268 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002269
Douglas Gregore7c20652011-03-02 00:47:37 +00002270 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2271 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2272 DTN->getQualifier(),
2273 DTN->getIdentifier(),
2274 TemplateArgs);
2275
2276 // Build type-source information.
2277 TypeLocBuilder TLB;
2278 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002279 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2280 SpecTL.setElaboratedKeywordLoc(TagLoc);
2281 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002282 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002283 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002284 SpecTL.setLAngleLoc(LAngleLoc);
2285 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002286 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2287 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2288 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2289 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002290
2291 if (TypeAliasTemplateDecl *TAT =
2292 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2293 // C++0x [dcl.type.elab]p2:
2294 // If the identifier resolves to a typedef-name or the simple-template-id
2295 // resolves to an alias template specialization, the
2296 // elaborated-type-specifier is ill-formed.
2297 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2298 Diag(TAT->getLocation(), diag::note_declared_at);
2299 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002300
2301 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2302 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002303 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002304
2305 // Check the tag kind
2306 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002307 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002308
John McCalld8fe9af2009-09-08 17:47:29 +00002309 IdentifierInfo *Id = D->getIdentifier();
2310 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002311
Richard Trieucaa33d32011-06-10 03:11:26 +00002312 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00002313 TagLoc, Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002314 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002315 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002316 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002317 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002318 }
2319 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002320
Douglas Gregore7c20652011-03-02 00:47:37 +00002321 // Provide source-location information for the template specialization.
2322 TypeLocBuilder TLB;
2323 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 McCall06f6fe8d2009-09-04 01:14:41 +00002331
Douglas Gregore7c20652011-03-02 00:47:37 +00002332 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002333 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002334 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2335 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002336 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002337 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2338 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002339}
2340
Larisse Voufo39a1e502013-08-06 01:03:05 +00002341static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002342 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2343 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002344
2345static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2346 NamedDecl *PrevDecl,
2347 SourceLocation Loc,
2348 bool IsPartialSpecialization);
2349
2350static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002351
Richard Smith300e0c32013-09-24 04:49:23 +00002352static bool isTemplateArgumentTemplateParameter(
2353 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2354 switch (Arg.getKind()) {
2355 case TemplateArgument::Null:
2356 case TemplateArgument::NullPtr:
2357 case TemplateArgument::Integral:
2358 case TemplateArgument::Declaration:
2359 case TemplateArgument::Pack:
2360 case TemplateArgument::TemplateExpansion:
2361 return false;
2362
2363 case TemplateArgument::Type: {
2364 QualType Type = Arg.getAsType();
2365 const TemplateTypeParmType *TPT =
2366 Arg.getAsType()->getAs<TemplateTypeParmType>();
2367 return TPT && !Type.hasQualifiers() &&
2368 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2369 }
2370
2371 case TemplateArgument::Expression: {
2372 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2373 if (!DRE || !DRE->getDecl())
2374 return false;
2375 const NonTypeTemplateParmDecl *NTTP =
2376 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2377 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2378 }
2379
2380 case TemplateArgument::Template:
2381 const TemplateTemplateParmDecl *TTP =
2382 dyn_cast_or_null<TemplateTemplateParmDecl>(
2383 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2384 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2385 }
2386 llvm_unreachable("unexpected kind of template argument");
2387}
2388
2389static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2390 ArrayRef<TemplateArgument> Args) {
2391 if (Params->size() != Args.size())
2392 return false;
2393
2394 unsigned Depth = Params->getDepth();
2395
2396 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2397 TemplateArgument Arg = Args[I];
2398
2399 // If the parameter is a pack expansion, the argument must be a pack
2400 // whose only element is a pack expansion.
2401 if (Params->getParam(I)->isParameterPack()) {
2402 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2403 !Arg.pack_begin()->isPackExpansion())
2404 return false;
2405 Arg = Arg.pack_begin()->getPackExpansionPattern();
2406 }
2407
2408 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2409 return false;
2410 }
2411
2412 return true;
2413}
2414
Richard Smith4b55a9c2014-04-17 03:29:33 +00002415/// Convert the parser's template argument list representation into our form.
2416static TemplateArgumentListInfo
2417makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2418 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2419 TemplateId.RAngleLoc);
2420 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2421 TemplateId.NumArgs);
2422 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2423 return TemplateArgs;
2424}
2425
Larisse Voufo39a1e502013-08-06 01:03:05 +00002426DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002427 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002428 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002429 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002430 // D must be variable template id.
2431 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2432 "Variable template specialization is declared with a template it.");
2433
2434 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002435 TemplateArgumentListInfo TemplateArgs =
2436 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002437 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2438 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2439 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002440
Richard Smithbeef3452014-01-16 23:39:20 +00002441 TemplateName Name = TemplateId->Template.get();
2442
2443 // The template-id must name a variable template.
2444 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002445 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2446 if (!VarTemplate) {
2447 NamedDecl *FnTemplate;
2448 if (auto *OTS = Name.getAsOverloadedTemplate())
2449 FnTemplate = *OTS->begin();
2450 else
2451 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2452 if (FnTemplate)
2453 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2454 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002455 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2456 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002457 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002458
2459 // Check for unexpanded parameter packs in any of the template arguments.
2460 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2461 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2462 UPPC_PartialSpecialization))
2463 return true;
2464
2465 // Check that the template argument list is well-formed for this
2466 // template.
2467 SmallVector<TemplateArgument, 4> Converted;
2468 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2469 false, Converted))
2470 return true;
2471
2472 // Check that the type of this variable template specialization
2473 // matches the expected type.
2474 TypeSourceInfo *ExpectedDI;
2475 {
2476 // Do substitution on the type of the declaration
2477 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2478 Converted.data(), Converted.size());
2479 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002480 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002481 return true;
2482 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2483 ExpectedDI =
2484 SubstType(Templated->getTypeSourceInfo(),
2485 MultiLevelTemplateArgumentList(TemplateArgList),
2486 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2487 }
2488 if (!ExpectedDI)
2489 return true;
2490
Larisse Voufo39a1e502013-08-06 01:03:05 +00002491 // Find the variable template (partial) specialization declaration that
2492 // corresponds to these arguments.
2493 if (IsPartialSpecialization) {
2494 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002495 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2496 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002497 return true;
2498
2499 bool InstantiationDependent;
2500 if (!Name.isDependent() &&
2501 !TemplateSpecializationType::anyDependentTemplateArguments(
2502 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2503 InstantiationDependent)) {
2504 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2505 << VarTemplate->getDeclName();
2506 IsPartialSpecialization = false;
2507 }
Richard Smith300e0c32013-09-24 04:49:23 +00002508
2509 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2510 Converted)) {
2511 // C++ [temp.class.spec]p9b3:
2512 //
2513 // -- The argument list of the specialization shall not be identical
2514 // to the implicit argument list of the primary template.
2515 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2516 << /*variable template*/ 1
2517 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2518 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2519 // FIXME: Recover from this by treating the declaration as a redeclaration
2520 // of the primary template.
2521 return true;
2522 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002523 }
2524
Craig Topperc3ec1492014-05-26 06:22:03 +00002525 void *InsertPos = nullptr;
2526 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002527
2528 if (IsPartialSpecialization)
2529 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002530 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002531 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002532 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002533
Craig Topperc3ec1492014-05-26 06:22:03 +00002534 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002535
2536 // Check whether we can declare a variable template specialization in
2537 // the current scope.
2538 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2539 TemplateNameLoc,
2540 IsPartialSpecialization))
2541 return true;
2542
2543 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2544 // Since the only prior variable template specialization with these
2545 // arguments was referenced but not declared, reuse that
2546 // declaration node as our own, updating its source location and
2547 // the list of outer template parameters to reflect our new declaration.
2548 Specialization = PrevDecl;
2549 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002550 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002551 } else if (IsPartialSpecialization) {
2552 // Create a new class template partial specialization declaration node.
2553 VarTemplatePartialSpecializationDecl *PrevPartial =
2554 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002555 VarTemplatePartialSpecializationDecl *Partial =
2556 VarTemplatePartialSpecializationDecl::Create(
2557 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2558 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002559 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002560
2561 if (!PrevPartial)
2562 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2563 Specialization = Partial;
2564
2565 // If we are providing an explicit specialization of a member variable
2566 // template specialization, make a note of that.
2567 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002568 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002569
2570 // Check that all of the template parameters of the variable template
2571 // partial specialization are deducible from the template
2572 // arguments. If not, this variable template partial specialization
2573 // will never be used.
2574 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2575 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2576 TemplateParams->getDepth(), DeducibleParams);
2577
2578 if (!DeducibleParams.all()) {
2579 unsigned NumNonDeducible =
2580 DeducibleParams.size() - DeducibleParams.count();
2581 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002582 << /*variable template*/ 1 << (NumNonDeducible > 1)
2583 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002584 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2585 if (!DeducibleParams[I]) {
2586 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2587 if (Param->getDeclName())
2588 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2589 << Param->getDeclName();
2590 else
2591 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002592 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002593 }
2594 }
2595 }
2596 } else {
2597 // Create a new class template specialization declaration node for
2598 // this explicit specialization or friend declaration.
2599 Specialization = VarTemplateSpecializationDecl::Create(
2600 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2601 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2602 Specialization->setTemplateArgsInfo(TemplateArgs);
2603
2604 if (!PrevDecl)
2605 VarTemplate->AddSpecialization(Specialization, InsertPos);
2606 }
2607
2608 // C++ [temp.expl.spec]p6:
2609 // If a template, a member template or the member of a class template is
2610 // explicitly specialized then that specialization shall be declared
2611 // before the first use of that specialization that would cause an implicit
2612 // instantiation to take place, in every translation unit in which such a
2613 // use occurs; no diagnostic is required.
2614 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2615 bool Okay = false;
2616 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2617 // Is there any previous explicit specialization declaration?
2618 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2619 Okay = true;
2620 break;
2621 }
2622 }
2623
2624 if (!Okay) {
2625 SourceRange Range(TemplateNameLoc, RAngleLoc);
2626 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2627 << Name << Range;
2628
2629 Diag(PrevDecl->getPointOfInstantiation(),
2630 diag::note_instantiation_required_here)
2631 << (PrevDecl->getTemplateSpecializationKind() !=
2632 TSK_ImplicitInstantiation);
2633 return true;
2634 }
2635 }
2636
2637 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2638 Specialization->setLexicalDeclContext(CurContext);
2639
2640 // Add the specialization into its lexical context, so that it can
2641 // be seen when iterating through the list of declarations in that
2642 // context. However, specializations are not found by name lookup.
2643 CurContext->addDecl(Specialization);
2644
2645 // Note that this is an explicit specialization.
2646 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2647
2648 if (PrevDecl) {
2649 // Check that this isn't a redefinition of this specialization,
2650 // merging with previous declarations.
2651 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2652 ForRedeclaration);
2653 PrevSpec.addDecl(PrevDecl);
2654 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002655 } else if (Specialization->isStaticDataMember() &&
2656 Specialization->isOutOfLine()) {
2657 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002658 }
2659
2660 // Link instantiations of static data members back to the template from
2661 // which they were instantiated.
2662 if (Specialization->isStaticDataMember())
2663 Specialization->setInstantiationOfStaticDataMember(
2664 VarTemplate->getTemplatedDecl(),
2665 Specialization->getSpecializationKind());
2666
2667 return Specialization;
2668}
2669
2670namespace {
2671/// \brief A partial specialization whose template arguments have matched
2672/// a given template-id.
2673struct PartialSpecMatchResult {
2674 VarTemplatePartialSpecializationDecl *Partial;
2675 TemplateArgumentList *Args;
2676};
2677}
2678
2679DeclResult
2680Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2681 SourceLocation TemplateNameLoc,
2682 const TemplateArgumentListInfo &TemplateArgs) {
2683 assert(Template && "A variable template id without template?");
2684
2685 // Check that the template argument list is well-formed for this template.
2686 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002687 if (CheckTemplateArgumentList(
2688 Template, TemplateNameLoc,
2689 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002690 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002691 return true;
2692
2693 // Find the variable template specialization declaration that
2694 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002695 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002696 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002697 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002698 // If we already have a variable template specialization, return it.
2699 return Spec;
2700
2701 // This is the first time we have referenced this variable template
2702 // specialization. Create the canonical declaration and add it to
2703 // the set of specializations, based on the closest partial specialization
2704 // that it represents. That is,
2705 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2706 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2707 Converted.data(), Converted.size());
2708 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2709 bool AmbiguousPartialSpec = false;
2710 typedef PartialSpecMatchResult MatchResult;
2711 SmallVector<MatchResult, 4> Matched;
2712 SourceLocation PointOfInstantiation = TemplateNameLoc;
2713 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2714
2715 // 1. Attempt to find the closest partial specialization that this
2716 // specializes, if any.
2717 // If any of the template arguments is dependent, then this is probably
2718 // a placeholder for an incomplete declarative context; which must be
2719 // complete by instantiation time. Thus, do not search through the partial
2720 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002721 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2722 // Perhaps better after unification of DeduceTemplateArguments() and
2723 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002724 bool InstantiationDependent = false;
2725 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2726 TemplateArgs, InstantiationDependent)) {
2727
2728 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2729 Template->getPartialSpecializations(PartialSpecs);
2730
2731 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2732 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2733 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2734
2735 if (TemplateDeductionResult Result =
2736 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2737 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002738 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002739 FailedCandidates.addCandidate()
2740 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2741 (void)Result;
2742 } else {
2743 Matched.push_back(PartialSpecMatchResult());
2744 Matched.back().Partial = Partial;
2745 Matched.back().Args = Info.take();
2746 }
2747 }
2748
Larisse Voufo39a1e502013-08-06 01:03:05 +00002749 if (Matched.size() >= 1) {
2750 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2751 if (Matched.size() == 1) {
2752 // -- If exactly one matching specialization is found, the
2753 // instantiation is generated from that specialization.
2754 // We don't need to do anything for this.
2755 } else {
2756 // -- If more than one matching specialization is found, the
2757 // partial order rules (14.5.4.2) are used to determine
2758 // whether one of the specializations is more specialized
2759 // than the others. If none of the specializations is more
2760 // specialized than all of the other matching
2761 // specializations, then the use of the variable template is
2762 // ambiguous and the program is ill-formed.
2763 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2764 PEnd = Matched.end();
2765 P != PEnd; ++P) {
2766 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2767 PointOfInstantiation) ==
2768 P->Partial)
2769 Best = P;
2770 }
2771
2772 // Determine if the best partial specialization is more specialized than
2773 // the others.
2774 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2775 PEnd = Matched.end();
2776 P != PEnd; ++P) {
2777 if (P != Best && getMoreSpecializedPartialSpecialization(
2778 P->Partial, Best->Partial,
2779 PointOfInstantiation) != Best->Partial) {
2780 AmbiguousPartialSpec = true;
2781 break;
2782 }
2783 }
2784 }
2785
2786 // Instantiate using the best variable template partial specialization.
2787 InstantiationPattern = Best->Partial;
2788 InstantiationArgs = Best->Args;
2789 } else {
2790 // -- If no match is found, the instantiation is generated
2791 // from the primary template.
2792 // InstantiationPattern = Template->getTemplatedDecl();
2793 }
2794 }
2795
Larisse Voufo39a1e502013-08-06 01:03:05 +00002796 // 2. Create the canonical declaration.
2797 // Note that we do not instantiate the variable just yet, since
2798 // instantiation is handled in DoMarkVarDeclReferenced().
2799 // FIXME: LateAttrs et al.?
2800 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2801 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2802 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2803 if (!Decl)
2804 return true;
2805
2806 if (AmbiguousPartialSpec) {
2807 // Partial ordering did not produce a clear winner. Complain.
2808 Decl->setInvalidDecl();
2809 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2810 << Decl;
2811
2812 // Print the matching partial specializations.
2813 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2814 PEnd = Matched.end();
2815 P != PEnd; ++P)
2816 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2817 << getTemplateArgumentBindingsText(
2818 P->Partial->getTemplateParameters(), *P->Args);
2819 return true;
2820 }
2821
2822 if (VarTemplatePartialSpecializationDecl *D =
2823 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2824 Decl->setInstantiationOf(D, InstantiationArgs);
2825
2826 assert(Decl && "No variable template specialization?");
2827 return Decl;
2828}
2829
2830ExprResult
2831Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2832 const DeclarationNameInfo &NameInfo,
2833 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2834 const TemplateArgumentListInfo *TemplateArgs) {
2835
2836 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2837 *TemplateArgs);
2838 if (Decl.isInvalid())
2839 return ExprError();
2840
2841 VarDecl *Var = cast<VarDecl>(Decl.get());
2842 if (!Var->getTemplateSpecializationKind())
2843 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2844 NameInfo.getLoc());
2845
2846 // Build an ordinary singleton decl ref.
2847 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002848 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002849}
2850
John McCalldadc5752010-08-24 06:29:42 +00002851ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002852 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002853 LookupResult &R,
2854 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002855 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002856 // FIXME: Can we do any checking at this point? I guess we could check the
2857 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002858 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002859 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002860 // foo<int> could identify a single function unambiguously
2861 // This approach does NOT work, since f<int>(1);
2862 // gets resolved prior to resorting to overload resolution
2863 // i.e., template<class T> void f(double);
2864 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002865
2866 // These should be filtered out by our callers.
2867 assert(!R.empty() && "empty lookup results when building templateid");
2868 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2869
Larisse Voufo39a1e502013-08-06 01:03:05 +00002870 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002871 bool InstantiationDependent;
2872 if (R.getAsSingle<VarTemplateDecl>() &&
2873 !TemplateSpecializationType::anyDependentTemplateArguments(
2874 *TemplateArgs, InstantiationDependent)) {
2875 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2876 R.getAsSingle<VarTemplateDecl>(),
2877 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002878 }
2879
John McCall58cc69d2010-01-27 01:50:18 +00002880 // We don't want lookup warnings at this point.
2881 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002882
John McCalle66edc12009-11-24 19:00:30 +00002883 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002884 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002885 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002886 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002887 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002888 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002889 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002890
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002891 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002892}
2893
John McCalle66edc12009-11-24 19:00:30 +00002894// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002895ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002896Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002897 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002898 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002899 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002900
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002901 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002902 DeclContext *DC;
2903 if (!(DC = computeDeclContext(SS, false)) ||
2904 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002905 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002906 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002907
Douglas Gregor786123d2010-05-21 23:18:07 +00002908 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002909 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002910 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002911 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002912
John McCalle66edc12009-11-24 19:00:30 +00002913 if (R.isAmbiguous())
2914 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915
John McCalle66edc12009-11-24 19:00:30 +00002916 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002917 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2918 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002919 return ExprError();
2920 }
2921
2922 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002923 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002924 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002925 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002926 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2927 return ExprError();
2928 }
2929
Abramo Bagnara7945c982012-01-27 09:46:47 +00002930 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002931}
2932
Douglas Gregorb67535d2009-03-31 00:43:58 +00002933/// \brief Form a dependent template name.
2934///
2935/// This action forms a dependent template name given the template
2936/// name and its (presumably dependent) scope specifier. For
2937/// example, given "MetaFun::template apply", the scope specifier \p
2938/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2939/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002941 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002942 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002943 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002944 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002945 bool EnteringContext,
2946 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002947 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2948 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002949 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002950 diag::warn_cxx98_compat_template_outside_of_template :
2951 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952 << FixItHint::CreateRemoval(TemplateKWLoc);
2953
Craig Topperc3ec1492014-05-26 06:22:03 +00002954 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002955 if (SS.isSet())
2956 LookupCtx = computeDeclContext(SS, EnteringContext);
2957 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002958 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002959 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00002960 // C++0x [temp.names]p5:
2961 // If a name prefixed by the keyword template is not the name of
2962 // a template, the program is ill-formed. [Note: the keyword
2963 // template may not be applied to non-template members of class
2964 // templates. -end note ] [ Note: as is the case with the
2965 // typename prefix, the template prefix is allowed in cases
2966 // where it is not strictly necessary; i.e., when the
2967 // nested-name-specifier or the expression on the left of the ->
2968 // or . is not dependent on a template-parameter, or the use
2969 // does not appear in the scope of a template. -end note]
2970 //
2971 // Note: C++03 was more strict here, because it banned the use of
2972 // the "template" keyword prior to a template-name that was not a
2973 // dependent name. C++ DR468 relaxed this requirement (the
2974 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00002975 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00002976 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00002977 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002978 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00002979 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00002980 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2981 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00002982 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2983 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00002984 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00002985 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002986 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002987 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002988 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002989 << Name.getSourceRange()
2990 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002991 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00002992 } else {
2993 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00002994 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002995 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00002996 }
2997
Aaron Ballman4a979672014-01-03 13:56:08 +00002998 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002999
Douglas Gregor3cf81312009-11-03 23:16:33 +00003000 switch (Name.getKind()) {
3001 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00003003 Name.Identifier));
3004 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003005
Douglas Gregor71395fa2009-11-04 00:56:37 +00003006 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00003007 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00003008 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00003009 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00003010
3011 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00003012 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00003013
Douglas Gregor3cf81312009-11-03 23:16:33 +00003014 default:
3015 break;
3016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003018 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003019 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003020 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003021 << Name.getSourceRange()
3022 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003023 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003024}
3025
Mike Stump11289f42009-09-09 15:08:12 +00003026bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003027 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003028 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003029 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003030 QualType ArgType;
3031 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003032
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003033 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003034 switch(Arg.getKind()) {
3035 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003036 // C++ [temp.arg.type]p1:
3037 // A template-argument for a template-parameter which is a
3038 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003039 ArgType = Arg.getAsType();
3040 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003041 break;
3042 case TemplateArgument::Template: {
3043 // We have a template type parameter but the template argument
3044 // is a template without any arguments.
3045 SourceRange SR = AL.getSourceRange();
3046 TemplateName Name = Arg.getAsTemplate();
3047 Diag(SR.getBegin(), diag::err_template_missing_args)
3048 << Name << SR;
3049 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3050 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003051
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003052 return true;
3053 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003054 case TemplateArgument::Expression: {
3055 // We have a template type parameter but the template argument is an
3056 // expression; see if maybe it is missing the "typename" keyword.
3057 CXXScopeSpec SS;
3058 DeclarationNameInfo NameInfo;
3059
3060 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3061 SS.Adopt(ArgExpr->getQualifierLoc());
3062 NameInfo = ArgExpr->getNameInfo();
3063 } else if (DependentScopeDeclRefExpr *ArgExpr =
3064 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3065 SS.Adopt(ArgExpr->getQualifierLoc());
3066 NameInfo = ArgExpr->getNameInfo();
3067 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3068 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003069 if (ArgExpr->isImplicitAccess()) {
3070 SS.Adopt(ArgExpr->getQualifierLoc());
3071 NameInfo = ArgExpr->getMemberNameInfo();
3072 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003073 }
3074
Reid Kleckner377c1592014-06-10 23:29:48 +00003075 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003076 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3077 LookupParsedName(Result, CurScope, &SS);
3078
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003079 if (Result.getAsSingle<TypeDecl>() ||
3080 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003081 LookupResult::NotFoundInCurrentInstantiation) {
3082 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003083 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003084 Diag(Loc, getLangOpts().MSVCCompat
3085 ? diag::ext_ms_template_type_arg_missing_typename
3086 : diag::err_template_arg_must_be_type_suggest)
3087 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003088 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003089
3090 // Recover by synthesizing a type using the location information that we
3091 // already have.
3092 ArgType =
3093 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3094 TypeLocBuilder TLB;
3095 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3096 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3097 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3098 TL.setNameLoc(NameInfo.getLoc());
3099 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3100
3101 // Overwrite our input TemplateArgumentLoc so that we can recover
3102 // properly.
3103 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3104 TemplateArgumentLocInfo(TSI));
3105
3106 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003107 }
3108 }
3109 // fallthrough
3110 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003111 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003112 // We have a template type parameter but the template argument
3113 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003114 SourceRange SR = AL.getSourceRange();
3115 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003116 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003117
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003118 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003119 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003120 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003121
Reid Kleckner377c1592014-06-10 23:29:48 +00003122 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003123 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003124
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003125 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003126 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003127
3128 // Objective-C ARC:
3129 // If an explicitly-specified template argument type is a lifetime type
3130 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003131 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003132 ArgType->isObjCLifetimeType() &&
3133 !ArgType.getObjCLifetime()) {
3134 Qualifiers Qs;
3135 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3136 ArgType = Context.getQualifiedType(ArgType, Qs);
3137 }
3138
3139 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003140 return false;
3141}
3142
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003143/// \brief Substitute template arguments into the default template argument for
3144/// the given template type parameter.
3145///
3146/// \param SemaRef the semantic analysis object for which we are performing
3147/// the substitution.
3148///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003150/// for.
3151///
3152/// \param TemplateLoc the location of the template name that started the
3153/// template-id we are checking.
3154///
3155/// \param RAngleLoc the location of the right angle bracket ('>') that
3156/// terminates the template-id.
3157///
3158/// \param Param the template template parameter whose default we are
3159/// substituting into.
3160///
3161/// \param Converted the list of template arguments provided for template
3162/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003163/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003164static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003165SubstDefaultTemplateArgument(Sema &SemaRef,
3166 TemplateDecl *Template,
3167 SourceLocation TemplateLoc,
3168 SourceLocation RAngleLoc,
3169 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003170 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003171 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003172
3173 // If the argument type is dependent, instantiate it now based
3174 // on the previously-computed template arguments.
3175 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003176 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003177 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003178 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003179 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003180 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003181
David Majnemer89189202013-08-28 23:48:32 +00003182 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3183 Converted.data(), Converted.size());
3184
3185 // Only substitute for the innermost template argument list.
3186 MultiLevelTemplateArgumentList TemplateArgLists;
3187 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3188 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3189 TemplateArgLists.addOuterTemplateArguments(None);
3190
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003191 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003192 ArgType =
3193 SemaRef.SubstType(ArgType, TemplateArgLists,
3194 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003195 }
3196
3197 return ArgType;
3198}
3199
3200/// \brief Substitute template arguments into the default template argument for
3201/// the given non-type template parameter.
3202///
3203/// \param SemaRef the semantic analysis object for which we are performing
3204/// the substitution.
3205///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003207/// for.
3208///
3209/// \param TemplateLoc the location of the template name that started the
3210/// template-id we are checking.
3211///
3212/// \param RAngleLoc the location of the right angle bracket ('>') that
3213/// terminates the template-id.
3214///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003215/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003216/// substituting into.
3217///
3218/// \param Converted the list of template arguments provided for template
3219/// parameters that precede \p Param in the template parameter list.
3220///
3221/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003222static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003223SubstDefaultTemplateArgument(Sema &SemaRef,
3224 TemplateDecl *Template,
3225 SourceLocation TemplateLoc,
3226 SourceLocation RAngleLoc,
3227 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003228 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003229 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003230 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003231 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003232 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003233 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003234
David Majnemer89189202013-08-28 23:48:32 +00003235 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3236 Converted.data(), Converted.size());
3237
3238 // Only substitute for the innermost template argument list.
3239 MultiLevelTemplateArgumentList TemplateArgLists;
3240 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3241 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3242 TemplateArgLists.addOuterTemplateArguments(None);
3243
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003244 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedmanc25372b2012-04-26 22:43:24 +00003245 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
David Majnemer89189202013-08-28 23:48:32 +00003246 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003247}
3248
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003249/// \brief Substitute template arguments into the default template argument for
3250/// the given template template parameter.
3251///
3252/// \param SemaRef the semantic analysis object for which we are performing
3253/// the substitution.
3254///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003255/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003256/// for.
3257///
3258/// \param TemplateLoc the location of the template name that started the
3259/// template-id we are checking.
3260///
3261/// \param RAngleLoc the location of the right angle bracket ('>') that
3262/// terminates the template-id.
3263///
3264/// \param Param the template template parameter whose default we are
3265/// substituting into.
3266///
3267/// \param Converted the list of template arguments provided for template
3268/// parameters that precede \p Param in the template parameter list.
3269///
Douglas Gregordf846d12011-03-02 18:46:51 +00003270/// \param QualifierLoc Will be set to the nested-name-specifier (with
3271/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003272///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003273/// \returns the substituted template argument, or NULL if an error occurred.
3274static TemplateName
3275SubstDefaultTemplateArgument(Sema &SemaRef,
3276 TemplateDecl *Template,
3277 SourceLocation TemplateLoc,
3278 SourceLocation RAngleLoc,
3279 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003280 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003281 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003282 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003283 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003284 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003285 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003286
David Majnemer89189202013-08-28 23:48:32 +00003287 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3288 Converted.data(), Converted.size());
3289
3290 // Only substitute for the innermost template argument list.
3291 MultiLevelTemplateArgumentList TemplateArgLists;
3292 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3293 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3294 TemplateArgLists.addOuterTemplateArguments(None);
3295
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003296 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003297 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003298 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003299 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003300 QualifierLoc =
3301 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003302 if (!QualifierLoc)
3303 return TemplateName();
3304 }
David Majnemer89189202013-08-28 23:48:32 +00003305
3306 return SemaRef.SubstTemplateName(
3307 QualifierLoc,
3308 Param->getDefaultArgument().getArgument().getAsTemplate(),
3309 Param->getDefaultArgument().getTemplateNameLoc(),
3310 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003311}
3312
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003313/// \brief If the given template parameter has a default template
3314/// argument, substitute into that default template argument and
3315/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003316TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003317Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3318 SourceLocation TemplateLoc,
3319 SourceLocation RAngleLoc,
3320 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003321 SmallVectorImpl<TemplateArgument>
3322 &Converted,
3323 bool &HasDefaultArg) {
3324 HasDefaultArg = false;
3325
3326 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003327 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003328 return TemplateArgumentLoc();
3329
Richard Smithc87b9382013-07-04 01:01:24 +00003330 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003331 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003332 TemplateLoc,
3333 RAngleLoc,
3334 TypeParm,
3335 Converted);
3336 if (DI)
3337 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3338
3339 return TemplateArgumentLoc();
3340 }
3341
3342 if (NonTypeTemplateParmDecl *NonTypeParm
3343 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003344 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003345 return TemplateArgumentLoc();
3346
Richard Smithc87b9382013-07-04 01:01:24 +00003347 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003348 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003349 TemplateLoc,
3350 RAngleLoc,
3351 NonTypeParm,
3352 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003353 if (Arg.isInvalid())
3354 return TemplateArgumentLoc();
3355
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003356 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003357 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3358 }
3359
3360 TemplateTemplateParmDecl *TempTempParm
3361 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003362 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003363 return TemplateArgumentLoc();
3364
Richard Smithc87b9382013-07-04 01:01:24 +00003365 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003366 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003367 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003369 RAngleLoc,
3370 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003371 Converted,
3372 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003373 if (TName.isNull())
3374 return TemplateArgumentLoc();
3375
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003377 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003378 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3379}
3380
Douglas Gregorda0fb532009-11-11 19:31:23 +00003381/// \brief Check that the given template argument corresponds to the given
3382/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003383///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003385/// checked.
3386///
Richard Trieu15b66532015-01-24 02:48:32 +00003387/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003388///
3389/// \param Template The template in which the template argument resides.
3390///
3391/// \param TemplateLoc The location of the template name for the template
3392/// whose argument list we're matching.
3393///
3394/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3395/// the template argument list.
3396///
3397/// \param ArgumentPackIndex The index into the argument pack where this
3398/// argument will be placed. Only valid if the parameter is a parameter pack.
3399///
3400/// \param Converted The checked, converted argument will be added to the
3401/// end of this small vector.
3402///
3403/// \param CTAK Describes how we arrived at this particular template argument:
3404/// explicitly written, deduced, etc.
3405///
3406/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003407bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003408 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003409 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003410 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003411 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003412 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003413 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003414 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003415 // Check template type parameters.
3416 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003417 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003418
Douglas Gregoreebed722009-11-11 19:41:09 +00003419 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003421 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003422 // with the template arguments we've seen thus far. But if the
3423 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003424 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003425 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3426 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427
Peter Collingbourne01687632010-12-10 17:08:53 +00003428 if (NTTPType->isDependentType() &&
3429 !isa<TemplateTemplateParmDecl>(Template) &&
3430 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003431 // Do substitution on the type of the non-type template parameter.
3432 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003433 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003434 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003435 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003436 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437
3438 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003439 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003440 NTTPType = SubstType(NTTPType,
3441 MultiLevelTemplateArgumentList(TemplateArgs),
3442 NTTP->getLocation(),
3443 NTTP->getDeclName());
3444 // If that worked, check the non-type template parameter type
3445 // for validity.
3446 if (!NTTPType.isNull())
3447 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3448 NTTP->getLocation());
3449 if (NTTPType.isNull())
3450 return true;
3451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452
Douglas Gregorda0fb532009-11-11 19:31:23 +00003453 switch (Arg.getArgument().getKind()) {
3454 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003455 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Douglas Gregorda0fb532009-11-11 19:31:23 +00003457 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003458 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003459 ExprResult Res =
3460 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3461 Result, CTAK);
3462 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003463 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464
Richard Trieu15b66532015-01-24 02:48:32 +00003465 // If the resulting expression is new, then use it in place of the
3466 // old expression in the template argument.
3467 if (Res.get() != Arg.getArgument().getAsExpr()) {
3468 TemplateArgument TA(Res.get());
3469 Arg = TemplateArgumentLoc(TA, Res.get());
3470 }
3471
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003472 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003473 break;
3474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003475
Douglas Gregorda0fb532009-11-11 19:31:23 +00003476 case TemplateArgument::Declaration:
3477 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003478 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003479 // We've already checked this template argument, so just copy
3480 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003481 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003482 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregorda0fb532009-11-11 19:31:23 +00003484 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003485 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003486 // We were given a template template argument. It may not be ill-formed;
3487 // see below.
3488 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003489 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3490 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003491 // We have a template argument such as \c T::template X, which we
3492 // parsed as a template template argument. However, since we now
3493 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003494 // template name into an expression.
3495
3496 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3497 Arg.getTemplateNameLoc());
3498
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003499 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003500 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003501 // FIXME: the template-template arg was a DependentTemplateName,
3502 // so it was provided with a template keyword. However, its source
3503 // location is not stored in the template argument structure.
3504 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003505 ExprResult E = DependentScopeDeclRefExpr::Create(
3506 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3507 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003509 // If we parsed the template argument as a pack expansion, create a
3510 // pack expansion expression.
3511 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003512 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003513 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003514 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516
Douglas Gregorda0fb532009-11-11 19:31:23 +00003517 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003518 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003519 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003520 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003522 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003523 break;
3524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525
Douglas Gregorda0fb532009-11-11 19:31:23 +00003526 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003527 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003528 // therefore cannot be a non-type template argument.
3529 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3530 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531
Douglas Gregorda0fb532009-11-11 19:31:23 +00003532 Diag(Param->getLocation(), diag::note_template_param_here);
3533 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534
Douglas Gregorda0fb532009-11-11 19:31:23 +00003535 case TemplateArgument::Type: {
3536 // We have a non-type template parameter but the template
3537 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538
Douglas Gregorda0fb532009-11-11 19:31:23 +00003539 // C++ [temp.arg]p2:
3540 // In a template-argument, an ambiguity between a type-id and
3541 // an expression is resolved to a type-id, regardless of the
3542 // form of the corresponding template-parameter.
3543 //
3544 // We warn specifically about this case, since it can be rather
3545 // confusing for users.
3546 QualType T = Arg.getArgument().getAsType();
3547 SourceRange SR = Arg.getSourceRange();
3548 if (T->isFunctionType())
3549 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3550 else
3551 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3552 Diag(Param->getLocation(), diag::note_template_param_here);
3553 return true;
3554 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555
Douglas Gregorda0fb532009-11-11 19:31:23 +00003556 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003557 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559
Douglas Gregorda0fb532009-11-11 19:31:23 +00003560 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003561 }
3562
3563
Douglas Gregorda0fb532009-11-11 19:31:23 +00003564 // Check template template parameters.
3565 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregorda0fb532009-11-11 19:31:23 +00003567 // Substitute into the template parameter list of the template
3568 // template parameter, since previously-supplied template arguments
3569 // may appear within the template template parameter.
3570 {
3571 // Set up a template instantiation context.
3572 LocalInstantiationScope Scope(*this);
3573 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003574 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003575 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003576 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003577 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003578
3579 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003580 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003581 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003583 MultiLevelTemplateArgumentList(TemplateArgs)));
3584 if (!TempParm)
3585 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003587
Douglas Gregorda0fb532009-11-11 19:31:23 +00003588 switch (Arg.getArgument().getKind()) {
3589 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003590 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591
Douglas Gregorda0fb532009-11-11 19:31:23 +00003592 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003593 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003594 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003595 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003597 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003598 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Douglas Gregorda0fb532009-11-11 19:31:23 +00003600 case TemplateArgument::Expression:
3601 case TemplateArgument::Type:
3602 // We have a template template parameter but the template
3603 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003604 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003605 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003606 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003607
Douglas Gregorda0fb532009-11-11 19:31:23 +00003608 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003609 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003610 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003611 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003612 case TemplateArgument::NullPtr:
3613 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003614
Douglas Gregorda0fb532009-11-11 19:31:23 +00003615 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003616 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618
Douglas Gregorda0fb532009-11-11 19:31:23 +00003619 return false;
3620}
3621
Douglas Gregor8e072612012-02-03 07:34:46 +00003622/// \brief Diagnose an arity mismatch in the
3623static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3624 SourceLocation TemplateLoc,
3625 TemplateArgumentListInfo &TemplateArgs) {
3626 TemplateParameterList *Params = Template->getTemplateParameters();
3627 unsigned NumParams = Params->size();
3628 unsigned NumArgs = TemplateArgs.size();
3629
3630 SourceRange Range;
3631 if (NumArgs > NumParams)
3632 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3633 TemplateArgs.getRAngleLoc());
3634 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3635 << (NumArgs > NumParams)
3636 << (isa<ClassTemplateDecl>(Template)? 0 :
3637 isa<FunctionTemplateDecl>(Template)? 1 :
3638 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3639 << Template << Range;
3640 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3641 << Params->getSourceRange();
3642 return true;
3643}
3644
Richard Smith1fde8ec2012-09-07 02:06:42 +00003645/// \brief Check whether the template parameter is a pack expansion, and if so,
3646/// determine the number of parameters produced by that expansion. For instance:
3647///
3648/// \code
3649/// template<typename ...Ts> struct A {
3650/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3651/// };
3652/// \endcode
3653///
3654/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3655/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003656static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003657 if (NonTypeTemplateParmDecl *NTTP
3658 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3659 if (NTTP->isExpandedParameterPack())
3660 return NTTP->getNumExpansionTypes();
3661 }
3662
3663 if (TemplateTemplateParmDecl *TTP
3664 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3665 if (TTP->isExpandedParameterPack())
3666 return TTP->getNumExpansionTemplateParameters();
3667 }
3668
David Blaikie7a30dc52013-02-21 01:47:18 +00003669 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003670}
3671
Richard Smith35c1df52015-06-17 20:16:32 +00003672/// Diagnose a missing template argument.
3673template<typename TemplateParmDecl>
3674static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3675 TemplateDecl *TD,
3676 const TemplateParmDecl *D,
3677 TemplateArgumentListInfo &Args) {
3678 // Dig out the most recent declaration of the template parameter; there may be
3679 // declarations of the template that are more recent than TD.
3680 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3681 ->getTemplateParameters()
3682 ->getParam(D->getIndex()));
3683
3684 // If there's a default argument that's not visible, diagnose that we're
3685 // missing a module import.
3686 llvm::SmallVector<Module*, 8> Modules;
3687 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3688 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3689 D->getDefaultArgumentLoc(), Modules,
3690 Sema::MissingImportKind::DefaultArgument,
3691 /*Recover*/ true);
3692 return true;
3693 }
3694
3695 // FIXME: If there's a more recent default argument that *is* visible,
3696 // diagnose that it was declared too late.
3697
3698 return diagnoseArityMismatch(S, TD, Loc, Args);
3699}
3700
Douglas Gregord32e0282009-02-09 23:23:08 +00003701/// \brief Check that the given template argument list is well-formed
3702/// for specializing the given template.
3703bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3704 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003705 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003706 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003707 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003708 // Make a copy of the template arguments for processing. Only make the
3709 // changes at the end when successful in matching the arguments to the
3710 // template.
3711 TemplateArgumentListInfo NewArgs = TemplateArgs;
3712
Douglas Gregord32e0282009-02-09 23:23:08 +00003713 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003714
Richard Trieu15b66532015-01-24 02:48:32 +00003715 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003716
Mike Stump11289f42009-09-09 15:08:12 +00003717 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003718 // [...] The type and form of each template-argument specified in
3719 // a template-id shall match the type and form specified for the
3720 // corresponding parameter declared by the template in its
3721 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003722 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003723 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003724 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003725 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003726 for (TemplateParameterList::iterator Param = Params->begin(),
3727 ParamEnd = Params->end();
3728 Param != ParamEnd; /* increment in loop */) {
3729 // If we have an expanded parameter pack, make sure we don't have too
3730 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003731 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003732 if (*Expansions == ArgumentPack.size()) {
3733 // We're done with this parameter pack. Pack up its arguments and add
3734 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003735 Converted.push_back(
Benjamin Kramercce63472015-08-05 09:40:22 +00003736 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003737 ArgumentPack.clear();
3738
Richard Smith1fde8ec2012-09-07 02:06:42 +00003739 // This argument is assigned to the next parameter.
3740 ++Param;
3741 continue;
3742 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3743 // Not enough arguments for this parameter pack.
3744 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3745 << false
3746 << (isa<ClassTemplateDecl>(Template)? 0 :
3747 isa<FunctionTemplateDecl>(Template)? 1 :
3748 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3749 << Template;
3750 Diag(Template->getLocation(), diag::note_template_decl_here)
3751 << Params->getSourceRange();
3752 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003753 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
Richard Smith1fde8ec2012-09-07 02:06:42 +00003756 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003757 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003758 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003759 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003760 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003761 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762
Richard Smith96d71c32014-11-12 23:38:38 +00003763 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003764 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003765 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3766 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003767 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003768 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003769 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003770 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003771 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003772 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003773 Diag((*Param)->getLocation(), diag::note_template_param_here);
3774 return true;
3775 }
3776
Richard Smith1fde8ec2012-09-07 02:06:42 +00003777 // We're now done with this argument.
3778 ++ArgIdx;
3779
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003780 if ((*Param)->isTemplateParameterPack()) {
3781 // The template parameter was a template parameter pack, so take the
3782 // deduced argument and place it on the argument pack. Note that we
3783 // stay on the same template parameter so that we can deduce more
3784 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003785 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003786 } else {
3787 // Move to the next template parameter.
3788 ++Param;
3789 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003790
Richard Smith96d71c32014-11-12 23:38:38 +00003791 // If we just saw a pack expansion into a non-pack, then directly convert
3792 // the remaining arguments, because we don't know what parameters they'll
3793 // match up with.
3794 if (PackExpansionIntoNonPack) {
3795 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003796 // If we were part way through filling in an expanded parameter pack,
3797 // fall back to just producing individual arguments.
3798 Converted.insert(Converted.end(),
3799 ArgumentPack.begin(), ArgumentPack.end());
3800 ArgumentPack.clear();
3801 }
3802
3803 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003804 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003805 ++ArgIdx;
3806 }
3807
Richard Smith1fde8ec2012-09-07 02:06:42 +00003808 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003809 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003810
Douglas Gregor84d49a22009-11-11 21:54:23 +00003811 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813
Douglas Gregor2f157c92011-06-03 02:59:40 +00003814 // If we're checking a partial template argument list, we're done.
3815 if (PartialTemplateArgs) {
3816 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
Benjamin Kramercce63472015-08-05 09:40:22 +00003817 Converted.push_back(
3818 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3819
Richard Smith1fde8ec2012-09-07 02:06:42 +00003820 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003821 }
3822
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003824 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003825 if ((*Param)->isTemplateParameterPack()) {
3826 assert(!getExpandedPackSize(*Param) &&
3827 "Should have dealt with this already");
3828
3829 // A non-expanded parameter pack before the end of the parameter list
3830 // only occurs for an ill-formed template parameter list, unless we've
3831 // got a partial argument list for a function template, so just bail out.
3832 if (Param + 1 != ParamEnd)
3833 return true;
3834
Benjamin Kramercce63472015-08-05 09:40:22 +00003835 Converted.push_back(
3836 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
Eli Friedmanb826a002012-09-26 02:36:12 +00003837 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003838
3839 ++Param;
3840 continue;
3841 }
3842
Douglas Gregor8e072612012-02-03 07:34:46 +00003843 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003844 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845
Douglas Gregor84d49a22009-11-11 21:54:23 +00003846 // Retrieve the default template argument from the template
3847 // parameter. For each kind of template parameter, we substitute the
3848 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003850 // the default argument.
3851 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003852 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003853 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3854 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003855
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003856 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003857 Template,
3858 TemplateLoc,
3859 RAngleLoc,
3860 TTP,
3861 Converted);
3862 if (!ArgType)
3863 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864
Douglas Gregor84d49a22009-11-11 21:54:23 +00003865 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3866 ArgType);
3867 } else if (NonTypeTemplateParmDecl *NTTP
3868 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003869 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003870 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3871 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003872
John McCalldadc5752010-08-24 06:29:42 +00003873 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874 TemplateLoc,
3875 RAngleLoc,
3876 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003877 Converted);
3878 if (E.isInvalid())
3879 return true;
3880
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003881 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003882 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3883 } else {
3884 TemplateTemplateParmDecl *TempParm
3885 = cast<TemplateTemplateParmDecl>(*Param);
3886
Richard Smith95d83952015-06-10 20:36:34 +00003887 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003888 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3889 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003890
Douglas Gregordf846d12011-03-02 18:46:51 +00003891 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003892 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893 TemplateLoc,
3894 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003895 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003896 Converted,
3897 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003898 if (Name.isNull())
3899 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900
Douglas Gregor9d802122011-03-02 17:09:35 +00003901 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3902 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904
Douglas Gregor84d49a22009-11-11 21:54:23 +00003905 // Introduce an instantiation record that describes where we are using
3906 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003907 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3908 SourceRange(TemplateLoc, RAngleLoc));
3909 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003910 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911
Douglas Gregor84d49a22009-11-11 21:54:23 +00003912 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003913 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003914 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003915 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916
Richard Trieu15b66532015-01-24 02:48:32 +00003917 // Core issue 150 (assumed resolution): if this is a template template
3918 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003919 // template definition.
3920 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003921 NewArgs.addArgument(Arg);
3922
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003923 // Move to the next template parameter and argument.
3924 ++Param;
3925 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927
Richard Smith07f79912014-06-06 16:00:50 +00003928 // If we're performing a partial argument substitution, allow any trailing
3929 // pack expansions; they might be empty. This can happen even if
3930 // PartialTemplateArgs is false (the list of arguments is complete but
3931 // still dependent).
3932 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3933 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003934 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3935 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003936 }
3937
Douglas Gregor8e072612012-02-03 07:34:46 +00003938 // If we have any leftover arguments, then there were too many arguments.
3939 // Complain and fail.
3940 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003941 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3942
3943 // No problems found with the new argument list, propagate changes back
3944 // to caller.
3945 TemplateArgs = NewArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946
Richard Smith1fde8ec2012-09-07 02:06:42 +00003947 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003948}
3949
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003950namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951 class UnnamedLocalNoLinkageFinder
3952 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003953 {
3954 Sema &S;
3955 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003956
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003957 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003959 public:
3960 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3961
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003962 bool Visit(QualType T) {
3963 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003965
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003966#define TYPE(Class, Parent) \
3967 bool Visit##Class##Type(const Class##Type *);
3968#define ABSTRACT_TYPE(Class, Parent) \
3969 bool Visit##Class##Type(const Class##Type *) { return false; }
3970#define NON_CANONICAL_TYPE(Class, Parent) \
3971 bool Visit##Class##Type(const Class##Type *) { return false; }
3972#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003974 bool VisitTagDecl(const TagDecl *Tag);
3975 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3976 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003977}
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003978
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003979bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003980 return false;
3981}
3982
3983bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3984 return Visit(T->getElementType());
3985}
3986
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003987bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003988 return Visit(T->getPointeeType());
3989}
3990
3991bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003993 return Visit(T->getPointeeType());
3994}
3995
3996bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003997 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003998 return Visit(T->getPointeeType());
3999}
4000
4001bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004003 return Visit(T->getPointeeType());
4004}
4005
4006bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004007 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004008 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4009}
4010
4011bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004012 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004013 return Visit(T->getElementType());
4014}
4015
4016bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004018 return Visit(T->getElementType());
4019}
4020
4021bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004022 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004023 return Visit(T->getElementType());
4024}
4025
4026bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004027 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004028 return Visit(T->getElementType());
4029}
4030
4031bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004032 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004033 return Visit(T->getElementType());
4034}
4035
4036bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4037 return Visit(T->getElementType());
4038}
4039
4040bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4041 return Visit(T->getElementType());
4042}
4043
4044bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4045 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004046 for (const auto &A : T->param_types()) {
4047 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004048 return true;
4049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050
Alp Toker314cc812014-01-25 16:55:45 +00004051 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004052}
4053
4054bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4055 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004056 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004057}
4058
4059bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4060 const UnresolvedUsingType*) {
4061 return false;
4062}
4063
4064bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4065 return false;
4066}
4067
4068bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4069 return Visit(T->getUnderlyingType());
4070}
4071
4072bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4073 return false;
4074}
4075
Alexis Hunte852b102011-05-24 22:41:36 +00004076bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4077 const UnaryTransformType*) {
4078 return false;
4079}
4080
Richard Smith30482bc2011-02-20 03:19:35 +00004081bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4082 return Visit(T->getDeducedType());
4083}
4084
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004085bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4086 return VisitTagDecl(T->getDecl());
4087}
4088
4089bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4090 return VisitTagDecl(T->getDecl());
4091}
4092
4093bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4094 const TemplateTypeParmType*) {
4095 return false;
4096}
4097
Douglas Gregorada4b792011-01-14 02:55:32 +00004098bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4099 const SubstTemplateTypeParmPackType *) {
4100 return false;
4101}
4102
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004103bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4104 const TemplateSpecializationType*) {
4105 return false;
4106}
4107
4108bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4109 const InjectedClassNameType* T) {
4110 return VisitTagDecl(T->getDecl());
4111}
4112
4113bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4114 const DependentNameType* T) {
4115 return VisitNestedNameSpecifier(T->getQualifier());
4116}
4117
4118bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4119 const DependentTemplateSpecializationType* T) {
4120 return VisitNestedNameSpecifier(T->getQualifier());
4121}
4122
Douglas Gregord2fa7662010-12-20 02:24:11 +00004123bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4124 const PackExpansionType* T) {
4125 return Visit(T->getPattern());
4126}
4127
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004128bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4129 return false;
4130}
4131
4132bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4133 const ObjCInterfaceType *) {
4134 return false;
4135}
4136
4137bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4138 const ObjCObjectPointerType *) {
4139 return false;
4140}
4141
Eli Friedman0dfb8892011-10-06 23:00:33 +00004142bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4143 return Visit(T->getValueType());
4144}
4145
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004146bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4147 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004148 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004149 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004150 diag::warn_cxx98_compat_template_arg_local_type :
4151 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004152 << S.Context.getTypeDeclType(Tag) << SR;
4153 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154 }
4155
John McCall5ea95772013-03-09 00:54:27 +00004156 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004157 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004158 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004159 diag::warn_cxx98_compat_template_arg_unnamed_type :
4160 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004161 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4162 return true;
4163 }
4164
4165 return false;
4166}
4167
4168bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4169 NestedNameSpecifier *NNS) {
4170 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4171 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004173 switch (NNS->getKind()) {
4174 case NestedNameSpecifier::Identifier:
4175 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004176 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004177 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004178 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004179 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004180
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004181 case NestedNameSpecifier::TypeSpec:
4182 case NestedNameSpecifier::TypeSpecWithTemplate:
4183 return Visit(QualType(NNS->getAsType(), 0));
4184 }
David Blaikie8a40f702012-01-17 06:56:22 +00004185 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004186}
4187
4188
Douglas Gregord32e0282009-02-09 23:23:08 +00004189/// \brief Check a template argument against its corresponding
4190/// template type parameter.
4191///
4192/// This routine implements the semantics of C++ [temp.arg.type]. It
4193/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004194bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004195 TypeSourceInfo *ArgInfo) {
4196 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004197 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004198 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004199
4200 if (Arg->isVariablyModifiedType()) {
4201 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004202 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004203 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004204 }
4205
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004206 // C++03 [temp.arg.type]p2:
4207 // A local type, a type with no linkage, an unnamed type or a type
4208 // compounded from any of these types shall not be used as a
4209 // template-argument for a template type-parameter.
4210 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004211 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004212 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004213 bool NeedsCheck;
4214 if (LangOpts.CPlusPlus11)
4215 NeedsCheck =
4216 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4217 SR.getBegin()) ||
4218 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4219 SR.getBegin());
4220 else
4221 NeedsCheck = Arg->hasUnnamedOrLocalType();
4222
4223 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004224 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4225 (void)Finder.Visit(Context.getCanonicalType(Arg));
4226 }
4227
Douglas Gregord32e0282009-02-09 23:23:08 +00004228 return false;
4229}
4230
Douglas Gregor20fdef32012-04-10 17:08:25 +00004231enum NullPointerValueKind {
4232 NPV_NotNullPointer,
4233 NPV_NullPointer,
4234 NPV_Error
4235};
4236
4237/// \brief Determine whether the given template argument is a null pointer
4238/// value of the appropriate type.
4239static NullPointerValueKind
4240isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4241 QualType ParamType, Expr *Arg) {
4242 if (Arg->isValueDependent() || Arg->isTypeDependent())
4243 return NPV_NotNullPointer;
4244
David Majnemer5c734ad2014-08-14 00:49:23 +00004245 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004246 return NPV_NotNullPointer;
4247
4248 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004249 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4250 if (ArgRV.isInvalid())
4251 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004252 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004253
Douglas Gregor20fdef32012-04-10 17:08:25 +00004254 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004255 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004256 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004257 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004258 EvalResult.HasSideEffects) {
4259 SourceLocation DiagLoc = Arg->getExprLoc();
4260
4261 // If our only note is the usual "invalid subexpression" note, just point
4262 // the caret at its location rather than producing an essentially
4263 // redundant note.
4264 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4265 diag::note_invalid_subexpr_in_const_expr) {
4266 DiagLoc = Notes[0].first;
4267 Notes.clear();
4268 }
4269
4270 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4271 << Arg->getType() << Arg->getSourceRange();
4272 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4273 S.Diag(Notes[I].first, Notes[I].second);
4274
4275 S.Diag(Param->getLocation(), diag::note_template_param_here);
4276 return NPV_Error;
4277 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004278
4279 // C++11 [temp.arg.nontype]p1:
4280 // - an address constant expression of type std::nullptr_t
4281 if (Arg->getType()->isNullPtrType())
4282 return NPV_NullPointer;
4283
4284 // - a constant expression that evaluates to a null pointer value (4.10); or
4285 // - a constant expression that evaluates to a null member pointer value
4286 // (4.11); or
4287 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4288 (EvalResult.Val.isMemberPointer() &&
4289 !EvalResult.Val.getMemberPointerDecl())) {
4290 // If our expression has an appropriate type, we've succeeded.
4291 bool ObjCLifetimeConversion;
4292 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4293 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4294 ObjCLifetimeConversion))
4295 return NPV_NullPointer;
4296
4297 // The types didn't match, but we know we got a null pointer; complain,
4298 // then recover as if the types were correct.
4299 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4300 << Arg->getType() << ParamType << Arg->getSourceRange();
4301 S.Diag(Param->getLocation(), diag::note_template_param_here);
4302 return NPV_NullPointer;
4303 }
4304
4305 // If we don't have a null pointer value, but we do have a NULL pointer
4306 // constant, suggest a cast to the appropriate type.
4307 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4308 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4309 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004310 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4311 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4312 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004313 S.Diag(Param->getLocation(), diag::note_template_param_here);
4314 return NPV_NullPointer;
4315 }
4316
4317 // FIXME: If we ever want to support general, address-constant expressions
4318 // as non-type template arguments, we should return the ExprResult here to
4319 // be interpreted by the caller.
4320 return NPV_NotNullPointer;
4321}
4322
David Majnemer61c39a12013-08-23 05:39:39 +00004323/// \brief Checks whether the given template argument is compatible with its
4324/// template parameter.
4325static bool CheckTemplateArgumentIsCompatibleWithParameter(
4326 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4327 Expr *Arg, QualType ArgType) {
4328 bool ObjCLifetimeConversion;
4329 if (ParamType->isPointerType() &&
4330 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4331 S.IsQualificationConversion(ArgType, ParamType, false,
4332 ObjCLifetimeConversion)) {
4333 // For pointer-to-object types, qualification conversions are
4334 // permitted.
4335 } else {
4336 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4337 if (!ParamRef->getPointeeType()->isFunctionType()) {
4338 // C++ [temp.arg.nontype]p5b3:
4339 // For a non-type template-parameter of type reference to
4340 // object, no conversions apply. The type referred to by the
4341 // reference may be more cv-qualified than the (otherwise
4342 // identical) type of the template- argument. The
4343 // template-parameter is bound directly to the
4344 // template-argument, which shall be an lvalue.
4345
4346 // FIXME: Other qualifiers?
4347 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4348 unsigned ArgQuals = ArgType.getCVRQualifiers();
4349
4350 if ((ParamQuals | ArgQuals) != ParamQuals) {
4351 S.Diag(Arg->getLocStart(),
4352 diag::err_template_arg_ref_bind_ignores_quals)
4353 << ParamType << Arg->getType() << Arg->getSourceRange();
4354 S.Diag(Param->getLocation(), diag::note_template_param_here);
4355 return true;
4356 }
4357 }
4358 }
4359
4360 // At this point, the template argument refers to an object or
4361 // function with external linkage. We now need to check whether the
4362 // argument and parameter types are compatible.
4363 if (!S.Context.hasSameUnqualifiedType(ArgType,
4364 ParamType.getNonReferenceType())) {
4365 // We can't perform this conversion or binding.
4366 if (ParamType->isReferenceType())
4367 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4368 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4369 else
4370 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4371 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4372 S.Diag(Param->getLocation(), diag::note_template_param_here);
4373 return true;
4374 }
4375 }
4376
4377 return false;
4378}
4379
Douglas Gregorccb07762009-02-11 19:52:55 +00004380/// \brief Checks whether the given template argument is the address
4381/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004382static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004383CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4384 NonTypeTemplateParmDecl *Param,
4385 QualType ParamType,
4386 Expr *ArgIn,
4387 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004388 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004389 Expr *Arg = ArgIn;
4390 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004391
Douglas Gregorb242683d2010-04-01 18:32:35 +00004392 bool AddressTaken = false;
4393 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004394 if (S.getLangOpts().MicrosoftExt) {
4395 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4396 // dereference and address-of operators.
4397 Arg = Arg->IgnoreParenCasts();
4398
4399 bool ExtWarnMSTemplateArg = false;
4400 UnaryOperatorKind FirstOpKind;
4401 SourceLocation FirstOpLoc;
4402 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4403 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4404 if (UnOpKind == UO_Deref)
4405 ExtWarnMSTemplateArg = true;
4406 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4407 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4408 if (!AddrOpLoc.isValid()) {
4409 FirstOpKind = UnOpKind;
4410 FirstOpLoc = UnOp->getOperatorLoc();
4411 }
4412 } else
4413 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004414 }
David Majnemer61c39a12013-08-23 05:39:39 +00004415 if (FirstOpLoc.isValid()) {
4416 if (ExtWarnMSTemplateArg)
4417 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4418 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004419
David Majnemer61c39a12013-08-23 05:39:39 +00004420 if (FirstOpKind == UO_AddrOf)
4421 AddressTaken = true;
4422 else if (Arg->getType()->isPointerType()) {
4423 // We cannot let pointers get dereferenced here, that is obviously not a
4424 // constant expression.
4425 assert(FirstOpKind == UO_Deref);
4426 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4427 << Arg->getSourceRange();
4428 }
4429 }
4430 } else {
4431 // See through any implicit casts we added to fix the type.
4432 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004433
David Majnemer61c39a12013-08-23 05:39:39 +00004434 // C++ [temp.arg.nontype]p1:
4435 //
4436 // A template-argument for a non-type, non-template
4437 // template-parameter shall be one of: [...]
4438 //
4439 // -- the address of an object or function with external
4440 // linkage, including function templates and function
4441 // template-ids but excluding non-static class members,
4442 // expressed as & id-expression where the & is optional if
4443 // the name refers to a function or array, or if the
4444 // corresponding template-parameter is a reference; or
4445
4446 // In C++98/03 mode, give an extension warning on any extra parentheses.
4447 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4448 bool ExtraParens = false;
4449 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4450 if (!Invalid && !ExtraParens) {
4451 S.Diag(Arg->getLocStart(),
4452 S.getLangOpts().CPlusPlus11
4453 ? diag::warn_cxx98_compat_template_arg_extra_parens
4454 : diag::ext_template_arg_extra_parens)
4455 << Arg->getSourceRange();
4456 ExtraParens = true;
4457 }
4458
4459 Arg = Parens->getSubExpr();
4460 }
4461
4462 while (SubstNonTypeTemplateParmExpr *subst =
4463 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4464 Arg = subst->getReplacement()->IgnoreImpCasts();
4465
4466 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4467 if (UnOp->getOpcode() == UO_AddrOf) {
4468 Arg = UnOp->getSubExpr();
4469 AddressTaken = true;
4470 AddrOpLoc = UnOp->getOperatorLoc();
4471 }
4472 }
4473
4474 while (SubstNonTypeTemplateParmExpr *subst =
4475 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4476 Arg = subst->getReplacement()->IgnoreImpCasts();
4477 }
John McCall7c454bb2011-07-15 05:09:51 +00004478
David Majnemer07910d62014-06-26 07:48:46 +00004479 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4480 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4481
4482 // If our parameter has pointer type, check for a null template value.
4483 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4484 NullPointerValueKind NPV;
4485 // dllimport'd entities aren't constant but are available inside of template
4486 // arguments.
4487 if (Entity && Entity->hasAttr<DLLImportAttr>())
4488 NPV = NPV_NotNullPointer;
4489 else
4490 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4491 switch (NPV) {
4492 case NPV_NullPointer:
4493 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004494 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4495 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004496 return false;
4497
4498 case NPV_Error:
4499 return true;
4500
4501 case NPV_NotNullPointer:
4502 break;
4503 }
4504 }
4505
Chandler Carruth724a8a12010-01-31 10:01:20 +00004506 // Stop checking the precise nature of the argument if it is value dependent,
4507 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004508 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004509 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004510 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004511 }
David Majnemer61c39a12013-08-23 05:39:39 +00004512
4513 if (isa<CXXUuidofExpr>(Arg)) {
4514 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4515 ArgIn, Arg, ArgType))
4516 return true;
4517
4518 Converted = TemplateArgument(ArgIn);
4519 return false;
4520 }
4521
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004522 if (!DRE) {
4523 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4524 << Arg->getSourceRange();
4525 S.Diag(Param->getLocation(), diag::note_template_param_here);
4526 return true;
4527 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004528
Douglas Gregorccb07762009-02-11 19:52:55 +00004529 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004530 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004531 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004532 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004533 S.Diag(Param->getLocation(), diag::note_template_param_here);
4534 return true;
4535 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004536
4537 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004538 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004539 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004540 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004541 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004542 S.Diag(Param->getLocation(), diag::note_template_param_here);
4543 return true;
4544 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004545 }
Mike Stump11289f42009-09-09 15:08:12 +00004546
Richard Smith9380e0e2012-04-04 21:11:30 +00004547 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4548 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004549
Richard Smith9380e0e2012-04-04 21:11:30 +00004550 // A non-type template argument must refer to an object or function.
4551 if (!Func && !Var) {
4552 // We found something, but we don't know specifically what it is.
4553 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4554 << Arg->getSourceRange();
4555 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4556 return true;
4557 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004558
Richard Smith9380e0e2012-04-04 21:11:30 +00004559 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004560 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004561 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004562 diag::warn_cxx98_compat_template_arg_object_internal :
4563 diag::ext_template_arg_object_internal)
4564 << !Func << Entity << Arg->getSourceRange();
4565 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4566 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004567 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004568 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4569 << !Func << Entity << Arg->getSourceRange();
4570 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4571 << !Func;
4572 return true;
4573 }
4574
4575 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004576 // If the template parameter has pointer type, the function decays.
4577 if (ParamType->isPointerType() && !AddressTaken)
4578 ArgType = S.Context.getPointerType(Func->getType());
4579 else if (AddressTaken && ParamType->isReferenceType()) {
4580 // If we originally had an address-of operator, but the
4581 // parameter has reference type, complain and (if things look
4582 // like they will work) drop the address-of operator.
4583 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4584 ParamType.getNonReferenceType())) {
4585 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4586 << ParamType;
4587 S.Diag(Param->getLocation(), diag::note_template_param_here);
4588 return true;
4589 }
4590
4591 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4592 << ParamType
4593 << FixItHint::CreateRemoval(AddrOpLoc);
4594 S.Diag(Param->getLocation(), diag::note_template_param_here);
4595
4596 ArgType = Func->getType();
4597 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004598 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004599 // A value of reference type is not an object.
4600 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004601 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004602 diag::err_template_arg_reference_var)
4603 << Var->getType() << Arg->getSourceRange();
4604 S.Diag(Param->getLocation(), diag::note_template_param_here);
4605 return true;
4606 }
4607
Richard Smith9380e0e2012-04-04 21:11:30 +00004608 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004609 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004610 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4611 << Arg->getSourceRange();
4612 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4613 return true;
4614 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004615
4616 // If the template parameter has pointer type, we must have taken
4617 // the address of this object.
4618 if (ParamType->isReferenceType()) {
4619 if (AddressTaken) {
4620 // If we originally had an address-of operator, but the
4621 // parameter has reference type, complain and (if things look
4622 // like they will work) drop the address-of operator.
4623 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4624 ParamType.getNonReferenceType())) {
4625 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4626 << ParamType;
4627 S.Diag(Param->getLocation(), diag::note_template_param_here);
4628 return true;
4629 }
4630
4631 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4632 << ParamType
4633 << FixItHint::CreateRemoval(AddrOpLoc);
4634 S.Diag(Param->getLocation(), diag::note_template_param_here);
4635
4636 ArgType = Var->getType();
4637 }
4638 } else if (!AddressTaken && ParamType->isPointerType()) {
4639 if (Var->getType()->isArrayType()) {
4640 // Array-to-pointer decay.
4641 ArgType = S.Context.getArrayDecayedType(Var->getType());
4642 } else {
4643 // If the template parameter has pointer type but the address of
4644 // this object was not taken, complain and (possibly) recover by
4645 // taking the address of the entity.
4646 ArgType = S.Context.getPointerType(Var->getType());
4647 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4648 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4649 << ParamType;
4650 S.Diag(Param->getLocation(), diag::note_template_param_here);
4651 return true;
4652 }
4653
4654 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4655 << ParamType
4656 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4657
4658 S.Diag(Param->getLocation(), diag::note_template_param_here);
4659 }
4660 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004661 }
Mike Stump11289f42009-09-09 15:08:12 +00004662
David Majnemer61c39a12013-08-23 05:39:39 +00004663 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4664 Arg, ArgType))
4665 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004666
4667 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004668 Converted =
4669 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004670 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004671 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004672}
4673
4674/// \brief Checks whether the given template argument is a pointer to
4675/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004676static bool CheckTemplateArgumentPointerToMember(Sema &S,
4677 NonTypeTemplateParmDecl *Param,
4678 QualType ParamType,
4679 Expr *&ResultArg,
4680 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004681 bool Invalid = false;
4682
Douglas Gregor20fdef32012-04-10 17:08:25 +00004683 // Check for a null pointer value.
4684 Expr *Arg = ResultArg;
4685 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4686 case NPV_Error:
4687 return true;
4688 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004689 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004690 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4691 /*isNullPtr*/true);
David Majnemer763584d2014-02-06 10:59:19 +00004692 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4693 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004694 return false;
4695 case NPV_NotNullPointer:
4696 break;
4697 }
4698
4699 bool ObjCLifetimeConversion;
4700 if (S.IsQualificationConversion(Arg->getType(),
4701 ParamType.getNonReferenceType(),
4702 false, ObjCLifetimeConversion)) {
4703 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004704 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004705 ResultArg = Arg;
4706 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4707 ParamType.getNonReferenceType())) {
4708 // We can't perform this conversion.
4709 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4710 << Arg->getType() << ParamType << Arg->getSourceRange();
4711 S.Diag(Param->getLocation(), diag::note_template_param_here);
4712 return true;
4713 }
4714
Douglas Gregorccb07762009-02-11 19:52:55 +00004715 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004716 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004717 Arg = Cast->getSubExpr();
4718
4719 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004720 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004721 // A template-argument for a non-type, non-template
4722 // template-parameter shall be one of: [...]
4723 //
4724 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004725 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004726
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004727 // In C++98/03 mode, give an extension warning on any extra parentheses.
4728 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4729 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004730 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004731 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004732 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004733 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004734 diag::warn_cxx98_compat_template_arg_extra_parens :
4735 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004736 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004737 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004738 }
4739
4740 Arg = Parens->getSubExpr();
4741 }
4742
John McCall7c454bb2011-07-15 05:09:51 +00004743 while (SubstNonTypeTemplateParmExpr *subst =
4744 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4745 Arg = subst->getReplacement()->IgnoreImpCasts();
4746
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004747 // A pointer-to-member constant written &Class::member.
4748 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004749 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004750 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4751 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004752 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004755 // A constant of pointer-to-member type.
4756 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4757 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4758 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004759 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004760 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004761 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004762 } else {
4763 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004764 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004765 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004766 return Invalid;
4767 }
4768 }
4769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770
Craig Topperc3ec1492014-05-26 06:22:03 +00004771 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773
Douglas Gregorccb07762009-02-11 19:52:55 +00004774 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004775 return S.Diag(Arg->getLocStart(),
4776 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004777 << Arg->getSourceRange();
4778
David Majnemer3ac84e62013-10-22 21:56:38 +00004779 if (isa<FieldDecl>(DRE->getDecl()) ||
4780 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4781 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004782 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004783 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004784 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4785 "Only non-static member pointers can make it here");
4786
4787 // Okay: this is the address of a non-static member, and therefore
4788 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004789 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004790 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004791 } else {
4792 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004793 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004794 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004795 return Invalid;
4796 }
4797
4798 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004799 S.Diag(Arg->getLocStart(),
4800 diag::err_template_arg_not_pointer_to_member_form)
4801 << Arg->getSourceRange();
4802 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004803 return true;
4804}
4805
Douglas Gregord32e0282009-02-09 23:23:08 +00004806/// \brief Check a template argument against its corresponding
4807/// non-type template parameter.
4808///
Douglas Gregor463421d2009-03-03 04:44:36 +00004809/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004810/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004811/// returns the converted template argument. \p ParamType is the
4812/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004813ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004814 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004815 TemplateArgument &Converted,
4816 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004817 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004818
Douglas Gregor86560402009-02-10 23:36:10 +00004819 // If either the parameter has a dependent type or the argument is
4820 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004821 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004822 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004823 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004824 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004825 }
Douglas Gregor86560402009-02-10 23:36:10 +00004826
Richard Smithd663fdd2014-12-17 20:42:37 +00004827 // We should have already dropped all cv-qualifiers by now.
4828 assert(!ParamType.hasQualifiers() &&
4829 "non-type template parameter type cannot be qualified");
4830
4831 if (CTAK == CTAK_Deduced &&
4832 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4833 // C++ [temp.deduct.type]p17:
4834 // If, in the declaration of a function template with a non-type
4835 // template-parameter, the non-type template-parameter is used
4836 // in an expression in the function parameter-list and, if the
4837 // corresponding template-argument is deduced, the
4838 // template-argument type shall match the type of the
4839 // template-parameter exactly, except that a template-argument
4840 // deduced from an array bound may be of any integral type.
4841 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4842 << Arg->getType().getUnqualifiedType()
4843 << ParamType.getUnqualifiedType();
4844 Diag(Param->getLocation(), diag::note_template_param_here);
4845 return ExprError();
4846 }
4847
Richard Smith410cc892014-11-26 03:26:53 +00004848 if (getLangOpts().CPlusPlus1z) {
4849 // FIXME: We can do some limited checking for a value-dependent but not
4850 // type-dependent argument.
4851 if (Arg->isValueDependent()) {
4852 Converted = TemplateArgument(Arg);
4853 return Arg;
4854 }
4855
4856 // C++1z [temp.arg.nontype]p1:
4857 // A template-argument for a non-type template parameter shall be
4858 // a converted constant expression of the type of the template-parameter.
4859 APValue Value;
4860 ExprResult ArgResult = CheckConvertedConstantExpression(
4861 Arg, ParamType, Value, CCEK_TemplateArg);
4862 if (ArgResult.isInvalid())
4863 return ExprError();
4864
Richard Smithd663fdd2014-12-17 20:42:37 +00004865 QualType CanonParamType = Context.getCanonicalType(ParamType);
4866
Richard Smith410cc892014-11-26 03:26:53 +00004867 // Convert the APValue to a TemplateArgument.
4868 switch (Value.getKind()) {
4869 case APValue::Uninitialized:
4870 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004871 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004872 break;
4873 case APValue::Int:
4874 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004875 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004876 break;
4877 case APValue::MemberPointer: {
4878 assert(ParamType->isMemberPointerType());
4879
4880 // FIXME: We need TemplateArgument representation and mangling for these.
4881 if (!Value.getMemberPointerPath().empty()) {
4882 Diag(Arg->getLocStart(),
4883 diag::err_template_arg_member_ptr_base_derived_not_supported)
4884 << Value.getMemberPointerDecl() << ParamType
4885 << Arg->getSourceRange();
4886 return ExprError();
4887 }
4888
4889 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004890 Converted = VD ? TemplateArgument(VD, CanonParamType)
4891 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004892 break;
4893 }
4894 case APValue::LValue: {
4895 // For a non-type template-parameter of pointer or reference type,
4896 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004897 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4898 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004899 // -- a temporary object
4900 // -- a string literal
4901 // -- the result of a typeid expression, or
4902 // -- a predefind __func__ variable
4903 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4904 if (isa<CXXUuidofExpr>(E)) {
4905 Converted = TemplateArgument(const_cast<Expr*>(E));
4906 break;
4907 }
4908 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4909 << Arg->getSourceRange();
4910 return ExprError();
4911 }
4912 auto *VD = const_cast<ValueDecl *>(
4913 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4914 // -- a subobject
4915 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4916 VD && VD->getType()->isArrayType() &&
4917 Value.getLValuePath()[0].ArrayIndex == 0 &&
4918 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4919 // Per defect report (no number yet):
4920 // ... other than a pointer to the first element of a complete array
4921 // object.
4922 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4923 Value.isLValueOnePastTheEnd()) {
4924 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4925 << Value.getAsString(Context, ParamType);
4926 return ExprError();
4927 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004928 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004929 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004930 assert((!VD || !ParamType->isNullPtrType()) &&
4931 "non-null value of type nullptr_t?");
4932 Converted = VD ? TemplateArgument(VD, CanonParamType)
4933 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004934 break;
4935 }
4936 case APValue::AddrLabelDiff:
4937 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4938 case APValue::Float:
4939 case APValue::ComplexInt:
4940 case APValue::ComplexFloat:
4941 case APValue::Vector:
4942 case APValue::Array:
4943 case APValue::Struct:
4944 case APValue::Union:
4945 llvm_unreachable("invalid kind for template argument");
4946 }
4947
4948 return ArgResult.get();
4949 }
4950
Douglas Gregor86560402009-02-10 23:36:10 +00004951 // C++ [temp.arg.nontype]p5:
4952 // The following conversions are performed on each expression used
4953 // as a non-type template-argument. If a non-type
4954 // template-argument cannot be converted to the type of the
4955 // corresponding template-parameter then the program is
4956 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00004957 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00004958 // C++11:
4959 // -- for a non-type template-parameter of integral or
4960 // enumeration type, conversions permitted in a converted
4961 // constant expression are applied.
4962 //
4963 // C++98:
4964 // -- for a non-type template-parameter of integral or
4965 // enumeration type, integral promotions (4.5) and integral
4966 // conversions (4.7) are applied.
4967
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004968 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00004969 // We can't check arbitrary value-dependent arguments.
4970 // FIXME: If there's no viable conversion to the template parameter type,
4971 // we should be able to diagnose that prior to instantiation.
4972 if (Arg->isValueDependent()) {
4973 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004974 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00004975 }
4976
4977 // C++ [temp.arg.nontype]p1:
4978 // A template-argument for a non-type, non-template template-parameter
4979 // shall be one of:
4980 //
4981 // -- for a non-type template-parameter of integral or enumeration
4982 // type, a converted constant expression of the type of the
4983 // template-parameter; or
4984 llvm::APSInt Value;
4985 ExprResult ArgResult =
4986 CheckConvertedConstantExpression(Arg, ParamType, Value,
4987 CCEK_TemplateArg);
4988 if (ArgResult.isInvalid())
4989 return ExprError();
4990
4991 // Widen the argument value to sizeof(parameter type). This is almost
4992 // always a no-op, except when the parameter type is bool. In
4993 // that case, this may extend the argument from 1 bit to 8 bits.
4994 QualType IntegerType = ParamType;
4995 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4996 IntegerType = Enum->getDecl()->getIntegerType();
4997 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4998
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004999 Converted = TemplateArgument(Context, Value,
5000 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00005001 return ArgResult;
5002 }
5003
Richard Smith08b12f12011-10-27 22:11:44 +00005004 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5005 if (ArgResult.isInvalid())
5006 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005007 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00005008
5009 QualType ArgType = Arg->getType();
5010
Douglas Gregor86560402009-02-10 23:36:10 +00005011 // C++ [temp.arg.nontype]p1:
5012 // A template-argument for a non-type, non-template
5013 // template-parameter shall be one of:
5014 //
5015 // -- an integral constant-expression of integral or enumeration
5016 // type; or
5017 // -- the name of a non-type template-parameter; or
5018 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005019 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005020 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005021 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005022 diag::err_template_arg_not_integral_or_enumeral)
5023 << ArgType << Arg->getSourceRange();
5024 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005025 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005026 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005027 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5028 QualType T;
5029
5030 public:
5031 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005032
5033 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5034 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005035 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5036 }
5037 } Diagnoser(ArgType);
5038
5039 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005040 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005041 if (!Arg)
5042 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005043 }
5044
Richard Smithd663fdd2014-12-17 20:42:37 +00005045 // From here on out, all we care about is the unqualified form
5046 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005047 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005048
5049 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005050 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005051 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005052 } else if (ParamType->isBooleanType()) {
5053 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005054 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005055 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5056 !ParamType->isEnumeralType()) {
5057 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005058 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005059 } else {
5060 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005061 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005062 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005063 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005064 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005065 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005066 }
5067
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005068 // Add the value of this argument to the list of converted
5069 // arguments. We use the bitwidth and signedness of the template
5070 // parameter.
5071 if (Arg->isValueDependent()) {
5072 // The argument is value-dependent. Create a new
5073 // TemplateArgument with the converted expression.
5074 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005075 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005076 }
5077
Douglas Gregor52aba872009-03-14 00:20:21 +00005078 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005079 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005080 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005081
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005082 if (ParamType->isBooleanType()) {
5083 // Value must be zero or one.
5084 Value = Value != 0;
5085 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5086 if (Value.getBitWidth() != AllowedBits)
5087 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005088 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005089 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005090 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005091
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005093 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005094 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005095 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005096 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005097 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005098
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005099 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005100 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005101 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005102 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005103 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5104 << Arg->getSourceRange();
5105 Diag(Param->getLocation(), diag::note_template_param_here);
5106 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005107
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005108 // Complain if we overflowed the template parameter's type.
5109 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005110 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005111 RequiredBits = OldValue.getActiveBits();
5112 else if (OldValue.isUnsigned())
5113 RequiredBits = OldValue.getActiveBits() + 1;
5114 else
5115 RequiredBits = OldValue.getMinSignedBits();
5116 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005117 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005118 diag::warn_template_arg_too_large)
5119 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5120 << Arg->getSourceRange();
5121 Diag(Param->getLocation(), diag::note_template_param_here);
5122 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005123 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005124
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005125 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005126 ParamType->isEnumeralType()
5127 ? Context.getCanonicalType(ParamType)
5128 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005129 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005130 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005131
Richard Smith08b12f12011-10-27 22:11:44 +00005132 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005133 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5134
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005135 // Handle pointer-to-function, reference-to-function, and
5136 // pointer-to-member-function all in (roughly) the same way.
5137 if (// -- For a non-type template-parameter of type pointer to
5138 // function, only the function-to-pointer conversion (4.3) is
5139 // applied. If the template-argument represents a set of
5140 // overloaded functions (or a pointer to such), the matching
5141 // function is selected from the set (13.4).
5142 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005143 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005144 // -- For a non-type template-parameter of type reference to
5145 // function, no conversions apply. If the template-argument
5146 // represents a set of overloaded functions, the matching
5147 // function is selected from the set (13.4).
5148 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005149 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005150 // -- For a non-type template-parameter of type pointer to
5151 // member function, no conversions apply. If the
5152 // template-argument represents a set of overloaded member
5153 // functions, the matching member function is selected from
5154 // the set (13.4).
5155 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005156 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005157 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005158
Douglas Gregor064fdb22010-04-14 23:11:21 +00005159 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005160 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005161 true,
5162 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005163 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005164 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005165
5166 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5167 ArgType = Arg->getType();
5168 } else
John Wiegley01296292011-04-08 18:41:53 +00005169 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171
John Wiegley01296292011-04-08 18:41:53 +00005172 if (!ParamType->isMemberPointerType()) {
5173 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5174 ParamType,
5175 Arg, Converted))
5176 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005177 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005178 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005179
Douglas Gregor20fdef32012-04-10 17:08:25 +00005180 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5181 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005182 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005183 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005184 }
5185
Chris Lattner696197c2009-02-20 21:37:53 +00005186 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005187 // -- for a non-type template-parameter of type pointer to
5188 // object, qualification conversions (4.4) and the
5189 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005190 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005191 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005192 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005193
John Wiegley01296292011-04-08 18:41:53 +00005194 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5195 ParamType,
5196 Arg, Converted))
5197 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005198 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005199 }
Mike Stump11289f42009-09-09 15:08:12 +00005200
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005201 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005202 // -- For a non-type template-parameter of type reference to
5203 // object, no conversions apply. The type referred to by the
5204 // reference may be more cv-qualified than the (otherwise
5205 // identical) type of the template-argument. The
5206 // template-parameter is bound directly to the
5207 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005208 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005209 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005210
Douglas Gregor064fdb22010-04-14 23:11:21 +00005211 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5213 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005214 true,
5215 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005216 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005217 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005218
5219 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5220 ArgType = Arg->getType();
5221 } else
John Wiegley01296292011-04-08 18:41:53 +00005222 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005223 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005224
John Wiegley01296292011-04-08 18:41:53 +00005225 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5226 ParamType,
5227 Arg, Converted))
5228 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005229 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005230 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005231
Douglas Gregor20fdef32012-04-10 17:08:25 +00005232 // Deal with parameters of type std::nullptr_t.
5233 if (ParamType->isNullPtrType()) {
5234 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5235 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005236 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005237 }
5238
5239 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5240 case NPV_NotNullPointer:
5241 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5242 << Arg->getType() << ParamType;
5243 Diag(Param->getLocation(), diag::note_template_param_here);
5244 return ExprError();
5245
5246 case NPV_Error:
5247 return ExprError();
5248
5249 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005250 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005251 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5252 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005253 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005254 }
5255 }
5256
Douglas Gregor0e558532009-02-11 16:16:59 +00005257 // -- For a non-type template-parameter of type pointer to data
5258 // member, qualification conversions (4.4) are applied.
5259 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5260
Douglas Gregor20fdef32012-04-10 17:08:25 +00005261 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5262 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005263 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005264 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005265}
5266
5267/// \brief Check a template argument against its corresponding
5268/// template template parameter.
5269///
5270/// This routine implements the semantics of C++ [temp.arg.template].
5271/// It returns true if an error occurred, and false otherwise.
5272bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005273 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005274 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005275 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005276 TemplateDecl *Template = Name.getAsTemplateDecl();
5277 if (!Template) {
5278 // Any dependent template name is fine.
5279 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5280 return false;
5281 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005282
Richard Smith3f1b5d02011-05-05 21:57:07 +00005283 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005284 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005285 // the name of a class template or an alias template, expressed as an
5286 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005287 // primary class templates are considered when matching the
5288 // template template argument with the corresponding parameter;
5289 // partial specializations are not considered even if their
5290 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005291 //
5292 // Note that we also allow template template parameters here, which
5293 // will happen when we are dealing with, e.g., class template
5294 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005295 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005296 !isa<TemplateTemplateParmDecl>(Template) &&
5297 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005298 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005299 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005300 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005301 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005302 << Template;
5303 }
5304
Richard Smith1fde8ec2012-09-07 02:06:42 +00005305 TemplateParameterList *Params = Param->getTemplateParameters();
5306 if (Param->isExpandedParameterPack())
5307 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5308
Douglas Gregor85e0f662009-02-10 00:24:35 +00005309 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005310 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005312 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005313 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005314}
5315
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005316/// \brief Given a non-type template argument that refers to a
5317/// declaration and the type of its corresponding non-type template
5318/// parameter, produce an expression that properly refers to that
5319/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005320ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005321Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5322 QualType ParamType,
5323 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005324 // C++ [temp.param]p8:
5325 //
5326 // A non-type template-parameter of type "array of T" or
5327 // "function returning T" is adjusted to be of type "pointer to
5328 // T" or "pointer to function returning T", respectively.
5329 if (ParamType->isArrayType())
5330 ParamType = Context.getArrayDecayedType(ParamType);
5331 else if (ParamType->isFunctionType())
5332 ParamType = Context.getPointerType(ParamType);
5333
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005334 // For a NULL non-type template argument, return nullptr casted to the
5335 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005336 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005337 return ImpCastExprToType(
5338 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5339 ParamType,
5340 ParamType->getAs<MemberPointerType>()
5341 ? CK_NullToMemberPointer
5342 : CK_NullToPointer);
5343 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005344 assert(Arg.getKind() == TemplateArgument::Declaration &&
5345 "Only declaration template arguments permitted here");
5346
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005347 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5348
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005350 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5351 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005352 // If the value is a class member, we might have a pointer-to-member.
5353 // Determine whether the non-type template template parameter is of
5354 // pointer-to-member type. If so, we need to build an appropriate
5355 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5356 // would refer to the member itself.
5357 if (ParamType->isMemberPointerType()) {
5358 QualType ClassType
5359 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5360 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005361 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005362 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005363 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005364 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005365
5366 // The actual value-ness of this is unimportant, but for
5367 // internal consistency's sake, references to instance methods
5368 // are r-values.
5369 ExprValueKind VK = VK_LValue;
5370 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5371 VK = VK_RValue;
5372
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005374 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005375 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005376 Loc,
5377 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005378 if (RefExpr.isInvalid())
5379 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005380
John McCalle3027922010-08-25 11:45:40 +00005381 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005382
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005383 // We might need to perform a trailing qualification conversion, since
5384 // the element type on the parameter could be more qualified than the
5385 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005386 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005387 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005388 ParamType.getUnqualifiedType(), false,
5389 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005390 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005392 assert(!RefExpr.isInvalid() &&
5393 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005394 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005395 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005396 }
5397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005399 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005400
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005401 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005402 // When the non-type template parameter is a pointer, take the
5403 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005404 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005405 if (RefExpr.isInvalid())
5406 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005407
5408 if (T->isFunctionType() || T->isArrayType()) {
5409 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005410 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005411 if (RefExpr.isInvalid())
5412 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005413
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005414 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005416
Douglas Gregorb242683d2010-04-01 18:32:35 +00005417 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005418 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005419 }
5420
John McCall7decc9e2010-11-18 06:31:45 +00005421 ExprValueKind VK = VK_RValue;
5422
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005423 // If the non-type template parameter has reference type, qualify the
5424 // resulting declaration reference with the extra qualifiers on the
5425 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005426 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5427 VK = VK_LValue;
5428 T = Context.getQualifiedType(T,
5429 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005430 } else if (isa<FunctionDecl>(VD)) {
5431 // References to functions are always lvalues.
5432 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005434
John McCall7decc9e2010-11-18 06:31:45 +00005435 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005436}
5437
5438/// \brief Construct a new expression that refers to the given
5439/// integral template argument with the given source-location
5440/// information.
5441///
5442/// This routine takes care of the mapping from an integral template
5443/// argument (which may have any integral type) to the appropriate
5444/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005445ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005446Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5447 SourceLocation Loc) {
5448 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005449 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005450 QualType OrigT = Arg.getIntegralType();
5451
5452 // If this is an enum type that we're instantiating, we need to use an integer
5453 // type the same size as the enumerator. We don't want to build an
5454 // IntegerLiteral with enum type. The integer type of an enum type can be of
5455 // any integral type with C++11 enum classes, make sure we create the right
5456 // type of literal for it.
5457 QualType T = OrigT;
5458 if (const EnumType *ET = OrigT->getAs<EnumType>())
5459 T = ET->getDecl()->getIntegerType();
5460
5461 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005462 if (T->isAnyCharacterType()) {
5463 CharacterLiteral::CharacterKind Kind;
5464 if (T->isWideCharType())
5465 Kind = CharacterLiteral::Wide;
5466 else if (T->isChar16Type())
5467 Kind = CharacterLiteral::UTF16;
5468 else if (T->isChar32Type())
5469 Kind = CharacterLiteral::UTF32;
5470 else
5471 Kind = CharacterLiteral::Ascii;
5472
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005473 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5474 Kind, T, Loc);
5475 } else if (T->isBooleanType()) {
5476 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5477 T, Loc);
5478 } else if (T->isNullPtrType()) {
5479 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5480 } else {
5481 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005482 }
5483
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005484 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005485 // FIXME: This is a hack. We need a better way to handle substituted
5486 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005487 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5488 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005489 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005490 Loc, Loc);
5491 }
5492
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005493 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005494}
5495
Douglas Gregor641040a2011-01-12 23:45:44 +00005496/// \brief Match two template parameters within template parameter lists.
5497static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5498 bool Complain,
5499 Sema::TemplateParameterListEqualKind Kind,
5500 SourceLocation TemplateArgLoc) {
5501 // Check the actual kind (type, non-type, template).
5502 if (Old->getKind() != New->getKind()) {
5503 if (Complain) {
5504 unsigned NextDiag = diag::err_template_param_different_kind;
5505 if (TemplateArgLoc.isValid()) {
5506 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5507 NextDiag = diag::note_template_param_different_kind;
5508 }
5509 S.Diag(New->getLocation(), NextDiag)
5510 << (Kind != Sema::TPL_TemplateMatch);
5511 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5512 << (Kind != Sema::TPL_TemplateMatch);
5513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514
Douglas Gregor641040a2011-01-12 23:45:44 +00005515 return false;
5516 }
5517
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518 // Check that both are parameter packs are neither are parameter packs.
5519 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005520 // template template parameter, the template template parameter can have
5521 // a parameter pack where the template template argument does not.
5522 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5523 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5524 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005525 if (Complain) {
5526 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5527 if (TemplateArgLoc.isValid()) {
5528 S.Diag(TemplateArgLoc,
5529 diag::err_template_arg_template_params_mismatch);
5530 NextDiag = diag::note_template_parameter_pack_non_pack;
5531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005532
Douglas Gregor641040a2011-01-12 23:45:44 +00005533 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5534 : isa<NonTypeTemplateParmDecl>(New)? 1
5535 : 2;
5536 S.Diag(New->getLocation(), NextDiag)
5537 << ParamKind << New->isParameterPack();
5538 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5539 << ParamKind << Old->isParameterPack();
5540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005541
Douglas Gregor641040a2011-01-12 23:45:44 +00005542 return false;
5543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Douglas Gregor641040a2011-01-12 23:45:44 +00005545 // For non-type template parameters, check the type of the parameter.
5546 if (NonTypeTemplateParmDecl *OldNTTP
5547 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5548 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005549
Douglas Gregor641040a2011-01-12 23:45:44 +00005550 // If we are matching a template template argument to a template
5551 // template parameter and one of the non-type template parameter types
5552 // is dependent, then we must wait until template instantiation time
5553 // to actually compare the arguments.
5554 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5555 (OldNTTP->getType()->isDependentType() ||
5556 NewNTTP->getType()->isDependentType()))
5557 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005558
Douglas Gregor641040a2011-01-12 23:45:44 +00005559 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5560 if (Complain) {
5561 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5562 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005564 diag::err_template_arg_template_params_mismatch);
5565 NextDiag = diag::note_template_nontype_parm_different_type;
5566 }
5567 S.Diag(NewNTTP->getLocation(), NextDiag)
5568 << NewNTTP->getType()
5569 << (Kind != Sema::TPL_TemplateMatch);
5570 S.Diag(OldNTTP->getLocation(),
5571 diag::note_template_nontype_parm_prev_declaration)
5572 << OldNTTP->getType();
5573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005574
Douglas Gregor641040a2011-01-12 23:45:44 +00005575 return false;
5576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
Douglas Gregor641040a2011-01-12 23:45:44 +00005578 return true;
5579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580
Douglas Gregor641040a2011-01-12 23:45:44 +00005581 // For template template parameters, check the template parameter types.
5582 // The template parameter lists of template template
5583 // parameters must agree.
5584 if (TemplateTemplateParmDecl *OldTTP
5585 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005586 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005587 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5588 OldTTP->getTemplateParameters(),
5589 Complain,
5590 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005591 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005592 : Kind),
5593 TemplateArgLoc);
5594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005595
Douglas Gregor641040a2011-01-12 23:45:44 +00005596 return true;
5597}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005598
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005599/// \brief Diagnose a known arity mismatch when comparing template argument
5600/// lists.
5601static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005602void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005603 TemplateParameterList *New,
5604 TemplateParameterList *Old,
5605 Sema::TemplateParameterListEqualKind Kind,
5606 SourceLocation TemplateArgLoc) {
5607 unsigned NextDiag = diag::err_template_param_list_different_arity;
5608 if (TemplateArgLoc.isValid()) {
5609 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5610 NextDiag = diag::note_template_param_list_different_arity;
5611 }
5612 S.Diag(New->getTemplateLoc(), NextDiag)
5613 << (New->size() > Old->size())
5614 << (Kind != Sema::TPL_TemplateMatch)
5615 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5616 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5617 << (Kind != Sema::TPL_TemplateMatch)
5618 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5619}
5620
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005621/// \brief Determine whether the given template parameter lists are
5622/// equivalent.
5623///
Mike Stump11289f42009-09-09 15:08:12 +00005624/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005625/// source code as part of a new template declaration.
5626///
5627/// \param Old The old template parameter list, typically found via
5628/// name lookup of the template declared with this template parameter
5629/// list.
5630///
5631/// \param Complain If true, this routine will produce a diagnostic if
5632/// the template parameter lists are not equivalent.
5633///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005634/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005635///
5636/// \param TemplateArgLoc If this source location is valid, then we
5637/// are actually checking the template parameter list of a template
5638/// argument (New) against the template parameter list of its
5639/// corresponding template template parameter (Old). We produce
5640/// slightly different diagnostics in this scenario.
5641///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005642/// \returns True if the template parameter lists are equal, false
5643/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005644bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005645Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5646 TemplateParameterList *Old,
5647 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005648 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005649 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005650 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5651 if (Complain)
5652 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5653 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005654
5655 return false;
5656 }
5657
Douglas Gregor641040a2011-01-12 23:45:44 +00005658 // C++0x [temp.arg.template]p3:
5659 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005660 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005661 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005662 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005663 // template-parameter-list of P. [...]
5664 TemplateParameterList::iterator NewParm = New->begin();
5665 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005666 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005667 OldParmEnd = Old->end();
5668 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005669 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5670 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005671 if (NewParm == NewParmEnd) {
5672 if (Complain)
5673 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5674 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005675
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005676 return false;
5677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005679 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5680 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005681 return false;
5682
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005683 ++NewParm;
5684 continue;
5685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005687 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005688 // [...] When P's template- parameter-list contains a template parameter
5689 // pack (14.5.3), the template parameter pack will match zero or more
5690 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005691 // template-parameter-list of A with the same type and form as the
5692 // template parameter pack in P (ignoring whether those template
5693 // parameters are template parameter packs).
5694 for (; NewParm != NewParmEnd; ++NewParm) {
5695 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5696 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005697 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005698 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005700
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005701 // Make sure we exhausted all of the arguments.
5702 if (NewParm != NewParmEnd) {
5703 if (Complain)
5704 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5705 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005706
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005707 return false;
5708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005710 return true;
5711}
5712
5713/// \brief Check whether a template can be declared within this scope.
5714///
5715/// If the template declaration is valid in this scope, returns
5716/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005717bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005718Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005719 if (!S)
5720 return false;
5721
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005722 // Find the nearest enclosing declaration scope.
5723 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5724 (S->getFlags() & Scope::TemplateParamScope) != 0)
5725 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005726
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005727 // C++ [temp]p4:
5728 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005729 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005730 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005731 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005732 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005733
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005734 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005735 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005736
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005737 // C++ [temp]p2:
5738 // A template-declaration can appear only as a namespace scope or
5739 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005740 if (Ctx) {
5741 if (Ctx->isFileContext())
5742 return false;
5743 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5744 // C++ [temp.mem]p2:
5745 // A local class shall not have member templates.
5746 if (RD->isLocalClass())
5747 return Diag(TemplateParams->getTemplateLoc(),
5748 diag::err_template_inside_local_class)
5749 << TemplateParams->getSourceRange();
5750 else
5751 return false;
5752 }
5753 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005754
Mike Stump11289f42009-09-09 15:08:12 +00005755 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005756 diag::err_template_outside_namespace_or_class_scope)
5757 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005758}
Douglas Gregor67a65642009-02-17 23:15:12 +00005759
Douglas Gregor54888652009-10-07 00:13:32 +00005760/// \brief Determine what kind of template specialization the given declaration
5761/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005762static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005763 if (!D)
5764 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005766 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5767 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005768 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5769 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005770 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5771 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005772
Douglas Gregor54888652009-10-07 00:13:32 +00005773 return TSK_Undeclared;
5774}
5775
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005776/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005777/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005778///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005779/// This routine determines whether a template specialization can be declared
5780/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005781///
5782/// \param S the semantic analysis object for which this check is being
5783/// performed.
5784///
5785/// \param Specialized the entity being specialized or instantiated, which
5786/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005787/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005788/// member class).
5789///
5790/// \param PrevDecl the previous declaration of this entity, if any.
5791///
5792/// \param Loc the location of the explicit specialization or instantiation of
5793/// this entity.
5794///
5795/// \param IsPartialSpecialization whether this is a partial specialization of
5796/// a class template.
5797///
Douglas Gregor54888652009-10-07 00:13:32 +00005798/// \returns true if there was an error that we cannot recover from, false
5799/// otherwise.
5800static bool CheckTemplateSpecializationScope(Sema &S,
5801 NamedDecl *Specialized,
5802 NamedDecl *PrevDecl,
5803 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005804 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005805 // Keep these "kind" numbers in sync with the %select statements in the
5806 // various diagnostics emitted by this routine.
5807 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005808 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005809 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005810 else if (isa<VarTemplateDecl>(Specialized))
5811 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005812 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005813 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005814 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005815 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005816 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005817 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005818 else if (isa<RecordDecl>(Specialized))
5819 EntityKind = 7;
5820 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5821 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005822 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005823 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005824 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005825 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005826 return true;
5827 }
5828
Douglas Gregorf47b9112009-02-25 22:02:03 +00005829 // C++ [temp.expl.spec]p2:
5830 // An explicit specialization shall be declared in the namespace
5831 // of which the template is a member, or, for member templates, in
5832 // the namespace of which the enclosing class or enclosing class
5833 // template is a member. An explicit specialization of a member
5834 // function, member class or static data member of a class
5835 // template shall be declared in the namespace of which the class
5836 // template is a member. Such a declaration may also be a
5837 // definition. If the declaration is not a definition, the
5838 // specialization may be defined later in the name- space in which
5839 // the explicit specialization was declared, or in a namespace
5840 // that encloses the one in which the explicit specialization was
5841 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005842 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005843 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005844 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005845 return true;
5846 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005847
Douglas Gregor40fb7442009-10-07 17:30:37 +00005848 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005849 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005850 // Do not warn for class scope explicit specialization during
5851 // instantiation, warning was already emitted during pattern
5852 // semantic analysis.
5853 if (!S.ActiveTemplateInstantiations.size())
5854 S.Diag(Loc, diag::ext_function_specialization_in_class)
5855 << Specialized;
5856 } else {
5857 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5858 << Specialized;
5859 return true;
5860 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005863 if (S.CurContext->isRecord() &&
5864 !S.CurContext->Equals(Specialized->getDeclContext())) {
5865 // Make sure that we're specializing in the right record context.
5866 // Otherwise, things can go horribly wrong.
5867 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5868 << Specialized;
5869 return true;
5870 }
5871
Douglas Gregore4b05162009-10-07 17:21:34 +00005872 // C++ [temp.class.spec]p6:
5873 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005874 // in any namespace scope in which its definition may be defined (14.5.1
5875 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005876 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005877 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005878 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005879
5880 // Make sure that this redeclaration (or definition) occurs in an enclosing
5881 // namespace.
5882 // Note that HandleDeclarator() performs this check for explicit
5883 // specializations of function templates, static data members, and member
5884 // functions, so we skip the check here for those kinds of entities.
5885 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5886 // Should we refactor that check, so that it occurs later?
5887 if (!DC->Encloses(SpecializedContext) &&
5888 !(isa<FunctionTemplateDecl>(Specialized) ||
5889 isa<FunctionDecl>(Specialized) ||
5890 isa<VarTemplateDecl>(Specialized) ||
5891 isa<VarDecl>(Specialized))) {
5892 if (isa<TranslationUnitDecl>(SpecializedContext))
5893 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5894 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005895 else if (isa<NamespaceDecl>(SpecializedContext)) {
5896 int Diag = diag::err_template_spec_redecl_out_of_scope;
5897 if (S.getLangOpts().MicrosoftExt)
5898 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5899 S.Diag(Loc, Diag) << EntityKind << Specialized
5900 << cast<NamedDecl>(SpecializedContext);
5901 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005902 llvm_unreachable("unexpected namespace context for specialization");
5903
5904 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5905 } else if ((!PrevDecl ||
5906 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5907 getTemplateSpecializationKind(PrevDecl) ==
5908 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005909 // C++ [temp.exp.spec]p2:
5910 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005911 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005912 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005913 // An explicit specialization of a member function, member class or
5914 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005915 // namespace of which the class template is a member.
5916 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005917 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005918 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005919 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005920 // C++11 [temp.explicit]p3:
5921 // An explicit instantiation shall appear in an enclosing namespace of its
5922 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005923 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005924 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005925 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005926 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005927 "DC encloses TU but isn't in enclosing namespace set");
5928 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005929 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005930 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5931 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005932 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005933 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005934 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005935 Diag = diag::ext_template_spec_decl_out_of_scope;
5936 else
5937 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5938 S.Diag(Loc, Diag)
5939 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005941
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005942 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005943 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005944 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005945
Douglas Gregorf47b9112009-02-25 22:02:03 +00005946 return false;
5947}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005948
Richard Smith6056d5e2014-02-09 00:54:43 +00005949static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5950 if (!E->isInstantiationDependent())
5951 return SourceLocation();
5952 DependencyChecker Checker(Depth);
5953 Checker.TraverseStmt(E);
5954 if (Checker.Match && Checker.MatchLoc.isInvalid())
5955 return E->getSourceRange();
5956 return Checker.MatchLoc;
5957}
5958
5959static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5960 if (!TL.getType()->isDependentType())
5961 return SourceLocation();
5962 DependencyChecker Checker(Depth);
5963 Checker.TraverseTypeLoc(TL);
5964 if (Checker.Match && Checker.MatchLoc.isInvalid())
5965 return TL.getSourceRange();
5966 return Checker.MatchLoc;
5967}
5968
Larisse Voufo39a1e502013-08-06 01:03:05 +00005969/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005970/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005971static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005972 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5973 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005974 for (unsigned I = 0; I != NumArgs; ++I) {
5975 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005976 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005977 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5978 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005979 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005980
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005981 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005982 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005983
Eli Friedmanb826a002012-09-26 02:36:12 +00005984 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005985 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00005986
5987 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005988
Douglas Gregor98318c22011-01-03 21:37:45 +00005989 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005990 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5991 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00005992
5993 // Strip off any implicit casts we added as part of type checking.
5994 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5995 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005996
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005997 // C++ [temp.class.spec]p8:
5998 // A non-type argument is non-specialized if it is the name of a
5999 // non-type parameter. All other non-type arguments are
6000 // specialized.
6001 //
6002 // Below, we check the two conditions that only apply to
6003 // specialized non-type arguments, so skip any non-specialized
6004 // arguments.
6005 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00006006 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006007 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006008
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006009 // C++ [temp.class.spec]p9:
6010 // Within the argument list of a class template partial
6011 // specialization, the following restrictions apply:
6012 // -- A partially specialized non-type argument expression
6013 // shall not involve a template parameter of the partial
6014 // specialization except when the argument expression is a
6015 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006016 SourceRange ParamUseRange =
6017 findTemplateParameter(Param->getDepth(), ArgExpr);
6018 if (ParamUseRange.isValid()) {
6019 if (IsDefaultArgument) {
6020 S.Diag(TemplateNameLoc,
6021 diag::err_dependent_non_type_arg_in_partial_spec);
6022 S.Diag(ParamUseRange.getBegin(),
6023 diag::note_dependent_non_type_default_arg_in_partial_spec)
6024 << ParamUseRange;
6025 } else {
6026 S.Diag(ParamUseRange.getBegin(),
6027 diag::err_dependent_non_type_arg_in_partial_spec)
6028 << ParamUseRange;
6029 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006030 return true;
6031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006032
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006033 // -- The type of a template parameter corresponding to a
6034 // specialized non-type argument shall not be dependent on a
6035 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006036 //
6037 // FIXME: We need to delay this check until instantiation in some cases:
6038 //
6039 // template<template<typename> class X> struct A {
6040 // template<typename T, X<T> N> struct B;
6041 // template<typename T> struct B<T, 0>;
6042 // };
6043 // template<typename> using X = int;
6044 // A<X>::B<int, 0> b;
6045 ParamUseRange = findTemplateParameter(
6046 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6047 if (ParamUseRange.isValid()) {
6048 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6049 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6050 << Param->getType() << ParamUseRange;
6051 S.Diag(Param->getLocation(), diag::note_template_param_here)
6052 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006053 return true;
6054 }
6055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006057 return false;
6058}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006059
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006060/// \brief Check the non-type template arguments of a class template
6061/// partial specialization according to C++ [temp.class.spec]p9.
6062///
Richard Smith6056d5e2014-02-09 00:54:43 +00006063/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006064/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006065/// template.
6066/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006067/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006068/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006069///
Richard Smith6056d5e2014-02-09 00:54:43 +00006070/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006071static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006072 Sema &S, SourceLocation TemplateNameLoc,
6073 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006074 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006075 const TemplateArgument *ArgList = TemplateArgs.data();
6076
6077 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6078 NonTypeTemplateParmDecl *Param
6079 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6080 if (!Param)
6081 continue;
6082
Richard Smith6056d5e2014-02-09 00:54:43 +00006083 if (CheckNonTypeTemplatePartialSpecializationArgs(
6084 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006085 return true;
6086 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006087
6088 return false;
6089}
6090
John McCall48871652010-08-21 09:40:31 +00006091DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006092Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6093 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006094 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006095 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006096 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006097 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006098 MultiTemplateParamsArg
6099 TemplateParameterLists,
6100 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006101 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006102
Richard Smith4b55a9c2014-04-17 03:29:33 +00006103 CXXScopeSpec &SS = TemplateId.SS;
6104
Abramo Bagnara60804e12011-03-18 15:16:37 +00006105 // NOTE: KWLoc is the location of the tag keyword. This will instead
6106 // store the location of the outermost template keyword in the declaration.
6107 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006108 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6109 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6110 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6111 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006112
Douglas Gregor67a65642009-02-17 23:15:12 +00006113 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006114 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006115 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006116 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6117
6118 if (!ClassTemplate) {
6119 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006120 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006121 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6122 return true;
6123 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006124
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006125 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006126 bool isPartialSpecialization = false;
6127
Douglas Gregorf47b9112009-02-25 22:02:03 +00006128 // Check the validity of the template headers that introduce this
6129 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006130 // FIXME: We probably shouldn't complain about these headers for
6131 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006132 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006133 TemplateParameterList *TemplateParams =
6134 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006135 KWLoc, TemplateNameLoc, SS, &TemplateId,
6136 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6137 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006138 if (Invalid)
6139 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006140
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006141 if (TemplateParams && TemplateParams->size() > 0) {
6142 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006143
Douglas Gregorec9518b2010-12-21 08:14:57 +00006144 if (TUK == TUK_Friend) {
6145 Diag(KWLoc, diag::err_partial_specialization_friend)
6146 << SourceRange(LAngleLoc, RAngleLoc);
6147 return true;
6148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006149
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006150 // C++ [temp.class.spec]p10:
6151 // The template parameter list of a specialization shall not
6152 // contain default template argument values.
6153 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6154 Decl *Param = TemplateParams->getParam(I);
6155 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6156 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006157 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006158 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006159 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006160 }
6161 } else if (NonTypeTemplateParmDecl *NTTP
6162 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6163 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006164 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006165 diag::err_default_arg_in_partial_spec)
6166 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006167 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006168 }
6169 } else {
6170 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006171 if (TTP->hasDefaultArgument()) {
6172 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006173 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006174 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006175 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006176 }
6177 }
6178 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006179 } else if (TemplateParams) {
6180 if (TUK == TUK_Friend)
6181 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006182 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006183 SourceRange(TemplateParams->getTemplateLoc(),
6184 TemplateParams->getRAngleLoc()))
6185 << SourceRange(LAngleLoc, RAngleLoc);
6186 else
6187 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006188 } else {
6189 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006190 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006191
Douglas Gregor67a65642009-02-17 23:15:12 +00006192 // Check that the specialization uses the same tag kind as the
6193 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006194 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6195 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006196 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006197 Kind, TUK == TUK_Definition, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00006198 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006199 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006200 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006201 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006202 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006203 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006204 diag::note_previous_use);
6205 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6206 }
6207
Douglas Gregorc40290e2009-03-09 23:48:35 +00006208 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006209 TemplateArgumentListInfo TemplateArgs =
6210 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006211
Douglas Gregor14406932011-01-03 20:35:03 +00006212 // Check for unexpanded parameter packs in any of the template arguments.
6213 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006214 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006215 UPPC_PartialSpecialization))
6216 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006217
Douglas Gregor67a65642009-02-17 23:15:12 +00006218 // Check that the template argument list is well-formed for this
6219 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006220 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006221 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6222 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006223 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006224
Douglas Gregor2373c592009-05-31 09:31:02 +00006225 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006226 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006227 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006228 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006229 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6230 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006231 return true;
6232
Douglas Gregor678d76c2011-07-01 01:22:09 +00006233 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006234 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006235 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006236 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006237 TemplateArgs.size(),
6238 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006239 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6240 << ClassTemplate->getDeclName();
6241 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006242 }
6243 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006244
Craig Topperc3ec1492014-05-26 06:22:03 +00006245 void *InsertPos = nullptr;
6246 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006247
6248 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006249 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006250 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006251 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006252 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006253
Craig Topperc3ec1492014-05-26 06:22:03 +00006254 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006255
Douglas Gregorf47b9112009-02-25 22:02:03 +00006256 // Check whether we can declare a class template specialization in
6257 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006258 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006259 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6260 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006261 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006262 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006263
Douglas Gregor15301382009-07-30 17:40:51 +00006264 // The canonical type
6265 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006266 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006267 // Build the canonical type that describes the converted template
6268 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006269 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6270 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006271 Converted.data(),
6272 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006273
6274 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006275 ClassTemplate->getInjectedClassNameSpecialization())) {
6276 // C++ [temp.class.spec]p9b3:
6277 //
6278 // -- The argument list of the specialization shall not be identical
6279 // to the implicit argument list of the primary template.
6280 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006281 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006282 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006283 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6284 ClassTemplate->getIdentifier(),
6285 TemplateNameLoc,
6286 Attr,
6287 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006288 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006289 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006290 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006291 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006292 }
Douglas Gregor15301382009-07-30 17:40:51 +00006293
Douglas Gregor2373c592009-05-31 09:31:02 +00006294 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006295 ClassTemplatePartialSpecializationDecl *PrevPartial
6296 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006297 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006298 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006299 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006300 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006301 TemplateParams,
6302 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006303 Converted.data(),
6304 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006305 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006306 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006307 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006308 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006309 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006310 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006311 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006312 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006313 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006314
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006315 if (!PrevPartial)
6316 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006317 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006318
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006319 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006320 // template specialization, make a note of that.
6321 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6322 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006323
Douglas Gregor91772d12009-06-13 00:26:55 +00006324 // Check that all of the template parameters of the class template
6325 // partial specialization are deducible from the template
6326 // arguments. If not, this class template partial specialization
6327 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006328 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006329 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006330 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006331 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006332
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006333 if (!DeducibleParams.all()) {
6334 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006335 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006336 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006337 << SourceRange(TemplateNameLoc, RAngleLoc);
6338 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6339 if (!DeducibleParams[I]) {
6340 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6341 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006342 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006343 diag::note_partial_spec_unused_parameter)
6344 << Param->getDeclName();
6345 else
Mike Stump11289f42009-09-09 15:08:12 +00006346 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006347 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006348 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006349 }
6350 }
6351 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006352 } else {
6353 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006354 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006355 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006356 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006357 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006358 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006359 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006360 Converted.data(),
6361 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006362 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006363 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006364 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006365 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006366 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006367 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006368 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006369
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006370 if (!PrevDecl)
6371 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006372
6373 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006374 }
6375
Douglas Gregor06db9f52009-10-12 20:18:28 +00006376 // C++ [temp.expl.spec]p6:
6377 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006379 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006380 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006381 // use occurs; no diagnostic is required.
6382 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006383 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006384 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006385 // Is there any previous explicit specialization declaration?
6386 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6387 Okay = true;
6388 break;
6389 }
6390 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006391
Douglas Gregorc854c662010-02-26 06:03:23 +00006392 if (!Okay) {
6393 SourceRange Range(TemplateNameLoc, RAngleLoc);
6394 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6395 << Context.getTypeDeclType(Specialization) << Range;
6396
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006397 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006398 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006399 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006400 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006401 return true;
6402 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006404
Douglas Gregor2208a292009-09-26 20:57:03 +00006405 // If this is not a friend, note that this is an explicit specialization.
6406 if (TUK != TUK_Friend)
6407 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006408
6409 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006410 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006411 RecordDecl *Def = Specialization->getDefinition();
6412 NamedDecl *Hidden = nullptr;
6413 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6414 SkipBody->ShouldSkip = true;
6415 makeMergedDefinitionVisible(Hidden, KWLoc);
6416 // From here on out, treat this as just a redeclaration.
6417 TUK = TUK_Declaration;
6418 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006419 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006420 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006421 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006422 Diag(Def->getLocation(), diag::note_previous_definition);
6423 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006424 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006425 }
6426 }
6427
John McCall659a3372010-12-18 03:30:47 +00006428 if (Attr)
6429 ProcessDeclAttributeList(S, Specialization, Attr);
6430
Richard Smith034b94a2012-08-17 03:20:55 +00006431 // Add alignment attributes if necessary; these attributes are checked when
6432 // the ASTContext lays out the structure.
6433 if (TUK == TUK_Definition) {
6434 AddAlignmentAttributesForRecord(Specialization);
6435 AddMsStructLayoutForRecord(Specialization);
6436 }
6437
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006438 if (ModulePrivateLoc.isValid())
6439 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6440 << (isPartialSpecialization? 1 : 0)
6441 << FixItHint::CreateRemoval(ModulePrivateLoc);
6442
Douglas Gregord56a91e2009-02-26 22:19:44 +00006443 // Build the fully-sugared type for this class template
6444 // specialization as the user wrote in the specialization
6445 // itself. This means that we'll pretty-print the type retrieved
6446 // from the specialization's declaration the way that the user
6447 // actually wrote the specialization, rather than formatting the
6448 // name based on the "canonical" representation used to store the
6449 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006450 TypeSourceInfo *WrittenTy
6451 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6452 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006453 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006454 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006455 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006456 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006457
Douglas Gregor1e249f82009-02-25 22:18:32 +00006458 // C++ [temp.expl.spec]p9:
6459 // A template explicit specialization is in the scope of the
6460 // namespace in which the template was defined.
6461 //
6462 // We actually implement this paragraph where we set the semantic
6463 // context (in the creation of the ClassTemplateSpecializationDecl),
6464 // but we also maintain the lexical context where the actual
6465 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006466 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006467
Douglas Gregor67a65642009-02-17 23:15:12 +00006468 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006469 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006470 Specialization->startDefinition();
6471
Douglas Gregor2208a292009-09-26 20:57:03 +00006472 if (TUK == TUK_Friend) {
6473 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6474 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006475 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006476 /*FIXME:*/KWLoc);
6477 Friend->setAccess(AS_public);
6478 CurContext->addDecl(Friend);
6479 } else {
6480 // Add the specialization into its lexical context, so that it can
6481 // be seen when iterating through the list of declarations in that
6482 // context. However, specializations are not found by name lookup.
6483 CurContext->addDecl(Specialization);
6484 }
John McCall48871652010-08-21 09:40:31 +00006485 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006486}
Douglas Gregor333489b2009-03-27 23:10:48 +00006487
John McCall48871652010-08-21 09:40:31 +00006488Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006489 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006490 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006491 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006492 ActOnDocumentableDecl(NewDecl);
6493 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006494}
6495
John McCall48871652010-08-21 09:40:31 +00006496Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00006497 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006498 Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006499 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006500 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00006501
Douglas Gregor17a7c122009-06-24 00:54:41 +00006502 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00006503 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00006504 }
Mike Stump11289f42009-09-09 15:08:12 +00006505
Douglas Gregor17a7c122009-06-24 00:54:41 +00006506 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006507
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006508 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00006509 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006510 TemplateParameterLists);
Argyrios Kyrtzidis6fada2d2012-12-14 06:53:58 +00006511 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Douglas Gregor17a7c122009-06-24 00:54:41 +00006512}
6513
John McCall4f7ced62010-02-11 01:33:53 +00006514/// \brief Strips various properties off an implicit instantiation
6515/// that has just been explicitly specialized.
6516static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006517 D->dropAttr<DLLImportAttr>();
6518 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006519
Nico Webere4974382014-12-19 23:52:45 +00006520 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006521 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006522}
6523
Nico Webera8f80b32012-01-09 19:52:25 +00006524/// \brief Compute the diagnostic location for an explicit instantiation
6525// declaration or definition.
6526static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006527 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006528 // Explicit instantiations following a specialization have no effect and
6529 // hence no PointOfInstantiation. In that case, walk decl backwards
6530 // until a valid name loc is found.
6531 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006532 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6533 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006534 PrevDiagLoc = Prev->getLocation();
6535 }
6536 assert(PrevDiagLoc.isValid() &&
6537 "Explicit instantiation without point of instantiation?");
6538 return PrevDiagLoc;
6539}
6540
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006541/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006542/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006544/// new specialization/instantiation will have any effect.
6545///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006546/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006547/// instantiation.
6548///
6549/// \param NewTSK the kind of the new explicit specialization or instantiation.
6550///
6551/// \param PrevDecl the previous declaration of the entity.
6552///
6553/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6554///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006555/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006556/// declaration was instantiated (either implicitly or explicitly).
6557///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006558/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006559/// specialization or instantiation has no effect and should be ignored.
6560///
6561/// \returns true if there was an error that should prevent the introduction of
6562/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006563bool
6564Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6565 TemplateSpecializationKind NewTSK,
6566 NamedDecl *PrevDecl,
6567 TemplateSpecializationKind PrevTSK,
6568 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006569 bool &HasNoEffect) {
6570 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006571
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006572 switch (NewTSK) {
6573 case TSK_Undeclared:
6574 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006575 assert(
6576 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6577 "previous declaration must be implicit!");
6578 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006579
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006580 case TSK_ExplicitSpecialization:
6581 switch (PrevTSK) {
6582 case TSK_Undeclared:
6583 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006585 // explicitly specialized or has merely been mentioned without any
6586 // instantiation.
6587 return false;
6588
6589 case TSK_ImplicitInstantiation:
6590 if (PrevPointOfInstantiation.isInvalid()) {
6591 // The declaration itself has not actually been instantiated, so it is
6592 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006593 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006594 return false;
6595 }
6596 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006597
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006598 case TSK_ExplicitInstantiationDeclaration:
6599 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006600 assert((PrevTSK == TSK_ImplicitInstantiation ||
6601 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006602 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006603
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006604 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006606 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006607 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006608 // implicit instantiation to take place, in every translation unit in
6609 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006610 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006611 // Is there any previous explicit specialization declaration?
6612 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6613 return false;
6614 }
6615
Douglas Gregor1d957a32009-10-27 18:42:08 +00006616 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006617 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006618 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006619 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006620
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006621 return true;
6622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006623
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006624 case TSK_ExplicitInstantiationDeclaration:
6625 switch (PrevTSK) {
6626 case TSK_ExplicitInstantiationDeclaration:
6627 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006628 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006629 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006630
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006631 case TSK_Undeclared:
6632 case TSK_ImplicitInstantiation:
6633 // We're explicitly instantiating something that may have already been
6634 // implicitly instantiated; that's fine.
6635 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006637 case TSK_ExplicitSpecialization:
6638 // C++0x [temp.explicit]p4:
6639 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006640 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006641 // specialization for that template, the explicit instantiation has no
6642 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006643 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006644 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006645
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006646 case TSK_ExplicitInstantiationDefinition:
6647 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006648 // If an entity is the subject of both an explicit instantiation
6649 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006650 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006651 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006652 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006653
6654 // Explicit instantiations following a specialization have no effect and
6655 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6656 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006657 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6658 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006659 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006660 return false;
6661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006662
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006663 case TSK_ExplicitInstantiationDefinition:
6664 switch (PrevTSK) {
6665 case TSK_Undeclared:
6666 case TSK_ImplicitInstantiation:
6667 // We're explicitly instantiating something that may have already been
6668 // implicitly instantiated; that's fine.
6669 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006670
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006671 case TSK_ExplicitSpecialization:
6672 // C++ DR 259, C++0x [temp.explicit]p4:
6673 // For a given set of template parameters, if an explicit
6674 // instantiation of a template appears after a declaration of
6675 // an explicit specialization for that template, the explicit
6676 // instantiation has no effect.
6677 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006678 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006679 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006680 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006681 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006682 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6683 diag::ext_explicit_instantiation_after_specialization)
6684 << PrevDecl;
6685 Diag(PrevDecl->getLocation(),
6686 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006687 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006688 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006689
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006690 case TSK_ExplicitInstantiationDeclaration:
6691 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006693
6694 // C++0x [temp.explicit]p4:
6695 // For a given set of template parameters, if an explicit instantiation
6696 // of a template appears after a declaration of an explicit
6697 // specialization for that template, the explicit instantiation has no
6698 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006699 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006700 // Is there any previous explicit specialization declaration?
6701 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6702 HasNoEffect = true;
6703 break;
6704 }
6705 }
6706
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006707 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006708
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006709 case TSK_ExplicitInstantiationDefinition:
6710 // C++0x [temp.spec]p5:
6711 // For a given template and a given set of template-arguments,
6712 // - an explicit instantiation definition shall appear at most once
6713 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006714
6715 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6716 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006717 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006718 : diag::err_explicit_instantiation_duplicate)
6719 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006720 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006721 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006722 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006723 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006724 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726
David Blaikie83d382b2011-09-23 05:06:16 +00006727 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006728}
6729
John McCallb9c78482010-04-08 09:05:18 +00006730/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006731/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006732///
James Dennettf14a6e52012-06-15 22:23:43 +00006733/// The only possible way to get a dependent function template specialization
6734/// is with a friend declaration, like so:
6735///
6736/// \code
6737/// template \<class T> void foo(T);
6738/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006739/// friend void foo<>(T);
6740/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006741/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006742///
6743/// There really isn't any useful analysis we can do here, so we
6744/// just store the information.
6745bool
6746Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6747 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6748 LookupResult &Previous) {
6749 // Remove anything from Previous that isn't a function template in
6750 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006751 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006752 LookupResult::Filter F = Previous.makeFilter();
6753 while (F.hasNext()) {
6754 NamedDecl *D = F.next()->getUnderlyingDecl();
6755 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006756 !FDLookupContext->InEnclosingNamespaceSetOf(
6757 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006758 F.erase();
6759 }
6760 F.done();
6761
6762 // Should this be diagnosed here?
6763 if (Previous.empty()) return true;
6764
6765 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6766 ExplicitTemplateArgs);
6767 return false;
6768}
6769
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006770/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006771/// specialization.
6772///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006773/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006774/// explicit function template specialization. On successful completion,
6775/// the function declaration \p FD will become a function template
6776/// specialization.
6777///
6778/// \param FD the function declaration, which will be updated to become a
6779/// function template specialization.
6780///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006781/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6782/// if any. Note that this may be valid info even when 0 arguments are
6783/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6784/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006785///
Francois Pichet3a44e432011-07-08 06:21:47 +00006786/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006787/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006788bool Sema::CheckFunctionTemplateSpecialization(
6789 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6790 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006791 // The set of function template specializations that could match this
6792 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006793 UnresolvedSet<8> Candidates;
Larisse Voufo98b20f12013-07-19 23:00:19 +00006794 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795
Sebastian Redl50c68252010-08-31 00:36:30 +00006796 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006797 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6798 I != E; ++I) {
6799 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6800 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006801 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006802 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006803 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6804 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006805 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006806
Richard Smith574f4f62013-01-14 05:37:29 +00006807 // When matching a constexpr member function template specialization
6808 // against the primary template, we don't yet know whether the
6809 // specialization has an implicit 'const' (because we don't know whether
6810 // it will be a static member function until we know which template it
6811 // specializes), so adjust it now assuming it specializes this template.
6812 QualType FT = FD->getType();
6813 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006814 CXXMethodDecl *OldMD =
6815 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006816 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006817 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006818 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6819 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006820 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006821 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006822 }
6823 }
6824
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006825 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006826 // A trailing template-argument can be left unspecified in the
6827 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006828 // provided it can be deduced from the function argument type.
6829 // Perform template argument deduction to determine whether we may be
6830 // specializing this template.
6831 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006832 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006833 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006834 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6835 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6836 ExplicitTemplateArgs, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006837 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006838 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006839 FailedCandidates.addCandidate()
6840 .set(FunTmpl->getTemplatedDecl(),
6841 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006842 (void)TDK;
6843 continue;
6844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006845
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006846 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00006847 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006848 }
6849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006850
Douglas Gregor5de279c2009-09-26 03:41:46 +00006851 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006852 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006853 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006854 FD->getLocation(),
6855 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6856 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006857 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006858 PDiag(diag::note_function_template_spec_matched));
6859
John McCall58cc69d2010-01-27 01:50:18 +00006860 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006861 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006862
6863 // Ignore access information; it doesn't figure into redeclaration checking.
6864 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006865
6866 FunctionTemplateSpecializationInfo *SpecInfo
6867 = Specialization->getTemplateSpecializationInfo();
6868 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006869
6870 // Note: do not overwrite location info if previous template
6871 // specialization kind was explicit.
6872 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006873 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006874 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006875 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6876 // function can differ from the template declaration with respect to
6877 // the constexpr specifier.
6878 Specialization->setConstexpr(FD->isConstexpr());
6879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006880
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006881 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006882 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006883
6884 // If this is a friend declaration, then we're not really declaring
6885 // an explicit specialization.
6886 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887
Douglas Gregor54888652009-10-07 00:13:32 +00006888 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006889 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006890 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006891 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006892 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006893 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006894 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006895
6896 // C++ [temp.expl.spec]p6:
6897 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006898 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006899 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006900 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006901 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006902 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006903 if (!isFriend &&
6904 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006905 TSK_ExplicitSpecialization,
6906 Specialization,
6907 SpecInfo->getTemplateSpecializationKind(),
6908 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006909 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006910 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006911
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006912 // Mark the prior declaration as an explicit specialization, so that later
6913 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006914 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006915 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006916 MarkUnusedFileScopedDecl(Specialization);
6917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006919 // Turn the given function declaration into a function template
6920 // specialization, with the template arguments from the previous
6921 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006922 // Take copies of (semantic and syntactic) template argument lists.
6923 const TemplateArgumentList* TemplArgs = new (Context)
6924 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregord5058122010-02-11 01:19:42 +00006925 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006926 TemplArgs, /*InsertPos=*/nullptr,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006927 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00006928 ExplicitTemplateArgs);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006929
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006930 // The "previous declaration" for this function template specialization is
6931 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006932 Previous.clear();
6933 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006934 return false;
6935}
6936
Douglas Gregor86d142a2009-10-08 07:24:58 +00006937/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006938/// specialization.
6939///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006941/// explicit member function specialization. On successful completion,
6942/// the function declaration \p FD will become a member function
6943/// specialization.
6944///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006945/// \param Member the member declaration, which will be updated to become a
6946/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006947///
John McCall1f82f242009-11-18 22:49:29 +00006948/// \param Previous the set of declarations, one of which may be specialized
6949/// by this function specialization; the set will be modified to contain the
6950/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006951bool
John McCall1f82f242009-11-18 22:49:29 +00006952Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006953 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006954
Douglas Gregor86d142a2009-10-08 07:24:58 +00006955 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00006956 NamedDecl *Instantiation = nullptr;
6957 NamedDecl *InstantiatedFrom = nullptr;
6958 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006959
John McCall1f82f242009-11-18 22:49:29 +00006960 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006961 // Nowhere to look anyway.
6962 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006963 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6964 I != E; ++I) {
6965 NamedDecl *D = (*I)->getUnderlyingDecl();
6966 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00006967 QualType Adjusted = Function->getType();
6968 if (!hasExplicitCallingConv(Adjusted))
6969 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6970 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006971 Instantiation = Method;
6972 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006973 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006974 break;
6975 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006976 }
6977 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00006978 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006979 VarDecl *PrevVar;
6980 if (Previous.isSingleResult() &&
6981 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00006982 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00006983 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006984 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006985 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006986 }
6987 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006988 CXXRecordDecl *PrevRecord;
6989 if (Previous.isSingleResult() &&
6990 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6991 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006992 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006993 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006994 }
Richard Smith7d137e32012-03-23 03:33:32 +00006995 } else if (isa<EnumDecl>(Member)) {
6996 EnumDecl *PrevEnum;
6997 if (Previous.isSingleResult() &&
6998 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6999 Instantiation = PrevEnum;
7000 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7001 MSInfo = PrevEnum->getMemberSpecializationInfo();
7002 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007004
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007005 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00007006 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007007 // specializations are always out-of-line, the caller will complain about
7008 // this mismatch later.
7009 return false;
7010 }
John McCalle820e5e2010-04-13 20:37:33 +00007011
7012 // If this is a friend, just bail out here before we start turning
7013 // things into explicit specializations.
7014 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7015 // Preserve instantiation information.
7016 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7017 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7018 cast<CXXMethodDecl>(InstantiatedFrom),
7019 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7020 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7021 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7022 cast<CXXRecordDecl>(InstantiatedFrom),
7023 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7024 }
7025
7026 Previous.clear();
7027 Previous.addDecl(Instantiation);
7028 return false;
7029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007030
Douglas Gregor86d142a2009-10-08 07:24:58 +00007031 // Make sure that this is a specialization of a member.
7032 if (!InstantiatedFrom) {
7033 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7034 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007035 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7036 return true;
7037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007038
Douglas Gregor06db9f52009-10-12 20:18:28 +00007039 // C++ [temp.expl.spec]p6:
7040 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007041 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007042 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007043 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007044 // use occurs; no diagnostic is required.
7045 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007046
Abramo Bagnara8075c852010-06-12 07:44:57 +00007047 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007048 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7049 TSK_ExplicitSpecialization,
7050 Instantiation,
7051 MSInfo->getTemplateSpecializationKind(),
7052 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007053 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007054 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007055
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007056 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007057 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007058 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007059 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007060 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007061 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007062
Douglas Gregor86d142a2009-10-08 07:24:58 +00007063 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007064 // the original declaration to note that it is an explicit specialization
7065 // (if it was previously an implicit instantiation). This latter step
7066 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007067 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007068 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7069 if (InstantiationFunction->getTemplateSpecializationKind() ==
7070 TSK_ImplicitInstantiation) {
7071 InstantiationFunction->setTemplateSpecializationKind(
7072 TSK_ExplicitSpecialization);
7073 InstantiationFunction->setLocation(Member->getLocation());
7074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007075
Douglas Gregor86d142a2009-10-08 07:24:58 +00007076 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7077 cast<CXXMethodDecl>(InstantiatedFrom),
7078 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007079 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007080 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007081 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7082 if (InstantiationVar->getTemplateSpecializationKind() ==
7083 TSK_ImplicitInstantiation) {
7084 InstantiationVar->setTemplateSpecializationKind(
7085 TSK_ExplicitSpecialization);
7086 InstantiationVar->setLocation(Member->getLocation());
7087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007088
Larisse Voufo39a1e502013-08-06 01:03:05 +00007089 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7090 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007091 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007092 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007093 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7094 if (InstantiationClass->getTemplateSpecializationKind() ==
7095 TSK_ImplicitInstantiation) {
7096 InstantiationClass->setTemplateSpecializationKind(
7097 TSK_ExplicitSpecialization);
7098 InstantiationClass->setLocation(Member->getLocation());
7099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100
Douglas Gregor86d142a2009-10-08 07:24:58 +00007101 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007102 cast<CXXRecordDecl>(InstantiatedFrom),
7103 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007104 } else {
7105 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7106 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7107 if (InstantiationEnum->getTemplateSpecializationKind() ==
7108 TSK_ImplicitInstantiation) {
7109 InstantiationEnum->setTemplateSpecializationKind(
7110 TSK_ExplicitSpecialization);
7111 InstantiationEnum->setLocation(Member->getLocation());
7112 }
7113
7114 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7115 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007118 // Save the caller the trouble of having to figure out which declaration
7119 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007120 Previous.clear();
7121 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007122 return false;
7123}
7124
Douglas Gregore47f5a72009-10-14 23:41:34 +00007125/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007126///
7127/// \returns true if a serious error occurs, false otherwise.
7128static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007129 SourceLocation InstLoc,
7130 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007131 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7132 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007133
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007134 if (CurContext->isRecord()) {
7135 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7136 << D;
7137 return true;
7138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007139
Richard Smith050d2612011-10-18 02:28:33 +00007140 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007141 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007142 // template. If the name declared in the explicit instantiation is an
7143 // unqualified name, the explicit instantiation shall appear in the
7144 // namespace where its template is declared or, if that namespace is inline
7145 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007146 //
7147 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007148 if (WasQualifiedName) {
7149 if (CurContext->Encloses(OrigContext))
7150 return false;
7151 } else {
7152 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7153 return false;
7154 }
7155
7156 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7157 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007158 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007159 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007160 diag::err_explicit_instantiation_out_of_scope :
7161 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007162 << D << NS;
7163 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007164 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007165 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007166 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7167 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7168 << D << NS;
7169 } else
7170 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007171 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007172 diag::err_explicit_instantiation_must_be_global :
7173 diag::warn_explicit_instantiation_must_be_global_0x)
7174 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007175 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007176 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007177}
7178
7179/// \brief Determine whether the given scope specifier has a template-id in it.
7180static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7181 if (!SS.isSet())
7182 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007183
Richard Smith050d2612011-10-18 02:28:33 +00007184 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007185 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007186 // or a static data member of a class template specialization, the name of
7187 // the class template specialization in the qualified-id for the member
7188 // name shall be a simple-template-id.
7189 //
7190 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007191 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7192 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007193 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007194 if (isa<TemplateSpecializationType>(T))
7195 return true;
7196
7197 return false;
7198}
7199
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007200// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007201DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007202Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007203 SourceLocation ExternLoc,
7204 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007205 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007206 SourceLocation KWLoc,
7207 const CXXScopeSpec &SS,
7208 TemplateTy TemplateD,
7209 SourceLocation TemplateNameLoc,
7210 SourceLocation LAngleLoc,
7211 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007212 SourceLocation RAngleLoc,
7213 AttributeList *Attr) {
7214 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007215 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007216 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007217 // Check that the specialization uses the same tag kind as the
7218 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007219 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7220 assert(Kind != TTK_Enum &&
7221 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007222
7223 if (isa<TypeAliasTemplateDecl>(TD)) {
7224 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7225 Diag(TD->getTemplatedDecl()->getLocation(),
7226 diag::note_previous_use);
7227 return true;
7228 }
7229
7230 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7231
Douglas Gregord9034f02009-05-14 16:41:31 +00007232 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007233 Kind, /*isDefinition*/false, KWLoc,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00007234 ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007235 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007236 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007237 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007238 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007239 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007240 diag::note_previous_use);
7241 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7242 }
7243
Douglas Gregore47f5a72009-10-14 23:41:34 +00007244 // C++0x [temp.explicit]p2:
7245 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007246 // definition and an explicit instantiation declaration. An explicit
7247 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007248 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7249 ? TSK_ExplicitInstantiationDefinition
7250 : TSK_ExplicitInstantiationDeclaration;
7251
7252 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7253 // Check for dllexport class template instantiation declarations.
7254 for (AttributeList *A = Attr; A; A = A->getNext()) {
7255 if (A->getKind() == AttributeList::AT_DLLExport) {
7256 Diag(ExternLoc,
7257 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7258 Diag(A->getLoc(), diag::note_attribute);
7259 break;
7260 }
7261 }
7262
7263 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7264 Diag(ExternLoc,
7265 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7266 Diag(A->getLocation(), diag::note_attribute);
7267 }
7268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007269
Douglas Gregora1f49972009-05-13 00:25:59 +00007270 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007271 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007272 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007273
7274 // Check that the template argument list is well-formed for this
7275 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007276 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007277 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7278 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007279 return true;
7280
Douglas Gregora1f49972009-05-13 00:25:59 +00007281 // Find the class template specialization declaration that
7282 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007283 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007284 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007285 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007286
Abramo Bagnara8075c852010-06-12 07:44:57 +00007287 TemplateSpecializationKind PrevDecl_TSK
7288 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7289
Douglas Gregor54888652009-10-07 00:13:32 +00007290 // C++0x [temp.explicit]p2:
7291 // [...] An explicit instantiation shall appear in an enclosing
7292 // namespace of its template. [...]
7293 //
7294 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007295 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7296 SS.isSet()))
7297 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007298
Craig Topperc3ec1492014-05-26 06:22:03 +00007299 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007300
Abramo Bagnara8075c852010-06-12 07:44:57 +00007301 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007302 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007303 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007304 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007305 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007306 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007307 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007308
Abramo Bagnara8075c852010-06-12 07:44:57 +00007309 // Even though HasNoEffect == true means that this explicit instantiation
7310 // has no effect on semantics, we go on to put its syntax in the AST.
7311
7312 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7313 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007314 // Since the only prior class template specialization with these
7315 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007316 // declaration node as our own, updating the source location
7317 // for the template name to reflect our new declaration.
7318 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007319 Specialization = PrevDecl;
7320 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007321 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007322 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007323 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007324
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007325 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007326 // Create a new class template specialization declaration node for
7327 // this explicit specialization.
7328 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007329 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007330 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007331 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007332 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007333 Converted.data(),
7334 Converted.size(),
7335 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007336 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007337
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007338 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007339 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007340 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007341 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007342 }
7343
7344 // Build the fully-sugared type for this explicit instantiation as
7345 // the user wrote in the explicit instantiation itself. This means
7346 // that we'll pretty-print the type retrieved from the
7347 // specialization's declaration the way that the user actually wrote
7348 // the explicit instantiation, rather than formatting the name based
7349 // on the "canonical" representation used to store the template
7350 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007351 TypeSourceInfo *WrittenTy
7352 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7353 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007354 Context.getTypeDeclType(Specialization));
7355 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007356
Abramo Bagnara8075c852010-06-12 07:44:57 +00007357 // Set source locations for keywords.
7358 Specialization->setExternLoc(ExternLoc);
7359 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007360 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007361
Rafael Espindola0b062072012-01-03 06:04:21 +00007362 if (Attr)
7363 ProcessDeclAttributeList(S, Specialization, Attr);
7364
Abramo Bagnara8075c852010-06-12 07:44:57 +00007365 // Add the explicit instantiation into its lexical context. However,
7366 // since explicit instantiations are never found by name lookup, we
7367 // just put it into the declaration context directly.
7368 Specialization->setLexicalDeclContext(CurContext);
7369 CurContext->addDecl(Specialization);
7370
7371 // Syntax is now OK, so return if it has no other effect on semantics.
7372 if (HasNoEffect) {
7373 // Set the template specialization kind.
7374 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007375 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007376 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007377
7378 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007379 // A definition of a class template or class member template
7380 // shall be in scope at the point of the explicit instantiation of
7381 // the class template or class member template.
7382 //
7383 // This check comes when we actually try to perform the
7384 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007385 ClassTemplateSpecializationDecl *Def
7386 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007387 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007388 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007389 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007390 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007391 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007392 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7393 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007394
Douglas Gregor1d957a32009-10-27 18:42:08 +00007395 // Instantiate the members of this class template specialization.
7396 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007397 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007398 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007399 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7400
7401 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7402 // TSK_ExplicitInstantiationDefinition
7403 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00007404 TSK == TSK_ExplicitInstantiationDefinition) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007405 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007406 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007407
Hans Wennborgc0875502015-06-09 00:39:05 +00007408 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7409 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7410 // In the MS ABI, an explicit instantiation definition can add a dll
7411 // attribute to a template with a previous instantiation declaration.
7412 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007413 auto *A = cast<InheritableAttr>(
7414 getDLLAttr(Specialization)->clone(getASTContext()));
7415 A->setInherited(true);
7416 Def->addAttr(A);
7417 checkClassLevelDLLAttribute(Def);
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007418
7419 // Propagate attribute to base class templates.
7420 for (auto &B : Def->bases()) {
7421 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7422 B.getType()->getAsCXXRecordDecl()))
7423 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7424 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007425 }
7426 }
7427
Douglas Gregor12e49d32009-10-15 22:53:21 +00007428 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007429 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007430
Abramo Bagnara8075c852010-06-12 07:44:57 +00007431 // Set the template specialization kind.
7432 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007433 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007434}
7435
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007436// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007437DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007438Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007439 SourceLocation ExternLoc,
7440 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007441 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007442 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007443 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007444 IdentifierInfo *Name,
7445 SourceLocation NameLoc,
7446 AttributeList *Attr) {
7447
Douglas Gregord6ab8742009-05-28 23:31:59 +00007448 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007449 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007450 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007451 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007452 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007453 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007454 SourceLocation(), false, TypeResult(),
7455 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007456 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7457
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007458 if (!TagD)
7459 return true;
7460
John McCall48871652010-08-21 09:40:31 +00007461 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007462 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007463
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007464 if (Tag->isInvalidDecl())
7465 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007466
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007467 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7468 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7469 if (!Pattern) {
7470 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7471 << Context.getTypeDeclType(Record);
7472 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7473 return true;
7474 }
7475
Douglas Gregore47f5a72009-10-14 23:41:34 +00007476 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007477 // If the explicit instantiation is for a class or member class, the
7478 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007479 // simple-template-id.
7480 //
7481 // C++98 has the same restriction, just worded differently.
7482 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007483 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007484 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007485
Douglas Gregore47f5a72009-10-14 23:41:34 +00007486 // C++0x [temp.explicit]p2:
7487 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007488 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007489 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007490 TemplateSpecializationKind TSK
7491 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7492 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007493
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007494 // C++0x [temp.explicit]p2:
7495 // [...] An explicit instantiation shall appear in an enclosing
7496 // namespace of its template. [...]
7497 //
7498 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007499 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007500
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007501 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007502 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007503 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007504 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007505 PrevDecl = Record;
7506 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007507 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007508 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007509 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007510 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007511 PrevDecl,
7512 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007513 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007514 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007515 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007516 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007517 return TagD;
7518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007519
Douglas Gregor12e49d32009-10-15 22:53:21 +00007520 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007521 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007522 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007523 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007524 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007525 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007526 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007527 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007528 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007529 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7530 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007531 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7532 << Pattern;
7533 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007534 } else {
7535 if (InstantiateClass(NameLoc, Record, Def,
7536 getTemplateInstantiationArgs(Record),
7537 TSK))
7538 return true;
7539
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007540 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007541 if (!RecordDef)
7542 return true;
7543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007544 }
7545
Douglas Gregor1d957a32009-10-27 18:42:08 +00007546 // Instantiate all of the members of the class.
7547 InstantiateClassMembers(NameLoc, RecordDef,
7548 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007549
Douglas Gregor88d292c2010-05-13 16:44:06 +00007550 if (TSK == TSK_ExplicitInstantiationDefinition)
7551 MarkVTableUsed(NameLoc, RecordDef, true);
7552
Mike Stump87c57ac2009-05-16 07:39:55 +00007553 // FIXME: We don't have any representation for explicit instantiations of
7554 // member classes. Such a representation is not needed for compilation, but it
7555 // should be available for clients that want to see all of the declarations in
7556 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007557 return TagD;
7558}
7559
John McCallfaf5fb42010-08-26 23:41:50 +00007560DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7561 SourceLocation ExternLoc,
7562 SourceLocation TemplateLoc,
7563 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007564 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007565 // TODO: check if/when DNInfo should replace Name.
7566 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7567 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007568 if (!Name) {
7569 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007570 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007571 diag::err_explicit_instantiation_requires_name)
7572 << D.getDeclSpec().getSourceRange()
7573 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007574
Douglas Gregor450f00842009-09-25 18:43:00 +00007575 return true;
7576 }
7577
7578 // The scope passed in may not be a decl scope. Zip up the scope tree until
7579 // we find one that is.
7580 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7581 (S->getFlags() & Scope::TemplateParamScope) != 0)
7582 S = S->getParent();
7583
7584 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007585 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7586 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007587 if (R.isNull())
7588 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007589
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007590 // C++ [dcl.stc]p1:
7591 // A storage-class-specifier shall not be specified in [...] an explicit
7592 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007593 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007594 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7595 << Name;
7596 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007597 } else if (D.getDeclSpec().getStorageClassSpec()
7598 != DeclSpec::SCS_unspecified) {
7599 // Complain about then remove the storage class specifier.
7600 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7601 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7602
7603 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007604 }
7605
Douglas Gregor3c74d412009-10-14 20:14:33 +00007606 // C++0x [temp.explicit]p1:
7607 // [...] An explicit instantiation of a function template shall not use the
7608 // inline or constexpr specifiers.
7609 // Presumably, this also applies to member functions of class templates as
7610 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007611 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007612 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007613 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007614 diag::err_explicit_instantiation_inline :
7615 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007616 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007617 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007618 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7619 // not already specified.
7620 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7621 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007622
Douglas Gregore47f5a72009-10-14 23:41:34 +00007623 // C++0x [temp.explicit]p2:
7624 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007625 // definition and an explicit instantiation declaration. An explicit
7626 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007627 TemplateSpecializationKind TSK
7628 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7629 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007630
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007631 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007632 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007633
7634 if (!R->isFunctionType()) {
7635 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007636 // A [...] static data member of a class template can be explicitly
7637 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007638 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007639 // C++1y [temp.explicit]p1:
7640 // A [...] variable [...] template specialization can be explicitly
7641 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007642 if (Previous.isAmbiguous())
7643 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007644
John McCall67c00872009-12-02 08:25:40 +00007645 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007646 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007647
Larisse Voufo39a1e502013-08-06 01:03:05 +00007648 if (!PrevTemplate) {
7649 if (!Prev || !Prev->isStaticDataMember()) {
7650 // We expect to see a data data member here.
7651 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7652 << Name;
7653 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7654 P != PEnd; ++P)
7655 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7656 return true;
7657 }
7658
7659 if (!Prev->getInstantiatedFromStaticDataMember()) {
7660 // FIXME: Check for explicit specialization?
7661 Diag(D.getIdentifierLoc(),
7662 diag::err_explicit_instantiation_data_member_not_instantiated)
7663 << Prev;
7664 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7665 // FIXME: Can we provide a note showing where this was declared?
7666 return true;
7667 }
7668 } else {
7669 // Explicitly instantiate a variable template.
7670
7671 // C++1y [dcl.spec.auto]p6:
7672 // ... A program that uses auto or decltype(auto) in a context not
7673 // explicitly allowed in this section is ill-formed.
7674 //
7675 // This includes auto-typed variable template instantiations.
7676 if (R->isUndeducedType()) {
7677 Diag(T->getTypeLoc().getLocStart(),
7678 diag::err_auto_not_allowed_var_inst);
7679 return true;
7680 }
7681
Richard Smithef985ac2013-09-18 02:10:12 +00007682 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7683 // C++1y [temp.explicit]p3:
7684 // If the explicit instantiation is for a variable, the unqualified-id
7685 // in the declaration shall be a template-id.
7686 Diag(D.getIdentifierLoc(),
7687 diag::err_explicit_instantiation_without_template_id)
7688 << PrevTemplate;
7689 Diag(PrevTemplate->getLocation(),
7690 diag::note_explicit_instantiation_here);
7691 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007692 }
7693
Richard Smithef985ac2013-09-18 02:10:12 +00007694 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007695 TemplateArgumentListInfo TemplateArgs =
7696 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007697
Larisse Voufo39a1e502013-08-06 01:03:05 +00007698 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7699 D.getIdentifierLoc(), TemplateArgs);
7700 if (Res.isInvalid())
7701 return true;
7702
7703 // Ignore access control bits, we don't need them for redeclaration
7704 // checking.
7705 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007707
Douglas Gregore47f5a72009-10-14 23:41:34 +00007708 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007709 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007710 // or a static data member of a class template specialization, the name of
7711 // the class template specialization in the qualified-id for the member
7712 // name shall be a simple-template-id.
7713 //
7714 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007715 //
Richard Smith5977d872013-09-18 21:55:14 +00007716 // This does not apply to variable template specializations, where the
7717 // template-id is in the unqualified-id instead.
7718 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007719 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007720 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007721 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007722
Douglas Gregore47f5a72009-10-14 23:41:34 +00007723 // Check the scope of this explicit instantiation.
7724 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007725
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007726 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007727 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7728 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007729 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007730 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007731 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007732 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007733
Larisse Voufo39a1e502013-08-06 01:03:05 +00007734 if (!HasNoEffect) {
7735 // Instantiate static data member or variable template.
7736
7737 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7738 if (PrevTemplate) {
7739 // Merge attributes.
7740 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7741 ProcessDeclAttributeList(S, Prev, Attr);
7742 }
7743 if (TSK == TSK_ExplicitInstantiationDefinition)
7744 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7745 }
7746
7747 // Check the new variable specialization against the parsed input.
7748 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7749 Diag(T->getTypeLoc().getLocStart(),
7750 diag::err_invalid_var_template_spec_type)
7751 << 0 << PrevTemplate << R << Prev->getType();
7752 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7753 << 2 << PrevTemplate->getDeclName();
7754 return true;
7755 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007756
Douglas Gregor450f00842009-09-25 18:43:00 +00007757 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007758 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007760
7761 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007762 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007763 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007764 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007765 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007766 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007767 HasExplicitTemplateArgs = true;
7768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007769
Douglas Gregor450f00842009-09-25 18:43:00 +00007770 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007771 // A [...] function [...] can be explicitly instantiated from its template.
7772 // A member function [...] of a class template can be explicitly
7773 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007774 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007775 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007776 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007777 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7778 P != PEnd; ++P) {
7779 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007780 if (!HasExplicitTemplateArgs) {
7781 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007782 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7783 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007784 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007785
John McCall58cc69d2010-01-27 01:50:18 +00007786 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007787 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7788 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007789 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007790 }
7791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007792
Douglas Gregor450f00842009-09-25 18:43:00 +00007793 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7794 if (!FunTmpl)
7795 continue;
7796
Larisse Voufo98b20f12013-07-19 23:00:19 +00007797 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007798 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007799 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007800 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007801 (HasExplicitTemplateArgs ? &TemplateArgs
7802 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007803 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007804 // Keep track of almost-matches.
7805 FailedCandidates.addCandidate()
7806 .set(FunTmpl->getTemplatedDecl(),
7807 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007808 (void)TDK;
7809 continue;
7810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007811
John McCall58cc69d2010-01-27 01:50:18 +00007812 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007814
Douglas Gregor450f00842009-09-25 18:43:00 +00007815 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007816 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007817 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007818 D.getIdentifierLoc(),
7819 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7820 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7821 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007822
John McCall58cc69d2010-01-27 01:50:18 +00007823 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007824 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007825
7826 // Ignore access control bits, we don't need them for redeclaration checking.
7827 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007828
Alexey Bataev73983912014-11-06 10:10:50 +00007829 // C++11 [except.spec]p4
7830 // In an explicit instantiation an exception-specification may be specified,
7831 // but is not required.
7832 // If an exception-specification is specified in an explicit instantiation
7833 // directive, it shall be compatible with the exception-specifications of
7834 // other declarations of that function.
7835 if (auto *FPT = R->getAs<FunctionProtoType>())
7836 if (FPT->hasExceptionSpec()) {
7837 unsigned DiagID =
7838 diag::err_mismatched_exception_spec_explicit_instantiation;
7839 if (getLangOpts().MicrosoftExt)
7840 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7841 bool Result = CheckEquivalentExceptionSpec(
7842 PDiag(DiagID) << Specialization->getType(),
7843 PDiag(diag::note_explicit_instantiation_here),
7844 Specialization->getType()->getAs<FunctionProtoType>(),
7845 Specialization->getLocation(), FPT, D.getLocStart());
7846 // In Microsoft mode, mismatching exception specifications just cause a
7847 // warning.
7848 if (!getLangOpts().MicrosoftExt && Result)
7849 return true;
7850 }
7851
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007852 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007853 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007854 diag::err_explicit_instantiation_member_function_not_instantiated)
7855 << Specialization
7856 << (Specialization->getTemplateSpecializationKind() ==
7857 TSK_ExplicitSpecialization);
7858 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7859 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007860 }
7861
Douglas Gregorec9fd132012-01-14 16:38:05 +00007862 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007863 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7864 PrevDecl = Specialization;
7865
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007866 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007867 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007868 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007869 PrevDecl,
7870 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007871 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007872 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007873 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007874
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007875 // FIXME: We may still want to build some representation of this
7876 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007877 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007878 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007879 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007880
7881 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007882 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7883 if (Attr)
7884 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007885
Richard Smitheb36ddf2014-04-24 22:45:46 +00007886 if (Specialization->isDefined()) {
7887 // Let the ASTConsumer know that this function has been explicitly
7888 // instantiated now, and its linkage might have changed.
7889 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7890 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007891 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007892
Douglas Gregore47f5a72009-10-14 23:41:34 +00007893 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007894 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007895 // or a static data member of a class template specialization, the name of
7896 // the class template specialization in the qualified-id for the member
7897 // name shall be a simple-template-id.
7898 //
7899 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007900 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007901 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007903 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007904 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007905 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007906 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007907
Douglas Gregore47f5a72009-10-14 23:41:34 +00007908 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007909 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007910 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007911 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007912 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007913
Douglas Gregor450f00842009-09-25 18:43:00 +00007914 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007915 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007916}
7917
John McCallfaf5fb42010-08-26 23:41:50 +00007918TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007919Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7920 const CXXScopeSpec &SS, IdentifierInfo *Name,
7921 SourceLocation TagLoc, SourceLocation NameLoc) {
7922 // This has to hold, because SS is expected to be defined.
7923 assert(Name && "Expected a name in a dependent tag");
7924
Aaron Ballman4a979672014-01-03 13:56:08 +00007925 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007926 if (!NNS)
7927 return true;
7928
Abramo Bagnara6150c882010-05-11 21:36:43 +00007929 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007930
Douglas Gregorba41d012010-04-24 16:38:41 +00007931 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7932 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007933 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007934 return true;
7935 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007936
Douglas Gregore7c20652011-03-02 00:47:37 +00007937 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007938 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007939 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7940
7941 // Create type-source location information for this type.
7942 TypeLocBuilder TLB;
7943 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007944 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007945 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7946 TL.setNameLoc(NameLoc);
7947 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00007948}
7949
John McCallfaf5fb42010-08-26 23:41:50 +00007950TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007951Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7952 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00007953 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007954 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00007955 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007956
Richard Smith0bf8a4922011-10-18 20:49:44 +00007957 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7958 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007959 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007960 diag::warn_cxx98_compat_typename_outside_of_template :
7961 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007962 << FixItHint::CreateRemoval(TypenameLoc);
7963
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007964 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00007965 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7966 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00007967 if (T.isNull())
7968 return true;
John McCall99b2fe52010-04-29 23:50:39 +00007969
7970 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7971 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00007972 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007973 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007974 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00007975 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007976 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00007977 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007978 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007979 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00007980 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982
John McCallba7bf592010-08-24 05:47:05 +00007983 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00007984}
7985
John McCallfaf5fb42010-08-26 23:41:50 +00007986TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007987Sema::ActOnTypenameType(Scope *S,
7988 SourceLocation TypenameLoc,
7989 const CXXScopeSpec &SS,
7990 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00007991 TemplateTy TemplateIn,
7992 SourceLocation TemplateNameLoc,
7993 SourceLocation LAngleLoc,
7994 ASTTemplateArgsPtr TemplateArgsIn,
7995 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00007996 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7997 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007998 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007999 diag::warn_cxx98_compat_typename_outside_of_template :
8000 diag::ext_typename_outside_of_template)
8001 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008002
8003 // Translate the parser's template argument list in our AST format.
8004 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8005 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8006
8007 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008008 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8009 // Construct a dependent template specialization type.
8010 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008011 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008012 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8013 DTN->getQualifier(),
8014 DTN->getIdentifier(),
8015 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008016
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008017 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008018 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008019 DependentTemplateSpecializationTypeLoc SpecTL
8020 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008021 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8022 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008023 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008024 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008025 SpecTL.setLAngleLoc(LAngleLoc);
8026 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008027 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8028 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008029 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008030 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008031
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008032 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8033 if (T.isNull())
8034 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008035
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008036 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008037 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008038 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008039 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008040 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8041 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008042 SpecTL.setLAngleLoc(LAngleLoc);
8043 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008044 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8045 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8046
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008047 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8048 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008049 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008050 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8051
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008052 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8053 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008054}
8055
Douglas Gregorb09518c2011-02-27 22:46:49 +00008056
Richard Smith6f8d2c62012-05-09 05:17:00 +00008057/// Determine whether this failed name lookup should be treated as being
8058/// disabled by a usage of std::enable_if.
8059static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8060 SourceRange &CondRange) {
8061 // We must be looking for a ::type...
8062 if (!II.isStr("type"))
8063 return false;
8064
8065 // ... within an explicitly-written template specialization...
8066 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8067 return false;
8068 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008069 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8070 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8071 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008072 return false;
8073 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008074 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008075
8076 // ... which names a complete class template declaration...
8077 const TemplateDecl *EnableIfDecl =
8078 EnableIfTST->getTemplateName().getAsTemplateDecl();
8079 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8080 return false;
8081
8082 // ... called "enable_if".
8083 const IdentifierInfo *EnableIfII =
8084 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8085 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8086 return false;
8087
8088 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008089 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008090 return true;
8091}
8092
Douglas Gregor333489b2009-03-27 23:10:48 +00008093/// \brief Build the type that describes a C++ typename specifier,
8094/// e.g., "typename T::type".
8095QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008096Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8097 SourceLocation KeywordLoc,
8098 NestedNameSpecifierLoc QualifierLoc,
8099 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008100 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008101 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008102 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008103
John McCall0b66eb32010-05-01 00:40:08 +00008104 DeclContext *Ctx = computeDeclContext(SS);
8105 if (!Ctx) {
8106 // If the nested-name-specifier is dependent and couldn't be
8107 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008108 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8109 return Context.getDependentNameType(Keyword,
8110 QualifierLoc.getNestedNameSpecifier(),
8111 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008112 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008113
John McCall0b66eb32010-05-01 00:40:08 +00008114 // If the nested-name-specifier refers to the current instantiation,
8115 // the "typename" keyword itself is superfluous. In C++03, the
8116 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8117 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008118 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008119
John McCall0b66eb32010-05-01 00:40:08 +00008120 if (RequireCompleteDeclContext(SS, Ctx))
8121 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008122
8123 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008124 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008125 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008126 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008127 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008128 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008129 case LookupResult::NotFound: {
8130 // If we're looking up 'type' within a template named 'enable_if', produce
8131 // a more specific diagnostic.
8132 SourceRange CondRange;
8133 if (isEnableIf(QualifierLoc, II, CondRange)) {
8134 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8135 << Ctx << CondRange;
8136 return QualType();
8137 }
8138
Douglas Gregore40876a2009-10-13 21:16:44 +00008139 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008140 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008141 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008142
8143 case LookupResult::FoundUnresolvedValue: {
8144 // We found a using declaration that is a value. Most likely, the using
8145 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008146 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008147 IILoc);
8148 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8149 << Name << Ctx << FullRange;
8150 if (UnresolvedUsingValueDecl *Using
8151 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008152 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008153 Diag(Loc, diag::note_using_value_decl_missing_typename)
8154 << FixItHint::CreateInsertion(Loc, "typename ");
8155 }
8156 }
8157 // Fall through to create a dependent typename type, from which we can recover
8158 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008159
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008160 case LookupResult::NotFoundInCurrentInstantiation:
8161 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008162 return Context.getDependentNameType(Keyword,
8163 QualifierLoc.getNestedNameSpecifier(),
8164 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008165
8166 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008167 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008168 // We found a type. Build an ElaboratedType, since the
8169 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008170 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008171 return Context.getElaboratedType(ETK_Typename,
8172 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008173 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008174 }
8175
8176 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008177 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008178 break;
8179
8180 case LookupResult::FoundOverloaded:
8181 DiagID = diag::err_typename_nested_not_type;
8182 Referenced = *Result.begin();
8183 break;
8184
John McCall6538c932009-10-10 05:48:19 +00008185 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008186 return QualType();
8187 }
8188
8189 // If we get here, it's because name lookup did not find a
8190 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008191 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008192 IILoc);
8193 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008194 if (Referenced)
8195 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8196 << Name;
8197 return QualType();
8198}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008199
8200namespace {
8201 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008202 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008203 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008204 SourceLocation Loc;
8205 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008206
Douglas Gregor15acfb92009-08-06 16:20:37 +00008207 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008208 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008209
Mike Stump11289f42009-09-09 15:08:12 +00008210 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008211 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008212 DeclarationName Entity)
8213 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008214 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008215
8216 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008217 /// transformed.
8218 ///
8219 /// For the purposes of type reconstruction, a type has already been
8220 /// transformed if it is NULL or if it is not dependent.
8221 bool AlreadyTransformed(QualType T) {
8222 return T.isNull() || !T->isDependentType();
8223 }
Mike Stump11289f42009-09-09 15:08:12 +00008224
8225 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008226 /// rebuilt.
8227 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008228
Douglas Gregor15acfb92009-08-06 16:20:37 +00008229 /// \brief Returns the name of the entity whose type is being rebuilt.
8230 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008231
Douglas Gregoref6ab412009-10-27 06:26:26 +00008232 /// \brief Sets the "base" location and entity when that
8233 /// information is known based on another transformation.
8234 void setBase(SourceLocation Loc, DeclarationName Entity) {
8235 this->Loc = Loc;
8236 this->Entity = Entity;
8237 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008238
8239 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8240 // Lambdas never need to be transformed.
8241 return E;
8242 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008243 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008244}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008245
Douglas Gregor15acfb92009-08-06 16:20:37 +00008246/// \brief Rebuilds a type within the context of the current instantiation.
8247///
Mike Stump11289f42009-09-09 15:08:12 +00008248/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008249/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008250/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008251/// partial specialization thereof). This routine will rebuild that type now
8252/// that we have entered the declarator's scope, which may produce different
8253/// canonical types, e.g.,
8254///
8255/// \code
8256/// template<typename T>
8257/// struct X {
8258/// typedef T* pointer;
8259/// pointer data();
8260/// };
8261///
8262/// template<typename T>
8263/// typename X<T>::pointer X<T>::data() { ... }
8264/// \endcode
8265///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008266/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008267/// since we do not know that we can look into X<T> when we parsed the type.
8268/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008269/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008270/// as the canonical type of T*, allowing the return types of the out-of-line
8271/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008272TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8273 SourceLocation Loc,
8274 DeclarationName Name) {
8275 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008276 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008277
Douglas Gregor15acfb92009-08-06 16:20:37 +00008278 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8279 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008280}
Douglas Gregorbe999392009-09-15 16:23:51 +00008281
John McCalldadc5752010-08-24 06:29:42 +00008282ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008283 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8284 DeclarationName());
8285 return Rebuilder.TransformExpr(E);
8286}
8287
John McCall99b2fe52010-04-29 23:50:39 +00008288bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008289 if (SS.isInvalid())
8290 return true;
John McCall2408e322010-04-27 00:57:59 +00008291
Douglas Gregor10176412011-02-25 16:07:42 +00008292 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008293 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8294 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008295 NestedNameSpecifierLoc Rebuilt
8296 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8297 if (!Rebuilt)
8298 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008299
Douglas Gregor10176412011-02-25 16:07:42 +00008300 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008301 return false;
John McCall2408e322010-04-27 00:57:59 +00008302}
8303
Douglas Gregor041b0842011-10-14 15:31:12 +00008304/// \brief Rebuild the template parameters now that we know we're in a current
8305/// instantiation.
8306bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8307 TemplateParameterList *Params) {
8308 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8309 Decl *Param = Params->getParam(I);
8310
8311 // There is nothing to rebuild in a type parameter.
8312 if (isa<TemplateTypeParmDecl>(Param))
8313 continue;
8314
8315 // Rebuild the template parameter list of a template template parameter.
8316 if (TemplateTemplateParmDecl *TTP
8317 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8318 if (RebuildTemplateParamsInCurrentInstantiation(
8319 TTP->getTemplateParameters()))
8320 return true;
8321
8322 continue;
8323 }
8324
8325 // Rebuild the type of a non-type template parameter.
8326 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8327 TypeSourceInfo *NewTSI
8328 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8329 NTTP->getLocation(),
8330 NTTP->getDeclName());
8331 if (!NewTSI)
8332 return true;
8333
8334 if (NewTSI != NTTP->getTypeSourceInfo()) {
8335 NTTP->setTypeSourceInfo(NewTSI);
8336 NTTP->setType(NewTSI->getType());
8337 }
8338 }
8339
8340 return false;
8341}
8342
Douglas Gregorbe999392009-09-15 16:23:51 +00008343/// \brief Produces a formatted string that describes the binding of
8344/// template parameters to template arguments.
8345std::string
8346Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8347 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008348 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008349}
8350
8351std::string
8352Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8353 const TemplateArgument *Args,
8354 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008355 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008356 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008357
Douglas Gregore62e6a02009-11-11 19:13:48 +00008358 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008359 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008360
Douglas Gregorbe999392009-09-15 16:23:51 +00008361 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008362 if (I >= NumArgs)
8363 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008364
Douglas Gregorbe999392009-09-15 16:23:51 +00008365 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008366 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008367 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008368 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008369
Douglas Gregorbe999392009-09-15 16:23:51 +00008370 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008371 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008372 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008373 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008375
Douglas Gregor0192c232010-12-20 16:52:59 +00008376 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008377 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008378 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008379
8380 Out << ']';
8381 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008382}
Francois Pichet1c229c02011-04-22 22:18:13 +00008383
Richard Smithe40f2ba2013-08-07 21:41:30 +00008384void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8385 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008386 if (!FD)
8387 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008388
8389 LateParsedTemplate *LPT = new LateParsedTemplate;
8390
8391 // Take tokens to avoid allocations
8392 LPT->Toks.swap(Toks);
8393 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008394 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008395
8396 FD->setLateTemplateParsed(true);
8397}
8398
8399void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8400 if (!FD)
8401 return;
8402 FD->setLateTemplateParsed(false);
8403}
Francois Pichet1c229c02011-04-22 22:18:13 +00008404
8405bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8406 DeclContext *DC = CurContext;
8407
8408 while (DC) {
8409 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8410 const FunctionDecl *FD = RD->isLocalClass();
8411 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8412 } else if (DC->isTranslationUnit() || DC->isNamespace())
8413 return false;
8414
8415 DC = DC->getParent();
8416 }
8417 return false;
8418}