blob: 272c8117834d1fa086dbe336db8320b841c5fe3b [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))
110 if (!ClassTemplates.insert(ClassTmpl)) {
111 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
321 CorrectionCandidateCallback FilterCCC;
322 FilterCCC.WantTypeSpecifiers = false;
323 FilterCCC.WantExpressionKeywords = false;
324 FilterCCC.WantRemainingKeywords = false;
325 FilterCCC.WantCXXNamedCasts = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000326 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
327 Found.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +0000328 FilterCCC, CTK_ErrorRecovery,
329 LookupCtx)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000330 Found.setLookupName(Corrected.getCorrection());
331 if (Corrected.getCorrectionDecl())
332 Found.addDecl(Corrected.getCorrectionDecl());
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000333 FilterAcceptableTemplateNames(Found);
John McCalle9cccd82010-06-16 08:42:20 +0000334 if (!Found.empty()) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000335 if (LookupCtx) {
Richard Smithf9b15102013-08-17 00:46:16 +0000336 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
337 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000338 Name.getAsString() == CorrectedStr;
Richard Smithf9b15102013-08-17 00:46:16 +0000339 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
340 << Name << LookupCtx << DroppedSpecifier
341 << SS.getRange());
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000342 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000343 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
Kaelyn Uhrain10413a42013-07-02 23:47:44 +0000344 }
John McCalle9cccd82010-06-16 08:42:20 +0000345 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000346 } else {
Douglas Gregorc048c522010-06-29 19:27:42 +0000347 Found.setLookupName(Name);
Douglas Gregorff18cc12009-12-31 08:11:17 +0000348 }
349 }
350
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000351 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000352 if (Found.empty()) {
353 if (isDependent)
354 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000355 return;
Douglas Gregorfc6c3e72010-07-16 16:54:17 +0000356 }
John McCalle66edc12009-11-24 19:00:30 +0000357
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000358 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
Richard Smithe7d67f22013-09-03 21:22:41 +0000359 !getLangOpts().CPlusPlus11) {
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000360 // C++03 [basic.lookup.classref]p1:
John McCalle66edc12009-11-24 19:00:30 +0000361 // [...] If the lookup in the class of the object expression finds a
362 // template, the name is also looked up in the context of the entire
363 // postfix-expression and [...]
364 //
Douglas Gregor1b02e4a2012-05-01 20:23:02 +0000365 // Note: C++11 does not perform this second lookup.
John McCalle66edc12009-11-24 19:00:30 +0000366 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
367 LookupOrdinaryName);
368 LookupName(FoundOuter, S);
Douglas Gregor50a3cdd2012-03-10 23:52:41 +0000369 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000370
John McCalle66edc12009-11-24 19:00:30 +0000371 if (FoundOuter.empty()) {
372 // - if the name is not found, the name found in the class of the
373 // object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000374 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
375 FoundOuter.isAmbiguous()) {
John McCalle66edc12009-11-24 19:00:30 +0000376 // - if the name is found in the context of the entire
377 // postfix-expression and does not name a class template, the name
378 // found in the class of the object expression is used, otherwise
Douglas Gregorde0a43f2011-08-10 21:59:45 +0000379 FoundOuter.clear();
John McCalle9cccd82010-06-16 08:42:20 +0000380 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000381 // - if the name found is a class template, it must refer to the same
382 // entity as the one found in the class of the object expression,
383 // otherwise the program is ill-formed.
384 if (!Found.isSingleResult() ||
385 Found.getFoundDecl()->getCanonicalDecl()
386 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000388 diag::ext_nested_name_member_ref_lookup_ambiguous)
389 << Found.getLookupName()
390 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000391 Diag(Found.getRepresentativeDecl()->getLocation(),
392 diag::note_ambig_member_ref_object_type)
393 << ObjectType;
394 Diag(FoundOuter.getFoundDecl()->getLocation(),
395 diag::note_ambig_member_ref_scope);
396
397 // Recover by taking the template that we found in the object
398 // expression's type.
399 }
400 }
401 }
402}
403
John McCallcd4b4772009-12-02 03:53:29 +0000404/// ActOnDependentIdExpression - Handle a dependent id-expression that
405/// was just parsed. This is only possible with an explicit scope
406/// specifier naming a dependent type.
John McCalldadc5752010-08-24 06:29:42 +0000407ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000408Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000409 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000410 const DeclarationNameInfo &NameInfo,
John McCallcd4b4772009-12-02 03:53:29 +0000411 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000412 const TemplateArgumentListInfo *TemplateArgs) {
John McCall87fe5d52010-05-20 01:18:31 +0000413 DeclContext *DC = getFunctionLevelDeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000414
John McCallcd4b4772009-12-02 03:53:29 +0000415 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000416 isa<CXXMethodDecl>(DC) &&
417 cast<CXXMethodDecl>(DC)->isInstance()) {
418 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419
John McCalle66edc12009-11-24 19:00:30 +0000420 // Since the 'this' expression is synthesized, we don't need to
421 // perform the double-lookup check.
Craig Topperc3ec1492014-05-26 06:22:03 +0000422 NamedDecl *FirstQualifierInScope = nullptr;
John McCalle66edc12009-11-24 19:00:30 +0000423
John McCall2d74de92009-12-01 22:10:20 +0000424 return Owned(CXXDependentScopeMemberExpr::Create(Context,
Craig Topperc3ec1492014-05-26 06:22:03 +0000425 /*This*/ nullptr, ThisType,
John McCall2d74de92009-12-01 22:10:20 +0000426 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000427 /*Op*/ SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +0000428 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000429 TemplateKWLoc,
John McCalle66edc12009-11-24 19:00:30 +0000430 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000431 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000432 TemplateArgs));
433 }
434
Abramo Bagnara7945c982012-01-27 09:46:47 +0000435 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +0000436}
437
John McCalldadc5752010-08-24 06:29:42 +0000438ExprResult
John McCalle66edc12009-11-24 19:00:30 +0000439Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000440 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000441 const DeclarationNameInfo &NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000442 const TemplateArgumentListInfo *TemplateArgs) {
443 return Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor3a43fd62011-02-25 20:49:16 +0000444 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000445 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000446 NameInfo,
John McCalle66edc12009-11-24 19:00:30 +0000447 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000448}
449
Douglas Gregor5101c242008-12-05 18:15:24 +0000450/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
451/// that the template parameter 'PrevDecl' is being shadowed by a new
452/// declaration at location Loc. Returns true to indicate that this is
453/// an error, and false otherwise.
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000454void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000455 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000456
457 // Microsoft Visual C++ permits template parameters to be shadowed.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000458 if (getLangOpts().MicrosoftExt)
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000459 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000460
461 // C++ [temp.local]p4:
462 // A template-parameter shall not be redeclared within its
463 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000464 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000465 << cast<NamedDecl>(PrevDecl)->getDeclName();
466 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +0000467 return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000468}
469
Douglas Gregor463421d2009-03-03 04:44:36 +0000470/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000471/// the parameter D to reference the templated declaration and return a pointer
472/// to the template declaration. Otherwise, do nothing to D and return null.
John McCall48871652010-08-21 09:40:31 +0000473TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
474 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
475 D = Temp->getTemplatedDecl();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000476 return Temp;
477 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000478 return nullptr;
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000479}
480
Douglas Gregoreb29d182011-01-05 17:40:24 +0000481ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
482 SourceLocation EllipsisLoc) const {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000483 assert(Kind == Template &&
Douglas Gregoreb29d182011-01-05 17:40:24 +0000484 "Only template template arguments can be pack expansions here");
485 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
486 "Template template argument pack expansion without packs");
487 ParsedTemplateArgument Result(*this);
488 Result.EllipsisLoc = EllipsisLoc;
489 return Result;
490}
491
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000492static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
493 const ParsedTemplateArgument &Arg) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000494
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000495 switch (Arg.getKind()) {
496 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000497 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000498 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000500 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000501 return TemplateArgumentLoc(TemplateArgument(T), DI);
502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000503
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000504 case ParsedTemplateArgument::NonType: {
505 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
506 return TemplateArgumentLoc(TemplateArgument(E), E);
507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000509 case ParsedTemplateArgument::Template: {
John McCall3e56fd42010-08-23 07:28:44 +0000510 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregore1d60df2011-01-14 23:41:42 +0000511 TemplateArgument TArg;
512 if (Arg.getEllipsisLoc().isValid())
David Blaikie05785d12013-02-20 22:23:23 +0000513 TArg = TemplateArgument(Template, Optional<unsigned int>());
Douglas Gregore1d60df2011-01-14 23:41:42 +0000514 else
515 TArg = Template;
516 return TemplateArgumentLoc(TArg,
Douglas Gregor9d802122011-03-02 17:09:35 +0000517 Arg.getScopeSpec().getWithLocInContext(
518 SemaRef.Context),
Douglas Gregoreb29d182011-01-05 17:40:24 +0000519 Arg.getLocation(),
520 Arg.getEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000521 }
522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000523
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000524 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000525}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000527/// \brief Translates template arguments as provided by the parser
528/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000529void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
530 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000531 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000532 TemplateArgs.addArgument(translateTemplateArgument(*this,
533 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000534}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535
Richard Smithb80d5402013-06-25 22:21:36 +0000536static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
537 SourceLocation Loc,
538 IdentifierInfo *Name) {
539 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
540 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
541 if (PrevDecl && PrevDecl->isTemplateParameter())
542 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
543}
544
Douglas Gregor5101c242008-12-05 18:15:24 +0000545/// ActOnTypeParameter - Called when a C++ template type parameter
546/// (e.g., "typename T") has been parsed. Typename specifies whether
547/// the keyword "typename" was used to declare the type parameter
548/// (otherwise, "class" was used), and KeyLoc is the location of the
549/// "class" or "typename" keyword. ParamName is the name of the
550/// parameter (NULL indicates an unnamed template parameter) and
Chandler Carruth08836322011-05-01 00:51:33 +0000551/// ParamNameLoc is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000552/// If the type parameter has a default argument, it will be added
553/// later via ActOnTypeParameterDefault.
John McCall48871652010-08-21 09:40:31 +0000554Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
555 SourceLocation EllipsisLoc,
556 SourceLocation KeyLoc,
557 IdentifierInfo *ParamName,
558 SourceLocation ParamNameLoc,
559 unsigned Depth, unsigned Position,
560 SourceLocation EqualLoc,
John McCallba7bf592010-08-24 05:47:05 +0000561 ParsedType DefaultArg) {
Mike Stump11289f42009-09-09 15:08:12 +0000562 assert(S->isTemplateParamScope() &&
563 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000564 bool Invalid = false;
565
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000566 SourceLocation Loc = ParamNameLoc;
567 if (!ParamName)
568 Loc = KeyLoc;
569
Douglas Gregor5101c242008-12-05 18:15:24 +0000570 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000571 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000572 KeyLoc, Loc, Depth, Position, ParamName,
573 Typename, Ellipsis);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000574 Param->setAccess(AS_public);
Douglas Gregor5101c242008-12-05 18:15:24 +0000575 if (Invalid)
576 Param->setInvalidDecl();
577
578 if (ParamName) {
Richard Smithb80d5402013-06-25 22:21:36 +0000579 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
580
Douglas Gregor5101c242008-12-05 18:15:24 +0000581 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000582 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000583 IdResolver.AddDecl(Param);
584 }
585
Douglas Gregorf5500772011-01-05 15:48:55 +0000586 // C++0x [temp.param]p9:
587 // A default template-argument may be specified for any kind of
588 // template-parameter that is not a template parameter pack.
589 if (DefaultArg && Ellipsis) {
590 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
591 DefaultArg = ParsedType();
592 }
593
Douglas Gregordc13ded2010-07-01 00:00:45 +0000594 // Handle the default argument, if provided.
595 if (DefaultArg) {
596 TypeSourceInfo *DefaultTInfo;
597 GetTypeFromParser(DefaultArg, &DefaultTInfo);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000598
Douglas Gregordc13ded2010-07-01 00:00:45 +0000599 assert(DefaultTInfo && "expected source information for type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000601 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000602 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000603 UPPC_DefaultArgument))
604 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregordc13ded2010-07-01 00:00:45 +0000606 // Check the template argument itself.
607 if (CheckTemplateArgument(Param, DefaultTInfo)) {
608 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000609 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611
Douglas Gregordc13ded2010-07-01 00:00:45 +0000612 Param->setDefaultArgument(DefaultTInfo, false);
613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000614
John McCall48871652010-08-21 09:40:31 +0000615 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000616}
617
Douglas Gregor463421d2009-03-03 04:44:36 +0000618/// \brief Check that the type of a non-type template parameter is
619/// well-formed.
620///
621/// \returns the (possibly-promoted) parameter type if valid;
622/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000623QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000624Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000625 // We don't allow variably-modified types as the type of non-type template
626 // parameters.
627 if (T->isVariablyModifiedType()) {
628 Diag(Loc, diag::err_variably_modified_nontype_template_param)
629 << T;
630 return QualType();
631 }
632
Douglas Gregor463421d2009-03-03 04:44:36 +0000633 // C++ [temp.param]p4:
634 //
635 // A non-type template-parameter shall have one of the following
636 // (optionally cv-qualified) types:
637 //
638 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000639 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000640 // -- pointer to object or pointer to function,
Eli Friedmana170cd62010-08-05 02:49:48 +0000641 T->isPointerType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000642 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000643 T->isReferenceType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000644 // -- pointer to member,
Douglas Gregor463421d2009-03-03 04:44:36 +0000645 T->isMemberPointerType() ||
Douglas Gregor80af3132011-05-21 23:15:46 +0000646 // -- std::nullptr_t.
647 T->isNullPtrType() ||
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 // If T is a dependent type, we can't do the check now, so we
649 // assume that it is well-formed.
Richard Smithd0e1c952012-03-13 07:21:50 +0000650 T->isDependentType()) {
651 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
652 // are ignored when determining its type.
653 return T.getUnqualifiedType();
654 }
655
Douglas Gregor463421d2009-03-03 04:44:36 +0000656 // C++ [temp.param]p8:
657 //
658 // A non-type template-parameter of type "array of T" or
659 // "function returning T" is adjusted to be of type "pointer to
660 // T" or "pointer to function returning T", respectively.
661 else if (T->isArrayType())
662 // FIXME: Keep the type prior to promotion?
663 return Context.getArrayDecayedType(T);
664 else if (T->isFunctionType())
665 // FIXME: Keep the type prior to promotion?
666 return Context.getPointerType(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000667
Douglas Gregor463421d2009-03-03 04:44:36 +0000668 Diag(Loc, diag::err_template_nontype_parm_bad_type)
669 << T;
670
671 return QualType();
672}
673
John McCall48871652010-08-21 09:40:31 +0000674Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
675 unsigned Depth,
676 unsigned Position,
677 SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000678 Expr *Default) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
680 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000681
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000682 assert(S->isTemplateParamScope() &&
683 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000684 bool Invalid = false;
685
Douglas Gregor38ee75e2010-12-16 15:36:43 +0000686 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
687 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000688 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000689 Invalid = true;
690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000691
Richard Smithb80d5402013-06-25 22:21:36 +0000692 IdentifierInfo *ParamName = D.getIdentifier();
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000693 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor5101c242008-12-05 18:15:24 +0000694 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000695 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000696 D.getLocStart(),
John McCallf7b2fb52010-01-22 00:28:27 +0000697 D.getIdentifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698 Depth, Position, ParamName, T,
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000699 IsParameterPack, TInfo);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000700 Param->setAccess(AS_public);
Richard Smithb80d5402013-06-25 22:21:36 +0000701
Douglas Gregor5101c242008-12-05 18:15:24 +0000702 if (Invalid)
703 Param->setInvalidDecl();
704
Richard Smithb80d5402013-06-25 22:21:36 +0000705 if (ParamName) {
706 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
707 ParamName);
708
Douglas Gregor5101c242008-12-05 18:15:24 +0000709 // Add the template parameter into the current scope.
John McCall48871652010-08-21 09:40:31 +0000710 S->AddDecl(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000711 IdResolver.AddDecl(Param);
712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713
Douglas Gregorf5500772011-01-05 15:48:55 +0000714 // C++0x [temp.param]p9:
715 // A default template-argument may be specified for any kind of
716 // template-parameter that is not a template parameter pack.
717 if (Default && IsParameterPack) {
718 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
Craig Topperc3ec1492014-05-26 06:22:03 +0000719 Default = nullptr;
Douglas Gregorf5500772011-01-05 15:48:55 +0000720 }
721
Douglas Gregordc13ded2010-07-01 00:00:45 +0000722 // Check the well-formedness of the default template argument, if provided.
Douglas Gregorda3cc0d2010-12-23 23:51:58 +0000723 if (Default) {
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000724 // Check for unexpanded parameter packs.
725 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
726 return Param;
727
Douglas Gregordc13ded2010-07-01 00:00:45 +0000728 TemplateArgument Converted;
John Wiegley01296292011-04-08 18:41:53 +0000729 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
730 if (DefaultRes.isInvalid()) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000731 Param->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +0000732 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000733 }
John Wiegley01296292011-04-08 18:41:53 +0000734 Default = DefaultRes.take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000735
John McCallb268a282010-08-23 23:25:46 +0000736 Param->setDefaultArgument(Default, false);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000738
John McCall48871652010-08-21 09:40:31 +0000739 return Param;
Douglas Gregor5101c242008-12-05 18:15:24 +0000740}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000741
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000742/// ActOnTemplateTemplateParameter - Called when a C++ template template
James Dennett2a4d13c2012-06-15 07:13:21 +0000743/// parameter (e.g. T in template <template \<typename> class T> class array)
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000744/// has been parsed. S is the current scope.
John McCall48871652010-08-21 09:40:31 +0000745Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
746 SourceLocation TmpLoc,
Richard Trieu9becef62011-09-09 03:18:59 +0000747 TemplateParameterList *Params,
Douglas Gregorf5500772011-01-05 15:48:55 +0000748 SourceLocation EllipsisLoc,
John McCall48871652010-08-21 09:40:31 +0000749 IdentifierInfo *Name,
750 SourceLocation NameLoc,
751 unsigned Depth,
752 unsigned Position,
753 SourceLocation EqualLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000754 ParsedTemplateArgument Default) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000755 assert(S->isTemplateParamScope() &&
756 "Template template parameter not in template parameter scope!");
757
758 // Construct the parameter object.
Douglas Gregorf5500772011-01-05 15:48:55 +0000759 bool IsParameterPack = EllipsisLoc.isValid();
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000760 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000761 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762 NameLoc.isInvalid()? TmpLoc : NameLoc,
763 Depth, Position, IsParameterPack,
Douglas Gregorf5500772011-01-05 15:48:55 +0000764 Name, Params);
Douglas Gregorfd7c2252011-03-04 17:52:15 +0000765 Param->setAccess(AS_public);
766
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000767 // If the template template parameter has a name, then link the identifier
Douglas Gregordc13ded2010-07-01 00:00:45 +0000768 // into the scope and lookup mechanisms.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000769 if (Name) {
Richard Smithb80d5402013-06-25 22:21:36 +0000770 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
771
John McCall48871652010-08-21 09:40:31 +0000772 S->AddDecl(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000773 IdResolver.AddDecl(Param);
774 }
775
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000776 if (Params->size() == 0) {
777 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
778 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
779 Param->setInvalidDecl();
780 }
781
Douglas Gregorf5500772011-01-05 15:48:55 +0000782 // C++0x [temp.param]p9:
783 // A default template-argument may be specified for any kind of
784 // template-parameter that is not a template parameter pack.
785 if (IsParameterPack && !Default.isInvalid()) {
786 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
787 Default = ParsedTemplateArgument();
788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789
Douglas Gregordc13ded2010-07-01 00:00:45 +0000790 if (!Default.isInvalid()) {
791 // Check only that we have a template template argument. We don't want to
792 // try to check well-formedness now, because our template template parameter
793 // might have dependent types in its template parameters, which we wouldn't
794 // be able to match now.
795 //
796 // If none of the template template parameter's template arguments mention
797 // other template parameters, we could actually perform more checking here.
798 // However, it isn't worth doing.
799 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
800 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
801 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
802 << DefaultArg.getSourceRange();
John McCall48871652010-08-21 09:40:31 +0000803 return Param;
Douglas Gregordc13ded2010-07-01 00:00:45 +0000804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000806 // Check for unexpanded parameter packs.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000808 DefaultArg.getArgument().getAsTemplate(),
809 UPPC_DefaultArgument))
810 return Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
Douglas Gregordc13ded2010-07-01 00:00:45 +0000812 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
John McCall48871652010-08-21 09:40:31 +0000815 return Param;
Douglas Gregordba32632009-02-10 19:49:53 +0000816}
817
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000818/// ActOnTemplateParameterList - Builds a TemplateParameterList that
819/// contains the template parameters in Params/NumParams.
Richard Trieu9becef62011-09-09 03:18:59 +0000820TemplateParameterList *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000821Sema::ActOnTemplateParameterList(unsigned Depth,
822 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000823 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000824 SourceLocation LAngleLoc,
John McCall48871652010-08-21 09:40:31 +0000825 Decl **Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000826 SourceLocation RAngleLoc) {
827 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000828 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000829
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000830 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831 (NamedDecl**)Params, NumParams,
Douglas Gregorbe999392009-09-15 16:23:51 +0000832 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000833}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000834
John McCall3e11ebe2010-03-15 10:12:16 +0000835static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
836 if (SS.isSet())
Douglas Gregor14454802011-02-25 02:25:35 +0000837 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +0000838}
839
John McCallfaf5fb42010-08-26 23:41:50 +0000840DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000841Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000842 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000843 IdentifierInfo *Name, SourceLocation NameLoc,
844 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000845 TemplateParameterList *TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +0000846 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +0000847 unsigned NumOuterTemplateParamLists,
848 TemplateParameterList** OuterTemplateParamLists) {
Mike Stump11289f42009-09-09 15:08:12 +0000849 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000850 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000851 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000852 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000853
854 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000855 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857
Abramo Bagnara6150c882010-05-11 21:36:43 +0000858 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
859 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000860
861 // There is no such thing as an unnamed class template.
862 if (!Name) {
863 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000864 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000865 }
866
Richard Smith6483d222012-04-21 01:27:54 +0000867 // Find any previous declaration with this name. For a friend with no
868 // scope explicitly specified, we only look for tag declarations (per
869 // C++11 [basic.lookup.elab]p2).
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000870 DeclContext *SemanticContext;
Richard Smith6483d222012-04-21 01:27:54 +0000871 LookupResult Previous(*this, Name, NameLoc,
872 (SS.isEmpty() && TUK == TUK_Friend)
873 ? LookupTagName : LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000874 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000875 if (SS.isNotEmpty() && !SS.isInvalid()) {
876 SemanticContext = computeDeclContext(SS, true);
877 if (!SemanticContext) {
Douglas Gregor67daacb2012-03-30 16:20:47 +0000878 // FIXME: Horrible, horrible hack! We can't currently represent this
879 // in the AST, and historically we have just ignored such friend
880 // class templates, so don't complain here.
Richard Smithcd556eb2013-11-08 18:59:56 +0000881 Diag(NameLoc, TUK == TUK_Friend
882 ? diag::warn_template_qualified_friend_ignored
883 : diag::err_template_qualified_declarator_no_match)
Douglas Gregor67daacb2012-03-30 16:20:47 +0000884 << SS.getScopeRep() << SS.getRange();
Richard Smithcd556eb2013-11-08 18:59:56 +0000885 return TUK != TUK_Friend;
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000886 }
Mike Stump11289f42009-09-09 15:08:12 +0000887
John McCall0b66eb32010-05-01 00:40:08 +0000888 if (RequireCompleteDeclContext(SS, SemanticContext))
889 return true;
890
Douglas Gregor041b0842011-10-14 15:31:12 +0000891 // If we're adding a template to a dependent context, we may need to
892 // rebuilding some of the types used within the template parameter list,
893 // now that we know what the current instantiation is.
894 if (SemanticContext->isDependentContext()) {
895 ContextRAII SavedContext(*this, SemanticContext);
896 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
897 Invalid = true;
Douglas Gregorb7d17dd2012-03-28 16:01:27 +0000898 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
899 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
Richard Smith6483d222012-04-21 01:27:54 +0000900
John McCall27b18f82009-11-17 02:14:36 +0000901 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000902 } else {
903 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000904 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000905 }
Mike Stump11289f42009-09-09 15:08:12 +0000906
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000907 if (Previous.isAmbiguous())
908 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909
Craig Topperc3ec1492014-05-26 06:22:03 +0000910 NamedDecl *PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000911 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000912 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000913
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000914 // If there is a previous declaration with the same name, check
915 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000916 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000917 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000918
919 // We may have found the injected-class-name of a class template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920 // class template partial specialization, or class template specialization.
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000921 // In these cases, grab the template that is being defined or specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000922 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000923 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
924 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000925 PrevClassTemplate
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000926 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
927 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
928 PrevClassTemplate
929 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
930 ->getSpecializedTemplate();
931 }
932 }
933
John McCalld43784f2009-12-18 11:25:59 +0000934 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000935 // C++ [namespace.memdef]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000936 // [...] When looking for a prior declaration of a class or a function
937 // declared as a friend, and when the name of the friend class or
John McCall90d3bb92009-12-17 23:21:11 +0000938 // function is neither a qualified name nor a template-id, scopes outside
939 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000940 if (!SS.isSet()) {
941 DeclContext *OutermostContext = CurContext;
942 while (!OutermostContext->isFileContext())
943 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000944
Richard Smith61e582f2012-04-20 07:12:26 +0000945 if (PrevDecl &&
Douglas Gregorb74b1032010-04-18 17:37:40 +0000946 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
947 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
948 SemanticContext = PrevDecl->getDeclContext();
949 } else {
950 // Declarations in outer scopes don't matter. However, the outermost
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000951 // context we computed is the semantic context for our new
Douglas Gregorb74b1032010-04-18 17:37:40 +0000952 // declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +0000953 PrevDecl = PrevClassTemplate = nullptr;
Douglas Gregorb74b1032010-04-18 17:37:40 +0000954 SemanticContext = OutermostContext;
Richard Smith6483d222012-04-21 01:27:54 +0000955
956 // Check that the chosen semantic context doesn't already contain a
957 // declaration of this name as a non-tag type.
958 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
959 ForRedeclaration);
960 DeclContext *LookupContext = SemanticContext;
961 while (LookupContext->isTransparentContext())
962 LookupContext = LookupContext->getLookupParent();
963 LookupQualifiedName(Previous, LookupContext);
964
965 if (Previous.isAmbiguous())
966 return true;
967
968 if (Previous.begin() != Previous.end())
969 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorb74b1032010-04-18 17:37:40 +0000970 }
John McCall90d3bb92009-12-17 23:21:11 +0000971 }
Richard Smith72bcaec2013-12-05 04:30:04 +0000972 } else if (PrevDecl &&
973 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
Craig Topperc3ec1492014-05-26 06:22:03 +0000974 PrevDecl = PrevClassTemplate = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000975
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000976 if (PrevClassTemplate) {
Richard Smithe85e1762012-04-22 02:13:50 +0000977 // Ensure that the template parameter lists are compatible. Skip this check
978 // for a friend in a dependent context: the template parameter list itself
979 // could be dependent.
980 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
981 !TemplateParameterListsAreEqual(TemplateParams,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000982 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000983 /*Complain=*/true,
984 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000985 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000986
987 // C++ [temp.class]p4:
988 // In a redeclaration, partial specialization, explicit
989 // specialization or explicit instantiation of a class template,
990 // the class-key shall agree in kind with the original class
991 // template declaration (7.1.5.3).
992 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Richard Trieucaa33d32011-06-10 03:11:26 +0000993 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
994 TUK == TUK_Definition, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000995 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000996 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000997 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000998 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000999 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001000 }
1001
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001002 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +00001003 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001004 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001005 Diag(NameLoc, diag::err_redefinition) << Name;
1006 Diag(Def->getLocation(), diag::note_previous_definition);
1007 // FIXME: Would it make sense to try to "forget" the previous
1008 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +00001009 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001010 }
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001011 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001012 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1013 // Maybe we will complain about the shadowed template parameter.
1014 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1015 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00001016 PrevDecl = nullptr;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001017 } else if (PrevDecl) {
1018 // C++ [temp]p5:
1019 // A class template shall not have the same name as any other
1020 // template, class, function, object, enumeration, enumerator,
1021 // namespace, or type in the same scope (3.3), except as specified
1022 // in (14.5.4).
1023 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1024 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +00001025 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001026 }
1027
Douglas Gregordba32632009-02-10 19:49:53 +00001028 // Check the template parameter list of this declaration, possibly
1029 // merging in the template parameter list from the previous class
Richard Smithe85e1762012-04-22 02:13:50 +00001030 // template declaration. Skip this check for a friend in a dependent
1031 // context, because the template parameter list might be dependent.
1032 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
David Majnemerba8f17a2013-06-25 22:08:55 +00001033 CheckTemplateParameterList(
1034 TemplateParams,
Craig Topperc3ec1492014-05-26 06:22:03 +00001035 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1036 : nullptr,
David Majnemerba8f17a2013-06-25 22:08:55 +00001037 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1038 SemanticContext->isDependentContext())
1039 ? TPC_ClassTemplateMember
1040 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1041 : TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +00001042 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +00001043
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001044 if (SS.isSet()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045 // If the name of the template was qualified, we must be defining the
Douglas Gregorce40e2e2010-04-12 16:00:01 +00001046 // template out-of-line.
Richard Smithe85e1762012-04-22 02:13:50 +00001047 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1048 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
Richard Smith114394f2013-08-09 04:35:01 +00001049 : diag::err_member_decl_does_not_match)
1050 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
Douglas Gregorfe0055e2011-11-01 21:35:16 +00001051 Invalid = true;
1052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001053 }
1054
Mike Stump11289f42009-09-09 15:08:12 +00001055 CXXRecordDecl *NewClass =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001056 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
Mike Stump11289f42009-09-09 15:08:12 +00001057 PrevClassTemplate?
Craig Topperc3ec1492014-05-26 06:22:03 +00001058 PrevClassTemplate->getTemplatedDecl() : nullptr,
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001059 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +00001060 SetNestedNameSpecifier(NewClass, SS);
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00001061 if (NumOuterTemplateParamLists > 0)
1062 NewClass->setTemplateParameterListsInfo(Context,
1063 NumOuterTemplateParamLists,
1064 OuterTemplateParamLists);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001065
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001066 // Add alignment attributes if necessary; these attributes are checked when
1067 // the ASTContext lays out the structure.
Eli Friedman0415f3e12012-08-08 21:08:34 +00001068 if (TUK == TUK_Definition) {
1069 AddAlignmentAttributesForRecord(NewClass);
1070 AddMsStructLayoutForRecord(NewClass);
1071 }
Eli Friedmanedb6f5d2012-02-10 02:02:21 +00001072
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001073 ClassTemplateDecl *NewTemplate
1074 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1075 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +00001076 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +00001077 NewClass->setDescribedClassTemplate(NewTemplate);
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001078
Douglas Gregor21823bf2011-12-20 18:11:52 +00001079 if (ModulePrivateLoc.isValid())
Douglas Gregoref15bdb2011-09-09 18:32:39 +00001080 NewTemplate->setModulePrivate();
Douglas Gregor26701a42011-09-09 02:06:17 +00001081
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001082 // Build the type for the class template declaration now.
Douglas Gregor9961ce92010-07-08 18:37:38 +00001083 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCalle78aac42010-03-10 03:28:59 +00001084 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +00001085 assert(T->isDependentType() && "Class template type is not dependent?");
1086 (void)T;
1087
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001088 // If we are providing an explicit specialization of a member that is a
Douglas Gregorcf915552009-10-13 16:30:37 +00001089 // class template, make a note of that.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090 if (PrevClassTemplate &&
Douglas Gregorcf915552009-10-13 16:30:37 +00001091 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1092 PrevClassTemplate->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093
Anders Carlsson137108d2009-03-26 01:24:28 +00001094 // Set the access specifier.
Douglas Gregor31feb332012-03-17 23:06:31 +00001095 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
John McCall27b5c252009-09-14 21:59:20 +00001096 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +00001097
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001098 // Set the lexical context of these templates
1099 NewClass->setLexicalDeclContext(CurContext);
1100 NewTemplate->setLexicalDeclContext(CurContext);
1101
John McCall9bb74a52009-07-31 02:45:11 +00001102 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001103 NewClass->startDefinition();
1104
1105 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00001106 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001107
Rafael Espindola0c6c4052012-08-22 14:52:14 +00001108 if (PrevClassTemplate)
1109 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1110
Rafael Espindola385c0422012-07-13 18:04:45 +00001111 AddPushedVisibilityAttribute(NewClass);
1112
John McCall27b5c252009-09-14 21:59:20 +00001113 if (TUK != TUK_Friend)
1114 PushOnScopeChains(NewTemplate, S);
1115 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +00001116 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +00001117 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +00001118 NewClass->setAccess(PrevClassTemplate->getAccess());
1119 }
John McCall27b5c252009-09-14 21:59:20 +00001120
Richard Smith64017682013-07-17 23:53:16 +00001121 NewTemplate->setObjectOfFriendDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001122
John McCall27b5c252009-09-14 21:59:20 +00001123 // Friend templates are visible in fairly strange ways.
1124 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001125 DeclContext *DC = SemanticContext->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +00001126 DC->makeDeclVisibleInContext(NewTemplate);
John McCall27b5c252009-09-14 21:59:20 +00001127 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1128 PushOnScopeChains(NewTemplate, EnclosingScope,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001129 /* AddToContext = */ false);
John McCall27b5c252009-09-14 21:59:20 +00001130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001131
Douglas Gregor3dad8422009-09-26 06:47:28 +00001132 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1133 NewClass->getLocation(),
1134 NewTemplate,
1135 /*FIXME:*/NewClass->getLocation());
1136 Friend->setAccess(AS_public);
1137 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +00001138 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001139
Douglas Gregordba32632009-02-10 19:49:53 +00001140 if (Invalid) {
1141 NewTemplate->setInvalidDecl();
1142 NewClass->setInvalidDecl();
1143 }
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001144
Dmitri Gribenko34df2202012-07-31 22:37:06 +00001145 ActOnDocumentableDecl(NewTemplate);
1146
John McCall48871652010-08-21 09:40:31 +00001147 return NewTemplate;
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001148}
1149
Douglas Gregored5731f2009-11-25 17:50:39 +00001150/// \brief Diagnose the presence of a default template argument on a
1151/// template parameter, which is ill-formed in certain contexts.
1152///
1153/// \returns true if the default template argument should be dropped.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001154static bool DiagnoseDefaultTemplateArgument(Sema &S,
Douglas Gregored5731f2009-11-25 17:50:39 +00001155 Sema::TemplateParamListContext TPC,
1156 SourceLocation ParamLoc,
1157 SourceRange DefArgRange) {
1158 switch (TPC) {
1159 case Sema::TPC_ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00001160 case Sema::TPC_VarTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00001161 case Sema::TPC_TypeAliasTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001162 return false;
1163
1164 case Sema::TPC_FunctionTemplate:
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001165 case Sema::TPC_FriendFunctionTemplateDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001166 // C++ [temp.param]p9:
Douglas Gregored5731f2009-11-25 17:50:39 +00001167 // A default template-argument shall not be specified in a
1168 // function template declaration or a function template
1169 // definition [...]
Douglas Gregora99fb4c2011-02-04 04:20:44 +00001170 // If a friend function template declaration specifies a default
1171 // template-argument, that declaration shall be a definition and shall be
1172 // the only declaration of the function template in the translation unit.
1173 // (C++98/03 doesn't have this wording; see DR226).
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001174 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001175 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1176 : diag::ext_template_parameter_default_in_function_template)
1177 << DefArgRange;
Douglas Gregored5731f2009-11-25 17:50:39 +00001178 return false;
1179
1180 case Sema::TPC_ClassTemplateMember:
1181 // C++0x [temp.param]p9:
1182 // A default template-argument shall not be specified in the
1183 // template-parameter-lists of the definition of a member of a
1184 // class template that appears outside of the member's class.
1185 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1186 << DefArgRange;
1187 return true;
1188
David Majnemerba8f17a2013-06-25 22:08:55 +00001189 case Sema::TPC_FriendClassTemplate:
Douglas Gregored5731f2009-11-25 17:50:39 +00001190 case Sema::TPC_FriendFunctionTemplate:
1191 // C++ [temp.param]p9:
1192 // A default template-argument shall not be specified in a
1193 // friend template declaration.
1194 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1195 << DefArgRange;
1196 return true;
1197
1198 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1199 // for friend function templates if there is only a single
1200 // declaration (and it is a definition). Strange!
1201 }
1202
David Blaikie8a40f702012-01-17 06:56:22 +00001203 llvm_unreachable("Invalid TemplateParamListContext!");
Douglas Gregored5731f2009-11-25 17:50:39 +00001204}
1205
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001206/// \brief Check for unexpanded parameter packs within the template parameters
1207/// of a template template parameter, recursively.
Benjamin Kramer8aef5962011-03-26 12:38:21 +00001208static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1209 TemplateTemplateParmDecl *TTP) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001210 // A template template parameter which is a parameter pack is also a pack
1211 // expansion.
1212 if (TTP->isParameterPack())
1213 return false;
1214
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001215 TemplateParameterList *Params = TTP->getTemplateParameters();
1216 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1217 NamedDecl *P = Params->getParam(I);
1218 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00001219 if (!NTTP->isParameterPack() &&
1220 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001221 NTTP->getTypeSourceInfo(),
1222 Sema::UPPC_NonTypeTemplateParameterType))
1223 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001224
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001225 continue;
1226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001227
1228 if (TemplateTemplateParmDecl *InnerTTP
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001229 = dyn_cast<TemplateTemplateParmDecl>(P))
1230 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1231 return true;
1232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001233
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001234 return false;
1235}
1236
Douglas Gregordba32632009-02-10 19:49:53 +00001237/// \brief Checks the validity of a template parameter list, possibly
1238/// considering the template parameter list from a previous
1239/// declaration.
1240///
1241/// If an "old" template parameter list is provided, it must be
1242/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1243/// template parameter list.
1244///
1245/// \param NewParams Template parameter list for a new template
1246/// declaration. This template parameter list will be updated with any
1247/// default arguments that are carried through from the previous
1248/// template parameter list.
1249///
1250/// \param OldParams If provided, template parameter list from a
1251/// previous declaration of the same template. Default template
1252/// arguments will be merged from the old template parameter list to
1253/// the new template parameter list.
1254///
Douglas Gregored5731f2009-11-25 17:50:39 +00001255/// \param TPC Describes the context in which we are checking the given
1256/// template parameter list.
1257///
Douglas Gregordba32632009-02-10 19:49:53 +00001258/// \returns true if an error occurred, false otherwise.
1259bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001260 TemplateParameterList *OldParams,
1261 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001262 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001263
Douglas Gregordba32632009-02-10 19:49:53 +00001264 // C++ [temp.param]p10:
1265 // The set of default template-arguments available for use with a
1266 // template declaration or definition is obtained by merging the
1267 // default arguments from the definition (if in scope) and all
1268 // declarations in scope in the same way default function
1269 // arguments are (8.3.6).
1270 bool SawDefaultArgument = false;
1271 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001272
Mike Stumpc89c8e32009-02-11 23:03:27 +00001273 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001274 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001275 if (OldParams)
1276 OldParam = OldParams->begin();
1277
Douglas Gregor0693def2011-01-27 01:40:17 +00001278 bool RemoveDefaultArguments = false;
Douglas Gregordba32632009-02-10 19:49:53 +00001279 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1280 NewParamEnd = NewParams->end();
1281 NewParam != NewParamEnd; ++NewParam) {
1282 // Variables used to diagnose redundant default arguments
1283 bool RedundantDefaultArg = false;
1284 SourceLocation OldDefaultLoc;
1285 SourceLocation NewDefaultLoc;
1286
David Blaikie651c73c2011-10-19 05:19:50 +00001287 // Variable used to diagnose missing default arguments
Douglas Gregordba32632009-02-10 19:49:53 +00001288 bool MissingDefaultArg = false;
1289
David Blaikie651c73c2011-10-19 05:19:50 +00001290 // Variable used to diagnose non-final parameter packs
1291 bool SawParameterPack = false;
Anders Carlsson327865d2009-06-12 23:20:15 +00001292
Douglas Gregordba32632009-02-10 19:49:53 +00001293 if (TemplateTypeParmDecl *NewTypeParm
1294 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001295 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001296 if (NewTypeParm->hasDefaultArgument() &&
1297 DiagnoseDefaultTemplateArgument(*this, TPC,
1298 NewTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001299 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001300 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001301 NewTypeParm->removeDefaultArgument();
1302
1303 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001304 TemplateTypeParmDecl *OldTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001305 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001306
Anders Carlsson327865d2009-06-12 23:20:15 +00001307 if (NewTypeParm->isParameterPack()) {
1308 assert(!NewTypeParm->hasDefaultArgument() &&
1309 "Parameter packs can't have a default argument!");
1310 SawParameterPack = true;
Mike Stump11289f42009-09-09 15:08:12 +00001311 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001312 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001313 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1314 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1315 SawDefaultArgument = true;
1316 RedundantDefaultArg = true;
1317 PreviousDefaultArgLoc = NewDefaultLoc;
1318 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1319 // Merge the default argument from the old declaration to the
1320 // new declaration.
John McCall0ad16662009-10-29 08:12:44 +00001321 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001322 true);
1323 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1324 } else if (NewTypeParm->hasDefaultArgument()) {
1325 SawDefaultArgument = true;
1326 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1327 } else if (SawDefaultArgument)
1328 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001329 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001330 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001331 // Check for unexpanded parameter packs.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001332 if (!NewNonTypeParm->isParameterPack() &&
1333 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334 NewNonTypeParm->getTypeSourceInfo(),
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001335 UPPC_NonTypeTemplateParameterType)) {
1336 Invalid = true;
1337 continue;
1338 }
1339
Douglas Gregored5731f2009-11-25 17:50:39 +00001340 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001341 if (NewNonTypeParm->hasDefaultArgument() &&
1342 DiagnoseDefaultTemplateArgument(*this, TPC,
1343 NewNonTypeParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001344 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnara656e3002010-06-09 09:26:05 +00001345 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001346 }
1347
Mike Stump12b8ce12009-08-04 21:02:39 +00001348 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001349 NonTypeTemplateParmDecl *OldNonTypeParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001350 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001351 if (NewNonTypeParm->isParameterPack()) {
1352 assert(!NewNonTypeParm->hasDefaultArgument() &&
1353 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001354 if (!NewNonTypeParm->isPackExpansion())
1355 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001356 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Richard Smith35828f12013-07-22 03:31:14 +00001357 NewNonTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001358 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1359 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1360 SawDefaultArgument = true;
1361 RedundantDefaultArg = true;
1362 PreviousDefaultArgLoc = NewDefaultLoc;
1363 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1364 // Merge the default argument from the old declaration to the
1365 // new declaration.
Douglas Gregordba32632009-02-10 19:49:53 +00001366 // FIXME: We need to create a new kind of "default argument"
Douglas Gregorf5500772011-01-05 15:48:55 +00001367 // expression that points to a previous non-type template
Douglas Gregordba32632009-02-10 19:49:53 +00001368 // parameter.
1369 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001370 OldNonTypeParm->getDefaultArgument(),
1371 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001372 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1373 } else if (NewNonTypeParm->hasDefaultArgument()) {
1374 SawDefaultArgument = true;
1375 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1376 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001377 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001378 } else {
Douglas Gregordba32632009-02-10 19:49:53 +00001379 TemplateTemplateParmDecl *NewTemplateParm
1380 = cast<TemplateTemplateParmDecl>(*NewParam);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001382 // Check for unexpanded parameter packs, recursively.
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00001383 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
Douglas Gregor38ee75e2010-12-16 15:36:43 +00001384 Invalid = true;
1385 continue;
1386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387
David Blaikie651c73c2011-10-19 05:19:50 +00001388 // Check the presence of a default argument here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389 if (NewTemplateParm->hasDefaultArgument() &&
1390 DiagnoseDefaultTemplateArgument(*this, TPC,
1391 NewTemplateParm->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +00001392 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001393 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001394
1395 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001396 TemplateTemplateParmDecl *OldTemplateParm
Craig Topperc3ec1492014-05-26 06:22:03 +00001397 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001398 if (NewTemplateParm->isParameterPack()) {
1399 assert(!NewTemplateParm->hasDefaultArgument() &&
1400 "Parameter packs can't have a default argument!");
Richard Smith1fde8ec2012-09-07 02:06:42 +00001401 if (!NewTemplateParm->isPackExpansion())
1402 SawParameterPack = true;
Douglas Gregor0018cdc2011-01-05 16:19:19 +00001403 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001404 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001405 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1406 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001407 SawDefaultArgument = true;
1408 RedundantDefaultArg = true;
1409 PreviousDefaultArgLoc = NewDefaultLoc;
1410 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1411 // Merge the default argument from the old declaration to the
1412 // new declaration.
Mike Stump87c57ac2009-05-16 07:39:55 +00001413 // FIXME: We need to create a new kind of "default argument" expression
1414 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001415 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001416 OldTemplateParm->getDefaultArgument(),
1417 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001418 PreviousDefaultArgLoc
1419 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001420 } else if (NewTemplateParm->hasDefaultArgument()) {
1421 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001422 PreviousDefaultArgLoc
1423 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001424 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001425 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001426 }
1427
Richard Smith1fde8ec2012-09-07 02:06:42 +00001428 // C++11 [temp.param]p11:
David Blaikie651c73c2011-10-19 05:19:50 +00001429 // If a template parameter of a primary class template or alias template
1430 // is a template parameter pack, it shall be the last template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001431 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00001432 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1433 TPC == TPC_TypeAliasTemplate)) {
David Blaikie651c73c2011-10-19 05:19:50 +00001434 Diag((*NewParam)->getLocation(),
1435 diag::err_template_param_pack_must_be_last_template_parameter);
1436 Invalid = true;
1437 }
1438
Douglas Gregordba32632009-02-10 19:49:53 +00001439 if (RedundantDefaultArg) {
1440 // C++ [temp.param]p12:
1441 // A template-parameter shall not be given default arguments
1442 // by two different declarations in the same scope.
1443 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1444 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1445 Invalid = true;
Douglas Gregor8b481d82011-02-04 03:57:22 +00001446 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
Douglas Gregordba32632009-02-10 19:49:53 +00001447 // C++ [temp.param]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001448 // If a template-parameter of a class template has a default
1449 // template-argument, each subsequent template-parameter shall either
Douglas Gregor7dba51f2011-01-05 16:21:17 +00001450 // have a default template-argument supplied or be a template parameter
1451 // pack.
Mike Stump11289f42009-09-09 15:08:12 +00001452 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001453 diag::err_template_param_default_arg_missing);
1454 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1455 Invalid = true;
Douglas Gregor0693def2011-01-27 01:40:17 +00001456 RemoveDefaultArguments = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001457 }
1458
1459 // If we have an old template parameter list that we're merging
1460 // in, move on to the next parameter.
1461 if (OldParams)
1462 ++OldParam;
1463 }
1464
Douglas Gregor0693def2011-01-27 01:40:17 +00001465 // We were missing some default arguments at the end of the list, so remove
1466 // all of the default arguments.
1467 if (RemoveDefaultArguments) {
1468 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1469 NewParamEnd = NewParams->end();
1470 NewParam != NewParamEnd; ++NewParam) {
1471 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1472 TTP->removeDefaultArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0693def2011-01-27 01:40:17 +00001474 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1475 NTTP->removeDefaultArgument();
1476 else
1477 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1478 }
1479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480
Douglas Gregordba32632009-02-10 19:49:53 +00001481 return Invalid;
1482}
Douglas Gregord32e0282009-02-09 23:23:08 +00001483
John McCalla020a012010-10-20 05:44:58 +00001484namespace {
1485
1486/// A class which looks for a use of a certain level of template
1487/// parameter.
1488struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1489 typedef RecursiveASTVisitor<DependencyChecker> super;
1490
1491 unsigned Depth;
1492 bool Match;
Richard Smith6056d5e2014-02-09 00:54:43 +00001493 SourceLocation MatchLoc;
1494
1495 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
John McCalla020a012010-10-20 05:44:58 +00001496
1497 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1498 NamedDecl *ND = Params->getParam(0);
1499 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1500 Depth = PD->getDepth();
1501 } else if (NonTypeTemplateParmDecl *PD =
1502 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1503 Depth = PD->getDepth();
1504 } else {
1505 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1506 }
1507 }
1508
Richard Smith6056d5e2014-02-09 00:54:43 +00001509 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
John McCalla020a012010-10-20 05:44:58 +00001510 if (ParmDepth >= Depth) {
1511 Match = true;
Richard Smith6056d5e2014-02-09 00:54:43 +00001512 MatchLoc = Loc;
John McCalla020a012010-10-20 05:44:58 +00001513 return true;
1514 }
1515 return false;
1516 }
1517
Richard Smith6056d5e2014-02-09 00:54:43 +00001518 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1519 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1520 }
1521
John McCalla020a012010-10-20 05:44:58 +00001522 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1523 return !Matches(T->getDepth());
1524 }
1525
1526 bool TraverseTemplateName(TemplateName N) {
1527 if (TemplateTemplateParmDecl *PD =
1528 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
Richard Smith6056d5e2014-02-09 00:54:43 +00001529 if (Matches(PD->getDepth()))
1530 return false;
John McCalla020a012010-10-20 05:44:58 +00001531 return super::TraverseTemplateName(N);
1532 }
1533
1534 bool VisitDeclRefExpr(DeclRefExpr *E) {
1535 if (NonTypeTemplateParmDecl *PD =
Richard Smith6056d5e2014-02-09 00:54:43 +00001536 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1537 if (Matches(PD->getDepth(), E->getExprLoc()))
John McCalla020a012010-10-20 05:44:58 +00001538 return false;
John McCalla020a012010-10-20 05:44:58 +00001539 return super::VisitDeclRefExpr(E);
1540 }
Richard Smith6056d5e2014-02-09 00:54:43 +00001541
1542 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1543 return TraverseType(T->getReplacementType());
1544 }
1545
1546 bool
1547 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1548 return TraverseTemplateArgument(T->getArgumentPack());
1549 }
1550
Douglas Gregora6a7e3c2011-05-13 00:34:01 +00001551 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1552 return TraverseType(T->getInjectedSpecializationType());
1553 }
John McCalla020a012010-10-20 05:44:58 +00001554};
1555}
1556
Douglas Gregor972fe532011-05-10 18:27:06 +00001557/// Determines whether a given type depends on the given parameter
John McCalla020a012010-10-20 05:44:58 +00001558/// list.
1559static bool
Douglas Gregor972fe532011-05-10 18:27:06 +00001560DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
John McCalla020a012010-10-20 05:44:58 +00001561 DependencyChecker Checker(Params);
Douglas Gregor972fe532011-05-10 18:27:06 +00001562 Checker.TraverseType(T);
John McCalla020a012010-10-20 05:44:58 +00001563 return Checker.Match;
1564}
1565
Douglas Gregor972fe532011-05-10 18:27:06 +00001566// Find the source range corresponding to the named type in the given
1567// nested-name-specifier, if any.
1568static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1569 QualType T,
1570 const CXXScopeSpec &SS) {
1571 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1572 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1573 if (const Type *CurType = NNS->getAsType()) {
1574 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1575 return NNSLoc.getTypeLoc().getSourceRange();
1576 } else
1577 break;
1578
1579 NNSLoc = NNSLoc.getPrefix();
1580 }
1581
1582 return SourceRange();
1583}
1584
Mike Stump11289f42009-09-09 15:08:12 +00001585/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001586/// specifier, returning the template parameter list that applies to the
1587/// name.
1588///
1589/// \param DeclStartLoc the start of the declaration that has a scope
1590/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001591///
Douglas Gregor972fe532011-05-10 18:27:06 +00001592/// \param DeclLoc The location of the declaration itself.
1593///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001594/// \param SS the scope specifier that will be matched to the given template
1595/// parameter lists. This scope specifier precedes a qualified name that is
1596/// being declared.
1597///
Richard Smith4b55a9c2014-04-17 03:29:33 +00001598/// \param TemplateId The template-id following the scope specifier, if there
1599/// is one. Used to check for a missing 'template<>'.
1600///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001601/// \param ParamLists the template parameter lists, from the outermost to the
1602/// innermost template parameter lists.
1603///
John McCalle820e5e2010-04-13 20:37:33 +00001604/// \param IsFriend Whether to apply the slightly different rules for
1605/// matching template parameters to scope specifiers in friend
1606/// declarations.
1607///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001608/// \param IsExplicitSpecialization will be set true if the entity being
1609/// declared is an explicit specialization, false otherwise.
1610///
Mike Stump11289f42009-09-09 15:08:12 +00001611/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001612/// name that is preceded by the scope specifier @p SS. This template
Abramo Bagnara60804e12011-03-18 15:16:37 +00001613/// parameter list may have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001614/// template) or may have no template parameters (if we're declaring a
Abramo Bagnara60804e12011-03-18 15:16:37 +00001615/// template specialization), or may be NULL (if what we're declaring isn't
Douglas Gregord8d297c2009-07-21 23:53:31 +00001616/// itself a template).
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001617TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1618 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001619 TemplateIdAnnotation *TemplateId,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001620 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1621 bool &IsExplicitSpecialization, bool &Invalid) {
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001622 IsExplicitSpecialization = false;
Douglas Gregor972fe532011-05-10 18:27:06 +00001623 Invalid = false;
1624
1625 // The sequence of nested types to which we will match up the template
1626 // parameter lists. We first build this list by starting with the type named
1627 // by the nested-name-specifier and walking out until we run out of types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001628 SmallVector<QualType, 4> NestedTypes;
Douglas Gregor972fe532011-05-10 18:27:06 +00001629 QualType T;
Douglas Gregor9d07dfa2011-05-15 17:27:27 +00001630 if (SS.getScopeRep()) {
1631 if (CXXRecordDecl *Record
1632 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1633 T = Context.getTypeDeclType(Record);
1634 else
1635 T = QualType(SS.getScopeRep()->getAsType(), 0);
1636 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001637
1638 // If we found an explicit specialization that prevents us from needing
1639 // 'template<>' headers, this will be set to the location of that
1640 // explicit specialization.
1641 SourceLocation ExplicitSpecLoc;
1642
1643 while (!T.isNull()) {
1644 NestedTypes.push_back(T);
1645
1646 // Retrieve the parent of a record type.
1647 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1648 // If this type is an explicit specialization, we're done.
1649 if (ClassTemplateSpecializationDecl *Spec
1650 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1651 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1652 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1653 ExplicitSpecLoc = Spec->getLocation();
1654 break;
Douglas Gregor65911492009-11-23 12:11:45 +00001655 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001656 } else if (Record->getTemplateSpecializationKind()
1657 == TSK_ExplicitSpecialization) {
1658 ExplicitSpecLoc = Record->getLocation();
John McCalle820e5e2010-04-13 20:37:33 +00001659 break;
1660 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001661
1662 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1663 T = Context.getTypeDeclType(Parent);
1664 else
1665 T = QualType();
1666 continue;
1667 }
1668
1669 if (const TemplateSpecializationType *TST
1670 = T->getAs<TemplateSpecializationType>()) {
1671 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1672 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1673 T = Context.getTypeDeclType(Parent);
1674 else
1675 T = QualType();
1676 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001677 }
Douglas Gregor972fe532011-05-10 18:27:06 +00001678 }
1679
1680 // Look one step prior in a dependent template specialization type.
1681 if (const DependentTemplateSpecializationType *DependentTST
1682 = T->getAs<DependentTemplateSpecializationType>()) {
1683 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1684 T = QualType(NNS->getAsType(), 0);
1685 else
1686 T = QualType();
1687 continue;
1688 }
1689
1690 // Look one step prior in a dependent name type.
1691 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1692 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1693 T = QualType(NNS->getAsType(), 0);
1694 else
1695 T = QualType();
1696 continue;
1697 }
1698
1699 // Retrieve the parent of an enumeration type.
1700 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1701 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1702 // check here.
1703 EnumDecl *Enum = EnumT->getDecl();
1704
1705 // Get to the parent type.
1706 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1707 T = Context.getTypeDeclType(Parent);
1708 else
1709 T = QualType();
1710 continue;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
Douglas Gregor972fe532011-05-10 18:27:06 +00001713 T = QualType();
1714 }
1715 // Reverse the nested types list, since we want to traverse from the outermost
1716 // to the innermost while checking template-parameter-lists.
1717 std::reverse(NestedTypes.begin(), NestedTypes.end());
Douglas Gregor15301382009-07-30 17:40:51 +00001718
Douglas Gregor972fe532011-05-10 18:27:06 +00001719 // C++0x [temp.expl.spec]p17:
1720 // A member or a member template may be nested within many
1721 // enclosing class templates. In an explicit specialization for
1722 // such a member, the member declaration shall be preceded by a
1723 // template<> for each enclosing class template that is
1724 // explicitly specialized.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001725 bool SawNonEmptyTemplateParameterList = false;
Richard Smith11a80dc2014-04-17 03:52:20 +00001726
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001727 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
Richard Smith11a80dc2014-04-17 03:52:20 +00001728 if (SawNonEmptyTemplateParameterList) {
1729 Diag(DeclLoc, diag::err_specialize_member_of_template)
1730 << !Recovery << Range;
1731 Invalid = true;
1732 IsExplicitSpecialization = false;
1733 return true;
1734 }
1735
1736 return false;
1737 };
1738
1739 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1740 // Check that we can have an explicit specialization here.
1741 if (CheckExplicitSpecialization(Range, true))
1742 return true;
1743
1744 // We don't have a template header, but we should.
1745 SourceLocation ExpectedTemplateLoc;
1746 if (!ParamLists.empty())
1747 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1748 else
1749 ExpectedTemplateLoc = DeclStartLoc;
1750
1751 Diag(DeclLoc, diag::err_template_spec_needs_header)
1752 << Range
1753 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1754 return false;
1755 };
1756
Douglas Gregor972fe532011-05-10 18:27:06 +00001757 unsigned ParamIdx = 0;
1758 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1759 ++TypeIdx) {
1760 T = NestedTypes[TypeIdx];
1761
1762 // Whether we expect a 'template<>' header.
1763 bool NeedEmptyTemplateHeader = false;
1764
1765 // Whether we expect a template header with parameters.
1766 bool NeedNonemptyTemplateHeader = false;
1767
1768 // For a dependent type, the set of template parameters that we
1769 // expect to see.
Craig Topperc3ec1492014-05-26 06:22:03 +00001770 TemplateParameterList *ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001771
Douglas Gregor373af9b2011-05-11 23:26:17 +00001772 // C++0x [temp.expl.spec]p15:
1773 // A member or a member template may be nested within many enclosing
1774 // class templates. In an explicit specialization for such a member, the
1775 // member declaration shall be preceded by a template<> for each
1776 // enclosing class template that is explicitly specialized.
Douglas Gregor972fe532011-05-10 18:27:06 +00001777 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1778 if (ClassTemplatePartialSpecializationDecl *Partial
1779 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1780 ExpectedTemplateParams = Partial->getTemplateParameters();
1781 NeedNonemptyTemplateHeader = true;
1782 } else if (Record->isDependentType()) {
1783 if (Record->getDescribedClassTemplate()) {
John McCall2408e322010-04-27 00:57:59 +00001784 ExpectedTemplateParams = Record->getDescribedClassTemplate()
Douglas Gregor972fe532011-05-10 18:27:06 +00001785 ->getTemplateParameters();
1786 NeedNonemptyTemplateHeader = true;
1787 }
1788 } else if (ClassTemplateSpecializationDecl *Spec
1789 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1790 // C++0x [temp.expl.spec]p4:
1791 // Members of an explicitly specialized class template are defined
1792 // in the same manner as members of normal classes, and not using
1793 // the template<> syntax.
1794 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1795 NeedEmptyTemplateHeader = true;
1796 else
Douglas Gregorb32e8252011-06-01 22:37:07 +00001797 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001798 } else if (Record->getTemplateSpecializationKind()) {
1799 if (Record->getTemplateSpecializationKind()
Douglas Gregor373af9b2011-05-11 23:26:17 +00001800 != TSK_ExplicitSpecialization &&
1801 TypeIdx == NumTypes - 1)
1802 IsExplicitSpecialization = true;
1803
1804 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001805 }
1806 } else if (const TemplateSpecializationType *TST
1807 = T->getAs<TemplateSpecializationType>()) {
1808 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1809 ExpectedTemplateParams = Template->getTemplateParameters();
1810 NeedNonemptyTemplateHeader = true;
1811 }
1812 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1813 // FIXME: We actually could/should check the template arguments here
1814 // against the corresponding template parameter list.
1815 NeedNonemptyTemplateHeader = false;
1816 }
1817
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001818 // C++ [temp.expl.spec]p16:
1819 // In an explicit specialization declaration for a member of a class
1820 // template or a member template that ap- pears in namespace scope, the
1821 // member template and some of its enclosing class templates may remain
1822 // unspecialized, except that the declaration shall not explicitly
1823 // specialize a class member template if its en- closing class templates
1824 // are not explicitly specialized as well.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001825 if (ParamIdx < ParamLists.size()) {
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001826 if (ParamLists[ParamIdx]->size() == 0) {
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001827 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1828 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001829 return nullptr;
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001830 } else
1831 SawNonEmptyTemplateParameterList = true;
1832 }
1833
Douglas Gregor972fe532011-05-10 18:27:06 +00001834 if (NeedEmptyTemplateHeader) {
1835 // If we're on the last of the types, and we need a 'template<>' header
1836 // here, then it's an explicit specialization.
1837 if (TypeIdx == NumTypes - 1)
1838 IsExplicitSpecialization = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001839
1840 if (ParamIdx < ParamLists.size()) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001841 if (ParamLists[ParamIdx]->size() > 0) {
1842 // The header has template parameters when it shouldn't. Complain.
1843 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1844 diag::err_template_param_list_matches_nontemplate)
1845 << T
1846 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1847 ParamLists[ParamIdx]->getRAngleLoc())
1848 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1849 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001850 return nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001851 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001852
Douglas Gregor972fe532011-05-10 18:27:06 +00001853 // Consume this template header.
1854 ++ParamIdx;
1855 continue;
Douglas Gregor972fe532011-05-10 18:27:06 +00001856 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001857
1858 if (!IsFriend)
1859 if (DiagnoseMissingExplicitSpecialization(
1860 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
Craig Topperc3ec1492014-05-26 06:22:03 +00001861 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001862
Douglas Gregor972fe532011-05-10 18:27:06 +00001863 continue;
1864 }
Richard Smith11a80dc2014-04-17 03:52:20 +00001865
Douglas Gregor972fe532011-05-10 18:27:06 +00001866 if (NeedNonemptyTemplateHeader) {
1867 // In friend declarations we can have template-ids which don't
1868 // depend on the corresponding template parameter lists. But
1869 // assume that empty parameter lists are supposed to match this
1870 // template-id.
1871 if (IsFriend && T->isDependentType()) {
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001872 if (ParamIdx < ParamLists.size() &&
Douglas Gregor972fe532011-05-10 18:27:06 +00001873 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
Craig Topperc3ec1492014-05-26 06:22:03 +00001874 ExpectedTemplateParams = nullptr;
Douglas Gregor972fe532011-05-10 18:27:06 +00001875 else
1876 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001877 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001878
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001879 if (ParamIdx < ParamLists.size()) {
1880 // Check the template parameter list, if we can.
Douglas Gregor972fe532011-05-10 18:27:06 +00001881 if (ExpectedTemplateParams &&
1882 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1883 ExpectedTemplateParams,
1884 true, TPL_TemplateMatch))
1885 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00001886
Douglas Gregor972fe532011-05-10 18:27:06 +00001887 if (!Invalid &&
Craig Topperc3ec1492014-05-26 06:22:03 +00001888 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
Douglas Gregor972fe532011-05-10 18:27:06 +00001889 TPC_ClassTemplateMember))
1890 Invalid = true;
1891
1892 ++ParamIdx;
1893 continue;
1894 }
1895
1896 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1897 << T
1898 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1899 Invalid = true;
1900 continue;
1901 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001902 }
Richard Smith4b55a9c2014-04-17 03:29:33 +00001903
Douglas Gregord8d297c2009-07-21 23:53:31 +00001904 // If there were at least as many template-ids as there were template
1905 // parameter lists, then there are no template parameter lists remaining for
1906 // the declaration itself.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001907 if (ParamIdx >= ParamLists.size()) {
1908 if (TemplateId && !IsFriend) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00001909 // We don't have a template header for the declaration itself, but we
1910 // should.
Richard Smith4b55a9c2014-04-17 03:29:33 +00001911 IsExplicitSpecialization = true;
Richard Smith11a80dc2014-04-17 03:52:20 +00001912 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1913 TemplateId->RAngleLoc));
Richard Smith4b55a9c2014-04-17 03:29:33 +00001914
1915 // Fabricate an empty template parameter list for the invented header.
1916 return TemplateParameterList::Create(Context, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001917 SourceLocation(), nullptr, 0,
Richard Smith4b55a9c2014-04-17 03:29:33 +00001918 SourceLocation());
1919 }
1920
Craig Topperc3ec1492014-05-26 06:22:03 +00001921 return nullptr;
Richard Smith4b55a9c2014-04-17 03:29:33 +00001922 }
Mike Stump11289f42009-09-09 15:08:12 +00001923
Douglas Gregord8d297c2009-07-21 23:53:31 +00001924 // If there were too many template parameter lists, complain about that now.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001925 if (ParamIdx < ParamLists.size() - 1) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001926 bool HasAnyExplicitSpecHeader = false;
1927 bool AllExplicitSpecHeaders = true;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001928 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
Douglas Gregor972fe532011-05-10 18:27:06 +00001929 if (ParamLists[I]->size() == 0)
1930 HasAnyExplicitSpecHeader = true;
1931 else
1932 AllExplicitSpecHeaders = false;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001933 }
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001934
Douglas Gregor972fe532011-05-10 18:27:06 +00001935 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001936 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1937 : diag::err_template_spec_extra_headers)
1938 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1939 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
Douglas Gregor972fe532011-05-10 18:27:06 +00001940
1941 // If there was a specialization somewhere, such that 'template<>' is
1942 // not required, and there were any 'template<>' headers, note where the
1943 // specialization occurred.
1944 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1945 Diag(ExplicitSpecLoc,
1946 diag::note_explicit_template_spec_does_not_need_header)
1947 << NestedTypes.back();
1948
1949 // We have a template parameter list with no corresponding scope, which
1950 // means that the resulting template declaration can't be instantiated
1951 // properly (we'll end up with dependent nodes when we shouldn't).
1952 if (!AllExplicitSpecHeaders)
1953 Invalid = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001954 }
Mike Stump11289f42009-09-09 15:08:12 +00001955
Douglas Gregor522d5eb2011-06-06 15:22:55 +00001956 // C++ [temp.expl.spec]p16:
1957 // In an explicit specialization declaration for a member of a class
1958 // template or a member template that ap- pears in namespace scope, the
1959 // member template and some of its enclosing class templates may remain
1960 // unspecialized, except that the declaration shall not explicitly
1961 // specialize a class member template if its en- closing class templates
1962 // are not explicitly specialized as well.
Richard Smith11a80dc2014-04-17 03:52:20 +00001963 if (ParamLists.back()->size() == 0 &&
NAKAMURA Takumide4077a2014-04-17 08:57:09 +00001964 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1965 false))
Craig Topperc3ec1492014-05-26 06:22:03 +00001966 return nullptr;
Richard Smith11a80dc2014-04-17 03:52:20 +00001967
Douglas Gregord8d297c2009-07-21 23:53:31 +00001968 // Return the last template parameter list, which corresponds to the
1969 // entity being declared.
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00001970 return ParamLists.back();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001971}
1972
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001973void Sema::NoteAllFoundTemplates(TemplateName Name) {
1974 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1975 Diag(Template->getLocation(), diag::note_template_declared_here)
Larisse Voufo39a1e502013-08-06 01:03:05 +00001976 << (isa<FunctionTemplateDecl>(Template)
1977 ? 0
1978 : isa<ClassTemplateDecl>(Template)
1979 ? 1
1980 : isa<VarTemplateDecl>(Template)
1981 ? 2
1982 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1983 << Template->getDeclName();
Douglas Gregor8b6070b2011-03-04 21:37:14 +00001984 return;
1985 }
1986
1987 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1988 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1989 IEnd = OST->end();
1990 I != IEnd; ++I)
1991 Diag((*I)->getLocation(), diag::note_template_declared_here)
1992 << 0 << (*I)->getDeclName();
1993
1994 return;
1995 }
1996}
1997
Douglas Gregordc572a32009-03-30 22:58:21 +00001998QualType Sema::CheckTemplateIdType(TemplateName Name,
1999 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002000 TemplateArgumentListInfo &TemplateArgs) {
John McCalld9dfe3a2011-06-30 08:33:18 +00002001 DependentTemplateName *DTN
2002 = Name.getUnderlying().getAsDependentTemplateName();
Richard Smith3f1b5d02011-05-05 21:57:07 +00002003 if (DTN && DTN->isIdentifier())
2004 // When building a template-id where the template-name is dependent,
2005 // assume the template is a type template. Either our assumption is
2006 // correct, or the code is ill-formed and will be diagnosed when the
2007 // dependent name is substituted.
2008 return Context.getDependentTemplateSpecializationType(ETK_None,
2009 DTN->getQualifier(),
2010 DTN->getIdentifier(),
2011 TemplateArgs);
2012
Douglas Gregordc572a32009-03-30 22:58:21 +00002013 TemplateDecl *Template = Name.getAsTemplateDecl();
Richard Smith8f658062013-12-04 00:56:29 +00002014 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2015 isa<VarTemplateDecl>(Template)) {
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002016 // We might have a substituted template template parameter pack. If so,
2017 // build a template specialization type for it.
2018 if (Name.getAsSubstTemplateTemplateParmPack())
2019 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002020
Douglas Gregor8b6070b2011-03-04 21:37:14 +00002021 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2022 << Name;
2023 NoteAllFoundTemplates(Name);
2024 return QualType();
Douglas Gregorb67535d2009-03-31 00:43:58 +00002025 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002026
Douglas Gregorc40290e2009-03-09 23:48:35 +00002027 // Check that the template argument list is well-formed for this
2028 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002029 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00002030 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00002031 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00002032 return QualType();
2033
Douglas Gregorc40290e2009-03-09 23:48:35 +00002034 QualType CanonType;
2035
Douglas Gregor678d76c2011-07-01 01:22:09 +00002036 bool InstantiationDependent = false;
Richard Smith83b11aa2014-01-09 02:22:22 +00002037 if (TypeAliasTemplateDecl *AliasTemplate =
2038 dyn_cast<TypeAliasTemplateDecl>(Template)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00002039 // Find the canonical type for this type alias template specialization.
2040 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2041 if (Pattern->isInvalidDecl())
2042 return QualType();
2043
2044 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2045 Converted.data(), Converted.size());
2046
2047 // Only substitute for the innermost template argument list.
2048 MultiLevelTemplateArgumentList TemplateArgLists;
Richard Smith0c4a34b2011-05-14 15:04:18 +00002049 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
Richard Smith5e96d832011-05-12 00:06:17 +00002050 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2051 for (unsigned I = 0; I < Depth; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +00002052 TemplateArgLists.addOuterTemplateArguments(None);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002053
Richard Smith802c4b72012-08-23 06:16:52 +00002054 LocalInstantiationScope Scope(*this);
Richard Smith3f1b5d02011-05-05 21:57:07 +00002055 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002056 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00002057 return QualType();
Richard Smith802c4b72012-08-23 06:16:52 +00002058
Richard Smith3f1b5d02011-05-05 21:57:07 +00002059 CanonType = SubstType(Pattern->getUnderlyingType(),
2060 TemplateArgLists, AliasTemplate->getLocation(),
2061 AliasTemplate->getDeclName());
2062 if (CanonType.isNull())
2063 return QualType();
2064 } else if (Name.isDependent() ||
2065 TemplateSpecializationType::anyDependentTemplateArguments(
Douglas Gregor678d76c2011-07-01 01:22:09 +00002066 TemplateArgs, InstantiationDependent)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002067 // This class template specialization is a dependent
2068 // type. Therefore, its canonical type is another class template
2069 // specialization type that contains all of the converted
2070 // arguments in canonical form. This ensures that, e.g., A<T> and
2071 // A<T, T> have identical types when A is declared as:
2072 //
2073 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00002074 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002075 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002076 Converted.data(),
2077 Converted.size());
Mike Stump11289f42009-09-09 15:08:12 +00002078
Douglas Gregora8e02e72009-07-28 23:00:59 +00002079 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00002080 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00002081 // In the future, we need to teach getTemplateSpecializationType to only
2082 // build the canonical type and return that to us.
2083 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00002084
2085 // This might work out to be a current instantiation, in which
2086 // case the canonical type needs to be the InjectedClassNameType.
2087 //
2088 // TODO: in theory this could be a simple hashtable lookup; most
2089 // changes to CurContext don't change the set of current
2090 // instantiations.
2091 if (isa<ClassTemplateDecl>(Template)) {
2092 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2093 // If we get out to a namespace, we're done.
2094 if (Ctx->isFileContext()) break;
2095
2096 // If this isn't a record, keep looking.
2097 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2098 if (!Record) continue;
2099
2100 // Look for one of the two cases with InjectedClassNameTypes
2101 // and check whether it's the same template.
2102 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2103 !Record->getDescribedClassTemplate())
2104 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105
John McCall2408e322010-04-27 00:57:59 +00002106 // Fetch the injected class name type and check whether its
2107 // injected type is equal to the type we just built.
2108 QualType ICNT = Context.getTypeDeclType(Record);
2109 QualType Injected = cast<InjectedClassNameType>(ICNT)
2110 ->getInjectedSpecializationType();
2111
2112 if (CanonType != Injected->getCanonicalTypeInternal())
2113 continue;
2114
2115 // If so, the canonical type of this TST is the injected
2116 // class name type of the record we just found.
2117 assert(ICNT.isCanonical());
2118 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00002119 break;
2120 }
2121 }
Mike Stump11289f42009-09-09 15:08:12 +00002122 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00002123 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002124 // Find the class template specialization declaration that
2125 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002126 void *InsertPos = nullptr;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002127 ClassTemplateSpecializationDecl *Decl
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002129 InsertPos);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002130 if (!Decl) {
2131 // This is the first time we have referenced this class template
2132 // specialization. Create the canonical declaration and add it to
2133 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00002134 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002135 ClassTemplate->getTemplatedDecl()->getTagKind(),
2136 ClassTemplate->getDeclContext(),
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002137 ClassTemplate->getTemplatedDecl()->getLocStart(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002138 ClassTemplate->getLocation(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002139 ClassTemplate,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002140 Converted.data(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002141 Converted.size(), nullptr);
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002142 ClassTemplate->AddSpecialization(Decl, InsertPos);
Abramo Bagnara02b95532012-09-05 09:05:18 +00002143 if (ClassTemplate->isOutOfLine())
2144 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
Douglas Gregorc40290e2009-03-09 23:48:35 +00002145 }
2146
Chandler Carruth2acfb222013-09-27 22:14:40 +00002147 // Diagnose uses of this specialization.
2148 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2149
Douglas Gregorc40290e2009-03-09 23:48:35 +00002150 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00002151 assert(isa<RecordType>(CanonType) &&
2152 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00002153 }
Mike Stump11289f42009-09-09 15:08:12 +00002154
Douglas Gregorc40290e2009-03-09 23:48:35 +00002155 // Build the fully-sugared type for this class template
2156 // specialization, which refers back to the class template
2157 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00002158 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00002159}
2160
John McCallfaf5fb42010-08-26 23:41:50 +00002161TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002162Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00002163 TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002164 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00002165 ASTTemplateArgsPtr TemplateArgsIn,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002166 SourceLocation RAngleLoc,
2167 bool IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002168 if (SS.isInvalid())
2169 return true;
2170
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002171 TemplateName Template = TemplateD.get();
Douglas Gregor8bf42052009-02-09 18:46:07 +00002172
Douglas Gregorc40290e2009-03-09 23:48:35 +00002173 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00002174 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002175 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00002176
Douglas Gregor5a064722011-02-28 17:23:35 +00002177 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
Abramo Bagnara4244b432012-01-27 08:46:19 +00002178 QualType T
2179 = Context.getDependentTemplateSpecializationType(ETK_None,
2180 DTN->getQualifier(),
2181 DTN->getIdentifier(),
2182 TemplateArgs);
2183 // Build type-source information.
Douglas Gregor5a064722011-02-28 17:23:35 +00002184 TypeLocBuilder TLB;
2185 DependentTemplateSpecializationTypeLoc SpecTL
2186 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002187 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2188 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002189 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002190 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002191 SpecTL.setLAngleLoc(LAngleLoc);
2192 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregor5a064722011-02-28 17:23:35 +00002193 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2194 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2195 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2196 }
2197
John McCall6b51f282009-11-23 01:53:49 +00002198 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00002199
2200 if (Result.isNull())
2201 return true;
2202
Douglas Gregore7c20652011-03-02 00:47:37 +00002203 // Build type-source information.
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002204 TypeLocBuilder TLB;
Douglas Gregore7c20652011-03-02 00:47:37 +00002205 TemplateSpecializationTypeLoc SpecTL
2206 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002207 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002208 SpecTL.setTemplateNameLoc(TemplateLoc);
2209 SpecTL.setLAngleLoc(LAngleLoc);
2210 SpecTL.setRAngleLoc(RAngleLoc);
2211 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2212 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall0ad16662009-10-29 08:12:44 +00002213
Abramo Bagnara4244b432012-01-27 08:46:19 +00002214 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2215 // constructor or destructor name (in such a case, the scope specifier
2216 // will be attached to the enclosing Decl or Expr node).
2217 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
Douglas Gregore7c20652011-03-02 00:47:37 +00002218 // Create an elaborated-type-specifier containing the nested-name-specifier.
2219 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2220 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002221 ElabTL.setElaboratedKeywordLoc(SourceLocation());
Douglas Gregore7c20652011-03-02 00:47:37 +00002222 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2223 }
2224
2225 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCalld8fe9af2009-09-08 17:47:29 +00002226}
John McCall06f6fe8d2009-09-04 01:14:41 +00002227
Douglas Gregore7c20652011-03-02 00:47:37 +00002228TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
John McCallfaf5fb42010-08-26 23:41:50 +00002229 TypeSpecifierType TagSpec,
Douglas Gregore7c20652011-03-02 00:47:37 +00002230 SourceLocation TagLoc,
2231 CXXScopeSpec &SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002232 SourceLocation TemplateKWLoc,
2233 TemplateTy TemplateD,
Douglas Gregore7c20652011-03-02 00:47:37 +00002234 SourceLocation TemplateLoc,
2235 SourceLocation LAngleLoc,
2236 ASTTemplateArgsPtr TemplateArgsIn,
2237 SourceLocation RAngleLoc) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002238 TemplateName Template = TemplateD.get();
Douglas Gregore7c20652011-03-02 00:47:37 +00002239
2240 // Translate the parser's template argument list in our AST format.
2241 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2242 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2243
2244 // Determine the tag kind
Abramo Bagnara6150c882010-05-11 21:36:43 +00002245 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Douglas Gregore7c20652011-03-02 00:47:37 +00002246 ElaboratedTypeKeyword Keyword
2247 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
Mike Stump11289f42009-09-09 15:08:12 +00002248
Douglas Gregore7c20652011-03-02 00:47:37 +00002249 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2250 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2251 DTN->getQualifier(),
2252 DTN->getIdentifier(),
2253 TemplateArgs);
2254
2255 // Build type-source information.
2256 TypeLocBuilder TLB;
2257 DependentTemplateSpecializationTypeLoc SpecTL
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002258 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2259 SpecTL.setElaboratedKeywordLoc(TagLoc);
2260 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00002261 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002262 SpecTL.setTemplateNameLoc(TemplateLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002263 SpecTL.setLAngleLoc(LAngleLoc);
2264 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002265 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2266 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2267 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2268 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00002269
2270 if (TypeAliasTemplateDecl *TAT =
2271 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2272 // C++0x [dcl.type.elab]p2:
2273 // If the identifier resolves to a typedef-name or the simple-template-id
2274 // resolves to an alias template specialization, the
2275 // elaborated-type-specifier is ill-formed.
2276 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2277 Diag(TAT->getLocation(), diag::note_declared_at);
2278 }
Douglas Gregore7c20652011-03-02 00:47:37 +00002279
2280 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2281 if (Result.isNull())
Matt Beaumont-Gay045bde42011-08-25 23:22:24 +00002282 return TypeResult(true);
Douglas Gregore7c20652011-03-02 00:47:37 +00002283
2284 // Check the tag kind
2285 if (const RecordType *RT = Result->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00002286 RecordDecl *D = RT->getDecl();
Douglas Gregore7c20652011-03-02 00:47:37 +00002287
John McCalld8fe9af2009-09-08 17:47:29 +00002288 IdentifierInfo *Id = D->getIdentifier();
2289 assert(Id && "templated class must have an identifier");
Douglas Gregore7c20652011-03-02 00:47:37 +00002290
Richard Trieucaa33d32011-06-10 03:11:26 +00002291 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2292 TagLoc, *Id)) {
John McCalld8fe9af2009-09-08 17:47:29 +00002293 Diag(TagLoc, diag::err_use_with_wrong_tag)
Douglas Gregore7c20652011-03-02 00:47:37 +00002294 << Result
Douglas Gregora771f462010-03-31 17:46:05 +00002295 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00002296 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00002297 }
2298 }
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002299
Douglas Gregore7c20652011-03-02 00:47:37 +00002300 // Provide source-location information for the template specialization.
2301 TypeLocBuilder TLB;
2302 TemplateSpecializationTypeLoc SpecTL
2303 = TLB.push<TemplateSpecializationTypeLoc>(Result);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002304 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002305 SpecTL.setTemplateNameLoc(TemplateLoc);
2306 SpecTL.setLAngleLoc(LAngleLoc);
2307 SpecTL.setRAngleLoc(RAngleLoc);
2308 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2309 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
John McCall06f6fe8d2009-09-04 01:14:41 +00002310
Douglas Gregore7c20652011-03-02 00:47:37 +00002311 // Construct an elaborated type containing the nested-name-specifier (if any)
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002312 // and tag keyword.
Douglas Gregore7c20652011-03-02 00:47:37 +00002313 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2314 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00002315 ElabTL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00002316 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2317 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
Douglas Gregor8bf42052009-02-09 18:46:07 +00002318}
2319
Larisse Voufo39a1e502013-08-06 01:03:05 +00002320static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002321 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2322 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002323
2324static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2325 NamedDecl *PrevDecl,
2326 SourceLocation Loc,
2327 bool IsPartialSpecialization);
2328
2329static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002330
Richard Smith300e0c32013-09-24 04:49:23 +00002331static bool isTemplateArgumentTemplateParameter(
2332 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2333 switch (Arg.getKind()) {
2334 case TemplateArgument::Null:
2335 case TemplateArgument::NullPtr:
2336 case TemplateArgument::Integral:
2337 case TemplateArgument::Declaration:
2338 case TemplateArgument::Pack:
2339 case TemplateArgument::TemplateExpansion:
2340 return false;
2341
2342 case TemplateArgument::Type: {
2343 QualType Type = Arg.getAsType();
2344 const TemplateTypeParmType *TPT =
2345 Arg.getAsType()->getAs<TemplateTypeParmType>();
2346 return TPT && !Type.hasQualifiers() &&
2347 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2348 }
2349
2350 case TemplateArgument::Expression: {
2351 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2352 if (!DRE || !DRE->getDecl())
2353 return false;
2354 const NonTypeTemplateParmDecl *NTTP =
2355 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2356 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2357 }
2358
2359 case TemplateArgument::Template:
2360 const TemplateTemplateParmDecl *TTP =
2361 dyn_cast_or_null<TemplateTemplateParmDecl>(
2362 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2363 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2364 }
2365 llvm_unreachable("unexpected kind of template argument");
2366}
2367
2368static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2369 ArrayRef<TemplateArgument> Args) {
2370 if (Params->size() != Args.size())
2371 return false;
2372
2373 unsigned Depth = Params->getDepth();
2374
2375 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2376 TemplateArgument Arg = Args[I];
2377
2378 // If the parameter is a pack expansion, the argument must be a pack
2379 // whose only element is a pack expansion.
2380 if (Params->getParam(I)->isParameterPack()) {
2381 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2382 !Arg.pack_begin()->isPackExpansion())
2383 return false;
2384 Arg = Arg.pack_begin()->getPackExpansionPattern();
2385 }
2386
2387 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2388 return false;
2389 }
2390
2391 return true;
2392}
2393
Richard Smith4b55a9c2014-04-17 03:29:33 +00002394/// Convert the parser's template argument list representation into our form.
2395static TemplateArgumentListInfo
2396makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2397 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2398 TemplateId.RAngleLoc);
2399 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2400 TemplateId.NumArgs);
2401 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2402 return TemplateArgs;
2403}
2404
Larisse Voufo39a1e502013-08-06 01:03:05 +00002405DeclResult Sema::ActOnVarTemplateSpecialization(
Richard Smithbeef3452014-01-16 23:39:20 +00002406 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2407 TemplateParameterList *TemplateParams, VarDecl::StorageClass SC,
2408 bool IsPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002409 // D must be variable template id.
2410 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2411 "Variable template specialization is declared with a template it.");
2412
2413 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002414 TemplateArgumentListInfo TemplateArgs =
2415 makeTemplateArgumentListInfo(*this, *TemplateId);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002416 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2417 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2418 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
Richard Smith4b55a9c2014-04-17 03:29:33 +00002419
Richard Smithbeef3452014-01-16 23:39:20 +00002420 TemplateName Name = TemplateId->Template.get();
2421
2422 // The template-id must name a variable template.
2423 VarTemplateDecl *VarTemplate =
Karthik Bhat967c13d2014-05-08 13:16:20 +00002424 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2425 if (!VarTemplate) {
2426 NamedDecl *FnTemplate;
2427 if (auto *OTS = Name.getAsOverloadedTemplate())
2428 FnTemplate = *OTS->begin();
2429 else
2430 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2431 if (FnTemplate)
2432 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2433 << FnTemplate->getDeclName();
Richard Smithbeef3452014-01-16 23:39:20 +00002434 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2435 << IsPartialSpecialization;
Karthik Bhat967c13d2014-05-08 13:16:20 +00002436 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002437
2438 // Check for unexpanded parameter packs in any of the template arguments.
2439 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2440 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2441 UPPC_PartialSpecialization))
2442 return true;
2443
2444 // Check that the template argument list is well-formed for this
2445 // template.
2446 SmallVector<TemplateArgument, 4> Converted;
2447 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2448 false, Converted))
2449 return true;
2450
2451 // Check that the type of this variable template specialization
2452 // matches the expected type.
2453 TypeSourceInfo *ExpectedDI;
2454 {
2455 // Do substitution on the type of the declaration
2456 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2457 Converted.data(), Converted.size());
2458 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002459 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002460 return true;
2461 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2462 ExpectedDI =
2463 SubstType(Templated->getTypeSourceInfo(),
2464 MultiLevelTemplateArgumentList(TemplateArgList),
2465 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2466 }
2467 if (!ExpectedDI)
2468 return true;
2469
Larisse Voufo39a1e502013-08-06 01:03:05 +00002470 // Find the variable template (partial) specialization declaration that
2471 // corresponds to these arguments.
2472 if (IsPartialSpecialization) {
2473 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00002474 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2475 TemplateArgs.size(), Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002476 return true;
2477
2478 bool InstantiationDependent;
2479 if (!Name.isDependent() &&
2480 !TemplateSpecializationType::anyDependentTemplateArguments(
2481 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2482 InstantiationDependent)) {
2483 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2484 << VarTemplate->getDeclName();
2485 IsPartialSpecialization = false;
2486 }
Richard Smith300e0c32013-09-24 04:49:23 +00002487
2488 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2489 Converted)) {
2490 // C++ [temp.class.spec]p9b3:
2491 //
2492 // -- The argument list of the specialization shall not be identical
2493 // to the implicit argument list of the primary template.
2494 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2495 << /*variable template*/ 1
2496 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2497 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2498 // FIXME: Recover from this by treating the declaration as a redeclaration
2499 // of the primary template.
2500 return true;
2501 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002502 }
2503
Craig Topperc3ec1492014-05-26 06:22:03 +00002504 void *InsertPos = nullptr;
2505 VarTemplateSpecializationDecl *PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002506
2507 if (IsPartialSpecialization)
2508 // FIXME: Template parameter list matters too
2509 PrevDecl = VarTemplate->findPartialSpecialization(
2510 Converted.data(), Converted.size(), InsertPos);
2511 else
2512 PrevDecl = VarTemplate->findSpecialization(Converted.data(),
2513 Converted.size(), InsertPos);
2514
Craig Topperc3ec1492014-05-26 06:22:03 +00002515 VarTemplateSpecializationDecl *Specialization = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002516
2517 // Check whether we can declare a variable template specialization in
2518 // the current scope.
2519 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2520 TemplateNameLoc,
2521 IsPartialSpecialization))
2522 return true;
2523
2524 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2525 // Since the only prior variable template specialization with these
2526 // arguments was referenced but not declared, reuse that
2527 // declaration node as our own, updating its source location and
2528 // the list of outer template parameters to reflect our new declaration.
2529 Specialization = PrevDecl;
2530 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002531 PrevDecl = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002532 } else if (IsPartialSpecialization) {
2533 // Create a new class template partial specialization declaration node.
2534 VarTemplatePartialSpecializationDecl *PrevPartial =
2535 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002536 VarTemplatePartialSpecializationDecl *Partial =
2537 VarTemplatePartialSpecializationDecl::Create(
2538 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2539 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
Richard Smithb2f61b42013-08-22 23:27:37 +00002540 Converted.data(), Converted.size(), TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002541
2542 if (!PrevPartial)
2543 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2544 Specialization = Partial;
2545
2546 // If we are providing an explicit specialization of a member variable
2547 // template specialization, make a note of that.
2548 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
Larisse Voufo4cda4612013-08-22 00:28:27 +00002549 PrevPartial->setMemberSpecialization();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002550
2551 // Check that all of the template parameters of the variable template
2552 // partial specialization are deducible from the template
2553 // arguments. If not, this variable template partial specialization
2554 // will never be used.
2555 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2556 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2557 TemplateParams->getDepth(), DeducibleParams);
2558
2559 if (!DeducibleParams.all()) {
2560 unsigned NumNonDeducible =
2561 DeducibleParams.size() - DeducibleParams.count();
2562 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00002563 << /*variable template*/ 1 << (NumNonDeducible > 1)
2564 << SourceRange(TemplateNameLoc, RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002565 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2566 if (!DeducibleParams[I]) {
2567 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2568 if (Param->getDeclName())
2569 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2570 << Param->getDeclName();
2571 else
2572 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00002573 << "(anonymous)";
Larisse Voufo39a1e502013-08-06 01:03:05 +00002574 }
2575 }
2576 }
2577 } else {
2578 // Create a new class template specialization declaration node for
2579 // this explicit specialization or friend declaration.
2580 Specialization = VarTemplateSpecializationDecl::Create(
2581 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2582 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2583 Specialization->setTemplateArgsInfo(TemplateArgs);
2584
2585 if (!PrevDecl)
2586 VarTemplate->AddSpecialization(Specialization, InsertPos);
2587 }
2588
2589 // C++ [temp.expl.spec]p6:
2590 // If a template, a member template or the member of a class template is
2591 // explicitly specialized then that specialization shall be declared
2592 // before the first use of that specialization that would cause an implicit
2593 // instantiation to take place, in every translation unit in which such a
2594 // use occurs; no diagnostic is required.
2595 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2596 bool Okay = false;
2597 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2598 // Is there any previous explicit specialization declaration?
2599 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2600 Okay = true;
2601 break;
2602 }
2603 }
2604
2605 if (!Okay) {
2606 SourceRange Range(TemplateNameLoc, RAngleLoc);
2607 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2608 << Name << Range;
2609
2610 Diag(PrevDecl->getPointOfInstantiation(),
2611 diag::note_instantiation_required_here)
2612 << (PrevDecl->getTemplateSpecializationKind() !=
2613 TSK_ImplicitInstantiation);
2614 return true;
2615 }
2616 }
2617
2618 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2619 Specialization->setLexicalDeclContext(CurContext);
2620
2621 // Add the specialization into its lexical context, so that it can
2622 // be seen when iterating through the list of declarations in that
2623 // context. However, specializations are not found by name lookup.
2624 CurContext->addDecl(Specialization);
2625
2626 // Note that this is an explicit specialization.
2627 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2628
2629 if (PrevDecl) {
2630 // Check that this isn't a redefinition of this specialization,
2631 // merging with previous declarations.
2632 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2633 ForRedeclaration);
2634 PrevSpec.addDecl(PrevDecl);
2635 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
Larisse Voufo4cda4612013-08-22 00:28:27 +00002636 } else if (Specialization->isStaticDataMember() &&
2637 Specialization->isOutOfLine()) {
2638 Specialization->setAccess(VarTemplate->getAccess());
Larisse Voufo39a1e502013-08-06 01:03:05 +00002639 }
2640
2641 // Link instantiations of static data members back to the template from
2642 // which they were instantiated.
2643 if (Specialization->isStaticDataMember())
2644 Specialization->setInstantiationOfStaticDataMember(
2645 VarTemplate->getTemplatedDecl(),
2646 Specialization->getSpecializationKind());
2647
2648 return Specialization;
2649}
2650
2651namespace {
2652/// \brief A partial specialization whose template arguments have matched
2653/// a given template-id.
2654struct PartialSpecMatchResult {
2655 VarTemplatePartialSpecializationDecl *Partial;
2656 TemplateArgumentList *Args;
2657};
2658}
2659
2660DeclResult
2661Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2662 SourceLocation TemplateNameLoc,
2663 const TemplateArgumentListInfo &TemplateArgs) {
2664 assert(Template && "A variable template id without template?");
2665
2666 // Check that the template argument list is well-formed for this template.
2667 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002668 if (CheckTemplateArgumentList(
2669 Template, TemplateNameLoc,
2670 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002671 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002672 return true;
2673
2674 // Find the variable template specialization declaration that
2675 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002676 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002677 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2678 Converted.data(), Converted.size(), InsertPos))
2679 // If we already have a variable template specialization, return it.
2680 return Spec;
2681
2682 // This is the first time we have referenced this variable template
2683 // specialization. Create the canonical declaration and add it to
2684 // the set of specializations, based on the closest partial specialization
2685 // that it represents. That is,
2686 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2687 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2688 Converted.data(), Converted.size());
2689 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2690 bool AmbiguousPartialSpec = false;
2691 typedef PartialSpecMatchResult MatchResult;
2692 SmallVector<MatchResult, 4> Matched;
2693 SourceLocation PointOfInstantiation = TemplateNameLoc;
2694 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2695
2696 // 1. Attempt to find the closest partial specialization that this
2697 // specializes, if any.
2698 // If any of the template arguments is dependent, then this is probably
2699 // a placeholder for an incomplete declarative context; which must be
2700 // complete by instantiation time. Thus, do not search through the partial
2701 // specializations yet.
Larisse Voufo30616382013-08-23 22:21:36 +00002702 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2703 // Perhaps better after unification of DeduceTemplateArguments() and
2704 // getMoreSpecializedPartialSpecialization().
Larisse Voufo39a1e502013-08-06 01:03:05 +00002705 bool InstantiationDependent = false;
2706 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2707 TemplateArgs, InstantiationDependent)) {
2708
2709 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2710 Template->getPartialSpecializations(PartialSpecs);
2711
2712 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2713 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2714 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2715
2716 if (TemplateDeductionResult Result =
2717 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2718 // Store the failed-deduction information for use in diagnostics, later.
Larisse Voufo30616382013-08-23 22:21:36 +00002719 // TODO: Actually use the failed-deduction info?
Larisse Voufo39a1e502013-08-06 01:03:05 +00002720 FailedCandidates.addCandidate()
2721 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2722 (void)Result;
2723 } else {
2724 Matched.push_back(PartialSpecMatchResult());
2725 Matched.back().Partial = Partial;
2726 Matched.back().Args = Info.take();
2727 }
2728 }
2729
Larisse Voufo39a1e502013-08-06 01:03:05 +00002730 if (Matched.size() >= 1) {
2731 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2732 if (Matched.size() == 1) {
2733 // -- If exactly one matching specialization is found, the
2734 // instantiation is generated from that specialization.
2735 // We don't need to do anything for this.
2736 } else {
2737 // -- If more than one matching specialization is found, the
2738 // partial order rules (14.5.4.2) are used to determine
2739 // whether one of the specializations is more specialized
2740 // than the others. If none of the specializations is more
2741 // specialized than all of the other matching
2742 // specializations, then the use of the variable template is
2743 // ambiguous and the program is ill-formed.
2744 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2745 PEnd = Matched.end();
2746 P != PEnd; ++P) {
2747 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2748 PointOfInstantiation) ==
2749 P->Partial)
2750 Best = P;
2751 }
2752
2753 // Determine if the best partial specialization is more specialized than
2754 // the others.
2755 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2756 PEnd = Matched.end();
2757 P != PEnd; ++P) {
2758 if (P != Best && getMoreSpecializedPartialSpecialization(
2759 P->Partial, Best->Partial,
2760 PointOfInstantiation) != Best->Partial) {
2761 AmbiguousPartialSpec = true;
2762 break;
2763 }
2764 }
2765 }
2766
2767 // Instantiate using the best variable template partial specialization.
2768 InstantiationPattern = Best->Partial;
2769 InstantiationArgs = Best->Args;
2770 } else {
2771 // -- If no match is found, the instantiation is generated
2772 // from the primary template.
2773 // InstantiationPattern = Template->getTemplatedDecl();
2774 }
2775 }
2776
Larisse Voufo39a1e502013-08-06 01:03:05 +00002777 // 2. Create the canonical declaration.
2778 // Note that we do not instantiate the variable just yet, since
2779 // instantiation is handled in DoMarkVarDeclReferenced().
2780 // FIXME: LateAttrs et al.?
2781 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2782 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2783 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2784 if (!Decl)
2785 return true;
2786
2787 if (AmbiguousPartialSpec) {
2788 // Partial ordering did not produce a clear winner. Complain.
2789 Decl->setInvalidDecl();
2790 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2791 << Decl;
2792
2793 // Print the matching partial specializations.
2794 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2795 PEnd = Matched.end();
2796 P != PEnd; ++P)
2797 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2798 << getTemplateArgumentBindingsText(
2799 P->Partial->getTemplateParameters(), *P->Args);
2800 return true;
2801 }
2802
2803 if (VarTemplatePartialSpecializationDecl *D =
2804 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2805 Decl->setInstantiationOf(D, InstantiationArgs);
2806
2807 assert(Decl && "No variable template specialization?");
2808 return Decl;
2809}
2810
2811ExprResult
2812Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2813 const DeclarationNameInfo &NameInfo,
2814 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2815 const TemplateArgumentListInfo *TemplateArgs) {
2816
2817 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2818 *TemplateArgs);
2819 if (Decl.isInvalid())
2820 return ExprError();
2821
2822 VarDecl *Var = cast<VarDecl>(Decl.get());
2823 if (!Var->getTemplateSpecializationKind())
2824 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2825 NameInfo.getLoc());
2826
2827 // Build an ordinary singleton decl ref.
2828 return BuildDeclarationNameExpr(SS, NameInfo, Var,
Craig Topperc3ec1492014-05-26 06:22:03 +00002829 /*FoundD=*/nullptr, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002830}
2831
John McCalldadc5752010-08-24 06:29:42 +00002832ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002833 SourceLocation TemplateKWLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00002834 LookupResult &R,
2835 bool RequiresADL,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002836 const TemplateArgumentListInfo *TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00002837 // FIXME: Can we do any checking at this point? I guess we could check the
2838 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00002839 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00002840 // though.
Douglas Gregorb491ed32011-02-19 21:32:49 +00002841 // foo<int> could identify a single function unambiguously
2842 // This approach does NOT work, since f<int>(1);
2843 // gets resolved prior to resorting to overload resolution
2844 // i.e., template<class T> void f(double);
2845 // vs template<class T, class U> void f(U);
John McCalle66edc12009-11-24 19:00:30 +00002846
2847 // These should be filtered out by our callers.
2848 assert(!R.empty() && "empty lookup results when building templateid");
2849 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2850
Larisse Voufo39a1e502013-08-06 01:03:05 +00002851 // In C++1y, check variable template ids.
Richard Smithd7d11ef2014-02-03 20:09:56 +00002852 bool InstantiationDependent;
2853 if (R.getAsSingle<VarTemplateDecl>() &&
2854 !TemplateSpecializationType::anyDependentTemplateArguments(
2855 *TemplateArgs, InstantiationDependent)) {
2856 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2857 R.getAsSingle<VarTemplateDecl>(),
2858 TemplateKWLoc, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002859 }
2860
John McCall58cc69d2010-01-27 01:50:18 +00002861 // We don't want lookup warnings at this point.
2862 R.suppressDiagnostics();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863
John McCalle66edc12009-11-24 19:00:30 +00002864 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002865 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002866 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002867 TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002868 R.getLookupNameInfo(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002869 RequiresADL, TemplateArgs,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002870 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00002871
2872 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00002873}
2874
John McCalle66edc12009-11-24 19:00:30 +00002875// We actually only call this from template instantiation.
John McCalldadc5752010-08-24 06:29:42 +00002876ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002877Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002878 SourceLocation TemplateKWLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002879 const DeclarationNameInfo &NameInfo,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002880 const TemplateArgumentListInfo *TemplateArgs) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002881
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002882 assert(TemplateArgs || TemplateKWLoc.isValid());
John McCalle66edc12009-11-24 19:00:30 +00002883 DeclContext *DC;
2884 if (!(DC = computeDeclContext(SS, false)) ||
2885 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00002886 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00002887 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002888
Douglas Gregor786123d2010-05-21 23:18:07 +00002889 bool MemberOfUnknownSpecialization;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002890 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Craig Topperc3ec1492014-05-26 06:22:03 +00002891 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
Douglas Gregor786123d2010-05-21 23:18:07 +00002892 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00002893
John McCalle66edc12009-11-24 19:00:30 +00002894 if (R.isAmbiguous())
2895 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002896
John McCalle66edc12009-11-24 19:00:30 +00002897 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002898 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2899 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002900 return ExprError();
2901 }
2902
2903 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002904 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
Aaron Ballman4a979672014-01-03 13:56:08 +00002905 << SS.getScopeRep()
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002906 << NameInfo.getName() << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002907 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2908 return ExprError();
2909 }
2910
Abramo Bagnara7945c982012-01-27 09:46:47 +00002911 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00002912}
2913
Douglas Gregorb67535d2009-03-31 00:43:58 +00002914/// \brief Form a dependent template name.
2915///
2916/// This action forms a dependent template name given the template
2917/// name and its (presumably dependent) scope specifier. For
2918/// example, given "MetaFun::template apply", the scope specifier \p
2919/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2920/// of the "template" keyword, and "apply" is the \p Name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002921TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
Douglas Gregorbb119652010-06-16 23:00:59 +00002922 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002923 SourceLocation TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002924 UnqualifiedId &Name,
John McCallba7bf592010-08-24 05:47:05 +00002925 ParsedType ObjectType,
Douglas Gregorbb119652010-06-16 23:00:59 +00002926 bool EnteringContext,
2927 TemplateTy &Result) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00002928 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2929 Diag(TemplateKWLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002930 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002931 diag::warn_cxx98_compat_template_outside_of_template :
2932 diag::ext_template_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002933 << FixItHint::CreateRemoval(TemplateKWLoc);
2934
Craig Topperc3ec1492014-05-26 06:22:03 +00002935 DeclContext *LookupCtx = nullptr;
Douglas Gregor9abe2372010-01-19 16:01:07 +00002936 if (SS.isSet())
2937 LookupCtx = computeDeclContext(SS, EnteringContext);
2938 if (!LookupCtx && ObjectType)
John McCallba7bf592010-08-24 05:47:05 +00002939 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor9abe2372010-01-19 16:01:07 +00002940 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00002941 // C++0x [temp.names]p5:
2942 // If a name prefixed by the keyword template is not the name of
2943 // a template, the program is ill-formed. [Note: the keyword
2944 // template may not be applied to non-template members of class
2945 // templates. -end note ] [ Note: as is the case with the
2946 // typename prefix, the template prefix is allowed in cases
2947 // where it is not strictly necessary; i.e., when the
2948 // nested-name-specifier or the expression on the left of the ->
2949 // or . is not dependent on a template-parameter, or the use
2950 // does not appear in the scope of a template. -end note]
2951 //
2952 // Note: C++03 was more strict here, because it banned the use of
2953 // the "template" keyword prior to a template-name that was not a
2954 // dependent name. C++ DR468 relaxed this requirement (the
2955 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00002956 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor786123d2010-05-21 23:18:07 +00002957 bool MemberOfUnknownSpecialization;
Richard Smithaf416962012-11-15 00:31:27 +00002958 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002959 ObjectType, EnteringContext, Result,
Douglas Gregor786123d2010-05-21 23:18:07 +00002960 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00002961 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2962 isa<CXXRecordDecl>(LookupCtx) &&
Douglas Gregor5ecbb1b2011-03-11 23:27:41 +00002963 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2964 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
Douglas Gregorbb119652010-06-16 23:00:59 +00002965 // This is a dependent template. Handle it below.
Douglas Gregord2e6a452010-01-14 17:47:39 +00002966 } else if (TNK == TNK_Non_template) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002967 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00002968 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002969 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00002970 << Name.getSourceRange()
2971 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00002972 return TNK_Non_template;
Douglas Gregord2e6a452010-01-14 17:47:39 +00002973 } else {
2974 // We found something; return it.
Douglas Gregorbb119652010-06-16 23:00:59 +00002975 return TNK;
Douglas Gregorb67535d2009-03-31 00:43:58 +00002976 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00002977 }
2978
Aaron Ballman4a979672014-01-03 13:56:08 +00002979 NestedNameSpecifier *Qualifier = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002980
Douglas Gregor3cf81312009-11-03 23:16:33 +00002981 switch (Name.getKind()) {
2982 case UnqualifiedId::IK_Identifier:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002983 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorbb119652010-06-16 23:00:59 +00002984 Name.Identifier));
2985 return TNK_Dependent_template_name;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002986
Douglas Gregor71395fa2009-11-04 00:56:37 +00002987 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregorbb119652010-06-16 23:00:59 +00002988 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002989 Name.OperatorFunctionId.Operator));
Richard Smith72bfbd82013-12-04 00:28:23 +00002990 return TNK_Function_template;
Alexis Hunted0530f2009-11-28 08:58:14 +00002991
2992 case UnqualifiedId::IK_LiteralOperatorId:
Richard Smithd091dc12013-12-05 00:58:33 +00002993 llvm_unreachable("literal operator id cannot have a dependent scope");
Alexis Hunted0530f2009-11-28 08:58:14 +00002994
Douglas Gregor3cf81312009-11-03 23:16:33 +00002995 default:
2996 break;
2997 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002998
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002999 Diag(Name.getLocStart(),
Douglas Gregor3cf81312009-11-03 23:16:33 +00003000 diag::err_template_kw_refers_to_non_template)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003001 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregorb22ee882010-05-05 05:58:24 +00003002 << Name.getSourceRange()
3003 << TemplateKWLoc;
Douglas Gregorbb119652010-06-16 23:00:59 +00003004 return TNK_Non_template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00003005}
3006
Mike Stump11289f42009-09-09 15:08:12 +00003007bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00003008 const TemplateArgumentLoc &AL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003009 SmallVectorImpl<TemplateArgument> &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00003010 const TemplateArgument &Arg = AL.getArgument();
3011
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003012 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003013 switch(Arg.getKind()) {
3014 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003015 // C++ [temp.arg.type]p1:
3016 // A template-argument for a template-parameter which is a
3017 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003018 break;
3019 case TemplateArgument::Template: {
3020 // We have a template type parameter but the template argument
3021 // is a template without any arguments.
3022 SourceRange SR = AL.getSourceRange();
3023 TemplateName Name = Arg.getAsTemplate();
3024 Diag(SR.getBegin(), diag::err_template_missing_args)
3025 << Name << SR;
3026 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3027 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003028
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003029 return true;
3030 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003031 case TemplateArgument::Expression: {
3032 // We have a template type parameter but the template argument is an
3033 // expression; see if maybe it is missing the "typename" keyword.
3034 CXXScopeSpec SS;
3035 DeclarationNameInfo NameInfo;
3036
3037 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3038 SS.Adopt(ArgExpr->getQualifierLoc());
3039 NameInfo = ArgExpr->getNameInfo();
3040 } else if (DependentScopeDeclRefExpr *ArgExpr =
3041 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3042 SS.Adopt(ArgExpr->getQualifierLoc());
3043 NameInfo = ArgExpr->getNameInfo();
3044 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3045 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003046 if (ArgExpr->isImplicitAccess()) {
3047 SS.Adopt(ArgExpr->getQualifierLoc());
3048 NameInfo = ArgExpr->getMemberNameInfo();
3049 }
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003050 }
3051
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003052 if (NameInfo.getName().isIdentifier()) {
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003053 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3054 LookupParsedName(Result, CurScope, &SS);
3055
Kaelyn Uhrain055e9472012-06-08 01:07:26 +00003056 if (Result.getAsSingle<TypeDecl>() ||
3057 Result.getResultKind() ==
3058 LookupResult::NotFoundInCurrentInstantiation) {
3059 // FIXME: Add a FixIt and fix up the template argument for recovery.
Kaelyn Uhrain864d0b02012-05-18 23:42:49 +00003060 SourceLocation Loc = AL.getSourceRange().getBegin();
3061 Diag(Loc, diag::err_template_arg_must_be_type_suggest);
3062 Diag(Param->getLocation(), diag::note_template_param_here);
3063 return true;
3064 }
3065 }
3066 // fallthrough
3067 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003068 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003069 // We have a template type parameter but the template argument
3070 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00003071 SourceRange SR = AL.getSourceRange();
3072 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003073 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003074
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003075 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003076 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00003077 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003078
John McCallbcd03502009-12-07 02:54:59 +00003079 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003080 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003081
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003082 // Add the converted template type argument.
Douglas Gregore46db902011-06-17 22:11:49 +00003083 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
3084
3085 // Objective-C ARC:
3086 // If an explicitly-specified template argument type is a lifetime type
3087 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003088 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00003089 ArgType->isObjCLifetimeType() &&
3090 !ArgType.getObjCLifetime()) {
3091 Qualifiers Qs;
3092 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3093 ArgType = Context.getQualifiedType(ArgType, Qs);
3094 }
3095
3096 Converted.push_back(TemplateArgument(ArgType));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00003097 return false;
3098}
3099
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003100/// \brief Substitute template arguments into the default template argument for
3101/// the given template type parameter.
3102///
3103/// \param SemaRef the semantic analysis object for which we are performing
3104/// the substitution.
3105///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003106/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003107/// for.
3108///
3109/// \param TemplateLoc the location of the template name that started the
3110/// template-id we are checking.
3111///
3112/// \param RAngleLoc the location of the right angle bracket ('>') that
3113/// terminates the template-id.
3114///
3115/// \param Param the template template parameter whose default we are
3116/// substituting into.
3117///
3118/// \param Converted the list of template arguments provided for template
3119/// parameters that precede \p Param in the template parameter list.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003120/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00003121static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003122SubstDefaultTemplateArgument(Sema &SemaRef,
3123 TemplateDecl *Template,
3124 SourceLocation TemplateLoc,
3125 SourceLocation RAngleLoc,
3126 TemplateTypeParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003127 SmallVectorImpl<TemplateArgument> &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00003128 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003129
3130 // If the argument type is dependent, instantiate it now based
3131 // on the previously-computed template arguments.
3132 if (ArgType->getType()->isDependentType()) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003133 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003134 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003135 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003136 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003137 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003138
David Majnemer89189202013-08-28 23:48:32 +00003139 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3140 Converted.data(), Converted.size());
3141
3142 // Only substitute for the innermost template argument list.
3143 MultiLevelTemplateArgumentList TemplateArgLists;
3144 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3145 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3146 TemplateArgLists.addOuterTemplateArguments(None);
3147
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003148 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003149 ArgType =
3150 SemaRef.SubstType(ArgType, TemplateArgLists,
3151 Param->getDefaultArgumentLoc(), Param->getDeclName());
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003152 }
3153
3154 return ArgType;
3155}
3156
3157/// \brief Substitute template arguments into the default template argument for
3158/// the given non-type template parameter.
3159///
3160/// \param SemaRef the semantic analysis object for which we are performing
3161/// the substitution.
3162///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163/// \param Template the template that we are synthesizing template arguments
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003164/// for.
3165///
3166/// \param TemplateLoc the location of the template name that started the
3167/// template-id we are checking.
3168///
3169/// \param RAngleLoc the location of the right angle bracket ('>') that
3170/// terminates the template-id.
3171///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003172/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003173/// substituting into.
3174///
3175/// \param Converted the list of template arguments provided for template
3176/// parameters that precede \p Param in the template parameter list.
3177///
3178/// \returns the substituted template argument, or NULL if an error occurred.
John McCalldadc5752010-08-24 06:29:42 +00003179static ExprResult
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003180SubstDefaultTemplateArgument(Sema &SemaRef,
3181 TemplateDecl *Template,
3182 SourceLocation TemplateLoc,
3183 SourceLocation RAngleLoc,
3184 NonTypeTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003185 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003186 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Richard Smith80934652012-07-16 01:09:10 +00003187 Template, Converted,
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003188 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003189 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003190 return ExprError();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003191
David Majnemer89189202013-08-28 23:48:32 +00003192 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3193 Converted.data(), Converted.size());
3194
3195 // Only substitute for the innermost template argument list.
3196 MultiLevelTemplateArgumentList TemplateArgLists;
3197 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3198 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3199 TemplateArgLists.addOuterTemplateArguments(None);
3200
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003201 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
Eli Friedmanc25372b2012-04-26 22:43:24 +00003202 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
David Majnemer89189202013-08-28 23:48:32 +00003203 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00003204}
3205
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003206/// \brief Substitute template arguments into the default template argument for
3207/// the given template template parameter.
3208///
3209/// \param SemaRef the semantic analysis object for which we are performing
3210/// the substitution.
3211///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003212/// \param Template the template that we are synthesizing template arguments
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003213/// for.
3214///
3215/// \param TemplateLoc the location of the template name that started the
3216/// template-id we are checking.
3217///
3218/// \param RAngleLoc the location of the right angle bracket ('>') that
3219/// terminates the template-id.
3220///
3221/// \param Param the template template parameter whose default we are
3222/// substituting into.
3223///
3224/// \param Converted the list of template arguments provided for template
3225/// parameters that precede \p Param in the template parameter list.
3226///
Douglas Gregordf846d12011-03-02 18:46:51 +00003227/// \param QualifierLoc Will be set to the nested-name-specifier (with
3228/// source-location information) that precedes the template name.
Douglas Gregor9d802122011-03-02 17:09:35 +00003229///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003230/// \returns the substituted template argument, or NULL if an error occurred.
3231static TemplateName
3232SubstDefaultTemplateArgument(Sema &SemaRef,
3233 TemplateDecl *Template,
3234 SourceLocation TemplateLoc,
3235 SourceLocation RAngleLoc,
3236 TemplateTemplateParmDecl *Param,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003237 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor9d802122011-03-02 17:09:35 +00003238 NestedNameSpecifierLoc &QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003239 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003240 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003241 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003242 return TemplateName();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243
David Majnemer89189202013-08-28 23:48:32 +00003244 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3245 Converted.data(), Converted.size());
3246
3247 // Only substitute for the innermost template argument list.
3248 MultiLevelTemplateArgumentList TemplateArgLists;
3249 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3250 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3251 TemplateArgLists.addOuterTemplateArguments(None);
3252
Argyrios Kyrtzidis6fe744c2012-04-25 18:39:17 +00003253 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
David Majnemer89189202013-08-28 23:48:32 +00003254 // Substitute into the nested-name-specifier first,
Douglas Gregordf846d12011-03-02 18:46:51 +00003255 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
Douglas Gregor9d802122011-03-02 17:09:35 +00003256 if (QualifierLoc) {
David Majnemer89189202013-08-28 23:48:32 +00003257 QualifierLoc =
3258 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
Douglas Gregor9d802122011-03-02 17:09:35 +00003259 if (!QualifierLoc)
3260 return TemplateName();
3261 }
David Majnemer89189202013-08-28 23:48:32 +00003262
3263 return SemaRef.SubstTemplateName(
3264 QualifierLoc,
3265 Param->getDefaultArgument().getArgument().getAsTemplate(),
3266 Param->getDefaultArgument().getTemplateNameLoc(),
3267 TemplateArgLists);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003268}
3269
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003270/// \brief If the given template parameter has a default template
3271/// argument, substitute into that default template argument and
3272/// return the corresponding template argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273TemplateArgumentLoc
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003274Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3275 SourceLocation TemplateLoc,
3276 SourceLocation RAngleLoc,
3277 Decl *Param,
Richard Smithc87b9382013-07-04 01:01:24 +00003278 SmallVectorImpl<TemplateArgument>
3279 &Converted,
3280 bool &HasDefaultArg) {
3281 HasDefaultArg = false;
3282
3283 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003284 if (!TypeParm->hasDefaultArgument())
3285 return TemplateArgumentLoc();
3286
Richard Smithc87b9382013-07-04 01:01:24 +00003287 HasDefaultArg = true;
John McCallbcd03502009-12-07 02:54:59 +00003288 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003289 TemplateLoc,
3290 RAngleLoc,
3291 TypeParm,
3292 Converted);
3293 if (DI)
3294 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3295
3296 return TemplateArgumentLoc();
3297 }
3298
3299 if (NonTypeTemplateParmDecl *NonTypeParm
3300 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3301 if (!NonTypeParm->hasDefaultArgument())
3302 return TemplateArgumentLoc();
3303
Richard Smithc87b9382013-07-04 01:01:24 +00003304 HasDefaultArg = true;
John McCalldadc5752010-08-24 06:29:42 +00003305 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor9d802122011-03-02 17:09:35 +00003306 TemplateLoc,
3307 RAngleLoc,
3308 NonTypeParm,
3309 Converted);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003310 if (Arg.isInvalid())
3311 return TemplateArgumentLoc();
3312
3313 Expr *ArgE = Arg.takeAs<Expr>();
3314 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3315 }
3316
3317 TemplateTemplateParmDecl *TempTempParm
3318 = cast<TemplateTemplateParmDecl>(Param);
3319 if (!TempTempParm->hasDefaultArgument())
3320 return TemplateArgumentLoc();
3321
Richard Smithc87b9382013-07-04 01:01:24 +00003322 HasDefaultArg = true;
Douglas Gregordf846d12011-03-02 18:46:51 +00003323 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003324 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003325 TemplateLoc,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003326 RAngleLoc,
3327 TempTempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003328 Converted,
3329 QualifierLoc);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003330 if (TName.isNull())
3331 return TemplateArgumentLoc();
3332
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003333 return TemplateArgumentLoc(TemplateArgument(TName),
Douglas Gregor9d802122011-03-02 17:09:35 +00003334 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003335 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3336}
3337
Douglas Gregorda0fb532009-11-11 19:31:23 +00003338/// \brief Check that the given template argument corresponds to the given
3339/// template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003340///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341/// \param Param The template parameter against which the argument will be
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003342/// checked.
3343///
3344/// \param Arg The template argument.
3345///
3346/// \param Template The template in which the template argument resides.
3347///
3348/// \param TemplateLoc The location of the template name for the template
3349/// whose argument list we're matching.
3350///
3351/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3352/// the template argument list.
3353///
3354/// \param ArgumentPackIndex The index into the argument pack where this
3355/// argument will be placed. Only valid if the parameter is a parameter pack.
3356///
3357/// \param Converted The checked, converted argument will be added to the
3358/// end of this small vector.
3359///
3360/// \param CTAK Describes how we arrived at this particular template argument:
3361/// explicitly written, deduced, etc.
3362///
3363/// \returns true on error, false otherwise.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003364bool Sema::CheckTemplateArgument(NamedDecl *Param,
3365 const TemplateArgumentLoc &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00003366 NamedDecl *Template,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003367 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003368 SourceLocation RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003369 unsigned ArgumentPackIndex,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003370 SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003371 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00003372 // Check template type parameters.
3373 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003374 return CheckTemplateTypeArgument(TTP, Arg, Converted);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375
Douglas Gregoreebed722009-11-11 19:41:09 +00003376 // Check non-type template parameters.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003378 // Do substitution on the type of the non-type template parameter
Peter Collingbourne01687632010-12-10 17:08:53 +00003379 // with the template arguments we've seen thus far. But if the
3380 // template has a dependent context then we cannot substitute yet.
Douglas Gregorda0fb532009-11-11 19:31:23 +00003381 QualType NTTPType = NTTP->getType();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003382 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3383 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
Peter Collingbourne01687632010-12-10 17:08:53 +00003385 if (NTTPType->isDependentType() &&
3386 !isa<TemplateTemplateParmDecl>(Template) &&
3387 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003388 // Do substitution on the type of the non-type template parameter.
3389 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003390 NTTP, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003391 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003392 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003393 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394
3395 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003396 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003397 NTTPType = SubstType(NTTPType,
3398 MultiLevelTemplateArgumentList(TemplateArgs),
3399 NTTP->getLocation(),
3400 NTTP->getDeclName());
3401 // If that worked, check the non-type template parameter type
3402 // for validity.
3403 if (!NTTPType.isNull())
3404 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3405 NTTP->getLocation());
3406 if (NTTPType.isNull())
3407 return true;
3408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409
Douglas Gregorda0fb532009-11-11 19:31:23 +00003410 switch (Arg.getArgument().getKind()) {
3411 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003412 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003413
Douglas Gregorda0fb532009-11-11 19:31:23 +00003414 case TemplateArgument::Expression: {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003415 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003416 ExprResult Res =
3417 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3418 Result, CTAK);
3419 if (Res.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003420 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003422 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003423 break;
3424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003425
Douglas Gregorda0fb532009-11-11 19:31:23 +00003426 case TemplateArgument::Declaration:
3427 case TemplateArgument::Integral:
Eli Friedmanb826a002012-09-26 02:36:12 +00003428 case TemplateArgument::NullPtr:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003429 // We've already checked this template argument, so just copy
3430 // it to the list of converted arguments.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003431 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003432 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433
Douglas Gregorda0fb532009-11-11 19:31:23 +00003434 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003435 case TemplateArgument::TemplateExpansion:
Douglas Gregorda0fb532009-11-11 19:31:23 +00003436 // We were given a template template argument. It may not be ill-formed;
3437 // see below.
3438 if (DependentTemplateName *DTN
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003439 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3440 .getAsDependentTemplateName()) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00003441 // We have a template argument such as \c T::template X, which we
3442 // parsed as a template template argument. However, since we now
3443 // know that we need a non-type template argument, convert this
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003444 // template name into an expression.
3445
3446 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3447 Arg.getTemplateNameLoc());
3448
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003449 CXXScopeSpec SS;
Douglas Gregor9d802122011-03-02 17:09:35 +00003450 SS.Adopt(Arg.getTemplateQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +00003451 // FIXME: the template-template arg was a DependentTemplateName,
3452 // so it was provided with a template keyword. However, its source
3453 // location is not stored in the template argument structure.
3454 SourceLocation TemplateKWLoc;
John Wiegley01296292011-04-08 18:41:53 +00003455 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
Douglas Gregor3a43fd62011-02-25 20:49:16 +00003456 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003457 TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00003458 NameInfo,
3459 nullptr));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003461 // If we parsed the template argument as a pack expansion, create a
3462 // pack expansion expression.
3463 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
John Wiegley01296292011-04-08 18:41:53 +00003464 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
3465 if (E.isInvalid())
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003466 return true;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468
Douglas Gregorda0fb532009-11-11 19:31:23 +00003469 TemplateArgument Result;
John Wiegley01296292011-04-08 18:41:53 +00003470 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
3471 if (E.isInvalid())
Douglas Gregorda0fb532009-11-11 19:31:23 +00003472 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003474 Converted.push_back(Result);
Douglas Gregorda0fb532009-11-11 19:31:23 +00003475 break;
3476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477
Douglas Gregorda0fb532009-11-11 19:31:23 +00003478 // We have a template argument that actually does refer to a class
Richard Smith3f1b5d02011-05-05 21:57:07 +00003479 // template, alias template, or template template parameter, and
Douglas Gregorda0fb532009-11-11 19:31:23 +00003480 // therefore cannot be a non-type template argument.
3481 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3482 << Arg.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregorda0fb532009-11-11 19:31:23 +00003484 Diag(Param->getLocation(), diag::note_template_param_here);
3485 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486
Douglas Gregorda0fb532009-11-11 19:31:23 +00003487 case TemplateArgument::Type: {
3488 // We have a non-type template parameter but the template
3489 // argument is a type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Douglas Gregorda0fb532009-11-11 19:31:23 +00003491 // C++ [temp.arg]p2:
3492 // In a template-argument, an ambiguity between a type-id and
3493 // an expression is resolved to a type-id, regardless of the
3494 // form of the corresponding template-parameter.
3495 //
3496 // We warn specifically about this case, since it can be rather
3497 // confusing for users.
3498 QualType T = Arg.getArgument().getAsType();
3499 SourceRange SR = Arg.getSourceRange();
3500 if (T->isFunctionType())
3501 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3502 else
3503 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3504 Diag(Param->getLocation(), diag::note_template_param_here);
3505 return true;
3506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507
Douglas Gregorda0fb532009-11-11 19:31:23 +00003508 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003509 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003511
Douglas Gregorda0fb532009-11-11 19:31:23 +00003512 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003513 }
3514
3515
Douglas Gregorda0fb532009-11-11 19:31:23 +00003516 // Check template template parameters.
3517 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518
Douglas Gregorda0fb532009-11-11 19:31:23 +00003519 // Substitute into the template parameter list of the template
3520 // template parameter, since previously-supplied template arguments
3521 // may appear within the template template parameter.
3522 {
3523 // Set up a template instantiation context.
3524 LocalInstantiationScope Scope(*this);
3525 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Richard Smith80934652012-07-16 01:09:10 +00003526 TempParm, Converted,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003527 SourceRange(TemplateLoc, RAngleLoc));
Alp Tokerd4a72d52013-10-08 08:09:04 +00003528 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003529 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003530
3531 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003532 Converted.data(), Converted.size());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003533 TempParm = cast_or_null<TemplateTemplateParmDecl>(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534 SubstDecl(TempParm, CurContext,
Douglas Gregorda0fb532009-11-11 19:31:23 +00003535 MultiLevelTemplateArgumentList(TemplateArgs)));
3536 if (!TempParm)
3537 return true;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539
Douglas Gregorda0fb532009-11-11 19:31:23 +00003540 switch (Arg.getArgument().getKind()) {
3541 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00003542 llvm_unreachable("Should never see a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543
Douglas Gregorda0fb532009-11-11 19:31:23 +00003544 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003545 case TemplateArgument::TemplateExpansion:
Richard Smith1fde8ec2012-09-07 02:06:42 +00003546 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003547 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003549 Converted.push_back(Arg.getArgument());
Douglas Gregorda0fb532009-11-11 19:31:23 +00003550 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Douglas Gregorda0fb532009-11-11 19:31:23 +00003552 case TemplateArgument::Expression:
3553 case TemplateArgument::Type:
3554 // We have a template template parameter but the template
3555 // argument does not refer to a template.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003556 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003557 << getLangOpts().CPlusPlus11;
Douglas Gregorda0fb532009-11-11 19:31:23 +00003558 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559
Douglas Gregorda0fb532009-11-11 19:31:23 +00003560 case TemplateArgument::Declaration:
David Blaikie8a40f702012-01-17 06:56:22 +00003561 llvm_unreachable("Declaration argument with template template parameter");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003562 case TemplateArgument::Integral:
David Blaikie8a40f702012-01-17 06:56:22 +00003563 llvm_unreachable("Integral argument with template template parameter");
Eli Friedmanb826a002012-09-26 02:36:12 +00003564 case TemplateArgument::NullPtr:
3565 llvm_unreachable("Null pointer argument with template template parameter");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregorda0fb532009-11-11 19:31:23 +00003567 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00003568 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00003569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003570
Douglas Gregorda0fb532009-11-11 19:31:23 +00003571 return false;
3572}
3573
Douglas Gregor8e072612012-02-03 07:34:46 +00003574/// \brief Diagnose an arity mismatch in the
3575static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3576 SourceLocation TemplateLoc,
3577 TemplateArgumentListInfo &TemplateArgs) {
3578 TemplateParameterList *Params = Template->getTemplateParameters();
3579 unsigned NumParams = Params->size();
3580 unsigned NumArgs = TemplateArgs.size();
3581
3582 SourceRange Range;
3583 if (NumArgs > NumParams)
3584 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3585 TemplateArgs.getRAngleLoc());
3586 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3587 << (NumArgs > NumParams)
3588 << (isa<ClassTemplateDecl>(Template)? 0 :
3589 isa<FunctionTemplateDecl>(Template)? 1 :
3590 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3591 << Template << Range;
3592 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3593 << Params->getSourceRange();
3594 return true;
3595}
3596
Richard Smith1fde8ec2012-09-07 02:06:42 +00003597/// \brief Check whether the template parameter is a pack expansion, and if so,
3598/// determine the number of parameters produced by that expansion. For instance:
3599///
3600/// \code
3601/// template<typename ...Ts> struct A {
3602/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3603/// };
3604/// \endcode
3605///
3606/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3607/// is not a pack expansion, so returns an empty Optional.
David Blaikie05785d12013-02-20 22:23:23 +00003608static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003609 if (NonTypeTemplateParmDecl *NTTP
3610 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3611 if (NTTP->isExpandedParameterPack())
3612 return NTTP->getNumExpansionTypes();
3613 }
3614
3615 if (TemplateTemplateParmDecl *TTP
3616 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3617 if (TTP->isExpandedParameterPack())
3618 return TTP->getNumExpansionTemplateParameters();
3619 }
3620
David Blaikie7a30dc52013-02-21 01:47:18 +00003621 return None;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003622}
3623
Douglas Gregord32e0282009-02-09 23:23:08 +00003624/// \brief Check that the given template argument list is well-formed
3625/// for specializing the given template.
3626bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3627 SourceLocation TemplateLoc,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003628 TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00003629 bool PartialTemplateArgs,
Richard Smith83b11aa2014-01-09 02:22:22 +00003630 SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00003631 TemplateParameterList *Params = Template->getTemplateParameters();
Douglas Gregord32e0282009-02-09 23:23:08 +00003632
John McCall6b51f282009-11-23 01:53:49 +00003633 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3634
Mike Stump11289f42009-09-09 15:08:12 +00003635 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00003636 // [...] The type and form of each template-argument specified in
3637 // a template-id shall match the type and form specified for the
3638 // corresponding parameter declared by the template in its
3639 // template-parameter-list.
Douglas Gregor739b107a2011-03-03 02:41:12 +00003640 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003641 SmallVector<TemplateArgument, 2> ArgumentPack;
Richard Smith1fde8ec2012-09-07 02:06:42 +00003642 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003643 LocalInstantiationScope InstScope(*this, true);
Richard Smith1fde8ec2012-09-07 02:06:42 +00003644 for (TemplateParameterList::iterator Param = Params->begin(),
3645 ParamEnd = Params->end();
3646 Param != ParamEnd; /* increment in loop */) {
3647 // If we have an expanded parameter pack, make sure we don't have too
3648 // many arguments.
David Blaikie05785d12013-02-20 22:23:23 +00003649 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
Richard Smith1fde8ec2012-09-07 02:06:42 +00003650 if (*Expansions == ArgumentPack.size()) {
3651 // We're done with this parameter pack. Pack up its arguments and add
3652 // them to the list.
Eli Friedmanb826a002012-09-26 02:36:12 +00003653 Converted.push_back(
3654 TemplateArgument::CreatePackCopy(Context,
3655 ArgumentPack.data(),
3656 ArgumentPack.size()));
3657 ArgumentPack.clear();
3658
Richard Smith1fde8ec2012-09-07 02:06:42 +00003659 // This argument is assigned to the next parameter.
3660 ++Param;
3661 continue;
3662 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3663 // Not enough arguments for this parameter pack.
3664 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3665 << false
3666 << (isa<ClassTemplateDecl>(Template)? 0 :
3667 isa<FunctionTemplateDecl>(Template)? 1 :
3668 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3669 << Template;
3670 Diag(Template->getLocation(), diag::note_template_decl_here)
3671 << Params->getSourceRange();
3672 return true;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003673 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003675
Richard Smith1fde8ec2012-09-07 02:06:42 +00003676 if (ArgIdx < NumArgs) {
Douglas Gregor84d49a22009-11-11 21:54:23 +00003677 // Check the template argument we were given.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3679 TemplateLoc, RAngleLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003680 ArgumentPack.size(), Converted))
Douglas Gregor84d49a22009-11-11 21:54:23 +00003681 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682
Richard Smith83b11aa2014-01-09 02:22:22 +00003683 if (TemplateArgs[ArgIdx].getArgument().isPackExpansion() &&
3684 isa<TypeAliasTemplateDecl>(Template) &&
3685 !(Param + 1 == ParamEnd && (*Param)->isTemplateParameterPack() &&
3686 !getExpandedPackSize(*Param))) {
3687 // Core issue 1430: we have a pack expansion as an argument to an
3688 // alias template, and it's not part of a final parameter pack. This
3689 // can't be canonicalized, so reject it now.
3690 Diag(TemplateArgs[ArgIdx].getLocation(),
3691 diag::err_alias_template_expansion_into_fixed_list)
3692 << TemplateArgs[ArgIdx].getSourceRange();
3693 Diag((*Param)->getLocation(), diag::note_template_param_here);
3694 return true;
3695 }
3696
Richard Smith1fde8ec2012-09-07 02:06:42 +00003697 // We're now done with this argument.
3698 ++ArgIdx;
3699
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003700 if ((*Param)->isTemplateParameterPack()) {
3701 // The template parameter was a template parameter pack, so take the
3702 // deduced argument and place it on the argument pack. Note that we
3703 // stay on the same template parameter so that we can deduce more
3704 // arguments.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003705 ArgumentPack.push_back(Converted.pop_back_val());
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003706 } else {
3707 // Move to the next template parameter.
3708 ++Param;
3709 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003710
3711 // If we just saw a pack expansion, then directly convert the remaining
3712 // arguments, because we don't know what parameters they'll match up
3713 // with.
3714 if (TemplateArgs[ArgIdx-1].getArgument().isPackExpansion()) {
3715 bool InFinalParameterPack = Param != ParamEnd &&
3716 Param + 1 == ParamEnd &&
3717 (*Param)->isTemplateParameterPack() &&
3718 !getExpandedPackSize(*Param);
3719
3720 if (!InFinalParameterPack && !ArgumentPack.empty()) {
3721 // If we were part way through filling in an expanded parameter pack,
3722 // fall back to just producing individual arguments.
3723 Converted.insert(Converted.end(),
3724 ArgumentPack.begin(), ArgumentPack.end());
3725 ArgumentPack.clear();
3726 }
3727
3728 while (ArgIdx < NumArgs) {
3729 if (InFinalParameterPack)
3730 ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3731 else
3732 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3733 ++ArgIdx;
3734 }
3735
3736 // Push the argument pack onto the list of converted arguments.
3737 if (InFinalParameterPack) {
Eli Friedmanb826a002012-09-26 02:36:12 +00003738 Converted.push_back(
3739 TemplateArgument::CreatePackCopy(Context,
3740 ArgumentPack.data(),
3741 ArgumentPack.size()));
3742 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003743 }
3744
3745 return false;
Douglas Gregor8e072612012-02-03 07:34:46 +00003746 }
Richard Smith1fde8ec2012-09-07 02:06:42 +00003747
Douglas Gregor84d49a22009-11-11 21:54:23 +00003748 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00003749 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750
Douglas Gregor2f157c92011-06-03 02:59:40 +00003751 // If we're checking a partial template argument list, we're done.
3752 if (PartialTemplateArgs) {
3753 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3754 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3755 ArgumentPack.data(),
3756 ArgumentPack.size()));
3757
Richard Smith1fde8ec2012-09-07 02:06:42 +00003758 return false;
Douglas Gregor2f157c92011-06-03 02:59:40 +00003759 }
3760
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 // If we have a template parameter pack with no more corresponding
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003762 // arguments, just break out now and we'll fill in the argument pack below.
Richard Smith1fde8ec2012-09-07 02:06:42 +00003763 if ((*Param)->isTemplateParameterPack()) {
3764 assert(!getExpandedPackSize(*Param) &&
3765 "Should have dealt with this already");
3766
3767 // A non-expanded parameter pack before the end of the parameter list
3768 // only occurs for an ill-formed template parameter list, unless we've
3769 // got a partial argument list for a function template, so just bail out.
3770 if (Param + 1 != ParamEnd)
3771 return true;
3772
Eli Friedmanb826a002012-09-26 02:36:12 +00003773 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3774 ArgumentPack.data(),
3775 ArgumentPack.size()));
3776 ArgumentPack.clear();
Richard Smith1fde8ec2012-09-07 02:06:42 +00003777
3778 ++Param;
3779 continue;
3780 }
3781
Douglas Gregor8e072612012-02-03 07:34:46 +00003782 // Check whether we have a default argument.
Douglas Gregor84d49a22009-11-11 21:54:23 +00003783 TemplateArgumentLoc Arg;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784
Douglas Gregor84d49a22009-11-11 21:54:23 +00003785 // Retrieve the default template argument from the template
3786 // parameter. For each kind of template parameter, we substitute the
3787 // template arguments provided thus far and any "outer" template arguments
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788 // (when the template parameter was part of a nested template) into
Douglas Gregor84d49a22009-11-11 21:54:23 +00003789 // the default argument.
3790 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003791 if (!TTP->hasDefaultArgument())
3792 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3793 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003794
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003796 Template,
3797 TemplateLoc,
3798 RAngleLoc,
3799 TTP,
3800 Converted);
3801 if (!ArgType)
3802 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803
Douglas Gregor84d49a22009-11-11 21:54:23 +00003804 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3805 ArgType);
3806 } else if (NonTypeTemplateParmDecl *NTTP
3807 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
Douglas Gregor8e072612012-02-03 07:34:46 +00003808 if (!NTTP->hasDefaultArgument())
3809 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3810 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003811
John McCalldadc5752010-08-24 06:29:42 +00003812 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003813 TemplateLoc,
3814 RAngleLoc,
3815 NTTP,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003816 Converted);
3817 if (E.isInvalid())
3818 return true;
3819
3820 Expr *Ex = E.takeAs<Expr>();
3821 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3822 } else {
3823 TemplateTemplateParmDecl *TempParm
3824 = cast<TemplateTemplateParmDecl>(*Param);
3825
Douglas Gregor8e072612012-02-03 07:34:46 +00003826 if (!TempParm->hasDefaultArgument())
3827 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3828 TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003829
Douglas Gregordf846d12011-03-02 18:46:51 +00003830 NestedNameSpecifierLoc QualifierLoc;
Douglas Gregor84d49a22009-11-11 21:54:23 +00003831 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832 TemplateLoc,
3833 RAngleLoc,
Douglas Gregor84d49a22009-11-11 21:54:23 +00003834 TempParm,
Douglas Gregor9d802122011-03-02 17:09:35 +00003835 Converted,
3836 QualifierLoc);
Douglas Gregor84d49a22009-11-11 21:54:23 +00003837 if (Name.isNull())
3838 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003839
Douglas Gregor9d802122011-03-02 17:09:35 +00003840 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3841 TempParm->getDefaultArgument().getTemplateNameLoc());
Douglas Gregor84d49a22009-11-11 21:54:23 +00003842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843
Douglas Gregor84d49a22009-11-11 21:54:23 +00003844 // Introduce an instantiation record that describes where we are using
3845 // the default template argument.
Alp Tokerd4a72d52013-10-08 08:09:04 +00003846 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3847 SourceRange(TemplateLoc, RAngleLoc));
3848 if (Inst.isInvalid())
Richard Smith8a874c92012-07-08 02:38:24 +00003849 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850
Douglas Gregor84d49a22009-11-11 21:54:23 +00003851 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00003852 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00003853 RAngleLoc, 0, Converted))
Douglas Gregorda0fb532009-11-11 19:31:23 +00003854 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003855
Douglas Gregor739b107a2011-03-03 02:41:12 +00003856 // Core issue 150 (assumed resolution): if this is a template template
3857 // parameter, keep track of the default template arguments from the
3858 // template definition.
3859 if (isTemplateTemplateParameter)
3860 TemplateArgs.addArgument(Arg);
3861
Douglas Gregor9abeaf52010-12-20 16:57:52 +00003862 // Move to the next template parameter and argument.
3863 ++Param;
3864 ++ArgIdx;
Douglas Gregord32e0282009-02-09 23:23:08 +00003865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003866
Douglas Gregor8e072612012-02-03 07:34:46 +00003867 // If we have any leftover arguments, then there were too many arguments.
3868 // Complain and fail.
3869 if (ArgIdx < NumArgs)
3870 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871
Richard Smith1fde8ec2012-09-07 02:06:42 +00003872 return false;
Douglas Gregord32e0282009-02-09 23:23:08 +00003873}
3874
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003875namespace {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876 class UnnamedLocalNoLinkageFinder
3877 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003878 {
3879 Sema &S;
3880 SourceRange SR;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003882 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003884 public:
3885 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3886
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887 bool Visit(QualType T) {
3888 return inherited::Visit(T.getTypePtr());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003889 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003890
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003891#define TYPE(Class, Parent) \
3892 bool Visit##Class##Type(const Class##Type *);
3893#define ABSTRACT_TYPE(Class, Parent) \
3894 bool Visit##Class##Type(const Class##Type *) { return false; }
3895#define NON_CANONICAL_TYPE(Class, Parent) \
3896 bool Visit##Class##Type(const Class##Type *) { return false; }
3897#include "clang/AST/TypeNodes.def"
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003898
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003899 bool VisitTagDecl(const TagDecl *Tag);
3900 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3901 };
3902}
3903
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003905 return false;
3906}
3907
3908bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3909 return Visit(T->getElementType());
3910}
3911
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003913 return Visit(T->getPointeeType());
3914}
3915
3916bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917 const BlockPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003918 return Visit(T->getPointeeType());
3919}
3920
3921bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922 const LValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003923 return Visit(T->getPointeeType());
3924}
3925
3926bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927 const RValueReferenceType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003928 return Visit(T->getPointeeType());
3929}
3930
3931bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932 const MemberPointerType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003933 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3934}
3935
3936bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937 const ConstantArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003938 return Visit(T->getElementType());
3939}
3940
3941bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942 const IncompleteArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003943 return Visit(T->getElementType());
3944}
3945
3946bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003947 const VariableArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003948 return Visit(T->getElementType());
3949}
3950
3951bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952 const DependentSizedArrayType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003953 return Visit(T->getElementType());
3954}
3955
3956bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003957 const DependentSizedExtVectorType* T) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003958 return Visit(T->getElementType());
3959}
3960
3961bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3962 return Visit(T->getElementType());
3963}
3964
3965bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3966 return Visit(T->getElementType());
3967}
3968
3969bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3970 const FunctionProtoType* T) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00003971 for (const auto &A : T->param_types()) {
3972 if (Visit(A))
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003973 return true;
3974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003975
Alp Toker314cc812014-01-25 16:55:45 +00003976 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003977}
3978
3979bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3980 const FunctionNoProtoType* T) {
Alp Toker314cc812014-01-25 16:55:45 +00003981 return Visit(T->getReturnType());
Douglas Gregor7731d3f2010-10-13 00:27:52 +00003982}
3983
3984bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3985 const UnresolvedUsingType*) {
3986 return false;
3987}
3988
3989bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3990 return false;
3991}
3992
3993bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3994 return Visit(T->getUnderlyingType());
3995}
3996
3997bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3998 return false;
3999}
4000
Alexis Hunte852b102011-05-24 22:41:36 +00004001bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4002 const UnaryTransformType*) {
4003 return false;
4004}
4005
Richard Smith30482bc2011-02-20 03:19:35 +00004006bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4007 return Visit(T->getDeducedType());
4008}
4009
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004010bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4011 return VisitTagDecl(T->getDecl());
4012}
4013
4014bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4015 return VisitTagDecl(T->getDecl());
4016}
4017
4018bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4019 const TemplateTypeParmType*) {
4020 return false;
4021}
4022
Douglas Gregorada4b792011-01-14 02:55:32 +00004023bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4024 const SubstTemplateTypeParmPackType *) {
4025 return false;
4026}
4027
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004028bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4029 const TemplateSpecializationType*) {
4030 return false;
4031}
4032
4033bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4034 const InjectedClassNameType* T) {
4035 return VisitTagDecl(T->getDecl());
4036}
4037
4038bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4039 const DependentNameType* T) {
4040 return VisitNestedNameSpecifier(T->getQualifier());
4041}
4042
4043bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4044 const DependentTemplateSpecializationType* T) {
4045 return VisitNestedNameSpecifier(T->getQualifier());
4046}
4047
Douglas Gregord2fa7662010-12-20 02:24:11 +00004048bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4049 const PackExpansionType* T) {
4050 return Visit(T->getPattern());
4051}
4052
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004053bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4054 return false;
4055}
4056
4057bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4058 const ObjCInterfaceType *) {
4059 return false;
4060}
4061
4062bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4063 const ObjCObjectPointerType *) {
4064 return false;
4065}
4066
Eli Friedman0dfb8892011-10-06 23:00:33 +00004067bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4068 return Visit(T->getValueType());
4069}
4070
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004071bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4072 if (Tag->getDeclContext()->isFunctionOrMethod()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004073 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004074 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004075 diag::warn_cxx98_compat_template_arg_local_type :
4076 diag::ext_template_arg_local_type)
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004077 << S.Context.getTypeDeclType(Tag) << SR;
4078 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079 }
4080
John McCall5ea95772013-03-09 00:54:27 +00004081 if (!Tag->hasNameForLinkage()) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004082 S.Diag(SR.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004083 S.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004084 diag::warn_cxx98_compat_template_arg_unnamed_type :
4085 diag::ext_template_arg_unnamed_type) << SR;
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004086 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4087 return true;
4088 }
4089
4090 return false;
4091}
4092
4093bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4094 NestedNameSpecifier *NNS) {
4095 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4096 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004097
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004098 switch (NNS->getKind()) {
4099 case NestedNameSpecifier::Identifier:
4100 case NestedNameSpecifier::Namespace:
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004101 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004102 case NestedNameSpecifier::Global:
4103 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004104
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004105 case NestedNameSpecifier::TypeSpec:
4106 case NestedNameSpecifier::TypeSpecWithTemplate:
4107 return Visit(QualType(NNS->getAsType(), 0));
4108 }
David Blaikie8a40f702012-01-17 06:56:22 +00004109 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004110}
4111
4112
Douglas Gregord32e0282009-02-09 23:23:08 +00004113/// \brief Check a template argument against its corresponding
4114/// template type parameter.
4115///
4116/// This routine implements the semantics of C++ [temp.arg.type]. It
4117/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00004118bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00004119 TypeSourceInfo *ArgInfo) {
4120 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00004121 QualType Arg = ArgInfo->getType();
Douglas Gregor959d5a02010-05-22 16:17:30 +00004122 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth9bb67f42010-09-03 21:12:34 +00004123
4124 if (Arg->isVariablyModifiedType()) {
4125 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004126 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004127 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00004128 }
4129
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004130 // C++03 [temp.arg.type]p2:
4131 // A local type, a type with no linkage, an unnamed type or a type
4132 // compounded from any of these types shall not be used as a
4133 // template-argument for a template type-parameter.
4134 //
Richard Smith0bf8a4922011-10-18 20:49:44 +00004135 // C++11 allows these, and even in C++03 we allow them as an extension with
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004136 // a warning.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004137 if (LangOpts.CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00004138 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
4139 SR.getBegin()) != DiagnosticsEngine::Ignored ||
4140 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
4141 SR.getBegin()) != DiagnosticsEngine::Ignored :
4142 Arg->hasUnnamedOrLocalType()) {
Douglas Gregor7731d3f2010-10-13 00:27:52 +00004143 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4144 (void)Finder.Visit(Context.getCanonicalType(Arg));
4145 }
4146
Douglas Gregord32e0282009-02-09 23:23:08 +00004147 return false;
4148}
4149
Douglas Gregor20fdef32012-04-10 17:08:25 +00004150enum NullPointerValueKind {
4151 NPV_NotNullPointer,
4152 NPV_NullPointer,
4153 NPV_Error
4154};
4155
4156/// \brief Determine whether the given template argument is a null pointer
4157/// value of the appropriate type.
4158static NullPointerValueKind
4159isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4160 QualType ParamType, Expr *Arg) {
4161 if (Arg->isValueDependent() || Arg->isTypeDependent())
4162 return NPV_NotNullPointer;
4163
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004164 if (!S.getLangOpts().CPlusPlus11)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004165 return NPV_NotNullPointer;
4166
4167 // Determine whether we have a constant expression.
Douglas Gregor350880c2012-04-10 19:03:30 +00004168 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4169 if (ArgRV.isInvalid())
4170 return NPV_Error;
4171 Arg = ArgRV.take();
4172
Douglas Gregor20fdef32012-04-10 17:08:25 +00004173 Expr::EvalResult EvalResult;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004174 SmallVector<PartialDiagnosticAt, 8> Notes;
Douglas Gregor350880c2012-04-10 19:03:30 +00004175 EvalResult.Diag = &Notes;
Douglas Gregor20fdef32012-04-10 17:08:25 +00004176 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
Douglas Gregor350880c2012-04-10 19:03:30 +00004177 EvalResult.HasSideEffects) {
4178 SourceLocation DiagLoc = Arg->getExprLoc();
4179
4180 // If our only note is the usual "invalid subexpression" note, just point
4181 // the caret at its location rather than producing an essentially
4182 // redundant note.
4183 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4184 diag::note_invalid_subexpr_in_const_expr) {
4185 DiagLoc = Notes[0].first;
4186 Notes.clear();
4187 }
4188
4189 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4190 << Arg->getType() << Arg->getSourceRange();
4191 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4192 S.Diag(Notes[I].first, Notes[I].second);
4193
4194 S.Diag(Param->getLocation(), diag::note_template_param_here);
4195 return NPV_Error;
4196 }
Douglas Gregor20fdef32012-04-10 17:08:25 +00004197
4198 // C++11 [temp.arg.nontype]p1:
4199 // - an address constant expression of type std::nullptr_t
4200 if (Arg->getType()->isNullPtrType())
4201 return NPV_NullPointer;
4202
4203 // - a constant expression that evaluates to a null pointer value (4.10); or
4204 // - a constant expression that evaluates to a null member pointer value
4205 // (4.11); or
4206 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4207 (EvalResult.Val.isMemberPointer() &&
4208 !EvalResult.Val.getMemberPointerDecl())) {
4209 // If our expression has an appropriate type, we've succeeded.
4210 bool ObjCLifetimeConversion;
4211 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4212 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4213 ObjCLifetimeConversion))
4214 return NPV_NullPointer;
4215
4216 // The types didn't match, but we know we got a null pointer; complain,
4217 // then recover as if the types were correct.
4218 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4219 << Arg->getType() << ParamType << Arg->getSourceRange();
4220 S.Diag(Param->getLocation(), diag::note_template_param_here);
4221 return NPV_NullPointer;
4222 }
4223
4224 // If we don't have a null pointer value, but we do have a NULL pointer
4225 // constant, suggest a cast to the appropriate type.
4226 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4227 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4228 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004229 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4230 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4231 ")");
Douglas Gregor20fdef32012-04-10 17:08:25 +00004232 S.Diag(Param->getLocation(), diag::note_template_param_here);
4233 return NPV_NullPointer;
4234 }
4235
4236 // FIXME: If we ever want to support general, address-constant expressions
4237 // as non-type template arguments, we should return the ExprResult here to
4238 // be interpreted by the caller.
4239 return NPV_NotNullPointer;
4240}
4241
David Majnemer61c39a12013-08-23 05:39:39 +00004242/// \brief Checks whether the given template argument is compatible with its
4243/// template parameter.
4244static bool CheckTemplateArgumentIsCompatibleWithParameter(
4245 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4246 Expr *Arg, QualType ArgType) {
4247 bool ObjCLifetimeConversion;
4248 if (ParamType->isPointerType() &&
4249 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4250 S.IsQualificationConversion(ArgType, ParamType, false,
4251 ObjCLifetimeConversion)) {
4252 // For pointer-to-object types, qualification conversions are
4253 // permitted.
4254 } else {
4255 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4256 if (!ParamRef->getPointeeType()->isFunctionType()) {
4257 // C++ [temp.arg.nontype]p5b3:
4258 // For a non-type template-parameter of type reference to
4259 // object, no conversions apply. The type referred to by the
4260 // reference may be more cv-qualified than the (otherwise
4261 // identical) type of the template- argument. The
4262 // template-parameter is bound directly to the
4263 // template-argument, which shall be an lvalue.
4264
4265 // FIXME: Other qualifiers?
4266 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4267 unsigned ArgQuals = ArgType.getCVRQualifiers();
4268
4269 if ((ParamQuals | ArgQuals) != ParamQuals) {
4270 S.Diag(Arg->getLocStart(),
4271 diag::err_template_arg_ref_bind_ignores_quals)
4272 << ParamType << Arg->getType() << Arg->getSourceRange();
4273 S.Diag(Param->getLocation(), diag::note_template_param_here);
4274 return true;
4275 }
4276 }
4277 }
4278
4279 // At this point, the template argument refers to an object or
4280 // function with external linkage. We now need to check whether the
4281 // argument and parameter types are compatible.
4282 if (!S.Context.hasSameUnqualifiedType(ArgType,
4283 ParamType.getNonReferenceType())) {
4284 // We can't perform this conversion or binding.
4285 if (ParamType->isReferenceType())
4286 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4287 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4288 else
4289 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4290 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4291 S.Diag(Param->getLocation(), diag::note_template_param_here);
4292 return true;
4293 }
4294 }
4295
4296 return false;
4297}
4298
Douglas Gregorccb07762009-02-11 19:52:55 +00004299/// \brief Checks whether the given template argument is the address
4300/// of an object or function according to C++ [temp.arg.nontype]p1.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301static bool
Douglas Gregorb242683d2010-04-01 18:32:35 +00004302CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4303 NonTypeTemplateParmDecl *Param,
4304 QualType ParamType,
4305 Expr *ArgIn,
4306 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004307 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004308 Expr *Arg = ArgIn;
4309 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00004310
Douglas Gregor20fdef32012-04-10 17:08:25 +00004311 // If our parameter has pointer type, check for a null template value.
4312 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4313 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4314 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004315 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00004316 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004317 return false;
4318
4319 case NPV_Error:
4320 return true;
4321
4322 case NPV_NotNullPointer:
4323 break;
4324 }
4325 }
John McCall7c454bb2011-07-15 05:09:51 +00004326
Douglas Gregorb242683d2010-04-01 18:32:35 +00004327 bool AddressTaken = false;
4328 SourceLocation AddrOpLoc;
David Majnemer61c39a12013-08-23 05:39:39 +00004329 if (S.getLangOpts().MicrosoftExt) {
4330 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4331 // dereference and address-of operators.
4332 Arg = Arg->IgnoreParenCasts();
4333
4334 bool ExtWarnMSTemplateArg = false;
4335 UnaryOperatorKind FirstOpKind;
4336 SourceLocation FirstOpLoc;
4337 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4338 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4339 if (UnOpKind == UO_Deref)
4340 ExtWarnMSTemplateArg = true;
4341 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4342 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4343 if (!AddrOpLoc.isValid()) {
4344 FirstOpKind = UnOpKind;
4345 FirstOpLoc = UnOp->getOperatorLoc();
4346 }
4347 } else
4348 break;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004349 }
David Majnemer61c39a12013-08-23 05:39:39 +00004350 if (FirstOpLoc.isValid()) {
4351 if (ExtWarnMSTemplateArg)
4352 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4353 << ArgIn->getSourceRange();
John McCall7c454bb2011-07-15 05:09:51 +00004354
David Majnemer61c39a12013-08-23 05:39:39 +00004355 if (FirstOpKind == UO_AddrOf)
4356 AddressTaken = true;
4357 else if (Arg->getType()->isPointerType()) {
4358 // We cannot let pointers get dereferenced here, that is obviously not a
4359 // constant expression.
4360 assert(FirstOpKind == UO_Deref);
4361 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4362 << Arg->getSourceRange();
4363 }
4364 }
4365 } else {
4366 // See through any implicit casts we added to fix the type.
4367 Arg = Arg->IgnoreImpCasts();
John McCall7c454bb2011-07-15 05:09:51 +00004368
David Majnemer61c39a12013-08-23 05:39:39 +00004369 // C++ [temp.arg.nontype]p1:
4370 //
4371 // A template-argument for a non-type, non-template
4372 // template-parameter shall be one of: [...]
4373 //
4374 // -- the address of an object or function with external
4375 // linkage, including function templates and function
4376 // template-ids but excluding non-static class members,
4377 // expressed as & id-expression where the & is optional if
4378 // the name refers to a function or array, or if the
4379 // corresponding template-parameter is a reference; or
4380
4381 // In C++98/03 mode, give an extension warning on any extra parentheses.
4382 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4383 bool ExtraParens = false;
4384 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4385 if (!Invalid && !ExtraParens) {
4386 S.Diag(Arg->getLocStart(),
4387 S.getLangOpts().CPlusPlus11
4388 ? diag::warn_cxx98_compat_template_arg_extra_parens
4389 : diag::ext_template_arg_extra_parens)
4390 << Arg->getSourceRange();
4391 ExtraParens = true;
4392 }
4393
4394 Arg = Parens->getSubExpr();
4395 }
4396
4397 while (SubstNonTypeTemplateParmExpr *subst =
4398 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4399 Arg = subst->getReplacement()->IgnoreImpCasts();
4400
4401 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4402 if (UnOp->getOpcode() == UO_AddrOf) {
4403 Arg = UnOp->getSubExpr();
4404 AddressTaken = true;
4405 AddrOpLoc = UnOp->getOperatorLoc();
4406 }
4407 }
4408
4409 while (SubstNonTypeTemplateParmExpr *subst =
4410 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4411 Arg = subst->getReplacement()->IgnoreImpCasts();
4412 }
John McCall7c454bb2011-07-15 05:09:51 +00004413
Chandler Carruth724a8a12010-01-31 10:01:20 +00004414 // Stop checking the precise nature of the argument if it is value dependent,
4415 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00004416 if (Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004417 Converted = TemplateArgument(ArgIn);
Chandler Carruth724a8a12010-01-31 10:01:20 +00004418 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004419 }
David Majnemer61c39a12013-08-23 05:39:39 +00004420
4421 if (isa<CXXUuidofExpr>(Arg)) {
4422 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4423 ArgIn, Arg, ArgType))
4424 return true;
4425
4426 Converted = TemplateArgument(ArgIn);
4427 return false;
4428 }
4429
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004430 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4431 if (!DRE) {
4432 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4433 << Arg->getSourceRange();
4434 S.Diag(Param->getLocation(), diag::note_template_param_here);
4435 return true;
4436 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00004437
Eli Friedmanb826a002012-09-26 02:36:12 +00004438 ValueDecl *Entity = DRE->getDecl();
Douglas Gregorccb07762009-02-11 19:52:55 +00004439
4440 // Cannot refer to non-static data members
David Majnemer6bedcfa2013-10-26 06:12:44 +00004441 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004442 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
David Majnemer6bedcfa2013-10-26 06:12:44 +00004443 << Entity << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004444 S.Diag(Param->getLocation(), diag::note_template_param_here);
4445 return true;
4446 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004447
4448 // Cannot refer to non-static member functions
Richard Smith9380e0e2012-04-04 21:11:30 +00004449 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004450 if (!Method->isStatic()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004451 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00004452 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00004453 S.Diag(Param->getLocation(), diag::note_template_param_here);
4454 return true;
4455 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004456 }
Mike Stump11289f42009-09-09 15:08:12 +00004457
Richard Smith9380e0e2012-04-04 21:11:30 +00004458 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4459 VarDecl *Var = dyn_cast<VarDecl>(Entity);
Douglas Gregorccb07762009-02-11 19:52:55 +00004460
Richard Smith9380e0e2012-04-04 21:11:30 +00004461 // A non-type template argument must refer to an object or function.
4462 if (!Func && !Var) {
4463 // We found something, but we don't know specifically what it is.
4464 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4465 << Arg->getSourceRange();
4466 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4467 return true;
4468 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004469
Richard Smith9380e0e2012-04-04 21:11:30 +00004470 // Address / reference template args must have external linkage in C++98.
Rafael Espindola3ae00052013-05-13 00:12:11 +00004471 if (Entity->getFormalLinkage() == InternalLinkage) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004472 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
Richard Smith9380e0e2012-04-04 21:11:30 +00004473 diag::warn_cxx98_compat_template_arg_object_internal :
4474 diag::ext_template_arg_object_internal)
4475 << !Func << Entity << Arg->getSourceRange();
4476 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4477 << !Func;
Rafael Espindola3ae00052013-05-13 00:12:11 +00004478 } else if (!Entity->hasLinkage()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004479 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4480 << !Func << Entity << Arg->getSourceRange();
4481 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4482 << !Func;
4483 return true;
4484 }
4485
4486 if (Func) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004487 // If the template parameter has pointer type, the function decays.
4488 if (ParamType->isPointerType() && !AddressTaken)
4489 ArgType = S.Context.getPointerType(Func->getType());
4490 else if (AddressTaken && ParamType->isReferenceType()) {
4491 // If we originally had an address-of operator, but the
4492 // parameter has reference type, complain and (if things look
4493 // like they will work) drop the address-of operator.
4494 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4495 ParamType.getNonReferenceType())) {
4496 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4497 << ParamType;
4498 S.Diag(Param->getLocation(), diag::note_template_param_here);
4499 return true;
4500 }
4501
4502 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4503 << ParamType
4504 << FixItHint::CreateRemoval(AddrOpLoc);
4505 S.Diag(Param->getLocation(), diag::note_template_param_here);
4506
4507 ArgType = Func->getType();
4508 }
Richard Smith9380e0e2012-04-04 21:11:30 +00004509 } else {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004510 // A value of reference type is not an object.
4511 if (Var->getType()->isReferenceType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004512 S.Diag(Arg->getLocStart(),
Douglas Gregorb242683d2010-04-01 18:32:35 +00004513 diag::err_template_arg_reference_var)
4514 << Var->getType() << Arg->getSourceRange();
4515 S.Diag(Param->getLocation(), diag::note_template_param_here);
4516 return true;
4517 }
4518
Richard Smith9380e0e2012-04-04 21:11:30 +00004519 // A template argument must have static storage duration.
Richard Smithfd3834f2013-04-13 02:43:54 +00004520 if (Var->getTLSKind()) {
Richard Smith9380e0e2012-04-04 21:11:30 +00004521 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4522 << Arg->getSourceRange();
4523 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4524 return true;
4525 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004526
4527 // If the template parameter has pointer type, we must have taken
4528 // the address of this object.
4529 if (ParamType->isReferenceType()) {
4530 if (AddressTaken) {
4531 // If we originally had an address-of operator, but the
4532 // parameter has reference type, complain and (if things look
4533 // like they will work) drop the address-of operator.
4534 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4535 ParamType.getNonReferenceType())) {
4536 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4537 << ParamType;
4538 S.Diag(Param->getLocation(), diag::note_template_param_here);
4539 return true;
4540 }
4541
4542 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4543 << ParamType
4544 << FixItHint::CreateRemoval(AddrOpLoc);
4545 S.Diag(Param->getLocation(), diag::note_template_param_here);
4546
4547 ArgType = Var->getType();
4548 }
4549 } else if (!AddressTaken && ParamType->isPointerType()) {
4550 if (Var->getType()->isArrayType()) {
4551 // Array-to-pointer decay.
4552 ArgType = S.Context.getArrayDecayedType(Var->getType());
4553 } else {
4554 // If the template parameter has pointer type but the address of
4555 // this object was not taken, complain and (possibly) recover by
4556 // taking the address of the entity.
4557 ArgType = S.Context.getPointerType(Var->getType());
4558 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4559 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4560 << ParamType;
4561 S.Diag(Param->getLocation(), diag::note_template_param_here);
4562 return true;
4563 }
4564
4565 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4566 << ParamType
4567 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4568
4569 S.Diag(Param->getLocation(), diag::note_template_param_here);
4570 }
4571 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
David Majnemer61c39a12013-08-23 05:39:39 +00004574 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4575 Arg, ArgType))
4576 return true;
Douglas Gregorb242683d2010-04-01 18:32:35 +00004577
4578 // Create the template argument.
Eli Friedmanb826a002012-09-26 02:36:12 +00004579 Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
4580 ParamType->isReferenceType());
Nick Lewycky45b50522013-02-02 00:25:55 +00004581 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
Douglas Gregorb242683d2010-04-01 18:32:35 +00004582 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004583}
4584
4585/// \brief Checks whether the given template argument is a pointer to
4586/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004587static bool CheckTemplateArgumentPointerToMember(Sema &S,
4588 NonTypeTemplateParmDecl *Param,
4589 QualType ParamType,
4590 Expr *&ResultArg,
4591 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004592 bool Invalid = false;
4593
Douglas Gregor20fdef32012-04-10 17:08:25 +00004594 // Check for a null pointer value.
4595 Expr *Arg = ResultArg;
4596 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4597 case NPV_Error:
4598 return true;
4599 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00004600 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00004601 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
David Majnemer763584d2014-02-06 10:59:19 +00004602 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4603 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
Douglas Gregor20fdef32012-04-10 17:08:25 +00004604 return false;
4605 case NPV_NotNullPointer:
4606 break;
4607 }
4608
4609 bool ObjCLifetimeConversion;
4610 if (S.IsQualificationConversion(Arg->getType(),
4611 ParamType.getNonReferenceType(),
4612 false, ObjCLifetimeConversion)) {
4613 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4614 Arg->getValueKind()).take();
4615 ResultArg = Arg;
4616 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4617 ParamType.getNonReferenceType())) {
4618 // We can't perform this conversion.
4619 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4620 << Arg->getType() << ParamType << Arg->getSourceRange();
4621 S.Diag(Param->getLocation(), diag::note_template_param_here);
4622 return true;
4623 }
4624
Douglas Gregorccb07762009-02-11 19:52:55 +00004625 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004626 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00004627 Arg = Cast->getSubExpr();
4628
4629 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004630 //
Douglas Gregorccb07762009-02-11 19:52:55 +00004631 // A template-argument for a non-type, non-template
4632 // template-parameter shall be one of: [...]
4633 //
4634 // -- a pointer to member expressed as described in 5.3.1.
Craig Topperc3ec1492014-05-26 06:22:03 +00004635 DeclRefExpr *DRE = nullptr;
Douglas Gregorccb07762009-02-11 19:52:55 +00004636
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004637 // In C++98/03 mode, give an extension warning on any extra parentheses.
4638 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4639 bool ExtraParens = false;
Douglas Gregorccb07762009-02-11 19:52:55 +00004640 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00004641 if (!Invalid && !ExtraParens) {
Douglas Gregor20fdef32012-04-10 17:08:25 +00004642 S.Diag(Arg->getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004643 S.getLangOpts().CPlusPlus11 ?
Douglas Gregor20fdef32012-04-10 17:08:25 +00004644 diag::warn_cxx98_compat_template_arg_extra_parens :
4645 diag::ext_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00004646 << Arg->getSourceRange();
Abramo Bagnara6a0c4092010-09-13 06:06:58 +00004647 ExtraParens = true;
Douglas Gregorccb07762009-02-11 19:52:55 +00004648 }
4649
4650 Arg = Parens->getSubExpr();
4651 }
4652
John McCall7c454bb2011-07-15 05:09:51 +00004653 while (SubstNonTypeTemplateParmExpr *subst =
4654 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4655 Arg = subst->getReplacement()->IgnoreImpCasts();
4656
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004657 // A pointer-to-member constant written &Class::member.
4658 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00004659 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004660 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4661 if (DRE && !DRE->getQualifier())
Craig Topperc3ec1492014-05-26 06:22:03 +00004662 DRE = nullptr;
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004665 // A constant of pointer-to-member type.
4666 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4667 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4668 if (VD->getType()->isMemberPointerType()) {
David Majnemercd053cd2013-12-10 00:40:58 +00004669 if (isa<NonTypeTemplateParmDecl>(VD)) {
Eli Friedmanb826a002012-09-26 02:36:12 +00004670 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004671 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004672 } else {
4673 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4674 Converted = TemplateArgument(VD, /*isReferenceParam*/false);
4675 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004676 return Invalid;
4677 }
4678 }
4679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680
Craig Topperc3ec1492014-05-26 06:22:03 +00004681 DRE = nullptr;
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00004682 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
Douglas Gregorccb07762009-02-11 19:52:55 +00004684 if (!DRE)
Douglas Gregor20fdef32012-04-10 17:08:25 +00004685 return S.Diag(Arg->getLocStart(),
4686 diag::err_template_arg_not_pointer_to_member_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00004687 << Arg->getSourceRange();
4688
David Majnemer3ac84e62013-10-22 21:56:38 +00004689 if (isa<FieldDecl>(DRE->getDecl()) ||
4690 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4691 isa<CXXMethodDecl>(DRE->getDecl())) {
Douglas Gregorccb07762009-02-11 19:52:55 +00004692 assert((isa<FieldDecl>(DRE->getDecl()) ||
David Majnemer3ac84e62013-10-22 21:56:38 +00004693 isa<IndirectFieldDecl>(DRE->getDecl()) ||
Douglas Gregorccb07762009-02-11 19:52:55 +00004694 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4695 "Only non-static member pointers can make it here");
4696
4697 // Okay: this is the address of a non-static member, and therefore
4698 // a member pointer constant.
Eli Friedmanb826a002012-09-26 02:36:12 +00004699 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
John McCallc3007a22010-10-26 07:05:15 +00004700 Converted = TemplateArgument(Arg);
Eli Friedmanb826a002012-09-26 02:36:12 +00004701 } else {
4702 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4703 Converted = TemplateArgument(D, /*isReferenceParam*/false);
4704 }
Douglas Gregorccb07762009-02-11 19:52:55 +00004705 return Invalid;
4706 }
4707
4708 // We found something else, but we don't know specifically what it is.
Douglas Gregor20fdef32012-04-10 17:08:25 +00004709 S.Diag(Arg->getLocStart(),
4710 diag::err_template_arg_not_pointer_to_member_form)
4711 << Arg->getSourceRange();
4712 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
Douglas Gregorccb07762009-02-11 19:52:55 +00004713 return true;
4714}
4715
Douglas Gregord32e0282009-02-09 23:23:08 +00004716/// \brief Check a template argument against its corresponding
4717/// non-type template parameter.
4718///
Douglas Gregor463421d2009-03-03 04:44:36 +00004719/// This routine implements the semantics of C++ [temp.arg.nontype].
John Wiegley01296292011-04-08 18:41:53 +00004720/// If an error occurred, it returns ExprError(); otherwise, it
4721/// returns the converted template argument. \p
Douglas Gregor463421d2009-03-03 04:44:36 +00004722/// InstantiatedParamType is the type of the non-type template
4723/// parameter after it has been instantiated.
John Wiegley01296292011-04-08 18:41:53 +00004724ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4725 QualType InstantiatedParamType, Expr *Arg,
4726 TemplateArgument &Converted,
4727 CheckTemplateArgumentKind CTAK) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004728 SourceLocation StartLoc = Arg->getLocStart();
Douglas Gregorc40290e2009-03-09 23:48:35 +00004729
Douglas Gregor86560402009-02-10 23:36:10 +00004730 // If either the parameter has a dependent type or the argument is
4731 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00004732 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
4733 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004734 Converted = TemplateArgument(Arg);
John Wiegley01296292011-04-08 18:41:53 +00004735 return Owned(Arg);
Douglas Gregorc40290e2009-03-09 23:48:35 +00004736 }
Douglas Gregor86560402009-02-10 23:36:10 +00004737
4738 // C++ [temp.arg.nontype]p5:
4739 // The following conversions are performed on each expression used
4740 // as a non-type template-argument. If a non-type
4741 // template-argument cannot be converted to the type of the
4742 // corresponding template-parameter then the program is
4743 // ill-formed.
Douglas Gregor463421d2009-03-03 04:44:36 +00004744 QualType ParamType = InstantiatedParamType;
Douglas Gregorb90df602010-06-16 00:17:44 +00004745 if (ParamType->isIntegralOrEnumerationType()) {
Richard Smithf8379a02012-01-18 23:55:52 +00004746 // C++11:
4747 // -- for a non-type template-parameter of integral or
4748 // enumeration type, conversions permitted in a converted
4749 // constant expression are applied.
4750 //
4751 // C++98:
4752 // -- for a non-type template-parameter of integral or
4753 // enumeration type, integral promotions (4.5) and integral
4754 // conversions (4.7) are applied.
4755
4756 if (CTAK == CTAK_Deduced &&
4757 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4758 // C++ [temp.deduct.type]p17:
4759 // If, in the declaration of a function template with a non-type
4760 // template-parameter, the non-type template-parameter is used
4761 // in an expression in the function parameter-list and, if the
4762 // corresponding template-argument is deduced, the
4763 // template-argument type shall match the type of the
4764 // template-parameter exactly, except that a template-argument
4765 // deduced from an array bound may be of any integral type.
4766 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4767 << Arg->getType().getUnqualifiedType()
4768 << ParamType.getUnqualifiedType();
4769 Diag(Param->getLocation(), diag::note_template_param_here);
4770 return ExprError();
4771 }
4772
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004773 if (getLangOpts().CPlusPlus11) {
Richard Smithf8379a02012-01-18 23:55:52 +00004774 // We can't check arbitrary value-dependent arguments.
4775 // FIXME: If there's no viable conversion to the template parameter type,
4776 // we should be able to diagnose that prior to instantiation.
4777 if (Arg->isValueDependent()) {
4778 Converted = TemplateArgument(Arg);
4779 return Owned(Arg);
4780 }
4781
4782 // C++ [temp.arg.nontype]p1:
4783 // A template-argument for a non-type, non-template template-parameter
4784 // shall be one of:
4785 //
4786 // -- for a non-type template-parameter of integral or enumeration
4787 // type, a converted constant expression of the type of the
4788 // template-parameter; or
4789 llvm::APSInt Value;
4790 ExprResult ArgResult =
4791 CheckConvertedConstantExpression(Arg, ParamType, Value,
4792 CCEK_TemplateArg);
4793 if (ArgResult.isInvalid())
4794 return ExprError();
4795
4796 // Widen the argument value to sizeof(parameter type). This is almost
4797 // always a no-op, except when the parameter type is bool. In
4798 // that case, this may extend the argument from 1 bit to 8 bits.
4799 QualType IntegerType = ParamType;
4800 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4801 IntegerType = Enum->getDecl()->getIntegerType();
4802 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4803
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004804 Converted = TemplateArgument(Context, Value,
4805 Context.getCanonicalType(ParamType));
Richard Smithf8379a02012-01-18 23:55:52 +00004806 return ArgResult;
4807 }
4808
Richard Smith08b12f12011-10-27 22:11:44 +00004809 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4810 if (ArgResult.isInvalid())
4811 return ExprError();
4812 Arg = ArgResult.take();
4813
4814 QualType ArgType = Arg->getType();
4815
Douglas Gregor86560402009-02-10 23:36:10 +00004816 // C++ [temp.arg.nontype]p1:
4817 // A template-argument for a non-type, non-template
4818 // template-parameter shall be one of:
4819 //
4820 // -- an integral constant-expression of integral or enumeration
4821 // type; or
4822 // -- the name of a non-type template-parameter; or
4823 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004824 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00004825 if (!ArgType->isIntegralOrEnumerationType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004826 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004827 diag::err_template_arg_not_integral_or_enumeral)
4828 << ArgType << Arg->getSourceRange();
4829 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004830 return ExprError();
Richard Smithf4c51d92012-02-04 09:53:13 +00004831 } else if (!Arg->isValueDependent()) {
Douglas Gregore2b37442012-05-04 22:38:52 +00004832 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4833 QualType T;
4834
4835 public:
4836 TmplArgICEDiagnoser(QualType T) : T(T) { }
Craig Toppere14c0f82014-03-12 04:55:44 +00004837
4838 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4839 SourceRange SR) override {
Douglas Gregore2b37442012-05-04 22:38:52 +00004840 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4841 }
4842 } Diagnoser(ArgType);
4843
4844 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4845 false).take();
Richard Smithf4c51d92012-02-04 09:53:13 +00004846 if (!Arg)
4847 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004848 }
4849
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004850 // From here on out, all we care about are the unqualified forms
4851 // of the parameter and argument types.
4852 ParamType = ParamType.getUnqualifiedType();
4853 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00004854
4855 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00004856 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00004857 // Okay: no conversion necessary
John McCall8cb679e2010-11-15 09:13:47 +00004858 } else if (ParamType->isBooleanType()) {
4859 // This is an integral-to-boolean conversion.
John Wiegley01296292011-04-08 18:41:53 +00004860 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
Douglas Gregor86560402009-02-10 23:36:10 +00004861 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4862 !ParamType->isEnumeralType()) {
4863 // This is an integral promotion or conversion.
John Wiegley01296292011-04-08 18:41:53 +00004864 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
Douglas Gregor86560402009-02-10 23:36:10 +00004865 } else {
4866 // We can't perform this conversion.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004867 Diag(Arg->getLocStart(),
Douglas Gregor86560402009-02-10 23:36:10 +00004868 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00004869 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00004870 Diag(Param->getLocation(), diag::note_template_param_here);
John Wiegley01296292011-04-08 18:41:53 +00004871 return ExprError();
Douglas Gregor86560402009-02-10 23:36:10 +00004872 }
4873
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004874 // Add the value of this argument to the list of converted
4875 // arguments. We use the bitwidth and signedness of the template
4876 // parameter.
4877 if (Arg->isValueDependent()) {
4878 // The argument is value-dependent. Create a new
4879 // TemplateArgument with the converted expression.
4880 Converted = TemplateArgument(Arg);
4881 return Owned(Arg);
4882 }
4883
Douglas Gregor52aba872009-03-14 00:20:21 +00004884 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00004885 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00004886 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00004887
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004888 if (ParamType->isBooleanType()) {
4889 // Value must be zero or one.
4890 Value = Value != 0;
4891 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4892 if (Value.getBitWidth() != AllowedBits)
4893 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004894 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004895 } else {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004896 llvm::APSInt OldValue = Value;
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004897
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004898 // Coerce the template argument's value to the value it will have
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004899 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00004900 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00004901 if (Value.getBitWidth() != AllowedBits)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004902 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004903 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004904
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004905 // Complain if an unsigned parameter received a negative value.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004906 if (IntegerType->isUnsignedIntegerOrEnumerationType()
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004907 && (OldValue.isSigned() && OldValue.isNegative())) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004908 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004909 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4910 << Arg->getSourceRange();
4911 Diag(Param->getLocation(), diag::note_template_param_here);
4912 }
Douglas Gregorb4f4d512011-05-04 21:55:00 +00004913
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004914 // Complain if we overflowed the template parameter's type.
4915 unsigned RequiredBits;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004916 if (IntegerType->isUnsignedIntegerOrEnumerationType())
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004917 RequiredBits = OldValue.getActiveBits();
4918 else if (OldValue.isUnsigned())
4919 RequiredBits = OldValue.getActiveBits() + 1;
4920 else
4921 RequiredBits = OldValue.getMinSignedBits();
4922 if (RequiredBits > AllowedBits) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004923 Diag(Arg->getLocStart(),
Douglas Gregorbb3d7862010-03-26 02:38:37 +00004924 diag::warn_template_arg_too_large)
4925 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4926 << Arg->getSourceRange();
4927 Diag(Param->getLocation(), diag::note_template_param_here);
4928 }
Douglas Gregor52aba872009-03-14 00:20:21 +00004929 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00004930
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004931 Converted = TemplateArgument(Context, Value,
Douglas Gregor3d63a9e2011-08-09 01:55:14 +00004932 ParamType->isEnumeralType()
4933 ? Context.getCanonicalType(ParamType)
4934 : IntegerType);
John Wiegley01296292011-04-08 18:41:53 +00004935 return Owned(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00004936 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004937
Richard Smith08b12f12011-10-27 22:11:44 +00004938 QualType ArgType = Arg->getType();
John McCall16df1e52010-03-30 21:47:33 +00004939 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4940
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004941 // Handle pointer-to-function, reference-to-function, and
4942 // pointer-to-member-function all in (roughly) the same way.
4943 if (// -- For a non-type template-parameter of type pointer to
4944 // function, only the function-to-pointer conversion (4.3) is
4945 // applied. If the template-argument represents a set of
4946 // overloaded functions (or a pointer to such), the matching
4947 // function is selected from the set (13.4).
4948 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004949 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004950 // -- For a non-type template-parameter of type reference to
4951 // function, no conversions apply. If the template-argument
4952 // represents a set of overloaded functions, the matching
4953 // function is selected from the set (13.4).
4954 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004955 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004956 // -- For a non-type template-parameter of type pointer to
4957 // member function, no conversions apply. If the
4958 // template-argument represents a set of overloaded member
4959 // functions, the matching member function is selected from
4960 // the set (13.4).
4961 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004962 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004963 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00004964
Douglas Gregor064fdb22010-04-14 23:11:21 +00004965 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
Douglas Gregor064fdb22010-04-14 23:11:21 +00004967 true,
4968 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004969 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00004970 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00004971
4972 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4973 ArgType = Arg->getType();
4974 } else
John Wiegley01296292011-04-08 18:41:53 +00004975 return ExprError();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004976 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004977
John Wiegley01296292011-04-08 18:41:53 +00004978 if (!ParamType->isMemberPointerType()) {
4979 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4980 ParamType,
4981 Arg, Converted))
4982 return ExprError();
4983 return Owned(Arg);
4984 }
Douglas Gregorb242683d2010-04-01 18:32:35 +00004985
Douglas Gregor20fdef32012-04-10 17:08:25 +00004986 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4987 Converted))
John Wiegley01296292011-04-08 18:41:53 +00004988 return ExprError();
4989 return Owned(Arg);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00004990 }
4991
Chris Lattner696197c2009-02-20 21:37:53 +00004992 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004993 // -- for a non-type template-parameter of type pointer to
4994 // object, qualification conversions (4.4) and the
4995 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00004996 // C++0x also allows a value of std::nullptr_t.
Eli Friedmana170cd62010-08-05 02:49:48 +00004997 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00004998 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00004999
John Wiegley01296292011-04-08 18:41:53 +00005000 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5001 ParamType,
5002 Arg, Converted))
5003 return ExprError();
5004 return Owned(Arg);
Douglas Gregora9faa442009-02-11 00:44:29 +00005005 }
Mike Stump11289f42009-09-09 15:08:12 +00005006
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005007 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005008 // -- For a non-type template-parameter of type reference to
5009 // object, no conversions apply. The type referred to by the
5010 // reference may be more cv-qualified than the (otherwise
5011 // identical) type of the template-argument. The
5012 // template-parameter is bound directly to the
5013 // template-argument, which must be an lvalue.
Eli Friedmana170cd62010-08-05 02:49:48 +00005014 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005015 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00005016
Douglas Gregor064fdb22010-04-14 23:11:21 +00005017 if (Arg->getType() == Context.OverloadTy) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005018 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5019 ParamRefType->getPointeeType(),
Douglas Gregor064fdb22010-04-14 23:11:21 +00005020 true,
5021 FoundResult)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005022 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00005023 return ExprError();
Douglas Gregor064fdb22010-04-14 23:11:21 +00005024
5025 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5026 ArgType = Arg->getType();
5027 } else
John Wiegley01296292011-04-08 18:41:53 +00005028 return ExprError();
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030
John Wiegley01296292011-04-08 18:41:53 +00005031 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5032 ParamType,
5033 Arg, Converted))
5034 return ExprError();
5035 return Owned(Arg);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005036 }
Douglas Gregor0e558532009-02-11 16:16:59 +00005037
Douglas Gregor20fdef32012-04-10 17:08:25 +00005038 // Deal with parameters of type std::nullptr_t.
5039 if (ParamType->isNullPtrType()) {
5040 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5041 Converted = TemplateArgument(Arg);
5042 return Owned(Arg);
5043 }
5044
5045 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5046 case NPV_NotNullPointer:
5047 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5048 << Arg->getType() << ParamType;
5049 Diag(Param->getLocation(), diag::note_template_param_here);
5050 return ExprError();
5051
5052 case NPV_Error:
5053 return ExprError();
5054
5055 case NPV_NullPointer:
Richard Smithbc8c5b52012-04-26 01:51:03 +00005056 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
Eli Friedmanb826a002012-09-26 02:36:12 +00005057 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005058 return Owned(Arg);
Douglas Gregor20fdef32012-04-10 17:08:25 +00005059 }
5060 }
5061
Douglas Gregor0e558532009-02-11 16:16:59 +00005062 // -- For a non-type template-parameter of type pointer to data
5063 // member, qualification conversions (4.4) are applied.
5064 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5065
Douglas Gregor20fdef32012-04-10 17:08:25 +00005066 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5067 Converted))
John Wiegley01296292011-04-08 18:41:53 +00005068 return ExprError();
5069 return Owned(Arg);
Douglas Gregord32e0282009-02-09 23:23:08 +00005070}
5071
5072/// \brief Check a template argument against its corresponding
5073/// template template parameter.
5074///
5075/// This routine implements the semantics of C++ [temp.arg.template].
5076/// It returns true if an error occurred, and false otherwise.
5077bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Richard Smith1fde8ec2012-09-07 02:06:42 +00005078 const TemplateArgumentLoc &Arg,
5079 unsigned ArgumentPackIndex) {
Eli Friedmanb826a002012-09-26 02:36:12 +00005080 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005081 TemplateDecl *Template = Name.getAsTemplateDecl();
5082 if (!Template) {
5083 // Any dependent template name is fine.
5084 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5085 return false;
5086 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00005087
Richard Smith3f1b5d02011-05-05 21:57:07 +00005088 // C++0x [temp.arg.template]p1:
Douglas Gregor85e0f662009-02-10 00:24:35 +00005089 // A template-argument for a template template-parameter shall be
Richard Smith3f1b5d02011-05-05 21:57:07 +00005090 // the name of a class template or an alias template, expressed as an
5091 // id-expression. When the template-argument names a class template, only
Douglas Gregor85e0f662009-02-10 00:24:35 +00005092 // primary class templates are considered when matching the
5093 // template template argument with the corresponding parameter;
5094 // partial specializations are not considered even if their
5095 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00005096 //
5097 // Note that we also allow template template parameters here, which
5098 // will happen when we are dealing with, e.g., class template
5099 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00005100 if (!isa<ClassTemplateDecl>(Template) &&
Richard Smith3f1b5d02011-05-05 21:57:07 +00005101 !isa<TemplateTemplateParmDecl>(Template) &&
5102 !isa<TypeAliasTemplateDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00005103 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00005104 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005105 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005106 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00005107 << Template;
5108 }
5109
Richard Smith1fde8ec2012-09-07 02:06:42 +00005110 TemplateParameterList *Params = Param->getTemplateParameters();
5111 if (Param->isExpandedParameterPack())
5112 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5113
Douglas Gregor85e0f662009-02-10 00:24:35 +00005114 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00005115 Params,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005116 true,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005117 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005118 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00005119}
5120
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005121/// \brief Given a non-type template argument that refers to a
5122/// declaration and the type of its corresponding non-type template
5123/// parameter, produce an expression that properly refers to that
5124/// declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005126Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5127 QualType ParamType,
5128 SourceLocation Loc) {
David Blaikiedc601e32013-02-27 22:10:40 +00005129 // C++ [temp.param]p8:
5130 //
5131 // A non-type template-parameter of type "array of T" or
5132 // "function returning T" is adjusted to be of type "pointer to
5133 // T" or "pointer to function returning T", respectively.
5134 if (ParamType->isArrayType())
5135 ParamType = Context.getArrayDecayedType(ParamType);
5136 else if (ParamType->isFunctionType())
5137 ParamType = Context.getPointerType(ParamType);
5138
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005139 // For a NULL non-type template argument, return nullptr casted to the
5140 // parameter's type.
Eli Friedmanb826a002012-09-26 02:36:12 +00005141 if (Arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005142 return ImpCastExprToType(
5143 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5144 ParamType,
5145 ParamType->getAs<MemberPointerType>()
5146 ? CK_NullToMemberPointer
5147 : CK_NullToPointer);
5148 }
Eli Friedmanb826a002012-09-26 02:36:12 +00005149 assert(Arg.getKind() == TemplateArgument::Declaration &&
5150 "Only declaration template arguments permitted here");
5151
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005152 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5153
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005154 if (VD->getDeclContext()->isRecord() &&
David Majnemer3ae0bfa2013-10-26 05:02:13 +00005155 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5156 isa<IndirectFieldDecl>(VD))) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005157 // If the value is a class member, we might have a pointer-to-member.
5158 // Determine whether the non-type template template parameter is of
5159 // pointer-to-member type. If so, we need to build an appropriate
5160 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5161 // would refer to the member itself.
5162 if (ParamType->isMemberPointerType()) {
5163 QualType ClassType
5164 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5165 NestedNameSpecifier *Qualifier
Craig Topperc3ec1492014-05-26 06:22:03 +00005166 = NestedNameSpecifier::Create(Context, nullptr, false,
John McCallb268a282010-08-23 23:25:46 +00005167 ClassType.getTypePtr());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005168 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005169 SS.MakeTrivial(Context, Qualifier, Loc);
John McCallfeb624a2010-11-23 20:48:44 +00005170
5171 // The actual value-ness of this is unimportant, but for
5172 // internal consistency's sake, references to instance methods
5173 // are r-values.
5174 ExprValueKind VK = VK_LValue;
5175 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5176 VK = VK_RValue;
5177
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005178 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCall7decc9e2010-11-18 06:31:45 +00005179 VD->getType().getNonReferenceType(),
John McCallfeb624a2010-11-23 20:48:44 +00005180 VK,
John McCall7decc9e2010-11-18 06:31:45 +00005181 Loc,
5182 &SS);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005183 if (RefExpr.isInvalid())
5184 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005185
John McCalle3027922010-08-25 11:45:40 +00005186 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005187
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005188 // We might need to perform a trailing qualification conversion, since
5189 // the element type on the parameter could be more qualified than the
5190 // element type in the expression we constructed.
John McCall31168b02011-06-15 23:02:42 +00005191 bool ObjCLifetimeConversion;
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005192 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
John McCall31168b02011-06-15 23:02:42 +00005193 ParamType.getUnqualifiedType(), false,
5194 ObjCLifetimeConversion))
John Wiegley01296292011-04-08 18:41:53 +00005195 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005196
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005197 assert(!RefExpr.isInvalid() &&
5198 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00005199 ParamType.getUnqualifiedType()));
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005200 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005201 }
5202 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005204 QualType T = VD->getType().getNonReferenceType();
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005205
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005206 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00005207 // When the non-type template parameter is a pointer, take the
5208 // address of the declaration.
John McCall7decc9e2010-11-18 06:31:45 +00005209 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005210 if (RefExpr.isInvalid())
5211 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005212
5213 if (T->isFunctionType() || T->isArrayType()) {
5214 // Decay functions and arrays.
John Wiegley01296292011-04-08 18:41:53 +00005215 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
5216 if (RefExpr.isInvalid())
5217 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00005218
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005219 return RefExpr;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005221
Douglas Gregorb242683d2010-04-01 18:32:35 +00005222 // Take the address of everything else
John McCalle3027922010-08-25 11:45:40 +00005223 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005224 }
5225
John McCall7decc9e2010-11-18 06:31:45 +00005226 ExprValueKind VK = VK_RValue;
5227
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005228 // If the non-type template parameter has reference type, qualify the
5229 // resulting declaration reference with the extra qualifiers on the
5230 // type that the reference refers to.
John McCall7decc9e2010-11-18 06:31:45 +00005231 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5232 VK = VK_LValue;
5233 T = Context.getQualifiedType(T,
5234 TargetRef->getPointeeType().getQualifiers());
Douglas Gregoreffe2a12013-01-16 00:52:15 +00005235 } else if (isa<FunctionDecl>(VD)) {
5236 // References to functions are always lvalues.
5237 VK = VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00005238 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005239
John McCall7decc9e2010-11-18 06:31:45 +00005240 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005241}
5242
5243/// \brief Construct a new expression that refers to the given
5244/// integral template argument with the given source-location
5245/// information.
5246///
5247/// This routine takes care of the mapping from an integral template
5248/// argument (which may have any integral type) to the appropriate
5249/// literal value.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005250ExprResult
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005251Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5252 SourceLocation Loc) {
5253 assert(Arg.getKind() == TemplateArgument::Integral &&
Douglas Gregora8bac7f2011-01-10 07:32:04 +00005254 "Operation is only valid for integral template arguments");
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005255 QualType OrigT = Arg.getIntegralType();
5256
5257 // If this is an enum type that we're instantiating, we need to use an integer
5258 // type the same size as the enumerator. We don't want to build an
5259 // IntegerLiteral with enum type. The integer type of an enum type can be of
5260 // any integral type with C++11 enum classes, make sure we create the right
5261 // type of literal for it.
5262 QualType T = OrigT;
5263 if (const EnumType *ET = OrigT->getAs<EnumType>())
5264 T = ET->getDecl()->getIntegerType();
5265
5266 Expr *E;
Douglas Gregorfb65e592011-07-27 05:40:30 +00005267 if (T->isAnyCharacterType()) {
5268 CharacterLiteral::CharacterKind Kind;
5269 if (T->isWideCharType())
5270 Kind = CharacterLiteral::Wide;
5271 else if (T->isChar16Type())
5272 Kind = CharacterLiteral::UTF16;
5273 else if (T->isChar32Type())
5274 Kind = CharacterLiteral::UTF32;
5275 else
5276 Kind = CharacterLiteral::Ascii;
5277
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005278 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5279 Kind, T, Loc);
5280 } else if (T->isBooleanType()) {
5281 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5282 T, Loc);
5283 } else if (T->isNullPtrType()) {
5284 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5285 } else {
5286 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
Douglas Gregorfb65e592011-07-27 05:40:30 +00005287 }
5288
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005289 if (OrigT->isEnumeralType()) {
John McCall6730e4d2011-07-15 07:47:58 +00005290 // FIXME: This is a hack. We need a better way to handle substituted
5291 // non-type template parameters.
Craig Topperc3ec1492014-05-26 06:22:03 +00005292 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5293 nullptr,
Benjamin Kramer3d3ddce2012-11-21 17:42:47 +00005294 Context.getTrivialTypeSourceInfo(OrigT, Loc),
John McCall6730e4d2011-07-15 07:47:58 +00005295 Loc, Loc);
5296 }
5297
5298 return Owned(E);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005299}
5300
Douglas Gregor641040a2011-01-12 23:45:44 +00005301/// \brief Match two template parameters within template parameter lists.
5302static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5303 bool Complain,
5304 Sema::TemplateParameterListEqualKind Kind,
5305 SourceLocation TemplateArgLoc) {
5306 // Check the actual kind (type, non-type, template).
5307 if (Old->getKind() != New->getKind()) {
5308 if (Complain) {
5309 unsigned NextDiag = diag::err_template_param_different_kind;
5310 if (TemplateArgLoc.isValid()) {
5311 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5312 NextDiag = diag::note_template_param_different_kind;
5313 }
5314 S.Diag(New->getLocation(), NextDiag)
5315 << (Kind != Sema::TPL_TemplateMatch);
5316 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5317 << (Kind != Sema::TPL_TemplateMatch);
5318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005319
Douglas Gregor641040a2011-01-12 23:45:44 +00005320 return false;
5321 }
5322
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005323 // Check that both are parameter packs are neither are parameter packs.
5324 // However, if we are matching a template template argument to a
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005325 // template template parameter, the template template parameter can have
5326 // a parameter pack where the template template argument does not.
5327 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5328 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5329 Old->isTemplateParameterPack())) {
Douglas Gregor641040a2011-01-12 23:45:44 +00005330 if (Complain) {
5331 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5332 if (TemplateArgLoc.isValid()) {
5333 S.Diag(TemplateArgLoc,
5334 diag::err_template_arg_template_params_mismatch);
5335 NextDiag = diag::note_template_parameter_pack_non_pack;
5336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005337
Douglas Gregor641040a2011-01-12 23:45:44 +00005338 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5339 : isa<NonTypeTemplateParmDecl>(New)? 1
5340 : 2;
5341 S.Diag(New->getLocation(), NextDiag)
5342 << ParamKind << New->isParameterPack();
5343 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5344 << ParamKind << Old->isParameterPack();
5345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005346
Douglas Gregor641040a2011-01-12 23:45:44 +00005347 return false;
5348 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349
Douglas Gregor641040a2011-01-12 23:45:44 +00005350 // For non-type template parameters, check the type of the parameter.
5351 if (NonTypeTemplateParmDecl *OldNTTP
5352 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5353 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005354
Douglas Gregor641040a2011-01-12 23:45:44 +00005355 // If we are matching a template template argument to a template
5356 // template parameter and one of the non-type template parameter types
5357 // is dependent, then we must wait until template instantiation time
5358 // to actually compare the arguments.
5359 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5360 (OldNTTP->getType()->isDependentType() ||
5361 NewNTTP->getType()->isDependentType()))
5362 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005363
Douglas Gregor641040a2011-01-12 23:45:44 +00005364 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5365 if (Complain) {
5366 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5367 if (TemplateArgLoc.isValid()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368 S.Diag(TemplateArgLoc,
Douglas Gregor641040a2011-01-12 23:45:44 +00005369 diag::err_template_arg_template_params_mismatch);
5370 NextDiag = diag::note_template_nontype_parm_different_type;
5371 }
5372 S.Diag(NewNTTP->getLocation(), NextDiag)
5373 << NewNTTP->getType()
5374 << (Kind != Sema::TPL_TemplateMatch);
5375 S.Diag(OldNTTP->getLocation(),
5376 diag::note_template_nontype_parm_prev_declaration)
5377 << OldNTTP->getType();
5378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005379
Douglas Gregor641040a2011-01-12 23:45:44 +00005380 return false;
5381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005382
Douglas Gregor641040a2011-01-12 23:45:44 +00005383 return true;
5384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385
Douglas Gregor641040a2011-01-12 23:45:44 +00005386 // For template template parameters, check the template parameter types.
5387 // The template parameter lists of template template
5388 // parameters must agree.
5389 if (TemplateTemplateParmDecl *OldTTP
5390 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
Douglas Gregor641040a2011-01-12 23:45:44 +00005392 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5393 OldTTP->getTemplateParameters(),
5394 Complain,
5395 (Kind == Sema::TPL_TemplateMatch
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005396 ? Sema::TPL_TemplateTemplateParmMatch
Douglas Gregor641040a2011-01-12 23:45:44 +00005397 : Kind),
5398 TemplateArgLoc);
5399 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005400
Douglas Gregor641040a2011-01-12 23:45:44 +00005401 return true;
5402}
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00005403
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005404/// \brief Diagnose a known arity mismatch when comparing template argument
5405/// lists.
5406static
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005407void DiagnoseTemplateParameterListArityMismatch(Sema &S,
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005408 TemplateParameterList *New,
5409 TemplateParameterList *Old,
5410 Sema::TemplateParameterListEqualKind Kind,
5411 SourceLocation TemplateArgLoc) {
5412 unsigned NextDiag = diag::err_template_param_list_different_arity;
5413 if (TemplateArgLoc.isValid()) {
5414 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5415 NextDiag = diag::note_template_param_list_different_arity;
5416 }
5417 S.Diag(New->getTemplateLoc(), NextDiag)
5418 << (New->size() > Old->size())
5419 << (Kind != Sema::TPL_TemplateMatch)
5420 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5421 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5422 << (Kind != Sema::TPL_TemplateMatch)
5423 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5424}
5425
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005426/// \brief Determine whether the given template parameter lists are
5427/// equivalent.
5428///
Mike Stump11289f42009-09-09 15:08:12 +00005429/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005430/// source code as part of a new template declaration.
5431///
5432/// \param Old The old template parameter list, typically found via
5433/// name lookup of the template declared with this template parameter
5434/// list.
5435///
5436/// \param Complain If true, this routine will produce a diagnostic if
5437/// the template parameter lists are not equivalent.
5438///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005439/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00005440///
5441/// \param TemplateArgLoc If this source location is valid, then we
5442/// are actually checking the template parameter list of a template
5443/// argument (New) against the template parameter list of its
5444/// corresponding template template parameter (Old). We produce
5445/// slightly different diagnostics in this scenario.
5446///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005447/// \returns True if the template parameter lists are equal, false
5448/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005449bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005450Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5451 TemplateParameterList *Old,
5452 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00005453 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00005454 SourceLocation TemplateArgLoc) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005455 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5456 if (Complain)
5457 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5458 TemplateArgLoc);
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005459
5460 return false;
5461 }
5462
Douglas Gregor641040a2011-01-12 23:45:44 +00005463 // C++0x [temp.arg.template]p3:
5464 // A template-argument matches a template template-parameter (call it P)
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005465 // when each of the template parameters in the template-parameter-list of
Richard Smith3f1b5d02011-05-05 21:57:07 +00005466 // the template-argument's corresponding class template or alias template
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005467 // (call it A) matches the corresponding template parameter in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005468 // template-parameter-list of P. [...]
5469 TemplateParameterList::iterator NewParm = New->begin();
5470 TemplateParameterList::iterator NewParmEnd = New->end();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005471 for (TemplateParameterList::iterator OldParm = Old->begin(),
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005472 OldParmEnd = Old->end();
5473 OldParm != OldParmEnd; ++OldParm) {
Douglas Gregor018778a2011-01-13 18:47:47 +00005474 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5475 !(*OldParm)->isTemplateParameterPack()) {
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005476 if (NewParm == NewParmEnd) {
5477 if (Complain)
5478 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5479 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005481 return false;
5482 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005483
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005484 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5485 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005486 return false;
5487
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005488 ++NewParm;
5489 continue;
5490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005491
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005492 // C++0x [temp.arg.template]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005493 // [...] When P's template- parameter-list contains a template parameter
5494 // pack (14.5.3), the template parameter pack will match zero or more
5495 // template parameters or template parameter packs in the
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005496 // template-parameter-list of A with the same type and form as the
5497 // template parameter pack in P (ignoring whether those template
5498 // parameters are template parameter packs).
5499 for (; NewParm != NewParmEnd; ++NewParm) {
5500 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5501 Kind, TemplateArgLoc))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005502 return false;
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005503 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005506 // Make sure we exhausted all of the arguments.
5507 if (NewParm != NewParmEnd) {
5508 if (Complain)
5509 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5510 TemplateArgLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005511
Douglas Gregorfd4344b2011-01-13 00:08:50 +00005512 return false;
5513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005515 return true;
5516}
5517
5518/// \brief Check whether a template can be declared within this scope.
5519///
5520/// If the template declaration is valid in this scope, returns
5521/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00005522bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005523Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregordd847ba2011-11-03 16:37:14 +00005524 if (!S)
5525 return false;
5526
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005527 // Find the nearest enclosing declaration scope.
5528 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5529 (S->getFlags() & Scope::TemplateParamScope) != 0)
5530 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00005531
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005532 // C++ [temp]p4:
5533 // A template [...] shall not have C linkage.
Ted Kremenekc37877d2013-10-08 17:08:03 +00005534 DeclContext *Ctx = S->getEntity();
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005535 if (Ctx && Ctx->isExternCContext())
Mike Stump11289f42009-09-09 15:08:12 +00005536 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005537 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005538
Eli Friedmandfbd0c42009-07-31 01:43:05 +00005539 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005540 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005541
Benjamin Kramer35e6fee2014-02-02 16:35:43 +00005542 // C++ [temp]p2:
5543 // A template-declaration can appear only as a namespace scope or
5544 // class scope declaration.
David Majnemer766e2592013-10-22 04:14:18 +00005545 if (Ctx) {
5546 if (Ctx->isFileContext())
5547 return false;
5548 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5549 // C++ [temp.mem]p2:
5550 // A local class shall not have member templates.
5551 if (RD->isLocalClass())
5552 return Diag(TemplateParams->getTemplateLoc(),
5553 diag::err_template_inside_local_class)
5554 << TemplateParams->getSourceRange();
5555 else
5556 return false;
5557 }
5558 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005559
Mike Stump11289f42009-09-09 15:08:12 +00005560 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005561 diag::err_template_outside_namespace_or_class_scope)
5562 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00005563}
Douglas Gregor67a65642009-02-17 23:15:12 +00005564
Douglas Gregor54888652009-10-07 00:13:32 +00005565/// \brief Determine what kind of template specialization the given declaration
5566/// is.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00005567static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
Douglas Gregor54888652009-10-07 00:13:32 +00005568 if (!D)
5569 return TSK_Undeclared;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005570
Douglas Gregorbbe8f462009-10-08 15:14:33 +00005571 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5572 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00005573 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5574 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00005575 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5576 return Var->getTemplateSpecializationKind();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
Douglas Gregor54888652009-10-07 00:13:32 +00005578 return TSK_Undeclared;
5579}
5580
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581/// \brief Check whether a specialization is well-formed in the current
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005582/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00005583///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005584/// This routine determines whether a template specialization can be declared
5585/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00005586///
5587/// \param S the semantic analysis object for which this check is being
5588/// performed.
5589///
5590/// \param Specialized the entity being specialized or instantiated, which
5591/// may be a kind of template (class template, function template, etc.) or
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592/// a member of a class template (member function, static data member,
Douglas Gregor54888652009-10-07 00:13:32 +00005593/// member class).
5594///
5595/// \param PrevDecl the previous declaration of this entity, if any.
5596///
5597/// \param Loc the location of the explicit specialization or instantiation of
5598/// this entity.
5599///
5600/// \param IsPartialSpecialization whether this is a partial specialization of
5601/// a class template.
5602///
Douglas Gregor54888652009-10-07 00:13:32 +00005603/// \returns true if there was an error that we cannot recover from, false
5604/// otherwise.
5605static bool CheckTemplateSpecializationScope(Sema &S,
5606 NamedDecl *Specialized,
5607 NamedDecl *PrevDecl,
5608 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005609 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00005610 // Keep these "kind" numbers in sync with the %select statements in the
5611 // various diagnostics emitted by this routine.
5612 int EntityKind = 0;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005613 if (isa<ClassTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005614 EntityKind = IsPartialSpecialization? 1 : 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005615 else if (isa<VarTemplateDecl>(Specialized))
5616 EntityKind = IsPartialSpecialization ? 3 : 2;
Ted Kremenek7f1f3f62011-01-14 22:31:36 +00005617 else if (isa<FunctionTemplateDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005618 EntityKind = 4;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005619 else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00005620 EntityKind = 5;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005621 else if (isa<VarDecl>(Specialized))
Richard Smith7d137e32012-03-23 03:33:32 +00005622 EntityKind = 6;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005623 else if (isa<RecordDecl>(Specialized))
5624 EntityKind = 7;
5625 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5626 EntityKind = 8;
Douglas Gregor54888652009-10-07 00:13:32 +00005627 else {
Richard Smith7d137e32012-03-23 03:33:32 +00005628 S.Diag(Loc, diag::err_template_spec_unknown_kind)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005629 << S.getLangOpts().CPlusPlus11;
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005630 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00005631 return true;
5632 }
5633
Douglas Gregorf47b9112009-02-25 22:02:03 +00005634 // C++ [temp.expl.spec]p2:
5635 // An explicit specialization shall be declared in the namespace
5636 // of which the template is a member, or, for member templates, in
5637 // the namespace of which the enclosing class or enclosing class
5638 // template is a member. An explicit specialization of a member
5639 // function, member class or static data member of a class
5640 // template shall be declared in the namespace of which the class
5641 // template is a member. Such a declaration may also be a
5642 // definition. If the declaration is not a definition, the
5643 // specialization may be defined later in the name- space in which
5644 // the explicit specialization was declared, or in a namespace
5645 // that encloses the one in which the explicit specialization was
5646 // declared.
Sebastian Redl50c68252010-08-31 00:36:30 +00005647 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor54888652009-10-07 00:13:32 +00005648 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005649 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005650 return true;
5651 }
Douglas Gregore4b05162009-10-07 17:21:34 +00005652
Douglas Gregor40fb7442009-10-07 17:30:37 +00005653 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005654 if (S.getLangOpts().MicrosoftExt) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00005655 // Do not warn for class scope explicit specialization during
5656 // instantiation, warning was already emitted during pattern
5657 // semantic analysis.
5658 if (!S.ActiveTemplateInstantiations.size())
5659 S.Diag(Loc, diag::ext_function_specialization_in_class)
5660 << Specialized;
5661 } else {
5662 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5663 << Specialized;
5664 return true;
5665 }
Douglas Gregor40fb7442009-10-07 17:30:37 +00005666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005667
Douglas Gregor44e5a0a2011-10-20 16:41:18 +00005668 if (S.CurContext->isRecord() &&
5669 !S.CurContext->Equals(Specialized->getDeclContext())) {
5670 // Make sure that we're specializing in the right record context.
5671 // Otherwise, things can go horribly wrong.
5672 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5673 << Specialized;
5674 return true;
5675 }
5676
Douglas Gregore4b05162009-10-07 17:21:34 +00005677 // C++ [temp.class.spec]p6:
5678 // A class template partial specialization may be declared or redeclared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005679 // in any namespace scope in which its definition may be defined (14.5.1
5680 // and 14.5.2).
Richard Smitha98f8fc2013-12-07 05:09:50 +00005681 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00005682 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00005683 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Richard Smitha98f8fc2013-12-07 05:09:50 +00005684
5685 // Make sure that this redeclaration (or definition) occurs in an enclosing
5686 // namespace.
5687 // Note that HandleDeclarator() performs this check for explicit
5688 // specializations of function templates, static data members, and member
5689 // functions, so we skip the check here for those kinds of entities.
5690 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5691 // Should we refactor that check, so that it occurs later?
5692 if (!DC->Encloses(SpecializedContext) &&
5693 !(isa<FunctionTemplateDecl>(Specialized) ||
5694 isa<FunctionDecl>(Specialized) ||
5695 isa<VarTemplateDecl>(Specialized) ||
5696 isa<VarDecl>(Specialized))) {
5697 if (isa<TranslationUnitDecl>(SpecializedContext))
5698 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5699 << EntityKind << Specialized;
5700 else if (isa<NamespaceDecl>(SpecializedContext))
5701 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5702 << EntityKind << Specialized
5703 << cast<NamedDecl>(SpecializedContext);
5704 else
5705 llvm_unreachable("unexpected namespace context for specialization");
5706
5707 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5708 } else if ((!PrevDecl ||
5709 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5710 getTemplateSpecializationKind(PrevDecl) ==
5711 TSK_ImplicitInstantiation)) {
Douglas Gregorb1aab432010-09-12 05:08:28 +00005712 // C++ [temp.exp.spec]p2:
5713 // An explicit specialization shall be declared in the namespace of which
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005714 // the template is a member, or, for member templates, in the namespace
Douglas Gregorb1aab432010-09-12 05:08:28 +00005715 // of which the enclosing class or enclosing class template is a member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005716 // An explicit specialization of a member function, member class or
5717 // static data member of a class template shall be declared in the
Douglas Gregorb1aab432010-09-12 05:08:28 +00005718 // namespace of which the class template is a member.
5719 //
Richard Smitha98f8fc2013-12-07 05:09:50 +00005720 // C++11 [temp.expl.spec]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005721 // An explicit specialization shall be declared in a namespace enclosing
Douglas Gregorb1aab432010-09-12 05:08:28 +00005722 // the specialized template.
Richard Smitha98f8fc2013-12-07 05:09:50 +00005723 // C++11 [temp.explicit]p3:
5724 // An explicit instantiation shall appear in an enclosing namespace of its
5725 // template.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005726 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005727 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
Richard Smith0bf8a4922011-10-18 20:49:44 +00005728 if (isa<TranslationUnitDecl>(SpecializedContext)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005729 assert(!IsCPlusPlus11Extension &&
Richard Smith0bf8a4922011-10-18 20:49:44 +00005730 "DC encloses TU but isn't in enclosing namespace set");
5731 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
Douglas Gregor8ce63152010-09-12 05:24:55 +00005732 << EntityKind << Specialized;
Richard Smith0bf8a4922011-10-18 20:49:44 +00005733 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5734 int Diag;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005735 if (!IsCPlusPlus11Extension)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005736 Diag = diag::err_template_spec_decl_out_of_scope;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005737 else if (!S.getLangOpts().CPlusPlus11)
Richard Smith0bf8a4922011-10-18 20:49:44 +00005738 Diag = diag::ext_template_spec_decl_out_of_scope;
5739 else
5740 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5741 S.Diag(Loc, Diag)
5742 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5743 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005744
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00005745 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00005746 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005748
Douglas Gregorf47b9112009-02-25 22:02:03 +00005749 return false;
5750}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751
Richard Smith6056d5e2014-02-09 00:54:43 +00005752static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5753 if (!E->isInstantiationDependent())
5754 return SourceLocation();
5755 DependencyChecker Checker(Depth);
5756 Checker.TraverseStmt(E);
5757 if (Checker.Match && Checker.MatchLoc.isInvalid())
5758 return E->getSourceRange();
5759 return Checker.MatchLoc;
5760}
5761
5762static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5763 if (!TL.getType()->isDependentType())
5764 return SourceLocation();
5765 DependencyChecker Checker(Depth);
5766 Checker.TraverseTypeLoc(TL);
5767 if (Checker.Match && Checker.MatchLoc.isInvalid())
5768 return TL.getSourceRange();
5769 return Checker.MatchLoc;
5770}
5771
Larisse Voufo39a1e502013-08-06 01:03:05 +00005772/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005773/// that checks non-type template partial specialization arguments.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005774static bool CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005775 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5776 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005777 for (unsigned I = 0; I != NumArgs; ++I) {
5778 if (Args[I].getKind() == TemplateArgument::Pack) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00005779 if (CheckNonTypeTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005780 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5781 Args[I].pack_size(), IsDefaultArgument))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005782 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005783
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005784 continue;
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005786
Eli Friedmanb826a002012-09-26 02:36:12 +00005787 if (Args[I].getKind() != TemplateArgument::Expression)
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005788 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +00005789
5790 Expr *ArgExpr = Args[I].getAsExpr();
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005791
Douglas Gregor98318c22011-01-03 21:37:45 +00005792 // We can have a pack expansion of any of the bullets below.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005793 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5794 ArgExpr = Expansion->getPattern();
Douglas Gregorca4686d2011-01-04 23:35:54 +00005795
5796 // Strip off any implicit casts we added as part of type checking.
5797 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5798 ArgExpr = ICE->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005799
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005800 // C++ [temp.class.spec]p8:
5801 // A non-type argument is non-specialized if it is the name of a
5802 // non-type parameter. All other non-type arguments are
5803 // specialized.
5804 //
5805 // Below, we check the two conditions that only apply to
5806 // specialized non-type arguments, so skip any non-specialized
5807 // arguments.
5808 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorca4686d2011-01-04 23:35:54 +00005809 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005810 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005811
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005812 // C++ [temp.class.spec]p9:
5813 // Within the argument list of a class template partial
5814 // specialization, the following restrictions apply:
5815 // -- A partially specialized non-type argument expression
5816 // shall not involve a template parameter of the partial
5817 // specialization except when the argument expression is a
5818 // simple identifier.
Richard Smith6056d5e2014-02-09 00:54:43 +00005819 SourceRange ParamUseRange =
5820 findTemplateParameter(Param->getDepth(), ArgExpr);
5821 if (ParamUseRange.isValid()) {
5822 if (IsDefaultArgument) {
5823 S.Diag(TemplateNameLoc,
5824 diag::err_dependent_non_type_arg_in_partial_spec);
5825 S.Diag(ParamUseRange.getBegin(),
5826 diag::note_dependent_non_type_default_arg_in_partial_spec)
5827 << ParamUseRange;
5828 } else {
5829 S.Diag(ParamUseRange.getBegin(),
5830 diag::err_dependent_non_type_arg_in_partial_spec)
5831 << ParamUseRange;
5832 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005833 return true;
5834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005835
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005836 // -- The type of a template parameter corresponding to a
5837 // specialized non-type argument shall not be dependent on a
5838 // parameter of the specialization.
Richard Smith6056d5e2014-02-09 00:54:43 +00005839 //
5840 // FIXME: We need to delay this check until instantiation in some cases:
5841 //
5842 // template<template<typename> class X> struct A {
5843 // template<typename T, X<T> N> struct B;
5844 // template<typename T> struct B<T, 0>;
5845 // };
5846 // template<typename> using X = int;
5847 // A<X>::B<int, 0> b;
5848 ParamUseRange = findTemplateParameter(
5849 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
5850 if (ParamUseRange.isValid()) {
5851 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
5852 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5853 << Param->getType() << ParamUseRange;
5854 S.Diag(Param->getLocation(), diag::note_template_param_here)
5855 << (IsDefaultArgument ? ParamUseRange : SourceRange());
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005856 return true;
5857 }
5858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005859
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005860 return false;
5861}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005862
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005863/// \brief Check the non-type template arguments of a class template
5864/// partial specialization according to C++ [temp.class.spec]p9.
5865///
Richard Smith6056d5e2014-02-09 00:54:43 +00005866/// \param TemplateNameLoc the location of the template name.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005867/// \param TemplateParams the template parameters of the primary class
Richard Smith6056d5e2014-02-09 00:54:43 +00005868/// template.
5869/// \param NumExplicit the number of explicitly-specified template arguments.
James Dennett634962f2012-06-14 21:40:34 +00005870/// \param TemplateArgs the template arguments of the class template
Richard Smith6056d5e2014-02-09 00:54:43 +00005871/// partial specialization.
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005872///
Richard Smith6056d5e2014-02-09 00:54:43 +00005873/// \returns \c true if there was an error, \c false otherwise.
Larisse Voufo39a1e502013-08-06 01:03:05 +00005874static bool CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00005875 Sema &S, SourceLocation TemplateNameLoc,
5876 TemplateParameterList *TemplateParams, unsigned NumExplicit,
Larisse Voufo39a1e502013-08-06 01:03:05 +00005877 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005878 const TemplateArgument *ArgList = TemplateArgs.data();
5879
5880 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5881 NonTypeTemplateParmDecl *Param
5882 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5883 if (!Param)
5884 continue;
5885
Richard Smith6056d5e2014-02-09 00:54:43 +00005886 if (CheckNonTypeTemplatePartialSpecializationArgs(
5887 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
Douglas Gregor875b6fe2011-01-03 21:13:47 +00005888 return true;
5889 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00005890
5891 return false;
5892}
5893
John McCall48871652010-08-21 09:40:31 +00005894DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00005895Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5896 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00005897 SourceLocation KWLoc,
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00005898 SourceLocation ModulePrivateLoc,
Richard Smith4b55a9c2014-04-17 03:29:33 +00005899 TemplateIdAnnotation &TemplateId,
Douglas Gregor67a65642009-02-17 23:15:12 +00005900 AttributeList *Attr,
5901 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00005902 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00005903
Richard Smith4b55a9c2014-04-17 03:29:33 +00005904 CXXScopeSpec &SS = TemplateId.SS;
5905
Abramo Bagnara60804e12011-03-18 15:16:37 +00005906 // NOTE: KWLoc is the location of the tag keyword. This will instead
5907 // store the location of the outermost template keyword in the declaration.
5908 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
Richard Smith4b55a9c2014-04-17 03:29:33 +00005909 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
5910 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
5911 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
5912 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
Abramo Bagnara60804e12011-03-18 15:16:37 +00005913
Douglas Gregor67a65642009-02-17 23:15:12 +00005914 // Find the class template we're specializing
Richard Smith4b55a9c2014-04-17 03:29:33 +00005915 TemplateName Name = TemplateId.Template.get();
Mike Stump11289f42009-09-09 15:08:12 +00005916 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00005917 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5918
5919 if (!ClassTemplate) {
5920 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005921 << (Name.getAsTemplateDecl() &&
Douglas Gregordd6c0352009-11-12 00:46:20 +00005922 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5923 return true;
5924 }
Douglas Gregor67a65642009-02-17 23:15:12 +00005925
Douglas Gregor5c0405d2009-10-07 22:35:40 +00005926 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00005927 bool isPartialSpecialization = false;
5928
Douglas Gregorf47b9112009-02-25 22:02:03 +00005929 // Check the validity of the template headers that introduce this
5930 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00005931 // FIXME: We probably shouldn't complain about these headers for
5932 // friend declarations.
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005933 bool Invalid = false;
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +00005934 TemplateParameterList *TemplateParams =
5935 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +00005936 KWLoc, TemplateNameLoc, SS, &TemplateId,
5937 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
5938 Invalid);
Douglas Gregor5f0e2522010-07-14 23:14:12 +00005939 if (Invalid)
5940 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005941
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005942 if (TemplateParams && TemplateParams->size() > 0) {
5943 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00005944
Douglas Gregorec9518b2010-12-21 08:14:57 +00005945 if (TUK == TUK_Friend) {
5946 Diag(KWLoc, diag::err_partial_specialization_friend)
5947 << SourceRange(LAngleLoc, RAngleLoc);
5948 return true;
5949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005950
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005951 // C++ [temp.class.spec]p10:
5952 // The template parameter list of a specialization shall not
5953 // contain default template argument values.
5954 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5955 Decl *Param = TemplateParams->getParam(I);
5956 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5957 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00005958 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005959 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00005960 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005961 }
5962 } else if (NonTypeTemplateParmDecl *NTTP
5963 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5964 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00005965 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005966 diag::err_default_arg_in_partial_spec)
5967 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00005968 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005969 }
5970 } else {
5971 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005972 if (TTP->hasDefaultArgument()) {
5973 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00005974 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005975 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00005976 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00005977 }
5978 }
5979 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005980 } else if (TemplateParams) {
5981 if (TUK == TUK_Friend)
5982 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00005983 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005984 SourceRange(TemplateParams->getTemplateLoc(),
5985 TemplateParams->getRAngleLoc()))
5986 << SourceRange(LAngleLoc, RAngleLoc);
5987 else
5988 isExplicitSpecialization = true;
Richard Smith4b55a9c2014-04-17 03:29:33 +00005989 } else {
5990 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00005991 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00005992
Douglas Gregor67a65642009-02-17 23:15:12 +00005993 // Check that the specialization uses the same tag kind as the
5994 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00005995 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5996 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00005997 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00005998 Kind, TUK == TUK_Definition, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00005999 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00006000 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006001 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00006002 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00006003 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00006004 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006005 diag::note_previous_use);
6006 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6007 }
6008
Douglas Gregorc40290e2009-03-09 23:48:35 +00006009 // Translate the parser's template argument list in our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00006010 TemplateArgumentListInfo TemplateArgs =
6011 makeTemplateArgumentListInfo(*this, TemplateId);
Douglas Gregorc40290e2009-03-09 23:48:35 +00006012
Douglas Gregor14406932011-01-03 20:35:03 +00006013 // Check for unexpanded parameter packs in any of the template arguments.
6014 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006015 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
Douglas Gregor14406932011-01-03 20:35:03 +00006016 UPPC_PartialSpecialization))
6017 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006018
Douglas Gregor67a65642009-02-17 23:15:12 +00006019 // Check that the template argument list is well-formed for this
6020 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006021 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00006022 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6023 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006024 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006025
Douglas Gregor2373c592009-05-31 09:31:02 +00006026 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00006027 // corresponds to these arguments.
Douglas Gregord5222052009-06-12 19:43:02 +00006028 if (isPartialSpecialization) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00006029 if (CheckTemplatePartialSpecializationArgs(
Richard Smith6056d5e2014-02-09 00:54:43 +00006030 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6031 TemplateArgs.size(), Converted))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00006032 return true;
6033
Douglas Gregor678d76c2011-07-01 01:22:09 +00006034 bool InstantiationDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006035 if (!Name.isDependent() &&
Douglas Gregor92354b62010-02-09 00:37:32 +00006036 !TemplateSpecializationType::anyDependentTemplateArguments(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006037 TemplateArgs.getArgumentArray(),
Douglas Gregor678d76c2011-07-01 01:22:09 +00006038 TemplateArgs.size(),
6039 InstantiationDependent)) {
Douglas Gregor92354b62010-02-09 00:37:32 +00006040 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6041 << ClassTemplate->getDeclName();
6042 isPartialSpecialization = false;
Douglas Gregor92354b62010-02-09 00:37:32 +00006043 }
6044 }
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006045
Craig Topperc3ec1492014-05-26 06:22:03 +00006046 void *InsertPos = nullptr;
6047 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00006048
6049 if (isPartialSpecialization)
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006050 // FIXME: Template parameter list matters, too
Douglas Gregor2373c592009-05-31 09:31:02 +00006051 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006052 = ClassTemplate->findPartialSpecialization(Converted.data(),
6053 Converted.size(),
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006054 InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006055 else
6056 PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006057 = ClassTemplate->findSpecialization(Converted.data(),
6058 Converted.size(), InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00006059
Craig Topperc3ec1492014-05-26 06:22:03 +00006060 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregor67a65642009-02-17 23:15:12 +00006061
Douglas Gregorf47b9112009-02-25 22:02:03 +00006062 // Check whether we can declare a class template specialization in
6063 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00006064 if (TUK != TUK_Friend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006065 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6066 TemplateNameLoc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006067 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00006068 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006069
Douglas Gregor15301382009-07-30 17:40:51 +00006070 // The canonical type
6071 QualType CanonType;
Richard Smith871cd4c2014-05-23 21:00:28 +00006072 if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00006073 // Build the canonical type that describes the converted template
6074 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00006075 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6076 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006077 Converted.data(),
6078 Converted.size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006079
6080 if (Context.hasSameType(CanonType,
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006081 ClassTemplate->getInjectedClassNameSpecialization())) {
6082 // C++ [temp.class.spec]p9b3:
6083 //
6084 // -- The argument list of the specialization shall not be identical
6085 // to the implicit argument list of the primary template.
6086 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
Richard Smith300e0c32013-09-24 04:49:23 +00006087 << /*class template*/0 << (TUK == TUK_Definition)
Douglas Gregor26701a42011-09-09 02:06:17 +00006088 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006089 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6090 ClassTemplate->getIdentifier(),
6091 TemplateNameLoc,
6092 Attr,
6093 TemplateParams,
Douglas Gregor2820e692011-09-09 19:05:14 +00006094 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006095 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006096 TemplateParameterLists.data());
Douglas Gregordd7ec4632010-12-23 17:13:55 +00006097 }
Douglas Gregor15301382009-07-30 17:40:51 +00006098
Douglas Gregor2373c592009-05-31 09:31:02 +00006099 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00006100 ClassTemplatePartialSpecializationDecl *PrevPartial
6101 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006102 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00006103 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00006104 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006105 KWLoc, TemplateNameLoc,
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00006106 TemplateParams,
6107 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006108 Converted.data(),
6109 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00006110 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00006111 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00006112 PrevPartial);
John McCall3e11ebe2010-03-15 10:12:16 +00006113 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006114 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006115 Partial->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006116 TemplateParameterLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006117 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006118 }
Douglas Gregor2373c592009-05-31 09:31:02 +00006119
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006120 if (!PrevPartial)
6121 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregor2373c592009-05-31 09:31:02 +00006122 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00006123
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006124 // If we are providing an explicit specialization of a member class
Douglas Gregor21610382009-10-29 00:04:11 +00006125 // template specialization, make a note of that.
6126 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6127 PrevPartial->setMemberSpecialization();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006128
Douglas Gregor91772d12009-06-13 00:26:55 +00006129 // Check that all of the template parameters of the class template
6130 // partial specialization are deducible from the template
6131 // arguments. If not, this class template partial specialization
6132 // will never be used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006133 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006134 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00006135 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00006136 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00006137
Benjamin Kramere0513cb2012-01-30 16:17:39 +00006138 if (!DeducibleParams.all()) {
6139 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
Douglas Gregor91772d12009-06-13 00:26:55 +00006140 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
Richard Smith300e0c32013-09-24 04:49:23 +00006141 << /*class template*/0 << (NumNonDeducible > 1)
Douglas Gregor91772d12009-06-13 00:26:55 +00006142 << SourceRange(TemplateNameLoc, RAngleLoc);
6143 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6144 if (!DeducibleParams[I]) {
6145 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6146 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00006147 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006148 diag::note_partial_spec_unused_parameter)
6149 << Param->getDeclName();
6150 else
Mike Stump11289f42009-09-09 15:08:12 +00006151 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00006152 diag::note_partial_spec_unused_parameter)
David Blaikieabe1a392014-04-02 05:58:29 +00006153 << "(anonymous)";
Douglas Gregor91772d12009-06-13 00:26:55 +00006154 }
6155 }
6156 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006157 } else {
6158 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00006159 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00006160 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00006161 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00006162 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006163 KWLoc, TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006164 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00006165 Converted.data(),
6166 Converted.size(),
Douglas Gregor67a65642009-02-17 23:15:12 +00006167 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00006168 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006169 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006170 Specialization->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006171 TemplateParameterLists.size(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006172 TemplateParameterLists.data());
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006173 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006174
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00006175 if (!PrevDecl)
6176 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregor15301382009-07-30 17:40:51 +00006177
6178 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006179 }
6180
Douglas Gregor06db9f52009-10-12 20:18:28 +00006181 // C++ [temp.expl.spec]p6:
6182 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006183 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006184 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006185 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006186 // use occurs; no diagnostic is required.
6187 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006188 bool Okay = false;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006189 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006190 // Is there any previous explicit specialization declaration?
6191 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6192 Okay = true;
6193 break;
6194 }
6195 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006196
Douglas Gregorc854c662010-02-26 06:03:23 +00006197 if (!Okay) {
6198 SourceRange Range(TemplateNameLoc, RAngleLoc);
6199 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6200 << Context.getTypeDeclType(Specialization) << Range;
6201
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006202 Diag(PrevDecl->getPointOfInstantiation(),
Douglas Gregorc854c662010-02-26 06:03:23 +00006203 diag::note_instantiation_required_here)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006204 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00006205 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00006206 return true;
6207 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00006208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006209
Douglas Gregor2208a292009-09-26 20:57:03 +00006210 // If this is not a friend, note that this is an explicit specialization.
6211 if (TUK != TUK_Friend)
6212 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00006213
6214 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006215 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00006216 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00006217 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006218 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00006219 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00006220 Diag(Def->getLocation(), diag::note_previous_definition);
6221 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00006222 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00006223 }
6224 }
6225
John McCall659a3372010-12-18 03:30:47 +00006226 if (Attr)
6227 ProcessDeclAttributeList(S, Specialization, Attr);
6228
Richard Smith034b94a2012-08-17 03:20:55 +00006229 // Add alignment attributes if necessary; these attributes are checked when
6230 // the ASTContext lays out the structure.
6231 if (TUK == TUK_Definition) {
6232 AddAlignmentAttributesForRecord(Specialization);
6233 AddMsStructLayoutForRecord(Specialization);
6234 }
6235
Douglas Gregor3c7cd6a2011-09-09 20:53:38 +00006236 if (ModulePrivateLoc.isValid())
6237 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6238 << (isPartialSpecialization? 1 : 0)
6239 << FixItHint::CreateRemoval(ModulePrivateLoc);
6240
Douglas Gregord56a91e2009-02-26 22:19:44 +00006241 // Build the fully-sugared type for this class template
6242 // specialization as the user wrote in the specialization
6243 // itself. This means that we'll pretty-print the type retrieved
6244 // from the specialization's declaration the way that the user
6245 // actually wrote the specialization, rather than formatting the
6246 // name based on the "canonical" representation used to store the
6247 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00006248 TypeSourceInfo *WrittenTy
6249 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6250 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006251 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00006252 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara60804e12011-03-18 15:16:37 +00006253 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006254 }
Douglas Gregor67a65642009-02-17 23:15:12 +00006255
Douglas Gregor1e249f82009-02-25 22:18:32 +00006256 // C++ [temp.expl.spec]p9:
6257 // A template explicit specialization is in the scope of the
6258 // namespace in which the template was defined.
6259 //
6260 // We actually implement this paragraph where we set the semantic
6261 // context (in the creation of the ClassTemplateSpecializationDecl),
6262 // but we also maintain the lexical context where the actual
6263 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00006264 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00006265
Douglas Gregor67a65642009-02-17 23:15:12 +00006266 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00006267 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00006268 Specialization->startDefinition();
6269
Douglas Gregor2208a292009-09-26 20:57:03 +00006270 if (TUK == TUK_Friend) {
6271 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6272 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00006273 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00006274 /*FIXME:*/KWLoc);
6275 Friend->setAccess(AS_public);
6276 CurContext->addDecl(Friend);
6277 } else {
6278 // Add the specialization into its lexical context, so that it can
6279 // be seen when iterating through the list of declarations in that
6280 // context. However, specializations are not found by name lookup.
6281 CurContext->addDecl(Specialization);
6282 }
John McCall48871652010-08-21 09:40:31 +00006283 return Specialization;
Douglas Gregor67a65642009-02-17 23:15:12 +00006284}
Douglas Gregor333489b2009-03-27 23:10:48 +00006285
John McCall48871652010-08-21 09:40:31 +00006286Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006287 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006288 Declarator &D) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006289 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
Dmitri Gribenko34df2202012-07-31 22:37:06 +00006290 ActOnDocumentableDecl(NewDecl);
6291 return NewDecl;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00006292}
6293
John McCall48871652010-08-21 09:40:31 +00006294Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00006295 MultiTemplateParamsArg TemplateParameterLists,
John McCall48871652010-08-21 09:40:31 +00006296 Declarator &D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006297 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006298 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump11289f42009-09-09 15:08:12 +00006299
Douglas Gregor17a7c122009-06-24 00:54:41 +00006300 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00006301 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00006302 }
Mike Stump11289f42009-09-09 15:08:12 +00006303
Douglas Gregor17a7c122009-06-24 00:54:41 +00006304 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00006305
Douglas Gregor5d1b4e32011-11-07 20:56:01 +00006306 D.setFunctionDefinitionKind(FDK_Definition);
John McCall48871652010-08-21 09:40:31 +00006307 Decl *DP = HandleDeclarator(ParentScope, D,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006308 TemplateParameterLists);
Argyrios Kyrtzidis6fada2d2012-12-14 06:53:58 +00006309 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Douglas Gregor17a7c122009-06-24 00:54:41 +00006310}
6311
John McCall4f7ced62010-02-11 01:33:53 +00006312/// \brief Strips various properties off an implicit instantiation
6313/// that has just been explicitly specialized.
6314static void StripImplicitInstantiation(NamedDecl *D) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006315 D->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00006316
6317 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6318 FD->setInlineSpecified(false);
Jordan Rosea0a86be2013-03-08 22:25:36 +00006319
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006320 for (auto I : FD->params())
6321 I->dropAttrs();
John McCall4f7ced62010-02-11 01:33:53 +00006322 }
6323}
6324
Nico Webera8f80b32012-01-09 19:52:25 +00006325/// \brief Compute the diagnostic location for an explicit instantiation
6326// declaration or definition.
6327static SourceLocation DiagLocForExplicitInstantiation(
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006328 NamedDecl* D, SourceLocation PointOfInstantiation) {
Nico Webera8f80b32012-01-09 19:52:25 +00006329 // Explicit instantiations following a specialization have no effect and
6330 // hence no PointOfInstantiation. In that case, walk decl backwards
6331 // until a valid name loc is found.
6332 SourceLocation PrevDiagLoc = PointOfInstantiation;
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006333 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6334 Prev = Prev->getPreviousDecl()) {
Nico Webera8f80b32012-01-09 19:52:25 +00006335 PrevDiagLoc = Prev->getLocation();
6336 }
6337 assert(PrevDiagLoc.isValid() &&
6338 "Explicit instantiation without point of instantiation?");
6339 return PrevDiagLoc;
6340}
6341
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006342/// \brief Diagnose cases where we have an explicit template specialization
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006343/// before/after an explicit template instantiation, producing diagnostics
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006344/// for those cases where they are required and determining whether the
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006345/// new specialization/instantiation will have any effect.
6346///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006347/// \param NewLoc the location of the new explicit specialization or
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006348/// instantiation.
6349///
6350/// \param NewTSK the kind of the new explicit specialization or instantiation.
6351///
6352/// \param PrevDecl the previous declaration of the entity.
6353///
6354/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6355///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006356/// \param PrevPointOfInstantiation if valid, indicates where the previus
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006357/// declaration was instantiated (either implicitly or explicitly).
6358///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006359/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006360/// specialization or instantiation has no effect and should be ignored.
6361///
6362/// \returns true if there was an error that should prevent the introduction of
6363/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00006364bool
6365Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6366 TemplateSpecializationKind NewTSK,
6367 NamedDecl *PrevDecl,
6368 TemplateSpecializationKind PrevTSK,
6369 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00006370 bool &HasNoEffect) {
6371 HasNoEffect = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006372
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006373 switch (NewTSK) {
6374 case TSK_Undeclared:
6375 case TSK_ImplicitInstantiation:
David Majnemer192d1792013-11-27 08:20:38 +00006376 assert(
6377 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6378 "previous declaration must be implicit!");
6379 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006380
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006381 case TSK_ExplicitSpecialization:
6382 switch (PrevTSK) {
6383 case TSK_Undeclared:
6384 case TSK_ExplicitSpecialization:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006385 // Okay, we're just specializing something that is either already
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006386 // explicitly specialized or has merely been mentioned without any
6387 // instantiation.
6388 return false;
6389
6390 case TSK_ImplicitInstantiation:
6391 if (PrevPointOfInstantiation.isInvalid()) {
6392 // The declaration itself has not actually been instantiated, so it is
6393 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00006394 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006395 return false;
6396 }
6397 // Fall through
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006398
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006399 case TSK_ExplicitInstantiationDeclaration:
6400 case TSK_ExplicitInstantiationDefinition:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401 assert((PrevTSK == TSK_ImplicitInstantiation ||
6402 PrevPointOfInstantiation.isValid()) &&
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006403 "Explicit instantiation without point of instantiation?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006404
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006405 // C++ [temp.expl.spec]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006406 // If a template, a member template or the member of a class template
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006407 // is explicitly specialized then that specialization shall be declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006408 // before the first use of that specialization that would cause an
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006409 // implicit instantiation to take place, in every translation unit in
6410 // which such a use occurs; no diagnostic is required.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006411 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00006412 // Is there any previous explicit specialization declaration?
6413 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6414 return false;
6415 }
6416
Douglas Gregor1d957a32009-10-27 18:42:08 +00006417 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006418 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00006419 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006420 << (PrevTSK != TSK_ImplicitInstantiation);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006421
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006422 return true;
6423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006424
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006425 case TSK_ExplicitInstantiationDeclaration:
6426 switch (PrevTSK) {
6427 case TSK_ExplicitInstantiationDeclaration:
6428 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00006429 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006430 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006431
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006432 case TSK_Undeclared:
6433 case TSK_ImplicitInstantiation:
6434 // We're explicitly instantiating something that may have already been
6435 // implicitly instantiated; that's fine.
6436 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006437
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006438 case TSK_ExplicitSpecialization:
6439 // C++0x [temp.explicit]p4:
6440 // For a given set of template parameters, if an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006441 // of a template appears after a declaration of an explicit
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006442 // specialization for that template, the explicit instantiation has no
6443 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006444 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006445 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006446
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006447 case TSK_ExplicitInstantiationDefinition:
6448 // C++0x [temp.explicit]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006449 // If an entity is the subject of both an explicit instantiation
6450 // declaration and an explicit instantiation definition in the same
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006451 // translation unit, the definition shall follow the declaration.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006452 Diag(NewLoc,
Douglas Gregor1d957a32009-10-27 18:42:08 +00006453 diag::err_explicit_instantiation_declaration_after_definition);
Nico Weberd3bdadf2011-12-23 20:58:04 +00006454
6455 // Explicit instantiations following a specialization have no effect and
6456 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6457 // until a valid name loc is found.
Nico Webera8f80b32012-01-09 19:52:25 +00006458 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6459 diag::note_explicit_instantiation_definition_here);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006460 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006461 return false;
6462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006463
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006464 case TSK_ExplicitInstantiationDefinition:
6465 switch (PrevTSK) {
6466 case TSK_Undeclared:
6467 case TSK_ImplicitInstantiation:
6468 // We're explicitly instantiating something that may have already been
6469 // implicitly instantiated; that's fine.
6470 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006471
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006472 case TSK_ExplicitSpecialization:
6473 // C++ DR 259, C++0x [temp.explicit]p4:
6474 // For a given set of template parameters, if an explicit
6475 // instantiation of a template appears after a declaration of
6476 // an explicit specialization for that template, the explicit
6477 // instantiation has no effect.
6478 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006479 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00006480 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006481 // has been explicitly specialized.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006482 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006483 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6484 diag::ext_explicit_instantiation_after_specialization)
6485 << PrevDecl;
6486 Diag(PrevDecl->getLocation(),
6487 diag::note_previous_template_specialization);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006488 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006489 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006490
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006491 case TSK_ExplicitInstantiationDeclaration:
6492 // We're explicity instantiating a definition for something for which we
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006493 // were previously asked to suppress instantiations. That's fine.
Nico Weberd3bdadf2011-12-23 20:58:04 +00006494
6495 // C++0x [temp.explicit]p4:
6496 // For a given set of template parameters, if an explicit instantiation
6497 // of a template appears after a declaration of an explicit
6498 // specialization for that template, the explicit instantiation has no
6499 // effect.
Douglas Gregor0bc8a212012-01-14 15:55:47 +00006500 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
Nico Weberd3bdadf2011-12-23 20:58:04 +00006501 // Is there any previous explicit specialization declaration?
6502 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6503 HasNoEffect = true;
6504 break;
6505 }
6506 }
6507
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006508 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006509
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006510 case TSK_ExplicitInstantiationDefinition:
6511 // C++0x [temp.spec]p5:
6512 // For a given template and a given set of template-arguments,
6513 // - an explicit instantiation definition shall appear at most once
6514 // in a program,
Will Wilsoneadcdbb2014-05-09 09:52:13 +00006515
6516 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6517 Diag(NewLoc, (getLangOpts().MSVCCompat)
6518 ? diag::warn_explicit_instantiation_duplicate
6519 : diag::err_explicit_instantiation_duplicate)
6520 << PrevDecl;
Nico Webera8f80b32012-01-09 19:52:25 +00006521 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
Douglas Gregor1d957a32009-10-27 18:42:08 +00006522 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00006523 HasNoEffect = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006524 return false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006525 }
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527
David Blaikie83d382b2011-09-23 05:06:16 +00006528 llvm_unreachable("Missing specialization/instantiation case?");
Douglas Gregord6ba93d2009-10-15 15:54:05 +00006529}
6530
John McCallb9c78482010-04-08 09:05:18 +00006531/// \brief Perform semantic analysis for the given dependent function
James Dennettf14a6e52012-06-15 22:23:43 +00006532/// template specialization.
John McCallb9c78482010-04-08 09:05:18 +00006533///
James Dennettf14a6e52012-06-15 22:23:43 +00006534/// The only possible way to get a dependent function template specialization
6535/// is with a friend declaration, like so:
6536///
6537/// \code
6538/// template \<class T> void foo(T);
6539/// template \<class T> class A {
John McCallb9c78482010-04-08 09:05:18 +00006540/// friend void foo<>(T);
6541/// };
James Dennettf14a6e52012-06-15 22:23:43 +00006542/// \endcode
John McCallb9c78482010-04-08 09:05:18 +00006543///
6544/// There really isn't any useful analysis we can do here, so we
6545/// just store the information.
6546bool
6547Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6548 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6549 LookupResult &Previous) {
6550 // Remove anything from Previous that isn't a function template in
6551 // the correct context.
Sebastian Redl50c68252010-08-31 00:36:30 +00006552 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallb9c78482010-04-08 09:05:18 +00006553 LookupResult::Filter F = Previous.makeFilter();
6554 while (F.hasNext()) {
6555 NamedDecl *D = F.next()->getUnderlyingDecl();
6556 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl50c68252010-08-31 00:36:30 +00006557 !FDLookupContext->InEnclosingNamespaceSetOf(
6558 D->getDeclContext()->getRedeclContext()))
John McCallb9c78482010-04-08 09:05:18 +00006559 F.erase();
6560 }
6561 F.done();
6562
6563 // Should this be diagnosed here?
6564 if (Previous.empty()) return true;
6565
6566 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6567 ExplicitTemplateArgs);
6568 return false;
6569}
6570
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006571/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006572/// specialization.
6573///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006574/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006575/// explicit function template specialization. On successful completion,
6576/// the function declaration \p FD will become a function template
6577/// specialization.
6578///
6579/// \param FD the function declaration, which will be updated to become a
6580/// function template specialization.
6581///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006582/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6583/// if any. Note that this may be valid info even when 0 arguments are
6584/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6585/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006586///
Francois Pichet3a44e432011-07-08 06:21:47 +00006587/// \param Previous the set of declarations that may be specialized by
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006588/// this function specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006589bool Sema::CheckFunctionTemplateSpecialization(
6590 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6591 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006592 // The set of function template specializations that could match this
6593 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00006594 UnresolvedSet<8> Candidates;
Larisse Voufo98b20f12013-07-19 23:00:19 +00006595 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006596
Sebastian Redl50c68252010-08-31 00:36:30 +00006597 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall1f82f242009-11-18 22:49:29 +00006598 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6599 I != E; ++I) {
6600 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6601 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602 // Only consider templates found within the same semantic lookup scope as
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006603 // FD.
Sebastian Redl50c68252010-08-31 00:36:30 +00006604 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6605 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006606 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006607
Richard Smith574f4f62013-01-14 05:37:29 +00006608 // When matching a constexpr member function template specialization
6609 // against the primary template, we don't yet know whether the
6610 // specialization has an implicit 'const' (because we don't know whether
6611 // it will be a static member function until we know which template it
6612 // specializes), so adjust it now assuming it specializes this template.
6613 QualType FT = FD->getType();
6614 if (FD->isConstexpr()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006615 CXXMethodDecl *OldMD =
6616 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
Richard Smith574f4f62013-01-14 05:37:29 +00006617 if (OldMD && OldMD->isConst()) {
Rafael Espindola92045bc2013-11-19 21:07:04 +00006618 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
Richard Smith574f4f62013-01-14 05:37:29 +00006619 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6620 EPI.TypeQuals |= Qualifiers::Const;
Alp Toker314cc812014-01-25 16:55:45 +00006621 FT = Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00006622 FPT->getParamTypes(), EPI);
Richard Smith574f4f62013-01-14 05:37:29 +00006623 }
6624 }
6625
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006626 // C++ [temp.expl.spec]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006627 // A trailing template-argument can be left unspecified in the
6628 // template-id naming an explicit function template specialization
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006629 // provided it can be deduced from the function argument type.
6630 // Perform template argument deduction to determine whether we may be
6631 // specializing this template.
6632 // FIXME: It is somewhat wasteful to build
Larisse Voufo98b20f12013-07-19 23:00:19 +00006633 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006634 FunctionDecl *Specialization = nullptr;
Richard Smith32983682013-12-14 03:18:05 +00006635 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6636 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6637 ExplicitTemplateArgs, FT, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00006638 // Template argument deduction failed; record why it failed, so
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006639 // that we can provide nifty diagnostics.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006640 FailedCandidates.addCandidate()
6641 .set(FunTmpl->getTemplatedDecl(),
6642 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006643 (void)TDK;
6644 continue;
6645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006647 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00006648 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006649 }
6650 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006651
Douglas Gregor5de279c2009-09-26 03:41:46 +00006652 // Find the most specialized function template.
Larisse Voufo98b20f12013-07-19 23:00:19 +00006653 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00006654 Candidates.begin(), Candidates.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00006655 FD->getLocation(),
6656 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6657 PDiag(diag::err_function_template_spec_ambiguous)
Craig Topperc3ec1492014-05-26 06:22:03 +00006658 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
Larisse Voufo98b20f12013-07-19 23:00:19 +00006659 PDiag(diag::note_function_template_spec_matched));
6660
John McCall58cc69d2010-01-27 01:50:18 +00006661 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006662 return true;
John McCall58cc69d2010-01-27 01:50:18 +00006663
6664 // Ignore access information; it doesn't figure into redeclaration checking.
6665 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Abramo Bagnarab9893d62011-03-04 17:20:30 +00006666
6667 FunctionTemplateSpecializationInfo *SpecInfo
6668 = Specialization->getTemplateSpecializationInfo();
6669 assert(SpecInfo && "Function template specialization info missing?");
Francois Pichet3a44e432011-07-08 06:21:47 +00006670
6671 // Note: do not overwrite location info if previous template
6672 // specialization kind was explicit.
6673 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
Richard Smith5b8b3db2012-02-20 23:28:05 +00006674 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
Francois Pichet3a44e432011-07-08 06:21:47 +00006675 Specialization->setLocation(FD->getLocation());
Richard Smith5b8b3db2012-02-20 23:28:05 +00006676 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6677 // function can differ from the template declaration with respect to
6678 // the constexpr specifier.
6679 Specialization->setConstexpr(FD->isConstexpr());
6680 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006682 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006683 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00006684
6685 // If this is a friend declaration, then we're not really declaring
6686 // an explicit specialization.
6687 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006688
Douglas Gregor54888652009-10-07 00:13:32 +00006689 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00006690 if (!isFriend &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006691 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00006692 Specialization->getPrimaryTemplate(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006693 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006694 false))
Douglas Gregor54888652009-10-07 00:13:32 +00006695 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006696
6697 // C++ [temp.expl.spec]p6:
6698 // If a template, a member template or the member of a class template is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006699 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006700 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006701 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006702 // use occurs; no diagnostic is required.
Abramo Bagnara8075c852010-06-12 07:44:57 +00006703 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00006704 if (!isFriend &&
6705 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00006706 TSK_ExplicitSpecialization,
6707 Specialization,
6708 SpecInfo->getTemplateSpecializationKind(),
6709 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006710 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006711 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00006712
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006713 // Mark the prior declaration as an explicit specialization, so that later
6714 // clients know that this is an explicit specialization.
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006715 if (!isFriend) {
John McCall816d75b2010-03-24 07:46:06 +00006716 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006717 MarkUnusedFileScopedDecl(Specialization);
6718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006719
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006720 // Turn the given function declaration into a function template
6721 // specialization, with the template arguments from the previous
6722 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006723 // Take copies of (semantic and syntactic) template argument lists.
6724 const TemplateArgumentList* TemplArgs = new (Context)
6725 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
Douglas Gregord5058122010-02-11 01:19:42 +00006726 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006727 TemplArgs, /*InsertPos=*/nullptr,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00006728 SpecInfo->getTemplateSpecializationKind(),
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00006729 ExplicitTemplateArgs);
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006730
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006731 // The "previous declaration" for this function template specialization is
6732 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00006733 Previous.clear();
6734 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006735 return false;
6736}
6737
Douglas Gregor86d142a2009-10-08 07:24:58 +00006738/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006739/// specialization.
6740///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006741/// This routine performs all of the semantic analysis required for an
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006742/// explicit member function specialization. On successful completion,
6743/// the function declaration \p FD will become a member function
6744/// specialization.
6745///
Douglas Gregor86d142a2009-10-08 07:24:58 +00006746/// \param Member the member declaration, which will be updated to become a
6747/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006748///
John McCall1f82f242009-11-18 22:49:29 +00006749/// \param Previous the set of declarations, one of which may be specialized
6750/// by this function specialization; the set will be modified to contain the
6751/// redeclared member.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006752bool
John McCall1f82f242009-11-18 22:49:29 +00006753Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006754 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00006755
Douglas Gregor86d142a2009-10-08 07:24:58 +00006756 // Try to find the member we are instantiating.
Craig Topperc3ec1492014-05-26 06:22:03 +00006757 NamedDecl *Instantiation = nullptr;
6758 NamedDecl *InstantiatedFrom = nullptr;
6759 MemberSpecializationInfo *MSInfo = nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00006760
John McCall1f82f242009-11-18 22:49:29 +00006761 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006762 // Nowhere to look anyway.
6763 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006764 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6765 I != E; ++I) {
6766 NamedDecl *D = (*I)->getUnderlyingDecl();
6767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Rafael Espindola66747222013-12-10 00:59:31 +00006768 QualType Adjusted = Function->getType();
6769 if (!hasExplicitCallingConv(Adjusted))
6770 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6771 if (Context.hasSameType(Adjusted, Method->getType())) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006772 Instantiation = Method;
6773 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006774 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006775 break;
6776 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006777 }
6778 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00006779 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006780 VarDecl *PrevVar;
6781 if (Previous.isSingleResult() &&
6782 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00006783 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00006784 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006785 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006786 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006787 }
6788 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00006789 CXXRecordDecl *PrevRecord;
6790 if (Previous.isSingleResult() &&
6791 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6792 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00006793 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006794 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00006795 }
Richard Smith7d137e32012-03-23 03:33:32 +00006796 } else if (isa<EnumDecl>(Member)) {
6797 EnumDecl *PrevEnum;
6798 if (Previous.isSingleResult() &&
6799 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6800 Instantiation = PrevEnum;
6801 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6802 MSInfo = PrevEnum->getMemberSpecializationInfo();
6803 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006805
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006806 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00006807 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006808 // specializations are always out-of-line, the caller will complain about
6809 // this mismatch later.
6810 return false;
6811 }
John McCalle820e5e2010-04-13 20:37:33 +00006812
6813 // If this is a friend, just bail out here before we start turning
6814 // things into explicit specializations.
6815 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6816 // Preserve instantiation information.
6817 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6818 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6819 cast<CXXMethodDecl>(InstantiatedFrom),
6820 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6821 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6822 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6823 cast<CXXRecordDecl>(InstantiatedFrom),
6824 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6825 }
6826
6827 Previous.clear();
6828 Previous.addDecl(Instantiation);
6829 return false;
6830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006831
Douglas Gregor86d142a2009-10-08 07:24:58 +00006832 // Make sure that this is a specialization of a member.
6833 if (!InstantiatedFrom) {
6834 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6835 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006836 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6837 return true;
6838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006839
Douglas Gregor06db9f52009-10-12 20:18:28 +00006840 // C++ [temp.expl.spec]p6:
6841 // If a template, a member template or the member of a class template is
Nico Weberd3bdadf2011-12-23 20:58:04 +00006842 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00006843 // before the first use of that specialization that would cause an implicit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844 // instantiation to take place, in every translation unit in which such a
Douglas Gregor06db9f52009-10-12 20:18:28 +00006845 // use occurs; no diagnostic is required.
6846 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00006847
Abramo Bagnara8075c852010-06-12 07:44:57 +00006848 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00006849 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6850 TSK_ExplicitSpecialization,
6851 Instantiation,
6852 MSInfo->getTemplateSpecializationKind(),
6853 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00006854 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00006855 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006856
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006857 // Check the scope of this explicit specialization.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006858 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00006859 InstantiatedFrom,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006860 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00006861 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006862 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00006863
Douglas Gregor86d142a2009-10-08 07:24:58 +00006864 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006865 // the original declaration to note that it is an explicit specialization
6866 // (if it was previously an implicit instantiation). This latter step
6867 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00006868 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006869 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6870 if (InstantiationFunction->getTemplateSpecializationKind() ==
6871 TSK_ImplicitInstantiation) {
6872 InstantiationFunction->setTemplateSpecializationKind(
6873 TSK_ExplicitSpecialization);
6874 InstantiationFunction->setLocation(Member->getLocation());
6875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006876
Douglas Gregor86d142a2009-10-08 07:24:58 +00006877 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6878 cast<CXXMethodDecl>(InstantiatedFrom),
6879 TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006880 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor86d142a2009-10-08 07:24:58 +00006881 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006882 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6883 if (InstantiationVar->getTemplateSpecializationKind() ==
6884 TSK_ImplicitInstantiation) {
6885 InstantiationVar->setTemplateSpecializationKind(
6886 TSK_ExplicitSpecialization);
6887 InstantiationVar->setLocation(Member->getLocation());
6888 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889
Larisse Voufo39a1e502013-08-06 01:03:05 +00006890 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
6891 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006892 MarkUnusedFileScopedDecl(InstantiationVar);
Richard Smith7d137e32012-03-23 03:33:32 +00006893 } else if (isa<CXXRecordDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006894 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6895 if (InstantiationClass->getTemplateSpecializationKind() ==
6896 TSK_ImplicitInstantiation) {
6897 InstantiationClass->setTemplateSpecializationKind(
6898 TSK_ExplicitSpecialization);
6899 InstantiationClass->setLocation(Member->getLocation());
6900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006901
Douglas Gregor86d142a2009-10-08 07:24:58 +00006902 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006903 cast<CXXRecordDecl>(InstantiatedFrom),
6904 TSK_ExplicitSpecialization);
Richard Smith7d137e32012-03-23 03:33:32 +00006905 } else {
6906 assert(isa<EnumDecl>(Member) && "Only member enums remain");
6907 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6908 if (InstantiationEnum->getTemplateSpecializationKind() ==
6909 TSK_ImplicitInstantiation) {
6910 InstantiationEnum->setTemplateSpecializationKind(
6911 TSK_ExplicitSpecialization);
6912 InstantiationEnum->setLocation(Member->getLocation());
6913 }
6914
6915 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6916 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00006917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006918
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006919 // Save the caller the trouble of having to figure out which declaration
6920 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00006921 Previous.clear();
6922 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006923 return false;
6924}
6925
Douglas Gregore47f5a72009-10-14 23:41:34 +00006926/// \brief Check the scope of an explicit instantiation.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006927///
6928/// \returns true if a serious error occurs, false otherwise.
6929static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregore47f5a72009-10-14 23:41:34 +00006930 SourceLocation InstLoc,
6931 bool WasQualifiedName) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006932 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6933 DeclContext *CurContext = S.CurContext->getRedeclContext();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006934
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006935 if (CurContext->isRecord()) {
6936 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6937 << D;
6938 return true;
6939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006940
Richard Smith050d2612011-10-18 02:28:33 +00006941 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006942 // An explicit instantiation shall appear in an enclosing namespace of its
Richard Smith050d2612011-10-18 02:28:33 +00006943 // template. If the name declared in the explicit instantiation is an
6944 // unqualified name, the explicit instantiation shall appear in the
6945 // namespace where its template is declared or, if that namespace is inline
6946 // (7.3.1), any namespace from its enclosing namespace set.
Douglas Gregore47f5a72009-10-14 23:41:34 +00006947 //
6948 // This is DR275, which we do not retroactively apply to C++98/03.
Richard Smith050d2612011-10-18 02:28:33 +00006949 if (WasQualifiedName) {
6950 if (CurContext->Encloses(OrigContext))
6951 return false;
6952 } else {
6953 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6954 return false;
6955 }
6956
6957 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6958 if (WasQualifiedName)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006959 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006960 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006961 diag::err_explicit_instantiation_out_of_scope :
6962 diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00006963 << D << NS;
6964 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006966 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006967 diag::err_explicit_instantiation_unqualified_wrong_namespace :
6968 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6969 << D << NS;
6970 } else
6971 S.Diag(InstLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006972 S.getLangOpts().CPlusPlus11?
Richard Smith050d2612011-10-18 02:28:33 +00006973 diag::err_explicit_instantiation_must_be_global :
6974 diag::warn_explicit_instantiation_must_be_global_0x)
6975 << D;
Douglas Gregore47f5a72009-10-14 23:41:34 +00006976 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor6cc1df52010-07-13 00:10:04 +00006977 return false;
Douglas Gregore47f5a72009-10-14 23:41:34 +00006978}
6979
6980/// \brief Determine whether the given scope specifier has a template-id in it.
6981static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
6982 if (!SS.isSet())
6983 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984
Richard Smith050d2612011-10-18 02:28:33 +00006985 // C++11 [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006986 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00006987 // or a static data member of a class template specialization, the name of
6988 // the class template specialization in the qualified-id for the member
6989 // name shall be a simple-template-id.
6990 //
6991 // C++98 has the same restriction, just worded differently.
Aaron Ballman4a979672014-01-03 13:56:08 +00006992 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
6993 NNS = NNS->getPrefix())
John McCall424cec92011-01-19 06:33:43 +00006994 if (const Type *T = NNS->getAsType())
Douglas Gregore47f5a72009-10-14 23:41:34 +00006995 if (isa<TemplateSpecializationType>(T))
6996 return true;
6997
6998 return false;
6999}
7000
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007001// Explicit instantiation of a class template specialization
John McCallfaf5fb42010-08-26 23:41:50 +00007002DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007003Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007004 SourceLocation ExternLoc,
7005 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007006 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00007007 SourceLocation KWLoc,
7008 const CXXScopeSpec &SS,
7009 TemplateTy TemplateD,
7010 SourceLocation TemplateNameLoc,
7011 SourceLocation LAngleLoc,
7012 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00007013 SourceLocation RAngleLoc,
7014 AttributeList *Attr) {
7015 // Find the class template we're specializing
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00007016 TemplateName Name = TemplateD.get();
Richard Smith392497b2013-06-22 22:03:31 +00007017 TemplateDecl *TD = Name.getAsTemplateDecl();
Douglas Gregora1f49972009-05-13 00:25:59 +00007018 // Check that the specialization uses the same tag kind as the
7019 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007020 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7021 assert(Kind != TTK_Enum &&
7022 "Invalid enum tag in class template explicit instantiation!");
Richard Smith392497b2013-06-22 22:03:31 +00007023
7024 if (isa<TypeAliasTemplateDecl>(TD)) {
7025 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7026 Diag(TD->getTemplatedDecl()->getLocation(),
7027 diag::note_previous_use);
7028 return true;
7029 }
7030
7031 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7032
Douglas Gregord9034f02009-05-14 16:41:31 +00007033 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Richard Trieucaa33d32011-06-10 03:11:26 +00007034 Kind, /*isDefinition*/false, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00007035 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00007036 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00007037 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00007038 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007039 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00007040 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00007041 diag::note_previous_use);
7042 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7043 }
7044
Douglas Gregore47f5a72009-10-14 23:41:34 +00007045 // C++0x [temp.explicit]p2:
7046 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007047 // definition and an explicit instantiation declaration. An explicit
7048 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00007049 TemplateSpecializationKind TSK
7050 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7051 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007052
Douglas Gregora1f49972009-05-13 00:25:59 +00007053 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00007054 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00007055 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00007056
7057 // Check that the template argument list is well-formed for this
7058 // template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007059 SmallVector<TemplateArgument, 4> Converted;
John McCall6b51f282009-11-23 01:53:49 +00007060 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7061 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00007062 return true;
7063
Douglas Gregora1f49972009-05-13 00:25:59 +00007064 // Find the class template specialization declaration that
7065 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00007066 void *InsertPos = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007067 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007068 = ClassTemplate->findSpecialization(Converted.data(),
7069 Converted.size(), InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00007070
Abramo Bagnara8075c852010-06-12 07:44:57 +00007071 TemplateSpecializationKind PrevDecl_TSK
7072 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7073
Douglas Gregor54888652009-10-07 00:13:32 +00007074 // C++0x [temp.explicit]p2:
7075 // [...] An explicit instantiation shall appear in an enclosing
7076 // namespace of its template. [...]
7077 //
7078 // This is C++ DR 275.
Douglas Gregor6cc1df52010-07-13 00:10:04 +00007079 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7080 SS.isSet()))
7081 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007082
Craig Topperc3ec1492014-05-26 06:22:03 +00007083 ClassTemplateSpecializationDecl *Specialization = nullptr;
Douglas Gregora1f49972009-05-13 00:25:59 +00007084
Abramo Bagnara8075c852010-06-12 07:44:57 +00007085 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00007086 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00007087 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00007088 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00007089 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007090 HasNoEffect))
John McCall48871652010-08-21 09:40:31 +00007091 return PrevDecl;
Douglas Gregora1f49972009-05-13 00:25:59 +00007092
Abramo Bagnara8075c852010-06-12 07:44:57 +00007093 // Even though HasNoEffect == true means that this explicit instantiation
7094 // has no effect on semantics, we go on to put its syntax in the AST.
7095
7096 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7097 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007098 // Since the only prior class template specialization with these
7099 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00007100 // declaration node as our own, updating the source location
7101 // for the template name to reflect our new declaration.
7102 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007103 Specialization = PrevDecl;
7104 Specialization->setLocation(TemplateNameLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007105 PrevDecl = nullptr;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007106 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00007107 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00007108
Douglas Gregor4aa04b12009-09-11 21:19:12 +00007109 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00007110 // Create a new class template specialization declaration node for
7111 // this explicit specialization.
7112 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00007113 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00007114 ClassTemplate->getDeclContext(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007115 KWLoc, TemplateNameLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00007116 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00007117 Converted.data(),
7118 Converted.size(),
7119 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00007120 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00007121
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007122 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007123 // Insert the new specialization.
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00007124 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007125 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007126 }
7127
7128 // Build the fully-sugared type for this explicit instantiation as
7129 // the user wrote in the explicit instantiation itself. This means
7130 // that we'll pretty-print the type retrieved from the
7131 // specialization's declaration the way that the user actually wrote
7132 // the explicit instantiation, rather than formatting the name based
7133 // on the "canonical" representation used to store the template
7134 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00007135 TypeSourceInfo *WrittenTy
7136 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7137 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00007138 Context.getTypeDeclType(Specialization));
7139 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregora1f49972009-05-13 00:25:59 +00007140
Abramo Bagnara8075c852010-06-12 07:44:57 +00007141 // Set source locations for keywords.
7142 Specialization->setExternLoc(ExternLoc);
7143 Specialization->setTemplateKeywordLoc(TemplateLoc);
Argyrios Kyrtzidis40bcfd72013-04-22 23:23:42 +00007144 Specialization->setRBraceLoc(SourceLocation());
Abramo Bagnara8075c852010-06-12 07:44:57 +00007145
Rafael Espindola0b062072012-01-03 06:04:21 +00007146 if (Attr)
7147 ProcessDeclAttributeList(S, Specialization, Attr);
7148
Abramo Bagnara8075c852010-06-12 07:44:57 +00007149 // Add the explicit instantiation into its lexical context. However,
7150 // since explicit instantiations are never found by name lookup, we
7151 // just put it into the declaration context directly.
7152 Specialization->setLexicalDeclContext(CurContext);
7153 CurContext->addDecl(Specialization);
7154
7155 // Syntax is now OK, so return if it has no other effect on semantics.
7156 if (HasNoEffect) {
7157 // Set the template specialization kind.
7158 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007159 return Specialization;
Douglas Gregor0681a352009-11-25 06:01:46 +00007160 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007161
7162 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00007163 // A definition of a class template or class member template
7164 // shall be in scope at the point of the explicit instantiation of
7165 // the class template or class member template.
7166 //
7167 // This check comes when we actually try to perform the
7168 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00007169 ClassTemplateSpecializationDecl *Def
7170 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007171 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007172 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00007173 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007174 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007175 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00007176 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7177 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007178
Douglas Gregor1d957a32009-10-27 18:42:08 +00007179 // Instantiate the members of this class template specialization.
7180 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007181 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00007182 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007183 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7184
7185 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7186 // TSK_ExplicitInstantiationDefinition
7187 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7188 TSK == TSK_ExplicitInstantiationDefinition)
Richard Smitheb36ddf2014-04-24 22:45:46 +00007189 // FIXME: Need to notify the ASTMutationListener that we did this.
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00007190 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007191
Douglas Gregor12e49d32009-10-15 22:53:21 +00007192 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00007193 }
Douglas Gregora1f49972009-05-13 00:25:59 +00007194
Abramo Bagnara8075c852010-06-12 07:44:57 +00007195 // Set the template specialization kind.
7196 Specialization->setTemplateSpecializationKind(TSK);
John McCall48871652010-08-21 09:40:31 +00007197 return Specialization;
Douglas Gregora1f49972009-05-13 00:25:59 +00007198}
7199
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007200// Explicit instantiation of a member class of a class template.
John McCall48871652010-08-21 09:40:31 +00007201DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00007202Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00007203 SourceLocation ExternLoc,
7204 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007205 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007206 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007207 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007208 IdentifierInfo *Name,
7209 SourceLocation NameLoc,
7210 AttributeList *Attr) {
7211
Douglas Gregord6ab8742009-05-28 23:31:59 +00007212 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00007213 bool IsDependent = false;
John McCallfaf5fb42010-08-26 23:41:50 +00007214 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCall48871652010-08-21 09:40:31 +00007215 KWLoc, SS, Name, NameLoc, Attr, AS_none,
Douglas Gregor2820e692011-09-09 19:05:14 +00007216 /*ModulePrivateLoc=*/SourceLocation(),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007217 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith649c7b062014-01-08 00:56:48 +00007218 SourceLocation(), false, TypeResult(),
7219 /*IsTypeSpecifier*/false);
John McCall7f41d982009-09-11 04:59:25 +00007220 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7221
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007222 if (!TagD)
7223 return true;
7224
John McCall48871652010-08-21 09:40:31 +00007225 TagDecl *Tag = cast<TagDecl>(TagD);
Richard Smith7d137e32012-03-23 03:33:32 +00007226 assert(!Tag->isEnum() && "shouldn't see enumerations here");
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007227
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007228 if (Tag->isInvalidDecl())
7229 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007230
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007231 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7232 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7233 if (!Pattern) {
7234 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7235 << Context.getTypeDeclType(Record);
7236 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7237 return true;
7238 }
7239
Douglas Gregore47f5a72009-10-14 23:41:34 +00007240 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007241 // If the explicit instantiation is for a class or member class, the
7242 // elaborated-type-specifier in the declaration shall include a
Douglas Gregore47f5a72009-10-14 23:41:34 +00007243 // simple-template-id.
7244 //
7245 // C++98 has the same restriction, just worded differently.
7246 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00007247 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007248 << Record << SS.getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007249
Douglas Gregore47f5a72009-10-14 23:41:34 +00007250 // C++0x [temp.explicit]p2:
7251 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007252 // definition and an explicit instantiation declaration. An explicit
Douglas Gregore47f5a72009-10-14 23:41:34 +00007253 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00007254 TemplateSpecializationKind TSK
7255 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7256 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007257
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007258 // C++0x [temp.explicit]p2:
7259 // [...] An explicit instantiation shall appear in an enclosing
7260 // namespace of its template. [...]
7261 //
7262 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00007263 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007264
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007265 // Verify that it is okay to explicitly instantiate here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007266 CXXRecordDecl *PrevDecl
Douglas Gregorec9fd132012-01-14 16:38:05 +00007267 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007268 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00007269 PrevDecl = Record;
7270 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007271 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007272 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007273 assert(MSInfo && "No member specialization information?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007274 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007275 PrevDecl,
7276 MSInfo->getTemplateSpecializationKind(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007277 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007278 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007279 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00007280 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007281 return TagD;
7282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007283
Douglas Gregor12e49d32009-10-15 22:53:21 +00007284 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007285 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00007286 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00007287 // C++ [temp.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007288 // A definition of a member class of a class template shall be in scope
Douglas Gregor68edf132009-10-15 12:53:22 +00007289 // at the point of an explicit instantiation of the member class.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007290 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007291 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00007292 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00007293 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7294 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00007295 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7296 << Pattern;
7297 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007298 } else {
7299 if (InstantiateClass(NameLoc, Record, Def,
7300 getTemplateInstantiationArgs(Record),
7301 TSK))
7302 return true;
7303
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007304 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00007305 if (!RecordDef)
7306 return true;
7307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007308 }
7309
Douglas Gregor1d957a32009-10-27 18:42:08 +00007310 // Instantiate all of the members of the class.
7311 InstantiateClassMembers(NameLoc, RecordDef,
7312 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007313
Douglas Gregor88d292c2010-05-13 16:44:06 +00007314 if (TSK == TSK_ExplicitInstantiationDefinition)
7315 MarkVTableUsed(NameLoc, RecordDef, true);
7316
Mike Stump87c57ac2009-05-16 07:39:55 +00007317 // FIXME: We don't have any representation for explicit instantiations of
7318 // member classes. Such a representation is not needed for compilation, but it
7319 // should be available for clients that want to see all of the declarations in
7320 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00007321 return TagD;
7322}
7323
John McCallfaf5fb42010-08-26 23:41:50 +00007324DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7325 SourceLocation ExternLoc,
7326 SourceLocation TemplateLoc,
7327 Declarator &D) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007328 // Explicit instantiations always require a name.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007329 // TODO: check if/when DNInfo should replace Name.
7330 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7331 DeclarationName Name = NameInfo.getName();
Douglas Gregor450f00842009-09-25 18:43:00 +00007332 if (!Name) {
7333 if (!D.isInvalidType())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007334 Diag(D.getDeclSpec().getLocStart(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007335 diag::err_explicit_instantiation_requires_name)
7336 << D.getDeclSpec().getSourceRange()
7337 << D.getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007338
Douglas Gregor450f00842009-09-25 18:43:00 +00007339 return true;
7340 }
7341
7342 // The scope passed in may not be a decl scope. Zip up the scope tree until
7343 // we find one that is.
7344 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7345 (S->getFlags() & Scope::TemplateParamScope) != 0)
7346 S = S->getParent();
7347
7348 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00007349 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7350 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00007351 if (R.isNull())
7352 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007353
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007354 // C++ [dcl.stc]p1:
7355 // A storage-class-specifier shall not be specified in [...] an explicit
7356 // instantiation (14.7.2) directive.
Douglas Gregor450f00842009-09-25 18:43:00 +00007357 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor450f00842009-09-25 18:43:00 +00007358 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7359 << Name;
7360 return true;
Douglas Gregor781ba6e2011-05-21 18:53:30 +00007361 } else if (D.getDeclSpec().getStorageClassSpec()
7362 != DeclSpec::SCS_unspecified) {
7363 // Complain about then remove the storage class specifier.
7364 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7365 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7366
7367 D.getMutableDeclSpec().ClearStorageClassSpecs();
Douglas Gregor450f00842009-09-25 18:43:00 +00007368 }
7369
Douglas Gregor3c74d412009-10-14 20:14:33 +00007370 // C++0x [temp.explicit]p1:
7371 // [...] An explicit instantiation of a function template shall not use the
7372 // inline or constexpr specifiers.
7373 // Presumably, this also applies to member functions of class templates as
7374 // well.
Richard Smith83c19292011-10-18 03:44:03 +00007375 if (D.getDeclSpec().isInlineSpecified())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007376 Diag(D.getDeclSpec().getInlineSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007377 getLangOpts().CPlusPlus11 ?
Richard Smith83c19292011-10-18 03:44:03 +00007378 diag::err_explicit_instantiation_inline :
7379 diag::warn_explicit_instantiation_inline_0x)
Richard Smith465841e2011-10-14 19:58:02 +00007380 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Larisse Voufo39a1e502013-08-06 01:03:05 +00007381 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
Richard Smith465841e2011-10-14 19:58:02 +00007382 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7383 // not already specified.
7384 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7385 diag::err_explicit_instantiation_constexpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007386
Douglas Gregore47f5a72009-10-14 23:41:34 +00007387 // C++0x [temp.explicit]p2:
7388 // There are two forms of explicit instantiation: an explicit instantiation
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007389 // definition and an explicit instantiation declaration. An explicit
7390 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00007391 TemplateSpecializationKind TSK
7392 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7393 : TSK_ExplicitInstantiationDeclaration;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007394
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007395 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007396 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00007397
7398 if (!R->isFunctionType()) {
7399 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007400 // A [...] static data member of a class template can be explicitly
7401 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007402 // template.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007403 // C++1y [temp.explicit]p1:
7404 // A [...] variable [...] template specialization can be explicitly
7405 // instantiated from its template.
John McCall27b18f82009-11-17 02:14:36 +00007406 if (Previous.isAmbiguous())
7407 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007408
John McCall67c00872009-12-02 08:25:40 +00007409 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Larisse Voufo39a1e502013-08-06 01:03:05 +00007410 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007411
Larisse Voufo39a1e502013-08-06 01:03:05 +00007412 if (!PrevTemplate) {
7413 if (!Prev || !Prev->isStaticDataMember()) {
7414 // We expect to see a data data member here.
7415 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7416 << Name;
7417 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7418 P != PEnd; ++P)
7419 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7420 return true;
7421 }
7422
7423 if (!Prev->getInstantiatedFromStaticDataMember()) {
7424 // FIXME: Check for explicit specialization?
7425 Diag(D.getIdentifierLoc(),
7426 diag::err_explicit_instantiation_data_member_not_instantiated)
7427 << Prev;
7428 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7429 // FIXME: Can we provide a note showing where this was declared?
7430 return true;
7431 }
7432 } else {
7433 // Explicitly instantiate a variable template.
7434
7435 // C++1y [dcl.spec.auto]p6:
7436 // ... A program that uses auto or decltype(auto) in a context not
7437 // explicitly allowed in this section is ill-formed.
7438 //
7439 // This includes auto-typed variable template instantiations.
7440 if (R->isUndeducedType()) {
7441 Diag(T->getTypeLoc().getLocStart(),
7442 diag::err_auto_not_allowed_var_inst);
7443 return true;
7444 }
7445
Richard Smithef985ac2013-09-18 02:10:12 +00007446 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7447 // C++1y [temp.explicit]p3:
7448 // If the explicit instantiation is for a variable, the unqualified-id
7449 // in the declaration shall be a template-id.
7450 Diag(D.getIdentifierLoc(),
7451 diag::err_explicit_instantiation_without_template_id)
7452 << PrevTemplate;
7453 Diag(PrevTemplate->getLocation(),
7454 diag::note_explicit_instantiation_here);
7455 return true;
Larisse Voufo39a1e502013-08-06 01:03:05 +00007456 }
7457
Richard Smithef985ac2013-09-18 02:10:12 +00007458 // Translate the parser's template argument list into our AST format.
Richard Smith4b55a9c2014-04-17 03:29:33 +00007459 TemplateArgumentListInfo TemplateArgs =
7460 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Richard Smithef985ac2013-09-18 02:10:12 +00007461
Larisse Voufo39a1e502013-08-06 01:03:05 +00007462 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7463 D.getIdentifierLoc(), TemplateArgs);
7464 if (Res.isInvalid())
7465 return true;
7466
7467 // Ignore access control bits, we don't need them for redeclaration
7468 // checking.
7469 Prev = cast<VarDecl>(Res.get());
Douglas Gregor450f00842009-09-25 18:43:00 +00007470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007471
Douglas Gregore47f5a72009-10-14 23:41:34 +00007472 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007473 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007474 // or a static data member of a class template specialization, the name of
7475 // the class template specialization in the qualified-id for the member
7476 // name shall be a simple-template-id.
7477 //
7478 // C++98 has the same restriction, just worded differently.
Larisse Voufo39a1e502013-08-06 01:03:05 +00007479 //
Richard Smith5977d872013-09-18 21:55:14 +00007480 // This does not apply to variable template specializations, where the
7481 // template-id is in the unqualified-id instead.
7482 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007483 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007484 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007485 << Prev << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007486
Douglas Gregore47f5a72009-10-14 23:41:34 +00007487 // Check the scope of this explicit instantiation.
7488 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), 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.
Richard Smith8809a0c2013-09-27 20:14:12 +00007491 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7492 SourceLocation POI = Prev->getPointOfInstantiation();
Abramo Bagnara8075c852010-06-12 07:44:57 +00007493 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007494 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Larisse Voufo39a1e502013-08-06 01:03:05 +00007495 PrevTSK, POI, HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00007496 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007497
Larisse Voufo39a1e502013-08-06 01:03:05 +00007498 if (!HasNoEffect) {
7499 // Instantiate static data member or variable template.
7500
7501 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7502 if (PrevTemplate) {
7503 // Merge attributes.
7504 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7505 ProcessDeclAttributeList(S, Prev, Attr);
7506 }
7507 if (TSK == TSK_ExplicitInstantiationDefinition)
7508 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7509 }
7510
7511 // Check the new variable specialization against the parsed input.
7512 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7513 Diag(T->getTypeLoc().getLocStart(),
7514 diag::err_invalid_var_template_spec_type)
7515 << 0 << PrevTemplate << R << Prev->getType();
7516 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7517 << 2 << PrevTemplate->getDeclName();
7518 return true;
7519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007520
Douglas Gregor450f00842009-09-25 18:43:00 +00007521 // FIXME: Create an ExplicitInstantiation node?
Craig Topperc3ec1492014-05-26 06:22:03 +00007522 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007524
7525 // If the declarator is a template-id, translate the parser's template
Douglas Gregor0e876e02009-09-25 23:53:26 +00007526 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00007527 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00007528 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00007529 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
Richard Smith4b55a9c2014-04-17 03:29:33 +00007530 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
Douglas Gregord90fd522009-09-25 21:45:23 +00007531 HasExplicitTemplateArgs = true;
7532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007533
Douglas Gregor450f00842009-09-25 18:43:00 +00007534 // C++ [temp.explicit]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007535 // A [...] function [...] can be explicitly instantiated from its template.
7536 // A member function [...] of a class template can be explicitly
7537 // instantiated from the member definition associated with its class
Douglas Gregor450f00842009-09-25 18:43:00 +00007538 // template.
John McCall58cc69d2010-01-27 01:50:18 +00007539 UnresolvedSet<8> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00007540 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00007541 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7542 P != PEnd; ++P) {
7543 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00007544 if (!HasExplicitTemplateArgs) {
7545 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00007546 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7547 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
Douglas Gregord90fd522009-09-25 21:45:23 +00007548 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007549
John McCall58cc69d2010-01-27 01:50:18 +00007550 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00007551 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7552 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00007553 }
Douglas Gregor450f00842009-09-25 18:43:00 +00007554 }
7555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007556
Douglas Gregor450f00842009-09-25 18:43:00 +00007557 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7558 if (!FunTmpl)
7559 continue;
7560
Larisse Voufo98b20f12013-07-19 23:00:19 +00007561 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00007562 FunctionDecl *Specialization = nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007563 if (TemplateDeductionResult TDK
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007564 = DeduceTemplateArguments(FunTmpl,
Craig Topperc3ec1492014-05-26 06:22:03 +00007565 (HasExplicitTemplateArgs ? &TemplateArgs
7566 : nullptr),
Douglas Gregor450f00842009-09-25 18:43:00 +00007567 R, Specialization, Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00007568 // Keep track of almost-matches.
7569 FailedCandidates.addCandidate()
7570 .set(FunTmpl->getTemplatedDecl(),
7571 MakeDeductionFailureInfo(Context, TDK, Info));
Douglas Gregor450f00842009-09-25 18:43:00 +00007572 (void)TDK;
7573 continue;
7574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007575
John McCall58cc69d2010-01-27 01:50:18 +00007576 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00007577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007578
Douglas Gregor450f00842009-09-25 18:43:00 +00007579 // Find the most specialized function template specialization.
Larisse Voufo98b20f12013-07-19 23:00:19 +00007580 UnresolvedSetIterator Result = getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00007581 Matches.begin(), Matches.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00007582 D.getIdentifierLoc(),
7583 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7584 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7585 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00007586
John McCall58cc69d2010-01-27 01:50:18 +00007587 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00007588 return true;
John McCall58cc69d2010-01-27 01:50:18 +00007589
7590 // Ignore access control bits, we don't need them for redeclaration checking.
7591 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007592
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007593 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007594 Diag(D.getIdentifierLoc(),
Douglas Gregor450f00842009-09-25 18:43:00 +00007595 diag::err_explicit_instantiation_member_function_not_instantiated)
7596 << Specialization
7597 << (Specialization->getTemplateSpecializationKind() ==
7598 TSK_ExplicitSpecialization);
7599 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7600 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007601 }
7602
Douglas Gregorec9fd132012-01-14 16:38:05 +00007603 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
Douglas Gregor8f003d02009-10-15 18:07:02 +00007604 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7605 PrevDecl = Specialization;
7606
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007607 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00007608 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00007609 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007610 PrevDecl,
7611 PrevDecl->getTemplateSpecializationKind(),
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007612 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00007613 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007614 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007615
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007616 // FIXME: We may still want to build some representation of this
7617 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00007618 if (HasNoEffect)
Craig Topperc3ec1492014-05-26 06:22:03 +00007619 return (Decl*) nullptr;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007620 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00007621
7622 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Rafael Espindola2aa7acf2012-01-04 05:40:59 +00007623 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7624 if (Attr)
7625 ProcessDeclAttributeList(S, Specialization, Attr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007626
Richard Smitheb36ddf2014-04-24 22:45:46 +00007627 if (Specialization->isDefined()) {
7628 // Let the ASTConsumer know that this function has been explicitly
7629 // instantiated now, and its linkage might have changed.
7630 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7631 } else if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruthcfe41db2010-08-25 08:27:02 +00007632 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007633
Douglas Gregore47f5a72009-10-14 23:41:34 +00007634 // C++0x [temp.explicit]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007635 // If the explicit instantiation is for a member function, a member class
Douglas Gregore47f5a72009-10-14 23:41:34 +00007636 // or a static data member of a class template specialization, the name of
7637 // the class template specialization in the qualified-id for the member
7638 // name shall be a simple-template-id.
7639 //
7640 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00007641 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00007642 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007643 D.getCXXScopeSpec().isSet() &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00007644 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007645 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00007646 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00007647 << Specialization << D.getCXXScopeSpec().getRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007648
Douglas Gregore47f5a72009-10-14 23:41:34 +00007649 CheckExplicitInstantiationScope(*this,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007650 FunTmpl? (NamedDecl *)FunTmpl
Douglas Gregore47f5a72009-10-14 23:41:34 +00007651 : Specialization->getInstantiatedFromMemberFunction(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007652 D.getIdentifierLoc(),
Douglas Gregore47f5a72009-10-14 23:41:34 +00007653 D.getCXXScopeSpec().isSet());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007654
Douglas Gregor450f00842009-09-25 18:43:00 +00007655 // FIXME: Create some kind of ExplicitInstantiationDecl here.
Craig Topperc3ec1492014-05-26 06:22:03 +00007656 return (Decl*) nullptr;
Douglas Gregor450f00842009-09-25 18:43:00 +00007657}
7658
John McCallfaf5fb42010-08-26 23:41:50 +00007659TypeResult
John McCall7f41d982009-09-11 04:59:25 +00007660Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7661 const CXXScopeSpec &SS, IdentifierInfo *Name,
7662 SourceLocation TagLoc, SourceLocation NameLoc) {
7663 // This has to hold, because SS is expected to be defined.
7664 assert(Name && "Expected a name in a dependent tag");
7665
Aaron Ballman4a979672014-01-03 13:56:08 +00007666 NestedNameSpecifier *NNS = SS.getScopeRep();
John McCall7f41d982009-09-11 04:59:25 +00007667 if (!NNS)
7668 return true;
7669
Abramo Bagnara6150c882010-05-11 21:36:43 +00007670 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00007671
Douglas Gregorba41d012010-04-24 16:38:41 +00007672 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7673 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00007674 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00007675 return true;
7676 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00007677
Douglas Gregore7c20652011-03-02 00:47:37 +00007678 // Create the resulting type.
Abramo Bagnara6150c882010-05-11 21:36:43 +00007679 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregore7c20652011-03-02 00:47:37 +00007680 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7681
7682 // Create type-source location information for this type.
7683 TypeLocBuilder TLB;
7684 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007685 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregore7c20652011-03-02 00:47:37 +00007686 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7687 TL.setNameLoc(NameLoc);
7688 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
John McCall7f41d982009-09-11 04:59:25 +00007689}
7690
John McCallfaf5fb42010-08-26 23:41:50 +00007691TypeResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007692Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7693 const CXXScopeSpec &SS, const IdentifierInfo &II,
Douglas Gregorf7d77712010-06-16 22:31:08 +00007694 SourceLocation IdLoc) {
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007695 if (SS.isInvalid())
Douglas Gregor333489b2009-03-27 23:10:48 +00007696 return true;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007697
Richard Smith0bf8a4922011-10-18 20:49:44 +00007698 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7699 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007700 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007701 diag::warn_cxx98_compat_typename_outside_of_template :
7702 diag::ext_typename_outside_of_template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007703 << FixItHint::CreateRemoval(TypenameLoc);
7704
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007705 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Douglas Gregor844cb502011-03-01 18:12:44 +00007706 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7707 TypenameLoc, QualifierLoc, II, IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00007708 if (T.isNull())
7709 return true;
John McCall99b2fe52010-04-29 23:50:39 +00007710
7711 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7712 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +00007713 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007714 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007715 TL.setQualifierLoc(QualifierLoc);
John McCallf7bcc812010-05-28 23:32:21 +00007716 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007717 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +00007718 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007719 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007720 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +00007721 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00007722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007723
John McCallba7bf592010-08-24 05:47:05 +00007724 return CreateParsedType(T, TSI);
Douglas Gregor333489b2009-03-27 23:10:48 +00007725}
7726
John McCallfaf5fb42010-08-26 23:41:50 +00007727TypeResult
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007728Sema::ActOnTypenameType(Scope *S,
7729 SourceLocation TypenameLoc,
7730 const CXXScopeSpec &SS,
7731 SourceLocation TemplateKWLoc,
Douglas Gregorb09518c2011-02-27 22:46:49 +00007732 TemplateTy TemplateIn,
7733 SourceLocation TemplateNameLoc,
7734 SourceLocation LAngleLoc,
7735 ASTTemplateArgsPtr TemplateArgsIn,
7736 SourceLocation RAngleLoc) {
Richard Smith0bf8a4922011-10-18 20:49:44 +00007737 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7738 Diag(TypenameLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007739 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007740 diag::warn_cxx98_compat_typename_outside_of_template :
7741 diag::ext_typename_outside_of_template)
7742 << FixItHint::CreateRemoval(TypenameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007743
7744 // Translate the parser's template argument list in our AST format.
7745 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7746 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7747
7748 TemplateName Template = TemplateIn.get();
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007749 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7750 // Construct a dependent template specialization type.
7751 assert(DTN && "dependent template has non-dependent name?");
Aaron Ballman4a979672014-01-03 13:56:08 +00007752 assert(DTN->getQualifier() == SS.getScopeRep());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007753 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7754 DTN->getQualifier(),
7755 DTN->getIdentifier(),
7756 TemplateArgs);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007757
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007758 // Create source-location information for this type.
John McCallf7bcc812010-05-28 23:32:21 +00007759 TypeLocBuilder Builder;
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007760 DependentTemplateSpecializationTypeLoc SpecTL
7761 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007762 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7763 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae0a70b22012-02-06 22:45:07 +00007764 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007765 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007766 SpecTL.setLAngleLoc(LAngleLoc);
7767 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007768 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7769 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007770 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
Douglas Gregor12bbfe12009-09-02 13:05:45 +00007771 }
Douglas Gregorb09518c2011-02-27 22:46:49 +00007772
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007773 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7774 if (T.isNull())
7775 return true;
Douglas Gregorb09518c2011-02-27 22:46:49 +00007776
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007777 // Provide source-location information for the template specialization type.
Douglas Gregorb09518c2011-02-27 22:46:49 +00007778 TypeLocBuilder Builder;
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007779 TemplateSpecializationTypeLoc SpecTL
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007780 = Builder.push<TemplateSpecializationTypeLoc>(T);
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007781 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7782 SpecTL.setTemplateNameLoc(TemplateNameLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007783 SpecTL.setLAngleLoc(LAngleLoc);
7784 SpecTL.setRAngleLoc(RAngleLoc);
Douglas Gregorb09518c2011-02-27 22:46:49 +00007785 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7786 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7787
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007788 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7789 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
Abramo Bagnara9033e2b2012-02-06 19:09:27 +00007790 TL.setElaboratedKeywordLoc(TypenameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007791 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7792
Douglas Gregor84a6a0a2011-03-01 16:44:30 +00007793 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7794 return CreateParsedType(T, TSI);
Douglas Gregordce2b622009-04-01 00:28:59 +00007795}
7796
Douglas Gregorb09518c2011-02-27 22:46:49 +00007797
Richard Smith6f8d2c62012-05-09 05:17:00 +00007798/// Determine whether this failed name lookup should be treated as being
7799/// disabled by a usage of std::enable_if.
7800static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7801 SourceRange &CondRange) {
7802 // We must be looking for a ::type...
7803 if (!II.isStr("type"))
7804 return false;
7805
7806 // ... within an explicitly-written template specialization...
7807 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7808 return false;
7809 TypeLoc EnableIfTy = NNS.getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00007810 TemplateSpecializationTypeLoc EnableIfTSTLoc =
7811 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7812 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
Richard Smith6f8d2c62012-05-09 05:17:00 +00007813 return false;
7814 const TemplateSpecializationType *EnableIfTST =
David Blaikie6adc78e2013-02-18 22:06:02 +00007815 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
Richard Smith6f8d2c62012-05-09 05:17:00 +00007816
7817 // ... which names a complete class template declaration...
7818 const TemplateDecl *EnableIfDecl =
7819 EnableIfTST->getTemplateName().getAsTemplateDecl();
7820 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7821 return false;
7822
7823 // ... called "enable_if".
7824 const IdentifierInfo *EnableIfII =
7825 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7826 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7827 return false;
7828
7829 // Assume the first template argument is the condition.
David Blaikie6adc78e2013-02-18 22:06:02 +00007830 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
Richard Smith6f8d2c62012-05-09 05:17:00 +00007831 return true;
7832}
7833
Douglas Gregor333489b2009-03-27 23:10:48 +00007834/// \brief Build the type that describes a C++ typename specifier,
7835/// e.g., "typename T::type".
7836QualType
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007837Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7838 SourceLocation KeywordLoc,
7839 NestedNameSpecifierLoc QualifierLoc,
7840 const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00007841 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00007842 CXXScopeSpec SS;
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007843 SS.Adopt(QualifierLoc);
Douglas Gregor333489b2009-03-27 23:10:48 +00007844
John McCall0b66eb32010-05-01 00:40:08 +00007845 DeclContext *Ctx = computeDeclContext(SS);
7846 if (!Ctx) {
7847 // If the nested-name-specifier is dependent and couldn't be
7848 // resolved to a type, build a typename type.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007849 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7850 return Context.getDependentNameType(Keyword,
7851 QualifierLoc.getNestedNameSpecifier(),
7852 &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007853 }
Douglas Gregor333489b2009-03-27 23:10:48 +00007854
John McCall0b66eb32010-05-01 00:40:08 +00007855 // If the nested-name-specifier refers to the current instantiation,
7856 // the "typename" keyword itself is superfluous. In C++03, the
7857 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7858 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00007859 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007860
John McCall0b66eb32010-05-01 00:40:08 +00007861 if (RequireCompleteDeclContext(SS, Ctx))
7862 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00007863
7864 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00007865 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00007866 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00007867 unsigned DiagID = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00007868 Decl *Referenced = nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007869 switch (Result.getResultKind()) {
Richard Smith6f8d2c62012-05-09 05:17:00 +00007870 case LookupResult::NotFound: {
7871 // If we're looking up 'type' within a template named 'enable_if', produce
7872 // a more specific diagnostic.
7873 SourceRange CondRange;
7874 if (isEnableIf(QualifierLoc, II, CondRange)) {
7875 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
7876 << Ctx << CondRange;
7877 return QualType();
7878 }
7879
Douglas Gregore40876a2009-10-13 21:16:44 +00007880 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00007881 break;
Richard Smith6f8d2c62012-05-09 05:17:00 +00007882 }
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007883
7884 case LookupResult::FoundUnresolvedValue: {
7885 // We found a using declaration that is a value. Most likely, the using
7886 // declaration itself is meant to have the 'typename' keyword.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007887 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007888 IILoc);
7889 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
7890 << Name << Ctx << FullRange;
7891 if (UnresolvedUsingValueDecl *Using
7892 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007893 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
Douglas Gregoraed2efb2010-12-09 00:06:27 +00007894 Diag(Loc, diag::note_using_value_decl_missing_typename)
7895 << FixItHint::CreateInsertion(Loc, "typename ");
7896 }
7897 }
7898 // Fall through to create a dependent typename type, from which we can recover
7899 // better.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007900
Douglas Gregord0d2ee02010-01-15 01:44:47 +00007901 case LookupResult::NotFoundInCurrentInstantiation:
7902 // Okay, it's a member of an unknown instantiation.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007903 return Context.getDependentNameType(Keyword,
7904 QualifierLoc.getNestedNameSpecifier(),
7905 &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00007906
7907 case LookupResult::Found:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007908 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00007909 // We found a type. Build an ElaboratedType, since the
7910 // typename-specifier was just sugar.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007911 return Context.getElaboratedType(ETK_Typename,
7912 QualifierLoc.getNestedNameSpecifier(),
Abramo Bagnara6150c882010-05-11 21:36:43 +00007913 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00007914 }
7915
7916 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00007917 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00007918 break;
7919
7920 case LookupResult::FoundOverloaded:
7921 DiagID = diag::err_typename_nested_not_type;
7922 Referenced = *Result.begin();
7923 break;
7924
John McCall6538c932009-10-10 05:48:19 +00007925 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00007926 return QualType();
7927 }
7928
7929 // If we get here, it's because name lookup did not find a
7930 // type. Emit an appropriate diagnostic and return an error.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007931 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00007932 IILoc);
7933 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00007934 if (Referenced)
7935 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
7936 << Name;
7937 return QualType();
7938}
Douglas Gregor15acfb92009-08-06 16:20:37 +00007939
7940namespace {
7941 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00007942 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00007943 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00007944 SourceLocation Loc;
7945 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00007946
Douglas Gregor15acfb92009-08-06 16:20:37 +00007947 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00007948 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007949
Mike Stump11289f42009-09-09 15:08:12 +00007950 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00007951 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00007952 DeclarationName Entity)
7953 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00007954 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00007955
7956 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00007957 /// transformed.
7958 ///
7959 /// For the purposes of type reconstruction, a type has already been
7960 /// transformed if it is NULL or if it is not dependent.
7961 bool AlreadyTransformed(QualType T) {
7962 return T.isNull() || !T->isDependentType();
7963 }
Mike Stump11289f42009-09-09 15:08:12 +00007964
7965 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00007966 /// rebuilt.
7967 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00007968
Douglas Gregor15acfb92009-08-06 16:20:37 +00007969 /// \brief Returns the name of the entity whose type is being rebuilt.
7970 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00007971
Douglas Gregoref6ab412009-10-27 06:26:26 +00007972 /// \brief Sets the "base" location and entity when that
7973 /// information is known based on another transformation.
7974 void setBase(SourceLocation Loc, DeclarationName Entity) {
7975 this->Loc = Loc;
7976 this->Entity = Entity;
7977 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00007978
7979 ExprResult TransformLambdaExpr(LambdaExpr *E) {
7980 // Lambdas never need to be transformed.
7981 return E;
7982 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00007983 };
7984}
7985
Douglas Gregor15acfb92009-08-06 16:20:37 +00007986/// \brief Rebuilds a type within the context of the current instantiation.
7987///
Mike Stump11289f42009-09-09 15:08:12 +00007988/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00007989/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00007990/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00007991/// partial specialization thereof). This routine will rebuild that type now
7992/// that we have entered the declarator's scope, which may produce different
7993/// canonical types, e.g.,
7994///
7995/// \code
7996/// template<typename T>
7997/// struct X {
7998/// typedef T* pointer;
7999/// pointer data();
8000/// };
8001///
8002/// template<typename T>
8003/// typename X<T>::pointer X<T>::data() { ... }
8004/// \endcode
8005///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00008006/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00008007/// since we do not know that we can look into X<T> when we parsed the type.
8008/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00008009/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00008010/// as the canonical type of T*, allowing the return types of the out-of-line
8011/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00008012TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8013 SourceLocation Loc,
8014 DeclarationName Name) {
8015 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00008016 return T;
Mike Stump11289f42009-09-09 15:08:12 +00008017
Douglas Gregor15acfb92009-08-06 16:20:37 +00008018 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8019 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00008020}
Douglas Gregorbe999392009-09-15 16:23:51 +00008021
John McCalldadc5752010-08-24 06:29:42 +00008022ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallba7bf592010-08-24 05:47:05 +00008023 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8024 DeclarationName());
8025 return Rebuilder.TransformExpr(E);
8026}
8027
John McCall99b2fe52010-04-29 23:50:39 +00008028bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
Douglas Gregor10176412011-02-25 16:07:42 +00008029 if (SS.isInvalid())
8030 return true;
John McCall2408e322010-04-27 00:57:59 +00008031
Douglas Gregor10176412011-02-25 16:07:42 +00008032 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall2408e322010-04-27 00:57:59 +00008033 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8034 DeclarationName());
Douglas Gregor10176412011-02-25 16:07:42 +00008035 NestedNameSpecifierLoc Rebuilt
8036 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8037 if (!Rebuilt)
8038 return true;
John McCall99b2fe52010-04-29 23:50:39 +00008039
Douglas Gregor10176412011-02-25 16:07:42 +00008040 SS.Adopt(Rebuilt);
John McCall99b2fe52010-04-29 23:50:39 +00008041 return false;
John McCall2408e322010-04-27 00:57:59 +00008042}
8043
Douglas Gregor041b0842011-10-14 15:31:12 +00008044/// \brief Rebuild the template parameters now that we know we're in a current
8045/// instantiation.
8046bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8047 TemplateParameterList *Params) {
8048 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8049 Decl *Param = Params->getParam(I);
8050
8051 // There is nothing to rebuild in a type parameter.
8052 if (isa<TemplateTypeParmDecl>(Param))
8053 continue;
8054
8055 // Rebuild the template parameter list of a template template parameter.
8056 if (TemplateTemplateParmDecl *TTP
8057 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8058 if (RebuildTemplateParamsInCurrentInstantiation(
8059 TTP->getTemplateParameters()))
8060 return true;
8061
8062 continue;
8063 }
8064
8065 // Rebuild the type of a non-type template parameter.
8066 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8067 TypeSourceInfo *NewTSI
8068 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8069 NTTP->getLocation(),
8070 NTTP->getDeclName());
8071 if (!NewTSI)
8072 return true;
8073
8074 if (NewTSI != NTTP->getTypeSourceInfo()) {
8075 NTTP->setTypeSourceInfo(NewTSI);
8076 NTTP->setType(NewTSI->getType());
8077 }
8078 }
8079
8080 return false;
8081}
8082
Douglas Gregorbe999392009-09-15 16:23:51 +00008083/// \brief Produces a formatted string that describes the binding of
8084/// template parameters to template arguments.
8085std::string
8086Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8087 const TemplateArgumentList &Args) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00008088 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregore62e6a02009-11-11 19:13:48 +00008089}
8090
8091std::string
8092Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8093 const TemplateArgument *Args,
8094 unsigned NumArgs) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008095 SmallString<128> Str;
Douglas Gregor0192c232010-12-20 16:52:59 +00008096 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbe999392009-09-15 16:23:51 +00008097
Douglas Gregore62e6a02009-11-11 19:13:48 +00008098 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008099 return std::string();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008100
Douglas Gregorbe999392009-09-15 16:23:51 +00008101 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00008102 if (I >= NumArgs)
8103 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008104
Douglas Gregorbe999392009-09-15 16:23:51 +00008105 if (I == 0)
Douglas Gregor0192c232010-12-20 16:52:59 +00008106 Out << "[with ";
Douglas Gregorbe999392009-09-15 16:23:51 +00008107 else
Douglas Gregor0192c232010-12-20 16:52:59 +00008108 Out << ", ";
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008109
Douglas Gregorbe999392009-09-15 16:23:51 +00008110 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor0192c232010-12-20 16:52:59 +00008111 Out << Id->getName();
Douglas Gregorbe999392009-09-15 16:23:51 +00008112 } else {
Douglas Gregor0192c232010-12-20 16:52:59 +00008113 Out << '$' << I;
Douglas Gregorbe999392009-09-15 16:23:51 +00008114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008115
Douglas Gregor0192c232010-12-20 16:52:59 +00008116 Out << " = ";
Douglas Gregor75acd922011-09-27 23:30:47 +00008117 Args[I].print(getPrintingPolicy(), Out);
Douglas Gregorbe999392009-09-15 16:23:51 +00008118 }
Douglas Gregor0192c232010-12-20 16:52:59 +00008119
8120 Out << ']';
8121 return Out.str();
Douglas Gregorbe999392009-09-15 16:23:51 +00008122}
Francois Pichet1c229c02011-04-22 22:18:13 +00008123
Richard Smithe40f2ba2013-08-07 21:41:30 +00008124void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8125 CachedTokens &Toks) {
Francois Pichet1c229c02011-04-22 22:18:13 +00008126 if (!FD)
8127 return;
Richard Smithe40f2ba2013-08-07 21:41:30 +00008128
8129 LateParsedTemplate *LPT = new LateParsedTemplate;
8130
8131 // Take tokens to avoid allocations
8132 LPT->Toks.swap(Toks);
8133 LPT->D = FnD;
8134 LateParsedTemplateMap[FD] = LPT;
8135
8136 FD->setLateTemplateParsed(true);
8137}
8138
8139void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8140 if (!FD)
8141 return;
8142 FD->setLateTemplateParsed(false);
8143}
Francois Pichet1c229c02011-04-22 22:18:13 +00008144
8145bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8146 DeclContext *DC = CurContext;
8147
8148 while (DC) {
8149 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8150 const FunctionDecl *FD = RD->isLocalClass();
8151 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8152 } else if (DC->isTranslationUnit() || DC->isNamespace())
8153 return false;
8154
8155 DC = DC->getParent();
8156 }
8157 return false;
8158}