blob: 79df1f210e668aeca53ea33c69cf72e8c78c2ad7 [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.
960 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
961 ForRedeclaration);
962 DeclContext *LookupContext = SemanticContext;
963 while (LookupContext->isTransparentContext())
964 LookupContext = LookupContext->getLookupParent();
965 LookupQualifiedName(Previous, LookupContext);
966
967 if (Previous.isAmbiguous())
968 return true;
969
970 if (Previous.begin() != Previous.end())
971 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000972 }
John McCall90d3bb92009-12-17 23:21:11 +0000973 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000974 } else if (PrevDecl &&
975 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000976 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000977
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000978 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000979 // Ensure that the template parameter lists are compatible. Skip this check
980 // for a friend in a dependent context: the template parameter list itself
981 // could be dependent.
982 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
983 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000984 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000985 /*Complain=*/true,
986 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000987 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000988
989 // C++ [temp.class]p4:
990 // In a redeclaration, partial specialization, explicit
991 // specialization or explicit instantiation of a class template,
992 // the class-key shall agree in kind with the original class
993 // template declaration (7.1.5.3).
994 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +0000995 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
996 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000997 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000998 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000999 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001000 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00001001 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001002 }
1003
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001004 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001005 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001006 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Richard Smithbe3980b2015-03-27 00:41:57 +00001007 // If we have a prior definition that is not visible, treat this as
1008 // simply making that previous definition visible.
1009 NamedDecl *Hidden = nullptr;
1010 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
Richard Smithd9ba2242015-05-07 03:54:19 +00001011 SkipBody->ShouldSkip = true;
Richard Smithbe3980b2015-03-27 00:41:57 +00001012 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1013 assert(Tmpl && "original definition of a class template is not a "
1014 "class template?");
Richard Smithd9ba2242015-05-07 03:54:19 +00001015 makeMergedDefinitionVisible(Hidden, KWLoc);
1016 makeMergedDefinitionVisible(Tmpl, KWLoc);
Richard Smithbe3980b2015-03-27 00:41:57 +00001017 return Def;
1018 }
1019
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001020 Diag(NameLoc, diag::err_redefinition) << Name;
1021 Diag(Def->getLocation(), diag::note_previous_definition);
1022 // FIXME: Would it make sense to try to "forget" the previous
1023 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001024 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001025 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001026 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001027 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1028 // Maybe we will complain about the shadowed template parameter.
1029 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1030 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001031 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001032 } else if (PrevDecl) {
1033 // C++ [temp]p5:
1034 // A class template shall not have the same name as any other
1035 // template, class, function, object, enumeration, enumerator,
1036 // namespace, or type in the same scope (3.3), except as specified
1037 // in (14.5.4).
1038 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1039 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001040 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001041 }
1042
Douglas Gregordba32632009-02-10 19:49:53 +00001043 // Check the template parameter list of this declaration, possibly
1044 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001045 // template declaration. Skip this check for a friend in a dependent
1046 // context, because the template parameter list might be dependent.
1047 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001048 CheckTemplateParameterList(
1049 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001050 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1051 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001052 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1053 SemanticContext->isDependentContext())
1054 ? TPC_ClassTemplateMember
1055 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1056 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001057 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001058
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001059 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001060 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001061 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001062 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1063 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001064 : diag::err_member_decl_does_not_match)
1065 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001066 Invalid = true;
1067 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068 }
1069
Mike Stump11289f42009-09-09 15:08:12 +00001070 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001071 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001072 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001073 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001074 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001075 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001076 if (NumOuterTemplateParamLists > 0)
1077 NewClass->setTemplateParameterListsInfo(Context,
1078 NumOuterTemplateParamLists,
1079 OuterTemplateParamLists);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001080
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001081 // Add alignment attributes if necessary; these attributes are checked when
1082 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001083 if (TUK == TUK_Definition) {
1084 AddAlignmentAttributesForRecord(NewClass);
1085 AddMsStructLayoutForRecord(NewClass);
1086 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001087
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001088 ClassTemplateDecl *NewTemplate
1089 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1090 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001091 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001092 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001093
Douglas Gregor21823bf2011-12-20 18:11:52 +00001094 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001095 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001096
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001097 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001098 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001099 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001100 assert(T->isDependentType() && "Class template type is not dependent?");
1101 (void)T;
1102
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001103 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001104 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001106 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1107 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
Anders Carlsson137108d2009-03-26 01:24:28 +00001109 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001110 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001111 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001112
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001113 // Set the lexical context of these templates
1114 NewClass->setLexicalDeclContext(CurContext);
1115 NewTemplate->setLexicalDeclContext(CurContext);
1116
John McCall9bb74a52009-07-31 02:45:11 +00001117 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001118 NewClass->startDefinition();
1119
1120 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001121 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001122
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001123 if (PrevClassTemplate)
1124 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1125
Rafael Espindola385c0422012-07-13 18:04:45 +00001126 AddPushedVisibilityAttribute(NewClass);
1127
Richard Smith234ff472014-08-23 00:49:01 +00001128 if (TUK != TUK_Friend) {
1129 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1130 Scope *Outer = S;
1131 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1132 Outer = Outer->getParent();
1133 PushOnScopeChains(NewTemplate, Outer);
1134 } else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001135 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001136 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001137 NewClass->setAccess(PrevClassTemplate->getAccess());
1138 }
John McCall27b5c252009-09-14 21:59:20 +00001139
Richard Smith64017682013-07-17 23:53:16 +00001140 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141
John McCall27b5c252009-09-14 21:59:20 +00001142 // Friend templates are visible in fairly strange ways.
1143 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001144 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001145 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001146 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1147 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001148 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001150
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00001151 FriendDecl *Friend = FriendDecl::Create(
1152 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
Douglas Gregor3dad8422009-09-26 06:47:28 +00001153 Friend->setAccess(AS_public);
1154 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001155 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001156
Douglas Gregordba32632009-02-10 19:49:53 +00001157 if (Invalid) {
1158 NewTemplate->setInvalidDecl();
1159 NewClass->setInvalidDecl();
1160 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001161
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001162 ActOnDocumentableDecl(NewTemplate);
1163
John McCall48871652010-08-21 09:40:31 +00001164 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001165}
1166
Douglas Gregored5731f2009-11-25 17:50:39 +00001167/// \brief Diagnose the presence of a default template argument on a
1168/// template parameter, which is ill-formed in certain contexts.
1169///
1170/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001171static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001172 Sema::TemplateParamListContext TPC,
1173 SourceLocation ParamLoc,
1174 SourceRange DefArgRange) {
1175 switch (TPC) {
1176 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001177 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001178 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001179 return false;
1180
1181 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001182 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001184 // A default template-argument shall not be specified in a
1185 // function template declaration or a function template
1186 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001187 // If a friend function template declaration specifies a default
1188 // template-argument, that declaration shall be a definition and shall be
1189 // the only declaration of the function template in the translation unit.
1190 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001191 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001192 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1193 : diag::ext_template_parameter_default_in_function_template)
1194 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001195 return false;
1196
1197 case Sema::TPC_ClassTemplateMember:
1198 // C++0x [temp.param]p9:
1199 // A default template-argument shall not be specified in the
1200 // template-parameter-lists of the definition of a member of a
1201 // class template that appears outside of the member's class.
1202 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1203 << DefArgRange;
1204 return true;
1205
David Majnemerba8f17a2013-06-25 22:08:55 +00001206 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001207 case Sema::TPC_FriendFunctionTemplate:
1208 // C++ [temp.param]p9:
1209 // A default template-argument shall not be specified in a
1210 // friend template declaration.
1211 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1212 << DefArgRange;
1213 return true;
1214
1215 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1216 // for friend function templates if there is only a single
1217 // declaration (and it is a definition). Strange!
1218 }
1219
David Blaikie8a40f702012-01-17 06:56:22 +00001220 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001221}
1222
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001223/// \brief Check for unexpanded parameter packs within the template parameters
1224/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001225static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1226 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001227 // A template template parameter which is a parameter pack is also a pack
1228 // expansion.
1229 if (TTP->isParameterPack())
1230 return false;
1231
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001232 TemplateParameterList *Params = TTP->getTemplateParameters();
1233 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1234 NamedDecl *P = Params->getParam(I);
1235 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001236 if (!NTTP->isParameterPack() &&
1237 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001238 NTTP->getTypeSourceInfo(),
1239 Sema::UPPC_NonTypeTemplateParameterType))
1240 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001241
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001242 continue;
1243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001244
1245 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001246 = dyn_cast<TemplateTemplateParmDecl>(P))
1247 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1248 return true;
1249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001250
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001251 return false;
1252}
1253
Douglas Gregordba32632009-02-10 19:49:53 +00001254/// \brief Checks the validity of a template parameter list, possibly
1255/// considering the template parameter list from a previous
1256/// declaration.
1257///
1258/// If an "old" template parameter list is provided, it must be
1259/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1260/// template parameter list.
1261///
1262/// \param NewParams Template parameter list for a new template
1263/// declaration. This template parameter list will be updated with any
1264/// default arguments that are carried through from the previous
1265/// template parameter list.
1266///
1267/// \param OldParams If provided, template parameter list from a
1268/// previous declaration of the same template. Default template
1269/// arguments will be merged from the old template parameter list to
1270/// the new template parameter list.
1271///
Douglas Gregored5731f2009-11-25 17:50:39 +00001272/// \param TPC Describes the context in which we are checking the given
1273/// template parameter list.
1274///
Douglas Gregordba32632009-02-10 19:49:53 +00001275/// \returns true if an error occurred, false otherwise.
1276bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001277 TemplateParameterList *OldParams,
1278 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001279 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001280
Douglas Gregordba32632009-02-10 19:49:53 +00001281 // C++ [temp.param]p10:
1282 // The set of default template-arguments available for use with a
1283 // template declaration or definition is obtained by merging the
1284 // default arguments from the definition (if in scope) and all
1285 // declarations in scope in the same way default function
1286 // arguments are (8.3.6).
1287 bool SawDefaultArgument = false;
1288 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001289
Mike Stumpc89c8e32009-02-11 23:03:27 +00001290 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001291 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001292 if (OldParams)
1293 OldParam = OldParams->begin();
1294
Douglas Gregor0693def2011-01-27 01:40:17 +00001295 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001296 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1297 NewParamEnd = NewParams->end();
1298 NewParam != NewParamEnd; ++NewParam) {
1299 // Variables used to diagnose redundant default arguments
1300 bool RedundantDefaultArg = false;
1301 SourceLocation OldDefaultLoc;
1302 SourceLocation NewDefaultLoc;
1303
David Blaikie651c73c2011-10-19 05:19:50 +00001304 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001305 bool MissingDefaultArg = false;
1306
David Blaikie651c73c2011-10-19 05:19:50 +00001307 // Variable used to diagnose non-final parameter packs
1308 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001309
Douglas Gregordba32632009-02-10 19:49:53 +00001310 if (TemplateTypeParmDecl *NewTypeParm
1311 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001312 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313 if (NewTypeParm->hasDefaultArgument() &&
1314 DiagnoseDefaultTemplateArgument(*this, TPC,
1315 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001316 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001317 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001318 NewTypeParm->removeDefaultArgument();
1319
1320 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001321 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001322 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Anders Carlsson327865d2009-06-12 23:20:15 +00001323 if (NewTypeParm->isParameterPack()) {
1324 assert(!NewTypeParm->hasDefaultArgument() &&
1325 "Parameter packs can't have a default argument!");
1326 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001327 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
John McCall0ad16662009-10-29 08:12:44 +00001328 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001329 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1330 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1331 SawDefaultArgument = true;
1332 RedundantDefaultArg = true;
1333 PreviousDefaultArgLoc = NewDefaultLoc;
1334 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1335 // Merge the default argument from the old declaration to the
1336 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001337 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001338 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1339 } else if (NewTypeParm->hasDefaultArgument()) {
1340 SawDefaultArgument = true;
1341 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1342 } else if (SawDefaultArgument)
1343 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001344 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001345 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001346 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001347 if (!NewNonTypeParm->isParameterPack() &&
1348 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001349 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001350 UPPC_NonTypeTemplateParameterType)) {
1351 Invalid = true;
1352 continue;
1353 }
1354
Douglas Gregored5731f2009-11-25 17:50:39 +00001355 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356 if (NewNonTypeParm->hasDefaultArgument() &&
1357 DiagnoseDefaultTemplateArgument(*this, TPC,
1358 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001359 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001360 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001361 }
1362
Mike Stump12b8ce12009-08-04 21:02:39 +00001363 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001364 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001365 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001366 if (NewNonTypeParm->isParameterPack()) {
1367 assert(!NewNonTypeParm->hasDefaultArgument() &&
1368 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001369 if (!NewNonTypeParm->isPackExpansion())
1370 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001371 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
Richard Smith35828f12013-07-22 03:31:14 +00001372 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001373 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1374 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1375 SawDefaultArgument = true;
1376 RedundantDefaultArg = true;
1377 PreviousDefaultArgLoc = NewDefaultLoc;
1378 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1379 // Merge the default argument from the old declaration to the
1380 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001381 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
Douglas Gregordba32632009-02-10 19:49:53 +00001382 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1383 } else if (NewNonTypeParm->hasDefaultArgument()) {
1384 SawDefaultArgument = true;
1385 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1386 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001387 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001388 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001389 TemplateTemplateParmDecl *NewTemplateParm
1390 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001392 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001393 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001394 Invalid = true;
1395 continue;
1396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001397
David Blaikie651c73c2011-10-19 05:19:50 +00001398 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399 if (NewTemplateParm->hasDefaultArgument() &&
1400 DiagnoseDefaultTemplateArgument(*this, TPC,
1401 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001402 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001403 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001404
1405 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001406 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001407 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001408 if (NewTemplateParm->isParameterPack()) {
1409 assert(!NewTemplateParm->hasDefaultArgument() &&
1410 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001411 if (!NewTemplateParm->isPackExpansion())
1412 SawParameterPack = true;
Richard Smithe7bd6de2015-06-10 20:30:23 +00001413 } else if (OldTemplateParm &&
1414 hasVisibleDefaultArgument(OldTemplateParm) &&
1415 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001416 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1417 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001418 SawDefaultArgument = true;
1419 RedundantDefaultArg = true;
1420 PreviousDefaultArgLoc = NewDefaultLoc;
1421 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1422 // Merge the default argument from the old declaration to the
1423 // new declaration.
Richard Smith1469b912015-06-10 00:29:03 +00001424 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001425 PreviousDefaultArgLoc
1426 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001427 } else if (NewTemplateParm->hasDefaultArgument()) {
1428 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001429 PreviousDefaultArgLoc
1430 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001431 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001432 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001433 }
1434
Richard Smith1fde8ec2012-09-07 02:06:42 +00001435 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001436 // If a template parameter of a primary class template or alias template
1437 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001438 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001439 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1440 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001441 Diag((*NewParam)->getLocation(),
1442 diag::err_template_param_pack_must_be_last_template_parameter);
1443 Invalid = true;
1444 }
1445
Douglas Gregordba32632009-02-10 19:49:53 +00001446 if (RedundantDefaultArg) {
1447 // C++ [temp.param]p12:
1448 // A template-parameter shall not be given default arguments
1449 // by two different declarations in the same scope.
1450 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1451 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1452 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001453 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001454 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001455 // If a template-parameter of a class template has a default
1456 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001457 // have a default template-argument supplied or be a template parameter
1458 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001459 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001460 diag::err_template_param_default_arg_missing);
1461 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1462 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001463 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001464 }
1465
1466 // If we have an old template parameter list that we're merging
1467 // in, move on to the next parameter.
1468 if (OldParams)
1469 ++OldParam;
1470 }
1471
Douglas Gregor0693def2011-01-27 01:40:17 +00001472 // We were missing some default arguments at the end of the list, so remove
1473 // all of the default arguments.
1474 if (RemoveDefaultArguments) {
1475 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1476 NewParamEnd = NewParams->end();
1477 NewParam != NewParamEnd; ++NewParam) {
1478 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1479 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001481 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1482 NTTP->removeDefaultArgument();
1483 else
1484 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1485 }
1486 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487
Douglas Gregordba32632009-02-10 19:49:53 +00001488 return Invalid;
1489}
Douglas Gregord32e0282009-02-09 23:23:08 +00001490
John McCalla020a012010-10-20 05:44:58 +00001491namespace {
1492
1493/// A class which looks for a use of a certain level of template
1494/// parameter.
1495struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1496 typedef RecursiveASTVisitor<DependencyChecker> super;
1497
1498 unsigned Depth;
1499 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001500 SourceLocation MatchLoc;
1501
1502 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001503
1504 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1505 NamedDecl *ND = Params->getParam(0);
1506 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1507 Depth = PD->getDepth();
1508 } else if (NonTypeTemplateParmDecl *PD =
1509 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1510 Depth = PD->getDepth();
1511 } else {
1512 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1513 }
1514 }
1515
Richard Smith6056d5e2014-02-09 00:54:43 +00001516 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001517 if (ParmDepth >= Depth) {
1518 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001519 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001520 return true;
1521 }
1522 return false;
1523 }
1524
Richard Smith6056d5e2014-02-09 00:54:43 +00001525 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1526 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1527 }
1528
John McCalla020a012010-10-20 05:44:58 +00001529 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1530 return !Matches(T->getDepth());
1531 }
1532
1533 bool TraverseTemplateName(TemplateName N) {
1534 if (TemplateTemplateParmDecl *PD =
1535 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001536 if (Matches(PD->getDepth()))
1537 return false;
John McCalla020a012010-10-20 05:44:58 +00001538 return super::TraverseTemplateName(N);
1539 }
1540
1541 bool VisitDeclRefExpr(DeclRefExpr *E) {
1542 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001543 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1544 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001545 return false;
John McCalla020a012010-10-20 05:44:58 +00001546 return super::VisitDeclRefExpr(E);
1547 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001548
1549 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1550 return TraverseType(T->getReplacementType());
1551 }
1552
1553 bool
1554 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1555 return TraverseTemplateArgument(T->getArgumentPack());
1556 }
1557
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001558 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1559 return TraverseType(T->getInjectedSpecializationType());
1560 }
John McCalla020a012010-10-20 05:44:58 +00001561};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001562}
John McCalla020a012010-10-20 05:44:58 +00001563
Douglas Gregor972fe532011-05-10 18:27:06 +00001564/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001565/// list.
1566static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001567DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001568 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001569 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001570 return Checker.Match;
1571}
1572
Douglas Gregor972fe532011-05-10 18:27:06 +00001573// Find the source range corresponding to the named type in the given
1574// nested-name-specifier, if any.
1575static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1576 QualType T,
1577 const CXXScopeSpec &SS) {
1578 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1579 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1580 if (const Type *CurType = NNS->getAsType()) {
1581 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1582 return NNSLoc.getTypeLoc().getSourceRange();
1583 } else
1584 break;
1585
1586 NNSLoc = NNSLoc.getPrefix();
1587 }
1588
1589 return SourceRange();
1590}
1591
Mike Stump11289f42009-09-09 15:08:12 +00001592/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001593/// specifier, returning the template parameter list that applies to the
1594/// name.
1595///
1596/// \param DeclStartLoc the start of the declaration that has a scope
1597/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001598///
Douglas Gregor972fe532011-05-10 18:27:06 +00001599/// \param DeclLoc The location of the declaration itself.
1600///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001601/// \param SS the scope specifier that will be matched to the given template
1602/// parameter lists. This scope specifier precedes a qualified name that is
1603/// being declared.
1604///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001605/// \param TemplateId The template-id following the scope specifier, if there
1606/// is one. Used to check for a missing 'template<>'.
1607///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001608/// \param ParamLists the template parameter lists, from the outermost to the
1609/// innermost template parameter lists.
1610///
John McCalle820e5e2010-04-13 20:37:33 +00001611/// \param IsFriend Whether to apply the slightly different rules for
1612/// matching template parameters to scope specifiers in friend
1613/// declarations.
1614///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001615/// \param IsExplicitSpecialization will be set true if the entity being
1616/// declared is an explicit specialization, false otherwise.
1617///
Mike Stump11289f42009-09-09 15:08:12 +00001618/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001619/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001620/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001621/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001622/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001623/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001624TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1625 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001626 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001627 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1628 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001629 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001630 Invalid = false;
1631
1632 // The sequence of nested types to which we will match up the template
1633 // parameter lists. We first build this list by starting with the type named
1634 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001635 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001636 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001637 if (SS.getScopeRep()) {
1638 if (CXXRecordDecl *Record
1639 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1640 T = Context.getTypeDeclType(Record);
1641 else
1642 T = QualType(SS.getScopeRep()->getAsType(), 0);
1643 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001644
1645 // If we found an explicit specialization that prevents us from needing
1646 // 'template<>' headers, this will be set to the location of that
1647 // explicit specialization.
1648 SourceLocation ExplicitSpecLoc;
1649
1650 while (!T.isNull()) {
1651 NestedTypes.push_back(T);
1652
1653 // Retrieve the parent of a record type.
1654 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1655 // If this type is an explicit specialization, we're done.
1656 if (ClassTemplateSpecializationDecl *Spec
1657 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1658 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1659 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1660 ExplicitSpecLoc = Spec->getLocation();
1661 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001662 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001663 } else if (Record->getTemplateSpecializationKind()
1664 == TSK_ExplicitSpecialization) {
1665 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001666 break;
1667 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001668
1669 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1670 T = Context.getTypeDeclType(Parent);
1671 else
1672 T = QualType();
1673 continue;
1674 }
1675
1676 if (const TemplateSpecializationType *TST
1677 = T->getAs<TemplateSpecializationType>()) {
1678 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1679 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1680 T = Context.getTypeDeclType(Parent);
1681 else
1682 T = QualType();
1683 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001684 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001685 }
1686
1687 // Look one step prior in a dependent template specialization type.
1688 if (const DependentTemplateSpecializationType *DependentTST
1689 = T->getAs<DependentTemplateSpecializationType>()) {
1690 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1691 T = QualType(NNS->getAsType(), 0);
1692 else
1693 T = QualType();
1694 continue;
1695 }
1696
1697 // Look one step prior in a dependent name type.
1698 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1699 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1700 T = QualType(NNS->getAsType(), 0);
1701 else
1702 T = QualType();
1703 continue;
1704 }
1705
1706 // Retrieve the parent of an enumeration type.
1707 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1708 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1709 // check here.
1710 EnumDecl *Enum = EnumT->getDecl();
1711
1712 // Get to the parent type.
1713 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1714 T = Context.getTypeDeclType(Parent);
1715 else
1716 T = QualType();
1717 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001718 }
Mike Stump11289f42009-09-09 15:08:12 +00001719
Douglas Gregor972fe532011-05-10 18:27:06 +00001720 T = QualType();
1721 }
1722 // Reverse the nested types list, since we want to traverse from the outermost
1723 // to the innermost while checking template-parameter-lists.
1724 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001725
Douglas Gregor972fe532011-05-10 18:27:06 +00001726 // C++0x [temp.expl.spec]p17:
1727 // A member or a member template may be nested within many
1728 // enclosing class templates. In an explicit specialization for
1729 // such a member, the member declaration shall be preceded by a
1730 // template<> for each enclosing class template that is
1731 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001732 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001733
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001734 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001735 if (SawNonEmptyTemplateParameterList) {
1736 Diag(DeclLoc, diag::err_specialize_member_of_template)
1737 << !Recovery << Range;
1738 Invalid = true;
1739 IsExplicitSpecialization = false;
1740 return true;
1741 }
1742
1743 return false;
1744 };
1745
1746 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1747 // Check that we can have an explicit specialization here.
1748 if (CheckExplicitSpecialization(Range, true))
1749 return true;
1750
1751 // We don't have a template header, but we should.
1752 SourceLocation ExpectedTemplateLoc;
1753 if (!ParamLists.empty())
1754 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1755 else
1756 ExpectedTemplateLoc = DeclStartLoc;
1757
1758 Diag(DeclLoc, diag::err_template_spec_needs_header)
1759 << Range
1760 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1761 return false;
1762 };
1763
Douglas Gregor972fe532011-05-10 18:27:06 +00001764 unsigned ParamIdx = 0;
1765 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1766 ++TypeIdx) {
1767 T = NestedTypes[TypeIdx];
1768
1769 // Whether we expect a 'template<>' header.
1770 bool NeedEmptyTemplateHeader = false;
1771
1772 // Whether we expect a template header with parameters.
1773 bool NeedNonemptyTemplateHeader = false;
1774
1775 // For a dependent type, the set of template parameters that we
1776 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001777 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001778
Douglas Gregor373af9b2011-05-11 23:26:17 +00001779 // C++0x [temp.expl.spec]p15:
1780 // A member or a member template may be nested within many enclosing
1781 // class templates. In an explicit specialization for such a member, the
1782 // member declaration shall be preceded by a template<> for each
1783 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001784 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1785 if (ClassTemplatePartialSpecializationDecl *Partial
1786 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1787 ExpectedTemplateParams = Partial->getTemplateParameters();
1788 NeedNonemptyTemplateHeader = true;
1789 } else if (Record->isDependentType()) {
1790 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001791 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001792 ->getTemplateParameters();
1793 NeedNonemptyTemplateHeader = true;
1794 }
1795 } else if (ClassTemplateSpecializationDecl *Spec
1796 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1797 // C++0x [temp.expl.spec]p4:
1798 // Members of an explicitly specialized class template are defined
1799 // in the same manner as members of normal classes, and not using
1800 // the template<> syntax.
1801 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1802 NeedEmptyTemplateHeader = true;
1803 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001804 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001805 } else if (Record->getTemplateSpecializationKind()) {
1806 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001807 != TSK_ExplicitSpecialization &&
1808 TypeIdx == NumTypes - 1)
1809 IsExplicitSpecialization = true;
1810
1811 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001812 }
1813 } else if (const TemplateSpecializationType *TST
1814 = T->getAs<TemplateSpecializationType>()) {
Nico Weber28900612015-01-30 02:35:21 +00001815 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001816 ExpectedTemplateParams = Template->getTemplateParameters();
1817 NeedNonemptyTemplateHeader = true;
1818 }
1819 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1820 // FIXME: We actually could/should check the template arguments here
1821 // against the corresponding template parameter list.
1822 NeedNonemptyTemplateHeader = false;
1823 }
1824
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001825 // C++ [temp.expl.spec]p16:
1826 // In an explicit specialization declaration for a member of a class
1827 // template or a member template that ap- pears in namespace scope, the
1828 // member template and some of its enclosing class templates may remain
1829 // unspecialized, except that the declaration shall not explicitly
1830 // specialize a class member template if its en- closing class templates
1831 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001832 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001833 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001834 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1835 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001836 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001837 } else
1838 SawNonEmptyTemplateParameterList = true;
1839 }
1840
Douglas Gregor972fe532011-05-10 18:27:06 +00001841 if (NeedEmptyTemplateHeader) {
1842 // If we're on the last of the types, and we need a 'template<>' header
1843 // here, then it's an explicit specialization.
1844 if (TypeIdx == NumTypes - 1)
1845 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001846
1847 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001848 if (ParamLists[ParamIdx]->size() > 0) {
1849 // The header has template parameters when it shouldn't. Complain.
1850 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1851 diag::err_template_param_list_matches_nontemplate)
1852 << T
1853 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1854 ParamLists[ParamIdx]->getRAngleLoc())
1855 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1856 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001857 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001858 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001859
Douglas Gregor972fe532011-05-10 18:27:06 +00001860 // Consume this template header.
1861 ++ParamIdx;
1862 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001863 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001864
1865 if (!IsFriend)
1866 if (DiagnoseMissingExplicitSpecialization(
1867 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001868 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001869
Douglas Gregor972fe532011-05-10 18:27:06 +00001870 continue;
1871 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001872
Douglas Gregor972fe532011-05-10 18:27:06 +00001873 if (NeedNonemptyTemplateHeader) {
1874 // In friend declarations we can have template-ids which don't
1875 // depend on the corresponding template parameter lists. But
1876 // assume that empty parameter lists are supposed to match this
1877 // template-id.
1878 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001879 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001880 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001881 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001882 else
1883 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001884 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001885
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001886 if (ParamIdx < ParamLists.size()) {
1887 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001888 if (ExpectedTemplateParams &&
1889 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1890 ExpectedTemplateParams,
1891 true, TPL_TemplateMatch))
1892 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001893
Douglas Gregor972fe532011-05-10 18:27:06 +00001894 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001895 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001896 TPC_ClassTemplateMember))
1897 Invalid = true;
1898
1899 ++ParamIdx;
1900 continue;
1901 }
1902
1903 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1904 << T
1905 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1906 Invalid = true;
1907 continue;
1908 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001909 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001910
Douglas Gregord8d297c2009-07-21 23:53:31 +00001911 // If there were at least as many template-ids as there were template
1912 // parameter lists, then there are no template parameter lists remaining for
1913 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001914 if (ParamIdx >= ParamLists.size()) {
1915 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001916 // We don't have a template header for the declaration itself, but we
1917 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001918 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001919 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1920 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001921
1922 // Fabricate an empty template parameter list for the invented header.
1923 return TemplateParameterList::Create(Context, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001924 SourceLocation(), nullptr, 0,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001925 SourceLocation());
1926 }
1927
Craig Topperc3ec1492014-05-26 06:22:03 +00001928 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001929 }
Mike Stump11289f42009-09-09 15:08:12 +00001930
Douglas Gregord8d297c2009-07-21 23:53:31 +00001931 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001932 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001933 bool HasAnyExplicitSpecHeader = false;
1934 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001935 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001936 if (ParamLists[I]->size() == 0)
1937 HasAnyExplicitSpecHeader = true;
1938 else
1939 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001940 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001941
Douglas Gregor972fe532011-05-10 18:27:06 +00001942 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001943 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1944 : diag::err_template_spec_extra_headers)
1945 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1946 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001947
1948 // If there was a specialization somewhere, such that 'template<>' is
1949 // not required, and there were any 'template<>' headers, note where the
1950 // specialization occurred.
1951 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1952 Diag(ExplicitSpecLoc,
1953 diag::note_explicit_template_spec_does_not_need_header)
1954 << NestedTypes.back();
1955
1956 // We have a template parameter list with no corresponding scope, which
1957 // means that the resulting template declaration can't be instantiated
1958 // properly (we'll end up with dependent nodes when we shouldn't).
1959 if (!AllExplicitSpecHeaders)
1960 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001963 // C++ [temp.expl.spec]p16:
1964 // In an explicit specialization declaration for a member of a class
1965 // template or a member template that ap- pears in namespace scope, the
1966 // member template and some of its enclosing class templates may remain
1967 // unspecialized, except that the declaration shall not explicitly
1968 // specialize a class member template if its en- closing class templates
1969 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001970 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001971 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1972 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001973 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001974
Douglas Gregord8d297c2009-07-21 23:53:31 +00001975 // Return the last template parameter list, which corresponds to the
1976 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001977 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001978}
1979
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001980void Sema::NoteAllFoundTemplates(TemplateName Name) {
1981 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1982 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001983 << (isa<FunctionTemplateDecl>(Template)
1984 ? 0
1985 : isa<ClassTemplateDecl>(Template)
1986 ? 1
1987 : isa<VarTemplateDecl>(Template)
1988 ? 2
1989 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1990 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001991 return;
1992 }
1993
1994 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1995 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1996 IEnd = OST->end();
1997 I != IEnd; ++I)
1998 Diag((*I)->getLocation(), diag::note_template_declared_here)
1999 << 0 << (*I)->getDeclName();
2000
2001 return;
2002 }
2003}
2004
Douglas Gregordc572a32009-03-30 22:58:21 +00002005QualType Sema::CheckTemplateIdType(TemplateName Name,
2006 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002007 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002008 DependentTemplateName *DTN
2009 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002010 if (DTN && DTN->isIdentifier())
2011 // When building a template-id where the template-name is dependent,
2012 // assume the template is a type template. Either our assumption is
2013 // correct, or the code is ill-formed and will be diagnosed when the
2014 // dependent name is substituted.
2015 return Context.getDependentTemplateSpecializationType(ETK_None,
2016 DTN->getQualifier(),
2017 DTN->getIdentifier(),
2018 TemplateArgs);
2019
Douglas Gregordc572a32009-03-30 22:58:21 +00002020 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002021 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2022 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002023 // We might have a substituted template template parameter pack. If so,
2024 // build a template specialization type for it.
2025 if (Name.getAsSubstTemplateTemplateParmPack())
2026 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002027
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002028 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2029 << Name;
2030 NoteAllFoundTemplates(Name);
2031 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002032 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002033
Douglas Gregorc40290e2009-03-09 23:48:35 +00002034 // Check that the template argument list is well-formed for this
2035 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002036 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002037 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002038 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002039 return QualType();
2040
Douglas Gregorc40290e2009-03-09 23:48:35 +00002041 QualType CanonType;
2042
Douglas Gregor678d76c2011-07-01 01:22:09 +00002043 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002044 if (TypeAliasTemplateDecl *AliasTemplate =
2045 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002046 // Find the canonical type for this type alias template specialization.
2047 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2048 if (Pattern->isInvalidDecl())
2049 return QualType();
2050
2051 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2052 Converted.data(), Converted.size());
2053
2054 // Only substitute for the innermost template argument list.
2055 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002056 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002057 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2058 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002059 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002060
Richard Smith802c4b72012-08-23 06:16:52 +00002061 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002062 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002063 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002064 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002065
Richard Smith3f1b5d02011-05-05 21:57:07 +00002066 CanonType = SubstType(Pattern->getUnderlyingType(),
2067 TemplateArgLists, AliasTemplate->getLocation(),
2068 AliasTemplate->getDeclName());
2069 if (CanonType.isNull())
2070 return QualType();
2071 } else if (Name.isDependent() ||
2072 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002073 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002074 // This class template specialization is a dependent
2075 // type. Therefore, its canonical type is another class template
2076 // specialization type that contains all of the converted
2077 // arguments in canonical form. This ensures that, e.g., A<T> and
2078 // A<T, T> have identical types when A is declared as:
2079 //
2080 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002081 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002082 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002083 Converted.data(),
2084 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002085
Douglas Gregora8e02e72009-07-28 23:00:59 +00002086 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002087 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002088 // In the future, we need to teach getTemplateSpecializationType to only
2089 // build the canonical type and return that to us.
2090 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002091
2092 // This might work out to be a current instantiation, in which
2093 // case the canonical type needs to be the InjectedClassNameType.
2094 //
2095 // TODO: in theory this could be a simple hashtable lookup; most
2096 // changes to CurContext don't change the set of current
2097 // instantiations.
2098 if (isa<ClassTemplateDecl>(Template)) {
2099 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2100 // If we get out to a namespace, we're done.
2101 if (Ctx->isFileContext()) break;
2102
2103 // If this isn't a record, keep looking.
2104 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2105 if (!Record) continue;
2106
2107 // Look for one of the two cases with InjectedClassNameTypes
2108 // and check whether it's the same template.
2109 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2110 !Record->getDescribedClassTemplate())
2111 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
John McCall2408e322010-04-27 00:57:59 +00002113 // Fetch the injected class name type and check whether its
2114 // injected type is equal to the type we just built.
2115 QualType ICNT = Context.getTypeDeclType(Record);
2116 QualType Injected = cast<InjectedClassNameType>(ICNT)
2117 ->getInjectedSpecializationType();
2118
2119 if (CanonType != Injected->getCanonicalTypeInternal())
2120 continue;
2121
2122 // If so, the canonical type of this TST is the injected
2123 // class name type of the record we just found.
2124 assert(ICNT.isCanonical());
2125 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002126 break;
2127 }
2128 }
Mike Stump11289f42009-09-09 15:08:12 +00002129 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002130 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002131 // Find the class template specialization declaration that
2132 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002133 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002134 ClassTemplateSpecializationDecl *Decl
Craig Topper7e0daca2014-06-26 04:58:53 +00002135 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002136 if (!Decl) {
2137 // This is the first time we have referenced this class template
2138 // specialization. Create the canonical declaration and add it to
2139 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002140 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002141 ClassTemplate->getTemplatedDecl()->getTagKind(),
2142 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002143 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002144 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002145 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002147 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002148 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002149 if (ClassTemplate->isOutOfLine())
2150 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002151 }
2152
Chandler Carruth2acfb222013-09-27 22:14:40 +00002153 // Diagnose uses of this specialization.
2154 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2155
Douglas Gregorc40290e2009-03-09 23:48:35 +00002156 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002157 assert(isa<RecordType>(CanonType) &&
2158 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00002159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Douglas Gregorc40290e2009-03-09 23:48:35 +00002161 // Build the fully-sugared type for this class template
2162 // specialization, which refers back to the class template
2163 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002164 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002165}
2166
John McCallfaf5fb42010-08-26 23:41:50 +00002167TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002168Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002169 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002170 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002171 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002172 SourceLocation RAngleLoc,
2173 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002174 if (SS.isInvalid())
2175 return true;
2176
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002177 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002178
Douglas Gregorc40290e2009-03-09 23:48:35 +00002179 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002180 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002181 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002182
Douglas Gregor5a064722011-02-28 17:23:35 +00002183 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002184 QualType T
2185 = Context.getDependentTemplateSpecializationType(ETK_None,
2186 DTN->getQualifier(),
2187 DTN->getIdentifier(),
2188 TemplateArgs);
2189 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002190 TypeLocBuilder TLB;
2191 DependentTemplateSpecializationTypeLoc SpecTL
2192 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002193 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2194 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002195 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002196 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002197 SpecTL.setLAngleLoc(LAngleLoc);
2198 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002199 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2200 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2201 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2202 }
2203
John McCall6b51f282009-11-23 01:53:49 +00002204 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002205
2206 if (Result.isNull())
2207 return true;
2208
Douglas Gregore7c20652011-03-02 00:47:37 +00002209 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002210 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002211 TemplateSpecializationTypeLoc SpecTL
2212 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002213 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002214 SpecTL.setTemplateNameLoc(TemplateLoc);
2215 SpecTL.setLAngleLoc(LAngleLoc);
2216 SpecTL.setRAngleLoc(RAngleLoc);
2217 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2218 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002219
Abramo Bagnara4244b432012-01-27 08:46:19 +00002220 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2221 // constructor or destructor name (in such a case, the scope specifier
2222 // will be attached to the enclosing Decl or Expr node).
2223 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002224 // Create an elaborated-type-specifier containing the nested-name-specifier.
2225 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2226 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002227 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002228 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2229 }
2230
2231 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002232}
John McCall06f6fe8d2009-09-04 01:14:41 +00002233
Douglas Gregore7c20652011-03-02 00:47:37 +00002234TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002235 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002236 SourceLocation TagLoc,
2237 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002238 SourceLocation TemplateKWLoc,
2239 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002240 SourceLocation TemplateLoc,
2241 SourceLocation LAngleLoc,
2242 ASTTemplateArgsPtr TemplateArgsIn,
2243 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002244 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002245
2246 // Translate the parser's template argument list in our AST format.
2247 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2248 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2249
2250 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002251 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002252 ElaboratedTypeKeyword Keyword
2253 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002254
Douglas Gregore7c20652011-03-02 00:47:37 +00002255 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2256 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2257 DTN->getQualifier(),
2258 DTN->getIdentifier(),
2259 TemplateArgs);
2260
2261 // Build type-source information.
2262 TypeLocBuilder TLB;
2263 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002264 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2265 SpecTL.setElaboratedKeywordLoc(TagLoc);
2266 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002267 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002268 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002269 SpecTL.setLAngleLoc(LAngleLoc);
2270 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002271 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2272 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2273 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2274 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002275
2276 if (TypeAliasTemplateDecl *TAT =
2277 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2278 // C++0x [dcl.type.elab]p2:
2279 // If the identifier resolves to a typedef-name or the simple-template-id
2280 // resolves to an alias template specialization, the
2281 // elaborated-type-specifier is ill-formed.
2282 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2283 Diag(TAT->getLocation(), diag::note_declared_at);
2284 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002285
2286 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2287 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002288 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002289
2290 // Check the tag kind
2291 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002292 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002293
John McCalld8fe9af2009-09-08 17:47:29 +00002294 IdentifierInfo *Id = D->getIdentifier();
2295 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002296
Richard Trieucaa33d32011-06-10 03:11:26 +00002297 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2298 TagLoc, *Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002299 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002300 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002301 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002302 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002303 }
2304 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002305
Douglas Gregore7c20652011-03-02 00:47:37 +00002306 // Provide source-location information for the template specialization.
2307 TypeLocBuilder TLB;
2308 TemplateSpecializationTypeLoc SpecTL
2309 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002310 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002311 SpecTL.setTemplateNameLoc(TemplateLoc);
2312 SpecTL.setLAngleLoc(LAngleLoc);
2313 SpecTL.setRAngleLoc(RAngleLoc);
2314 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2315 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002316
Douglas Gregore7c20652011-03-02 00:47:37 +00002317 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002318 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002319 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2320 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002321 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002322 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2323 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002324}
2325
Larisse Voufo39a1e502013-08-06 01:03:05 +00002326static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002327 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2328 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002329
2330static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2331 NamedDecl *PrevDecl,
2332 SourceLocation Loc,
2333 bool IsPartialSpecialization);
2334
2335static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002336
Richard Smith300e0c32013-09-24 04:49:23 +00002337static bool isTemplateArgumentTemplateParameter(
2338 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2339 switch (Arg.getKind()) {
2340 case TemplateArgument::Null:
2341 case TemplateArgument::NullPtr:
2342 case TemplateArgument::Integral:
2343 case TemplateArgument::Declaration:
2344 case TemplateArgument::Pack:
2345 case TemplateArgument::TemplateExpansion:
2346 return false;
2347
2348 case TemplateArgument::Type: {
2349 QualType Type = Arg.getAsType();
2350 const TemplateTypeParmType *TPT =
2351 Arg.getAsType()->getAs<TemplateTypeParmType>();
2352 return TPT && !Type.hasQualifiers() &&
2353 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2354 }
2355
2356 case TemplateArgument::Expression: {
2357 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2358 if (!DRE || !DRE->getDecl())
2359 return false;
2360 const NonTypeTemplateParmDecl *NTTP =
2361 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2362 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2363 }
2364
2365 case TemplateArgument::Template:
2366 const TemplateTemplateParmDecl *TTP =
2367 dyn_cast_or_null<TemplateTemplateParmDecl>(
2368 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2369 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2370 }
2371 llvm_unreachable("unexpected kind of template argument");
2372}
2373
2374static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2375 ArrayRef<TemplateArgument> Args) {
2376 if (Params->size() != Args.size())
2377 return false;
2378
2379 unsigned Depth = Params->getDepth();
2380
2381 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2382 TemplateArgument Arg = Args[I];
2383
2384 // If the parameter is a pack expansion, the argument must be a pack
2385 // whose only element is a pack expansion.
2386 if (Params->getParam(I)->isParameterPack()) {
2387 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2388 !Arg.pack_begin()->isPackExpansion())
2389 return false;
2390 Arg = Arg.pack_begin()->getPackExpansionPattern();
2391 }
2392
2393 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2394 return false;
2395 }
2396
2397 return true;
2398}
2399
Richard Smith4b55a9c2014-04-17 03:29:33 +00002400/// Convert the parser's template argument list representation into our form.
2401static TemplateArgumentListInfo
2402makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2403 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2404 TemplateId.RAngleLoc);
2405 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2406 TemplateId.NumArgs);
2407 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2408 return TemplateArgs;
2409}
2410
Larisse Voufo39a1e502013-08-06 01:03:05 +00002411DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002412 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
Craig Topperc79e5e32014-10-31 06:57:13 +00002413 TemplateParameterList *TemplateParams, StorageClass SC,
Richard Smithbeef3452014-01-16 23:39:20 +00002414 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002415 // D must be variable template id.
2416 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2417 "Variable template specialization is declared with a template it.");
2418
2419 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002420 TemplateArgumentListInfo TemplateArgs =
2421 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002422 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2423 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2424 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002425
Richard Smithbeef3452014-01-16 23:39:20 +00002426 TemplateName Name = TemplateId->Template.get();
2427
2428 // The template-id must name a variable template.
2429 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002430 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2431 if (!VarTemplate) {
2432 NamedDecl *FnTemplate;
2433 if (auto *OTS = Name.getAsOverloadedTemplate())
2434 FnTemplate = *OTS->begin();
2435 else
2436 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2437 if (FnTemplate)
2438 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2439 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002440 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2441 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002442 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002443
2444 // Check for unexpanded parameter packs in any of the template arguments.
2445 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2446 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2447 UPPC_PartialSpecialization))
2448 return true;
2449
2450 // Check that the template argument list is well-formed for this
2451 // template.
2452 SmallVector<TemplateArgument, 4> Converted;
2453 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2454 false, Converted))
2455 return true;
2456
2457 // Check that the type of this variable template specialization
2458 // matches the expected type.
2459 TypeSourceInfo *ExpectedDI;
2460 {
2461 // Do substitution on the type of the declaration
2462 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2463 Converted.data(), Converted.size());
2464 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002465 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002466 return true;
2467 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2468 ExpectedDI =
2469 SubstType(Templated->getTypeSourceInfo(),
2470 MultiLevelTemplateArgumentList(TemplateArgList),
2471 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2472 }
2473 if (!ExpectedDI)
2474 return true;
2475
Larisse Voufo39a1e502013-08-06 01:03:05 +00002476 // Find the variable template (partial) specialization declaration that
2477 // corresponds to these arguments.
2478 if (IsPartialSpecialization) {
2479 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002480 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2481 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002482 return true;
2483
2484 bool InstantiationDependent;
2485 if (!Name.isDependent() &&
2486 !TemplateSpecializationType::anyDependentTemplateArguments(
2487 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2488 InstantiationDependent)) {
2489 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2490 << VarTemplate->getDeclName();
2491 IsPartialSpecialization = false;
2492 }
Richard Smith300e0c32013-09-24 04:49:23 +00002493
2494 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2495 Converted)) {
2496 // C++ [temp.class.spec]p9b3:
2497 //
2498 // -- The argument list of the specialization shall not be identical
2499 // to the implicit argument list of the primary template.
2500 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2501 << /*variable template*/ 1
2502 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2503 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2504 // FIXME: Recover from this by treating the declaration as a redeclaration
2505 // of the primary template.
2506 return true;
2507 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002508 }
2509
Craig Topperc3ec1492014-05-26 06:22:03 +00002510 void *InsertPos = nullptr;
2511 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002512
2513 if (IsPartialSpecialization)
2514 // FIXME: Template parameter list matters too
Craig Topper7e0daca2014-06-26 04:58:53 +00002515 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002516 else
Craig Topper7e0daca2014-06-26 04:58:53 +00002517 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002518
Craig Topperc3ec1492014-05-26 06:22:03 +00002519 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002520
2521 // Check whether we can declare a variable template specialization in
2522 // the current scope.
2523 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2524 TemplateNameLoc,
2525 IsPartialSpecialization))
2526 return true;
2527
2528 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2529 // Since the only prior variable template specialization with these
2530 // arguments was referenced but not declared, reuse that
2531 // declaration node as our own, updating its source location and
2532 // the list of outer template parameters to reflect our new declaration.
2533 Specialization = PrevDecl;
2534 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002535 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002536 } else if (IsPartialSpecialization) {
2537 // Create a new class template partial specialization declaration node.
2538 VarTemplatePartialSpecializationDecl *PrevPartial =
2539 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002540 VarTemplatePartialSpecializationDecl *Partial =
2541 VarTemplatePartialSpecializationDecl::Create(
2542 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2543 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002544 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002545
2546 if (!PrevPartial)
2547 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2548 Specialization = Partial;
2549
2550 // If we are providing an explicit specialization of a member variable
2551 // template specialization, make a note of that.
2552 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002553 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002554
2555 // Check that all of the template parameters of the variable template
2556 // partial specialization are deducible from the template
2557 // arguments. If not, this variable template partial specialization
2558 // will never be used.
2559 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2560 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2561 TemplateParams->getDepth(), DeducibleParams);
2562
2563 if (!DeducibleParams.all()) {
2564 unsigned NumNonDeducible =
2565 DeducibleParams.size() - DeducibleParams.count();
2566 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002567 << /*variable template*/ 1 << (NumNonDeducible > 1)
2568 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002569 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2570 if (!DeducibleParams[I]) {
2571 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2572 if (Param->getDeclName())
2573 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2574 << Param->getDeclName();
2575 else
2576 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002577 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002578 }
2579 }
2580 }
2581 } else {
2582 // Create a new class template specialization declaration node for
2583 // this explicit specialization or friend declaration.
2584 Specialization = VarTemplateSpecializationDecl::Create(
2585 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2586 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2587 Specialization->setTemplateArgsInfo(TemplateArgs);
2588
2589 if (!PrevDecl)
2590 VarTemplate->AddSpecialization(Specialization, InsertPos);
2591 }
2592
2593 // C++ [temp.expl.spec]p6:
2594 // If a template, a member template or the member of a class template is
2595 // explicitly specialized then that specialization shall be declared
2596 // before the first use of that specialization that would cause an implicit
2597 // instantiation to take place, in every translation unit in which such a
2598 // use occurs; no diagnostic is required.
2599 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2600 bool Okay = false;
2601 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2602 // Is there any previous explicit specialization declaration?
2603 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2604 Okay = true;
2605 break;
2606 }
2607 }
2608
2609 if (!Okay) {
2610 SourceRange Range(TemplateNameLoc, RAngleLoc);
2611 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2612 << Name << Range;
2613
2614 Diag(PrevDecl->getPointOfInstantiation(),
2615 diag::note_instantiation_required_here)
2616 << (PrevDecl->getTemplateSpecializationKind() !=
2617 TSK_ImplicitInstantiation);
2618 return true;
2619 }
2620 }
2621
2622 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2623 Specialization->setLexicalDeclContext(CurContext);
2624
2625 // Add the specialization into its lexical context, so that it can
2626 // be seen when iterating through the list of declarations in that
2627 // context. However, specializations are not found by name lookup.
2628 CurContext->addDecl(Specialization);
2629
2630 // Note that this is an explicit specialization.
2631 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2632
2633 if (PrevDecl) {
2634 // Check that this isn't a redefinition of this specialization,
2635 // merging with previous declarations.
2636 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2637 ForRedeclaration);
2638 PrevSpec.addDecl(PrevDecl);
2639 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002640 } else if (Specialization->isStaticDataMember() &&
2641 Specialization->isOutOfLine()) {
2642 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002643 }
2644
2645 // Link instantiations of static data members back to the template from
2646 // which they were instantiated.
2647 if (Specialization->isStaticDataMember())
2648 Specialization->setInstantiationOfStaticDataMember(
2649 VarTemplate->getTemplatedDecl(),
2650 Specialization->getSpecializationKind());
2651
2652 return Specialization;
2653}
2654
2655namespace {
2656/// \brief A partial specialization whose template arguments have matched
2657/// a given template-id.
2658struct PartialSpecMatchResult {
2659 VarTemplatePartialSpecializationDecl *Partial;
2660 TemplateArgumentList *Args;
2661};
2662}
2663
2664DeclResult
2665Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2666 SourceLocation TemplateNameLoc,
2667 const TemplateArgumentListInfo &TemplateArgs) {
2668 assert(Template && "A variable template id without template?");
2669
2670 // Check that the template argument list is well-formed for this template.
2671 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002672 if (CheckTemplateArgumentList(
2673 Template, TemplateNameLoc,
2674 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002675 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002676 return true;
2677
2678 // Find the variable template specialization declaration that
2679 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002680 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002681 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002682 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002683 // If we already have a variable template specialization, return it.
2684 return Spec;
2685
2686 // This is the first time we have referenced this variable template
2687 // specialization. Create the canonical declaration and add it to
2688 // the set of specializations, based on the closest partial specialization
2689 // that it represents. That is,
2690 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2691 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2692 Converted.data(), Converted.size());
2693 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2694 bool AmbiguousPartialSpec = false;
2695 typedef PartialSpecMatchResult MatchResult;
2696 SmallVector<MatchResult, 4> Matched;
2697 SourceLocation PointOfInstantiation = TemplateNameLoc;
2698 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2699
2700 // 1. Attempt to find the closest partial specialization that this
2701 // specializes, if any.
2702 // If any of the template arguments is dependent, then this is probably
2703 // a placeholder for an incomplete declarative context; which must be
2704 // complete by instantiation time. Thus, do not search through the partial
2705 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002706 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2707 // Perhaps better after unification of DeduceTemplateArguments() and
2708 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002709 bool InstantiationDependent = false;
2710 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2711 TemplateArgs, InstantiationDependent)) {
2712
2713 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2714 Template->getPartialSpecializations(PartialSpecs);
2715
2716 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2717 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2718 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2719
2720 if (TemplateDeductionResult Result =
2721 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2722 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002723 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002724 FailedCandidates.addCandidate()
2725 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2726 (void)Result;
2727 } else {
2728 Matched.push_back(PartialSpecMatchResult());
2729 Matched.back().Partial = Partial;
2730 Matched.back().Args = Info.take();
2731 }
2732 }
2733
Larisse Voufo39a1e502013-08-06 01:03:05 +00002734 if (Matched.size() >= 1) {
2735 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2736 if (Matched.size() == 1) {
2737 // -- If exactly one matching specialization is found, the
2738 // instantiation is generated from that specialization.
2739 // We don't need to do anything for this.
2740 } else {
2741 // -- If more than one matching specialization is found, the
2742 // partial order rules (14.5.4.2) are used to determine
2743 // whether one of the specializations is more specialized
2744 // than the others. If none of the specializations is more
2745 // specialized than all of the other matching
2746 // specializations, then the use of the variable template is
2747 // ambiguous and the program is ill-formed.
2748 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2749 PEnd = Matched.end();
2750 P != PEnd; ++P) {
2751 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2752 PointOfInstantiation) ==
2753 P->Partial)
2754 Best = P;
2755 }
2756
2757 // Determine if the best partial specialization is more specialized than
2758 // the others.
2759 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2760 PEnd = Matched.end();
2761 P != PEnd; ++P) {
2762 if (P != Best && getMoreSpecializedPartialSpecialization(
2763 P->Partial, Best->Partial,
2764 PointOfInstantiation) != Best->Partial) {
2765 AmbiguousPartialSpec = true;
2766 break;
2767 }
2768 }
2769 }
2770
2771 // Instantiate using the best variable template partial specialization.
2772 InstantiationPattern = Best->Partial;
2773 InstantiationArgs = Best->Args;
2774 } else {
2775 // -- If no match is found, the instantiation is generated
2776 // from the primary template.
2777 // InstantiationPattern = Template->getTemplatedDecl();
2778 }
2779 }
2780
Larisse Voufo39a1e502013-08-06 01:03:05 +00002781 // 2. Create the canonical declaration.
2782 // Note that we do not instantiate the variable just yet, since
2783 // instantiation is handled in DoMarkVarDeclReferenced().
2784 // FIXME: LateAttrs et al.?
2785 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2786 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2787 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2788 if (!Decl)
2789 return true;
2790
2791 if (AmbiguousPartialSpec) {
2792 // Partial ordering did not produce a clear winner. Complain.
2793 Decl->setInvalidDecl();
2794 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2795 << Decl;
2796
2797 // Print the matching partial specializations.
2798 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2799 PEnd = Matched.end();
2800 P != PEnd; ++P)
2801 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2802 << getTemplateArgumentBindingsText(
2803 P->Partial->getTemplateParameters(), *P->Args);
2804 return true;
2805 }
2806
2807 if (VarTemplatePartialSpecializationDecl *D =
2808 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2809 Decl->setInstantiationOf(D, InstantiationArgs);
2810
2811 assert(Decl && "No variable template specialization?");
2812 return Decl;
2813}
2814
2815ExprResult
2816Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2817 const DeclarationNameInfo &NameInfo,
2818 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2819 const TemplateArgumentListInfo *TemplateArgs) {
2820
2821 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2822 *TemplateArgs);
2823 if (Decl.isInvalid())
2824 return ExprError();
2825
2826 VarDecl *Var = cast<VarDecl>(Decl.get());
2827 if (!Var->getTemplateSpecializationKind())
2828 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2829 NameInfo.getLoc());
2830
2831 // Build an ordinary singleton decl ref.
2832 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002833 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002834}
2835
John McCalldadc5752010-08-24 06:29:42 +00002836ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002837 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002838 LookupResult &R,
2839 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002840 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002841 // FIXME: Can we do any checking at this point? I guess we could check the
2842 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002843 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002844 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002845 // foo<int> could identify a single function unambiguously
2846 // This approach does NOT work, since f<int>(1);
2847 // gets resolved prior to resorting to overload resolution
2848 // i.e., template<class T> void f(double);
2849 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002850
2851 // These should be filtered out by our callers.
2852 assert(!R.empty() && "empty lookup results when building templateid");
2853 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2854
Larisse Voufo39a1e502013-08-06 01:03:05 +00002855 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002856 bool InstantiationDependent;
2857 if (R.getAsSingle<VarTemplateDecl>() &&
2858 !TemplateSpecializationType::anyDependentTemplateArguments(
2859 *TemplateArgs, InstantiationDependent)) {
2860 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2861 R.getAsSingle<VarTemplateDecl>(),
2862 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002863 }
2864
John McCall58cc69d2010-01-27 01:50:18 +00002865 // We don't want lookup warnings at this point.
2866 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867
John McCalle66edc12009-11-24 19:00:30 +00002868 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002869 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002870 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002871 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002872 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002874 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002875
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002876 return ULE;
Douglas Gregora727cb92009-06-30 22:34:41 +00002877}
2878
John McCalle66edc12009-11-24 19:00:30 +00002879// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002880ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002881Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002882 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002883 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002884 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002885
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002886 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002887 DeclContext *DC;
2888 if (!(DC = computeDeclContext(SS, false)) ||
2889 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002890 RequireCompleteDeclContext(SS, DC))
Reid Kleckner034531d2014-12-18 18:17:42 +00002891 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002892
Douglas Gregor786123d2010-05-21 23:18:07 +00002893 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002894 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002895 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002896 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002897
John McCalle66edc12009-11-24 19:00:30 +00002898 if (R.isAmbiguous())
2899 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900
John McCalle66edc12009-11-24 19:00:30 +00002901 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002902 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2903 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002904 return ExprError();
2905 }
2906
2907 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002908 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002909 << SS.getScopeRep()
Reid Kleckner32506ed2014-06-12 23:03:48 +00002910 << NameInfo.getName().getAsString() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002911 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2912 return ExprError();
2913 }
2914
Abramo Bagnara7945c982012-01-27 09:46:47 +00002915 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002916}
2917
Douglas Gregorb67535d2009-03-31 00:43:58 +00002918/// \brief Form a dependent template name.
2919///
2920/// This action forms a dependent template name given the template
2921/// name and its (presumably dependent) scope specifier. For
2922/// example, given "MetaFun::template apply", the scope specifier \p
2923/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2924/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002925TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002926 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002927 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002928 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002929 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002930 bool EnteringContext,
2931 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002932 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2933 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002934 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002935 diag::warn_cxx98_compat_template_outside_of_template :
2936 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002937 << FixItHint::CreateRemoval(TemplateKWLoc);
2938
Craig Topperc3ec1492014-05-26 06:22:03 +00002939 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002940 if (SS.isSet())
2941 LookupCtx = computeDeclContext(SS, EnteringContext);
2942 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002943 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002944 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00002945 // C++0x [temp.names]p5:
2946 // If a name prefixed by the keyword template is not the name of
2947 // a template, the program is ill-formed. [Note: the keyword
2948 // template may not be applied to non-template members of class
2949 // templates. -end note ] [ Note: as is the case with the
2950 // typename prefix, the template prefix is allowed in cases
2951 // where it is not strictly necessary; i.e., when the
2952 // nested-name-specifier or the expression on the left of the ->
2953 // or . is not dependent on a template-parameter, or the use
2954 // does not appear in the scope of a template. -end note]
2955 //
2956 // Note: C++03 was more strict here, because it banned the use of
2957 // the "template" keyword prior to a template-name that was not a
2958 // dependent name. C++ DR468 relaxed this requirement (the
2959 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00002960 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00002961 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00002962 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002963 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00002964 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00002965 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2966 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00002967 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2968 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00002969 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00002970 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002971 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002972 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002973 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002974 << Name.getSourceRange()
2975 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002976 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00002977 } else {
2978 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00002979 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002980 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00002981 }
2982
Aaron Ballman4a979672014-01-03 13:56:08 +00002983 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002984
Douglas Gregor3cf81312009-11-03 23:16:33 +00002985 switch (Name.getKind()) {
2986 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002987 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00002988 Name.Identifier));
2989 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002990
Douglas Gregor71395fa2009-11-04 00:56:37 +00002991 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00002992 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002993 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00002994 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00002995
2996 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00002997 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00002998
Douglas Gregor3cf81312009-11-03 23:16:33 +00002999 default:
3000 break;
3001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003002
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003003 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003004 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003005 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003006 << Name.getSourceRange()
3007 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003008 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003009}
3010
Mike Stump11289f42009-09-09 15:08:12 +00003011bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003012 TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003013 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003014 const TemplateArgument &Arg = AL.getArgument();
Reid Kleckner377c1592014-06-10 23:29:48 +00003015 QualType ArgType;
3016 TypeSourceInfo *TSI = nullptr;
John McCall0ad16662009-10-29 08:12:44 +00003017
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003018 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003019 switch(Arg.getKind()) {
3020 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003021 // C++ [temp.arg.type]p1:
3022 // A template-argument for a template-parameter which is a
3023 // type shall be a type-id.
Reid Kleckner377c1592014-06-10 23:29:48 +00003024 ArgType = Arg.getAsType();
3025 TSI = AL.getTypeSourceInfo();
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003026 break;
3027 case TemplateArgument::Template: {
3028 // We have a template type parameter but the template argument
3029 // is a template without any arguments.
3030 SourceRange SR = AL.getSourceRange();
3031 TemplateName Name = Arg.getAsTemplate();
3032 Diag(SR.getBegin(), diag::err_template_missing_args)
3033 << Name << SR;
3034 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3035 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003036
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003037 return true;
3038 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003039 case TemplateArgument::Expression: {
3040 // We have a template type parameter but the template argument is an
3041 // expression; see if maybe it is missing the "typename" keyword.
3042 CXXScopeSpec SS;
3043 DeclarationNameInfo NameInfo;
3044
3045 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3046 SS.Adopt(ArgExpr->getQualifierLoc());
3047 NameInfo = ArgExpr->getNameInfo();
3048 } else if (DependentScopeDeclRefExpr *ArgExpr =
3049 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3050 SS.Adopt(ArgExpr->getQualifierLoc());
3051 NameInfo = ArgExpr->getNameInfo();
3052 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3053 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003054 if (ArgExpr->isImplicitAccess()) {
3055 SS.Adopt(ArgExpr->getQualifierLoc());
3056 NameInfo = ArgExpr->getMemberNameInfo();
3057 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003058 }
3059
Reid Kleckner377c1592014-06-10 23:29:48 +00003060 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003061 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3062 LookupParsedName(Result, CurScope, &SS);
3063
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003064 if (Result.getAsSingle<TypeDecl>() ||
3065 Result.getResultKind() ==
Reid Kleckner377c1592014-06-10 23:29:48 +00003066 LookupResult::NotFoundInCurrentInstantiation) {
3067 // Suggest that the user add 'typename' before the NNS.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003068 SourceLocation Loc = AL.getSourceRange().getBegin();
Reid Kleckner377c1592014-06-10 23:29:48 +00003069 Diag(Loc, getLangOpts().MSVCCompat
3070 ? diag::ext_ms_template_type_arg_missing_typename
3071 : diag::err_template_arg_must_be_type_suggest)
3072 << FixItHint::CreateInsertion(Loc, "typename ");
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003073 Diag(Param->getLocation(), diag::note_template_param_here);
Reid Kleckner377c1592014-06-10 23:29:48 +00003074
3075 // Recover by synthesizing a type using the location information that we
3076 // already have.
3077 ArgType =
3078 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3079 TypeLocBuilder TLB;
3080 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3081 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3082 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3083 TL.setNameLoc(NameInfo.getLoc());
3084 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3085
3086 // Overwrite our input TemplateArgumentLoc so that we can recover
3087 // properly.
3088 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3089 TemplateArgumentLocInfo(TSI));
3090
3091 break;
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003092 }
3093 }
3094 // fallthrough
3095 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003096 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003097 // We have a template type parameter but the template argument
3098 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003099 SourceRange SR = AL.getSourceRange();
3100 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003101 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003102
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003103 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003104 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003105 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003106
Reid Kleckner377c1592014-06-10 23:29:48 +00003107 if (CheckTemplateArgument(Param, TSI))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003108 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003109
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003110 // Add the converted template type argument.
Reid Kleckner377c1592014-06-10 23:29:48 +00003111 ArgType = Context.getCanonicalType(ArgType);
Douglas Gregore46db902011-06-17 22:11:49 +00003112
3113 // Objective-C ARC:
3114 // If an explicitly-specified template argument type is a lifetime type
3115 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003116 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003117 ArgType->isObjCLifetimeType() &&
3118 !ArgType.getObjCLifetime()) {
3119 Qualifiers Qs;
3120 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3121 ArgType = Context.getQualifiedType(ArgType, Qs);
3122 }
3123
3124 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003125 return false;
3126}
3127
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003128/// \brief Substitute template arguments into the default template argument for
3129/// the given template type parameter.
3130///
3131/// \param SemaRef the semantic analysis object for which we are performing
3132/// the substitution.
3133///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003135/// for.
3136///
3137/// \param TemplateLoc the location of the template name that started the
3138/// template-id we are checking.
3139///
3140/// \param RAngleLoc the location of the right angle bracket ('>') that
3141/// terminates the template-id.
3142///
3143/// \param Param the template template parameter whose default we are
3144/// substituting into.
3145///
3146/// \param Converted the list of template arguments provided for template
3147/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003148/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003149static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003150SubstDefaultTemplateArgument(Sema &SemaRef,
3151 TemplateDecl *Template,
3152 SourceLocation TemplateLoc,
3153 SourceLocation RAngleLoc,
3154 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003155 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003156 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003157
3158 // If the argument type is dependent, instantiate it now based
3159 // on the previously-computed template arguments.
3160 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003161 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003162 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003163 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003164 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003165 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
David Majnemer89189202013-08-28 23:48:32 +00003167 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3168 Converted.data(), Converted.size());
3169
3170 // Only substitute for the innermost template argument list.
3171 MultiLevelTemplateArgumentList TemplateArgLists;
3172 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3173 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3174 TemplateArgLists.addOuterTemplateArguments(None);
3175
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003176 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003177 ArgType =
3178 SemaRef.SubstType(ArgType, TemplateArgLists,
3179 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003180 }
3181
3182 return ArgType;
3183}
3184
3185/// \brief Substitute template arguments into the default template argument for
3186/// the given non-type template parameter.
3187///
3188/// \param SemaRef the semantic analysis object for which we are performing
3189/// the substitution.
3190///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003192/// for.
3193///
3194/// \param TemplateLoc the location of the template name that started the
3195/// template-id we are checking.
3196///
3197/// \param RAngleLoc the location of the right angle bracket ('>') that
3198/// terminates the template-id.
3199///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003200/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003201/// substituting into.
3202///
3203/// \param Converted the list of template arguments provided for template
3204/// parameters that precede \p Param in the template parameter list.
3205///
3206/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003207static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003208SubstDefaultTemplateArgument(Sema &SemaRef,
3209 TemplateDecl *Template,
3210 SourceLocation TemplateLoc,
3211 SourceLocation RAngleLoc,
3212 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003213 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003214 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003215 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003216 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003217 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003218 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003219
David Majnemer89189202013-08-28 23:48:32 +00003220 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3221 Converted.data(), Converted.size());
3222
3223 // Only substitute for the innermost template argument list.
3224 MultiLevelTemplateArgumentList TemplateArgLists;
3225 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3226 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3227 TemplateArgLists.addOuterTemplateArguments(None);
3228
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003229 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedmanc25372b2012-04-26 22:43:24 +00003230 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
David Majnemer89189202013-08-28 23:48:32 +00003231 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003232}
3233
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003234/// \brief Substitute template arguments into the default template argument for
3235/// the given template template parameter.
3236///
3237/// \param SemaRef the semantic analysis object for which we are performing
3238/// the substitution.
3239///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003240/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003241/// for.
3242///
3243/// \param TemplateLoc the location of the template name that started the
3244/// template-id we are checking.
3245///
3246/// \param RAngleLoc the location of the right angle bracket ('>') that
3247/// terminates the template-id.
3248///
3249/// \param Param the template template parameter whose default we are
3250/// substituting into.
3251///
3252/// \param Converted the list of template arguments provided for template
3253/// parameters that precede \p Param in the template parameter list.
3254///
Douglas Gregordf846d12011-03-02 18:46:51 +00003255/// \param QualifierLoc Will be set to the nested-name-specifier (with
3256/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003257///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003258/// \returns the substituted template argument, or NULL if an error occurred.
3259static TemplateName
3260SubstDefaultTemplateArgument(Sema &SemaRef,
3261 TemplateDecl *Template,
3262 SourceLocation TemplateLoc,
3263 SourceLocation RAngleLoc,
3264 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003265 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003266 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003267 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003268 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003269 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003270 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003271
David Majnemer89189202013-08-28 23:48:32 +00003272 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3273 Converted.data(), Converted.size());
3274
3275 // Only substitute for the innermost template argument list.
3276 MultiLevelTemplateArgumentList TemplateArgLists;
3277 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3278 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3279 TemplateArgLists.addOuterTemplateArguments(None);
3280
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003281 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003282 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003283 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003284 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003285 QualifierLoc =
3286 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003287 if (!QualifierLoc)
3288 return TemplateName();
3289 }
David Majnemer89189202013-08-28 23:48:32 +00003290
3291 return SemaRef.SubstTemplateName(
3292 QualifierLoc,
3293 Param->getDefaultArgument().getArgument().getAsTemplate(),
3294 Param->getDefaultArgument().getTemplateNameLoc(),
3295 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003296}
3297
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003298/// \brief If the given template parameter has a default template
3299/// argument, substitute into that default template argument and
3300/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003301TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003302Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3303 SourceLocation TemplateLoc,
3304 SourceLocation RAngleLoc,
3305 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003306 SmallVectorImpl<TemplateArgument>
3307 &Converted,
3308 bool &HasDefaultArg) {
3309 HasDefaultArg = false;
3310
3311 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003312 if (!hasVisibleDefaultArgument(TypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003313 return TemplateArgumentLoc();
3314
Richard Smithc87b9382013-07-04 01:01:24 +00003315 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003316 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003317 TemplateLoc,
3318 RAngleLoc,
3319 TypeParm,
3320 Converted);
3321 if (DI)
3322 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3323
3324 return TemplateArgumentLoc();
3325 }
3326
3327 if (NonTypeTemplateParmDecl *NonTypeParm
3328 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003329 if (!hasVisibleDefaultArgument(NonTypeParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003330 return TemplateArgumentLoc();
3331
Richard Smithc87b9382013-07-04 01:01:24 +00003332 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003333 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003334 TemplateLoc,
3335 RAngleLoc,
3336 NonTypeParm,
3337 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003338 if (Arg.isInvalid())
3339 return TemplateArgumentLoc();
3340
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003341 Expr *ArgE = Arg.getAs<Expr>();
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003342 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3343 }
3344
3345 TemplateTemplateParmDecl *TempTempParm
3346 = cast<TemplateTemplateParmDecl>(Param);
Richard Smith95d83952015-06-10 20:36:34 +00003347 if (!hasVisibleDefaultArgument(TempTempParm))
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003348 return TemplateArgumentLoc();
3349
Richard Smithc87b9382013-07-04 01:01:24 +00003350 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003351 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003352 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003354 RAngleLoc,
3355 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003356 Converted,
3357 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003358 if (TName.isNull())
3359 return TemplateArgumentLoc();
3360
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003361 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003362 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003363 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3364}
3365
Douglas Gregorda0fb532009-11-11 19:31:23 +00003366/// \brief Check that the given template argument corresponds to the given
3367/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003368///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003369/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003370/// checked.
3371///
Richard Trieu15b66532015-01-24 02:48:32 +00003372/// \param Arg The template argument, which may be updated due to conversions.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003373///
3374/// \param Template The template in which the template argument resides.
3375///
3376/// \param TemplateLoc The location of the template name for the template
3377/// whose argument list we're matching.
3378///
3379/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3380/// the template argument list.
3381///
3382/// \param ArgumentPackIndex The index into the argument pack where this
3383/// argument will be placed. Only valid if the parameter is a parameter pack.
3384///
3385/// \param Converted The checked, converted argument will be added to the
3386/// end of this small vector.
3387///
3388/// \param CTAK Describes how we arrived at this particular template argument:
3389/// explicitly written, deduced, etc.
3390///
3391/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003392bool Sema::CheckTemplateArgument(NamedDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00003393 TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003394 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003395 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003396 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003397 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003398 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003399 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003400 // Check template type parameters.
3401 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003402 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
Douglas Gregoreebed722009-11-11 19:41:09 +00003404 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003406 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003407 // with the template arguments we've seen thus far. But if the
3408 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003409 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003410 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3411 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412
Peter Collingbourne01687632010-12-10 17:08:53 +00003413 if (NTTPType->isDependentType() &&
3414 !isa<TemplateTemplateParmDecl>(Template) &&
3415 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003416 // Do substitution on the type of the non-type template parameter.
3417 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003418 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003419 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003420 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003421 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422
3423 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003424 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003425 NTTPType = SubstType(NTTPType,
3426 MultiLevelTemplateArgumentList(TemplateArgs),
3427 NTTP->getLocation(),
3428 NTTP->getDeclName());
3429 // If that worked, check the non-type template parameter type
3430 // for validity.
3431 if (!NTTPType.isNull())
3432 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3433 NTTP->getLocation());
3434 if (NTTPType.isNull())
3435 return true;
3436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437
Douglas Gregorda0fb532009-11-11 19:31:23 +00003438 switch (Arg.getArgument().getKind()) {
3439 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003440 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441
Douglas Gregorda0fb532009-11-11 19:31:23 +00003442 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003443 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003444 ExprResult Res =
3445 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3446 Result, CTAK);
3447 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003448 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Richard Trieu15b66532015-01-24 02:48:32 +00003450 // If the resulting expression is new, then use it in place of the
3451 // old expression in the template argument.
3452 if (Res.get() != Arg.getArgument().getAsExpr()) {
3453 TemplateArgument TA(Res.get());
3454 Arg = TemplateArgumentLoc(TA, Res.get());
3455 }
3456
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003457 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003458 break;
3459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460
Douglas Gregorda0fb532009-11-11 19:31:23 +00003461 case TemplateArgument::Declaration:
3462 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003463 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003464 // We've already checked this template argument, so just copy
3465 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003466 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003467 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468
Douglas Gregorda0fb532009-11-11 19:31:23 +00003469 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003470 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003471 // We were given a template template argument. It may not be ill-formed;
3472 // see below.
3473 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003474 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3475 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003476 // We have a template argument such as \c T::template X, which we
3477 // parsed as a template template argument. However, since we now
3478 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003479 // template name into an expression.
3480
3481 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3482 Arg.getTemplateNameLoc());
3483
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003484 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003485 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003486 // FIXME: the template-template arg was a DependentTemplateName,
3487 // so it was provided with a template keyword. However, its source
3488 // location is not stored in the template argument structure.
3489 SourceLocation TemplateKWLoc;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003490 ExprResult E = DependentScopeDeclRefExpr::Create(
3491 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3492 nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003494 // If we parsed the template argument as a pack expansion, create a
3495 // pack expansion expression.
3496 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003497 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
John Wiegley01296292011-04-08 18:41:53 +00003498 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003499 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Douglas Gregorda0fb532009-11-11 19:31:23 +00003502 TemplateArgument Result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003503 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
John Wiegley01296292011-04-08 18:41:53 +00003504 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003505 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003507 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003508 break;
3509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510
Douglas Gregorda0fb532009-11-11 19:31:23 +00003511 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003512 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003513 // therefore cannot be a non-type template argument.
3514 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3515 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516
Douglas Gregorda0fb532009-11-11 19:31:23 +00003517 Diag(Param->getLocation(), diag::note_template_param_here);
3518 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003519
Douglas Gregorda0fb532009-11-11 19:31:23 +00003520 case TemplateArgument::Type: {
3521 // We have a non-type template parameter but the template
3522 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523
Douglas Gregorda0fb532009-11-11 19:31:23 +00003524 // C++ [temp.arg]p2:
3525 // In a template-argument, an ambiguity between a type-id and
3526 // an expression is resolved to a type-id, regardless of the
3527 // form of the corresponding template-parameter.
3528 //
3529 // We warn specifically about this case, since it can be rather
3530 // confusing for users.
3531 QualType T = Arg.getArgument().getAsType();
3532 SourceRange SR = Arg.getSourceRange();
3533 if (T->isFunctionType())
3534 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3535 else
3536 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3537 Diag(Param->getLocation(), diag::note_template_param_here);
3538 return true;
3539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003540
Douglas Gregorda0fb532009-11-11 19:31:23 +00003541 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003542 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544
Douglas Gregorda0fb532009-11-11 19:31:23 +00003545 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546 }
3547
3548
Douglas Gregorda0fb532009-11-11 19:31:23 +00003549 // Check template template parameters.
3550 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Douglas Gregorda0fb532009-11-11 19:31:23 +00003552 // Substitute into the template parameter list of the template
3553 // template parameter, since previously-supplied template arguments
3554 // may appear within the template template parameter.
3555 {
3556 // Set up a template instantiation context.
3557 LocalInstantiationScope Scope(*this);
3558 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003559 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003560 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003561 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003562 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563
3564 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003565 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003566 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003568 MultiLevelTemplateArgumentList(TemplateArgs)));
3569 if (!TempParm)
3570 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003571 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572
Douglas Gregorda0fb532009-11-11 19:31:23 +00003573 switch (Arg.getArgument().getKind()) {
3574 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003575 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003576
Douglas Gregorda0fb532009-11-11 19:31:23 +00003577 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003578 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003579 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003580 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003581
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003582 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584
Douglas Gregorda0fb532009-11-11 19:31:23 +00003585 case TemplateArgument::Expression:
3586 case TemplateArgument::Type:
3587 // We have a template template parameter but the template
3588 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003589 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003590 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003591 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
Douglas Gregorda0fb532009-11-11 19:31:23 +00003593 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003594 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003595 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003596 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003597 case TemplateArgument::NullPtr:
3598 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599
Douglas Gregorda0fb532009-11-11 19:31:23 +00003600 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003601 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003603
Douglas Gregorda0fb532009-11-11 19:31:23 +00003604 return false;
3605}
3606
Douglas Gregor8e072612012-02-03 07:34:46 +00003607/// \brief Diagnose an arity mismatch in the
3608static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3609 SourceLocation TemplateLoc,
3610 TemplateArgumentListInfo &TemplateArgs) {
3611 TemplateParameterList *Params = Template->getTemplateParameters();
3612 unsigned NumParams = Params->size();
3613 unsigned NumArgs = TemplateArgs.size();
3614
3615 SourceRange Range;
3616 if (NumArgs > NumParams)
3617 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3618 TemplateArgs.getRAngleLoc());
3619 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3620 << (NumArgs > NumParams)
3621 << (isa<ClassTemplateDecl>(Template)? 0 :
3622 isa<FunctionTemplateDecl>(Template)? 1 :
3623 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3624 << Template << Range;
3625 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3626 << Params->getSourceRange();
3627 return true;
3628}
3629
Richard Smith1fde8ec2012-09-07 02:06:42 +00003630/// \brief Check whether the template parameter is a pack expansion, and if so,
3631/// determine the number of parameters produced by that expansion. For instance:
3632///
3633/// \code
3634/// template<typename ...Ts> struct A {
3635/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3636/// };
3637/// \endcode
3638///
3639/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3640/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003641static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003642 if (NonTypeTemplateParmDecl *NTTP
3643 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3644 if (NTTP->isExpandedParameterPack())
3645 return NTTP->getNumExpansionTypes();
3646 }
3647
3648 if (TemplateTemplateParmDecl *TTP
3649 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3650 if (TTP->isExpandedParameterPack())
3651 return TTP->getNumExpansionTemplateParameters();
3652 }
3653
David Blaikie7a30dc52013-02-21 01:47:18 +00003654 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003655}
3656
Richard Smith35c1df52015-06-17 20:16:32 +00003657/// Diagnose a missing template argument.
3658template<typename TemplateParmDecl>
3659static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3660 TemplateDecl *TD,
3661 const TemplateParmDecl *D,
3662 TemplateArgumentListInfo &Args) {
3663 // Dig out the most recent declaration of the template parameter; there may be
3664 // declarations of the template that are more recent than TD.
3665 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3666 ->getTemplateParameters()
3667 ->getParam(D->getIndex()));
3668
3669 // If there's a default argument that's not visible, diagnose that we're
3670 // missing a module import.
3671 llvm::SmallVector<Module*, 8> Modules;
3672 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3673 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3674 D->getDefaultArgumentLoc(), Modules,
3675 Sema::MissingImportKind::DefaultArgument,
3676 /*Recover*/ true);
3677 return true;
3678 }
3679
3680 // FIXME: If there's a more recent default argument that *is* visible,
3681 // diagnose that it was declared too late.
3682
3683 return diagnoseArityMismatch(S, TD, Loc, Args);
3684}
3685
Douglas Gregord32e0282009-02-09 23:23:08 +00003686/// \brief Check that the given template argument list is well-formed
3687/// for specializing the given template.
3688bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3689 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003690 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003691 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003692 SmallVectorImpl<TemplateArgument> &Converted) {
Richard Trieu15b66532015-01-24 02:48:32 +00003693 // Make a copy of the template arguments for processing. Only make the
3694 // changes at the end when successful in matching the arguments to the
3695 // template.
3696 TemplateArgumentListInfo NewArgs = TemplateArgs;
3697
Douglas Gregord32e0282009-02-09 23:23:08 +00003698 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003699
Richard Trieu15b66532015-01-24 02:48:32 +00003700 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
John McCall6b51f282009-11-23 01:53:49 +00003701
Mike Stump11289f42009-09-09 15:08:12 +00003702 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003703 // [...] The type and form of each template-argument specified in
3704 // a template-id shall match the type and form specified for the
3705 // corresponding parameter declared by the template in its
3706 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003707 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003708 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Trieu15b66532015-01-24 02:48:32 +00003709 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003710 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003711 for (TemplateParameterList::iterator Param = Params->begin(),
3712 ParamEnd = Params->end();
3713 Param != ParamEnd; /* increment in loop */) {
3714 // If we have an expanded parameter pack, make sure we don't have too
3715 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003716 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003717 if (*Expansions == ArgumentPack.size()) {
3718 // We're done with this parameter pack. Pack up its arguments and add
3719 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003720 Converted.push_back(
3721 TemplateArgument::CreatePackCopy(Context,
3722 ArgumentPack.data(),
3723 ArgumentPack.size()));
3724 ArgumentPack.clear();
3725
Richard Smith1fde8ec2012-09-07 02:06:42 +00003726 // This argument is assigned to the next parameter.
3727 ++Param;
3728 continue;
3729 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3730 // Not enough arguments for this parameter pack.
3731 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3732 << false
3733 << (isa<ClassTemplateDecl>(Template)? 0 :
3734 isa<FunctionTemplateDecl>(Template)? 1 :
3735 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3736 << Template;
3737 Diag(Template->getLocation(), diag::note_template_decl_here)
3738 << Params->getSourceRange();
3739 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003740 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Richard Smith1fde8ec2012-09-07 02:06:42 +00003743 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003744 // Check the template argument we were given.
Richard Trieu15b66532015-01-24 02:48:32 +00003745 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003747 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003748 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Richard Smith96d71c32014-11-12 23:38:38 +00003750 bool PackExpansionIntoNonPack =
Richard Trieu15b66532015-01-24 02:48:32 +00003751 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
Richard Smith96d71c32014-11-12 23:38:38 +00003752 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3753 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
Richard Smith83b11aa2014-01-09 02:22:22 +00003754 // Core issue 1430: we have a pack expansion as an argument to an
Richard Smith96d71c32014-11-12 23:38:38 +00003755 // alias template, and it's not part of a parameter pack. This
Richard Smith83b11aa2014-01-09 02:22:22 +00003756 // can't be canonicalized, so reject it now.
Richard Trieu15b66532015-01-24 02:48:32 +00003757 Diag(NewArgs[ArgIdx].getLocation(),
Richard Smith83b11aa2014-01-09 02:22:22 +00003758 diag::err_alias_template_expansion_into_fixed_list)
Richard Trieu15b66532015-01-24 02:48:32 +00003759 << NewArgs[ArgIdx].getSourceRange();
Richard Smith83b11aa2014-01-09 02:22:22 +00003760 Diag((*Param)->getLocation(), diag::note_template_param_here);
3761 return true;
3762 }
3763
Richard Smith1fde8ec2012-09-07 02:06:42 +00003764 // We're now done with this argument.
3765 ++ArgIdx;
3766
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003767 if ((*Param)->isTemplateParameterPack()) {
3768 // The template parameter was a template parameter pack, so take the
3769 // deduced argument and place it on the argument pack. Note that we
3770 // stay on the same template parameter so that we can deduce more
3771 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003772 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003773 } else {
3774 // Move to the next template parameter.
3775 ++Param;
3776 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003777
Richard Smith96d71c32014-11-12 23:38:38 +00003778 // If we just saw a pack expansion into a non-pack, then directly convert
3779 // the remaining arguments, because we don't know what parameters they'll
3780 // match up with.
3781 if (PackExpansionIntoNonPack) {
3782 if (!ArgumentPack.empty()) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003783 // If we were part way through filling in an expanded parameter pack,
3784 // fall back to just producing individual arguments.
3785 Converted.insert(Converted.end(),
3786 ArgumentPack.begin(), ArgumentPack.end());
3787 ArgumentPack.clear();
3788 }
3789
3790 while (ArgIdx < NumArgs) {
Richard Trieu15b66532015-01-24 02:48:32 +00003791 Converted.push_back(NewArgs[ArgIdx].getArgument());
Richard Smith1fde8ec2012-09-07 02:06:42 +00003792 ++ArgIdx;
3793 }
3794
Richard Smith1fde8ec2012-09-07 02:06:42 +00003795 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003796 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003797
Douglas Gregor84d49a22009-11-11 21:54:23 +00003798 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800
Douglas Gregor2f157c92011-06-03 02:59:40 +00003801 // If we're checking a partial template argument list, we're done.
3802 if (PartialTemplateArgs) {
3803 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3804 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3805 ArgumentPack.data(),
3806 ArgumentPack.size()));
3807
Richard Smith1fde8ec2012-09-07 02:06:42 +00003808 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003809 }
3810
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003811 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003812 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003813 if ((*Param)->isTemplateParameterPack()) {
3814 assert(!getExpandedPackSize(*Param) &&
3815 "Should have dealt with this already");
3816
3817 // A non-expanded parameter pack before the end of the parameter list
3818 // only occurs for an ill-formed template parameter list, unless we've
3819 // got a partial argument list for a function template, so just bail out.
3820 if (Param + 1 != ParamEnd)
3821 return true;
3822
Eli Friedmanb826a002012-09-26 02:36:12 +00003823 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3824 ArgumentPack.data(),
3825 ArgumentPack.size()));
3826 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003827
3828 ++Param;
3829 continue;
3830 }
3831
Douglas Gregor8e072612012-02-03 07:34:46 +00003832 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003833 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003834
Douglas Gregor84d49a22009-11-11 21:54:23 +00003835 // Retrieve the default template argument from the template
3836 // parameter. For each kind of template parameter, we substitute the
3837 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003838 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003839 // the default argument.
3840 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003841 if (!hasVisibleDefaultArgument(TTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003842 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3843 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003844
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003846 Template,
3847 TemplateLoc,
3848 RAngleLoc,
3849 TTP,
3850 Converted);
3851 if (!ArgType)
3852 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003853
Douglas Gregor84d49a22009-11-11 21:54:23 +00003854 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3855 ArgType);
3856 } else if (NonTypeTemplateParmDecl *NTTP
3857 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Richard Smith95d83952015-06-10 20:36:34 +00003858 if (!hasVisibleDefaultArgument(NTTP))
Richard Smith35c1df52015-06-17 20:16:32 +00003859 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3860 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003861
John McCalldadc5752010-08-24 06:29:42 +00003862 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863 TemplateLoc,
3864 RAngleLoc,
3865 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003866 Converted);
3867 if (E.isInvalid())
3868 return true;
3869
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003870 Expr *Ex = E.getAs<Expr>();
Douglas Gregor84d49a22009-11-11 21:54:23 +00003871 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3872 } else {
3873 TemplateTemplateParmDecl *TempParm
3874 = cast<TemplateTemplateParmDecl>(*Param);
3875
Richard Smith95d83952015-06-10 20:36:34 +00003876 if (!hasVisibleDefaultArgument(TempParm))
Richard Smith35c1df52015-06-17 20:16:32 +00003877 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3878 NewArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003879
Douglas Gregordf846d12011-03-02 18:46:51 +00003880 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003881 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882 TemplateLoc,
3883 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003884 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003885 Converted,
3886 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003887 if (Name.isNull())
3888 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003889
Douglas Gregor9d802122011-03-02 17:09:35 +00003890 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3891 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
Douglas Gregor84d49a22009-11-11 21:54:23 +00003894 // Introduce an instantiation record that describes where we are using
3895 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003896 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3897 SourceRange(TemplateLoc, RAngleLoc));
3898 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003899 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900
Douglas Gregor84d49a22009-11-11 21:54:23 +00003901 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003902 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003903 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003904 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905
Richard Trieu15b66532015-01-24 02:48:32 +00003906 // Core issue 150 (assumed resolution): if this is a template template
3907 // parameter, keep track of the default template arguments from the
Douglas Gregor739b107a2011-03-03 02:41:12 +00003908 // template definition.
3909 if (isTemplateTemplateParameter)
Richard Trieu15b66532015-01-24 02:48:32 +00003910 NewArgs.addArgument(Arg);
3911
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003912 // Move to the next template parameter and argument.
3913 ++Param;
3914 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003916
Richard Smith07f79912014-06-06 16:00:50 +00003917 // If we're performing a partial argument substitution, allow any trailing
3918 // pack expansions; they might be empty. This can happen even if
3919 // PartialTemplateArgs is false (the list of arguments is complete but
3920 // still dependent).
3921 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3922 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
Richard Trieu15b66532015-01-24 02:48:32 +00003923 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3924 Converted.push_back(NewArgs[ArgIdx++].getArgument());
Richard Smith07f79912014-06-06 16:00:50 +00003925 }
3926
Douglas Gregor8e072612012-02-03 07:34:46 +00003927 // If we have any leftover arguments, then there were too many arguments.
3928 // Complain and fail.
3929 if (ArgIdx < NumArgs)
Richard Trieu15b66532015-01-24 02:48:32 +00003930 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3931
3932 // No problems found with the new argument list, propagate changes back
3933 // to caller.
3934 TemplateArgs = NewArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935
Richard Smith1fde8ec2012-09-07 02:06:42 +00003936 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003937}
3938
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003939namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003940 class UnnamedLocalNoLinkageFinder
3941 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003942 {
3943 Sema &S;
3944 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003945
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003946 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003947
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003948 public:
3949 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951 bool Visit(QualType T) {
3952 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003953 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003954
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003955#define TYPE(Class, Parent) \
3956 bool Visit##Class##Type(const Class##Type *);
3957#define ABSTRACT_TYPE(Class, Parent) \
3958 bool Visit##Class##Type(const Class##Type *) { return false; }
3959#define NON_CANONICAL_TYPE(Class, Parent) \
3960 bool Visit##Class##Type(const Class##Type *) { return false; }
3961#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003962
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003963 bool VisitTagDecl(const TagDecl *Tag);
3964 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3965 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003966}
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003967
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003968bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003969 return false;
3970}
3971
3972bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3973 return Visit(T->getElementType());
3974}
3975
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003976bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003977 return Visit(T->getPointeeType());
3978}
3979
3980bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003981 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003982 return Visit(T->getPointeeType());
3983}
3984
3985bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003987 return Visit(T->getPointeeType());
3988}
3989
3990bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003992 return Visit(T->getPointeeType());
3993}
3994
3995bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003996 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003997 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3998}
3999
4000bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004002 return Visit(T->getElementType());
4003}
4004
4005bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004007 return Visit(T->getElementType());
4008}
4009
4010bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004011 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004012 return Visit(T->getElementType());
4013}
4014
4015bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004016 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004017 return Visit(T->getElementType());
4018}
4019
4020bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004021 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004022 return Visit(T->getElementType());
4023}
4024
4025bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4026 return Visit(T->getElementType());
4027}
4028
4029bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4030 return Visit(T->getElementType());
4031}
4032
4033bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4034 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00004035 for (const auto &A : T->param_types()) {
4036 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004037 return true;
4038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039
Alp Toker314cc812014-01-25 16:55:45 +00004040 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004041}
4042
4043bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4044 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00004045 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004046}
4047
4048bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4049 const UnresolvedUsingType*) {
4050 return false;
4051}
4052
4053bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4054 return false;
4055}
4056
4057bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4058 return Visit(T->getUnderlyingType());
4059}
4060
4061bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4062 return false;
4063}
4064
Alexis Hunte852b102011-05-24 22:41:36 +00004065bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4066 const UnaryTransformType*) {
4067 return false;
4068}
4069
Richard Smith30482bc2011-02-20 03:19:35 +00004070bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4071 return Visit(T->getDeducedType());
4072}
4073
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004074bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4075 return VisitTagDecl(T->getDecl());
4076}
4077
4078bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4079 return VisitTagDecl(T->getDecl());
4080}
4081
4082bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4083 const TemplateTypeParmType*) {
4084 return false;
4085}
4086
Douglas Gregorada4b792011-01-14 02:55:32 +00004087bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4088 const SubstTemplateTypeParmPackType *) {
4089 return false;
4090}
4091
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004092bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4093 const TemplateSpecializationType*) {
4094 return false;
4095}
4096
4097bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4098 const InjectedClassNameType* T) {
4099 return VisitTagDecl(T->getDecl());
4100}
4101
4102bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4103 const DependentNameType* T) {
4104 return VisitNestedNameSpecifier(T->getQualifier());
4105}
4106
4107bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4108 const DependentTemplateSpecializationType* T) {
4109 return VisitNestedNameSpecifier(T->getQualifier());
4110}
4111
Douglas Gregord2fa7662010-12-20 02:24:11 +00004112bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4113 const PackExpansionType* T) {
4114 return Visit(T->getPattern());
4115}
4116
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004117bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4118 return false;
4119}
4120
4121bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4122 const ObjCInterfaceType *) {
4123 return false;
4124}
4125
4126bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4127 const ObjCObjectPointerType *) {
4128 return false;
4129}
4130
Eli Friedman0dfb8892011-10-06 23:00:33 +00004131bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4132 return Visit(T->getValueType());
4133}
4134
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004135bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4136 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004137 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004138 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004139 diag::warn_cxx98_compat_template_arg_local_type :
4140 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004141 << S.Context.getTypeDeclType(Tag) << SR;
4142 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 }
4144
John McCall5ea95772013-03-09 00:54:27 +00004145 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004146 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004147 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004148 diag::warn_cxx98_compat_template_arg_unnamed_type :
4149 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004150 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4151 return true;
4152 }
4153
4154 return false;
4155}
4156
4157bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4158 NestedNameSpecifier *NNS) {
4159 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4160 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004161
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004162 switch (NNS->getKind()) {
4163 case NestedNameSpecifier::Identifier:
4164 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004165 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004166 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004167 case NestedNameSpecifier::Super:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004168 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004170 case NestedNameSpecifier::TypeSpec:
4171 case NestedNameSpecifier::TypeSpecWithTemplate:
4172 return Visit(QualType(NNS->getAsType(), 0));
4173 }
David Blaikie8a40f702012-01-17 06:56:22 +00004174 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004175}
4176
4177
Douglas Gregord32e0282009-02-09 23:23:08 +00004178/// \brief Check a template argument against its corresponding
4179/// template type parameter.
4180///
4181/// This routine implements the semantics of C++ [temp.arg.type]. It
4182/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004183bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004184 TypeSourceInfo *ArgInfo) {
4185 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004186 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004187 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004188
4189 if (Arg->isVariablyModifiedType()) {
4190 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004191 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004192 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004193 }
4194
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004195 // C++03 [temp.arg.type]p2:
4196 // A local type, a type with no linkage, an unnamed type or a type
4197 // compounded from any of these types shall not be used as a
4198 // template-argument for a template type-parameter.
4199 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004200 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004201 // a warning.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004202 bool NeedsCheck;
4203 if (LangOpts.CPlusPlus11)
4204 NeedsCheck =
4205 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4206 SR.getBegin()) ||
4207 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4208 SR.getBegin());
4209 else
4210 NeedsCheck = Arg->hasUnnamedOrLocalType();
4211
4212 if (NeedsCheck) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004213 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4214 (void)Finder.Visit(Context.getCanonicalType(Arg));
4215 }
4216
Douglas Gregord32e0282009-02-09 23:23:08 +00004217 return false;
4218}
4219
Douglas Gregor20fdef32012-04-10 17:08:25 +00004220enum NullPointerValueKind {
4221 NPV_NotNullPointer,
4222 NPV_NullPointer,
4223 NPV_Error
4224};
4225
4226/// \brief Determine whether the given template argument is a null pointer
4227/// value of the appropriate type.
4228static NullPointerValueKind
4229isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4230 QualType ParamType, Expr *Arg) {
4231 if (Arg->isValueDependent() || Arg->isTypeDependent())
4232 return NPV_NotNullPointer;
4233
David Majnemer5c734ad2014-08-14 00:49:23 +00004234 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004235 return NPV_NotNullPointer;
4236
4237 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004238 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4239 if (ArgRV.isInvalid())
4240 return NPV_Error;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004241 Arg = ArgRV.get();
Douglas Gregor350880c2012-04-10 19:03:30 +00004242
Douglas Gregor20fdef32012-04-10 17:08:25 +00004243 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004244 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004245 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004246 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004247 EvalResult.HasSideEffects) {
4248 SourceLocation DiagLoc = Arg->getExprLoc();
4249
4250 // If our only note is the usual "invalid subexpression" note, just point
4251 // the caret at its location rather than producing an essentially
4252 // redundant note.
4253 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4254 diag::note_invalid_subexpr_in_const_expr) {
4255 DiagLoc = Notes[0].first;
4256 Notes.clear();
4257 }
4258
4259 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4260 << Arg->getType() << Arg->getSourceRange();
4261 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4262 S.Diag(Notes[I].first, Notes[I].second);
4263
4264 S.Diag(Param->getLocation(), diag::note_template_param_here);
4265 return NPV_Error;
4266 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004267
4268 // C++11 [temp.arg.nontype]p1:
4269 // - an address constant expression of type std::nullptr_t
4270 if (Arg->getType()->isNullPtrType())
4271 return NPV_NullPointer;
4272
4273 // - a constant expression that evaluates to a null pointer value (4.10); or
4274 // - a constant expression that evaluates to a null member pointer value
4275 // (4.11); or
4276 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4277 (EvalResult.Val.isMemberPointer() &&
4278 !EvalResult.Val.getMemberPointerDecl())) {
4279 // If our expression has an appropriate type, we've succeeded.
4280 bool ObjCLifetimeConversion;
4281 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4282 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4283 ObjCLifetimeConversion))
4284 return NPV_NullPointer;
4285
4286 // The types didn't match, but we know we got a null pointer; complain,
4287 // then recover as if the types were correct.
4288 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4289 << Arg->getType() << ParamType << Arg->getSourceRange();
4290 S.Diag(Param->getLocation(), diag::note_template_param_here);
4291 return NPV_NullPointer;
4292 }
4293
4294 // If we don't have a null pointer value, but we do have a NULL pointer
4295 // constant, suggest a cast to the appropriate type.
4296 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4297 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4298 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004299 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4300 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4301 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004302 S.Diag(Param->getLocation(), diag::note_template_param_here);
4303 return NPV_NullPointer;
4304 }
4305
4306 // FIXME: If we ever want to support general, address-constant expressions
4307 // as non-type template arguments, we should return the ExprResult here to
4308 // be interpreted by the caller.
4309 return NPV_NotNullPointer;
4310}
4311
David Majnemer61c39a12013-08-23 05:39:39 +00004312/// \brief Checks whether the given template argument is compatible with its
4313/// template parameter.
4314static bool CheckTemplateArgumentIsCompatibleWithParameter(
4315 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4316 Expr *Arg, QualType ArgType) {
4317 bool ObjCLifetimeConversion;
4318 if (ParamType->isPointerType() &&
4319 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4320 S.IsQualificationConversion(ArgType, ParamType, false,
4321 ObjCLifetimeConversion)) {
4322 // For pointer-to-object types, qualification conversions are
4323 // permitted.
4324 } else {
4325 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4326 if (!ParamRef->getPointeeType()->isFunctionType()) {
4327 // C++ [temp.arg.nontype]p5b3:
4328 // For a non-type template-parameter of type reference to
4329 // object, no conversions apply. The type referred to by the
4330 // reference may be more cv-qualified than the (otherwise
4331 // identical) type of the template- argument. The
4332 // template-parameter is bound directly to the
4333 // template-argument, which shall be an lvalue.
4334
4335 // FIXME: Other qualifiers?
4336 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4337 unsigned ArgQuals = ArgType.getCVRQualifiers();
4338
4339 if ((ParamQuals | ArgQuals) != ParamQuals) {
4340 S.Diag(Arg->getLocStart(),
4341 diag::err_template_arg_ref_bind_ignores_quals)
4342 << ParamType << Arg->getType() << Arg->getSourceRange();
4343 S.Diag(Param->getLocation(), diag::note_template_param_here);
4344 return true;
4345 }
4346 }
4347 }
4348
4349 // At this point, the template argument refers to an object or
4350 // function with external linkage. We now need to check whether the
4351 // argument and parameter types are compatible.
4352 if (!S.Context.hasSameUnqualifiedType(ArgType,
4353 ParamType.getNonReferenceType())) {
4354 // We can't perform this conversion or binding.
4355 if (ParamType->isReferenceType())
4356 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4357 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4358 else
4359 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4360 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4361 S.Diag(Param->getLocation(), diag::note_template_param_here);
4362 return true;
4363 }
4364 }
4365
4366 return false;
4367}
4368
Douglas Gregorccb07762009-02-11 19:52:55 +00004369/// \brief Checks whether the given template argument is the address
4370/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004372CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4373 NonTypeTemplateParmDecl *Param,
4374 QualType ParamType,
4375 Expr *ArgIn,
4376 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004377 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004378 Expr *Arg = ArgIn;
4379 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004380
Douglas Gregorb242683d2010-04-01 18:32:35 +00004381 bool AddressTaken = false;
4382 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004383 if (S.getLangOpts().MicrosoftExt) {
4384 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4385 // dereference and address-of operators.
4386 Arg = Arg->IgnoreParenCasts();
4387
4388 bool ExtWarnMSTemplateArg = false;
4389 UnaryOperatorKind FirstOpKind;
4390 SourceLocation FirstOpLoc;
4391 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4392 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4393 if (UnOpKind == UO_Deref)
4394 ExtWarnMSTemplateArg = true;
4395 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4396 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4397 if (!AddrOpLoc.isValid()) {
4398 FirstOpKind = UnOpKind;
4399 FirstOpLoc = UnOp->getOperatorLoc();
4400 }
4401 } else
4402 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004403 }
David Majnemer61c39a12013-08-23 05:39:39 +00004404 if (FirstOpLoc.isValid()) {
4405 if (ExtWarnMSTemplateArg)
4406 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4407 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004408
David Majnemer61c39a12013-08-23 05:39:39 +00004409 if (FirstOpKind == UO_AddrOf)
4410 AddressTaken = true;
4411 else if (Arg->getType()->isPointerType()) {
4412 // We cannot let pointers get dereferenced here, that is obviously not a
4413 // constant expression.
4414 assert(FirstOpKind == UO_Deref);
4415 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4416 << Arg->getSourceRange();
4417 }
4418 }
4419 } else {
4420 // See through any implicit casts we added to fix the type.
4421 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004422
David Majnemer61c39a12013-08-23 05:39:39 +00004423 // C++ [temp.arg.nontype]p1:
4424 //
4425 // A template-argument for a non-type, non-template
4426 // template-parameter shall be one of: [...]
4427 //
4428 // -- the address of an object or function with external
4429 // linkage, including function templates and function
4430 // template-ids but excluding non-static class members,
4431 // expressed as & id-expression where the & is optional if
4432 // the name refers to a function or array, or if the
4433 // corresponding template-parameter is a reference; or
4434
4435 // In C++98/03 mode, give an extension warning on any extra parentheses.
4436 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4437 bool ExtraParens = false;
4438 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4439 if (!Invalid && !ExtraParens) {
4440 S.Diag(Arg->getLocStart(),
4441 S.getLangOpts().CPlusPlus11
4442 ? diag::warn_cxx98_compat_template_arg_extra_parens
4443 : diag::ext_template_arg_extra_parens)
4444 << Arg->getSourceRange();
4445 ExtraParens = true;
4446 }
4447
4448 Arg = Parens->getSubExpr();
4449 }
4450
4451 while (SubstNonTypeTemplateParmExpr *subst =
4452 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4453 Arg = subst->getReplacement()->IgnoreImpCasts();
4454
4455 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4456 if (UnOp->getOpcode() == UO_AddrOf) {
4457 Arg = UnOp->getSubExpr();
4458 AddressTaken = true;
4459 AddrOpLoc = UnOp->getOperatorLoc();
4460 }
4461 }
4462
4463 while (SubstNonTypeTemplateParmExpr *subst =
4464 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4465 Arg = subst->getReplacement()->IgnoreImpCasts();
4466 }
John McCall7c454bb2011-07-15 05:09:51 +00004467
David Majnemer07910d62014-06-26 07:48:46 +00004468 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4469 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4470
4471 // If our parameter has pointer type, check for a null template value.
4472 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4473 NullPointerValueKind NPV;
4474 // dllimport'd entities aren't constant but are available inside of template
4475 // arguments.
4476 if (Entity && Entity->hasAttr<DLLImportAttr>())
4477 NPV = NPV_NotNullPointer;
4478 else
4479 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4480 switch (NPV) {
4481 case NPV_NullPointer:
4482 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004483 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4484 /*isNullPtr=*/true);
David Majnemer07910d62014-06-26 07:48:46 +00004485 return false;
4486
4487 case NPV_Error:
4488 return true;
4489
4490 case NPV_NotNullPointer:
4491 break;
4492 }
4493 }
4494
Chandler Carruth724a8a12010-01-31 10:01:20 +00004495 // Stop checking the precise nature of the argument if it is value dependent,
4496 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004497 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004498 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004499 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004500 }
David Majnemer61c39a12013-08-23 05:39:39 +00004501
4502 if (isa<CXXUuidofExpr>(Arg)) {
4503 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4504 ArgIn, Arg, ArgType))
4505 return true;
4506
4507 Converted = TemplateArgument(ArgIn);
4508 return false;
4509 }
4510
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004511 if (!DRE) {
4512 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4513 << Arg->getSourceRange();
4514 S.Diag(Param->getLocation(), diag::note_template_param_here);
4515 return true;
4516 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004517
Douglas Gregorccb07762009-02-11 19:52:55 +00004518 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004519 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004520 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004521 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004522 S.Diag(Param->getLocation(), diag::note_template_param_here);
4523 return true;
4524 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004525
4526 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004527 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004528 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004529 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004530 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004531 S.Diag(Param->getLocation(), diag::note_template_param_here);
4532 return true;
4533 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004534 }
Mike Stump11289f42009-09-09 15:08:12 +00004535
Richard Smith9380e0e2012-04-04 21:11:30 +00004536 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4537 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004538
Richard Smith9380e0e2012-04-04 21:11:30 +00004539 // A non-type template argument must refer to an object or function.
4540 if (!Func && !Var) {
4541 // We found something, but we don't know specifically what it is.
4542 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4543 << Arg->getSourceRange();
4544 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4545 return true;
4546 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004547
Richard Smith9380e0e2012-04-04 21:11:30 +00004548 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004549 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004550 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004551 diag::warn_cxx98_compat_template_arg_object_internal :
4552 diag::ext_template_arg_object_internal)
4553 << !Func << Entity << Arg->getSourceRange();
4554 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4555 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004556 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004557 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4558 << !Func << Entity << Arg->getSourceRange();
4559 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4560 << !Func;
4561 return true;
4562 }
4563
4564 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004565 // If the template parameter has pointer type, the function decays.
4566 if (ParamType->isPointerType() && !AddressTaken)
4567 ArgType = S.Context.getPointerType(Func->getType());
4568 else if (AddressTaken && ParamType->isReferenceType()) {
4569 // If we originally had an address-of operator, but the
4570 // parameter has reference type, complain and (if things look
4571 // like they will work) drop the address-of operator.
4572 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4573 ParamType.getNonReferenceType())) {
4574 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4575 << ParamType;
4576 S.Diag(Param->getLocation(), diag::note_template_param_here);
4577 return true;
4578 }
4579
4580 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4581 << ParamType
4582 << FixItHint::CreateRemoval(AddrOpLoc);
4583 S.Diag(Param->getLocation(), diag::note_template_param_here);
4584
4585 ArgType = Func->getType();
4586 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004587 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004588 // A value of reference type is not an object.
4589 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004590 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004591 diag::err_template_arg_reference_var)
4592 << Var->getType() << Arg->getSourceRange();
4593 S.Diag(Param->getLocation(), diag::note_template_param_here);
4594 return true;
4595 }
4596
Richard Smith9380e0e2012-04-04 21:11:30 +00004597 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004598 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004599 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4600 << Arg->getSourceRange();
4601 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4602 return true;
4603 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004604
4605 // If the template parameter has pointer type, we must have taken
4606 // the address of this object.
4607 if (ParamType->isReferenceType()) {
4608 if (AddressTaken) {
4609 // If we originally had an address-of operator, but the
4610 // parameter has reference type, complain and (if things look
4611 // like they will work) drop the address-of operator.
4612 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4613 ParamType.getNonReferenceType())) {
4614 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4615 << ParamType;
4616 S.Diag(Param->getLocation(), diag::note_template_param_here);
4617 return true;
4618 }
4619
4620 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4621 << ParamType
4622 << FixItHint::CreateRemoval(AddrOpLoc);
4623 S.Diag(Param->getLocation(), diag::note_template_param_here);
4624
4625 ArgType = Var->getType();
4626 }
4627 } else if (!AddressTaken && ParamType->isPointerType()) {
4628 if (Var->getType()->isArrayType()) {
4629 // Array-to-pointer decay.
4630 ArgType = S.Context.getArrayDecayedType(Var->getType());
4631 } else {
4632 // If the template parameter has pointer type but the address of
4633 // this object was not taken, complain and (possibly) recover by
4634 // taking the address of the entity.
4635 ArgType = S.Context.getPointerType(Var->getType());
4636 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4637 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4638 << ParamType;
4639 S.Diag(Param->getLocation(), diag::note_template_param_here);
4640 return true;
4641 }
4642
4643 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4644 << ParamType
4645 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4646
4647 S.Diag(Param->getLocation(), diag::note_template_param_here);
4648 }
4649 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004650 }
Mike Stump11289f42009-09-09 15:08:12 +00004651
David Majnemer61c39a12013-08-23 05:39:39 +00004652 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4653 Arg, ArgType))
4654 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004655
4656 // Create the template argument.
David Blaikie0f62c8d2014-10-16 04:21:25 +00004657 Converted =
4658 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
Nick Lewycky45b50522013-02-02 00:25:55 +00004659 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004660 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004661}
4662
4663/// \brief Checks whether the given template argument is a pointer to
4664/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004665static bool CheckTemplateArgumentPointerToMember(Sema &S,
4666 NonTypeTemplateParmDecl *Param,
4667 QualType ParamType,
4668 Expr *&ResultArg,
4669 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004670 bool Invalid = false;
4671
Douglas Gregor20fdef32012-04-10 17:08:25 +00004672 // Check for a null pointer value.
4673 Expr *Arg = ResultArg;
4674 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4675 case NPV_Error:
4676 return true;
4677 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004678 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00004679 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4680 /*isNullPtr*/true);
David Majnemer763584d2014-02-06 10:59:19 +00004681 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4682 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004683 return false;
4684 case NPV_NotNullPointer:
4685 break;
4686 }
4687
4688 bool ObjCLifetimeConversion;
4689 if (S.IsQualificationConversion(Arg->getType(),
4690 ParamType.getNonReferenceType(),
4691 false, ObjCLifetimeConversion)) {
4692 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004693 Arg->getValueKind()).get();
Douglas Gregor20fdef32012-04-10 17:08:25 +00004694 ResultArg = Arg;
4695 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4696 ParamType.getNonReferenceType())) {
4697 // We can't perform this conversion.
4698 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4699 << Arg->getType() << ParamType << Arg->getSourceRange();
4700 S.Diag(Param->getLocation(), diag::note_template_param_here);
4701 return true;
4702 }
4703
Douglas Gregorccb07762009-02-11 19:52:55 +00004704 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004705 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004706 Arg = Cast->getSubExpr();
4707
4708 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004709 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004710 // A template-argument for a non-type, non-template
4711 // template-parameter shall be one of: [...]
4712 //
4713 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004714 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004715
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004716 // In C++98/03 mode, give an extension warning on any extra parentheses.
4717 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4718 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004719 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004720 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004721 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004722 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004723 diag::warn_cxx98_compat_template_arg_extra_parens :
4724 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004725 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004726 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004727 }
4728
4729 Arg = Parens->getSubExpr();
4730 }
4731
John McCall7c454bb2011-07-15 05:09:51 +00004732 while (SubstNonTypeTemplateParmExpr *subst =
4733 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4734 Arg = subst->getReplacement()->IgnoreImpCasts();
4735
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004736 // A pointer-to-member constant written &Class::member.
4737 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004738 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004739 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4740 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004741 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004744 // A constant of pointer-to-member type.
4745 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4746 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4747 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004748 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004749 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004750 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004751 } else {
4752 VD = cast<ValueDecl>(VD->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004753 Converted = TemplateArgument(VD, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004754 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004755 return Invalid;
4756 }
4757 }
4758 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Craig Topperc3ec1492014-05-26 06:22:03 +00004760 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004761 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004762
Douglas Gregorccb07762009-02-11 19:52:55 +00004763 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004764 return S.Diag(Arg->getLocStart(),
4765 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004766 << Arg->getSourceRange();
4767
David Majnemer3ac84e62013-10-22 21:56:38 +00004768 if (isa<FieldDecl>(DRE->getDecl()) ||
4769 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4770 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004771 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004772 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004773 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4774 "Only non-static member pointers can make it here");
4775
4776 // Okay: this is the address of a non-static member, and therefore
4777 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004778 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004779 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004780 } else {
4781 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
David Blaikie0f62c8d2014-10-16 04:21:25 +00004782 Converted = TemplateArgument(D, ParamType);
Eli Friedmanb826a002012-09-26 02:36:12 +00004783 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004784 return Invalid;
4785 }
4786
4787 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004788 S.Diag(Arg->getLocStart(),
4789 diag::err_template_arg_not_pointer_to_member_form)
4790 << Arg->getSourceRange();
4791 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004792 return true;
4793}
4794
Douglas Gregord32e0282009-02-09 23:23:08 +00004795/// \brief Check a template argument against its corresponding
4796/// non-type template parameter.
4797///
Douglas Gregor463421d2009-03-03 04:44:36 +00004798/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004799/// If an error occurred, it returns ExprError(); otherwise, it
Richard Smithd663fdd2014-12-17 20:42:37 +00004800/// returns the converted template argument. \p ParamType is the
4801/// type of the non-type template parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004802ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Richard Smithd663fdd2014-12-17 20:42:37 +00004803 QualType ParamType, Expr *Arg,
John Wiegley01296292011-04-08 18:41:53 +00004804 TemplateArgument &Converted,
4805 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004806 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004807
Douglas Gregor86560402009-02-10 23:36:10 +00004808 // If either the parameter has a dependent type or the argument is
4809 // type-dependent, there's nothing we can check now.
Richard Smithd663fdd2014-12-17 20:42:37 +00004810 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00004811 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004812 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004813 return Arg;
Douglas Gregorc40290e2009-03-09 23:48:35 +00004814 }
Douglas Gregor86560402009-02-10 23:36:10 +00004815
Richard Smithd663fdd2014-12-17 20:42:37 +00004816 // We should have already dropped all cv-qualifiers by now.
4817 assert(!ParamType.hasQualifiers() &&
4818 "non-type template parameter type cannot be qualified");
4819
4820 if (CTAK == CTAK_Deduced &&
4821 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4822 // C++ [temp.deduct.type]p17:
4823 // If, in the declaration of a function template with a non-type
4824 // template-parameter, the non-type template-parameter is used
4825 // in an expression in the function parameter-list and, if the
4826 // corresponding template-argument is deduced, the
4827 // template-argument type shall match the type of the
4828 // template-parameter exactly, except that a template-argument
4829 // deduced from an array bound may be of any integral type.
4830 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4831 << Arg->getType().getUnqualifiedType()
4832 << ParamType.getUnqualifiedType();
4833 Diag(Param->getLocation(), diag::note_template_param_here);
4834 return ExprError();
4835 }
4836
Richard Smith410cc892014-11-26 03:26:53 +00004837 if (getLangOpts().CPlusPlus1z) {
4838 // FIXME: We can do some limited checking for a value-dependent but not
4839 // type-dependent argument.
4840 if (Arg->isValueDependent()) {
4841 Converted = TemplateArgument(Arg);
4842 return Arg;
4843 }
4844
4845 // C++1z [temp.arg.nontype]p1:
4846 // A template-argument for a non-type template parameter shall be
4847 // a converted constant expression of the type of the template-parameter.
4848 APValue Value;
4849 ExprResult ArgResult = CheckConvertedConstantExpression(
4850 Arg, ParamType, Value, CCEK_TemplateArg);
4851 if (ArgResult.isInvalid())
4852 return ExprError();
4853
Richard Smithd663fdd2014-12-17 20:42:37 +00004854 QualType CanonParamType = Context.getCanonicalType(ParamType);
4855
Richard Smith410cc892014-11-26 03:26:53 +00004856 // Convert the APValue to a TemplateArgument.
4857 switch (Value.getKind()) {
4858 case APValue::Uninitialized:
4859 assert(ParamType->isNullPtrType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004860 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004861 break;
4862 case APValue::Int:
4863 assert(ParamType->isIntegralOrEnumerationType());
Richard Smithd663fdd2014-12-17 20:42:37 +00004864 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
Richard Smith410cc892014-11-26 03:26:53 +00004865 break;
4866 case APValue::MemberPointer: {
4867 assert(ParamType->isMemberPointerType());
4868
4869 // FIXME: We need TemplateArgument representation and mangling for these.
4870 if (!Value.getMemberPointerPath().empty()) {
4871 Diag(Arg->getLocStart(),
4872 diag::err_template_arg_member_ptr_base_derived_not_supported)
4873 << Value.getMemberPointerDecl() << ParamType
4874 << Arg->getSourceRange();
4875 return ExprError();
4876 }
4877
4878 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
Richard Smithd663fdd2014-12-17 20:42:37 +00004879 Converted = VD ? TemplateArgument(VD, CanonParamType)
4880 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004881 break;
4882 }
4883 case APValue::LValue: {
4884 // For a non-type template-parameter of pointer or reference type,
4885 // the value of the constant expression shall not refer to
Richard Smithd663fdd2014-12-17 20:42:37 +00004886 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4887 ParamType->isNullPtrType());
Richard Smith410cc892014-11-26 03:26:53 +00004888 // -- a temporary object
4889 // -- a string literal
4890 // -- the result of a typeid expression, or
4891 // -- a predefind __func__ variable
4892 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4893 if (isa<CXXUuidofExpr>(E)) {
4894 Converted = TemplateArgument(const_cast<Expr*>(E));
4895 break;
4896 }
4897 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4898 << Arg->getSourceRange();
4899 return ExprError();
4900 }
4901 auto *VD = const_cast<ValueDecl *>(
4902 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4903 // -- a subobject
4904 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4905 VD && VD->getType()->isArrayType() &&
4906 Value.getLValuePath()[0].ArrayIndex == 0 &&
4907 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4908 // Per defect report (no number yet):
4909 // ... other than a pointer to the first element of a complete array
4910 // object.
4911 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4912 Value.isLValueOnePastTheEnd()) {
4913 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4914 << Value.getAsString(Context, ParamType);
4915 return ExprError();
4916 }
Richard Smithd663fdd2014-12-17 20:42:37 +00004917 assert((VD || !ParamType->isReferenceType()) &&
Richard Smith410cc892014-11-26 03:26:53 +00004918 "null reference should not be a constant expression");
Richard Smithd663fdd2014-12-17 20:42:37 +00004919 assert((!VD || !ParamType->isNullPtrType()) &&
4920 "non-null value of type nullptr_t?");
4921 Converted = VD ? TemplateArgument(VD, CanonParamType)
4922 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
Richard Smith410cc892014-11-26 03:26:53 +00004923 break;
4924 }
4925 case APValue::AddrLabelDiff:
4926 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4927 case APValue::Float:
4928 case APValue::ComplexInt:
4929 case APValue::ComplexFloat:
4930 case APValue::Vector:
4931 case APValue::Array:
4932 case APValue::Struct:
4933 case APValue::Union:
4934 llvm_unreachable("invalid kind for template argument");
4935 }
4936
4937 return ArgResult.get();
4938 }
4939
Douglas Gregor86560402009-02-10 23:36:10 +00004940 // C++ [temp.arg.nontype]p5:
4941 // The following conversions are performed on each expression used
4942 // as a non-type template-argument. If a non-type
4943 // template-argument cannot be converted to the type of the
4944 // corresponding template-parameter then the program is
4945 // ill-formed.
Douglas Gregorb90df602010-06-16 00:17:44 +00004946 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00004947 // C++11:
4948 // -- for a non-type template-parameter of integral or
4949 // enumeration type, conversions permitted in a converted
4950 // constant expression are applied.
4951 //
4952 // C++98:
4953 // -- for a non-type template-parameter of integral or
4954 // enumeration type, integral promotions (4.5) and integral
4955 // conversions (4.7) are applied.
4956
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004957 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00004958 // We can't check arbitrary value-dependent arguments.
4959 // FIXME: If there's no viable conversion to the template parameter type,
4960 // we should be able to diagnose that prior to instantiation.
4961 if (Arg->isValueDependent()) {
4962 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004963 return Arg;
Richard Smithf8379a02012-01-18 23:55:52 +00004964 }
4965
4966 // C++ [temp.arg.nontype]p1:
4967 // A template-argument for a non-type, non-template template-parameter
4968 // shall be one of:
4969 //
4970 // -- for a non-type template-parameter of integral or enumeration
4971 // type, a converted constant expression of the type of the
4972 // template-parameter; or
4973 llvm::APSInt Value;
4974 ExprResult ArgResult =
4975 CheckConvertedConstantExpression(Arg, ParamType, Value,
4976 CCEK_TemplateArg);
4977 if (ArgResult.isInvalid())
4978 return ExprError();
4979
4980 // Widen the argument value to sizeof(parameter type). This is almost
4981 // always a no-op, except when the parameter type is bool. In
4982 // that case, this may extend the argument from 1 bit to 8 bits.
4983 QualType IntegerType = ParamType;
4984 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4985 IntegerType = Enum->getDecl()->getIntegerType();
4986 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4987
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004988 Converted = TemplateArgument(Context, Value,
4989 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00004990 return ArgResult;
4991 }
4992
Richard Smith08b12f12011-10-27 22:11:44 +00004993 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4994 if (ArgResult.isInvalid())
4995 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004996 Arg = ArgResult.get();
Richard Smith08b12f12011-10-27 22:11:44 +00004997
4998 QualType ArgType = Arg->getType();
4999
Douglas Gregor86560402009-02-10 23:36:10 +00005000 // C++ [temp.arg.nontype]p1:
5001 // A template-argument for a non-type, non-template
5002 // template-parameter shall be one of:
5003 //
5004 // -- an integral constant-expression of integral or enumeration
5005 // type; or
5006 // -- the name of a non-type template-parameter; or
5007 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005008 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00005009 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005010 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005011 diag::err_template_arg_not_integral_or_enumeral)
5012 << ArgType << Arg->getSourceRange();
5013 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005014 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00005015 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00005016 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5017 QualType T;
5018
5019 public:
5020 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00005021
5022 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5023 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00005024 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5025 }
5026 } Diagnoser(ArgType);
5027
5028 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005029 false).get();
Richard Smithf4c51d92012-02-04 09:53:13 +00005030 if (!Arg)
5031 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005032 }
5033
Richard Smithd663fdd2014-12-17 20:42:37 +00005034 // From here on out, all we care about is the unqualified form
5035 // of the argument type.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005036 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00005037
5038 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00005039 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00005040 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00005041 } else if (ParamType->isBooleanType()) {
5042 // This is an integral-to-boolean conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005043 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005044 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5045 !ParamType->isEnumeralType()) {
5046 // This is an integral promotion or conversion.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005047 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
Douglas Gregor86560402009-02-10 23:36:10 +00005048 } else {
5049 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005050 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00005051 diag::err_template_arg_not_convertible)
Richard Smithd663fdd2014-12-17 20:42:37 +00005052 << Arg->getType() << ParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00005053 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00005054 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00005055 }
5056
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005057 // Add the value of this argument to the list of converted
5058 // arguments. We use the bitwidth and signedness of the template
5059 // parameter.
5060 if (Arg->isValueDependent()) {
5061 // The argument is value-dependent. Create a new
5062 // TemplateArgument with the converted expression.
5063 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005064 return Arg;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005065 }
5066
Douglas Gregor52aba872009-03-14 00:20:21 +00005067 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00005068 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00005069 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00005070
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005071 if (ParamType->isBooleanType()) {
5072 // Value must be zero or one.
5073 Value = Value != 0;
5074 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5075 if (Value.getBitWidth() != AllowedBits)
5076 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005077 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005078 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005079 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005080
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005082 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005083 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00005084 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005085 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005086 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005087
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005088 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005089 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005090 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005091 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005092 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5093 << Arg->getSourceRange();
5094 Diag(Param->getLocation(), diag::note_template_param_here);
5095 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00005096
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005097 // Complain if we overflowed the template parameter's type.
5098 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005099 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005100 RequiredBits = OldValue.getActiveBits();
5101 else if (OldValue.isUnsigned())
5102 RequiredBits = OldValue.getActiveBits() + 1;
5103 else
5104 RequiredBits = OldValue.getMinSignedBits();
5105 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005106 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00005107 diag::warn_template_arg_too_large)
5108 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5109 << Arg->getSourceRange();
5110 Diag(Param->getLocation(), diag::note_template_param_here);
5111 }
Douglas Gregor52aba872009-03-14 00:20:21 +00005112 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00005113
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005114 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00005115 ParamType->isEnumeralType()
5116 ? Context.getCanonicalType(ParamType)
5117 : IntegerType);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005118 return Arg;
Douglas Gregor86560402009-02-10 23:36:10 +00005119 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005120
Richard Smith08b12f12011-10-27 22:11:44 +00005121 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00005122 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5123
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005124 // Handle pointer-to-function, reference-to-function, and
5125 // pointer-to-member-function all in (roughly) the same way.
5126 if (// -- For a non-type template-parameter of type pointer to
5127 // function, only the function-to-pointer conversion (4.3) is
5128 // applied. If the template-argument represents a set of
5129 // overloaded functions (or a pointer to such), the matching
5130 // function is selected from the set (13.4).
5131 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005132 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005133 // -- For a non-type template-parameter of type reference to
5134 // function, no conversions apply. If the template-argument
5135 // represents a set of overloaded functions, the matching
5136 // function is selected from the set (13.4).
5137 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005138 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005139 // -- For a non-type template-parameter of type pointer to
5140 // member function, no conversions apply. If the
5141 // template-argument represents a set of overloaded member
5142 // functions, the matching member function is selected from
5143 // the set (13.4).
5144 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005145 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005146 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005147
Douglas Gregor064fdb22010-04-14 23:11:21 +00005148 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005149 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00005150 true,
5151 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005152 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005153 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005154
5155 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5156 ArgType = Arg->getType();
5157 } else
John Wiegley01296292011-04-08 18:41:53 +00005158 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005160
John Wiegley01296292011-04-08 18:41:53 +00005161 if (!ParamType->isMemberPointerType()) {
5162 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5163 ParamType,
5164 Arg, Converted))
5165 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005166 return Arg;
John Wiegley01296292011-04-08 18:41:53 +00005167 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00005168
Douglas Gregor20fdef32012-04-10 17:08:25 +00005169 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5170 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005171 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005172 return Arg;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005173 }
5174
Chris Lattner696197c2009-02-20 21:37:53 +00005175 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005176 // -- for a non-type template-parameter of type pointer to
5177 // object, qualification conversions (4.4) and the
5178 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00005179 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00005180 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005181 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005182
John Wiegley01296292011-04-08 18:41:53 +00005183 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5184 ParamType,
5185 Arg, Converted))
5186 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005187 return Arg;
Douglas Gregora9faa442009-02-11 00:44:29 +00005188 }
Mike Stump11289f42009-09-09 15:08:12 +00005189
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005190 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005191 // -- For a non-type template-parameter of type reference to
5192 // object, no conversions apply. The type referred to by the
5193 // reference may be more cv-qualified than the (otherwise
5194 // identical) type of the template-argument. The
5195 // template-parameter is bound directly to the
5196 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005197 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005198 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005199
Douglas Gregor064fdb22010-04-14 23:11:21 +00005200 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005201 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5202 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005203 true,
5204 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005205 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005206 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005207
5208 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5209 ArgType = Arg->getType();
5210 } else
John Wiegley01296292011-04-08 18:41:53 +00005211 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005212 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005213
John Wiegley01296292011-04-08 18:41:53 +00005214 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5215 ParamType,
5216 Arg, Converted))
5217 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005218 return Arg;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005219 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005220
Douglas Gregor20fdef32012-04-10 17:08:25 +00005221 // Deal with parameters of type std::nullptr_t.
5222 if (ParamType->isNullPtrType()) {
5223 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5224 Converted = TemplateArgument(Arg);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005225 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005226 }
5227
5228 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5229 case NPV_NotNullPointer:
5230 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5231 << Arg->getType() << ParamType;
5232 Diag(Param->getLocation(), diag::note_template_param_here);
5233 return ExprError();
5234
5235 case NPV_Error:
5236 return ExprError();
5237
5238 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005239 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Richard Smith78bb36f2014-07-24 02:27:39 +00005240 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5241 /*isNullPtr*/true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005242 return Arg;
Douglas Gregor20fdef32012-04-10 17:08:25 +00005243 }
5244 }
5245
Douglas Gregor0e558532009-02-11 16:16:59 +00005246 // -- For a non-type template-parameter of type pointer to data
5247 // member, qualification conversions (4.4) are applied.
5248 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5249
Douglas Gregor20fdef32012-04-10 17:08:25 +00005250 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5251 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005252 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005253 return Arg;
Douglas Gregord32e0282009-02-09 23:23:08 +00005254}
5255
5256/// \brief Check a template argument against its corresponding
5257/// template template parameter.
5258///
5259/// This routine implements the semantics of C++ [temp.arg.template].
5260/// It returns true if an error occurred, and false otherwise.
5261bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Reid Kleckner377c1592014-06-10 23:29:48 +00005262 TemplateArgumentLoc &Arg,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005263 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005264 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005265 TemplateDecl *Template = Name.getAsTemplateDecl();
5266 if (!Template) {
5267 // Any dependent template name is fine.
5268 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5269 return false;
5270 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005271
Richard Smith3f1b5d02011-05-05 21:57:07 +00005272 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005273 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005274 // the name of a class template or an alias template, expressed as an
5275 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005276 // primary class templates are considered when matching the
5277 // template template argument with the corresponding parameter;
5278 // partial specializations are not considered even if their
5279 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005280 //
5281 // Note that we also allow template template parameters here, which
5282 // will happen when we are dealing with, e.g., class template
5283 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005284 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005285 !isa<TemplateTemplateParmDecl>(Template) &&
5286 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005287 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005288 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005289 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005290 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005291 << Template;
5292 }
5293
Richard Smith1fde8ec2012-09-07 02:06:42 +00005294 TemplateParameterList *Params = Param->getTemplateParameters();
5295 if (Param->isExpandedParameterPack())
5296 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5297
Douglas Gregor85e0f662009-02-10 00:24:35 +00005298 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005299 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005300 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005301 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005302 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005303}
5304
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005305/// \brief Given a non-type template argument that refers to a
5306/// declaration and the type of its corresponding non-type template
5307/// parameter, produce an expression that properly refers to that
5308/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005309ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005310Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5311 QualType ParamType,
5312 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005313 // C++ [temp.param]p8:
5314 //
5315 // A non-type template-parameter of type "array of T" or
5316 // "function returning T" is adjusted to be of type "pointer to
5317 // T" or "pointer to function returning T", respectively.
5318 if (ParamType->isArrayType())
5319 ParamType = Context.getArrayDecayedType(ParamType);
5320 else if (ParamType->isFunctionType())
5321 ParamType = Context.getPointerType(ParamType);
5322
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005323 // For a NULL non-type template argument, return nullptr casted to the
5324 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005325 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005326 return ImpCastExprToType(
5327 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5328 ParamType,
5329 ParamType->getAs<MemberPointerType>()
5330 ? CK_NullToMemberPointer
5331 : CK_NullToPointer);
5332 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005333 assert(Arg.getKind() == TemplateArgument::Declaration &&
5334 "Only declaration template arguments permitted here");
5335
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005336 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5337
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005338 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005339 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5340 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005341 // If the value is a class member, we might have a pointer-to-member.
5342 // Determine whether the non-type template template parameter is of
5343 // pointer-to-member type. If so, we need to build an appropriate
5344 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5345 // would refer to the member itself.
5346 if (ParamType->isMemberPointerType()) {
5347 QualType ClassType
5348 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5349 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005350 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005351 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005352 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005353 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005354
5355 // The actual value-ness of this is unimportant, but for
5356 // internal consistency's sake, references to instance methods
5357 // are r-values.
5358 ExprValueKind VK = VK_LValue;
5359 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5360 VK = VK_RValue;
5361
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005362 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005363 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005364 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005365 Loc,
5366 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005367 if (RefExpr.isInvalid())
5368 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005369
John McCalle3027922010-08-25 11:45:40 +00005370 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005371
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005372 // We might need to perform a trailing qualification conversion, since
5373 // the element type on the parameter could be more qualified than the
5374 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005375 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005376 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005377 ParamType.getUnqualifiedType(), false,
5378 ObjCLifetimeConversion))
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005379 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005380
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005381 assert(!RefExpr.isInvalid() &&
5382 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005383 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005384 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005385 }
5386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005387
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005388 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005389
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005390 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005391 // When the non-type template parameter is a pointer, take the
5392 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005393 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005394 if (RefExpr.isInvalid())
5395 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005396
5397 if (T->isFunctionType() || T->isArrayType()) {
5398 // Decay functions and arrays.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005399 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
John Wiegley01296292011-04-08 18:41:53 +00005400 if (RefExpr.isInvalid())
5401 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005402
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005403 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005405
Douglas Gregorb242683d2010-04-01 18:32:35 +00005406 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005407 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005408 }
5409
John McCall7decc9e2010-11-18 06:31:45 +00005410 ExprValueKind VK = VK_RValue;
5411
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005412 // If the non-type template parameter has reference type, qualify the
5413 // resulting declaration reference with the extra qualifiers on the
5414 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005415 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5416 VK = VK_LValue;
5417 T = Context.getQualifiedType(T,
5418 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005419 } else if (isa<FunctionDecl>(VD)) {
5420 // References to functions are always lvalues.
5421 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423
John McCall7decc9e2010-11-18 06:31:45 +00005424 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005425}
5426
5427/// \brief Construct a new expression that refers to the given
5428/// integral template argument with the given source-location
5429/// information.
5430///
5431/// This routine takes care of the mapping from an integral template
5432/// argument (which may have any integral type) to the appropriate
5433/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005434ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005435Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5436 SourceLocation Loc) {
5437 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005438 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005439 QualType OrigT = Arg.getIntegralType();
5440
5441 // If this is an enum type that we're instantiating, we need to use an integer
5442 // type the same size as the enumerator. We don't want to build an
5443 // IntegerLiteral with enum type. The integer type of an enum type can be of
5444 // any integral type with C++11 enum classes, make sure we create the right
5445 // type of literal for it.
5446 QualType T = OrigT;
5447 if (const EnumType *ET = OrigT->getAs<EnumType>())
5448 T = ET->getDecl()->getIntegerType();
5449
5450 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005451 if (T->isAnyCharacterType()) {
5452 CharacterLiteral::CharacterKind Kind;
5453 if (T->isWideCharType())
5454 Kind = CharacterLiteral::Wide;
5455 else if (T->isChar16Type())
5456 Kind = CharacterLiteral::UTF16;
5457 else if (T->isChar32Type())
5458 Kind = CharacterLiteral::UTF32;
5459 else
5460 Kind = CharacterLiteral::Ascii;
5461
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005462 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5463 Kind, T, Loc);
5464 } else if (T->isBooleanType()) {
5465 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5466 T, Loc);
5467 } else if (T->isNullPtrType()) {
5468 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5469 } else {
5470 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005471 }
5472
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005473 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005474 // FIXME: This is a hack. We need a better way to handle substituted
5475 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005476 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5477 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005478 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005479 Loc, Loc);
5480 }
5481
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005482 return E;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005483}
5484
Douglas Gregor641040a2011-01-12 23:45:44 +00005485/// \brief Match two template parameters within template parameter lists.
5486static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5487 bool Complain,
5488 Sema::TemplateParameterListEqualKind Kind,
5489 SourceLocation TemplateArgLoc) {
5490 // Check the actual kind (type, non-type, template).
5491 if (Old->getKind() != New->getKind()) {
5492 if (Complain) {
5493 unsigned NextDiag = diag::err_template_param_different_kind;
5494 if (TemplateArgLoc.isValid()) {
5495 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5496 NextDiag = diag::note_template_param_different_kind;
5497 }
5498 S.Diag(New->getLocation(), NextDiag)
5499 << (Kind != Sema::TPL_TemplateMatch);
5500 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5501 << (Kind != Sema::TPL_TemplateMatch);
5502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005503
Douglas Gregor641040a2011-01-12 23:45:44 +00005504 return false;
5505 }
5506
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005507 // Check that both are parameter packs are neither are parameter packs.
5508 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005509 // template template parameter, the template template parameter can have
5510 // a parameter pack where the template template argument does not.
5511 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5512 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5513 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005514 if (Complain) {
5515 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5516 if (TemplateArgLoc.isValid()) {
5517 S.Diag(TemplateArgLoc,
5518 diag::err_template_arg_template_params_mismatch);
5519 NextDiag = diag::note_template_parameter_pack_non_pack;
5520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521
Douglas Gregor641040a2011-01-12 23:45:44 +00005522 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5523 : isa<NonTypeTemplateParmDecl>(New)? 1
5524 : 2;
5525 S.Diag(New->getLocation(), NextDiag)
5526 << ParamKind << New->isParameterPack();
5527 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5528 << ParamKind << Old->isParameterPack();
5529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
Douglas Gregor641040a2011-01-12 23:45:44 +00005531 return false;
5532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533
Douglas Gregor641040a2011-01-12 23:45:44 +00005534 // For non-type template parameters, check the type of the parameter.
5535 if (NonTypeTemplateParmDecl *OldNTTP
5536 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5537 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005538
Douglas Gregor641040a2011-01-12 23:45:44 +00005539 // If we are matching a template template argument to a template
5540 // template parameter and one of the non-type template parameter types
5541 // is dependent, then we must wait until template instantiation time
5542 // to actually compare the arguments.
5543 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5544 (OldNTTP->getType()->isDependentType() ||
5545 NewNTTP->getType()->isDependentType()))
5546 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005547
Douglas Gregor641040a2011-01-12 23:45:44 +00005548 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5549 if (Complain) {
5550 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5551 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005553 diag::err_template_arg_template_params_mismatch);
5554 NextDiag = diag::note_template_nontype_parm_different_type;
5555 }
5556 S.Diag(NewNTTP->getLocation(), NextDiag)
5557 << NewNTTP->getType()
5558 << (Kind != Sema::TPL_TemplateMatch);
5559 S.Diag(OldNTTP->getLocation(),
5560 diag::note_template_nontype_parm_prev_declaration)
5561 << OldNTTP->getType();
5562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005563
Douglas Gregor641040a2011-01-12 23:45:44 +00005564 return false;
5565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566
Douglas Gregor641040a2011-01-12 23:45:44 +00005567 return true;
5568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569
Douglas Gregor641040a2011-01-12 23:45:44 +00005570 // For template template parameters, check the template parameter types.
5571 // The template parameter lists of template template
5572 // parameters must agree.
5573 if (TemplateTemplateParmDecl *OldTTP
5574 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005576 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5577 OldTTP->getTemplateParameters(),
5578 Complain,
5579 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005581 : Kind),
5582 TemplateArgLoc);
5583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005584
Douglas Gregor641040a2011-01-12 23:45:44 +00005585 return true;
5586}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005587
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005588/// \brief Diagnose a known arity mismatch when comparing template argument
5589/// lists.
5590static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005591void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005592 TemplateParameterList *New,
5593 TemplateParameterList *Old,
5594 Sema::TemplateParameterListEqualKind Kind,
5595 SourceLocation TemplateArgLoc) {
5596 unsigned NextDiag = diag::err_template_param_list_different_arity;
5597 if (TemplateArgLoc.isValid()) {
5598 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5599 NextDiag = diag::note_template_param_list_different_arity;
5600 }
5601 S.Diag(New->getTemplateLoc(), NextDiag)
5602 << (New->size() > Old->size())
5603 << (Kind != Sema::TPL_TemplateMatch)
5604 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5605 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5606 << (Kind != Sema::TPL_TemplateMatch)
5607 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5608}
5609
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005610/// \brief Determine whether the given template parameter lists are
5611/// equivalent.
5612///
Mike Stump11289f42009-09-09 15:08:12 +00005613/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005614/// source code as part of a new template declaration.
5615///
5616/// \param Old The old template parameter list, typically found via
5617/// name lookup of the template declared with this template parameter
5618/// list.
5619///
5620/// \param Complain If true, this routine will produce a diagnostic if
5621/// the template parameter lists are not equivalent.
5622///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005623/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005624///
5625/// \param TemplateArgLoc If this source location is valid, then we
5626/// are actually checking the template parameter list of a template
5627/// argument (New) against the template parameter list of its
5628/// corresponding template template parameter (Old). We produce
5629/// slightly different diagnostics in this scenario.
5630///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005631/// \returns True if the template parameter lists are equal, false
5632/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005633bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005634Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5635 TemplateParameterList *Old,
5636 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005637 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005638 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005639 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5640 if (Complain)
5641 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5642 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005643
5644 return false;
5645 }
5646
Douglas Gregor641040a2011-01-12 23:45:44 +00005647 // C++0x [temp.arg.template]p3:
5648 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005649 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005650 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005651 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005652 // template-parameter-list of P. [...]
5653 TemplateParameterList::iterator NewParm = New->begin();
5654 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005655 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005656 OldParmEnd = Old->end();
5657 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005658 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5659 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005660 if (NewParm == NewParmEnd) {
5661 if (Complain)
5662 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5663 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005664
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005665 return false;
5666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005667
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005668 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5669 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005670 return false;
5671
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005672 ++NewParm;
5673 continue;
5674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005675
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005676 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005677 // [...] When P's template- parameter-list contains a template parameter
5678 // pack (14.5.3), the template parameter pack will match zero or more
5679 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005680 // template-parameter-list of A with the same type and form as the
5681 // template parameter pack in P (ignoring whether those template
5682 // parameters are template parameter packs).
5683 for (; NewParm != NewParmEnd; ++NewParm) {
5684 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5685 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005686 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005687 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005688 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005689
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005690 // Make sure we exhausted all of the arguments.
5691 if (NewParm != NewParmEnd) {
5692 if (Complain)
5693 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5694 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005696 return false;
5697 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005698
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005699 return true;
5700}
5701
5702/// \brief Check whether a template can be declared within this scope.
5703///
5704/// If the template declaration is valid in this scope, returns
5705/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005706bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005707Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005708 if (!S)
5709 return false;
5710
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005711 // Find the nearest enclosing declaration scope.
5712 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5713 (S->getFlags() & Scope::TemplateParamScope) != 0)
5714 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005715
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005716 // C++ [temp]p4:
5717 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005718 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005719 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005720 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005721 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005722
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005723 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005724 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005725
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005726 // C++ [temp]p2:
5727 // A template-declaration can appear only as a namespace scope or
5728 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005729 if (Ctx) {
5730 if (Ctx->isFileContext())
5731 return false;
5732 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5733 // C++ [temp.mem]p2:
5734 // A local class shall not have member templates.
5735 if (RD->isLocalClass())
5736 return Diag(TemplateParams->getTemplateLoc(),
5737 diag::err_template_inside_local_class)
5738 << TemplateParams->getSourceRange();
5739 else
5740 return false;
5741 }
5742 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005743
Mike Stump11289f42009-09-09 15:08:12 +00005744 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005745 diag::err_template_outside_namespace_or_class_scope)
5746 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005747}
Douglas Gregor67a65642009-02-17 23:15:12 +00005748
Douglas Gregor54888652009-10-07 00:13:32 +00005749/// \brief Determine what kind of template specialization the given declaration
5750/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005751static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005752 if (!D)
5753 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005754
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005755 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5756 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005757 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5758 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005759 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5760 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761
Douglas Gregor54888652009-10-07 00:13:32 +00005762 return TSK_Undeclared;
5763}
5764
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005766/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005767///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005768/// This routine determines whether a template specialization can be declared
5769/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005770///
5771/// \param S the semantic analysis object for which this check is being
5772/// performed.
5773///
5774/// \param Specialized the entity being specialized or instantiated, which
5775/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005776/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005777/// member class).
5778///
5779/// \param PrevDecl the previous declaration of this entity, if any.
5780///
5781/// \param Loc the location of the explicit specialization or instantiation of
5782/// this entity.
5783///
5784/// \param IsPartialSpecialization whether this is a partial specialization of
5785/// a class template.
5786///
Douglas Gregor54888652009-10-07 00:13:32 +00005787/// \returns true if there was an error that we cannot recover from, false
5788/// otherwise.
5789static bool CheckTemplateSpecializationScope(Sema &S,
5790 NamedDecl *Specialized,
5791 NamedDecl *PrevDecl,
5792 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005793 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005794 // Keep these "kind" numbers in sync with the %select statements in the
5795 // various diagnostics emitted by this routine.
5796 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005797 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005798 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005799 else if (isa<VarTemplateDecl>(Specialized))
5800 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005801 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005802 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005803 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005804 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005805 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005806 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005807 else if (isa<RecordDecl>(Specialized))
5808 EntityKind = 7;
5809 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5810 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005811 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005812 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005813 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005814 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005815 return true;
5816 }
5817
Douglas Gregorf47b9112009-02-25 22:02:03 +00005818 // C++ [temp.expl.spec]p2:
5819 // An explicit specialization shall be declared in the namespace
5820 // of which the template is a member, or, for member templates, in
5821 // the namespace of which the enclosing class or enclosing class
5822 // template is a member. An explicit specialization of a member
5823 // function, member class or static data member of a class
5824 // template shall be declared in the namespace of which the class
5825 // template is a member. Such a declaration may also be a
5826 // definition. If the declaration is not a definition, the
5827 // specialization may be defined later in the name- space in which
5828 // the explicit specialization was declared, or in a namespace
5829 // that encloses the one in which the explicit specialization was
5830 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005831 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005832 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005833 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005834 return true;
5835 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005836
Douglas Gregor40fb7442009-10-07 17:30:37 +00005837 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005838 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005839 // Do not warn for class scope explicit specialization during
5840 // instantiation, warning was already emitted during pattern
5841 // semantic analysis.
5842 if (!S.ActiveTemplateInstantiations.size())
5843 S.Diag(Loc, diag::ext_function_specialization_in_class)
5844 << Specialized;
5845 } else {
5846 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5847 << Specialized;
5848 return true;
5849 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005850 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005851
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005852 if (S.CurContext->isRecord() &&
5853 !S.CurContext->Equals(Specialized->getDeclContext())) {
5854 // Make sure that we're specializing in the right record context.
5855 // Otherwise, things can go horribly wrong.
5856 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5857 << Specialized;
5858 return true;
5859 }
5860
Douglas Gregore4b05162009-10-07 17:21:34 +00005861 // C++ [temp.class.spec]p6:
5862 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005863 // in any namespace scope in which its definition may be defined (14.5.1
5864 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005865 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005866 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005867 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005868
5869 // Make sure that this redeclaration (or definition) occurs in an enclosing
5870 // namespace.
5871 // Note that HandleDeclarator() performs this check for explicit
5872 // specializations of function templates, static data members, and member
5873 // functions, so we skip the check here for those kinds of entities.
5874 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5875 // Should we refactor that check, so that it occurs later?
5876 if (!DC->Encloses(SpecializedContext) &&
5877 !(isa<FunctionTemplateDecl>(Specialized) ||
5878 isa<FunctionDecl>(Specialized) ||
5879 isa<VarTemplateDecl>(Specialized) ||
5880 isa<VarDecl>(Specialized))) {
5881 if (isa<TranslationUnitDecl>(SpecializedContext))
5882 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5883 << EntityKind << Specialized;
Alexey Bataev0068cb22015-03-20 07:21:46 +00005884 else if (isa<NamespaceDecl>(SpecializedContext)) {
5885 int Diag = diag::err_template_spec_redecl_out_of_scope;
5886 if (S.getLangOpts().MicrosoftExt)
5887 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5888 S.Diag(Loc, Diag) << EntityKind << Specialized
5889 << cast<NamedDecl>(SpecializedContext);
5890 } else
Richard Smitha98f8fc2013-12-07 05:09:50 +00005891 llvm_unreachable("unexpected namespace context for specialization");
5892
5893 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5894 } else if ((!PrevDecl ||
5895 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5896 getTemplateSpecializationKind(PrevDecl) ==
5897 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005898 // C++ [temp.exp.spec]p2:
5899 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005900 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005901 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005902 // An explicit specialization of a member function, member class or
5903 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005904 // namespace of which the class template is a member.
5905 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005906 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005907 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005908 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005909 // C++11 [temp.explicit]p3:
5910 // An explicit instantiation shall appear in an enclosing namespace of its
5911 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005912 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005913 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005914 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005915 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005916 "DC encloses TU but isn't in enclosing namespace set");
5917 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005918 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005919 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5920 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005921 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005922 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005923 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005924 Diag = diag::ext_template_spec_decl_out_of_scope;
5925 else
5926 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5927 S.Diag(Loc, Diag)
5928 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5929 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005930
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005931 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005932 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005933 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005934
Douglas Gregorf47b9112009-02-25 22:02:03 +00005935 return false;
5936}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005937
Richard Smith6056d5e2014-02-09 00:54:43 +00005938static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5939 if (!E->isInstantiationDependent())
5940 return SourceLocation();
5941 DependencyChecker Checker(Depth);
5942 Checker.TraverseStmt(E);
5943 if (Checker.Match && Checker.MatchLoc.isInvalid())
5944 return E->getSourceRange();
5945 return Checker.MatchLoc;
5946}
5947
5948static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5949 if (!TL.getType()->isDependentType())
5950 return SourceLocation();
5951 DependencyChecker Checker(Depth);
5952 Checker.TraverseTypeLoc(TL);
5953 if (Checker.Match && Checker.MatchLoc.isInvalid())
5954 return TL.getSourceRange();
5955 return Checker.MatchLoc;
5956}
5957
Larisse Voufo39a1e502013-08-06 01:03:05 +00005958/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005959/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005960static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005961 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5962 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005963 for (unsigned I = 0; I != NumArgs; ++I) {
5964 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005965 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005966 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5967 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005968 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005969
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005970 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005972
Eli Friedmanb826a002012-09-26 02:36:12 +00005973 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005974 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00005975
5976 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005977
Douglas Gregor98318c22011-01-03 21:37:45 +00005978 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005979 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5980 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00005981
5982 // Strip off any implicit casts we added as part of type checking.
5983 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5984 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005986 // C++ [temp.class.spec]p8:
5987 // A non-type argument is non-specialized if it is the name of a
5988 // non-type parameter. All other non-type arguments are
5989 // specialized.
5990 //
5991 // Below, we check the two conditions that only apply to
5992 // specialized non-type arguments, so skip any non-specialized
5993 // arguments.
5994 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00005995 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005996 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005997
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005998 // C++ [temp.class.spec]p9:
5999 // Within the argument list of a class template partial
6000 // specialization, the following restrictions apply:
6001 // -- A partially specialized non-type argument expression
6002 // shall not involve a template parameter of the partial
6003 // specialization except when the argument expression is a
6004 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00006005 SourceRange ParamUseRange =
6006 findTemplateParameter(Param->getDepth(), ArgExpr);
6007 if (ParamUseRange.isValid()) {
6008 if (IsDefaultArgument) {
6009 S.Diag(TemplateNameLoc,
6010 diag::err_dependent_non_type_arg_in_partial_spec);
6011 S.Diag(ParamUseRange.getBegin(),
6012 diag::note_dependent_non_type_default_arg_in_partial_spec)
6013 << ParamUseRange;
6014 } else {
6015 S.Diag(ParamUseRange.getBegin(),
6016 diag::err_dependent_non_type_arg_in_partial_spec)
6017 << ParamUseRange;
6018 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006019 return true;
6020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006022 // -- The type of a template parameter corresponding to a
6023 // specialized non-type argument shall not be dependent on a
6024 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00006025 //
6026 // FIXME: We need to delay this check until instantiation in some cases:
6027 //
6028 // template<template<typename> class X> struct A {
6029 // template<typename T, X<T> N> struct B;
6030 // template<typename T> struct B<T, 0>;
6031 // };
6032 // template<typename> using X = int;
6033 // A<X>::B<int, 0> b;
6034 ParamUseRange = findTemplateParameter(
6035 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6036 if (ParamUseRange.isValid()) {
6037 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6038 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6039 << Param->getType() << ParamUseRange;
6040 S.Diag(Param->getLocation(), diag::note_template_param_here)
6041 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006042 return true;
6043 }
6044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006045
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006046 return false;
6047}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006048
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006049/// \brief Check the non-type template arguments of a class template
6050/// partial specialization according to C++ [temp.class.spec]p9.
6051///
Richard Smith6056d5e2014-02-09 00:54:43 +00006052/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006053/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00006054/// template.
6055/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00006056/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00006057/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006058///
Richard Smith6056d5e2014-02-09 00:54:43 +00006059/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00006060static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006061 Sema &S, SourceLocation TemplateNameLoc,
6062 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00006063 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006064 const TemplateArgument *ArgList = TemplateArgs.data();
6065
6066 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6067 NonTypeTemplateParmDecl *Param
6068 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6069 if (!Param)
6070 continue;
6071
Richard Smith6056d5e2014-02-09 00:54:43 +00006072 if (CheckNonTypeTemplatePartialSpecializationArgs(
6073 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00006074 return true;
6075 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006076
6077 return false;
6078}
6079
John McCall48871652010-08-21 09:40:31 +00006080DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00006081Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6082 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00006083 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006084 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00006085 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00006086 AttributeList *Attr,
Richard Smithc7e6ff02015-05-18 20:36:47 +00006087 MultiTemplateParamsArg
6088 TemplateParameterLists,
6089 SkipBodyInfo *SkipBody) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006090 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00006091
Richard Smith4b55a9c2014-04-17 03:29:33 +00006092 CXXScopeSpec &SS = TemplateId.SS;
6093
Abramo Bagnara60804e12011-03-18 15:16:37 +00006094 // NOTE: KWLoc is the location of the tag keyword. This will instead
6095 // store the location of the outermost template keyword in the declaration.
6096 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00006097 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6098 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6099 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6100 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00006101
Douglas Gregor67a65642009-02-17 23:15:12 +00006102 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00006103 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00006104 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00006105 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6106
6107 if (!ClassTemplate) {
6108 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006109 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00006110 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6111 return true;
6112 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006113
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006114 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00006115 bool isPartialSpecialization = false;
6116
Douglas Gregorf47b9112009-02-25 22:02:03 +00006117 // Check the validity of the template headers that introduce this
6118 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00006119 // FIXME: We probably shouldn't complain about these headers for
6120 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006121 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00006122 TemplateParameterList *TemplateParams =
6123 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00006124 KWLoc, TemplateNameLoc, SS, &TemplateId,
6125 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6126 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006127 if (Invalid)
6128 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006129
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006130 if (TemplateParams && TemplateParams->size() > 0) {
6131 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00006132
Douglas Gregorec9518b2010-12-21 08:14:57 +00006133 if (TUK == TUK_Friend) {
6134 Diag(KWLoc, diag::err_partial_specialization_friend)
6135 << SourceRange(LAngleLoc, RAngleLoc);
6136 return true;
6137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006138
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006139 // C++ [temp.class.spec]p10:
6140 // The template parameter list of a specialization shall not
6141 // contain default template argument values.
6142 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6143 Decl *Param = TemplateParams->getParam(I);
6144 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6145 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006146 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006147 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00006148 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006149 }
6150 } else if (NonTypeTemplateParmDecl *NTTP
6151 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6152 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00006153 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006154 diag::err_default_arg_in_partial_spec)
6155 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006156 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006157 }
6158 } else {
6159 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006160 if (TTP->hasDefaultArgument()) {
6161 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006162 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00006163 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00006164 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00006165 }
6166 }
6167 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006168 } else if (TemplateParams) {
6169 if (TUK == TUK_Friend)
6170 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00006171 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006172 SourceRange(TemplateParams->getTemplateLoc(),
6173 TemplateParams->getRAngleLoc()))
6174 << SourceRange(LAngleLoc, RAngleLoc);
6175 else
6176 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00006177 } else {
6178 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006179 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00006180
Douglas Gregor67a65642009-02-17 23:15:12 +00006181 // Check that the specialization uses the same tag kind as the
6182 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006183 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6184 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00006185 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00006186 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00006187 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006188 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006189 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006190 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006191 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006192 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006193 diag::note_previous_use);
6194 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6195 }
6196
Douglas Gregorc40290e2009-03-09 23:48:35 +00006197 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006198 TemplateArgumentListInfo TemplateArgs =
6199 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006200
Douglas Gregor14406932011-01-03 20:35:03 +00006201 // Check for unexpanded parameter packs in any of the template arguments.
6202 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006203 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006204 UPPC_PartialSpecialization))
6205 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006206
Douglas Gregor67a65642009-02-17 23:15:12 +00006207 // Check that the template argument list is well-formed for this
6208 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006209 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006210 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6211 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006212 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006213
Douglas Gregor2373c592009-05-31 09:31:02 +00006214 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006215 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006216 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006217 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006218 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6219 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006220 return true;
6221
Douglas Gregor678d76c2011-07-01 01:22:09 +00006222 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006223 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006224 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006225 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006226 TemplateArgs.size(),
6227 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006228 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6229 << ClassTemplate->getDeclName();
6230 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006231 }
6232 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006233
Craig Topperc3ec1492014-05-26 06:22:03 +00006234 void *InsertPos = nullptr;
6235 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006236
6237 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006238 // FIXME: Template parameter list matters, too
Craig Topper7e0daca2014-06-26 04:58:53 +00006239 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006240 else
Craig Topper7e0daca2014-06-26 04:58:53 +00006241 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006242
Craig Topperc3ec1492014-05-26 06:22:03 +00006243 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006244
Douglas Gregorf47b9112009-02-25 22:02:03 +00006245 // Check whether we can declare a class template specialization in
6246 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006247 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006248 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6249 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006250 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006251 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006252
Douglas Gregor15301382009-07-30 17:40:51 +00006253 // The canonical type
6254 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006255 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006256 // Build the canonical type that describes the converted template
6257 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006258 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6259 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006260 Converted.data(),
6261 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006262
6263 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006264 ClassTemplate->getInjectedClassNameSpecialization())) {
6265 // C++ [temp.class.spec]p9b3:
6266 //
6267 // -- The argument list of the specialization shall not be identical
6268 // to the implicit argument list of the primary template.
6269 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006270 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006271 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006272 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6273 ClassTemplate->getIdentifier(),
6274 TemplateNameLoc,
6275 Attr,
6276 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006277 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +00006278 /*FriendLoc*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006279 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006280 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006281 }
Douglas Gregor15301382009-07-30 17:40:51 +00006282
Douglas Gregor2373c592009-05-31 09:31:02 +00006283 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006284 ClassTemplatePartialSpecializationDecl *PrevPartial
6285 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006286 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006287 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006288 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006289 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006290 TemplateParams,
6291 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006292 Converted.data(),
6293 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006294 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006295 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006296 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006297 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006298 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006299 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006300 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006301 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006302 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006303
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006304 if (!PrevPartial)
6305 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006306 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006307
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006308 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006309 // template specialization, make a note of that.
6310 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6311 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006312
Douglas Gregor91772d12009-06-13 00:26:55 +00006313 // Check that all of the template parameters of the class template
6314 // partial specialization are deducible from the template
6315 // arguments. If not, this class template partial specialization
6316 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006317 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006318 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006319 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006320 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006321
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006322 if (!DeducibleParams.all()) {
6323 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006324 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006325 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006326 << SourceRange(TemplateNameLoc, RAngleLoc);
6327 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6328 if (!DeducibleParams[I]) {
6329 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6330 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006331 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006332 diag::note_partial_spec_unused_parameter)
6333 << Param->getDeclName();
6334 else
Mike Stump11289f42009-09-09 15:08:12 +00006335 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006336 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006337 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006338 }
6339 }
6340 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006341 } else {
6342 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006343 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006344 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006345 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006346 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006347 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006348 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006349 Converted.data(),
6350 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006351 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006352 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006353 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006354 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006355 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006356 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006357 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006358
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006359 if (!PrevDecl)
6360 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006361
6362 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006363 }
6364
Douglas Gregor06db9f52009-10-12 20:18:28 +00006365 // C++ [temp.expl.spec]p6:
6366 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006367 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006368 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006369 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006370 // use occurs; no diagnostic is required.
6371 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006372 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006373 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006374 // Is there any previous explicit specialization declaration?
6375 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6376 Okay = true;
6377 break;
6378 }
6379 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006380
Douglas Gregorc854c662010-02-26 06:03:23 +00006381 if (!Okay) {
6382 SourceRange Range(TemplateNameLoc, RAngleLoc);
6383 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6384 << Context.getTypeDeclType(Specialization) << Range;
6385
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006386 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006387 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006388 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006389 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006390 return true;
6391 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006393
Douglas Gregor2208a292009-09-26 20:57:03 +00006394 // If this is not a friend, note that this is an explicit specialization.
6395 if (TUK != TUK_Friend)
6396 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006397
6398 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006399 if (TUK == TUK_Definition) {
Richard Smithc7e6ff02015-05-18 20:36:47 +00006400 RecordDecl *Def = Specialization->getDefinition();
6401 NamedDecl *Hidden = nullptr;
6402 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6403 SkipBody->ShouldSkip = true;
6404 makeMergedDefinitionVisible(Hidden, KWLoc);
6405 // From here on out, treat this as just a redeclaration.
6406 TUK = TUK_Declaration;
6407 } else if (Def) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006408 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006409 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006410 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006411 Diag(Def->getLocation(), diag::note_previous_definition);
6412 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006413 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006414 }
6415 }
6416
John McCall659a3372010-12-18 03:30:47 +00006417 if (Attr)
6418 ProcessDeclAttributeList(S, Specialization, Attr);
6419
Richard Smith034b94a2012-08-17 03:20:55 +00006420 // Add alignment attributes if necessary; these attributes are checked when
6421 // the ASTContext lays out the structure.
6422 if (TUK == TUK_Definition) {
6423 AddAlignmentAttributesForRecord(Specialization);
6424 AddMsStructLayoutForRecord(Specialization);
6425 }
6426
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006427 if (ModulePrivateLoc.isValid())
6428 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6429 << (isPartialSpecialization? 1 : 0)
6430 << FixItHint::CreateRemoval(ModulePrivateLoc);
6431
Douglas Gregord56a91e2009-02-26 22:19:44 +00006432 // Build the fully-sugared type for this class template
6433 // specialization as the user wrote in the specialization
6434 // itself. This means that we'll pretty-print the type retrieved
6435 // from the specialization's declaration the way that the user
6436 // actually wrote the specialization, rather than formatting the
6437 // name based on the "canonical" representation used to store the
6438 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006439 TypeSourceInfo *WrittenTy
6440 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6441 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006442 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006443 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006444 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006445 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006446
Douglas Gregor1e249f82009-02-25 22:18:32 +00006447 // C++ [temp.expl.spec]p9:
6448 // A template explicit specialization is in the scope of the
6449 // namespace in which the template was defined.
6450 //
6451 // We actually implement this paragraph where we set the semantic
6452 // context (in the creation of the ClassTemplateSpecializationDecl),
6453 // but we also maintain the lexical context where the actual
6454 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006455 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006456
Douglas Gregor67a65642009-02-17 23:15:12 +00006457 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006458 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006459 Specialization->startDefinition();
6460
Douglas Gregor2208a292009-09-26 20:57:03 +00006461 if (TUK == TUK_Friend) {
6462 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6463 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006464 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006465 /*FIXME:*/KWLoc);
6466 Friend->setAccess(AS_public);
6467 CurContext->addDecl(Friend);
6468 } else {
6469 // Add the specialization into its lexical context, so that it can
6470 // be seen when iterating through the list of declarations in that
6471 // context. However, specializations are not found by name lookup.
6472 CurContext->addDecl(Specialization);
6473 }
John McCall48871652010-08-21 09:40:31 +00006474 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006475}
Douglas Gregor333489b2009-03-27 23:10:48 +00006476
John McCall48871652010-08-21 09:40:31 +00006477Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006478 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006479 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006480 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006481 ActOnDocumentableDecl(NewDecl);
6482 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006483}
6484
John McCall48871652010-08-21 09:40:31 +00006485Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00006486 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006487 Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006488 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006489 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00006490
Douglas Gregor17a7c122009-06-24 00:54:41 +00006491 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00006492 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00006493 }
Mike Stump11289f42009-09-09 15:08:12 +00006494
Douglas Gregor17a7c122009-06-24 00:54:41 +00006495 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006496
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006497 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00006498 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006499 TemplateParameterLists);
Argyrios Kyrtzidis6fada2d2012-12-14 06:53:58 +00006500 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Douglas Gregor17a7c122009-06-24 00:54:41 +00006501}
6502
John McCall4f7ced62010-02-11 01:33:53 +00006503/// \brief Strips various properties off an implicit instantiation
6504/// that has just been explicitly specialized.
6505static void StripImplicitInstantiation(NamedDecl *D) {
Nico Webere4974382014-12-19 23:52:45 +00006506 D->dropAttr<DLLImportAttr>();
6507 D->dropAttr<DLLExportAttr>();
John McCall4f7ced62010-02-11 01:33:53 +00006508
Nico Webere4974382014-12-19 23:52:45 +00006509 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
John McCall4f7ced62010-02-11 01:33:53 +00006510 FD->setInlineSpecified(false);
John McCall4f7ced62010-02-11 01:33:53 +00006511}
6512
Nico Webera8f80b32012-01-09 19:52:25 +00006513/// \brief Compute the diagnostic location for an explicit instantiation
6514// declaration or definition.
6515static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006516 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006517 // Explicit instantiations following a specialization have no effect and
6518 // hence no PointOfInstantiation. In that case, walk decl backwards
6519 // until a valid name loc is found.
6520 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006521 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6522 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006523 PrevDiagLoc = Prev->getLocation();
6524 }
6525 assert(PrevDiagLoc.isValid() &&
6526 "Explicit instantiation without point of instantiation?");
6527 return PrevDiagLoc;
6528}
6529
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006530/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006531/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006533/// new specialization/instantiation will have any effect.
6534///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006536/// instantiation.
6537///
6538/// \param NewTSK the kind of the new explicit specialization or instantiation.
6539///
6540/// \param PrevDecl the previous declaration of the entity.
6541///
6542/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6543///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006545/// declaration was instantiated (either implicitly or explicitly).
6546///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006547/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006548/// specialization or instantiation has no effect and should be ignored.
6549///
6550/// \returns true if there was an error that should prevent the introduction of
6551/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006552bool
6553Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6554 TemplateSpecializationKind NewTSK,
6555 NamedDecl *PrevDecl,
6556 TemplateSpecializationKind PrevTSK,
6557 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006558 bool &HasNoEffect) {
6559 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006560
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006561 switch (NewTSK) {
6562 case TSK_Undeclared:
6563 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006564 assert(
6565 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6566 "previous declaration must be implicit!");
6567 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006568
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006569 case TSK_ExplicitSpecialization:
6570 switch (PrevTSK) {
6571 case TSK_Undeclared:
6572 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006573 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006574 // explicitly specialized or has merely been mentioned without any
6575 // instantiation.
6576 return false;
6577
6578 case TSK_ImplicitInstantiation:
6579 if (PrevPointOfInstantiation.isInvalid()) {
6580 // The declaration itself has not actually been instantiated, so it is
6581 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006582 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006583 return false;
6584 }
6585 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006586
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006587 case TSK_ExplicitInstantiationDeclaration:
6588 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006589 assert((PrevTSK == TSK_ImplicitInstantiation ||
6590 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006591 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006592
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006593 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006595 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006596 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006597 // implicit instantiation to take place, in every translation unit in
6598 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006599 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006600 // Is there any previous explicit specialization declaration?
6601 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6602 return false;
6603 }
6604
Douglas Gregor1d957a32009-10-27 18:42:08 +00006605 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006606 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006607 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006608 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006609
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006610 return true;
6611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006612
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006613 case TSK_ExplicitInstantiationDeclaration:
6614 switch (PrevTSK) {
6615 case TSK_ExplicitInstantiationDeclaration:
6616 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006617 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006618 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006619
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006620 case TSK_Undeclared:
6621 case TSK_ImplicitInstantiation:
6622 // We're explicitly instantiating something that may have already been
6623 // implicitly instantiated; that's fine.
6624 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006626 case TSK_ExplicitSpecialization:
6627 // C++0x [temp.explicit]p4:
6628 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006629 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006630 // specialization for that template, the explicit instantiation has no
6631 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006632 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006633 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006635 case TSK_ExplicitInstantiationDefinition:
6636 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006637 // If an entity is the subject of both an explicit instantiation
6638 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006639 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006640 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006641 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006642
6643 // Explicit instantiations following a specialization have no effect and
6644 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6645 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006646 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6647 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006648 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006649 return false;
6650 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006651
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006652 case TSK_ExplicitInstantiationDefinition:
6653 switch (PrevTSK) {
6654 case TSK_Undeclared:
6655 case TSK_ImplicitInstantiation:
6656 // We're explicitly instantiating something that may have already been
6657 // implicitly instantiated; that's fine.
6658 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006660 case TSK_ExplicitSpecialization:
6661 // C++ DR 259, C++0x [temp.explicit]p4:
6662 // For a given set of template parameters, if an explicit
6663 // instantiation of a template appears after a declaration of
6664 // an explicit specialization for that template, the explicit
6665 // instantiation has no effect.
6666 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006667 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006668 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006669 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006670 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006671 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6672 diag::ext_explicit_instantiation_after_specialization)
6673 << PrevDecl;
6674 Diag(PrevDecl->getLocation(),
6675 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006676 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006677 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006678
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006679 case TSK_ExplicitInstantiationDeclaration:
6680 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006682
6683 // C++0x [temp.explicit]p4:
6684 // For a given set of template parameters, if an explicit instantiation
6685 // of a template appears after a declaration of an explicit
6686 // specialization for that template, the explicit instantiation has no
6687 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006688 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006689 // Is there any previous explicit specialization declaration?
6690 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6691 HasNoEffect = true;
6692 break;
6693 }
6694 }
6695
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006696 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006697
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006698 case TSK_ExplicitInstantiationDefinition:
6699 // C++0x [temp.spec]p5:
6700 // For a given template and a given set of template-arguments,
6701 // - an explicit instantiation definition shall appear at most once
6702 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006703
6704 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6705 Diag(NewLoc, (getLangOpts().MSVCCompat)
Richard Smith1b98ccc2014-07-19 01:39:17 +00006706 ? diag::ext_explicit_instantiation_duplicate
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006707 : diag::err_explicit_instantiation_duplicate)
6708 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006709 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006710 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006711 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006713 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006715
David Blaikie83d382b2011-09-23 05:06:16 +00006716 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006717}
6718
John McCallb9c78482010-04-08 09:05:18 +00006719/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006720/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006721///
James Dennettf14a6e52012-06-15 22:23:43 +00006722/// The only possible way to get a dependent function template specialization
6723/// is with a friend declaration, like so:
6724///
6725/// \code
6726/// template \<class T> void foo(T);
6727/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006728/// friend void foo<>(T);
6729/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006730/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006731///
6732/// There really isn't any useful analysis we can do here, so we
6733/// just store the information.
6734bool
6735Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6736 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6737 LookupResult &Previous) {
6738 // Remove anything from Previous that isn't a function template in
6739 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006740 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006741 LookupResult::Filter F = Previous.makeFilter();
6742 while (F.hasNext()) {
6743 NamedDecl *D = F.next()->getUnderlyingDecl();
6744 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006745 !FDLookupContext->InEnclosingNamespaceSetOf(
6746 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006747 F.erase();
6748 }
6749 F.done();
6750
6751 // Should this be diagnosed here?
6752 if (Previous.empty()) return true;
6753
6754 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6755 ExplicitTemplateArgs);
6756 return false;
6757}
6758
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006759/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006760/// specialization.
6761///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006762/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006763/// explicit function template specialization. On successful completion,
6764/// the function declaration \p FD will become a function template
6765/// specialization.
6766///
6767/// \param FD the function declaration, which will be updated to become a
6768/// function template specialization.
6769///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006770/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6771/// if any. Note that this may be valid info even when 0 arguments are
6772/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6773/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006774///
Francois Pichet3a44e432011-07-08 06:21:47 +00006775/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006776/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006777bool Sema::CheckFunctionTemplateSpecialization(
6778 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6779 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006780 // The set of function template specializations that could match this
6781 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006782 UnresolvedSet<8> Candidates;
Larisse Voufo98b20f12013-07-19 23:00:19 +00006783 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006784
Sebastian Redl50c68252010-08-31 00:36:30 +00006785 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006786 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6787 I != E; ++I) {
6788 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6789 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006790 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006791 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006792 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6793 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006794 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795
Richard Smith574f4f62013-01-14 05:37:29 +00006796 // When matching a constexpr member function template specialization
6797 // against the primary template, we don't yet know whether the
6798 // specialization has an implicit 'const' (because we don't know whether
6799 // it will be a static member function until we know which template it
6800 // specializes), so adjust it now assuming it specializes this template.
6801 QualType FT = FD->getType();
6802 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006803 CXXMethodDecl *OldMD =
6804 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006805 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006806 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006807 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6808 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006809 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006810 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006811 }
6812 }
6813
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006814 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006815 // A trailing template-argument can be left unspecified in the
6816 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006817 // provided it can be deduced from the function argument type.
6818 // Perform template argument deduction to determine whether we may be
6819 // specializing this template.
6820 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006821 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006822 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006823 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6824 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6825 ExplicitTemplateArgs, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006826 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006827 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006828 FailedCandidates.addCandidate()
6829 .set(FunTmpl->getTemplatedDecl(),
6830 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006831 (void)TDK;
6832 continue;
6833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006834
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006835 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00006836 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006837 }
6838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839
Douglas Gregor5de279c2009-09-26 03:41:46 +00006840 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006841 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006842 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006843 FD->getLocation(),
6844 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6845 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006846 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006847 PDiag(diag::note_function_template_spec_matched));
6848
John McCall58cc69d2010-01-27 01:50:18 +00006849 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006850 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006851
6852 // Ignore access information; it doesn't figure into redeclaration checking.
6853 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006854
6855 FunctionTemplateSpecializationInfo *SpecInfo
6856 = Specialization->getTemplateSpecializationInfo();
6857 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006858
6859 // Note: do not overwrite location info if previous template
6860 // specialization kind was explicit.
6861 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006862 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006863 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006864 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6865 // function can differ from the template declaration with respect to
6866 // the constexpr specifier.
6867 Specialization->setConstexpr(FD->isConstexpr());
6868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006869
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006870 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006871 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006872
6873 // If this is a friend declaration, then we're not really declaring
6874 // an explicit specialization.
6875 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006876
Douglas Gregor54888652009-10-07 00:13:32 +00006877 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006878 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006879 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006880 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006881 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006882 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006883 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006884
6885 // C++ [temp.expl.spec]p6:
6886 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006888 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006890 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006891 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006892 if (!isFriend &&
6893 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006894 TSK_ExplicitSpecialization,
6895 Specialization,
6896 SpecInfo->getTemplateSpecializationKind(),
6897 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006898 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006899 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006900
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006901 // Mark the prior declaration as an explicit specialization, so that later
6902 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006903 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006904 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006905 MarkUnusedFileScopedDecl(Specialization);
6906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006907
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006908 // Turn the given function declaration into a function template
6909 // specialization, with the template arguments from the previous
6910 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006911 // Take copies of (semantic and syntactic) template argument lists.
6912 const TemplateArgumentList* TemplArgs = new (Context)
6913 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregord5058122010-02-11 01:19:42 +00006914 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006915 TemplArgs, /*InsertPos=*/nullptr,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006916 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00006917 ExplicitTemplateArgs);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006918
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006919 // The "previous declaration" for this function template specialization is
6920 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006921 Previous.clear();
6922 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006923 return false;
6924}
6925
Douglas Gregor86d142a2009-10-08 07:24:58 +00006926/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006927/// specialization.
6928///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006929/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006930/// explicit member function specialization. On successful completion,
6931/// the function declaration \p FD will become a member function
6932/// specialization.
6933///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006934/// \param Member the member declaration, which will be updated to become a
6935/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006936///
John McCall1f82f242009-11-18 22:49:29 +00006937/// \param Previous the set of declarations, one of which may be specialized
6938/// by this function specialization; the set will be modified to contain the
6939/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940bool
John McCall1f82f242009-11-18 22:49:29 +00006941Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006942 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006943
Douglas Gregor86d142a2009-10-08 07:24:58 +00006944 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00006945 NamedDecl *Instantiation = nullptr;
6946 NamedDecl *InstantiatedFrom = nullptr;
6947 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006948
John McCall1f82f242009-11-18 22:49:29 +00006949 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006950 // Nowhere to look anyway.
6951 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006952 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6953 I != E; ++I) {
6954 NamedDecl *D = (*I)->getUnderlyingDecl();
6955 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00006956 QualType Adjusted = Function->getType();
6957 if (!hasExplicitCallingConv(Adjusted))
6958 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6959 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006960 Instantiation = Method;
6961 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006962 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006963 break;
6964 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006965 }
6966 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00006967 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006968 VarDecl *PrevVar;
6969 if (Previous.isSingleResult() &&
6970 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00006971 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00006972 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006973 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006974 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006975 }
6976 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006977 CXXRecordDecl *PrevRecord;
6978 if (Previous.isSingleResult() &&
6979 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6980 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006981 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006982 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006983 }
Richard Smith7d137e32012-03-23 03:33:32 +00006984 } else if (isa<EnumDecl>(Member)) {
6985 EnumDecl *PrevEnum;
6986 if (Previous.isSingleResult() &&
6987 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6988 Instantiation = PrevEnum;
6989 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6990 MSInfo = PrevEnum->getMemberSpecializationInfo();
6991 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006992 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006994 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006995 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006996 // specializations are always out-of-line, the caller will complain about
6997 // this mismatch later.
6998 return false;
6999 }
John McCalle820e5e2010-04-13 20:37:33 +00007000
7001 // If this is a friend, just bail out here before we start turning
7002 // things into explicit specializations.
7003 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7004 // Preserve instantiation information.
7005 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7006 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7007 cast<CXXMethodDecl>(InstantiatedFrom),
7008 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7009 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7010 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7011 cast<CXXRecordDecl>(InstantiatedFrom),
7012 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7013 }
7014
7015 Previous.clear();
7016 Previous.addDecl(Instantiation);
7017 return false;
7018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007019
Douglas Gregor86d142a2009-10-08 07:24:58 +00007020 // Make sure that this is a specialization of a member.
7021 if (!InstantiatedFrom) {
7022 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7023 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007024 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7025 return true;
7026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007027
Douglas Gregor06db9f52009-10-12 20:18:28 +00007028 // C++ [temp.expl.spec]p6:
7029 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00007030 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00007031 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007032 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00007033 // use occurs; no diagnostic is required.
7034 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00007035
Abramo Bagnara8075c852010-06-12 07:44:57 +00007036 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00007037 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7038 TSK_ExplicitSpecialization,
7039 Instantiation,
7040 MSInfo->getTemplateSpecializationKind(),
7041 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007042 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00007043 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007044
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007045 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007046 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00007047 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007048 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00007049 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007050 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00007051
Douglas Gregor86d142a2009-10-08 07:24:58 +00007052 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007053 // the original declaration to note that it is an explicit specialization
7054 // (if it was previously an implicit instantiation). This latter step
7055 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00007056 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007057 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7058 if (InstantiationFunction->getTemplateSpecializationKind() ==
7059 TSK_ImplicitInstantiation) {
7060 InstantiationFunction->setTemplateSpecializationKind(
7061 TSK_ExplicitSpecialization);
7062 InstantiationFunction->setLocation(Member->getLocation());
7063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007064
Douglas Gregor86d142a2009-10-08 07:24:58 +00007065 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7066 cast<CXXMethodDecl>(InstantiatedFrom),
7067 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007068 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007069 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007070 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7071 if (InstantiationVar->getTemplateSpecializationKind() ==
7072 TSK_ImplicitInstantiation) {
7073 InstantiationVar->setTemplateSpecializationKind(
7074 TSK_ExplicitSpecialization);
7075 InstantiationVar->setLocation(Member->getLocation());
7076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007077
Larisse Voufo39a1e502013-08-06 01:03:05 +00007078 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7079 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00007080 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00007081 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007082 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7083 if (InstantiationClass->getTemplateSpecializationKind() ==
7084 TSK_ImplicitInstantiation) {
7085 InstantiationClass->setTemplateSpecializationKind(
7086 TSK_ExplicitSpecialization);
7087 InstantiationClass->setLocation(Member->getLocation());
7088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007089
Douglas Gregor86d142a2009-10-08 07:24:58 +00007090 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007091 cast<CXXRecordDecl>(InstantiatedFrom),
7092 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00007093 } else {
7094 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7095 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7096 if (InstantiationEnum->getTemplateSpecializationKind() ==
7097 TSK_ImplicitInstantiation) {
7098 InstantiationEnum->setTemplateSpecializationKind(
7099 TSK_ExplicitSpecialization);
7100 InstantiationEnum->setLocation(Member->getLocation());
7101 }
7102
7103 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7104 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00007105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007106
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007107 // Save the caller the trouble of having to figure out which declaration
7108 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00007109 Previous.clear();
7110 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00007111 return false;
7112}
7113
Douglas Gregore47f5a72009-10-14 23:41:34 +00007114/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007115///
7116/// \returns true if a serious error occurs, false otherwise.
7117static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00007118 SourceLocation InstLoc,
7119 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007120 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7121 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007122
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007123 if (CurContext->isRecord()) {
7124 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7125 << D;
7126 return true;
7127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128
Richard Smith050d2612011-10-18 02:28:33 +00007129 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007130 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00007131 // template. If the name declared in the explicit instantiation is an
7132 // unqualified name, the explicit instantiation shall appear in the
7133 // namespace where its template is declared or, if that namespace is inline
7134 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007135 //
7136 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00007137 if (WasQualifiedName) {
7138 if (CurContext->Encloses(OrigContext))
7139 return false;
7140 } else {
7141 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7142 return false;
7143 }
7144
7145 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7146 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007147 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007148 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007149 diag::err_explicit_instantiation_out_of_scope :
7150 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007151 << D << NS;
7152 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007153 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007154 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007155 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7156 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7157 << D << NS;
7158 } else
7159 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007160 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00007161 diag::err_explicit_instantiation_must_be_global :
7162 diag::warn_explicit_instantiation_must_be_global_0x)
7163 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007164 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007165 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00007166}
7167
7168/// \brief Determine whether the given scope specifier has a template-id in it.
7169static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7170 if (!SS.isSet())
7171 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007172
Richard Smith050d2612011-10-18 02:28:33 +00007173 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007174 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007175 // or a static data member of a class template specialization, the name of
7176 // the class template specialization in the qualified-id for the member
7177 // name shall be a simple-template-id.
7178 //
7179 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00007180 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7181 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00007182 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00007183 if (isa<TemplateSpecializationType>(T))
7184 return true;
7185
7186 return false;
7187}
7188
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007189// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007190DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007191Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007192 SourceLocation ExternLoc,
7193 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007194 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007195 SourceLocation KWLoc,
7196 const CXXScopeSpec &SS,
7197 TemplateTy TemplateD,
7198 SourceLocation TemplateNameLoc,
7199 SourceLocation LAngleLoc,
7200 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007201 SourceLocation RAngleLoc,
7202 AttributeList *Attr) {
7203 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007204 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007205 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007206 // Check that the specialization uses the same tag kind as the
7207 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007208 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7209 assert(Kind != TTK_Enum &&
7210 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007211
7212 if (isa<TypeAliasTemplateDecl>(TD)) {
7213 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7214 Diag(TD->getTemplatedDecl()->getLocation(),
7215 diag::note_previous_use);
7216 return true;
7217 }
7218
7219 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7220
Douglas Gregord9034f02009-05-14 16:41:31 +00007221 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007222 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00007223 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007224 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007225 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007226 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007227 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007228 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007229 diag::note_previous_use);
7230 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7231 }
7232
Douglas Gregore47f5a72009-10-14 23:41:34 +00007233 // C++0x [temp.explicit]p2:
7234 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007235 // definition and an explicit instantiation declaration. An explicit
7236 // instantiation declaration begins with the extern keyword. [...]
Hans Wennborgfd76d912015-01-15 21:18:30 +00007237 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7238 ? TSK_ExplicitInstantiationDefinition
7239 : TSK_ExplicitInstantiationDeclaration;
7240
7241 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7242 // Check for dllexport class template instantiation declarations.
7243 for (AttributeList *A = Attr; A; A = A->getNext()) {
7244 if (A->getKind() == AttributeList::AT_DLLExport) {
7245 Diag(ExternLoc,
7246 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7247 Diag(A->getLoc(), diag::note_attribute);
7248 break;
7249 }
7250 }
7251
7252 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7253 Diag(ExternLoc,
7254 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7255 Diag(A->getLocation(), diag::note_attribute);
7256 }
7257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007258
Douglas Gregora1f49972009-05-13 00:25:59 +00007259 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007260 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007261 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007262
7263 // Check that the template argument list is well-formed for this
7264 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007265 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007266 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7267 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007268 return true;
7269
Douglas Gregora1f49972009-05-13 00:25:59 +00007270 // Find the class template specialization declaration that
7271 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007272 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007273 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00007274 = ClassTemplate->findSpecialization(Converted, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007275
Abramo Bagnara8075c852010-06-12 07:44:57 +00007276 TemplateSpecializationKind PrevDecl_TSK
7277 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7278
Douglas Gregor54888652009-10-07 00:13:32 +00007279 // C++0x [temp.explicit]p2:
7280 // [...] An explicit instantiation shall appear in an enclosing
7281 // namespace of its template. [...]
7282 //
7283 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007284 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7285 SS.isSet()))
7286 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007287
Craig Topperc3ec1492014-05-26 06:22:03 +00007288 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007289
Abramo Bagnara8075c852010-06-12 07:44:57 +00007290 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007291 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007292 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007293 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007294 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007295 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007296 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007297
Abramo Bagnara8075c852010-06-12 07:44:57 +00007298 // Even though HasNoEffect == true means that this explicit instantiation
7299 // has no effect on semantics, we go on to put its syntax in the AST.
7300
7301 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7302 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007303 // Since the only prior class template specialization with these
7304 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007305 // declaration node as our own, updating the source location
7306 // for the template name to reflect our new declaration.
7307 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007308 Specialization = PrevDecl;
7309 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007310 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007311 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007312 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007313
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007314 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007315 // Create a new class template specialization declaration node for
7316 // this explicit specialization.
7317 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007318 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007319 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007320 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007321 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007322 Converted.data(),
7323 Converted.size(),
7324 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007325 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007326
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007327 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007328 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007329 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007330 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007331 }
7332
7333 // Build the fully-sugared type for this explicit instantiation as
7334 // the user wrote in the explicit instantiation itself. This means
7335 // that we'll pretty-print the type retrieved from the
7336 // specialization's declaration the way that the user actually wrote
7337 // the explicit instantiation, rather than formatting the name based
7338 // on the "canonical" representation used to store the template
7339 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007340 TypeSourceInfo *WrittenTy
7341 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7342 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007343 Context.getTypeDeclType(Specialization));
7344 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007345
Abramo Bagnara8075c852010-06-12 07:44:57 +00007346 // Set source locations for keywords.
7347 Specialization->setExternLoc(ExternLoc);
7348 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007349 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007350
Rafael Espindola0b062072012-01-03 06:04:21 +00007351 if (Attr)
7352 ProcessDeclAttributeList(S, Specialization, Attr);
7353
Abramo Bagnara8075c852010-06-12 07:44:57 +00007354 // Add the explicit instantiation into its lexical context. However,
7355 // since explicit instantiations are never found by name lookup, we
7356 // just put it into the declaration context directly.
7357 Specialization->setLexicalDeclContext(CurContext);
7358 CurContext->addDecl(Specialization);
7359
7360 // Syntax is now OK, so return if it has no other effect on semantics.
7361 if (HasNoEffect) {
7362 // Set the template specialization kind.
7363 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007364 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007365 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007366
7367 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007368 // A definition of a class template or class member template
7369 // shall be in scope at the point of the explicit instantiation of
7370 // the class template or class member template.
7371 //
7372 // This check comes when we actually try to perform the
7373 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007374 ClassTemplateSpecializationDecl *Def
7375 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007376 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007377 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007378 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007379 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007380 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007381 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7382 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007383
Douglas Gregor1d957a32009-10-27 18:42:08 +00007384 // Instantiate the members of this class template specialization.
7385 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007386 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007387 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007388 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7389
7390 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7391 // TSK_ExplicitInstantiationDefinition
7392 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00007393 TSK == TSK_ExplicitInstantiationDefinition) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00007394 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007395 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007396
Hans Wennborgc0875502015-06-09 00:39:05 +00007397 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7398 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7399 // In the MS ABI, an explicit instantiation definition can add a dll
7400 // attribute to a template with a previous instantiation declaration.
7401 // MinGW doesn't allow this.
Hans Wennborg17f9b442015-05-27 00:06:45 +00007402 auto *A = cast<InheritableAttr>(
7403 getDLLAttr(Specialization)->clone(getASTContext()));
7404 A->setInherited(true);
7405 Def->addAttr(A);
7406 checkClassLevelDLLAttribute(Def);
Hans Wennborgfce87ca2015-06-09 00:39:09 +00007407
7408 // Propagate attribute to base class templates.
7409 for (auto &B : Def->bases()) {
7410 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7411 B.getType()->getAsCXXRecordDecl()))
7412 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7413 }
Hans Wennborg17f9b442015-05-27 00:06:45 +00007414 }
7415 }
7416
Douglas Gregor12e49d32009-10-15 22:53:21 +00007417 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007418 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007419
Abramo Bagnara8075c852010-06-12 07:44:57 +00007420 // Set the template specialization kind.
7421 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007422 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007423}
7424
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007425// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007426DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007427Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007428 SourceLocation ExternLoc,
7429 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007430 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007431 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007432 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007433 IdentifierInfo *Name,
7434 SourceLocation NameLoc,
7435 AttributeList *Attr) {
7436
Douglas Gregord6ab8742009-05-28 23:31:59 +00007437 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007438 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007439 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007440 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007441 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007442 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007443 SourceLocation(), false, TypeResult(),
7444 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007445 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7446
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007447 if (!TagD)
7448 return true;
7449
John McCall48871652010-08-21 09:40:31 +00007450 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007451 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007452
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007453 if (Tag->isInvalidDecl())
7454 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007455
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007456 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7457 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7458 if (!Pattern) {
7459 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7460 << Context.getTypeDeclType(Record);
7461 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7462 return true;
7463 }
7464
Douglas Gregore47f5a72009-10-14 23:41:34 +00007465 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007466 // If the explicit instantiation is for a class or member class, the
7467 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007468 // simple-template-id.
7469 //
7470 // C++98 has the same restriction, just worded differently.
7471 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007472 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007473 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474
Douglas Gregore47f5a72009-10-14 23:41:34 +00007475 // C++0x [temp.explicit]p2:
7476 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007477 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007478 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007479 TemplateSpecializationKind TSK
7480 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7481 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007482
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007483 // C++0x [temp.explicit]p2:
7484 // [...] An explicit instantiation shall appear in an enclosing
7485 // namespace of its template. [...]
7486 //
7487 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007488 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007489
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007490 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007491 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007492 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007493 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007494 PrevDecl = Record;
7495 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007496 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007497 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007498 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007499 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007500 PrevDecl,
7501 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007502 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007503 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007504 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007505 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007506 return TagD;
7507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007508
Douglas Gregor12e49d32009-10-15 22:53:21 +00007509 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007510 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007511 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007512 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007513 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007514 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007516 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007517 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007518 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7519 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007520 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7521 << Pattern;
7522 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007523 } else {
7524 if (InstantiateClass(NameLoc, Record, Def,
7525 getTemplateInstantiationArgs(Record),
7526 TSK))
7527 return true;
7528
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007529 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007530 if (!RecordDef)
7531 return true;
7532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007533 }
7534
Douglas Gregor1d957a32009-10-27 18:42:08 +00007535 // Instantiate all of the members of the class.
7536 InstantiateClassMembers(NameLoc, RecordDef,
7537 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007538
Douglas Gregor88d292c2010-05-13 16:44:06 +00007539 if (TSK == TSK_ExplicitInstantiationDefinition)
7540 MarkVTableUsed(NameLoc, RecordDef, true);
7541
Mike Stump87c57ac2009-05-16 07:39:55 +00007542 // FIXME: We don't have any representation for explicit instantiations of
7543 // member classes. Such a representation is not needed for compilation, but it
7544 // should be available for clients that want to see all of the declarations in
7545 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007546 return TagD;
7547}
7548
John McCallfaf5fb42010-08-26 23:41:50 +00007549DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7550 SourceLocation ExternLoc,
7551 SourceLocation TemplateLoc,
7552 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007553 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007554 // TODO: check if/when DNInfo should replace Name.
7555 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7556 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007557 if (!Name) {
7558 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007559 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007560 diag::err_explicit_instantiation_requires_name)
7561 << D.getDeclSpec().getSourceRange()
7562 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007563
Douglas Gregor450f00842009-09-25 18:43:00 +00007564 return true;
7565 }
7566
7567 // The scope passed in may not be a decl scope. Zip up the scope tree until
7568 // we find one that is.
7569 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7570 (S->getFlags() & Scope::TemplateParamScope) != 0)
7571 S = S->getParent();
7572
7573 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007574 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7575 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007576 if (R.isNull())
7577 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007579 // C++ [dcl.stc]p1:
7580 // A storage-class-specifier shall not be specified in [...] an explicit
7581 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007582 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007583 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7584 << Name;
7585 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007586 } else if (D.getDeclSpec().getStorageClassSpec()
7587 != DeclSpec::SCS_unspecified) {
7588 // Complain about then remove the storage class specifier.
7589 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7590 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7591
7592 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007593 }
7594
Douglas Gregor3c74d412009-10-14 20:14:33 +00007595 // C++0x [temp.explicit]p1:
7596 // [...] An explicit instantiation of a function template shall not use the
7597 // inline or constexpr specifiers.
7598 // Presumably, this also applies to member functions of class templates as
7599 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007600 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007601 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007602 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007603 diag::err_explicit_instantiation_inline :
7604 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007605 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007606 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007607 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7608 // not already specified.
7609 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7610 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007611
Douglas Gregore47f5a72009-10-14 23:41:34 +00007612 // C++0x [temp.explicit]p2:
7613 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007614 // definition and an explicit instantiation declaration. An explicit
7615 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007616 TemplateSpecializationKind TSK
7617 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7618 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007619
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007620 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007621 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007622
7623 if (!R->isFunctionType()) {
7624 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007625 // A [...] static data member of a class template can be explicitly
7626 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007627 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007628 // C++1y [temp.explicit]p1:
7629 // A [...] variable [...] template specialization can be explicitly
7630 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007631 if (Previous.isAmbiguous())
7632 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007633
John McCall67c00872009-12-02 08:25:40 +00007634 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007635 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007636
Larisse Voufo39a1e502013-08-06 01:03:05 +00007637 if (!PrevTemplate) {
7638 if (!Prev || !Prev->isStaticDataMember()) {
7639 // We expect to see a data data member here.
7640 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7641 << Name;
7642 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7643 P != PEnd; ++P)
7644 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7645 return true;
7646 }
7647
7648 if (!Prev->getInstantiatedFromStaticDataMember()) {
7649 // FIXME: Check for explicit specialization?
7650 Diag(D.getIdentifierLoc(),
7651 diag::err_explicit_instantiation_data_member_not_instantiated)
7652 << Prev;
7653 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7654 // FIXME: Can we provide a note showing where this was declared?
7655 return true;
7656 }
7657 } else {
7658 // Explicitly instantiate a variable template.
7659
7660 // C++1y [dcl.spec.auto]p6:
7661 // ... A program that uses auto or decltype(auto) in a context not
7662 // explicitly allowed in this section is ill-formed.
7663 //
7664 // This includes auto-typed variable template instantiations.
7665 if (R->isUndeducedType()) {
7666 Diag(T->getTypeLoc().getLocStart(),
7667 diag::err_auto_not_allowed_var_inst);
7668 return true;
7669 }
7670
Richard Smithef985ac2013-09-18 02:10:12 +00007671 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7672 // C++1y [temp.explicit]p3:
7673 // If the explicit instantiation is for a variable, the unqualified-id
7674 // in the declaration shall be a template-id.
7675 Diag(D.getIdentifierLoc(),
7676 diag::err_explicit_instantiation_without_template_id)
7677 << PrevTemplate;
7678 Diag(PrevTemplate->getLocation(),
7679 diag::note_explicit_instantiation_here);
7680 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007681 }
7682
Richard Smithef985ac2013-09-18 02:10:12 +00007683 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007684 TemplateArgumentListInfo TemplateArgs =
7685 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007686
Larisse Voufo39a1e502013-08-06 01:03:05 +00007687 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7688 D.getIdentifierLoc(), TemplateArgs);
7689 if (Res.isInvalid())
7690 return true;
7691
7692 // Ignore access control bits, we don't need them for redeclaration
7693 // checking.
7694 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007696
Douglas Gregore47f5a72009-10-14 23:41:34 +00007697 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007698 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007699 // or a static data member of a class template specialization, the name of
7700 // the class template specialization in the qualified-id for the member
7701 // name shall be a simple-template-id.
7702 //
7703 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007704 //
Richard Smith5977d872013-09-18 21:55:14 +00007705 // This does not apply to variable template specializations, where the
7706 // template-id is in the unqualified-id instead.
7707 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007708 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007709 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007710 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007711
Douglas Gregore47f5a72009-10-14 23:41:34 +00007712 // Check the scope of this explicit instantiation.
7713 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007714
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007715 // Verify that it is okay to explicitly instantiate here.
Richard Smith8809a0c2013-09-27 20:14:12 +00007716 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7717 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007718 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007719 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007720 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007721 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007722
Larisse Voufo39a1e502013-08-06 01:03:05 +00007723 if (!HasNoEffect) {
7724 // Instantiate static data member or variable template.
7725
7726 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7727 if (PrevTemplate) {
7728 // Merge attributes.
7729 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7730 ProcessDeclAttributeList(S, Prev, Attr);
7731 }
7732 if (TSK == TSK_ExplicitInstantiationDefinition)
7733 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7734 }
7735
7736 // Check the new variable specialization against the parsed input.
7737 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7738 Diag(T->getTypeLoc().getLocStart(),
7739 diag::err_invalid_var_template_spec_type)
7740 << 0 << PrevTemplate << R << Prev->getType();
7741 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7742 << 2 << PrevTemplate->getDeclName();
7743 return true;
7744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007745
Douglas Gregor450f00842009-09-25 18:43:00 +00007746 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007747 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007749
7750 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007751 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007752 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007753 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007754 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007755 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007756 HasExplicitTemplateArgs = true;
7757 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007758
Douglas Gregor450f00842009-09-25 18:43:00 +00007759 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007760 // A [...] function [...] can be explicitly instantiated from its template.
7761 // A member function [...] of a class template can be explicitly
7762 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007763 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007764 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007765 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007766 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7767 P != PEnd; ++P) {
7768 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007769 if (!HasExplicitTemplateArgs) {
7770 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007771 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7772 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007773 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007774
John McCall58cc69d2010-01-27 01:50:18 +00007775 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007776 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7777 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007778 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007779 }
7780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007781
Douglas Gregor450f00842009-09-25 18:43:00 +00007782 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7783 if (!FunTmpl)
7784 continue;
7785
Larisse Voufo98b20f12013-07-19 23:00:19 +00007786 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007787 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007788 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007789 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007790 (HasExplicitTemplateArgs ? &TemplateArgs
7791 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007792 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007793 // Keep track of almost-matches.
7794 FailedCandidates.addCandidate()
7795 .set(FunTmpl->getTemplatedDecl(),
7796 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007797 (void)TDK;
7798 continue;
7799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007800
John McCall58cc69d2010-01-27 01:50:18 +00007801 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803
Douglas Gregor450f00842009-09-25 18:43:00 +00007804 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007805 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007806 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007807 D.getIdentifierLoc(),
7808 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7809 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7810 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007811
John McCall58cc69d2010-01-27 01:50:18 +00007812 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007813 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007814
7815 // Ignore access control bits, we don't need them for redeclaration checking.
7816 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007817
Alexey Bataev73983912014-11-06 10:10:50 +00007818 // C++11 [except.spec]p4
7819 // In an explicit instantiation an exception-specification may be specified,
7820 // but is not required.
7821 // If an exception-specification is specified in an explicit instantiation
7822 // directive, it shall be compatible with the exception-specifications of
7823 // other declarations of that function.
7824 if (auto *FPT = R->getAs<FunctionProtoType>())
7825 if (FPT->hasExceptionSpec()) {
7826 unsigned DiagID =
7827 diag::err_mismatched_exception_spec_explicit_instantiation;
7828 if (getLangOpts().MicrosoftExt)
7829 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7830 bool Result = CheckEquivalentExceptionSpec(
7831 PDiag(DiagID) << Specialization->getType(),
7832 PDiag(diag::note_explicit_instantiation_here),
7833 Specialization->getType()->getAs<FunctionProtoType>(),
7834 Specialization->getLocation(), FPT, D.getLocStart());
7835 // In Microsoft mode, mismatching exception specifications just cause a
7836 // warning.
7837 if (!getLangOpts().MicrosoftExt && Result)
7838 return true;
7839 }
7840
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007841 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007842 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007843 diag::err_explicit_instantiation_member_function_not_instantiated)
7844 << Specialization
7845 << (Specialization->getTemplateSpecializationKind() ==
7846 TSK_ExplicitSpecialization);
7847 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7848 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007849 }
7850
Douglas Gregorec9fd132012-01-14 16:38:05 +00007851 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007852 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7853 PrevDecl = Specialization;
7854
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007855 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007856 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007857 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007858 PrevDecl,
7859 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007860 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007861 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007862 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007863
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007864 // FIXME: We may still want to build some representation of this
7865 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007866 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007867 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007868 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007869
7870 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007871 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7872 if (Attr)
7873 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007874
Richard Smitheb36ddf2014-04-24 22:45:46 +00007875 if (Specialization->isDefined()) {
7876 // Let the ASTConsumer know that this function has been explicitly
7877 // instantiated now, and its linkage might have changed.
7878 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7879 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007880 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007881
Douglas Gregore47f5a72009-10-14 23:41:34 +00007882 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007883 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007884 // or a static data member of a class template specialization, the name of
7885 // the class template specialization in the qualified-id for the member
7886 // name shall be a simple-template-id.
7887 //
7888 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007889 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007890 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007891 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007892 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007893 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007894 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007895 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007896
Douglas Gregore47f5a72009-10-14 23:41:34 +00007897 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007898 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007899 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007900 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007901 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902
Douglas Gregor450f00842009-09-25 18:43:00 +00007903 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007904 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007905}
7906
John McCallfaf5fb42010-08-26 23:41:50 +00007907TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007908Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7909 const CXXScopeSpec &SS, IdentifierInfo *Name,
7910 SourceLocation TagLoc, SourceLocation NameLoc) {
7911 // This has to hold, because SS is expected to be defined.
7912 assert(Name && "Expected a name in a dependent tag");
7913
Aaron Ballman4a979672014-01-03 13:56:08 +00007914 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007915 if (!NNS)
7916 return true;
7917
Abramo Bagnara6150c882010-05-11 21:36:43 +00007918 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007919
Douglas Gregorba41d012010-04-24 16:38:41 +00007920 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7921 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007922 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007923 return true;
7924 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007925
Douglas Gregore7c20652011-03-02 00:47:37 +00007926 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007927 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007928 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7929
7930 // Create type-source location information for this type.
7931 TypeLocBuilder TLB;
7932 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007933 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007934 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7935 TL.setNameLoc(NameLoc);
7936 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00007937}
7938
John McCallfaf5fb42010-08-26 23:41:50 +00007939TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007940Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7941 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00007942 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007943 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00007944 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007945
Richard Smith0bf8a4922011-10-18 20:49:44 +00007946 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7947 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007948 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007949 diag::warn_cxx98_compat_typename_outside_of_template :
7950 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007951 << FixItHint::CreateRemoval(TypenameLoc);
7952
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007953 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00007954 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7955 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00007956 if (T.isNull())
7957 return true;
John McCall99b2fe52010-04-29 23:50:39 +00007958
7959 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7960 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00007961 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007962 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007963 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00007964 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007965 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00007966 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007967 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007968 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00007969 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007971
John McCallba7bf592010-08-24 05:47:05 +00007972 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00007973}
7974
John McCallfaf5fb42010-08-26 23:41:50 +00007975TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007976Sema::ActOnTypenameType(Scope *S,
7977 SourceLocation TypenameLoc,
7978 const CXXScopeSpec &SS,
7979 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00007980 TemplateTy TemplateIn,
7981 SourceLocation TemplateNameLoc,
7982 SourceLocation LAngleLoc,
7983 ASTTemplateArgsPtr TemplateArgsIn,
7984 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00007985 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7986 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007987 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007988 diag::warn_cxx98_compat_typename_outside_of_template :
7989 diag::ext_typename_outside_of_template)
7990 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007991
7992 // Translate the parser's template argument list in our AST format.
7993 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7994 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7995
7996 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007997 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7998 // Construct a dependent template specialization type.
7999 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00008000 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008001 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8002 DTN->getQualifier(),
8003 DTN->getIdentifier(),
8004 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008005
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008006 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00008007 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008008 DependentTemplateSpecializationTypeLoc SpecTL
8009 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008010 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8011 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00008012 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008013 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008014 SpecTL.setLAngleLoc(LAngleLoc);
8015 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008016 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8017 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008018 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00008019 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00008020
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008021 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8022 if (T.isNull())
8023 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00008024
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008025 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00008026 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008027 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008028 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00008029 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8030 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008031 SpecTL.setLAngleLoc(LAngleLoc);
8032 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00008033 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8034 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8035
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008036 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8037 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00008038 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008039 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8040
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00008041 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8042 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00008043}
8044
Douglas Gregorb09518c2011-02-27 22:46:49 +00008045
Richard Smith6f8d2c62012-05-09 05:17:00 +00008046/// Determine whether this failed name lookup should be treated as being
8047/// disabled by a usage of std::enable_if.
8048static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8049 SourceRange &CondRange) {
8050 // We must be looking for a ::type...
8051 if (!II.isStr("type"))
8052 return false;
8053
8054 // ... within an explicitly-written template specialization...
8055 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8056 return false;
8057 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00008058 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8059 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8060 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00008061 return false;
8062 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00008063 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00008064
8065 // ... which names a complete class template declaration...
8066 const TemplateDecl *EnableIfDecl =
8067 EnableIfTST->getTemplateName().getAsTemplateDecl();
8068 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8069 return false;
8070
8071 // ... called "enable_if".
8072 const IdentifierInfo *EnableIfII =
8073 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8074 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8075 return false;
8076
8077 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00008078 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008079 return true;
8080}
8081
Douglas Gregor333489b2009-03-27 23:10:48 +00008082/// \brief Build the type that describes a C++ typename specifier,
8083/// e.g., "typename T::type".
8084QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008085Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8086 SourceLocation KeywordLoc,
8087 NestedNameSpecifierLoc QualifierLoc,
8088 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00008089 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00008090 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008091 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00008092
John McCall0b66eb32010-05-01 00:40:08 +00008093 DeclContext *Ctx = computeDeclContext(SS);
8094 if (!Ctx) {
8095 // If the nested-name-specifier is dependent and couldn't be
8096 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008097 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8098 return Context.getDependentNameType(Keyword,
8099 QualifierLoc.getNestedNameSpecifier(),
8100 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008101 }
Douglas Gregor333489b2009-03-27 23:10:48 +00008102
John McCall0b66eb32010-05-01 00:40:08 +00008103 // If the nested-name-specifier refers to the current instantiation,
8104 // the "typename" keyword itself is superfluous. In C++03, the
8105 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8106 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00008107 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00008108
John McCall0b66eb32010-05-01 00:40:08 +00008109 if (RequireCompleteDeclContext(SS, Ctx))
8110 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00008111
8112 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00008113 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
Nikola Smiljanicfce370e2014-12-01 23:15:01 +00008114 LookupQualifiedName(Result, Ctx, SS);
Douglas Gregor333489b2009-03-27 23:10:48 +00008115 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00008116 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008117 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00008118 case LookupResult::NotFound: {
8119 // If we're looking up 'type' within a template named 'enable_if', produce
8120 // a more specific diagnostic.
8121 SourceRange CondRange;
8122 if (isEnableIf(QualifierLoc, II, CondRange)) {
8123 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8124 << Ctx << CondRange;
8125 return QualType();
8126 }
8127
Douglas Gregore40876a2009-10-13 21:16:44 +00008128 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00008129 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008130 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008131
8132 case LookupResult::FoundUnresolvedValue: {
8133 // We found a using declaration that is a value. Most likely, the using
8134 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008135 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008136 IILoc);
8137 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8138 << Name << Ctx << FullRange;
8139 if (UnresolvedUsingValueDecl *Using
8140 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008141 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00008142 Diag(Loc, diag::note_using_value_decl_missing_typename)
8143 << FixItHint::CreateInsertion(Loc, "typename ");
8144 }
8145 }
8146 // Fall through to create a dependent typename type, from which we can recover
8147 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008148
Douglas Gregord0d2ee02010-01-15 01:44:47 +00008149 case LookupResult::NotFoundInCurrentInstantiation:
8150 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008151 return Context.getDependentNameType(Keyword,
8152 QualifierLoc.getNestedNameSpecifier(),
8153 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00008154
8155 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008156 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00008157 // We found a type. Build an ElaboratedType, since the
8158 // typename-specifier was just sugar.
Nico Weber72889432014-09-06 01:25:55 +00008159 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008160 return Context.getElaboratedType(ETK_Typename,
8161 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00008162 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00008163 }
8164
8165 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00008166 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00008167 break;
8168
8169 case LookupResult::FoundOverloaded:
8170 DiagID = diag::err_typename_nested_not_type;
8171 Referenced = *Result.begin();
8172 break;
8173
John McCall6538c932009-10-10 05:48:19 +00008174 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00008175 return QualType();
8176 }
8177
8178 // If we get here, it's because name lookup did not find a
8179 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008180 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00008181 IILoc);
8182 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00008183 if (Referenced)
8184 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8185 << Name;
8186 return QualType();
8187}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008188
8189namespace {
8190 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00008191 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00008192 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00008193 SourceLocation Loc;
8194 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00008195
Douglas Gregor15acfb92009-08-06 16:20:37 +00008196 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00008197 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008198
Mike Stump11289f42009-09-09 15:08:12 +00008199 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008200 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00008201 DeclarationName Entity)
8202 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00008203 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00008204
8205 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00008206 /// transformed.
8207 ///
8208 /// For the purposes of type reconstruction, a type has already been
8209 /// transformed if it is NULL or if it is not dependent.
8210 bool AlreadyTransformed(QualType T) {
8211 return T.isNull() || !T->isDependentType();
8212 }
Mike Stump11289f42009-09-09 15:08:12 +00008213
8214 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00008215 /// rebuilt.
8216 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00008217
Douglas Gregor15acfb92009-08-06 16:20:37 +00008218 /// \brief Returns the name of the entity whose type is being rebuilt.
8219 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00008220
Douglas Gregoref6ab412009-10-27 06:26:26 +00008221 /// \brief Sets the "base" location and entity when that
8222 /// information is known based on another transformation.
8223 void setBase(SourceLocation Loc, DeclarationName Entity) {
8224 this->Loc = Loc;
8225 this->Entity = Entity;
8226 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00008227
8228 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8229 // Lambdas never need to be transformed.
8230 return E;
8231 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00008232 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008233}
Douglas Gregor15acfb92009-08-06 16:20:37 +00008234
Douglas Gregor15acfb92009-08-06 16:20:37 +00008235/// \brief Rebuilds a type within the context of the current instantiation.
8236///
Mike Stump11289f42009-09-09 15:08:12 +00008237/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00008238/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00008239/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00008240/// partial specialization thereof). This routine will rebuild that type now
8241/// that we have entered the declarator's scope, which may produce different
8242/// canonical types, e.g.,
8243///
8244/// \code
8245/// template<typename T>
8246/// struct X {
8247/// typedef T* pointer;
8248/// pointer data();
8249/// };
8250///
8251/// template<typename T>
8252/// typename X<T>::pointer X<T>::data() { ... }
8253/// \endcode
8254///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008255/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008256/// since we do not know that we can look into X<T> when we parsed the type.
8257/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008258/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008259/// as the canonical type of T*, allowing the return types of the out-of-line
8260/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008261TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8262 SourceLocation Loc,
8263 DeclarationName Name) {
8264 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008265 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008266
Douglas Gregor15acfb92009-08-06 16:20:37 +00008267 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8268 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008269}
Douglas Gregorbe999392009-09-15 16:23:51 +00008270
John McCalldadc5752010-08-24 06:29:42 +00008271ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008272 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8273 DeclarationName());
8274 return Rebuilder.TransformExpr(E);
8275}
8276
John McCall99b2fe52010-04-29 23:50:39 +00008277bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008278 if (SS.isInvalid())
8279 return true;
John McCall2408e322010-04-27 00:57:59 +00008280
Douglas Gregor10176412011-02-25 16:07:42 +00008281 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008282 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8283 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008284 NestedNameSpecifierLoc Rebuilt
8285 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8286 if (!Rebuilt)
8287 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008288
Douglas Gregor10176412011-02-25 16:07:42 +00008289 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008290 return false;
John McCall2408e322010-04-27 00:57:59 +00008291}
8292
Douglas Gregor041b0842011-10-14 15:31:12 +00008293/// \brief Rebuild the template parameters now that we know we're in a current
8294/// instantiation.
8295bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8296 TemplateParameterList *Params) {
8297 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8298 Decl *Param = Params->getParam(I);
8299
8300 // There is nothing to rebuild in a type parameter.
8301 if (isa<TemplateTypeParmDecl>(Param))
8302 continue;
8303
8304 // Rebuild the template parameter list of a template template parameter.
8305 if (TemplateTemplateParmDecl *TTP
8306 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8307 if (RebuildTemplateParamsInCurrentInstantiation(
8308 TTP->getTemplateParameters()))
8309 return true;
8310
8311 continue;
8312 }
8313
8314 // Rebuild the type of a non-type template parameter.
8315 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8316 TypeSourceInfo *NewTSI
8317 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8318 NTTP->getLocation(),
8319 NTTP->getDeclName());
8320 if (!NewTSI)
8321 return true;
8322
8323 if (NewTSI != NTTP->getTypeSourceInfo()) {
8324 NTTP->setTypeSourceInfo(NewTSI);
8325 NTTP->setType(NewTSI->getType());
8326 }
8327 }
8328
8329 return false;
8330}
8331
Douglas Gregorbe999392009-09-15 16:23:51 +00008332/// \brief Produces a formatted string that describes the binding of
8333/// template parameters to template arguments.
8334std::string
8335Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8336 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008337 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008338}
8339
8340std::string
8341Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8342 const TemplateArgument *Args,
8343 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008344 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008345 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008346
Douglas Gregore62e6a02009-11-11 19:13:48 +00008347 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008348 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008349
Douglas Gregorbe999392009-09-15 16:23:51 +00008350 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008351 if (I >= NumArgs)
8352 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008353
Douglas Gregorbe999392009-09-15 16:23:51 +00008354 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008355 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008356 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008357 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008358
Douglas Gregorbe999392009-09-15 16:23:51 +00008359 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008360 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008361 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008362 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008364
Douglas Gregor0192c232010-12-20 16:52:59 +00008365 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008366 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008367 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008368
8369 Out << ']';
8370 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008371}
Francois Pichet1c229c02011-04-22 22:18:13 +00008372
Richard Smithe40f2ba2013-08-07 21:41:30 +00008373void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8374 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008375 if (!FD)
8376 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008377
8378 LateParsedTemplate *LPT = new LateParsedTemplate;
8379
8380 // Take tokens to avoid allocations
8381 LPT->Toks.swap(Toks);
8382 LPT->D = FnD;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00008383 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008384
8385 FD->setLateTemplateParsed(true);
8386}
8387
8388void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8389 if (!FD)
8390 return;
8391 FD->setLateTemplateParsed(false);
8392}
Francois Pichet1c229c02011-04-22 22:18:13 +00008393
8394bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8395 DeclContext *DC = CurContext;
8396
8397 while (DC) {
8398 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8399 const FunctionDecl *FD = RD->isLocalClass();
8400 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8401 } else if (DC->isTranslationUnit() || DC->isNamespace())
8402 return false;
8403
8404 DC = DC->getParent();
8405 }
8406 return false;
8407}