Deleted Added
full compact
SemaTemplate.cpp (280031) SemaTemplate.cpp (283526)
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2//
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.
7//===----------------------------------------------------------------------===/
8//
9// This file implements semantic analysis for C++ templates.
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclFriend.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/RecursiveASTVisitor.h"
20#include "clang/AST/TypeVisitor.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/TargetInfo.h"
24#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"
31#include "llvm/ADT/SmallBitVector.h"
32#include "llvm/ADT/SmallString.h"
33#include "llvm/ADT/StringExtras.h"
34using namespace clang;
35using namespace sema;
36
37// 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
45/// \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.
48static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
49 NamedDecl *Orig,
50 bool AllowFunctionTemplates) {
51 NamedDecl *D = Orig->getUnderlyingDecl();
52
53 if (isa<TemplateDecl>(D)) {
54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
55 return nullptr;
56
57 return Orig;
58 }
59
60 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()) {
73 Record = cast<CXXRecordDecl>(Record->getDeclContext());
74 if (Record->getDescribedClassTemplate())
75 return Record->getDescribedClassTemplate();
76
77 if (ClassTemplateSpecializationDecl *Spec
78 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
79 return Spec->getSpecializedTemplate();
80 }
81
82 return nullptr;
83 }
84
85 return nullptr;
86}
87
88void Sema::FilterAcceptableTemplateNames(LookupResult &R,
89 bool AllowFunctionTemplates) {
90 // The set of class templates we've already seen.
91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
92 LookupResult::Filter filter = R.makeFilter();
93 while (filter.hasNext()) {
94 NamedDecl *Orig = filter.next();
95 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
96 AllowFunctionTemplates);
97 if (!Repl)
98 filter.erase();
99 else if (Repl != Orig) {
100
101 // C++ [temp.local]p3:
102 // A lookup that finds an injected-class-name (10.2) can result in an
103 // ambiguity in certain cases (for example, if it is found in more than
104 // 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
106 // is used as a template-name, the reference refers to the class
107 // template itself and not a specialization thereof, and is not
108 // ambiguous.
109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
110 if (!ClassTemplates.insert(ClassTmpl).second) {
111 filter.erase();
112 continue;
113 }
114
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);
121 }
122 }
123 filter.done();
124}
125
126bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
127 bool AllowFunctionTemplates) {
128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
130 return true;
131
132 return false;
133}
134
135TemplateNameKind Sema::isTemplateName(Scope *S,
136 CXXScopeSpec &SS,
137 bool hasTemplateKeyword,
138 UnqualifiedId &Name,
139 ParsedType ObjectTypePtr,
140 bool EnteringContext,
141 TemplateTy &TemplateResult,
142 bool &MemberOfUnknownSpecialization) {
143 assert(getLangOpts().CPlusPlus && "No template names in C!");
144
145 DeclarationName TName;
146 MemberOfUnknownSpecialization = false;
147
148 switch (Name.getKind()) {
149 case UnqualifiedId::IK_Identifier:
150 TName = DeclarationName(Name.Identifier);
151 break;
152
153 case UnqualifiedId::IK_OperatorFunctionId:
154 TName = Context.DeclarationNames.getCXXOperatorName(
155 Name.OperatorFunctionId.Operator);
156 break;
157
158 case UnqualifiedId::IK_LiteralOperatorId:
159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
160 break;
161
162 default:
163 return TNK_Non_template;
164 }
165
166 QualType ObjectType = ObjectTypePtr.get();
167
168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
170 MemberOfUnknownSpecialization);
171 if (R.empty()) return TNK_Non_template;
172 if (R.isAmbiguous()) {
173 // Suppress diagnostics; we'll redo this lookup later.
174 R.suppressDiagnostics();
175
176 // FIXME: we might have ambiguous templates, in which case we
177 // should at least parse them properly!
178 return TNK_Non_template;
179 }
180
181 TemplateName Template;
182 TemplateNameKind TemplateKind;
183
184 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;
190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
195
196 if (SS.isSet() && !SS.isInvalid()) {
197 NestedNameSpecifier *Qualifier = SS.getScopeRep();
198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
200 } else {
201 Template = TemplateName(TD);
202 }
203
204 if (isa<FunctionTemplateDecl>(TD)) {
205 TemplateKind = TNK_Function_template;
206
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
209 } else {
210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
212 TemplateKind =
213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
214 }
215 }
216
217 TemplateResult = TemplateTy::make(Template);
218 return TemplateKind;
219}
220
221bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
222 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.
229 // FIXME: Typo correction?
230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
231 computeDeclContext(*SS))
232 return false;
233
234 // 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()
239 << FixItHint::CreateInsertion(IILoc, "template ");
240 SuggestedTemplate
241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
242 SuggestedKind = TNK_Dependent_template_name;
243 return true;
244}
245
246void Sema::LookupTemplateName(LookupResult &Found,
247 Scope *S, CXXScopeSpec &SS,
248 QualType ObjectType,
249 bool EnteringContext,
250 bool &MemberOfUnknownSpecialization) {
251 // Determine where to perform name lookup
252 MemberOfUnknownSpecialization = false;
253 DeclContext *LookupCtx = nullptr;
254 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();
261 assert((isDependent || !ObjectType->isIncompleteType() ||
262 ObjectType->castAs<TagType>()->isBeingDefined()) &&
263 "Caller should have completed object type");
264
265 // Template names cannot appear inside an Objective-C class or object type.
266 if (ObjectType->isObjCObjectOrInterfaceType()) {
267 Found.clear();
268 return;
269 }
270 } 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);
275
276 // The declaration context must be complete.
277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
278 return;
279 }
280
281 bool ObjectTypeSearchedInScope = false;
282 bool AllowFunctionTemplatesInLookup = true;
283 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);
289 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.
299 if (S) LookupName(Found, S);
300 ObjectTypeSearchedInScope = true;
301 AllowFunctionTemplatesInLookup = false;
302 }
303 } else if (isDependent && (!S || ObjectType.isNull())) {
304 // We cannot look into a dependent object type or nested nme
305 // specifier.
306 MemberOfUnknownSpecialization = true;
307 return;
308 } else {
309 // Perform unqualified name lookup in the current scope.
310 LookupName(Found, S);
311
312 if (!ObjectType.isNull())
313 AllowFunctionTemplatesInLookup = false;
314 }
315
316 if (Found.empty() && !isDependent) {
317 // If we did not find any names, attempt to correct any typos.
318 DeclarationName Name = Found.getLookupName();
319 Found.clear();
320 // Simple filter callback that, for keywords, only accepts the C++ *_cast
321 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
322 FilterCCC->WantTypeSpecifiers = false;
323 FilterCCC->WantExpressionKeywords = false;
324 FilterCCC->WantRemainingKeywords = false;
325 FilterCCC->WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(
327 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
328 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
329 Found.setLookupName(Corrected.getCorrection());
330 if (Corrected.getCorrectionDecl())
331 Found.addDecl(Corrected.getCorrectionDecl());
332 FilterAcceptableTemplateNames(Found);
333 if (!Found.empty()) {
334 if (LookupCtx) {
335 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
336 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
337 Name.getAsString() == CorrectedStr;
338 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
339 << Name << LookupCtx << DroppedSpecifier
340 << SS.getRange());
341 } else {
342 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
343 }
344 }
345 } else {
346 Found.setLookupName(Name);
347 }
348 }
349
350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
351 if (Found.empty()) {
352 if (isDependent)
353 MemberOfUnknownSpecialization = true;
354 return;
355 }
356
357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
358 !getLangOpts().CPlusPlus11) {
359 // C++03 [basic.lookup.classref]p1:
360 // [...] If the lookup in the class of the object expression finds a
361 // template, the name is also looked up in the context of the entire
362 // postfix-expression and [...]
363 //
364 // Note: C++11 does not perform this second lookup.
365 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
366 LookupOrdinaryName);
367 LookupName(FoundOuter, S);
368 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
369
370 if (FoundOuter.empty()) {
371 // - if the name is not found, the name found in the class of the
372 // object expression is used, otherwise
373 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
374 FoundOuter.isAmbiguous()) {
375 // - if the name is found in the context of the entire
376 // postfix-expression and does not name a class template, the name
377 // found in the class of the object expression is used, otherwise
378 FoundOuter.clear();
379 } else if (!Found.isSuppressingDiagnostics()) {
380 // - if the name found is a class template, it must refer to the same
381 // entity as the one found in the class of the object expression,
382 // otherwise the program is ill-formed.
383 if (!Found.isSingleResult() ||
384 Found.getFoundDecl()->getCanonicalDecl()
385 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
386 Diag(Found.getNameLoc(),
387 diag::ext_nested_name_member_ref_lookup_ambiguous)
388 << Found.getLookupName()
389 << ObjectType;
390 Diag(Found.getRepresentativeDecl()->getLocation(),
391 diag::note_ambig_member_ref_object_type)
392 << ObjectType;
393 Diag(FoundOuter.getFoundDecl()->getLocation(),
394 diag::note_ambig_member_ref_scope);
395
396 // Recover by taking the template that we found in the object
397 // expression's type.
398 }
399 }
400 }
401}
402
403/// ActOnDependentIdExpression - Handle a dependent id-expression that
404/// was just parsed. This is only possible with an explicit scope
405/// specifier naming a dependent type.
406ExprResult
407Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
408 SourceLocation TemplateKWLoc,
409 const DeclarationNameInfo &NameInfo,
410 bool isAddressOfOperand,
411 const TemplateArgumentListInfo *TemplateArgs) {
412 DeclContext *DC = getFunctionLevelDeclContext();
413
414 if (!isAddressOfOperand &&
415 isa<CXXMethodDecl>(DC) &&
416 cast<CXXMethodDecl>(DC)->isInstance()) {
417 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
418
419 // Since the 'this' expression is synthesized, we don't need to
420 // perform the double-lookup check.
421 NamedDecl *FirstQualifierInScope = nullptr;
422
423 return CXXDependentScopeMemberExpr::Create(
424 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
425 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
426 FirstQualifierInScope, NameInfo, TemplateArgs);
427 }
428
429 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
430}
431
432ExprResult
433Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
434 SourceLocation TemplateKWLoc,
435 const DeclarationNameInfo &NameInfo,
436 const TemplateArgumentListInfo *TemplateArgs) {
437 return DependentScopeDeclRefExpr::Create(
438 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
439 TemplateArgs);
440}
441
442/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
443/// that the template parameter 'PrevDecl' is being shadowed by a new
444/// declaration at location Loc. Returns true to indicate that this is
445/// an error, and false otherwise.
446void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
447 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
448
449 // Microsoft Visual C++ permits template parameters to be shadowed.
450 if (getLangOpts().MicrosoftExt)
451 return;
452
453 // C++ [temp.local]p4:
454 // A template-parameter shall not be redeclared within its
455 // scope (including nested scopes).
456 Diag(Loc, diag::err_template_param_shadow)
457 << cast<NamedDecl>(PrevDecl)->getDeclName();
458 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
459 return;
460}
461
462/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
463/// the parameter D to reference the templated declaration and return a pointer
464/// to the template declaration. Otherwise, do nothing to D and return null.
465TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
466 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
467 D = Temp->getTemplatedDecl();
468 return Temp;
469 }
470 return nullptr;
471}
472
473ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
474 SourceLocation EllipsisLoc) const {
475 assert(Kind == Template &&
476 "Only template template arguments can be pack expansions here");
477 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
478 "Template template argument pack expansion without packs");
479 ParsedTemplateArgument Result(*this);
480 Result.EllipsisLoc = EllipsisLoc;
481 return Result;
482}
483
484static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
485 const ParsedTemplateArgument &Arg) {
486
487 switch (Arg.getKind()) {
488 case ParsedTemplateArgument::Type: {
489 TypeSourceInfo *DI;
490 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
491 if (!DI)
492 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
493 return TemplateArgumentLoc(TemplateArgument(T), DI);
494 }
495
496 case ParsedTemplateArgument::NonType: {
497 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
498 return TemplateArgumentLoc(TemplateArgument(E), E);
499 }
500
501 case ParsedTemplateArgument::Template: {
502 TemplateName Template = Arg.getAsTemplate().get();
503 TemplateArgument TArg;
504 if (Arg.getEllipsisLoc().isValid())
505 TArg = TemplateArgument(Template, Optional<unsigned int>());
506 else
507 TArg = Template;
508 return TemplateArgumentLoc(TArg,
509 Arg.getScopeSpec().getWithLocInContext(
510 SemaRef.Context),
511 Arg.getLocation(),
512 Arg.getEllipsisLoc());
513 }
514 }
515
516 llvm_unreachable("Unhandled parsed template argument");
517}
518
519/// \brief Translates template arguments as provided by the parser
520/// into template arguments used by semantic analysis.
521void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
522 TemplateArgumentListInfo &TemplateArgs) {
523 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
524 TemplateArgs.addArgument(translateTemplateArgument(*this,
525 TemplateArgsIn[I]));
526}
527
528static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
529 SourceLocation Loc,
530 IdentifierInfo *Name) {
531 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
532 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
533 if (PrevDecl && PrevDecl->isTemplateParameter())
534 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
535}
536
537/// ActOnTypeParameter - Called when a C++ template type parameter
538/// (e.g., "typename T") has been parsed. Typename specifies whether
539/// the keyword "typename" was used to declare the type parameter
540/// (otherwise, "class" was used), and KeyLoc is the location of the
541/// "class" or "typename" keyword. ParamName is the name of the
542/// parameter (NULL indicates an unnamed template parameter) and
543/// ParamNameLoc is the location of the parameter name (if any).
544/// If the type parameter has a default argument, it will be added
545/// later via ActOnTypeParameterDefault.
546Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
553 ParsedType DefaultArg) {
554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
556 bool Invalid = false;
557
558 SourceLocation Loc = ParamNameLoc;
559 if (!ParamName)
560 Loc = KeyLoc;
561
562 bool IsParameterPack = EllipsisLoc.isValid();
563 TemplateTypeParmDecl *Param
564 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
565 KeyLoc, Loc, Depth, Position, ParamName,
566 Typename, IsParameterPack);
567 Param->setAccess(AS_public);
568 if (Invalid)
569 Param->setInvalidDecl();
570
571 if (ParamName) {
572 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
573
574 // Add the template parameter into the current scope.
575 S->AddDecl(Param);
576 IdResolver.AddDecl(Param);
577 }
578
579 // C++0x [temp.param]p9:
580 // A default template-argument may be specified for any kind of
581 // template-parameter that is not a template parameter pack.
582 if (DefaultArg && IsParameterPack) {
583 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
584 DefaultArg = ParsedType();
585 }
586
587 // Handle the default argument, if provided.
588 if (DefaultArg) {
589 TypeSourceInfo *DefaultTInfo;
590 GetTypeFromParser(DefaultArg, &DefaultTInfo);
591
592 assert(DefaultTInfo && "expected source information for type");
593
594 // Check for unexpanded parameter packs.
595 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
596 UPPC_DefaultArgument))
597 return Param;
598
599 // Check the template argument itself.
600 if (CheckTemplateArgument(Param, DefaultTInfo)) {
601 Param->setInvalidDecl();
602 return Param;
603 }
604
605 Param->setDefaultArgument(DefaultTInfo, false);
606 }
607
608 return Param;
609}
610
611/// \brief Check that the type of a non-type template parameter is
612/// well-formed.
613///
614/// \returns the (possibly-promoted) parameter type if valid;
615/// otherwise, produces a diagnostic and returns a NULL type.
616QualType
617Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
618 // We don't allow variably-modified types as the type of non-type template
619 // parameters.
620 if (T->isVariablyModifiedType()) {
621 Diag(Loc, diag::err_variably_modified_nontype_template_param)
622 << T;
623 return QualType();
624 }
625
626 // C++ [temp.param]p4:
627 //
628 // A non-type template-parameter shall have one of the following
629 // (optionally cv-qualified) types:
630 //
631 // -- integral or enumeration type,
632 if (T->isIntegralOrEnumerationType() ||
633 // -- pointer to object or pointer to function,
634 T->isPointerType() ||
635 // -- reference to object or reference to function,
636 T->isReferenceType() ||
637 // -- pointer to member,
638 T->isMemberPointerType() ||
639 // -- std::nullptr_t.
640 T->isNullPtrType() ||
641 // If T is a dependent type, we can't do the check now, so we
642 // assume that it is well-formed.
643 T->isDependentType()) {
644 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
645 // are ignored when determining its type.
646 return T.getUnqualifiedType();
647 }
648
649 // C++ [temp.param]p8:
650 //
651 // A non-type template-parameter of type "array of T" or
652 // "function returning T" is adjusted to be of type "pointer to
653 // T" or "pointer to function returning T", respectively.
654 else if (T->isArrayType() || T->isFunctionType())
655 return Context.getDecayedType(T);
656
657 Diag(Loc, diag::err_template_nontype_parm_bad_type)
658 << T;
659
660 return QualType();
661}
662
663Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
664 unsigned Depth,
665 unsigned Position,
666 SourceLocation EqualLoc,
667 Expr *Default) {
668 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
669 QualType T = TInfo->getType();
670
671 assert(S->isTemplateParamScope() &&
672 "Non-type template parameter not in template parameter scope!");
673 bool Invalid = false;
674
675 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
676 if (T.isNull()) {
677 T = Context.IntTy; // Recover with an 'int' type.
678 Invalid = true;
679 }
680
681 IdentifierInfo *ParamName = D.getIdentifier();
682 bool IsParameterPack = D.hasEllipsis();
683 NonTypeTemplateParmDecl *Param
684 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
685 D.getLocStart(),
686 D.getIdentifierLoc(),
687 Depth, Position, ParamName, T,
688 IsParameterPack, TInfo);
689 Param->setAccess(AS_public);
690
691 if (Invalid)
692 Param->setInvalidDecl();
693
694 if (ParamName) {
695 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
696 ParamName);
697
698 // Add the template parameter into the current scope.
699 S->AddDecl(Param);
700 IdResolver.AddDecl(Param);
701 }
702
703 // C++0x [temp.param]p9:
704 // A default template-argument may be specified for any kind of
705 // template-parameter that is not a template parameter pack.
706 if (Default && IsParameterPack) {
707 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
708 Default = nullptr;
709 }
710
711 // Check the well-formedness of the default template argument, if provided.
712 if (Default) {
713 // Check for unexpanded parameter packs.
714 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
715 return Param;
716
717 TemplateArgument Converted;
718 ExprResult DefaultRes =
719 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
720 if (DefaultRes.isInvalid()) {
721 Param->setInvalidDecl();
722 return Param;
723 }
724 Default = DefaultRes.get();
725
726 Param->setDefaultArgument(Default, false);
727 }
728
729 return Param;
730}
731
732/// ActOnTemplateTemplateParameter - Called when a C++ template template
733/// parameter (e.g. T in template <template \<typename> class T> class array)
734/// has been parsed. S is the current scope.
735Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
736 SourceLocation TmpLoc,
737 TemplateParameterList *Params,
738 SourceLocation EllipsisLoc,
739 IdentifierInfo *Name,
740 SourceLocation NameLoc,
741 unsigned Depth,
742 unsigned Position,
743 SourceLocation EqualLoc,
744 ParsedTemplateArgument Default) {
745 assert(S->isTemplateParamScope() &&
746 "Template template parameter not in template parameter scope!");
747
748 // Construct the parameter object.
749 bool IsParameterPack = EllipsisLoc.isValid();
750 TemplateTemplateParmDecl *Param =
751 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
752 NameLoc.isInvalid()? TmpLoc : NameLoc,
753 Depth, Position, IsParameterPack,
754 Name, Params);
755 Param->setAccess(AS_public);
756
757 // If the template template parameter has a name, then link the identifier
758 // into the scope and lookup mechanisms.
759 if (Name) {
760 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
761
762 S->AddDecl(Param);
763 IdResolver.AddDecl(Param);
764 }
765
766 if (Params->size() == 0) {
767 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
768 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
769 Param->setInvalidDecl();
770 }
771
772 // C++0x [temp.param]p9:
773 // A default template-argument may be specified for any kind of
774 // template-parameter that is not a template parameter pack.
775 if (IsParameterPack && !Default.isInvalid()) {
776 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
777 Default = ParsedTemplateArgument();
778 }
779
780 if (!Default.isInvalid()) {
781 // Check only that we have a template template argument. We don't want to
782 // try to check well-formedness now, because our template template parameter
783 // might have dependent types in its template parameters, which we wouldn't
784 // be able to match now.
785 //
786 // If none of the template template parameter's template arguments mention
787 // other template parameters, we could actually perform more checking here.
788 // However, it isn't worth doing.
789 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
790 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
791 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
792 << DefaultArg.getSourceRange();
793 return Param;
794 }
795
796 // Check for unexpanded parameter packs.
797 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
798 DefaultArg.getArgument().getAsTemplate(),
799 UPPC_DefaultArgument))
800 return Param;
801
802 Param->setDefaultArgument(DefaultArg, false);
803 }
804
805 return Param;
806}
807
808/// ActOnTemplateParameterList - Builds a TemplateParameterList that
809/// contains the template parameters in Params/NumParams.
810TemplateParameterList *
811Sema::ActOnTemplateParameterList(unsigned Depth,
812 SourceLocation ExportLoc,
813 SourceLocation TemplateLoc,
814 SourceLocation LAngleLoc,
815 Decl **Params, unsigned NumParams,
816 SourceLocation RAngleLoc) {
817 if (ExportLoc.isValid())
818 Diag(ExportLoc, diag::warn_template_export_unsupported);
819
820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
821 (NamedDecl**)Params, NumParams,
822 RAngleLoc);
823}
824
825static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
826 if (SS.isSet())
827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
828}
829
830DeclResult
831Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
832 SourceLocation KWLoc, CXXScopeSpec &SS,
833 IdentifierInfo *Name, SourceLocation NameLoc,
834 AttributeList *Attr,
835 TemplateParameterList *TemplateParams,
836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
837 SourceLocation FriendLoc,
838 unsigned NumOuterTemplateParamLists,
839 TemplateParameterList** OuterTemplateParamLists) {
840 assert(TemplateParams && TemplateParams->size() > 0 &&
841 "No template parameters");
842 assert(TUK != TUK_Reference && "Can only declare or define class templates");
843 bool Invalid = false;
844
845 // Check that we can declare a template here.
846 if (CheckTemplateDeclScope(S, TemplateParams))
847 return true;
848
849 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
850 assert(Kind != TTK_Enum && "can't build template of enumerated type");
851
852 // There is no such thing as an unnamed class template.
853 if (!Name) {
854 Diag(KWLoc, diag::err_template_unnamed_class);
855 return true;
856 }
857
858 // Find any previous declaration with this name. For a friend with no
859 // scope explicitly specified, we only look for tag declarations (per
860 // C++11 [basic.lookup.elab]p2).
861 DeclContext *SemanticContext;
862 LookupResult Previous(*this, Name, NameLoc,
863 (SS.isEmpty() && TUK == TUK_Friend)
864 ? LookupTagName : LookupOrdinaryName,
865 ForRedeclaration);
866 if (SS.isNotEmpty() && !SS.isInvalid()) {
867 SemanticContext = computeDeclContext(SS, true);
868 if (!SemanticContext) {
869 // FIXME: Horrible, horrible hack! We can't currently represent this
870 // in the AST, and historically we have just ignored such friend
871 // class templates, so don't complain here.
872 Diag(NameLoc, TUK == TUK_Friend
873 ? diag::warn_template_qualified_friend_ignored
874 : diag::err_template_qualified_declarator_no_match)
875 << SS.getScopeRep() << SS.getRange();
876 return TUK != TUK_Friend;
877 }
878
879 if (RequireCompleteDeclContext(SS, SemanticContext))
880 return true;
881
882 // If we're adding a template to a dependent context, we may need to
883 // rebuilding some of the types used within the template parameter list,
884 // now that we know what the current instantiation is.
885 if (SemanticContext->isDependentContext()) {
886 ContextRAII SavedContext(*this, SemanticContext);
887 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
888 Invalid = true;
889 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
890 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
891
892 LookupQualifiedName(Previous, SemanticContext);
893 } else {
894 SemanticContext = CurContext;
895 LookupName(Previous, S);
896 }
897
898 if (Previous.isAmbiguous())
899 return true;
900
901 NamedDecl *PrevDecl = nullptr;
902 if (Previous.begin() != Previous.end())
903 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
904
905 // If there is a previous declaration with the same name, check
906 // whether this is a valid redeclaration.
907 ClassTemplateDecl *PrevClassTemplate
908 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
909
910 // We may have found the injected-class-name of a class template,
911 // class template partial specialization, or class template specialization.
912 // In these cases, grab the template that is being defined or specialized.
913 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
914 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
915 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
916 PrevClassTemplate
917 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
918 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
919 PrevClassTemplate
920 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
921 ->getSpecializedTemplate();
922 }
923 }
924
925 if (TUK == TUK_Friend) {
926 // C++ [namespace.memdef]p3:
927 // [...] When looking for a prior declaration of a class or a function
928 // declared as a friend, and when the name of the friend class or
929 // function is neither a qualified name nor a template-id, scopes outside
930 // the innermost enclosing namespace scope are not considered.
931 if (!SS.isSet()) {
932 DeclContext *OutermostContext = CurContext;
933 while (!OutermostContext->isFileContext())
934 OutermostContext = OutermostContext->getLookupParent();
935
936 if (PrevDecl &&
937 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
938 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
939 SemanticContext = PrevDecl->getDeclContext();
940 } else {
941 // Declarations in outer scopes don't matter. However, the outermost
942 // context we computed is the semantic context for our new
943 // declaration.
944 PrevDecl = PrevClassTemplate = nullptr;
945 SemanticContext = OutermostContext;
946
947 // Check that the chosen semantic context doesn't already contain a
948 // declaration of this name as a non-tag type.
949 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
950 ForRedeclaration);
951 DeclContext *LookupContext = SemanticContext;
952 while (LookupContext->isTransparentContext())
953 LookupContext = LookupContext->getLookupParent();
954 LookupQualifiedName(Previous, LookupContext);
955
956 if (Previous.isAmbiguous())
957 return true;
958
959 if (Previous.begin() != Previous.end())
960 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
961 }
962 }
963 } else if (PrevDecl &&
964 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
965 PrevDecl = PrevClassTemplate = nullptr;
966
967 if (PrevClassTemplate) {
968 // Ensure that the template parameter lists are compatible. Skip this check
969 // for a friend in a dependent context: the template parameter list itself
970 // could be dependent.
971 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
972 !TemplateParameterListsAreEqual(TemplateParams,
973 PrevClassTemplate->getTemplateParameters(),
974 /*Complain=*/true,
975 TPL_TemplateMatch))
976 return true;
977
978 // C++ [temp.class]p4:
979 // In a redeclaration, partial specialization, explicit
980 // specialization or explicit instantiation of a class template,
981 // the class-key shall agree in kind with the original class
982 // template declaration (7.1.5.3).
983 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
984 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
985 TUK == TUK_Definition, KWLoc, *Name)) {
986 Diag(KWLoc, diag::err_use_with_wrong_tag)
987 << Name
988 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
989 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
990 Kind = PrevRecordDecl->getTagKind();
991 }
992
993 // Check for redefinition of this class template.
994 if (TUK == TUK_Definition) {
995 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
996 Diag(NameLoc, diag::err_redefinition) << Name;
997 Diag(Def->getLocation(), diag::note_previous_definition);
998 // FIXME: Would it make sense to try to "forget" the previous
999 // definition, as part of error recovery?
1000 return true;
1001 }
1002 }
1003 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1004 // Maybe we will complain about the shadowed template parameter.
1005 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1006 // Just pretend that we didn't see the previous declaration.
1007 PrevDecl = nullptr;
1008 } else if (PrevDecl) {
1009 // C++ [temp]p5:
1010 // A class template shall not have the same name as any other
1011 // template, class, function, object, enumeration, enumerator,
1012 // namespace, or type in the same scope (3.3), except as specified
1013 // in (14.5.4).
1014 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1015 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1016 return true;
1017 }
1018
1019 // Check the template parameter list of this declaration, possibly
1020 // merging in the template parameter list from the previous class
1021 // template declaration. Skip this check for a friend in a dependent
1022 // context, because the template parameter list might be dependent.
1023 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1024 CheckTemplateParameterList(
1025 TemplateParams,
1026 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1027 : nullptr,
1028 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1029 SemanticContext->isDependentContext())
1030 ? TPC_ClassTemplateMember
1031 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1032 : TPC_ClassTemplate))
1033 Invalid = true;
1034
1035 if (SS.isSet()) {
1036 // If the name of the template was qualified, we must be defining the
1037 // template out-of-line.
1038 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1039 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1040 : diag::err_member_decl_does_not_match)
1041 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1042 Invalid = true;
1043 }
1044 }
1045
1046 CXXRecordDecl *NewClass =
1047 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1048 PrevClassTemplate?
1049 PrevClassTemplate->getTemplatedDecl() : nullptr,
1050 /*DelayTypeCreation=*/true);
1051 SetNestedNameSpecifier(NewClass, SS);
1052 if (NumOuterTemplateParamLists > 0)
1053 NewClass->setTemplateParameterListsInfo(Context,
1054 NumOuterTemplateParamLists,
1055 OuterTemplateParamLists);
1056
1057 // Add alignment attributes if necessary; these attributes are checked when
1058 // the ASTContext lays out the structure.
1059 if (TUK == TUK_Definition) {
1060 AddAlignmentAttributesForRecord(NewClass);
1061 AddMsStructLayoutForRecord(NewClass);
1062 }
1063
1064 ClassTemplateDecl *NewTemplate
1065 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1066 DeclarationName(Name), TemplateParams,
1067 NewClass, PrevClassTemplate);
1068 NewClass->setDescribedClassTemplate(NewTemplate);
1069
1070 if (ModulePrivateLoc.isValid())
1071 NewTemplate->setModulePrivate();
1072
1073 // Build the type for the class template declaration now.
1074 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1075 T = Context.getInjectedClassNameType(NewClass, T);
1076 assert(T->isDependentType() && "Class template type is not dependent?");
1077 (void)T;
1078
1079 // If we are providing an explicit specialization of a member that is a
1080 // class template, make a note of that.
1081 if (PrevClassTemplate &&
1082 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1083 PrevClassTemplate->setMemberSpecialization();
1084
1085 // Set the access specifier.
1086 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1087 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1088
1089 // Set the lexical context of these templates
1090 NewClass->setLexicalDeclContext(CurContext);
1091 NewTemplate->setLexicalDeclContext(CurContext);
1092
1093 if (TUK == TUK_Definition)
1094 NewClass->startDefinition();
1095
1096 if (Attr)
1097 ProcessDeclAttributeList(S, NewClass, Attr);
1098
1099 if (PrevClassTemplate)
1100 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1101
1102 AddPushedVisibilityAttribute(NewClass);
1103
1104 if (TUK != TUK_Friend) {
1105 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1106 Scope *Outer = S;
1107 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1108 Outer = Outer->getParent();
1109 PushOnScopeChains(NewTemplate, Outer);
1110 } else {
1111 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1112 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1113 NewClass->setAccess(PrevClassTemplate->getAccess());
1114 }
1115
1116 NewTemplate->setObjectOfFriendDecl();
1117
1118 // Friend templates are visible in fairly strange ways.
1119 if (!CurContext->isDependentContext()) {
1120 DeclContext *DC = SemanticContext->getRedeclContext();
1121 DC->makeDeclVisibleInContext(NewTemplate);
1122 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1123 PushOnScopeChains(NewTemplate, EnclosingScope,
1124 /* AddToContext = */ false);
1125 }
1126
1127 FriendDecl *Friend = FriendDecl::Create(
1128 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1129 Friend->setAccess(AS_public);
1130 CurContext->addDecl(Friend);
1131 }
1132
1133 if (Invalid) {
1134 NewTemplate->setInvalidDecl();
1135 NewClass->setInvalidDecl();
1136 }
1137
1138 ActOnDocumentableDecl(NewTemplate);
1139
1140 return NewTemplate;
1141}
1142
1143/// \brief Diagnose the presence of a default template argument on a
1144/// template parameter, which is ill-formed in certain contexts.
1145///
1146/// \returns true if the default template argument should be dropped.
1147static bool DiagnoseDefaultTemplateArgument(Sema &S,
1148 Sema::TemplateParamListContext TPC,
1149 SourceLocation ParamLoc,
1150 SourceRange DefArgRange) {
1151 switch (TPC) {
1152 case Sema::TPC_ClassTemplate:
1153 case Sema::TPC_VarTemplate:
1154 case Sema::TPC_TypeAliasTemplate:
1155 return false;
1156
1157 case Sema::TPC_FunctionTemplate:
1158 case Sema::TPC_FriendFunctionTemplateDefinition:
1159 // C++ [temp.param]p9:
1160 // A default template-argument shall not be specified in a
1161 // function template declaration or a function template
1162 // definition [...]
1163 // If a friend function template declaration specifies a default
1164 // template-argument, that declaration shall be a definition and shall be
1165 // the only declaration of the function template in the translation unit.
1166 // (C++98/03 doesn't have this wording; see DR226).
1167 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1168 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1169 : diag::ext_template_parameter_default_in_function_template)
1170 << DefArgRange;
1171 return false;
1172
1173 case Sema::TPC_ClassTemplateMember:
1174 // C++0x [temp.param]p9:
1175 // A default template-argument shall not be specified in the
1176 // template-parameter-lists of the definition of a member of a
1177 // class template that appears outside of the member's class.
1178 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1179 << DefArgRange;
1180 return true;
1181
1182 case Sema::TPC_FriendClassTemplate:
1183 case Sema::TPC_FriendFunctionTemplate:
1184 // C++ [temp.param]p9:
1185 // A default template-argument shall not be specified in a
1186 // friend template declaration.
1187 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1188 << DefArgRange;
1189 return true;
1190
1191 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1192 // for friend function templates if there is only a single
1193 // declaration (and it is a definition). Strange!
1194 }
1195
1196 llvm_unreachable("Invalid TemplateParamListContext!");
1197}
1198
1199/// \brief Check for unexpanded parameter packs within the template parameters
1200/// of a template template parameter, recursively.
1201static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1202 TemplateTemplateParmDecl *TTP) {
1203 // A template template parameter which is a parameter pack is also a pack
1204 // expansion.
1205 if (TTP->isParameterPack())
1206 return false;
1207
1208 TemplateParameterList *Params = TTP->getTemplateParameters();
1209 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1210 NamedDecl *P = Params->getParam(I);
1211 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1212 if (!NTTP->isParameterPack() &&
1213 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1214 NTTP->getTypeSourceInfo(),
1215 Sema::UPPC_NonTypeTemplateParameterType))
1216 return true;
1217
1218 continue;
1219 }
1220
1221 if (TemplateTemplateParmDecl *InnerTTP
1222 = dyn_cast<TemplateTemplateParmDecl>(P))
1223 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1224 return true;
1225 }
1226
1227 return false;
1228}
1229
1230/// \brief Checks the validity of a template parameter list, possibly
1231/// considering the template parameter list from a previous
1232/// declaration.
1233///
1234/// If an "old" template parameter list is provided, it must be
1235/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1236/// template parameter list.
1237///
1238/// \param NewParams Template parameter list for a new template
1239/// declaration. This template parameter list will be updated with any
1240/// default arguments that are carried through from the previous
1241/// template parameter list.
1242///
1243/// \param OldParams If provided, template parameter list from a
1244/// previous declaration of the same template. Default template
1245/// arguments will be merged from the old template parameter list to
1246/// the new template parameter list.
1247///
1248/// \param TPC Describes the context in which we are checking the given
1249/// template parameter list.
1250///
1251/// \returns true if an error occurred, false otherwise.
1252bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1253 TemplateParameterList *OldParams,
1254 TemplateParamListContext TPC) {
1255 bool Invalid = false;
1256
1257 // C++ [temp.param]p10:
1258 // The set of default template-arguments available for use with a
1259 // template declaration or definition is obtained by merging the
1260 // default arguments from the definition (if in scope) and all
1261 // declarations in scope in the same way default function
1262 // arguments are (8.3.6).
1263 bool SawDefaultArgument = false;
1264 SourceLocation PreviousDefaultArgLoc;
1265
1266 // Dummy initialization to avoid warnings.
1267 TemplateParameterList::iterator OldParam = NewParams->end();
1268 if (OldParams)
1269 OldParam = OldParams->begin();
1270
1271 bool RemoveDefaultArguments = false;
1272 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1273 NewParamEnd = NewParams->end();
1274 NewParam != NewParamEnd; ++NewParam) {
1275 // Variables used to diagnose redundant default arguments
1276 bool RedundantDefaultArg = false;
1277 SourceLocation OldDefaultLoc;
1278 SourceLocation NewDefaultLoc;
1279
1280 // Variable used to diagnose missing default arguments
1281 bool MissingDefaultArg = false;
1282
1283 // Variable used to diagnose non-final parameter packs
1284 bool SawParameterPack = false;
1285
1286 if (TemplateTypeParmDecl *NewTypeParm
1287 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1288 // Check the presence of a default argument here.
1289 if (NewTypeParm->hasDefaultArgument() &&
1290 DiagnoseDefaultTemplateArgument(*this, TPC,
1291 NewTypeParm->getLocation(),
1292 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1293 .getSourceRange()))
1294 NewTypeParm->removeDefaultArgument();
1295
1296 // Merge default arguments for template type parameters.
1297 TemplateTypeParmDecl *OldTypeParm
1298 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1299
1300 if (NewTypeParm->isParameterPack()) {
1301 assert(!NewTypeParm->hasDefaultArgument() &&
1302 "Parameter packs can't have a default argument!");
1303 SawParameterPack = true;
1304 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1305 NewTypeParm->hasDefaultArgument()) {
1306 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1307 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1308 SawDefaultArgument = true;
1309 RedundantDefaultArg = true;
1310 PreviousDefaultArgLoc = NewDefaultLoc;
1311 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1312 // Merge the default argument from the old declaration to the
1313 // new declaration.
1314 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1315 true);
1316 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1317 } else if (NewTypeParm->hasDefaultArgument()) {
1318 SawDefaultArgument = true;
1319 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1320 } else if (SawDefaultArgument)
1321 MissingDefaultArg = true;
1322 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1323 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1324 // Check for unexpanded parameter packs.
1325 if (!NewNonTypeParm->isParameterPack() &&
1326 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1327 NewNonTypeParm->getTypeSourceInfo(),
1328 UPPC_NonTypeTemplateParameterType)) {
1329 Invalid = true;
1330 continue;
1331 }
1332
1333 // Check the presence of a default argument here.
1334 if (NewNonTypeParm->hasDefaultArgument() &&
1335 DiagnoseDefaultTemplateArgument(*this, TPC,
1336 NewNonTypeParm->getLocation(),
1337 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1338 NewNonTypeParm->removeDefaultArgument();
1339 }
1340
1341 // Merge default arguments for non-type template parameters
1342 NonTypeTemplateParmDecl *OldNonTypeParm
1343 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1344 if (NewNonTypeParm->isParameterPack()) {
1345 assert(!NewNonTypeParm->hasDefaultArgument() &&
1346 "Parameter packs can't have a default argument!");
1347 if (!NewNonTypeParm->isPackExpansion())
1348 SawParameterPack = true;
1349 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1350 NewNonTypeParm->hasDefaultArgument()) {
1351 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1352 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1353 SawDefaultArgument = true;
1354 RedundantDefaultArg = true;
1355 PreviousDefaultArgLoc = NewDefaultLoc;
1356 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1357 // Merge the default argument from the old declaration to the
1358 // new declaration.
1359 // FIXME: We need to create a new kind of "default argument"
1360 // expression that points to a previous non-type template
1361 // parameter.
1362 NewNonTypeParm->setDefaultArgument(
1363 OldNonTypeParm->getDefaultArgument(),
1364 /*Inherited=*/ true);
1365 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1366 } else if (NewNonTypeParm->hasDefaultArgument()) {
1367 SawDefaultArgument = true;
1368 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1369 } else if (SawDefaultArgument)
1370 MissingDefaultArg = true;
1371 } else {
1372 TemplateTemplateParmDecl *NewTemplateParm
1373 = cast<TemplateTemplateParmDecl>(*NewParam);
1374
1375 // Check for unexpanded parameter packs, recursively.
1376 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1377 Invalid = true;
1378 continue;
1379 }
1380
1381 // Check the presence of a default argument here.
1382 if (NewTemplateParm->hasDefaultArgument() &&
1383 DiagnoseDefaultTemplateArgument(*this, TPC,
1384 NewTemplateParm->getLocation(),
1385 NewTemplateParm->getDefaultArgument().getSourceRange()))
1386 NewTemplateParm->removeDefaultArgument();
1387
1388 // Merge default arguments for template template parameters
1389 TemplateTemplateParmDecl *OldTemplateParm
1390 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1391 if (NewTemplateParm->isParameterPack()) {
1392 assert(!NewTemplateParm->hasDefaultArgument() &&
1393 "Parameter packs can't have a default argument!");
1394 if (!NewTemplateParm->isPackExpansion())
1395 SawParameterPack = true;
1396 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1397 NewTemplateParm->hasDefaultArgument()) {
1398 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1399 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1400 SawDefaultArgument = true;
1401 RedundantDefaultArg = true;
1402 PreviousDefaultArgLoc = NewDefaultLoc;
1403 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1404 // Merge the default argument from the old declaration to the
1405 // new declaration.
1406 // FIXME: We need to create a new kind of "default argument" expression
1407 // that points to a previous template template parameter.
1408 NewTemplateParm->setDefaultArgument(
1409 OldTemplateParm->getDefaultArgument(),
1410 /*Inherited=*/ true);
1411 PreviousDefaultArgLoc
1412 = OldTemplateParm->getDefaultArgument().getLocation();
1413 } else if (NewTemplateParm->hasDefaultArgument()) {
1414 SawDefaultArgument = true;
1415 PreviousDefaultArgLoc
1416 = NewTemplateParm->getDefaultArgument().getLocation();
1417 } else if (SawDefaultArgument)
1418 MissingDefaultArg = true;
1419 }
1420
1421 // C++11 [temp.param]p11:
1422 // If a template parameter of a primary class template or alias template
1423 // is a template parameter pack, it shall be the last template parameter.
1424 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1425 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1426 TPC == TPC_TypeAliasTemplate)) {
1427 Diag((*NewParam)->getLocation(),
1428 diag::err_template_param_pack_must_be_last_template_parameter);
1429 Invalid = true;
1430 }
1431
1432 if (RedundantDefaultArg) {
1433 // C++ [temp.param]p12:
1434 // A template-parameter shall not be given default arguments
1435 // by two different declarations in the same scope.
1436 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1437 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1438 Invalid = true;
1439 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1440 // C++ [temp.param]p11:
1441 // If a template-parameter of a class template has a default
1442 // template-argument, each subsequent template-parameter shall either
1443 // have a default template-argument supplied or be a template parameter
1444 // pack.
1445 Diag((*NewParam)->getLocation(),
1446 diag::err_template_param_default_arg_missing);
1447 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1448 Invalid = true;
1449 RemoveDefaultArguments = true;
1450 }
1451
1452 // If we have an old template parameter list that we're merging
1453 // in, move on to the next parameter.
1454 if (OldParams)
1455 ++OldParam;
1456 }
1457
1458 // We were missing some default arguments at the end of the list, so remove
1459 // all of the default arguments.
1460 if (RemoveDefaultArguments) {
1461 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1462 NewParamEnd = NewParams->end();
1463 NewParam != NewParamEnd; ++NewParam) {
1464 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1465 TTP->removeDefaultArgument();
1466 else if (NonTypeTemplateParmDecl *NTTP
1467 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1468 NTTP->removeDefaultArgument();
1469 else
1470 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1471 }
1472 }
1473
1474 return Invalid;
1475}
1476
1477namespace {
1478
1479/// A class which looks for a use of a certain level of template
1480/// parameter.
1481struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1482 typedef RecursiveASTVisitor<DependencyChecker> super;
1483
1484 unsigned Depth;
1485 bool Match;
1486 SourceLocation MatchLoc;
1487
1488 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1489
1490 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1491 NamedDecl *ND = Params->getParam(0);
1492 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1493 Depth = PD->getDepth();
1494 } else if (NonTypeTemplateParmDecl *PD =
1495 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1496 Depth = PD->getDepth();
1497 } else {
1498 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1499 }
1500 }
1501
1502 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1503 if (ParmDepth >= Depth) {
1504 Match = true;
1505 MatchLoc = Loc;
1506 return true;
1507 }
1508 return false;
1509 }
1510
1511 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1512 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1513 }
1514
1515 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1516 return !Matches(T->getDepth());
1517 }
1518
1519 bool TraverseTemplateName(TemplateName N) {
1520 if (TemplateTemplateParmDecl *PD =
1521 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1522 if (Matches(PD->getDepth()))
1523 return false;
1524 return super::TraverseTemplateName(N);
1525 }
1526
1527 bool VisitDeclRefExpr(DeclRefExpr *E) {
1528 if (NonTypeTemplateParmDecl *PD =
1529 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1530 if (Matches(PD->getDepth(), E->getExprLoc()))
1531 return false;
1532 return super::VisitDeclRefExpr(E);
1533 }
1534
1535 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1536 return TraverseType(T->getReplacementType());
1537 }
1538
1539 bool
1540 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1541 return TraverseTemplateArgument(T->getArgumentPack());
1542 }
1543
1544 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1545 return TraverseType(T->getInjectedSpecializationType());
1546 }
1547};
1548}
1549
1550/// Determines whether a given type depends on the given parameter
1551/// list.
1552static bool
1553DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1554 DependencyChecker Checker(Params);
1555 Checker.TraverseType(T);
1556 return Checker.Match;
1557}
1558
1559// Find the source range corresponding to the named type in the given
1560// nested-name-specifier, if any.
1561static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1562 QualType T,
1563 const CXXScopeSpec &SS) {
1564 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1565 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1566 if (const Type *CurType = NNS->getAsType()) {
1567 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1568 return NNSLoc.getTypeLoc().getSourceRange();
1569 } else
1570 break;
1571
1572 NNSLoc = NNSLoc.getPrefix();
1573 }
1574
1575 return SourceRange();
1576}
1577
1578/// \brief Match the given template parameter lists to the given scope
1579/// specifier, returning the template parameter list that applies to the
1580/// name.
1581///
1582/// \param DeclStartLoc the start of the declaration that has a scope
1583/// specifier or a template parameter list.
1584///
1585/// \param DeclLoc The location of the declaration itself.
1586///
1587/// \param SS the scope specifier that will be matched to the given template
1588/// parameter lists. This scope specifier precedes a qualified name that is
1589/// being declared.
1590///
1591/// \param TemplateId The template-id following the scope specifier, if there
1592/// is one. Used to check for a missing 'template<>'.
1593///
1594/// \param ParamLists the template parameter lists, from the outermost to the
1595/// innermost template parameter lists.
1596///
1597/// \param IsFriend Whether to apply the slightly different rules for
1598/// matching template parameters to scope specifiers in friend
1599/// declarations.
1600///
1601/// \param IsExplicitSpecialization will be set true if the entity being
1602/// declared is an explicit specialization, false otherwise.
1603///
1604/// \returns the template parameter list, if any, that corresponds to the
1605/// name that is preceded by the scope specifier @p SS. This template
1606/// parameter list may have template parameters (if we're declaring a
1607/// template) or may have no template parameters (if we're declaring a
1608/// template specialization), or may be NULL (if what we're declaring isn't
1609/// itself a template).
1610TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1611 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1612 TemplateIdAnnotation *TemplateId,
1613 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1614 bool &IsExplicitSpecialization, bool &Invalid) {
1615 IsExplicitSpecialization = false;
1616 Invalid = false;
1617
1618 // The sequence of nested types to which we will match up the template
1619 // parameter lists. We first build this list by starting with the type named
1620 // by the nested-name-specifier and walking out until we run out of types.
1621 SmallVector<QualType, 4> NestedTypes;
1622 QualType T;
1623 if (SS.getScopeRep()) {
1624 if (CXXRecordDecl *Record
1625 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1626 T = Context.getTypeDeclType(Record);
1627 else
1628 T = QualType(SS.getScopeRep()->getAsType(), 0);
1629 }
1630
1631 // If we found an explicit specialization that prevents us from needing
1632 // 'template<>' headers, this will be set to the location of that
1633 // explicit specialization.
1634 SourceLocation ExplicitSpecLoc;
1635
1636 while (!T.isNull()) {
1637 NestedTypes.push_back(T);
1638
1639 // Retrieve the parent of a record type.
1640 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1641 // If this type is an explicit specialization, we're done.
1642 if (ClassTemplateSpecializationDecl *Spec
1643 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1644 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1645 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1646 ExplicitSpecLoc = Spec->getLocation();
1647 break;
1648 }
1649 } else if (Record->getTemplateSpecializationKind()
1650 == TSK_ExplicitSpecialization) {
1651 ExplicitSpecLoc = Record->getLocation();
1652 break;
1653 }
1654
1655 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1656 T = Context.getTypeDeclType(Parent);
1657 else
1658 T = QualType();
1659 continue;
1660 }
1661
1662 if (const TemplateSpecializationType *TST
1663 = T->getAs<TemplateSpecializationType>()) {
1664 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1665 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1666 T = Context.getTypeDeclType(Parent);
1667 else
1668 T = QualType();
1669 continue;
1670 }
1671 }
1672
1673 // Look one step prior in a dependent template specialization type.
1674 if (const DependentTemplateSpecializationType *DependentTST
1675 = T->getAs<DependentTemplateSpecializationType>()) {
1676 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1677 T = QualType(NNS->getAsType(), 0);
1678 else
1679 T = QualType();
1680 continue;
1681 }
1682
1683 // Look one step prior in a dependent name type.
1684 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1685 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1686 T = QualType(NNS->getAsType(), 0);
1687 else
1688 T = QualType();
1689 continue;
1690 }
1691
1692 // Retrieve the parent of an enumeration type.
1693 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1694 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1695 // check here.
1696 EnumDecl *Enum = EnumT->getDecl();
1697
1698 // Get to the parent type.
1699 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1700 T = Context.getTypeDeclType(Parent);
1701 else
1702 T = QualType();
1703 continue;
1704 }
1705
1706 T = QualType();
1707 }
1708 // Reverse the nested types list, since we want to traverse from the outermost
1709 // to the innermost while checking template-parameter-lists.
1710 std::reverse(NestedTypes.begin(), NestedTypes.end());
1711
1712 // C++0x [temp.expl.spec]p17:
1713 // A member or a member template may be nested within many
1714 // enclosing class templates. In an explicit specialization for
1715 // such a member, the member declaration shall be preceded by a
1716 // template<> for each enclosing class template that is
1717 // explicitly specialized.
1718 bool SawNonEmptyTemplateParameterList = false;
1719
1720 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1721 if (SawNonEmptyTemplateParameterList) {
1722 Diag(DeclLoc, diag::err_specialize_member_of_template)
1723 << !Recovery << Range;
1724 Invalid = true;
1725 IsExplicitSpecialization = false;
1726 return true;
1727 }
1728
1729 return false;
1730 };
1731
1732 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1733 // Check that we can have an explicit specialization here.
1734 if (CheckExplicitSpecialization(Range, true))
1735 return true;
1736
1737 // We don't have a template header, but we should.
1738 SourceLocation ExpectedTemplateLoc;
1739 if (!ParamLists.empty())
1740 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1741 else
1742 ExpectedTemplateLoc = DeclStartLoc;
1743
1744 Diag(DeclLoc, diag::err_template_spec_needs_header)
1745 << Range
1746 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1747 return false;
1748 };
1749
1750 unsigned ParamIdx = 0;
1751 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1752 ++TypeIdx) {
1753 T = NestedTypes[TypeIdx];
1754
1755 // Whether we expect a 'template<>' header.
1756 bool NeedEmptyTemplateHeader = false;
1757
1758 // Whether we expect a template header with parameters.
1759 bool NeedNonemptyTemplateHeader = false;
1760
1761 // For a dependent type, the set of template parameters that we
1762 // expect to see.
1763 TemplateParameterList *ExpectedTemplateParams = nullptr;
1764
1765 // C++0x [temp.expl.spec]p15:
1766 // A member or a member template may be nested within many enclosing
1767 // class templates. In an explicit specialization for such a member, the
1768 // member declaration shall be preceded by a template<> for each
1769 // enclosing class template that is explicitly specialized.
1770 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1771 if (ClassTemplatePartialSpecializationDecl *Partial
1772 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1773 ExpectedTemplateParams = Partial->getTemplateParameters();
1774 NeedNonemptyTemplateHeader = true;
1775 } else if (Record->isDependentType()) {
1776 if (Record->getDescribedClassTemplate()) {
1777 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1778 ->getTemplateParameters();
1779 NeedNonemptyTemplateHeader = true;
1780 }
1781 } else if (ClassTemplateSpecializationDecl *Spec
1782 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1783 // C++0x [temp.expl.spec]p4:
1784 // Members of an explicitly specialized class template are defined
1785 // in the same manner as members of normal classes, and not using
1786 // the template<> syntax.
1787 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1788 NeedEmptyTemplateHeader = true;
1789 else
1790 continue;
1791 } else if (Record->getTemplateSpecializationKind()) {
1792 if (Record->getTemplateSpecializationKind()
1793 != TSK_ExplicitSpecialization &&
1794 TypeIdx == NumTypes - 1)
1795 IsExplicitSpecialization = true;
1796
1797 continue;
1798 }
1799 } else if (const TemplateSpecializationType *TST
1800 = T->getAs<TemplateSpecializationType>()) {
1801 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1802 ExpectedTemplateParams = Template->getTemplateParameters();
1803 NeedNonemptyTemplateHeader = true;
1804 }
1805 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1806 // FIXME: We actually could/should check the template arguments here
1807 // against the corresponding template parameter list.
1808 NeedNonemptyTemplateHeader = false;
1809 }
1810
1811 // C++ [temp.expl.spec]p16:
1812 // In an explicit specialization declaration for a member of a class
1813 // template or a member template that ap- pears in namespace scope, the
1814 // member template and some of its enclosing class templates may remain
1815 // unspecialized, except that the declaration shall not explicitly
1816 // specialize a class member template if its en- closing class templates
1817 // are not explicitly specialized as well.
1818 if (ParamIdx < ParamLists.size()) {
1819 if (ParamLists[ParamIdx]->size() == 0) {
1820 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1821 false))
1822 return nullptr;
1823 } else
1824 SawNonEmptyTemplateParameterList = true;
1825 }
1826
1827 if (NeedEmptyTemplateHeader) {
1828 // If we're on the last of the types, and we need a 'template<>' header
1829 // here, then it's an explicit specialization.
1830 if (TypeIdx == NumTypes - 1)
1831 IsExplicitSpecialization = true;
1832
1833 if (ParamIdx < ParamLists.size()) {
1834 if (ParamLists[ParamIdx]->size() > 0) {
1835 // The header has template parameters when it shouldn't. Complain.
1836 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1837 diag::err_template_param_list_matches_nontemplate)
1838 << T
1839 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1840 ParamLists[ParamIdx]->getRAngleLoc())
1841 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1842 Invalid = true;
1843 return nullptr;
1844 }
1845
1846 // Consume this template header.
1847 ++ParamIdx;
1848 continue;
1849 }
1850
1851 if (!IsFriend)
1852 if (DiagnoseMissingExplicitSpecialization(
1853 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1854 return nullptr;
1855
1856 continue;
1857 }
1858
1859 if (NeedNonemptyTemplateHeader) {
1860 // In friend declarations we can have template-ids which don't
1861 // depend on the corresponding template parameter lists. But
1862 // assume that empty parameter lists are supposed to match this
1863 // template-id.
1864 if (IsFriend && T->isDependentType()) {
1865 if (ParamIdx < ParamLists.size() &&
1866 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1867 ExpectedTemplateParams = nullptr;
1868 else
1869 continue;
1870 }
1871
1872 if (ParamIdx < ParamLists.size()) {
1873 // Check the template parameter list, if we can.
1874 if (ExpectedTemplateParams &&
1875 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1876 ExpectedTemplateParams,
1877 true, TPL_TemplateMatch))
1878 Invalid = true;
1879
1880 if (!Invalid &&
1881 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1882 TPC_ClassTemplateMember))
1883 Invalid = true;
1884
1885 ++ParamIdx;
1886 continue;
1887 }
1888
1889 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1890 << T
1891 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1892 Invalid = true;
1893 continue;
1894 }
1895 }
1896
1897 // If there were at least as many template-ids as there were template
1898 // parameter lists, then there are no template parameter lists remaining for
1899 // the declaration itself.
1900 if (ParamIdx >= ParamLists.size()) {
1901 if (TemplateId && !IsFriend) {
1902 // We don't have a template header for the declaration itself, but we
1903 // should.
1904 IsExplicitSpecialization = true;
1905 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1906 TemplateId->RAngleLoc));
1907
1908 // Fabricate an empty template parameter list for the invented header.
1909 return TemplateParameterList::Create(Context, SourceLocation(),
1910 SourceLocation(), nullptr, 0,
1911 SourceLocation());
1912 }
1913
1914 return nullptr;
1915 }
1916
1917 // If there were too many template parameter lists, complain about that now.
1918 if (ParamIdx < ParamLists.size() - 1) {
1919 bool HasAnyExplicitSpecHeader = false;
1920 bool AllExplicitSpecHeaders = true;
1921 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1922 if (ParamLists[I]->size() == 0)
1923 HasAnyExplicitSpecHeader = true;
1924 else
1925 AllExplicitSpecHeaders = false;
1926 }
1927
1928 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1929 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1930 : diag::err_template_spec_extra_headers)
1931 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1932 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1933
1934 // If there was a specialization somewhere, such that 'template<>' is
1935 // not required, and there were any 'template<>' headers, note where the
1936 // specialization occurred.
1937 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1938 Diag(ExplicitSpecLoc,
1939 diag::note_explicit_template_spec_does_not_need_header)
1940 << NestedTypes.back();
1941
1942 // We have a template parameter list with no corresponding scope, which
1943 // means that the resulting template declaration can't be instantiated
1944 // properly (we'll end up with dependent nodes when we shouldn't).
1945 if (!AllExplicitSpecHeaders)
1946 Invalid = true;
1947 }
1948
1949 // C++ [temp.expl.spec]p16:
1950 // In an explicit specialization declaration for a member of a class
1951 // template or a member template that ap- pears in namespace scope, the
1952 // member template and some of its enclosing class templates may remain
1953 // unspecialized, except that the declaration shall not explicitly
1954 // specialize a class member template if its en- closing class templates
1955 // are not explicitly specialized as well.
1956 if (ParamLists.back()->size() == 0 &&
1957 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1958 false))
1959 return nullptr;
1960
1961 // Return the last template parameter list, which corresponds to the
1962 // entity being declared.
1963 return ParamLists.back();
1964}
1965
1966void Sema::NoteAllFoundTemplates(TemplateName Name) {
1967 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1968 Diag(Template->getLocation(), diag::note_template_declared_here)
1969 << (isa<FunctionTemplateDecl>(Template)
1970 ? 0
1971 : isa<ClassTemplateDecl>(Template)
1972 ? 1
1973 : isa<VarTemplateDecl>(Template)
1974 ? 2
1975 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1976 << Template->getDeclName();
1977 return;
1978 }
1979
1980 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1981 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1982 IEnd = OST->end();
1983 I != IEnd; ++I)
1984 Diag((*I)->getLocation(), diag::note_template_declared_here)
1985 << 0 << (*I)->getDeclName();
1986
1987 return;
1988 }
1989}
1990
1991QualType Sema::CheckTemplateIdType(TemplateName Name,
1992 SourceLocation TemplateLoc,
1993 TemplateArgumentListInfo &TemplateArgs) {
1994 DependentTemplateName *DTN
1995 = Name.getUnderlying().getAsDependentTemplateName();
1996 if (DTN && DTN->isIdentifier())
1997 // When building a template-id where the template-name is dependent,
1998 // assume the template is a type template. Either our assumption is
1999 // correct, or the code is ill-formed and will be diagnosed when the
2000 // dependent name is substituted.
2001 return Context.getDependentTemplateSpecializationType(ETK_None,
2002 DTN->getQualifier(),
2003 DTN->getIdentifier(),
2004 TemplateArgs);
2005
2006 TemplateDecl *Template = Name.getAsTemplateDecl();
2007 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2008 isa<VarTemplateDecl>(Template)) {
2009 // We might have a substituted template template parameter pack. If so,
2010 // build a template specialization type for it.
2011 if (Name.getAsSubstTemplateTemplateParmPack())
2012 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2013
2014 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2015 << Name;
2016 NoteAllFoundTemplates(Name);
2017 return QualType();
2018 }
2019
2020 // Check that the template argument list is well-formed for this
2021 // template.
2022 SmallVector<TemplateArgument, 4> Converted;
2023 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2024 false, Converted))
2025 return QualType();
2026
2027 QualType CanonType;
2028
2029 bool InstantiationDependent = false;
2030 if (TypeAliasTemplateDecl *AliasTemplate =
2031 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2032 // Find the canonical type for this type alias template specialization.
2033 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2034 if (Pattern->isInvalidDecl())
2035 return QualType();
2036
2037 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2038 Converted.data(), Converted.size());
2039
2040 // Only substitute for the innermost template argument list.
2041 MultiLevelTemplateArgumentList TemplateArgLists;
2042 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2043 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2044 for (unsigned I = 0; I < Depth; ++I)
2045 TemplateArgLists.addOuterTemplateArguments(None);
2046
2047 LocalInstantiationScope Scope(*this);
2048 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2049 if (Inst.isInvalid())
2050 return QualType();
2051
2052 CanonType = SubstType(Pattern->getUnderlyingType(),
2053 TemplateArgLists, AliasTemplate->getLocation(),
2054 AliasTemplate->getDeclName());
2055 if (CanonType.isNull())
2056 return QualType();
2057 } else if (Name.isDependent() ||
2058 TemplateSpecializationType::anyDependentTemplateArguments(
2059 TemplateArgs, InstantiationDependent)) {
2060 // This class template specialization is a dependent
2061 // type. Therefore, its canonical type is another class template
2062 // specialization type that contains all of the converted
2063 // arguments in canonical form. This ensures that, e.g., A<T> and
2064 // A<T, T> have identical types when A is declared as:
2065 //
2066 // template<typename T, typename U = T> struct A;
2067 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2068 CanonType = Context.getTemplateSpecializationType(CanonName,
2069 Converted.data(),
2070 Converted.size());
2071
2072 // FIXME: CanonType is not actually the canonical type, and unfortunately
2073 // it is a TemplateSpecializationType that we will never use again.
2074 // In the future, we need to teach getTemplateSpecializationType to only
2075 // build the canonical type and return that to us.
2076 CanonType = Context.getCanonicalType(CanonType);
2077
2078 // This might work out to be a current instantiation, in which
2079 // case the canonical type needs to be the InjectedClassNameType.
2080 //
2081 // TODO: in theory this could be a simple hashtable lookup; most
2082 // changes to CurContext don't change the set of current
2083 // instantiations.
2084 if (isa<ClassTemplateDecl>(Template)) {
2085 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2086 // If we get out to a namespace, we're done.
2087 if (Ctx->isFileContext()) break;
2088
2089 // If this isn't a record, keep looking.
2090 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2091 if (!Record) continue;
2092
2093 // Look for one of the two cases with InjectedClassNameTypes
2094 // and check whether it's the same template.
2095 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2096 !Record->getDescribedClassTemplate())
2097 continue;
2098
2099 // Fetch the injected class name type and check whether its
2100 // injected type is equal to the type we just built.
2101 QualType ICNT = Context.getTypeDeclType(Record);
2102 QualType Injected = cast<InjectedClassNameType>(ICNT)
2103 ->getInjectedSpecializationType();
2104
2105 if (CanonType != Injected->getCanonicalTypeInternal())
2106 continue;
2107
2108 // If so, the canonical type of this TST is the injected
2109 // class name type of the record we just found.
2110 assert(ICNT.isCanonical());
2111 CanonType = ICNT;
2112 break;
2113 }
2114 }
2115 } else if (ClassTemplateDecl *ClassTemplate
2116 = dyn_cast<ClassTemplateDecl>(Template)) {
2117 // Find the class template specialization declaration that
2118 // corresponds to these arguments.
2119 void *InsertPos = nullptr;
2120 ClassTemplateSpecializationDecl *Decl
2121 = ClassTemplate->findSpecialization(Converted, InsertPos);
2122 if (!Decl) {
2123 // This is the first time we have referenced this class template
2124 // specialization. Create the canonical declaration and add it to
2125 // the set of specializations.
2126 Decl = ClassTemplateSpecializationDecl::Create(Context,
2127 ClassTemplate->getTemplatedDecl()->getTagKind(),
2128 ClassTemplate->getDeclContext(),
2129 ClassTemplate->getTemplatedDecl()->getLocStart(),
2130 ClassTemplate->getLocation(),
2131 ClassTemplate,
2132 Converted.data(),
2133 Converted.size(), nullptr);
2134 ClassTemplate->AddSpecialization(Decl, InsertPos);
2135 if (ClassTemplate->isOutOfLine())
2136 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2137 }
2138
2139 // Diagnose uses of this specialization.
2140 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2141
2142 CanonType = Context.getTypeDeclType(Decl);
2143 assert(isa<RecordType>(CanonType) &&
2144 "type of non-dependent specialization is not a RecordType");
2145 }
2146
2147 // Build the fully-sugared type for this class template
2148 // specialization, which refers back to the class template
2149 // specialization we created or found.
2150 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2151}
2152
2153TypeResult
2154Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2155 TemplateTy TemplateD, SourceLocation TemplateLoc,
2156 SourceLocation LAngleLoc,
2157 ASTTemplateArgsPtr TemplateArgsIn,
2158 SourceLocation RAngleLoc,
2159 bool IsCtorOrDtorName) {
2160 if (SS.isInvalid())
2161 return true;
2162
2163 TemplateName Template = TemplateD.get();
2164
2165 // Translate the parser's template argument list in our AST format.
2166 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2167 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2168
2169 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2170 QualType T
2171 = Context.getDependentTemplateSpecializationType(ETK_None,
2172 DTN->getQualifier(),
2173 DTN->getIdentifier(),
2174 TemplateArgs);
2175 // Build type-source information.
2176 TypeLocBuilder TLB;
2177 DependentTemplateSpecializationTypeLoc SpecTL
2178 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2179 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2180 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2181 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2182 SpecTL.setTemplateNameLoc(TemplateLoc);
2183 SpecTL.setLAngleLoc(LAngleLoc);
2184 SpecTL.setRAngleLoc(RAngleLoc);
2185 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2186 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2187 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2188 }
2189
2190 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2191
2192 if (Result.isNull())
2193 return true;
2194
2195 // Build type-source information.
2196 TypeLocBuilder TLB;
2197 TemplateSpecializationTypeLoc SpecTL
2198 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2199 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2200 SpecTL.setTemplateNameLoc(TemplateLoc);
2201 SpecTL.setLAngleLoc(LAngleLoc);
2202 SpecTL.setRAngleLoc(RAngleLoc);
2203 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2204 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2205
2206 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2207 // constructor or destructor name (in such a case, the scope specifier
2208 // will be attached to the enclosing Decl or Expr node).
2209 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2210 // Create an elaborated-type-specifier containing the nested-name-specifier.
2211 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2212 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2213 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2214 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2215 }
2216
2217 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2218}
2219
2220TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2221 TypeSpecifierType TagSpec,
2222 SourceLocation TagLoc,
2223 CXXScopeSpec &SS,
2224 SourceLocation TemplateKWLoc,
2225 TemplateTy TemplateD,
2226 SourceLocation TemplateLoc,
2227 SourceLocation LAngleLoc,
2228 ASTTemplateArgsPtr TemplateArgsIn,
2229 SourceLocation RAngleLoc) {
2230 TemplateName Template = TemplateD.get();
2231
2232 // Translate the parser's template argument list in our AST format.
2233 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2234 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2235
2236 // Determine the tag kind
2237 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2238 ElaboratedTypeKeyword Keyword
2239 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2240
2241 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2242 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2243 DTN->getQualifier(),
2244 DTN->getIdentifier(),
2245 TemplateArgs);
2246
2247 // Build type-source information.
2248 TypeLocBuilder TLB;
2249 DependentTemplateSpecializationTypeLoc SpecTL
2250 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2251 SpecTL.setElaboratedKeywordLoc(TagLoc);
2252 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2253 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2254 SpecTL.setTemplateNameLoc(TemplateLoc);
2255 SpecTL.setLAngleLoc(LAngleLoc);
2256 SpecTL.setRAngleLoc(RAngleLoc);
2257 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2258 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2259 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2260 }
2261
2262 if (TypeAliasTemplateDecl *TAT =
2263 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2264 // C++0x [dcl.type.elab]p2:
2265 // If the identifier resolves to a typedef-name or the simple-template-id
2266 // resolves to an alias template specialization, the
2267 // elaborated-type-specifier is ill-formed.
2268 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2269 Diag(TAT->getLocation(), diag::note_declared_at);
2270 }
2271
2272 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2273 if (Result.isNull())
2274 return TypeResult(true);
2275
2276 // Check the tag kind
2277 if (const RecordType *RT = Result->getAs<RecordType>()) {
2278 RecordDecl *D = RT->getDecl();
2279
2280 IdentifierInfo *Id = D->getIdentifier();
2281 assert(Id && "templated class must have an identifier");
2282
2283 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2284 TagLoc, *Id)) {
2285 Diag(TagLoc, diag::err_use_with_wrong_tag)
2286 << Result
2287 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2288 Diag(D->getLocation(), diag::note_previous_use);
2289 }
2290 }
2291
2292 // Provide source-location information for the template specialization.
2293 TypeLocBuilder TLB;
2294 TemplateSpecializationTypeLoc SpecTL
2295 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2296 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2297 SpecTL.setTemplateNameLoc(TemplateLoc);
2298 SpecTL.setLAngleLoc(LAngleLoc);
2299 SpecTL.setRAngleLoc(RAngleLoc);
2300 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2301 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2302
2303 // Construct an elaborated type containing the nested-name-specifier (if any)
2304 // and tag keyword.
2305 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2306 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2307 ElabTL.setElaboratedKeywordLoc(TagLoc);
2308 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2309 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2310}
2311
2312static bool CheckTemplatePartialSpecializationArgs(
2313 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2314 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2315
2316static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2317 NamedDecl *PrevDecl,
2318 SourceLocation Loc,
2319 bool IsPartialSpecialization);
2320
2321static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2322
2323static bool isTemplateArgumentTemplateParameter(
2324 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2325 switch (Arg.getKind()) {
2326 case TemplateArgument::Null:
2327 case TemplateArgument::NullPtr:
2328 case TemplateArgument::Integral:
2329 case TemplateArgument::Declaration:
2330 case TemplateArgument::Pack:
2331 case TemplateArgument::TemplateExpansion:
2332 return false;
2333
2334 case TemplateArgument::Type: {
2335 QualType Type = Arg.getAsType();
2336 const TemplateTypeParmType *TPT =
2337 Arg.getAsType()->getAs<TemplateTypeParmType>();
2338 return TPT && !Type.hasQualifiers() &&
2339 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2340 }
2341
2342 case TemplateArgument::Expression: {
2343 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2344 if (!DRE || !DRE->getDecl())
2345 return false;
2346 const NonTypeTemplateParmDecl *NTTP =
2347 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2348 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2349 }
2350
2351 case TemplateArgument::Template:
2352 const TemplateTemplateParmDecl *TTP =
2353 dyn_cast_or_null<TemplateTemplateParmDecl>(
2354 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2355 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2356 }
2357 llvm_unreachable("unexpected kind of template argument");
2358}
2359
2360static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2361 ArrayRef<TemplateArgument> Args) {
2362 if (Params->size() != Args.size())
2363 return false;
2364
2365 unsigned Depth = Params->getDepth();
2366
2367 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2368 TemplateArgument Arg = Args[I];
2369
2370 // If the parameter is a pack expansion, the argument must be a pack
2371 // whose only element is a pack expansion.
2372 if (Params->getParam(I)->isParameterPack()) {
2373 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2374 !Arg.pack_begin()->isPackExpansion())
2375 return false;
2376 Arg = Arg.pack_begin()->getPackExpansionPattern();
2377 }
2378
2379 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2380 return false;
2381 }
2382
2383 return true;
2384}
2385
2386/// Convert the parser's template argument list representation into our form.
2387static TemplateArgumentListInfo
2388makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2389 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2390 TemplateId.RAngleLoc);
2391 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2392 TemplateId.NumArgs);
2393 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2394 return TemplateArgs;
2395}
2396
2397DeclResult Sema::ActOnVarTemplateSpecialization(
2398 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2399 TemplateParameterList *TemplateParams, StorageClass SC,
2400 bool IsPartialSpecialization) {
2401 // D must be variable template id.
2402 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2403 "Variable template specialization is declared with a template it.");
2404
2405 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2406 TemplateArgumentListInfo TemplateArgs =
2407 makeTemplateArgumentListInfo(*this, *TemplateId);
2408 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2409 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2410 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2411
2412 TemplateName Name = TemplateId->Template.get();
2413
2414 // The template-id must name a variable template.
2415 VarTemplateDecl *VarTemplate =
2416 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2417 if (!VarTemplate) {
2418 NamedDecl *FnTemplate;
2419 if (auto *OTS = Name.getAsOverloadedTemplate())
2420 FnTemplate = *OTS->begin();
2421 else
2422 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2423 if (FnTemplate)
2424 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2425 << FnTemplate->getDeclName();
2426 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2427 << IsPartialSpecialization;
2428 }
2429
2430 // Check for unexpanded parameter packs in any of the template arguments.
2431 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2432 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2433 UPPC_PartialSpecialization))
2434 return true;
2435
2436 // Check that the template argument list is well-formed for this
2437 // template.
2438 SmallVector<TemplateArgument, 4> Converted;
2439 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2440 false, Converted))
2441 return true;
2442
2443 // Check that the type of this variable template specialization
2444 // matches the expected type.
2445 TypeSourceInfo *ExpectedDI;
2446 {
2447 // Do substitution on the type of the declaration
2448 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2449 Converted.data(), Converted.size());
2450 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
2451 if (Inst.isInvalid())
2452 return true;
2453 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2454 ExpectedDI =
2455 SubstType(Templated->getTypeSourceInfo(),
2456 MultiLevelTemplateArgumentList(TemplateArgList),
2457 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2458 }
2459 if (!ExpectedDI)
2460 return true;
2461
2462 // Find the variable template (partial) specialization declaration that
2463 // corresponds to these arguments.
2464 if (IsPartialSpecialization) {
2465 if (CheckTemplatePartialSpecializationArgs(
2466 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2467 TemplateArgs.size(), Converted))
2468 return true;
2469
2470 bool InstantiationDependent;
2471 if (!Name.isDependent() &&
2472 !TemplateSpecializationType::anyDependentTemplateArguments(
2473 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2474 InstantiationDependent)) {
2475 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2476 << VarTemplate->getDeclName();
2477 IsPartialSpecialization = false;
2478 }
2479
2480 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2481 Converted)) {
2482 // C++ [temp.class.spec]p9b3:
2483 //
2484 // -- The argument list of the specialization shall not be identical
2485 // to the implicit argument list of the primary template.
2486 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2487 << /*variable template*/ 1
2488 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2489 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2490 // FIXME: Recover from this by treating the declaration as a redeclaration
2491 // of the primary template.
2492 return true;
2493 }
2494 }
2495
2496 void *InsertPos = nullptr;
2497 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2498
2499 if (IsPartialSpecialization)
2500 // FIXME: Template parameter list matters too
2501 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2502 else
2503 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2504
2505 VarTemplateSpecializationDecl *Specialization = nullptr;
2506
2507 // Check whether we can declare a variable template specialization in
2508 // the current scope.
2509 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2510 TemplateNameLoc,
2511 IsPartialSpecialization))
2512 return true;
2513
2514 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2515 // Since the only prior variable template specialization with these
2516 // arguments was referenced but not declared, reuse that
2517 // declaration node as our own, updating its source location and
2518 // the list of outer template parameters to reflect our new declaration.
2519 Specialization = PrevDecl;
2520 Specialization->setLocation(TemplateNameLoc);
2521 PrevDecl = nullptr;
2522 } else if (IsPartialSpecialization) {
2523 // Create a new class template partial specialization declaration node.
2524 VarTemplatePartialSpecializationDecl *PrevPartial =
2525 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2526 VarTemplatePartialSpecializationDecl *Partial =
2527 VarTemplatePartialSpecializationDecl::Create(
2528 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2529 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2530 Converted.data(), Converted.size(), TemplateArgs);
2531
2532 if (!PrevPartial)
2533 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2534 Specialization = Partial;
2535
2536 // If we are providing an explicit specialization of a member variable
2537 // template specialization, make a note of that.
2538 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2539 PrevPartial->setMemberSpecialization();
2540
2541 // Check that all of the template parameters of the variable template
2542 // partial specialization are deducible from the template
2543 // arguments. If not, this variable template partial specialization
2544 // will never be used.
2545 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2546 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2547 TemplateParams->getDepth(), DeducibleParams);
2548
2549 if (!DeducibleParams.all()) {
2550 unsigned NumNonDeducible =
2551 DeducibleParams.size() - DeducibleParams.count();
2552 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2553 << /*variable template*/ 1 << (NumNonDeducible > 1)
2554 << SourceRange(TemplateNameLoc, RAngleLoc);
2555 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2556 if (!DeducibleParams[I]) {
2557 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2558 if (Param->getDeclName())
2559 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2560 << Param->getDeclName();
2561 else
2562 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2563 << "(anonymous)";
2564 }
2565 }
2566 }
2567 } else {
2568 // Create a new class template specialization declaration node for
2569 // this explicit specialization or friend declaration.
2570 Specialization = VarTemplateSpecializationDecl::Create(
2571 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2572 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2573 Specialization->setTemplateArgsInfo(TemplateArgs);
2574
2575 if (!PrevDecl)
2576 VarTemplate->AddSpecialization(Specialization, InsertPos);
2577 }
2578
2579 // C++ [temp.expl.spec]p6:
2580 // If a template, a member template or the member of a class template is
2581 // explicitly specialized then that specialization shall be declared
2582 // before the first use of that specialization that would cause an implicit
2583 // instantiation to take place, in every translation unit in which such a
2584 // use occurs; no diagnostic is required.
2585 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2586 bool Okay = false;
2587 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2588 // Is there any previous explicit specialization declaration?
2589 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2590 Okay = true;
2591 break;
2592 }
2593 }
2594
2595 if (!Okay) {
2596 SourceRange Range(TemplateNameLoc, RAngleLoc);
2597 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2598 << Name << Range;
2599
2600 Diag(PrevDecl->getPointOfInstantiation(),
2601 diag::note_instantiation_required_here)
2602 << (PrevDecl->getTemplateSpecializationKind() !=
2603 TSK_ImplicitInstantiation);
2604 return true;
2605 }
2606 }
2607
2608 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2609 Specialization->setLexicalDeclContext(CurContext);
2610
2611 // Add the specialization into its lexical context, so that it can
2612 // be seen when iterating through the list of declarations in that
2613 // context. However, specializations are not found by name lookup.
2614 CurContext->addDecl(Specialization);
2615
2616 // Note that this is an explicit specialization.
2617 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2618
2619 if (PrevDecl) {
2620 // Check that this isn't a redefinition of this specialization,
2621 // merging with previous declarations.
2622 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2623 ForRedeclaration);
2624 PrevSpec.addDecl(PrevDecl);
2625 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2626 } else if (Specialization->isStaticDataMember() &&
2627 Specialization->isOutOfLine()) {
2628 Specialization->setAccess(VarTemplate->getAccess());
2629 }
2630
2631 // Link instantiations of static data members back to the template from
2632 // which they were instantiated.
2633 if (Specialization->isStaticDataMember())
2634 Specialization->setInstantiationOfStaticDataMember(
2635 VarTemplate->getTemplatedDecl(),
2636 Specialization->getSpecializationKind());
2637
2638 return Specialization;
2639}
2640
2641namespace {
2642/// \brief A partial specialization whose template arguments have matched
2643/// a given template-id.
2644struct PartialSpecMatchResult {
2645 VarTemplatePartialSpecializationDecl *Partial;
2646 TemplateArgumentList *Args;
2647};
2648}
2649
2650DeclResult
2651Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2652 SourceLocation TemplateNameLoc,
2653 const TemplateArgumentListInfo &TemplateArgs) {
2654 assert(Template && "A variable template id without template?");
2655
2656 // Check that the template argument list is well-formed for this template.
2657 SmallVector<TemplateArgument, 4> Converted;
2658 if (CheckTemplateArgumentList(
2659 Template, TemplateNameLoc,
2660 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2661 Converted))
2662 return true;
2663
2664 // Find the variable template specialization declaration that
2665 // corresponds to these arguments.
2666 void *InsertPos = nullptr;
2667 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2668 Converted, InsertPos))
2669 // If we already have a variable template specialization, return it.
2670 return Spec;
2671
2672 // This is the first time we have referenced this variable template
2673 // specialization. Create the canonical declaration and add it to
2674 // the set of specializations, based on the closest partial specialization
2675 // that it represents. That is,
2676 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2677 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2678 Converted.data(), Converted.size());
2679 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2680 bool AmbiguousPartialSpec = false;
2681 typedef PartialSpecMatchResult MatchResult;
2682 SmallVector<MatchResult, 4> Matched;
2683 SourceLocation PointOfInstantiation = TemplateNameLoc;
2684 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2685
2686 // 1. Attempt to find the closest partial specialization that this
2687 // specializes, if any.
2688 // If any of the template arguments is dependent, then this is probably
2689 // a placeholder for an incomplete declarative context; which must be
2690 // complete by instantiation time. Thus, do not search through the partial
2691 // specializations yet.
2692 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2693 // Perhaps better after unification of DeduceTemplateArguments() and
2694 // getMoreSpecializedPartialSpecialization().
2695 bool InstantiationDependent = false;
2696 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2697 TemplateArgs, InstantiationDependent)) {
2698
2699 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2700 Template->getPartialSpecializations(PartialSpecs);
2701
2702 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2703 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2704 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2705
2706 if (TemplateDeductionResult Result =
2707 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2708 // Store the failed-deduction information for use in diagnostics, later.
2709 // TODO: Actually use the failed-deduction info?
2710 FailedCandidates.addCandidate()
2711 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2712 (void)Result;
2713 } else {
2714 Matched.push_back(PartialSpecMatchResult());
2715 Matched.back().Partial = Partial;
2716 Matched.back().Args = Info.take();
2717 }
2718 }
2719
2720 if (Matched.size() >= 1) {
2721 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2722 if (Matched.size() == 1) {
2723 // -- If exactly one matching specialization is found, the
2724 // instantiation is generated from that specialization.
2725 // We don't need to do anything for this.
2726 } else {
2727 // -- If more than one matching specialization is found, the
2728 // partial order rules (14.5.4.2) are used to determine
2729 // whether one of the specializations is more specialized
2730 // than the others. If none of the specializations is more
2731 // specialized than all of the other matching
2732 // specializations, then the use of the variable template is
2733 // ambiguous and the program is ill-formed.
2734 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2735 PEnd = Matched.end();
2736 P != PEnd; ++P) {
2737 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2738 PointOfInstantiation) ==
2739 P->Partial)
2740 Best = P;
2741 }
2742
2743 // Determine if the best partial specialization is more specialized than
2744 // the others.
2745 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2746 PEnd = Matched.end();
2747 P != PEnd; ++P) {
2748 if (P != Best && getMoreSpecializedPartialSpecialization(
2749 P->Partial, Best->Partial,
2750 PointOfInstantiation) != Best->Partial) {
2751 AmbiguousPartialSpec = true;
2752 break;
2753 }
2754 }
2755 }
2756
2757 // Instantiate using the best variable template partial specialization.
2758 InstantiationPattern = Best->Partial;
2759 InstantiationArgs = Best->Args;
2760 } else {
2761 // -- If no match is found, the instantiation is generated
2762 // from the primary template.
2763 // InstantiationPattern = Template->getTemplatedDecl();
2764 }
2765 }
2766
2767 // 2. Create the canonical declaration.
2768 // Note that we do not instantiate the variable just yet, since
2769 // instantiation is handled in DoMarkVarDeclReferenced().
2770 // FIXME: LateAttrs et al.?
2771 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2772 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2773 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2774 if (!Decl)
2775 return true;
2776
2777 if (AmbiguousPartialSpec) {
2778 // Partial ordering did not produce a clear winner. Complain.
2779 Decl->setInvalidDecl();
2780 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2781 << Decl;
2782
2783 // Print the matching partial specializations.
2784 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2785 PEnd = Matched.end();
2786 P != PEnd; ++P)
2787 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2788 << getTemplateArgumentBindingsText(
2789 P->Partial->getTemplateParameters(), *P->Args);
2790 return true;
2791 }
2792
2793 if (VarTemplatePartialSpecializationDecl *D =
2794 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2795 Decl->setInstantiationOf(D, InstantiationArgs);
2796
2797 assert(Decl && "No variable template specialization?");
2798 return Decl;
2799}
2800
2801ExprResult
2802Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2803 const DeclarationNameInfo &NameInfo,
2804 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2805 const TemplateArgumentListInfo *TemplateArgs) {
2806
2807 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2808 *TemplateArgs);
2809 if (Decl.isInvalid())
2810 return ExprError();
2811
2812 VarDecl *Var = cast<VarDecl>(Decl.get());
2813 if (!Var->getTemplateSpecializationKind())
2814 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2815 NameInfo.getLoc());
2816
2817 // Build an ordinary singleton decl ref.
2818 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2819 /*FoundD=*/nullptr, TemplateArgs);
2820}
2821
2822ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2823 SourceLocation TemplateKWLoc,
2824 LookupResult &R,
2825 bool RequiresADL,
2826 const TemplateArgumentListInfo *TemplateArgs) {
2827 // FIXME: Can we do any checking at this point? I guess we could check the
2828 // template arguments that we have against the template name, if the template
2829 // name refers to a single template. That's not a terribly common case,
2830 // though.
2831 // foo<int> could identify a single function unambiguously
2832 // This approach does NOT work, since f<int>(1);
2833 // gets resolved prior to resorting to overload resolution
2834 // i.e., template<class T> void f(double);
2835 // vs template<class T, class U> void f(U);
2836
2837 // These should be filtered out by our callers.
2838 assert(!R.empty() && "empty lookup results when building templateid");
2839 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2840
2841 // In C++1y, check variable template ids.
2842 bool InstantiationDependent;
2843 if (R.getAsSingle<VarTemplateDecl>() &&
2844 !TemplateSpecializationType::anyDependentTemplateArguments(
2845 *TemplateArgs, InstantiationDependent)) {
2846 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2847 R.getAsSingle<VarTemplateDecl>(),
2848 TemplateKWLoc, TemplateArgs);
2849 }
2850
2851 // We don't want lookup warnings at this point.
2852 R.suppressDiagnostics();
2853
2854 UnresolvedLookupExpr *ULE
2855 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2856 SS.getWithLocInContext(Context),
2857 TemplateKWLoc,
2858 R.getLookupNameInfo(),
2859 RequiresADL, TemplateArgs,
2860 R.begin(), R.end());
2861
2862 return ULE;
2863}
2864
2865// We actually only call this from template instantiation.
2866ExprResult
2867Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2868 SourceLocation TemplateKWLoc,
2869 const DeclarationNameInfo &NameInfo,
2870 const TemplateArgumentListInfo *TemplateArgs) {
2871
2872 assert(TemplateArgs || TemplateKWLoc.isValid());
2873 DeclContext *DC;
2874 if (!(DC = computeDeclContext(SS, false)) ||
2875 DC->isDependentContext() ||
2876 RequireCompleteDeclContext(SS, DC))
2877 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2878
2879 bool MemberOfUnknownSpecialization;
2880 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2881 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2882 MemberOfUnknownSpecialization);
2883
2884 if (R.isAmbiguous())
2885 return ExprError();
2886
2887 if (R.empty()) {
2888 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2889 << NameInfo.getName() << SS.getRange();
2890 return ExprError();
2891 }
2892
2893 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2894 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2895 << SS.getScopeRep()
2896 << NameInfo.getName().getAsString() << SS.getRange();
2897 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2898 return ExprError();
2899 }
2900
2901 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2902}
2903
2904/// \brief Form a dependent template name.
2905///
2906/// This action forms a dependent template name given the template
2907/// name and its (presumably dependent) scope specifier. For
2908/// example, given "MetaFun::template apply", the scope specifier \p
2909/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2910/// of the "template" keyword, and "apply" is the \p Name.
2911TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2912 CXXScopeSpec &SS,
2913 SourceLocation TemplateKWLoc,
2914 UnqualifiedId &Name,
2915 ParsedType ObjectType,
2916 bool EnteringContext,
2917 TemplateTy &Result) {
2918 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2919 Diag(TemplateKWLoc,
2920 getLangOpts().CPlusPlus11 ?
2921 diag::warn_cxx98_compat_template_outside_of_template :
2922 diag::ext_template_outside_of_template)
2923 << FixItHint::CreateRemoval(TemplateKWLoc);
2924
2925 DeclContext *LookupCtx = nullptr;
2926 if (SS.isSet())
2927 LookupCtx = computeDeclContext(SS, EnteringContext);
2928 if (!LookupCtx && ObjectType)
2929 LookupCtx = computeDeclContext(ObjectType.get());
2930 if (LookupCtx) {
2931 // C++0x [temp.names]p5:
2932 // If a name prefixed by the keyword template is not the name of
2933 // a template, the program is ill-formed. [Note: the keyword
2934 // template may not be applied to non-template members of class
2935 // templates. -end note ] [ Note: as is the case with the
2936 // typename prefix, the template prefix is allowed in cases
2937 // where it is not strictly necessary; i.e., when the
2938 // nested-name-specifier or the expression on the left of the ->
2939 // or . is not dependent on a template-parameter, or the use
2940 // does not appear in the scope of a template. -end note]
2941 //
2942 // Note: C++03 was more strict here, because it banned the use of
2943 // the "template" keyword prior to a template-name that was not a
2944 // dependent name. C++ DR468 relaxed this requirement (the
2945 // "template" keyword is now permitted). We follow the C++0x
2946 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2947 bool MemberOfUnknownSpecialization;
2948 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2949 ObjectType, EnteringContext, Result,
2950 MemberOfUnknownSpecialization);
2951 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2952 isa<CXXRecordDecl>(LookupCtx) &&
2953 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2954 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2955 // This is a dependent template. Handle it below.
2956 } else if (TNK == TNK_Non_template) {
2957 Diag(Name.getLocStart(),
2958 diag::err_template_kw_refers_to_non_template)
2959 << GetNameFromUnqualifiedId(Name).getName()
2960 << Name.getSourceRange()
2961 << TemplateKWLoc;
2962 return TNK_Non_template;
2963 } else {
2964 // We found something; return it.
2965 return TNK;
2966 }
2967 }
2968
2969 NestedNameSpecifier *Qualifier = SS.getScopeRep();
2970
2971 switch (Name.getKind()) {
2972 case UnqualifiedId::IK_Identifier:
2973 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2974 Name.Identifier));
2975 return TNK_Dependent_template_name;
2976
2977 case UnqualifiedId::IK_OperatorFunctionId:
2978 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2979 Name.OperatorFunctionId.Operator));
2980 return TNK_Function_template;
2981
2982 case UnqualifiedId::IK_LiteralOperatorId:
2983 llvm_unreachable("literal operator id cannot have a dependent scope");
2984
2985 default:
2986 break;
2987 }
2988
2989 Diag(Name.getLocStart(),
2990 diag::err_template_kw_refers_to_non_template)
2991 << GetNameFromUnqualifiedId(Name).getName()
2992 << Name.getSourceRange()
2993 << TemplateKWLoc;
2994 return TNK_Non_template;
2995}
2996
2997bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
2998 TemplateArgumentLoc &AL,
2999 SmallVectorImpl<TemplateArgument> &Converted) {
3000 const TemplateArgument &Arg = AL.getArgument();
3001 QualType ArgType;
3002 TypeSourceInfo *TSI = nullptr;
3003
3004 // Check template type parameter.
3005 switch(Arg.getKind()) {
3006 case TemplateArgument::Type:
3007 // C++ [temp.arg.type]p1:
3008 // A template-argument for a template-parameter which is a
3009 // type shall be a type-id.
3010 ArgType = Arg.getAsType();
3011 TSI = AL.getTypeSourceInfo();
3012 break;
3013 case TemplateArgument::Template: {
3014 // We have a template type parameter but the template argument
3015 // is a template without any arguments.
3016 SourceRange SR = AL.getSourceRange();
3017 TemplateName Name = Arg.getAsTemplate();
3018 Diag(SR.getBegin(), diag::err_template_missing_args)
3019 << Name << SR;
3020 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3021 Diag(Decl->getLocation(), diag::note_template_decl_here);
3022
3023 return true;
3024 }
3025 case TemplateArgument::Expression: {
3026 // We have a template type parameter but the template argument is an
3027 // expression; see if maybe it is missing the "typename" keyword.
3028 CXXScopeSpec SS;
3029 DeclarationNameInfo NameInfo;
3030
3031 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3032 SS.Adopt(ArgExpr->getQualifierLoc());
3033 NameInfo = ArgExpr->getNameInfo();
3034 } else if (DependentScopeDeclRefExpr *ArgExpr =
3035 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3036 SS.Adopt(ArgExpr->getQualifierLoc());
3037 NameInfo = ArgExpr->getNameInfo();
3038 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3039 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3040 if (ArgExpr->isImplicitAccess()) {
3041 SS.Adopt(ArgExpr->getQualifierLoc());
3042 NameInfo = ArgExpr->getMemberNameInfo();
3043 }
3044 }
3045
3046 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3047 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3048 LookupParsedName(Result, CurScope, &SS);
3049
3050 if (Result.getAsSingle<TypeDecl>() ||
3051 Result.getResultKind() ==
3052 LookupResult::NotFoundInCurrentInstantiation) {
3053 // Suggest that the user add 'typename' before the NNS.
3054 SourceLocation Loc = AL.getSourceRange().getBegin();
3055 Diag(Loc, getLangOpts().MSVCCompat
3056 ? diag::ext_ms_template_type_arg_missing_typename
3057 : diag::err_template_arg_must_be_type_suggest)
3058 << FixItHint::CreateInsertion(Loc, "typename ");
3059 Diag(Param->getLocation(), diag::note_template_param_here);
3060
3061 // Recover by synthesizing a type using the location information that we
3062 // already have.
3063 ArgType =
3064 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3065 TypeLocBuilder TLB;
3066 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3067 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3068 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3069 TL.setNameLoc(NameInfo.getLoc());
3070 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3071
3072 // Overwrite our input TemplateArgumentLoc so that we can recover
3073 // properly.
3074 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3075 TemplateArgumentLocInfo(TSI));
3076
3077 break;
3078 }
3079 }
3080 // fallthrough
3081 }
3082 default: {
3083 // We have a template type parameter but the template argument
3084 // is not a type.
3085 SourceRange SR = AL.getSourceRange();
3086 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3087 Diag(Param->getLocation(), diag::note_template_param_here);
3088
3089 return true;
3090 }
3091 }
3092
3093 if (CheckTemplateArgument(Param, TSI))
3094 return true;
3095
3096 // Add the converted template type argument.
3097 ArgType = Context.getCanonicalType(ArgType);
3098
3099 // Objective-C ARC:
3100 // If an explicitly-specified template argument type is a lifetime type
3101 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3102 if (getLangOpts().ObjCAutoRefCount &&
3103 ArgType->isObjCLifetimeType() &&
3104 !ArgType.getObjCLifetime()) {
3105 Qualifiers Qs;
3106 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3107 ArgType = Context.getQualifiedType(ArgType, Qs);
3108 }
3109
3110 Converted.push_back(TemplateArgument(ArgType));
3111 return false;
3112}
3113
3114/// \brief Substitute template arguments into the default template argument for
3115/// the given template type parameter.
3116///
3117/// \param SemaRef the semantic analysis object for which we are performing
3118/// the substitution.
3119///
3120/// \param Template the template that we are synthesizing template arguments
3121/// for.
3122///
3123/// \param TemplateLoc the location of the template name that started the
3124/// template-id we are checking.
3125///
3126/// \param RAngleLoc the location of the right angle bracket ('>') that
3127/// terminates the template-id.
3128///
3129/// \param Param the template template parameter whose default we are
3130/// substituting into.
3131///
3132/// \param Converted the list of template arguments provided for template
3133/// parameters that precede \p Param in the template parameter list.
3134/// \returns the substituted template argument, or NULL if an error occurred.
3135static TypeSourceInfo *
3136SubstDefaultTemplateArgument(Sema &SemaRef,
3137 TemplateDecl *Template,
3138 SourceLocation TemplateLoc,
3139 SourceLocation RAngleLoc,
3140 TemplateTypeParmDecl *Param,
3141 SmallVectorImpl<TemplateArgument> &Converted) {
3142 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3143
3144 // If the argument type is dependent, instantiate it now based
3145 // on the previously-computed template arguments.
3146 if (ArgType->getType()->isDependentType()) {
3147 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3148 Template, Converted,
3149 SourceRange(TemplateLoc, RAngleLoc));
3150 if (Inst.isInvalid())
3151 return nullptr;
3152
3153 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3154 Converted.data(), Converted.size());
3155
3156 // Only substitute for the innermost template argument list.
3157 MultiLevelTemplateArgumentList TemplateArgLists;
3158 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3159 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3160 TemplateArgLists.addOuterTemplateArguments(None);
3161
3162 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3163 ArgType =
3164 SemaRef.SubstType(ArgType, TemplateArgLists,
3165 Param->getDefaultArgumentLoc(), Param->getDeclName());
3166 }
3167
3168 return ArgType;
3169}
3170
3171/// \brief Substitute template arguments into the default template argument for
3172/// the given non-type template parameter.
3173///
3174/// \param SemaRef the semantic analysis object for which we are performing
3175/// the substitution.
3176///
3177/// \param Template the template that we are synthesizing template arguments
3178/// for.
3179///
3180/// \param TemplateLoc the location of the template name that started the
3181/// template-id we are checking.
3182///
3183/// \param RAngleLoc the location of the right angle bracket ('>') that
3184/// terminates the template-id.
3185///
3186/// \param Param the non-type template parameter whose default we are
3187/// substituting into.
3188///
3189/// \param Converted the list of template arguments provided for template
3190/// parameters that precede \p Param in the template parameter list.
3191///
3192/// \returns the substituted template argument, or NULL if an error occurred.
3193static ExprResult
3194SubstDefaultTemplateArgument(Sema &SemaRef,
3195 TemplateDecl *Template,
3196 SourceLocation TemplateLoc,
3197 SourceLocation RAngleLoc,
3198 NonTypeTemplateParmDecl *Param,
3199 SmallVectorImpl<TemplateArgument> &Converted) {
3200 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3201 Template, Converted,
3202 SourceRange(TemplateLoc, RAngleLoc));
3203 if (Inst.isInvalid())
3204 return ExprError();
3205
3206 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3207 Converted.data(), Converted.size());
3208
3209 // Only substitute for the innermost template argument list.
3210 MultiLevelTemplateArgumentList TemplateArgLists;
3211 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3212 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3213 TemplateArgLists.addOuterTemplateArguments(None);
3214
3215 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3216 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3217 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3218}
3219
3220/// \brief Substitute template arguments into the default template argument for
3221/// the given template template parameter.
3222///
3223/// \param SemaRef the semantic analysis object for which we are performing
3224/// the substitution.
3225///
3226/// \param Template the template that we are synthesizing template arguments
3227/// for.
3228///
3229/// \param TemplateLoc the location of the template name that started the
3230/// template-id we are checking.
3231///
3232/// \param RAngleLoc the location of the right angle bracket ('>') that
3233/// terminates the template-id.
3234///
3235/// \param Param the template template parameter whose default we are
3236/// substituting into.
3237///
3238/// \param Converted the list of template arguments provided for template
3239/// parameters that precede \p Param in the template parameter list.
3240///
3241/// \param QualifierLoc Will be set to the nested-name-specifier (with
3242/// source-location information) that precedes the template name.
3243///
3244/// \returns the substituted template argument, or NULL if an error occurred.
3245static TemplateName
3246SubstDefaultTemplateArgument(Sema &SemaRef,
3247 TemplateDecl *Template,
3248 SourceLocation TemplateLoc,
3249 SourceLocation RAngleLoc,
3250 TemplateTemplateParmDecl *Param,
3251 SmallVectorImpl<TemplateArgument> &Converted,
3252 NestedNameSpecifierLoc &QualifierLoc) {
3253 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3254 SourceRange(TemplateLoc, RAngleLoc));
3255 if (Inst.isInvalid())
3256 return TemplateName();
3257
3258 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3259 Converted.data(), Converted.size());
3260
3261 // Only substitute for the innermost template argument list.
3262 MultiLevelTemplateArgumentList TemplateArgLists;
3263 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3264 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3265 TemplateArgLists.addOuterTemplateArguments(None);
3266
3267 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3268 // Substitute into the nested-name-specifier first,
3269 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3270 if (QualifierLoc) {
3271 QualifierLoc =
3272 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3273 if (!QualifierLoc)
3274 return TemplateName();
3275 }
3276
3277 return SemaRef.SubstTemplateName(
3278 QualifierLoc,
3279 Param->getDefaultArgument().getArgument().getAsTemplate(),
3280 Param->getDefaultArgument().getTemplateNameLoc(),
3281 TemplateArgLists);
3282}
3283
3284/// \brief If the given template parameter has a default template
3285/// argument, substitute into that default template argument and
3286/// return the corresponding template argument.
3287TemplateArgumentLoc
3288Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3289 SourceLocation TemplateLoc,
3290 SourceLocation RAngleLoc,
3291 Decl *Param,
3292 SmallVectorImpl<TemplateArgument>
3293 &Converted,
3294 bool &HasDefaultArg) {
3295 HasDefaultArg = false;
3296
3297 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3298 if (!TypeParm->hasDefaultArgument())
3299 return TemplateArgumentLoc();
3300
3301 HasDefaultArg = true;
3302 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3303 TemplateLoc,
3304 RAngleLoc,
3305 TypeParm,
3306 Converted);
3307 if (DI)
3308 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3309
3310 return TemplateArgumentLoc();
3311 }
3312
3313 if (NonTypeTemplateParmDecl *NonTypeParm
3314 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3315 if (!NonTypeParm->hasDefaultArgument())
3316 return TemplateArgumentLoc();
3317
3318 HasDefaultArg = true;
3319 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3320 TemplateLoc,
3321 RAngleLoc,
3322 NonTypeParm,
3323 Converted);
3324 if (Arg.isInvalid())
3325 return TemplateArgumentLoc();
3326
3327 Expr *ArgE = Arg.getAs<Expr>();
3328 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3329 }
3330
3331 TemplateTemplateParmDecl *TempTempParm
3332 = cast<TemplateTemplateParmDecl>(Param);
3333 if (!TempTempParm->hasDefaultArgument())
3334 return TemplateArgumentLoc();
3335
3336 HasDefaultArg = true;
3337 NestedNameSpecifierLoc QualifierLoc;
3338 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3339 TemplateLoc,
3340 RAngleLoc,
3341 TempTempParm,
3342 Converted,
3343 QualifierLoc);
3344 if (TName.isNull())
3345 return TemplateArgumentLoc();
3346
3347 return TemplateArgumentLoc(TemplateArgument(TName),
3348 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3349 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3350}
3351
3352/// \brief Check that the given template argument corresponds to the given
3353/// template parameter.
3354///
3355/// \param Param The template parameter against which the argument will be
3356/// checked.
3357///
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2//
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.
7//===----------------------------------------------------------------------===/
8//
9// This file implements semantic analysis for C++ templates.
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclFriend.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/RecursiveASTVisitor.h"
20#include "clang/AST/TypeVisitor.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/TargetInfo.h"
24#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"
31#include "llvm/ADT/SmallBitVector.h"
32#include "llvm/ADT/SmallString.h"
33#include "llvm/ADT/StringExtras.h"
34using namespace clang;
35using namespace sema;
36
37// 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
45/// \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.
48static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
49 NamedDecl *Orig,
50 bool AllowFunctionTemplates) {
51 NamedDecl *D = Orig->getUnderlyingDecl();
52
53 if (isa<TemplateDecl>(D)) {
54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
55 return nullptr;
56
57 return Orig;
58 }
59
60 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()) {
73 Record = cast<CXXRecordDecl>(Record->getDeclContext());
74 if (Record->getDescribedClassTemplate())
75 return Record->getDescribedClassTemplate();
76
77 if (ClassTemplateSpecializationDecl *Spec
78 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
79 return Spec->getSpecializedTemplate();
80 }
81
82 return nullptr;
83 }
84
85 return nullptr;
86}
87
88void Sema::FilterAcceptableTemplateNames(LookupResult &R,
89 bool AllowFunctionTemplates) {
90 // The set of class templates we've already seen.
91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
92 LookupResult::Filter filter = R.makeFilter();
93 while (filter.hasNext()) {
94 NamedDecl *Orig = filter.next();
95 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
96 AllowFunctionTemplates);
97 if (!Repl)
98 filter.erase();
99 else if (Repl != Orig) {
100
101 // C++ [temp.local]p3:
102 // A lookup that finds an injected-class-name (10.2) can result in an
103 // ambiguity in certain cases (for example, if it is found in more than
104 // 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
106 // is used as a template-name, the reference refers to the class
107 // template itself and not a specialization thereof, and is not
108 // ambiguous.
109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
110 if (!ClassTemplates.insert(ClassTmpl).second) {
111 filter.erase();
112 continue;
113 }
114
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);
121 }
122 }
123 filter.done();
124}
125
126bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
127 bool AllowFunctionTemplates) {
128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
130 return true;
131
132 return false;
133}
134
135TemplateNameKind Sema::isTemplateName(Scope *S,
136 CXXScopeSpec &SS,
137 bool hasTemplateKeyword,
138 UnqualifiedId &Name,
139 ParsedType ObjectTypePtr,
140 bool EnteringContext,
141 TemplateTy &TemplateResult,
142 bool &MemberOfUnknownSpecialization) {
143 assert(getLangOpts().CPlusPlus && "No template names in C!");
144
145 DeclarationName TName;
146 MemberOfUnknownSpecialization = false;
147
148 switch (Name.getKind()) {
149 case UnqualifiedId::IK_Identifier:
150 TName = DeclarationName(Name.Identifier);
151 break;
152
153 case UnqualifiedId::IK_OperatorFunctionId:
154 TName = Context.DeclarationNames.getCXXOperatorName(
155 Name.OperatorFunctionId.Operator);
156 break;
157
158 case UnqualifiedId::IK_LiteralOperatorId:
159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
160 break;
161
162 default:
163 return TNK_Non_template;
164 }
165
166 QualType ObjectType = ObjectTypePtr.get();
167
168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
170 MemberOfUnknownSpecialization);
171 if (R.empty()) return TNK_Non_template;
172 if (R.isAmbiguous()) {
173 // Suppress diagnostics; we'll redo this lookup later.
174 R.suppressDiagnostics();
175
176 // FIXME: we might have ambiguous templates, in which case we
177 // should at least parse them properly!
178 return TNK_Non_template;
179 }
180
181 TemplateName Template;
182 TemplateNameKind TemplateKind;
183
184 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;
190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
195
196 if (SS.isSet() && !SS.isInvalid()) {
197 NestedNameSpecifier *Qualifier = SS.getScopeRep();
198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
200 } else {
201 Template = TemplateName(TD);
202 }
203
204 if (isa<FunctionTemplateDecl>(TD)) {
205 TemplateKind = TNK_Function_template;
206
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
209 } else {
210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
212 TemplateKind =
213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
214 }
215 }
216
217 TemplateResult = TemplateTy::make(Template);
218 return TemplateKind;
219}
220
221bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
222 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.
229 // FIXME: Typo correction?
230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
231 computeDeclContext(*SS))
232 return false;
233
234 // 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()
239 << FixItHint::CreateInsertion(IILoc, "template ");
240 SuggestedTemplate
241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
242 SuggestedKind = TNK_Dependent_template_name;
243 return true;
244}
245
246void Sema::LookupTemplateName(LookupResult &Found,
247 Scope *S, CXXScopeSpec &SS,
248 QualType ObjectType,
249 bool EnteringContext,
250 bool &MemberOfUnknownSpecialization) {
251 // Determine where to perform name lookup
252 MemberOfUnknownSpecialization = false;
253 DeclContext *LookupCtx = nullptr;
254 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();
261 assert((isDependent || !ObjectType->isIncompleteType() ||
262 ObjectType->castAs<TagType>()->isBeingDefined()) &&
263 "Caller should have completed object type");
264
265 // Template names cannot appear inside an Objective-C class or object type.
266 if (ObjectType->isObjCObjectOrInterfaceType()) {
267 Found.clear();
268 return;
269 }
270 } 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);
275
276 // The declaration context must be complete.
277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
278 return;
279 }
280
281 bool ObjectTypeSearchedInScope = false;
282 bool AllowFunctionTemplatesInLookup = true;
283 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);
289 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.
299 if (S) LookupName(Found, S);
300 ObjectTypeSearchedInScope = true;
301 AllowFunctionTemplatesInLookup = false;
302 }
303 } else if (isDependent && (!S || ObjectType.isNull())) {
304 // We cannot look into a dependent object type or nested nme
305 // specifier.
306 MemberOfUnknownSpecialization = true;
307 return;
308 } else {
309 // Perform unqualified name lookup in the current scope.
310 LookupName(Found, S);
311
312 if (!ObjectType.isNull())
313 AllowFunctionTemplatesInLookup = false;
314 }
315
316 if (Found.empty() && !isDependent) {
317 // If we did not find any names, attempt to correct any typos.
318 DeclarationName Name = Found.getLookupName();
319 Found.clear();
320 // Simple filter callback that, for keywords, only accepts the C++ *_cast
321 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
322 FilterCCC->WantTypeSpecifiers = false;
323 FilterCCC->WantExpressionKeywords = false;
324 FilterCCC->WantRemainingKeywords = false;
325 FilterCCC->WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(
327 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
328 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
329 Found.setLookupName(Corrected.getCorrection());
330 if (Corrected.getCorrectionDecl())
331 Found.addDecl(Corrected.getCorrectionDecl());
332 FilterAcceptableTemplateNames(Found);
333 if (!Found.empty()) {
334 if (LookupCtx) {
335 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
336 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
337 Name.getAsString() == CorrectedStr;
338 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
339 << Name << LookupCtx << DroppedSpecifier
340 << SS.getRange());
341 } else {
342 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
343 }
344 }
345 } else {
346 Found.setLookupName(Name);
347 }
348 }
349
350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
351 if (Found.empty()) {
352 if (isDependent)
353 MemberOfUnknownSpecialization = true;
354 return;
355 }
356
357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
358 !getLangOpts().CPlusPlus11) {
359 // C++03 [basic.lookup.classref]p1:
360 // [...] If the lookup in the class of the object expression finds a
361 // template, the name is also looked up in the context of the entire
362 // postfix-expression and [...]
363 //
364 // Note: C++11 does not perform this second lookup.
365 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
366 LookupOrdinaryName);
367 LookupName(FoundOuter, S);
368 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
369
370 if (FoundOuter.empty()) {
371 // - if the name is not found, the name found in the class of the
372 // object expression is used, otherwise
373 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
374 FoundOuter.isAmbiguous()) {
375 // - if the name is found in the context of the entire
376 // postfix-expression and does not name a class template, the name
377 // found in the class of the object expression is used, otherwise
378 FoundOuter.clear();
379 } else if (!Found.isSuppressingDiagnostics()) {
380 // - if the name found is a class template, it must refer to the same
381 // entity as the one found in the class of the object expression,
382 // otherwise the program is ill-formed.
383 if (!Found.isSingleResult() ||
384 Found.getFoundDecl()->getCanonicalDecl()
385 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
386 Diag(Found.getNameLoc(),
387 diag::ext_nested_name_member_ref_lookup_ambiguous)
388 << Found.getLookupName()
389 << ObjectType;
390 Diag(Found.getRepresentativeDecl()->getLocation(),
391 diag::note_ambig_member_ref_object_type)
392 << ObjectType;
393 Diag(FoundOuter.getFoundDecl()->getLocation(),
394 diag::note_ambig_member_ref_scope);
395
396 // Recover by taking the template that we found in the object
397 // expression's type.
398 }
399 }
400 }
401}
402
403/// ActOnDependentIdExpression - Handle a dependent id-expression that
404/// was just parsed. This is only possible with an explicit scope
405/// specifier naming a dependent type.
406ExprResult
407Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
408 SourceLocation TemplateKWLoc,
409 const DeclarationNameInfo &NameInfo,
410 bool isAddressOfOperand,
411 const TemplateArgumentListInfo *TemplateArgs) {
412 DeclContext *DC = getFunctionLevelDeclContext();
413
414 if (!isAddressOfOperand &&
415 isa<CXXMethodDecl>(DC) &&
416 cast<CXXMethodDecl>(DC)->isInstance()) {
417 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
418
419 // Since the 'this' expression is synthesized, we don't need to
420 // perform the double-lookup check.
421 NamedDecl *FirstQualifierInScope = nullptr;
422
423 return CXXDependentScopeMemberExpr::Create(
424 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
425 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
426 FirstQualifierInScope, NameInfo, TemplateArgs);
427 }
428
429 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
430}
431
432ExprResult
433Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
434 SourceLocation TemplateKWLoc,
435 const DeclarationNameInfo &NameInfo,
436 const TemplateArgumentListInfo *TemplateArgs) {
437 return DependentScopeDeclRefExpr::Create(
438 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
439 TemplateArgs);
440}
441
442/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
443/// that the template parameter 'PrevDecl' is being shadowed by a new
444/// declaration at location Loc. Returns true to indicate that this is
445/// an error, and false otherwise.
446void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
447 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
448
449 // Microsoft Visual C++ permits template parameters to be shadowed.
450 if (getLangOpts().MicrosoftExt)
451 return;
452
453 // C++ [temp.local]p4:
454 // A template-parameter shall not be redeclared within its
455 // scope (including nested scopes).
456 Diag(Loc, diag::err_template_param_shadow)
457 << cast<NamedDecl>(PrevDecl)->getDeclName();
458 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
459 return;
460}
461
462/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
463/// the parameter D to reference the templated declaration and return a pointer
464/// to the template declaration. Otherwise, do nothing to D and return null.
465TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
466 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
467 D = Temp->getTemplatedDecl();
468 return Temp;
469 }
470 return nullptr;
471}
472
473ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
474 SourceLocation EllipsisLoc) const {
475 assert(Kind == Template &&
476 "Only template template arguments can be pack expansions here");
477 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
478 "Template template argument pack expansion without packs");
479 ParsedTemplateArgument Result(*this);
480 Result.EllipsisLoc = EllipsisLoc;
481 return Result;
482}
483
484static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
485 const ParsedTemplateArgument &Arg) {
486
487 switch (Arg.getKind()) {
488 case ParsedTemplateArgument::Type: {
489 TypeSourceInfo *DI;
490 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
491 if (!DI)
492 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
493 return TemplateArgumentLoc(TemplateArgument(T), DI);
494 }
495
496 case ParsedTemplateArgument::NonType: {
497 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
498 return TemplateArgumentLoc(TemplateArgument(E), E);
499 }
500
501 case ParsedTemplateArgument::Template: {
502 TemplateName Template = Arg.getAsTemplate().get();
503 TemplateArgument TArg;
504 if (Arg.getEllipsisLoc().isValid())
505 TArg = TemplateArgument(Template, Optional<unsigned int>());
506 else
507 TArg = Template;
508 return TemplateArgumentLoc(TArg,
509 Arg.getScopeSpec().getWithLocInContext(
510 SemaRef.Context),
511 Arg.getLocation(),
512 Arg.getEllipsisLoc());
513 }
514 }
515
516 llvm_unreachable("Unhandled parsed template argument");
517}
518
519/// \brief Translates template arguments as provided by the parser
520/// into template arguments used by semantic analysis.
521void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
522 TemplateArgumentListInfo &TemplateArgs) {
523 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
524 TemplateArgs.addArgument(translateTemplateArgument(*this,
525 TemplateArgsIn[I]));
526}
527
528static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
529 SourceLocation Loc,
530 IdentifierInfo *Name) {
531 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
532 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
533 if (PrevDecl && PrevDecl->isTemplateParameter())
534 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
535}
536
537/// ActOnTypeParameter - Called when a C++ template type parameter
538/// (e.g., "typename T") has been parsed. Typename specifies whether
539/// the keyword "typename" was used to declare the type parameter
540/// (otherwise, "class" was used), and KeyLoc is the location of the
541/// "class" or "typename" keyword. ParamName is the name of the
542/// parameter (NULL indicates an unnamed template parameter) and
543/// ParamNameLoc is the location of the parameter name (if any).
544/// If the type parameter has a default argument, it will be added
545/// later via ActOnTypeParameterDefault.
546Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
553 ParsedType DefaultArg) {
554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
556 bool Invalid = false;
557
558 SourceLocation Loc = ParamNameLoc;
559 if (!ParamName)
560 Loc = KeyLoc;
561
562 bool IsParameterPack = EllipsisLoc.isValid();
563 TemplateTypeParmDecl *Param
564 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
565 KeyLoc, Loc, Depth, Position, ParamName,
566 Typename, IsParameterPack);
567 Param->setAccess(AS_public);
568 if (Invalid)
569 Param->setInvalidDecl();
570
571 if (ParamName) {
572 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
573
574 // Add the template parameter into the current scope.
575 S->AddDecl(Param);
576 IdResolver.AddDecl(Param);
577 }
578
579 // C++0x [temp.param]p9:
580 // A default template-argument may be specified for any kind of
581 // template-parameter that is not a template parameter pack.
582 if (DefaultArg && IsParameterPack) {
583 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
584 DefaultArg = ParsedType();
585 }
586
587 // Handle the default argument, if provided.
588 if (DefaultArg) {
589 TypeSourceInfo *DefaultTInfo;
590 GetTypeFromParser(DefaultArg, &DefaultTInfo);
591
592 assert(DefaultTInfo && "expected source information for type");
593
594 // Check for unexpanded parameter packs.
595 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
596 UPPC_DefaultArgument))
597 return Param;
598
599 // Check the template argument itself.
600 if (CheckTemplateArgument(Param, DefaultTInfo)) {
601 Param->setInvalidDecl();
602 return Param;
603 }
604
605 Param->setDefaultArgument(DefaultTInfo, false);
606 }
607
608 return Param;
609}
610
611/// \brief Check that the type of a non-type template parameter is
612/// well-formed.
613///
614/// \returns the (possibly-promoted) parameter type if valid;
615/// otherwise, produces a diagnostic and returns a NULL type.
616QualType
617Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
618 // We don't allow variably-modified types as the type of non-type template
619 // parameters.
620 if (T->isVariablyModifiedType()) {
621 Diag(Loc, diag::err_variably_modified_nontype_template_param)
622 << T;
623 return QualType();
624 }
625
626 // C++ [temp.param]p4:
627 //
628 // A non-type template-parameter shall have one of the following
629 // (optionally cv-qualified) types:
630 //
631 // -- integral or enumeration type,
632 if (T->isIntegralOrEnumerationType() ||
633 // -- pointer to object or pointer to function,
634 T->isPointerType() ||
635 // -- reference to object or reference to function,
636 T->isReferenceType() ||
637 // -- pointer to member,
638 T->isMemberPointerType() ||
639 // -- std::nullptr_t.
640 T->isNullPtrType() ||
641 // If T is a dependent type, we can't do the check now, so we
642 // assume that it is well-formed.
643 T->isDependentType()) {
644 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
645 // are ignored when determining its type.
646 return T.getUnqualifiedType();
647 }
648
649 // C++ [temp.param]p8:
650 //
651 // A non-type template-parameter of type "array of T" or
652 // "function returning T" is adjusted to be of type "pointer to
653 // T" or "pointer to function returning T", respectively.
654 else if (T->isArrayType() || T->isFunctionType())
655 return Context.getDecayedType(T);
656
657 Diag(Loc, diag::err_template_nontype_parm_bad_type)
658 << T;
659
660 return QualType();
661}
662
663Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
664 unsigned Depth,
665 unsigned Position,
666 SourceLocation EqualLoc,
667 Expr *Default) {
668 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
669 QualType T = TInfo->getType();
670
671 assert(S->isTemplateParamScope() &&
672 "Non-type template parameter not in template parameter scope!");
673 bool Invalid = false;
674
675 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
676 if (T.isNull()) {
677 T = Context.IntTy; // Recover with an 'int' type.
678 Invalid = true;
679 }
680
681 IdentifierInfo *ParamName = D.getIdentifier();
682 bool IsParameterPack = D.hasEllipsis();
683 NonTypeTemplateParmDecl *Param
684 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
685 D.getLocStart(),
686 D.getIdentifierLoc(),
687 Depth, Position, ParamName, T,
688 IsParameterPack, TInfo);
689 Param->setAccess(AS_public);
690
691 if (Invalid)
692 Param->setInvalidDecl();
693
694 if (ParamName) {
695 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
696 ParamName);
697
698 // Add the template parameter into the current scope.
699 S->AddDecl(Param);
700 IdResolver.AddDecl(Param);
701 }
702
703 // C++0x [temp.param]p9:
704 // A default template-argument may be specified for any kind of
705 // template-parameter that is not a template parameter pack.
706 if (Default && IsParameterPack) {
707 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
708 Default = nullptr;
709 }
710
711 // Check the well-formedness of the default template argument, if provided.
712 if (Default) {
713 // Check for unexpanded parameter packs.
714 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
715 return Param;
716
717 TemplateArgument Converted;
718 ExprResult DefaultRes =
719 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
720 if (DefaultRes.isInvalid()) {
721 Param->setInvalidDecl();
722 return Param;
723 }
724 Default = DefaultRes.get();
725
726 Param->setDefaultArgument(Default, false);
727 }
728
729 return Param;
730}
731
732/// ActOnTemplateTemplateParameter - Called when a C++ template template
733/// parameter (e.g. T in template <template \<typename> class T> class array)
734/// has been parsed. S is the current scope.
735Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
736 SourceLocation TmpLoc,
737 TemplateParameterList *Params,
738 SourceLocation EllipsisLoc,
739 IdentifierInfo *Name,
740 SourceLocation NameLoc,
741 unsigned Depth,
742 unsigned Position,
743 SourceLocation EqualLoc,
744 ParsedTemplateArgument Default) {
745 assert(S->isTemplateParamScope() &&
746 "Template template parameter not in template parameter scope!");
747
748 // Construct the parameter object.
749 bool IsParameterPack = EllipsisLoc.isValid();
750 TemplateTemplateParmDecl *Param =
751 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
752 NameLoc.isInvalid()? TmpLoc : NameLoc,
753 Depth, Position, IsParameterPack,
754 Name, Params);
755 Param->setAccess(AS_public);
756
757 // If the template template parameter has a name, then link the identifier
758 // into the scope and lookup mechanisms.
759 if (Name) {
760 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
761
762 S->AddDecl(Param);
763 IdResolver.AddDecl(Param);
764 }
765
766 if (Params->size() == 0) {
767 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
768 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
769 Param->setInvalidDecl();
770 }
771
772 // C++0x [temp.param]p9:
773 // A default template-argument may be specified for any kind of
774 // template-parameter that is not a template parameter pack.
775 if (IsParameterPack && !Default.isInvalid()) {
776 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
777 Default = ParsedTemplateArgument();
778 }
779
780 if (!Default.isInvalid()) {
781 // Check only that we have a template template argument. We don't want to
782 // try to check well-formedness now, because our template template parameter
783 // might have dependent types in its template parameters, which we wouldn't
784 // be able to match now.
785 //
786 // If none of the template template parameter's template arguments mention
787 // other template parameters, we could actually perform more checking here.
788 // However, it isn't worth doing.
789 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
790 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
791 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
792 << DefaultArg.getSourceRange();
793 return Param;
794 }
795
796 // Check for unexpanded parameter packs.
797 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
798 DefaultArg.getArgument().getAsTemplate(),
799 UPPC_DefaultArgument))
800 return Param;
801
802 Param->setDefaultArgument(DefaultArg, false);
803 }
804
805 return Param;
806}
807
808/// ActOnTemplateParameterList - Builds a TemplateParameterList that
809/// contains the template parameters in Params/NumParams.
810TemplateParameterList *
811Sema::ActOnTemplateParameterList(unsigned Depth,
812 SourceLocation ExportLoc,
813 SourceLocation TemplateLoc,
814 SourceLocation LAngleLoc,
815 Decl **Params, unsigned NumParams,
816 SourceLocation RAngleLoc) {
817 if (ExportLoc.isValid())
818 Diag(ExportLoc, diag::warn_template_export_unsupported);
819
820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
821 (NamedDecl**)Params, NumParams,
822 RAngleLoc);
823}
824
825static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
826 if (SS.isSet())
827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
828}
829
830DeclResult
831Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
832 SourceLocation KWLoc, CXXScopeSpec &SS,
833 IdentifierInfo *Name, SourceLocation NameLoc,
834 AttributeList *Attr,
835 TemplateParameterList *TemplateParams,
836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
837 SourceLocation FriendLoc,
838 unsigned NumOuterTemplateParamLists,
839 TemplateParameterList** OuterTemplateParamLists) {
840 assert(TemplateParams && TemplateParams->size() > 0 &&
841 "No template parameters");
842 assert(TUK != TUK_Reference && "Can only declare or define class templates");
843 bool Invalid = false;
844
845 // Check that we can declare a template here.
846 if (CheckTemplateDeclScope(S, TemplateParams))
847 return true;
848
849 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
850 assert(Kind != TTK_Enum && "can't build template of enumerated type");
851
852 // There is no such thing as an unnamed class template.
853 if (!Name) {
854 Diag(KWLoc, diag::err_template_unnamed_class);
855 return true;
856 }
857
858 // Find any previous declaration with this name. For a friend with no
859 // scope explicitly specified, we only look for tag declarations (per
860 // C++11 [basic.lookup.elab]p2).
861 DeclContext *SemanticContext;
862 LookupResult Previous(*this, Name, NameLoc,
863 (SS.isEmpty() && TUK == TUK_Friend)
864 ? LookupTagName : LookupOrdinaryName,
865 ForRedeclaration);
866 if (SS.isNotEmpty() && !SS.isInvalid()) {
867 SemanticContext = computeDeclContext(SS, true);
868 if (!SemanticContext) {
869 // FIXME: Horrible, horrible hack! We can't currently represent this
870 // in the AST, and historically we have just ignored such friend
871 // class templates, so don't complain here.
872 Diag(NameLoc, TUK == TUK_Friend
873 ? diag::warn_template_qualified_friend_ignored
874 : diag::err_template_qualified_declarator_no_match)
875 << SS.getScopeRep() << SS.getRange();
876 return TUK != TUK_Friend;
877 }
878
879 if (RequireCompleteDeclContext(SS, SemanticContext))
880 return true;
881
882 // If we're adding a template to a dependent context, we may need to
883 // rebuilding some of the types used within the template parameter list,
884 // now that we know what the current instantiation is.
885 if (SemanticContext->isDependentContext()) {
886 ContextRAII SavedContext(*this, SemanticContext);
887 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
888 Invalid = true;
889 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
890 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
891
892 LookupQualifiedName(Previous, SemanticContext);
893 } else {
894 SemanticContext = CurContext;
895 LookupName(Previous, S);
896 }
897
898 if (Previous.isAmbiguous())
899 return true;
900
901 NamedDecl *PrevDecl = nullptr;
902 if (Previous.begin() != Previous.end())
903 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
904
905 // If there is a previous declaration with the same name, check
906 // whether this is a valid redeclaration.
907 ClassTemplateDecl *PrevClassTemplate
908 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
909
910 // We may have found the injected-class-name of a class template,
911 // class template partial specialization, or class template specialization.
912 // In these cases, grab the template that is being defined or specialized.
913 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
914 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
915 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
916 PrevClassTemplate
917 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
918 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
919 PrevClassTemplate
920 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
921 ->getSpecializedTemplate();
922 }
923 }
924
925 if (TUK == TUK_Friend) {
926 // C++ [namespace.memdef]p3:
927 // [...] When looking for a prior declaration of a class or a function
928 // declared as a friend, and when the name of the friend class or
929 // function is neither a qualified name nor a template-id, scopes outside
930 // the innermost enclosing namespace scope are not considered.
931 if (!SS.isSet()) {
932 DeclContext *OutermostContext = CurContext;
933 while (!OutermostContext->isFileContext())
934 OutermostContext = OutermostContext->getLookupParent();
935
936 if (PrevDecl &&
937 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
938 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
939 SemanticContext = PrevDecl->getDeclContext();
940 } else {
941 // Declarations in outer scopes don't matter. However, the outermost
942 // context we computed is the semantic context for our new
943 // declaration.
944 PrevDecl = PrevClassTemplate = nullptr;
945 SemanticContext = OutermostContext;
946
947 // Check that the chosen semantic context doesn't already contain a
948 // declaration of this name as a non-tag type.
949 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
950 ForRedeclaration);
951 DeclContext *LookupContext = SemanticContext;
952 while (LookupContext->isTransparentContext())
953 LookupContext = LookupContext->getLookupParent();
954 LookupQualifiedName(Previous, LookupContext);
955
956 if (Previous.isAmbiguous())
957 return true;
958
959 if (Previous.begin() != Previous.end())
960 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
961 }
962 }
963 } else if (PrevDecl &&
964 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
965 PrevDecl = PrevClassTemplate = nullptr;
966
967 if (PrevClassTemplate) {
968 // Ensure that the template parameter lists are compatible. Skip this check
969 // for a friend in a dependent context: the template parameter list itself
970 // could be dependent.
971 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
972 !TemplateParameterListsAreEqual(TemplateParams,
973 PrevClassTemplate->getTemplateParameters(),
974 /*Complain=*/true,
975 TPL_TemplateMatch))
976 return true;
977
978 // C++ [temp.class]p4:
979 // In a redeclaration, partial specialization, explicit
980 // specialization or explicit instantiation of a class template,
981 // the class-key shall agree in kind with the original class
982 // template declaration (7.1.5.3).
983 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
984 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
985 TUK == TUK_Definition, KWLoc, *Name)) {
986 Diag(KWLoc, diag::err_use_with_wrong_tag)
987 << Name
988 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
989 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
990 Kind = PrevRecordDecl->getTagKind();
991 }
992
993 // Check for redefinition of this class template.
994 if (TUK == TUK_Definition) {
995 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
996 Diag(NameLoc, diag::err_redefinition) << Name;
997 Diag(Def->getLocation(), diag::note_previous_definition);
998 // FIXME: Would it make sense to try to "forget" the previous
999 // definition, as part of error recovery?
1000 return true;
1001 }
1002 }
1003 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1004 // Maybe we will complain about the shadowed template parameter.
1005 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1006 // Just pretend that we didn't see the previous declaration.
1007 PrevDecl = nullptr;
1008 } else if (PrevDecl) {
1009 // C++ [temp]p5:
1010 // A class template shall not have the same name as any other
1011 // template, class, function, object, enumeration, enumerator,
1012 // namespace, or type in the same scope (3.3), except as specified
1013 // in (14.5.4).
1014 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1015 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1016 return true;
1017 }
1018
1019 // Check the template parameter list of this declaration, possibly
1020 // merging in the template parameter list from the previous class
1021 // template declaration. Skip this check for a friend in a dependent
1022 // context, because the template parameter list might be dependent.
1023 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1024 CheckTemplateParameterList(
1025 TemplateParams,
1026 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1027 : nullptr,
1028 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1029 SemanticContext->isDependentContext())
1030 ? TPC_ClassTemplateMember
1031 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1032 : TPC_ClassTemplate))
1033 Invalid = true;
1034
1035 if (SS.isSet()) {
1036 // If the name of the template was qualified, we must be defining the
1037 // template out-of-line.
1038 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1039 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1040 : diag::err_member_decl_does_not_match)
1041 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1042 Invalid = true;
1043 }
1044 }
1045
1046 CXXRecordDecl *NewClass =
1047 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1048 PrevClassTemplate?
1049 PrevClassTemplate->getTemplatedDecl() : nullptr,
1050 /*DelayTypeCreation=*/true);
1051 SetNestedNameSpecifier(NewClass, SS);
1052 if (NumOuterTemplateParamLists > 0)
1053 NewClass->setTemplateParameterListsInfo(Context,
1054 NumOuterTemplateParamLists,
1055 OuterTemplateParamLists);
1056
1057 // Add alignment attributes if necessary; these attributes are checked when
1058 // the ASTContext lays out the structure.
1059 if (TUK == TUK_Definition) {
1060 AddAlignmentAttributesForRecord(NewClass);
1061 AddMsStructLayoutForRecord(NewClass);
1062 }
1063
1064 ClassTemplateDecl *NewTemplate
1065 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1066 DeclarationName(Name), TemplateParams,
1067 NewClass, PrevClassTemplate);
1068 NewClass->setDescribedClassTemplate(NewTemplate);
1069
1070 if (ModulePrivateLoc.isValid())
1071 NewTemplate->setModulePrivate();
1072
1073 // Build the type for the class template declaration now.
1074 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1075 T = Context.getInjectedClassNameType(NewClass, T);
1076 assert(T->isDependentType() && "Class template type is not dependent?");
1077 (void)T;
1078
1079 // If we are providing an explicit specialization of a member that is a
1080 // class template, make a note of that.
1081 if (PrevClassTemplate &&
1082 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1083 PrevClassTemplate->setMemberSpecialization();
1084
1085 // Set the access specifier.
1086 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1087 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1088
1089 // Set the lexical context of these templates
1090 NewClass->setLexicalDeclContext(CurContext);
1091 NewTemplate->setLexicalDeclContext(CurContext);
1092
1093 if (TUK == TUK_Definition)
1094 NewClass->startDefinition();
1095
1096 if (Attr)
1097 ProcessDeclAttributeList(S, NewClass, Attr);
1098
1099 if (PrevClassTemplate)
1100 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1101
1102 AddPushedVisibilityAttribute(NewClass);
1103
1104 if (TUK != TUK_Friend) {
1105 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1106 Scope *Outer = S;
1107 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1108 Outer = Outer->getParent();
1109 PushOnScopeChains(NewTemplate, Outer);
1110 } else {
1111 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1112 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1113 NewClass->setAccess(PrevClassTemplate->getAccess());
1114 }
1115
1116 NewTemplate->setObjectOfFriendDecl();
1117
1118 // Friend templates are visible in fairly strange ways.
1119 if (!CurContext->isDependentContext()) {
1120 DeclContext *DC = SemanticContext->getRedeclContext();
1121 DC->makeDeclVisibleInContext(NewTemplate);
1122 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1123 PushOnScopeChains(NewTemplate, EnclosingScope,
1124 /* AddToContext = */ false);
1125 }
1126
1127 FriendDecl *Friend = FriendDecl::Create(
1128 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1129 Friend->setAccess(AS_public);
1130 CurContext->addDecl(Friend);
1131 }
1132
1133 if (Invalid) {
1134 NewTemplate->setInvalidDecl();
1135 NewClass->setInvalidDecl();
1136 }
1137
1138 ActOnDocumentableDecl(NewTemplate);
1139
1140 return NewTemplate;
1141}
1142
1143/// \brief Diagnose the presence of a default template argument on a
1144/// template parameter, which is ill-formed in certain contexts.
1145///
1146/// \returns true if the default template argument should be dropped.
1147static bool DiagnoseDefaultTemplateArgument(Sema &S,
1148 Sema::TemplateParamListContext TPC,
1149 SourceLocation ParamLoc,
1150 SourceRange DefArgRange) {
1151 switch (TPC) {
1152 case Sema::TPC_ClassTemplate:
1153 case Sema::TPC_VarTemplate:
1154 case Sema::TPC_TypeAliasTemplate:
1155 return false;
1156
1157 case Sema::TPC_FunctionTemplate:
1158 case Sema::TPC_FriendFunctionTemplateDefinition:
1159 // C++ [temp.param]p9:
1160 // A default template-argument shall not be specified in a
1161 // function template declaration or a function template
1162 // definition [...]
1163 // If a friend function template declaration specifies a default
1164 // template-argument, that declaration shall be a definition and shall be
1165 // the only declaration of the function template in the translation unit.
1166 // (C++98/03 doesn't have this wording; see DR226).
1167 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1168 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1169 : diag::ext_template_parameter_default_in_function_template)
1170 << DefArgRange;
1171 return false;
1172
1173 case Sema::TPC_ClassTemplateMember:
1174 // C++0x [temp.param]p9:
1175 // A default template-argument shall not be specified in the
1176 // template-parameter-lists of the definition of a member of a
1177 // class template that appears outside of the member's class.
1178 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1179 << DefArgRange;
1180 return true;
1181
1182 case Sema::TPC_FriendClassTemplate:
1183 case Sema::TPC_FriendFunctionTemplate:
1184 // C++ [temp.param]p9:
1185 // A default template-argument shall not be specified in a
1186 // friend template declaration.
1187 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1188 << DefArgRange;
1189 return true;
1190
1191 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1192 // for friend function templates if there is only a single
1193 // declaration (and it is a definition). Strange!
1194 }
1195
1196 llvm_unreachable("Invalid TemplateParamListContext!");
1197}
1198
1199/// \brief Check for unexpanded parameter packs within the template parameters
1200/// of a template template parameter, recursively.
1201static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1202 TemplateTemplateParmDecl *TTP) {
1203 // A template template parameter which is a parameter pack is also a pack
1204 // expansion.
1205 if (TTP->isParameterPack())
1206 return false;
1207
1208 TemplateParameterList *Params = TTP->getTemplateParameters();
1209 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1210 NamedDecl *P = Params->getParam(I);
1211 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1212 if (!NTTP->isParameterPack() &&
1213 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1214 NTTP->getTypeSourceInfo(),
1215 Sema::UPPC_NonTypeTemplateParameterType))
1216 return true;
1217
1218 continue;
1219 }
1220
1221 if (TemplateTemplateParmDecl *InnerTTP
1222 = dyn_cast<TemplateTemplateParmDecl>(P))
1223 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1224 return true;
1225 }
1226
1227 return false;
1228}
1229
1230/// \brief Checks the validity of a template parameter list, possibly
1231/// considering the template parameter list from a previous
1232/// declaration.
1233///
1234/// If an "old" template parameter list is provided, it must be
1235/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1236/// template parameter list.
1237///
1238/// \param NewParams Template parameter list for a new template
1239/// declaration. This template parameter list will be updated with any
1240/// default arguments that are carried through from the previous
1241/// template parameter list.
1242///
1243/// \param OldParams If provided, template parameter list from a
1244/// previous declaration of the same template. Default template
1245/// arguments will be merged from the old template parameter list to
1246/// the new template parameter list.
1247///
1248/// \param TPC Describes the context in which we are checking the given
1249/// template parameter list.
1250///
1251/// \returns true if an error occurred, false otherwise.
1252bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1253 TemplateParameterList *OldParams,
1254 TemplateParamListContext TPC) {
1255 bool Invalid = false;
1256
1257 // C++ [temp.param]p10:
1258 // The set of default template-arguments available for use with a
1259 // template declaration or definition is obtained by merging the
1260 // default arguments from the definition (if in scope) and all
1261 // declarations in scope in the same way default function
1262 // arguments are (8.3.6).
1263 bool SawDefaultArgument = false;
1264 SourceLocation PreviousDefaultArgLoc;
1265
1266 // Dummy initialization to avoid warnings.
1267 TemplateParameterList::iterator OldParam = NewParams->end();
1268 if (OldParams)
1269 OldParam = OldParams->begin();
1270
1271 bool RemoveDefaultArguments = false;
1272 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1273 NewParamEnd = NewParams->end();
1274 NewParam != NewParamEnd; ++NewParam) {
1275 // Variables used to diagnose redundant default arguments
1276 bool RedundantDefaultArg = false;
1277 SourceLocation OldDefaultLoc;
1278 SourceLocation NewDefaultLoc;
1279
1280 // Variable used to diagnose missing default arguments
1281 bool MissingDefaultArg = false;
1282
1283 // Variable used to diagnose non-final parameter packs
1284 bool SawParameterPack = false;
1285
1286 if (TemplateTypeParmDecl *NewTypeParm
1287 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1288 // Check the presence of a default argument here.
1289 if (NewTypeParm->hasDefaultArgument() &&
1290 DiagnoseDefaultTemplateArgument(*this, TPC,
1291 NewTypeParm->getLocation(),
1292 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1293 .getSourceRange()))
1294 NewTypeParm->removeDefaultArgument();
1295
1296 // Merge default arguments for template type parameters.
1297 TemplateTypeParmDecl *OldTypeParm
1298 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1299
1300 if (NewTypeParm->isParameterPack()) {
1301 assert(!NewTypeParm->hasDefaultArgument() &&
1302 "Parameter packs can't have a default argument!");
1303 SawParameterPack = true;
1304 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1305 NewTypeParm->hasDefaultArgument()) {
1306 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1307 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1308 SawDefaultArgument = true;
1309 RedundantDefaultArg = true;
1310 PreviousDefaultArgLoc = NewDefaultLoc;
1311 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1312 // Merge the default argument from the old declaration to the
1313 // new declaration.
1314 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1315 true);
1316 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1317 } else if (NewTypeParm->hasDefaultArgument()) {
1318 SawDefaultArgument = true;
1319 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1320 } else if (SawDefaultArgument)
1321 MissingDefaultArg = true;
1322 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1323 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1324 // Check for unexpanded parameter packs.
1325 if (!NewNonTypeParm->isParameterPack() &&
1326 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1327 NewNonTypeParm->getTypeSourceInfo(),
1328 UPPC_NonTypeTemplateParameterType)) {
1329 Invalid = true;
1330 continue;
1331 }
1332
1333 // Check the presence of a default argument here.
1334 if (NewNonTypeParm->hasDefaultArgument() &&
1335 DiagnoseDefaultTemplateArgument(*this, TPC,
1336 NewNonTypeParm->getLocation(),
1337 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1338 NewNonTypeParm->removeDefaultArgument();
1339 }
1340
1341 // Merge default arguments for non-type template parameters
1342 NonTypeTemplateParmDecl *OldNonTypeParm
1343 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1344 if (NewNonTypeParm->isParameterPack()) {
1345 assert(!NewNonTypeParm->hasDefaultArgument() &&
1346 "Parameter packs can't have a default argument!");
1347 if (!NewNonTypeParm->isPackExpansion())
1348 SawParameterPack = true;
1349 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1350 NewNonTypeParm->hasDefaultArgument()) {
1351 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1352 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1353 SawDefaultArgument = true;
1354 RedundantDefaultArg = true;
1355 PreviousDefaultArgLoc = NewDefaultLoc;
1356 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1357 // Merge the default argument from the old declaration to the
1358 // new declaration.
1359 // FIXME: We need to create a new kind of "default argument"
1360 // expression that points to a previous non-type template
1361 // parameter.
1362 NewNonTypeParm->setDefaultArgument(
1363 OldNonTypeParm->getDefaultArgument(),
1364 /*Inherited=*/ true);
1365 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1366 } else if (NewNonTypeParm->hasDefaultArgument()) {
1367 SawDefaultArgument = true;
1368 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1369 } else if (SawDefaultArgument)
1370 MissingDefaultArg = true;
1371 } else {
1372 TemplateTemplateParmDecl *NewTemplateParm
1373 = cast<TemplateTemplateParmDecl>(*NewParam);
1374
1375 // Check for unexpanded parameter packs, recursively.
1376 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1377 Invalid = true;
1378 continue;
1379 }
1380
1381 // Check the presence of a default argument here.
1382 if (NewTemplateParm->hasDefaultArgument() &&
1383 DiagnoseDefaultTemplateArgument(*this, TPC,
1384 NewTemplateParm->getLocation(),
1385 NewTemplateParm->getDefaultArgument().getSourceRange()))
1386 NewTemplateParm->removeDefaultArgument();
1387
1388 // Merge default arguments for template template parameters
1389 TemplateTemplateParmDecl *OldTemplateParm
1390 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1391 if (NewTemplateParm->isParameterPack()) {
1392 assert(!NewTemplateParm->hasDefaultArgument() &&
1393 "Parameter packs can't have a default argument!");
1394 if (!NewTemplateParm->isPackExpansion())
1395 SawParameterPack = true;
1396 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1397 NewTemplateParm->hasDefaultArgument()) {
1398 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1399 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1400 SawDefaultArgument = true;
1401 RedundantDefaultArg = true;
1402 PreviousDefaultArgLoc = NewDefaultLoc;
1403 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1404 // Merge the default argument from the old declaration to the
1405 // new declaration.
1406 // FIXME: We need to create a new kind of "default argument" expression
1407 // that points to a previous template template parameter.
1408 NewTemplateParm->setDefaultArgument(
1409 OldTemplateParm->getDefaultArgument(),
1410 /*Inherited=*/ true);
1411 PreviousDefaultArgLoc
1412 = OldTemplateParm->getDefaultArgument().getLocation();
1413 } else if (NewTemplateParm->hasDefaultArgument()) {
1414 SawDefaultArgument = true;
1415 PreviousDefaultArgLoc
1416 = NewTemplateParm->getDefaultArgument().getLocation();
1417 } else if (SawDefaultArgument)
1418 MissingDefaultArg = true;
1419 }
1420
1421 // C++11 [temp.param]p11:
1422 // If a template parameter of a primary class template or alias template
1423 // is a template parameter pack, it shall be the last template parameter.
1424 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1425 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1426 TPC == TPC_TypeAliasTemplate)) {
1427 Diag((*NewParam)->getLocation(),
1428 diag::err_template_param_pack_must_be_last_template_parameter);
1429 Invalid = true;
1430 }
1431
1432 if (RedundantDefaultArg) {
1433 // C++ [temp.param]p12:
1434 // A template-parameter shall not be given default arguments
1435 // by two different declarations in the same scope.
1436 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1437 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1438 Invalid = true;
1439 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1440 // C++ [temp.param]p11:
1441 // If a template-parameter of a class template has a default
1442 // template-argument, each subsequent template-parameter shall either
1443 // have a default template-argument supplied or be a template parameter
1444 // pack.
1445 Diag((*NewParam)->getLocation(),
1446 diag::err_template_param_default_arg_missing);
1447 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1448 Invalid = true;
1449 RemoveDefaultArguments = true;
1450 }
1451
1452 // If we have an old template parameter list that we're merging
1453 // in, move on to the next parameter.
1454 if (OldParams)
1455 ++OldParam;
1456 }
1457
1458 // We were missing some default arguments at the end of the list, so remove
1459 // all of the default arguments.
1460 if (RemoveDefaultArguments) {
1461 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1462 NewParamEnd = NewParams->end();
1463 NewParam != NewParamEnd; ++NewParam) {
1464 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1465 TTP->removeDefaultArgument();
1466 else if (NonTypeTemplateParmDecl *NTTP
1467 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1468 NTTP->removeDefaultArgument();
1469 else
1470 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1471 }
1472 }
1473
1474 return Invalid;
1475}
1476
1477namespace {
1478
1479/// A class which looks for a use of a certain level of template
1480/// parameter.
1481struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1482 typedef RecursiveASTVisitor<DependencyChecker> super;
1483
1484 unsigned Depth;
1485 bool Match;
1486 SourceLocation MatchLoc;
1487
1488 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1489
1490 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1491 NamedDecl *ND = Params->getParam(0);
1492 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1493 Depth = PD->getDepth();
1494 } else if (NonTypeTemplateParmDecl *PD =
1495 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1496 Depth = PD->getDepth();
1497 } else {
1498 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1499 }
1500 }
1501
1502 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1503 if (ParmDepth >= Depth) {
1504 Match = true;
1505 MatchLoc = Loc;
1506 return true;
1507 }
1508 return false;
1509 }
1510
1511 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1512 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1513 }
1514
1515 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1516 return !Matches(T->getDepth());
1517 }
1518
1519 bool TraverseTemplateName(TemplateName N) {
1520 if (TemplateTemplateParmDecl *PD =
1521 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1522 if (Matches(PD->getDepth()))
1523 return false;
1524 return super::TraverseTemplateName(N);
1525 }
1526
1527 bool VisitDeclRefExpr(DeclRefExpr *E) {
1528 if (NonTypeTemplateParmDecl *PD =
1529 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1530 if (Matches(PD->getDepth(), E->getExprLoc()))
1531 return false;
1532 return super::VisitDeclRefExpr(E);
1533 }
1534
1535 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1536 return TraverseType(T->getReplacementType());
1537 }
1538
1539 bool
1540 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1541 return TraverseTemplateArgument(T->getArgumentPack());
1542 }
1543
1544 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1545 return TraverseType(T->getInjectedSpecializationType());
1546 }
1547};
1548}
1549
1550/// Determines whether a given type depends on the given parameter
1551/// list.
1552static bool
1553DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1554 DependencyChecker Checker(Params);
1555 Checker.TraverseType(T);
1556 return Checker.Match;
1557}
1558
1559// Find the source range corresponding to the named type in the given
1560// nested-name-specifier, if any.
1561static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1562 QualType T,
1563 const CXXScopeSpec &SS) {
1564 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1565 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1566 if (const Type *CurType = NNS->getAsType()) {
1567 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1568 return NNSLoc.getTypeLoc().getSourceRange();
1569 } else
1570 break;
1571
1572 NNSLoc = NNSLoc.getPrefix();
1573 }
1574
1575 return SourceRange();
1576}
1577
1578/// \brief Match the given template parameter lists to the given scope
1579/// specifier, returning the template parameter list that applies to the
1580/// name.
1581///
1582/// \param DeclStartLoc the start of the declaration that has a scope
1583/// specifier or a template parameter list.
1584///
1585/// \param DeclLoc The location of the declaration itself.
1586///
1587/// \param SS the scope specifier that will be matched to the given template
1588/// parameter lists. This scope specifier precedes a qualified name that is
1589/// being declared.
1590///
1591/// \param TemplateId The template-id following the scope specifier, if there
1592/// is one. Used to check for a missing 'template<>'.
1593///
1594/// \param ParamLists the template parameter lists, from the outermost to the
1595/// innermost template parameter lists.
1596///
1597/// \param IsFriend Whether to apply the slightly different rules for
1598/// matching template parameters to scope specifiers in friend
1599/// declarations.
1600///
1601/// \param IsExplicitSpecialization will be set true if the entity being
1602/// declared is an explicit specialization, false otherwise.
1603///
1604/// \returns the template parameter list, if any, that corresponds to the
1605/// name that is preceded by the scope specifier @p SS. This template
1606/// parameter list may have template parameters (if we're declaring a
1607/// template) or may have no template parameters (if we're declaring a
1608/// template specialization), or may be NULL (if what we're declaring isn't
1609/// itself a template).
1610TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1611 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1612 TemplateIdAnnotation *TemplateId,
1613 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1614 bool &IsExplicitSpecialization, bool &Invalid) {
1615 IsExplicitSpecialization = false;
1616 Invalid = false;
1617
1618 // The sequence of nested types to which we will match up the template
1619 // parameter lists. We first build this list by starting with the type named
1620 // by the nested-name-specifier and walking out until we run out of types.
1621 SmallVector<QualType, 4> NestedTypes;
1622 QualType T;
1623 if (SS.getScopeRep()) {
1624 if (CXXRecordDecl *Record
1625 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1626 T = Context.getTypeDeclType(Record);
1627 else
1628 T = QualType(SS.getScopeRep()->getAsType(), 0);
1629 }
1630
1631 // If we found an explicit specialization that prevents us from needing
1632 // 'template<>' headers, this will be set to the location of that
1633 // explicit specialization.
1634 SourceLocation ExplicitSpecLoc;
1635
1636 while (!T.isNull()) {
1637 NestedTypes.push_back(T);
1638
1639 // Retrieve the parent of a record type.
1640 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1641 // If this type is an explicit specialization, we're done.
1642 if (ClassTemplateSpecializationDecl *Spec
1643 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1644 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1645 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1646 ExplicitSpecLoc = Spec->getLocation();
1647 break;
1648 }
1649 } else if (Record->getTemplateSpecializationKind()
1650 == TSK_ExplicitSpecialization) {
1651 ExplicitSpecLoc = Record->getLocation();
1652 break;
1653 }
1654
1655 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1656 T = Context.getTypeDeclType(Parent);
1657 else
1658 T = QualType();
1659 continue;
1660 }
1661
1662 if (const TemplateSpecializationType *TST
1663 = T->getAs<TemplateSpecializationType>()) {
1664 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1665 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1666 T = Context.getTypeDeclType(Parent);
1667 else
1668 T = QualType();
1669 continue;
1670 }
1671 }
1672
1673 // Look one step prior in a dependent template specialization type.
1674 if (const DependentTemplateSpecializationType *DependentTST
1675 = T->getAs<DependentTemplateSpecializationType>()) {
1676 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1677 T = QualType(NNS->getAsType(), 0);
1678 else
1679 T = QualType();
1680 continue;
1681 }
1682
1683 // Look one step prior in a dependent name type.
1684 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1685 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1686 T = QualType(NNS->getAsType(), 0);
1687 else
1688 T = QualType();
1689 continue;
1690 }
1691
1692 // Retrieve the parent of an enumeration type.
1693 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1694 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1695 // check here.
1696 EnumDecl *Enum = EnumT->getDecl();
1697
1698 // Get to the parent type.
1699 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1700 T = Context.getTypeDeclType(Parent);
1701 else
1702 T = QualType();
1703 continue;
1704 }
1705
1706 T = QualType();
1707 }
1708 // Reverse the nested types list, since we want to traverse from the outermost
1709 // to the innermost while checking template-parameter-lists.
1710 std::reverse(NestedTypes.begin(), NestedTypes.end());
1711
1712 // C++0x [temp.expl.spec]p17:
1713 // A member or a member template may be nested within many
1714 // enclosing class templates. In an explicit specialization for
1715 // such a member, the member declaration shall be preceded by a
1716 // template<> for each enclosing class template that is
1717 // explicitly specialized.
1718 bool SawNonEmptyTemplateParameterList = false;
1719
1720 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1721 if (SawNonEmptyTemplateParameterList) {
1722 Diag(DeclLoc, diag::err_specialize_member_of_template)
1723 << !Recovery << Range;
1724 Invalid = true;
1725 IsExplicitSpecialization = false;
1726 return true;
1727 }
1728
1729 return false;
1730 };
1731
1732 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1733 // Check that we can have an explicit specialization here.
1734 if (CheckExplicitSpecialization(Range, true))
1735 return true;
1736
1737 // We don't have a template header, but we should.
1738 SourceLocation ExpectedTemplateLoc;
1739 if (!ParamLists.empty())
1740 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1741 else
1742 ExpectedTemplateLoc = DeclStartLoc;
1743
1744 Diag(DeclLoc, diag::err_template_spec_needs_header)
1745 << Range
1746 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1747 return false;
1748 };
1749
1750 unsigned ParamIdx = 0;
1751 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1752 ++TypeIdx) {
1753 T = NestedTypes[TypeIdx];
1754
1755 // Whether we expect a 'template<>' header.
1756 bool NeedEmptyTemplateHeader = false;
1757
1758 // Whether we expect a template header with parameters.
1759 bool NeedNonemptyTemplateHeader = false;
1760
1761 // For a dependent type, the set of template parameters that we
1762 // expect to see.
1763 TemplateParameterList *ExpectedTemplateParams = nullptr;
1764
1765 // C++0x [temp.expl.spec]p15:
1766 // A member or a member template may be nested within many enclosing
1767 // class templates. In an explicit specialization for such a member, the
1768 // member declaration shall be preceded by a template<> for each
1769 // enclosing class template that is explicitly specialized.
1770 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1771 if (ClassTemplatePartialSpecializationDecl *Partial
1772 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1773 ExpectedTemplateParams = Partial->getTemplateParameters();
1774 NeedNonemptyTemplateHeader = true;
1775 } else if (Record->isDependentType()) {
1776 if (Record->getDescribedClassTemplate()) {
1777 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1778 ->getTemplateParameters();
1779 NeedNonemptyTemplateHeader = true;
1780 }
1781 } else if (ClassTemplateSpecializationDecl *Spec
1782 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1783 // C++0x [temp.expl.spec]p4:
1784 // Members of an explicitly specialized class template are defined
1785 // in the same manner as members of normal classes, and not using
1786 // the template<> syntax.
1787 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1788 NeedEmptyTemplateHeader = true;
1789 else
1790 continue;
1791 } else if (Record->getTemplateSpecializationKind()) {
1792 if (Record->getTemplateSpecializationKind()
1793 != TSK_ExplicitSpecialization &&
1794 TypeIdx == NumTypes - 1)
1795 IsExplicitSpecialization = true;
1796
1797 continue;
1798 }
1799 } else if (const TemplateSpecializationType *TST
1800 = T->getAs<TemplateSpecializationType>()) {
1801 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1802 ExpectedTemplateParams = Template->getTemplateParameters();
1803 NeedNonemptyTemplateHeader = true;
1804 }
1805 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1806 // FIXME: We actually could/should check the template arguments here
1807 // against the corresponding template parameter list.
1808 NeedNonemptyTemplateHeader = false;
1809 }
1810
1811 // C++ [temp.expl.spec]p16:
1812 // In an explicit specialization declaration for a member of a class
1813 // template or a member template that ap- pears in namespace scope, the
1814 // member template and some of its enclosing class templates may remain
1815 // unspecialized, except that the declaration shall not explicitly
1816 // specialize a class member template if its en- closing class templates
1817 // are not explicitly specialized as well.
1818 if (ParamIdx < ParamLists.size()) {
1819 if (ParamLists[ParamIdx]->size() == 0) {
1820 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1821 false))
1822 return nullptr;
1823 } else
1824 SawNonEmptyTemplateParameterList = true;
1825 }
1826
1827 if (NeedEmptyTemplateHeader) {
1828 // If we're on the last of the types, and we need a 'template<>' header
1829 // here, then it's an explicit specialization.
1830 if (TypeIdx == NumTypes - 1)
1831 IsExplicitSpecialization = true;
1832
1833 if (ParamIdx < ParamLists.size()) {
1834 if (ParamLists[ParamIdx]->size() > 0) {
1835 // The header has template parameters when it shouldn't. Complain.
1836 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1837 diag::err_template_param_list_matches_nontemplate)
1838 << T
1839 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1840 ParamLists[ParamIdx]->getRAngleLoc())
1841 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1842 Invalid = true;
1843 return nullptr;
1844 }
1845
1846 // Consume this template header.
1847 ++ParamIdx;
1848 continue;
1849 }
1850
1851 if (!IsFriend)
1852 if (DiagnoseMissingExplicitSpecialization(
1853 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1854 return nullptr;
1855
1856 continue;
1857 }
1858
1859 if (NeedNonemptyTemplateHeader) {
1860 // In friend declarations we can have template-ids which don't
1861 // depend on the corresponding template parameter lists. But
1862 // assume that empty parameter lists are supposed to match this
1863 // template-id.
1864 if (IsFriend && T->isDependentType()) {
1865 if (ParamIdx < ParamLists.size() &&
1866 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1867 ExpectedTemplateParams = nullptr;
1868 else
1869 continue;
1870 }
1871
1872 if (ParamIdx < ParamLists.size()) {
1873 // Check the template parameter list, if we can.
1874 if (ExpectedTemplateParams &&
1875 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1876 ExpectedTemplateParams,
1877 true, TPL_TemplateMatch))
1878 Invalid = true;
1879
1880 if (!Invalid &&
1881 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1882 TPC_ClassTemplateMember))
1883 Invalid = true;
1884
1885 ++ParamIdx;
1886 continue;
1887 }
1888
1889 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1890 << T
1891 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1892 Invalid = true;
1893 continue;
1894 }
1895 }
1896
1897 // If there were at least as many template-ids as there were template
1898 // parameter lists, then there are no template parameter lists remaining for
1899 // the declaration itself.
1900 if (ParamIdx >= ParamLists.size()) {
1901 if (TemplateId && !IsFriend) {
1902 // We don't have a template header for the declaration itself, but we
1903 // should.
1904 IsExplicitSpecialization = true;
1905 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1906 TemplateId->RAngleLoc));
1907
1908 // Fabricate an empty template parameter list for the invented header.
1909 return TemplateParameterList::Create(Context, SourceLocation(),
1910 SourceLocation(), nullptr, 0,
1911 SourceLocation());
1912 }
1913
1914 return nullptr;
1915 }
1916
1917 // If there were too many template parameter lists, complain about that now.
1918 if (ParamIdx < ParamLists.size() - 1) {
1919 bool HasAnyExplicitSpecHeader = false;
1920 bool AllExplicitSpecHeaders = true;
1921 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1922 if (ParamLists[I]->size() == 0)
1923 HasAnyExplicitSpecHeader = true;
1924 else
1925 AllExplicitSpecHeaders = false;
1926 }
1927
1928 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1929 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1930 : diag::err_template_spec_extra_headers)
1931 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1932 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1933
1934 // If there was a specialization somewhere, such that 'template<>' is
1935 // not required, and there were any 'template<>' headers, note where the
1936 // specialization occurred.
1937 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1938 Diag(ExplicitSpecLoc,
1939 diag::note_explicit_template_spec_does_not_need_header)
1940 << NestedTypes.back();
1941
1942 // We have a template parameter list with no corresponding scope, which
1943 // means that the resulting template declaration can't be instantiated
1944 // properly (we'll end up with dependent nodes when we shouldn't).
1945 if (!AllExplicitSpecHeaders)
1946 Invalid = true;
1947 }
1948
1949 // C++ [temp.expl.spec]p16:
1950 // In an explicit specialization declaration for a member of a class
1951 // template or a member template that ap- pears in namespace scope, the
1952 // member template and some of its enclosing class templates may remain
1953 // unspecialized, except that the declaration shall not explicitly
1954 // specialize a class member template if its en- closing class templates
1955 // are not explicitly specialized as well.
1956 if (ParamLists.back()->size() == 0 &&
1957 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1958 false))
1959 return nullptr;
1960
1961 // Return the last template parameter list, which corresponds to the
1962 // entity being declared.
1963 return ParamLists.back();
1964}
1965
1966void Sema::NoteAllFoundTemplates(TemplateName Name) {
1967 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1968 Diag(Template->getLocation(), diag::note_template_declared_here)
1969 << (isa<FunctionTemplateDecl>(Template)
1970 ? 0
1971 : isa<ClassTemplateDecl>(Template)
1972 ? 1
1973 : isa<VarTemplateDecl>(Template)
1974 ? 2
1975 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1976 << Template->getDeclName();
1977 return;
1978 }
1979
1980 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1981 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1982 IEnd = OST->end();
1983 I != IEnd; ++I)
1984 Diag((*I)->getLocation(), diag::note_template_declared_here)
1985 << 0 << (*I)->getDeclName();
1986
1987 return;
1988 }
1989}
1990
1991QualType Sema::CheckTemplateIdType(TemplateName Name,
1992 SourceLocation TemplateLoc,
1993 TemplateArgumentListInfo &TemplateArgs) {
1994 DependentTemplateName *DTN
1995 = Name.getUnderlying().getAsDependentTemplateName();
1996 if (DTN && DTN->isIdentifier())
1997 // When building a template-id where the template-name is dependent,
1998 // assume the template is a type template. Either our assumption is
1999 // correct, or the code is ill-formed and will be diagnosed when the
2000 // dependent name is substituted.
2001 return Context.getDependentTemplateSpecializationType(ETK_None,
2002 DTN->getQualifier(),
2003 DTN->getIdentifier(),
2004 TemplateArgs);
2005
2006 TemplateDecl *Template = Name.getAsTemplateDecl();
2007 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2008 isa<VarTemplateDecl>(Template)) {
2009 // We might have a substituted template template parameter pack. If so,
2010 // build a template specialization type for it.
2011 if (Name.getAsSubstTemplateTemplateParmPack())
2012 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2013
2014 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2015 << Name;
2016 NoteAllFoundTemplates(Name);
2017 return QualType();
2018 }
2019
2020 // Check that the template argument list is well-formed for this
2021 // template.
2022 SmallVector<TemplateArgument, 4> Converted;
2023 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2024 false, Converted))
2025 return QualType();
2026
2027 QualType CanonType;
2028
2029 bool InstantiationDependent = false;
2030 if (TypeAliasTemplateDecl *AliasTemplate =
2031 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2032 // Find the canonical type for this type alias template specialization.
2033 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2034 if (Pattern->isInvalidDecl())
2035 return QualType();
2036
2037 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2038 Converted.data(), Converted.size());
2039
2040 // Only substitute for the innermost template argument list.
2041 MultiLevelTemplateArgumentList TemplateArgLists;
2042 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2043 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2044 for (unsigned I = 0; I < Depth; ++I)
2045 TemplateArgLists.addOuterTemplateArguments(None);
2046
2047 LocalInstantiationScope Scope(*this);
2048 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2049 if (Inst.isInvalid())
2050 return QualType();
2051
2052 CanonType = SubstType(Pattern->getUnderlyingType(),
2053 TemplateArgLists, AliasTemplate->getLocation(),
2054 AliasTemplate->getDeclName());
2055 if (CanonType.isNull())
2056 return QualType();
2057 } else if (Name.isDependent() ||
2058 TemplateSpecializationType::anyDependentTemplateArguments(
2059 TemplateArgs, InstantiationDependent)) {
2060 // This class template specialization is a dependent
2061 // type. Therefore, its canonical type is another class template
2062 // specialization type that contains all of the converted
2063 // arguments in canonical form. This ensures that, e.g., A<T> and
2064 // A<T, T> have identical types when A is declared as:
2065 //
2066 // template<typename T, typename U = T> struct A;
2067 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2068 CanonType = Context.getTemplateSpecializationType(CanonName,
2069 Converted.data(),
2070 Converted.size());
2071
2072 // FIXME: CanonType is not actually the canonical type, and unfortunately
2073 // it is a TemplateSpecializationType that we will never use again.
2074 // In the future, we need to teach getTemplateSpecializationType to only
2075 // build the canonical type and return that to us.
2076 CanonType = Context.getCanonicalType(CanonType);
2077
2078 // This might work out to be a current instantiation, in which
2079 // case the canonical type needs to be the InjectedClassNameType.
2080 //
2081 // TODO: in theory this could be a simple hashtable lookup; most
2082 // changes to CurContext don't change the set of current
2083 // instantiations.
2084 if (isa<ClassTemplateDecl>(Template)) {
2085 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2086 // If we get out to a namespace, we're done.
2087 if (Ctx->isFileContext()) break;
2088
2089 // If this isn't a record, keep looking.
2090 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2091 if (!Record) continue;
2092
2093 // Look for one of the two cases with InjectedClassNameTypes
2094 // and check whether it's the same template.
2095 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2096 !Record->getDescribedClassTemplate())
2097 continue;
2098
2099 // Fetch the injected class name type and check whether its
2100 // injected type is equal to the type we just built.
2101 QualType ICNT = Context.getTypeDeclType(Record);
2102 QualType Injected = cast<InjectedClassNameType>(ICNT)
2103 ->getInjectedSpecializationType();
2104
2105 if (CanonType != Injected->getCanonicalTypeInternal())
2106 continue;
2107
2108 // If so, the canonical type of this TST is the injected
2109 // class name type of the record we just found.
2110 assert(ICNT.isCanonical());
2111 CanonType = ICNT;
2112 break;
2113 }
2114 }
2115 } else if (ClassTemplateDecl *ClassTemplate
2116 = dyn_cast<ClassTemplateDecl>(Template)) {
2117 // Find the class template specialization declaration that
2118 // corresponds to these arguments.
2119 void *InsertPos = nullptr;
2120 ClassTemplateSpecializationDecl *Decl
2121 = ClassTemplate->findSpecialization(Converted, InsertPos);
2122 if (!Decl) {
2123 // This is the first time we have referenced this class template
2124 // specialization. Create the canonical declaration and add it to
2125 // the set of specializations.
2126 Decl = ClassTemplateSpecializationDecl::Create(Context,
2127 ClassTemplate->getTemplatedDecl()->getTagKind(),
2128 ClassTemplate->getDeclContext(),
2129 ClassTemplate->getTemplatedDecl()->getLocStart(),
2130 ClassTemplate->getLocation(),
2131 ClassTemplate,
2132 Converted.data(),
2133 Converted.size(), nullptr);
2134 ClassTemplate->AddSpecialization(Decl, InsertPos);
2135 if (ClassTemplate->isOutOfLine())
2136 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2137 }
2138
2139 // Diagnose uses of this specialization.
2140 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2141
2142 CanonType = Context.getTypeDeclType(Decl);
2143 assert(isa<RecordType>(CanonType) &&
2144 "type of non-dependent specialization is not a RecordType");
2145 }
2146
2147 // Build the fully-sugared type for this class template
2148 // specialization, which refers back to the class template
2149 // specialization we created or found.
2150 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2151}
2152
2153TypeResult
2154Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2155 TemplateTy TemplateD, SourceLocation TemplateLoc,
2156 SourceLocation LAngleLoc,
2157 ASTTemplateArgsPtr TemplateArgsIn,
2158 SourceLocation RAngleLoc,
2159 bool IsCtorOrDtorName) {
2160 if (SS.isInvalid())
2161 return true;
2162
2163 TemplateName Template = TemplateD.get();
2164
2165 // Translate the parser's template argument list in our AST format.
2166 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2167 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2168
2169 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2170 QualType T
2171 = Context.getDependentTemplateSpecializationType(ETK_None,
2172 DTN->getQualifier(),
2173 DTN->getIdentifier(),
2174 TemplateArgs);
2175 // Build type-source information.
2176 TypeLocBuilder TLB;
2177 DependentTemplateSpecializationTypeLoc SpecTL
2178 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2179 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2180 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2181 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2182 SpecTL.setTemplateNameLoc(TemplateLoc);
2183 SpecTL.setLAngleLoc(LAngleLoc);
2184 SpecTL.setRAngleLoc(RAngleLoc);
2185 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2186 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2187 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2188 }
2189
2190 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2191
2192 if (Result.isNull())
2193 return true;
2194
2195 // Build type-source information.
2196 TypeLocBuilder TLB;
2197 TemplateSpecializationTypeLoc SpecTL
2198 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2199 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2200 SpecTL.setTemplateNameLoc(TemplateLoc);
2201 SpecTL.setLAngleLoc(LAngleLoc);
2202 SpecTL.setRAngleLoc(RAngleLoc);
2203 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2204 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2205
2206 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2207 // constructor or destructor name (in such a case, the scope specifier
2208 // will be attached to the enclosing Decl or Expr node).
2209 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2210 // Create an elaborated-type-specifier containing the nested-name-specifier.
2211 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2212 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2213 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2214 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2215 }
2216
2217 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2218}
2219
2220TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2221 TypeSpecifierType TagSpec,
2222 SourceLocation TagLoc,
2223 CXXScopeSpec &SS,
2224 SourceLocation TemplateKWLoc,
2225 TemplateTy TemplateD,
2226 SourceLocation TemplateLoc,
2227 SourceLocation LAngleLoc,
2228 ASTTemplateArgsPtr TemplateArgsIn,
2229 SourceLocation RAngleLoc) {
2230 TemplateName Template = TemplateD.get();
2231
2232 // Translate the parser's template argument list in our AST format.
2233 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2234 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2235
2236 // Determine the tag kind
2237 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2238 ElaboratedTypeKeyword Keyword
2239 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2240
2241 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2242 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2243 DTN->getQualifier(),
2244 DTN->getIdentifier(),
2245 TemplateArgs);
2246
2247 // Build type-source information.
2248 TypeLocBuilder TLB;
2249 DependentTemplateSpecializationTypeLoc SpecTL
2250 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2251 SpecTL.setElaboratedKeywordLoc(TagLoc);
2252 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2253 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2254 SpecTL.setTemplateNameLoc(TemplateLoc);
2255 SpecTL.setLAngleLoc(LAngleLoc);
2256 SpecTL.setRAngleLoc(RAngleLoc);
2257 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2258 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2259 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2260 }
2261
2262 if (TypeAliasTemplateDecl *TAT =
2263 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2264 // C++0x [dcl.type.elab]p2:
2265 // If the identifier resolves to a typedef-name or the simple-template-id
2266 // resolves to an alias template specialization, the
2267 // elaborated-type-specifier is ill-formed.
2268 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2269 Diag(TAT->getLocation(), diag::note_declared_at);
2270 }
2271
2272 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2273 if (Result.isNull())
2274 return TypeResult(true);
2275
2276 // Check the tag kind
2277 if (const RecordType *RT = Result->getAs<RecordType>()) {
2278 RecordDecl *D = RT->getDecl();
2279
2280 IdentifierInfo *Id = D->getIdentifier();
2281 assert(Id && "templated class must have an identifier");
2282
2283 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2284 TagLoc, *Id)) {
2285 Diag(TagLoc, diag::err_use_with_wrong_tag)
2286 << Result
2287 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2288 Diag(D->getLocation(), diag::note_previous_use);
2289 }
2290 }
2291
2292 // Provide source-location information for the template specialization.
2293 TypeLocBuilder TLB;
2294 TemplateSpecializationTypeLoc SpecTL
2295 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2296 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2297 SpecTL.setTemplateNameLoc(TemplateLoc);
2298 SpecTL.setLAngleLoc(LAngleLoc);
2299 SpecTL.setRAngleLoc(RAngleLoc);
2300 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2301 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2302
2303 // Construct an elaborated type containing the nested-name-specifier (if any)
2304 // and tag keyword.
2305 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2306 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2307 ElabTL.setElaboratedKeywordLoc(TagLoc);
2308 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2309 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2310}
2311
2312static bool CheckTemplatePartialSpecializationArgs(
2313 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2314 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2315
2316static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2317 NamedDecl *PrevDecl,
2318 SourceLocation Loc,
2319 bool IsPartialSpecialization);
2320
2321static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2322
2323static bool isTemplateArgumentTemplateParameter(
2324 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2325 switch (Arg.getKind()) {
2326 case TemplateArgument::Null:
2327 case TemplateArgument::NullPtr:
2328 case TemplateArgument::Integral:
2329 case TemplateArgument::Declaration:
2330 case TemplateArgument::Pack:
2331 case TemplateArgument::TemplateExpansion:
2332 return false;
2333
2334 case TemplateArgument::Type: {
2335 QualType Type = Arg.getAsType();
2336 const TemplateTypeParmType *TPT =
2337 Arg.getAsType()->getAs<TemplateTypeParmType>();
2338 return TPT && !Type.hasQualifiers() &&
2339 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2340 }
2341
2342 case TemplateArgument::Expression: {
2343 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2344 if (!DRE || !DRE->getDecl())
2345 return false;
2346 const NonTypeTemplateParmDecl *NTTP =
2347 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2348 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2349 }
2350
2351 case TemplateArgument::Template:
2352 const TemplateTemplateParmDecl *TTP =
2353 dyn_cast_or_null<TemplateTemplateParmDecl>(
2354 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2355 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2356 }
2357 llvm_unreachable("unexpected kind of template argument");
2358}
2359
2360static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2361 ArrayRef<TemplateArgument> Args) {
2362 if (Params->size() != Args.size())
2363 return false;
2364
2365 unsigned Depth = Params->getDepth();
2366
2367 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2368 TemplateArgument Arg = Args[I];
2369
2370 // If the parameter is a pack expansion, the argument must be a pack
2371 // whose only element is a pack expansion.
2372 if (Params->getParam(I)->isParameterPack()) {
2373 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2374 !Arg.pack_begin()->isPackExpansion())
2375 return false;
2376 Arg = Arg.pack_begin()->getPackExpansionPattern();
2377 }
2378
2379 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2380 return false;
2381 }
2382
2383 return true;
2384}
2385
2386/// Convert the parser's template argument list representation into our form.
2387static TemplateArgumentListInfo
2388makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2389 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2390 TemplateId.RAngleLoc);
2391 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2392 TemplateId.NumArgs);
2393 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2394 return TemplateArgs;
2395}
2396
2397DeclResult Sema::ActOnVarTemplateSpecialization(
2398 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2399 TemplateParameterList *TemplateParams, StorageClass SC,
2400 bool IsPartialSpecialization) {
2401 // D must be variable template id.
2402 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2403 "Variable template specialization is declared with a template it.");
2404
2405 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2406 TemplateArgumentListInfo TemplateArgs =
2407 makeTemplateArgumentListInfo(*this, *TemplateId);
2408 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2409 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2410 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2411
2412 TemplateName Name = TemplateId->Template.get();
2413
2414 // The template-id must name a variable template.
2415 VarTemplateDecl *VarTemplate =
2416 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2417 if (!VarTemplate) {
2418 NamedDecl *FnTemplate;
2419 if (auto *OTS = Name.getAsOverloadedTemplate())
2420 FnTemplate = *OTS->begin();
2421 else
2422 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2423 if (FnTemplate)
2424 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2425 << FnTemplate->getDeclName();
2426 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2427 << IsPartialSpecialization;
2428 }
2429
2430 // Check for unexpanded parameter packs in any of the template arguments.
2431 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2432 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2433 UPPC_PartialSpecialization))
2434 return true;
2435
2436 // Check that the template argument list is well-formed for this
2437 // template.
2438 SmallVector<TemplateArgument, 4> Converted;
2439 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2440 false, Converted))
2441 return true;
2442
2443 // Check that the type of this variable template specialization
2444 // matches the expected type.
2445 TypeSourceInfo *ExpectedDI;
2446 {
2447 // Do substitution on the type of the declaration
2448 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2449 Converted.data(), Converted.size());
2450 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
2451 if (Inst.isInvalid())
2452 return true;
2453 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2454 ExpectedDI =
2455 SubstType(Templated->getTypeSourceInfo(),
2456 MultiLevelTemplateArgumentList(TemplateArgList),
2457 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2458 }
2459 if (!ExpectedDI)
2460 return true;
2461
2462 // Find the variable template (partial) specialization declaration that
2463 // corresponds to these arguments.
2464 if (IsPartialSpecialization) {
2465 if (CheckTemplatePartialSpecializationArgs(
2466 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2467 TemplateArgs.size(), Converted))
2468 return true;
2469
2470 bool InstantiationDependent;
2471 if (!Name.isDependent() &&
2472 !TemplateSpecializationType::anyDependentTemplateArguments(
2473 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2474 InstantiationDependent)) {
2475 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2476 << VarTemplate->getDeclName();
2477 IsPartialSpecialization = false;
2478 }
2479
2480 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2481 Converted)) {
2482 // C++ [temp.class.spec]p9b3:
2483 //
2484 // -- The argument list of the specialization shall not be identical
2485 // to the implicit argument list of the primary template.
2486 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2487 << /*variable template*/ 1
2488 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2489 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2490 // FIXME: Recover from this by treating the declaration as a redeclaration
2491 // of the primary template.
2492 return true;
2493 }
2494 }
2495
2496 void *InsertPos = nullptr;
2497 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2498
2499 if (IsPartialSpecialization)
2500 // FIXME: Template parameter list matters too
2501 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2502 else
2503 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2504
2505 VarTemplateSpecializationDecl *Specialization = nullptr;
2506
2507 // Check whether we can declare a variable template specialization in
2508 // the current scope.
2509 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2510 TemplateNameLoc,
2511 IsPartialSpecialization))
2512 return true;
2513
2514 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2515 // Since the only prior variable template specialization with these
2516 // arguments was referenced but not declared, reuse that
2517 // declaration node as our own, updating its source location and
2518 // the list of outer template parameters to reflect our new declaration.
2519 Specialization = PrevDecl;
2520 Specialization->setLocation(TemplateNameLoc);
2521 PrevDecl = nullptr;
2522 } else if (IsPartialSpecialization) {
2523 // Create a new class template partial specialization declaration node.
2524 VarTemplatePartialSpecializationDecl *PrevPartial =
2525 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2526 VarTemplatePartialSpecializationDecl *Partial =
2527 VarTemplatePartialSpecializationDecl::Create(
2528 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2529 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2530 Converted.data(), Converted.size(), TemplateArgs);
2531
2532 if (!PrevPartial)
2533 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2534 Specialization = Partial;
2535
2536 // If we are providing an explicit specialization of a member variable
2537 // template specialization, make a note of that.
2538 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2539 PrevPartial->setMemberSpecialization();
2540
2541 // Check that all of the template parameters of the variable template
2542 // partial specialization are deducible from the template
2543 // arguments. If not, this variable template partial specialization
2544 // will never be used.
2545 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2546 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2547 TemplateParams->getDepth(), DeducibleParams);
2548
2549 if (!DeducibleParams.all()) {
2550 unsigned NumNonDeducible =
2551 DeducibleParams.size() - DeducibleParams.count();
2552 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2553 << /*variable template*/ 1 << (NumNonDeducible > 1)
2554 << SourceRange(TemplateNameLoc, RAngleLoc);
2555 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2556 if (!DeducibleParams[I]) {
2557 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2558 if (Param->getDeclName())
2559 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2560 << Param->getDeclName();
2561 else
2562 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2563 << "(anonymous)";
2564 }
2565 }
2566 }
2567 } else {
2568 // Create a new class template specialization declaration node for
2569 // this explicit specialization or friend declaration.
2570 Specialization = VarTemplateSpecializationDecl::Create(
2571 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2572 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2573 Specialization->setTemplateArgsInfo(TemplateArgs);
2574
2575 if (!PrevDecl)
2576 VarTemplate->AddSpecialization(Specialization, InsertPos);
2577 }
2578
2579 // C++ [temp.expl.spec]p6:
2580 // If a template, a member template or the member of a class template is
2581 // explicitly specialized then that specialization shall be declared
2582 // before the first use of that specialization that would cause an implicit
2583 // instantiation to take place, in every translation unit in which such a
2584 // use occurs; no diagnostic is required.
2585 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2586 bool Okay = false;
2587 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2588 // Is there any previous explicit specialization declaration?
2589 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2590 Okay = true;
2591 break;
2592 }
2593 }
2594
2595 if (!Okay) {
2596 SourceRange Range(TemplateNameLoc, RAngleLoc);
2597 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2598 << Name << Range;
2599
2600 Diag(PrevDecl->getPointOfInstantiation(),
2601 diag::note_instantiation_required_here)
2602 << (PrevDecl->getTemplateSpecializationKind() !=
2603 TSK_ImplicitInstantiation);
2604 return true;
2605 }
2606 }
2607
2608 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2609 Specialization->setLexicalDeclContext(CurContext);
2610
2611 // Add the specialization into its lexical context, so that it can
2612 // be seen when iterating through the list of declarations in that
2613 // context. However, specializations are not found by name lookup.
2614 CurContext->addDecl(Specialization);
2615
2616 // Note that this is an explicit specialization.
2617 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2618
2619 if (PrevDecl) {
2620 // Check that this isn't a redefinition of this specialization,
2621 // merging with previous declarations.
2622 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2623 ForRedeclaration);
2624 PrevSpec.addDecl(PrevDecl);
2625 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2626 } else if (Specialization->isStaticDataMember() &&
2627 Specialization->isOutOfLine()) {
2628 Specialization->setAccess(VarTemplate->getAccess());
2629 }
2630
2631 // Link instantiations of static data members back to the template from
2632 // which they were instantiated.
2633 if (Specialization->isStaticDataMember())
2634 Specialization->setInstantiationOfStaticDataMember(
2635 VarTemplate->getTemplatedDecl(),
2636 Specialization->getSpecializationKind());
2637
2638 return Specialization;
2639}
2640
2641namespace {
2642/// \brief A partial specialization whose template arguments have matched
2643/// a given template-id.
2644struct PartialSpecMatchResult {
2645 VarTemplatePartialSpecializationDecl *Partial;
2646 TemplateArgumentList *Args;
2647};
2648}
2649
2650DeclResult
2651Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2652 SourceLocation TemplateNameLoc,
2653 const TemplateArgumentListInfo &TemplateArgs) {
2654 assert(Template && "A variable template id without template?");
2655
2656 // Check that the template argument list is well-formed for this template.
2657 SmallVector<TemplateArgument, 4> Converted;
2658 if (CheckTemplateArgumentList(
2659 Template, TemplateNameLoc,
2660 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2661 Converted))
2662 return true;
2663
2664 // Find the variable template specialization declaration that
2665 // corresponds to these arguments.
2666 void *InsertPos = nullptr;
2667 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2668 Converted, InsertPos))
2669 // If we already have a variable template specialization, return it.
2670 return Spec;
2671
2672 // This is the first time we have referenced this variable template
2673 // specialization. Create the canonical declaration and add it to
2674 // the set of specializations, based on the closest partial specialization
2675 // that it represents. That is,
2676 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2677 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2678 Converted.data(), Converted.size());
2679 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2680 bool AmbiguousPartialSpec = false;
2681 typedef PartialSpecMatchResult MatchResult;
2682 SmallVector<MatchResult, 4> Matched;
2683 SourceLocation PointOfInstantiation = TemplateNameLoc;
2684 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2685
2686 // 1. Attempt to find the closest partial specialization that this
2687 // specializes, if any.
2688 // If any of the template arguments is dependent, then this is probably
2689 // a placeholder for an incomplete declarative context; which must be
2690 // complete by instantiation time. Thus, do not search through the partial
2691 // specializations yet.
2692 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2693 // Perhaps better after unification of DeduceTemplateArguments() and
2694 // getMoreSpecializedPartialSpecialization().
2695 bool InstantiationDependent = false;
2696 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2697 TemplateArgs, InstantiationDependent)) {
2698
2699 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2700 Template->getPartialSpecializations(PartialSpecs);
2701
2702 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2703 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2704 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2705
2706 if (TemplateDeductionResult Result =
2707 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2708 // Store the failed-deduction information for use in diagnostics, later.
2709 // TODO: Actually use the failed-deduction info?
2710 FailedCandidates.addCandidate()
2711 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2712 (void)Result;
2713 } else {
2714 Matched.push_back(PartialSpecMatchResult());
2715 Matched.back().Partial = Partial;
2716 Matched.back().Args = Info.take();
2717 }
2718 }
2719
2720 if (Matched.size() >= 1) {
2721 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2722 if (Matched.size() == 1) {
2723 // -- If exactly one matching specialization is found, the
2724 // instantiation is generated from that specialization.
2725 // We don't need to do anything for this.
2726 } else {
2727 // -- If more than one matching specialization is found, the
2728 // partial order rules (14.5.4.2) are used to determine
2729 // whether one of the specializations is more specialized
2730 // than the others. If none of the specializations is more
2731 // specialized than all of the other matching
2732 // specializations, then the use of the variable template is
2733 // ambiguous and the program is ill-formed.
2734 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2735 PEnd = Matched.end();
2736 P != PEnd; ++P) {
2737 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2738 PointOfInstantiation) ==
2739 P->Partial)
2740 Best = P;
2741 }
2742
2743 // Determine if the best partial specialization is more specialized than
2744 // the others.
2745 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2746 PEnd = Matched.end();
2747 P != PEnd; ++P) {
2748 if (P != Best && getMoreSpecializedPartialSpecialization(
2749 P->Partial, Best->Partial,
2750 PointOfInstantiation) != Best->Partial) {
2751 AmbiguousPartialSpec = true;
2752 break;
2753 }
2754 }
2755 }
2756
2757 // Instantiate using the best variable template partial specialization.
2758 InstantiationPattern = Best->Partial;
2759 InstantiationArgs = Best->Args;
2760 } else {
2761 // -- If no match is found, the instantiation is generated
2762 // from the primary template.
2763 // InstantiationPattern = Template->getTemplatedDecl();
2764 }
2765 }
2766
2767 // 2. Create the canonical declaration.
2768 // Note that we do not instantiate the variable just yet, since
2769 // instantiation is handled in DoMarkVarDeclReferenced().
2770 // FIXME: LateAttrs et al.?
2771 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2772 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2773 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2774 if (!Decl)
2775 return true;
2776
2777 if (AmbiguousPartialSpec) {
2778 // Partial ordering did not produce a clear winner. Complain.
2779 Decl->setInvalidDecl();
2780 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2781 << Decl;
2782
2783 // Print the matching partial specializations.
2784 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2785 PEnd = Matched.end();
2786 P != PEnd; ++P)
2787 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2788 << getTemplateArgumentBindingsText(
2789 P->Partial->getTemplateParameters(), *P->Args);
2790 return true;
2791 }
2792
2793 if (VarTemplatePartialSpecializationDecl *D =
2794 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2795 Decl->setInstantiationOf(D, InstantiationArgs);
2796
2797 assert(Decl && "No variable template specialization?");
2798 return Decl;
2799}
2800
2801ExprResult
2802Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2803 const DeclarationNameInfo &NameInfo,
2804 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2805 const TemplateArgumentListInfo *TemplateArgs) {
2806
2807 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2808 *TemplateArgs);
2809 if (Decl.isInvalid())
2810 return ExprError();
2811
2812 VarDecl *Var = cast<VarDecl>(Decl.get());
2813 if (!Var->getTemplateSpecializationKind())
2814 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2815 NameInfo.getLoc());
2816
2817 // Build an ordinary singleton decl ref.
2818 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2819 /*FoundD=*/nullptr, TemplateArgs);
2820}
2821
2822ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2823 SourceLocation TemplateKWLoc,
2824 LookupResult &R,
2825 bool RequiresADL,
2826 const TemplateArgumentListInfo *TemplateArgs) {
2827 // FIXME: Can we do any checking at this point? I guess we could check the
2828 // template arguments that we have against the template name, if the template
2829 // name refers to a single template. That's not a terribly common case,
2830 // though.
2831 // foo<int> could identify a single function unambiguously
2832 // This approach does NOT work, since f<int>(1);
2833 // gets resolved prior to resorting to overload resolution
2834 // i.e., template<class T> void f(double);
2835 // vs template<class T, class U> void f(U);
2836
2837 // These should be filtered out by our callers.
2838 assert(!R.empty() && "empty lookup results when building templateid");
2839 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2840
2841 // In C++1y, check variable template ids.
2842 bool InstantiationDependent;
2843 if (R.getAsSingle<VarTemplateDecl>() &&
2844 !TemplateSpecializationType::anyDependentTemplateArguments(
2845 *TemplateArgs, InstantiationDependent)) {
2846 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2847 R.getAsSingle<VarTemplateDecl>(),
2848 TemplateKWLoc, TemplateArgs);
2849 }
2850
2851 // We don't want lookup warnings at this point.
2852 R.suppressDiagnostics();
2853
2854 UnresolvedLookupExpr *ULE
2855 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2856 SS.getWithLocInContext(Context),
2857 TemplateKWLoc,
2858 R.getLookupNameInfo(),
2859 RequiresADL, TemplateArgs,
2860 R.begin(), R.end());
2861
2862 return ULE;
2863}
2864
2865// We actually only call this from template instantiation.
2866ExprResult
2867Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2868 SourceLocation TemplateKWLoc,
2869 const DeclarationNameInfo &NameInfo,
2870 const TemplateArgumentListInfo *TemplateArgs) {
2871
2872 assert(TemplateArgs || TemplateKWLoc.isValid());
2873 DeclContext *DC;
2874 if (!(DC = computeDeclContext(SS, false)) ||
2875 DC->isDependentContext() ||
2876 RequireCompleteDeclContext(SS, DC))
2877 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2878
2879 bool MemberOfUnknownSpecialization;
2880 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2881 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2882 MemberOfUnknownSpecialization);
2883
2884 if (R.isAmbiguous())
2885 return ExprError();
2886
2887 if (R.empty()) {
2888 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2889 << NameInfo.getName() << SS.getRange();
2890 return ExprError();
2891 }
2892
2893 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2894 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2895 << SS.getScopeRep()
2896 << NameInfo.getName().getAsString() << SS.getRange();
2897 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2898 return ExprError();
2899 }
2900
2901 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2902}
2903
2904/// \brief Form a dependent template name.
2905///
2906/// This action forms a dependent template name given the template
2907/// name and its (presumably dependent) scope specifier. For
2908/// example, given "MetaFun::template apply", the scope specifier \p
2909/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2910/// of the "template" keyword, and "apply" is the \p Name.
2911TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2912 CXXScopeSpec &SS,
2913 SourceLocation TemplateKWLoc,
2914 UnqualifiedId &Name,
2915 ParsedType ObjectType,
2916 bool EnteringContext,
2917 TemplateTy &Result) {
2918 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2919 Diag(TemplateKWLoc,
2920 getLangOpts().CPlusPlus11 ?
2921 diag::warn_cxx98_compat_template_outside_of_template :
2922 diag::ext_template_outside_of_template)
2923 << FixItHint::CreateRemoval(TemplateKWLoc);
2924
2925 DeclContext *LookupCtx = nullptr;
2926 if (SS.isSet())
2927 LookupCtx = computeDeclContext(SS, EnteringContext);
2928 if (!LookupCtx && ObjectType)
2929 LookupCtx = computeDeclContext(ObjectType.get());
2930 if (LookupCtx) {
2931 // C++0x [temp.names]p5:
2932 // If a name prefixed by the keyword template is not the name of
2933 // a template, the program is ill-formed. [Note: the keyword
2934 // template may not be applied to non-template members of class
2935 // templates. -end note ] [ Note: as is the case with the
2936 // typename prefix, the template prefix is allowed in cases
2937 // where it is not strictly necessary; i.e., when the
2938 // nested-name-specifier or the expression on the left of the ->
2939 // or . is not dependent on a template-parameter, or the use
2940 // does not appear in the scope of a template. -end note]
2941 //
2942 // Note: C++03 was more strict here, because it banned the use of
2943 // the "template" keyword prior to a template-name that was not a
2944 // dependent name. C++ DR468 relaxed this requirement (the
2945 // "template" keyword is now permitted). We follow the C++0x
2946 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2947 bool MemberOfUnknownSpecialization;
2948 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2949 ObjectType, EnteringContext, Result,
2950 MemberOfUnknownSpecialization);
2951 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2952 isa<CXXRecordDecl>(LookupCtx) &&
2953 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2954 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2955 // This is a dependent template. Handle it below.
2956 } else if (TNK == TNK_Non_template) {
2957 Diag(Name.getLocStart(),
2958 diag::err_template_kw_refers_to_non_template)
2959 << GetNameFromUnqualifiedId(Name).getName()
2960 << Name.getSourceRange()
2961 << TemplateKWLoc;
2962 return TNK_Non_template;
2963 } else {
2964 // We found something; return it.
2965 return TNK;
2966 }
2967 }
2968
2969 NestedNameSpecifier *Qualifier = SS.getScopeRep();
2970
2971 switch (Name.getKind()) {
2972 case UnqualifiedId::IK_Identifier:
2973 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2974 Name.Identifier));
2975 return TNK_Dependent_template_name;
2976
2977 case UnqualifiedId::IK_OperatorFunctionId:
2978 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2979 Name.OperatorFunctionId.Operator));
2980 return TNK_Function_template;
2981
2982 case UnqualifiedId::IK_LiteralOperatorId:
2983 llvm_unreachable("literal operator id cannot have a dependent scope");
2984
2985 default:
2986 break;
2987 }
2988
2989 Diag(Name.getLocStart(),
2990 diag::err_template_kw_refers_to_non_template)
2991 << GetNameFromUnqualifiedId(Name).getName()
2992 << Name.getSourceRange()
2993 << TemplateKWLoc;
2994 return TNK_Non_template;
2995}
2996
2997bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
2998 TemplateArgumentLoc &AL,
2999 SmallVectorImpl<TemplateArgument> &Converted) {
3000 const TemplateArgument &Arg = AL.getArgument();
3001 QualType ArgType;
3002 TypeSourceInfo *TSI = nullptr;
3003
3004 // Check template type parameter.
3005 switch(Arg.getKind()) {
3006 case TemplateArgument::Type:
3007 // C++ [temp.arg.type]p1:
3008 // A template-argument for a template-parameter which is a
3009 // type shall be a type-id.
3010 ArgType = Arg.getAsType();
3011 TSI = AL.getTypeSourceInfo();
3012 break;
3013 case TemplateArgument::Template: {
3014 // We have a template type parameter but the template argument
3015 // is a template without any arguments.
3016 SourceRange SR = AL.getSourceRange();
3017 TemplateName Name = Arg.getAsTemplate();
3018 Diag(SR.getBegin(), diag::err_template_missing_args)
3019 << Name << SR;
3020 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3021 Diag(Decl->getLocation(), diag::note_template_decl_here);
3022
3023 return true;
3024 }
3025 case TemplateArgument::Expression: {
3026 // We have a template type parameter but the template argument is an
3027 // expression; see if maybe it is missing the "typename" keyword.
3028 CXXScopeSpec SS;
3029 DeclarationNameInfo NameInfo;
3030
3031 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3032 SS.Adopt(ArgExpr->getQualifierLoc());
3033 NameInfo = ArgExpr->getNameInfo();
3034 } else if (DependentScopeDeclRefExpr *ArgExpr =
3035 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3036 SS.Adopt(ArgExpr->getQualifierLoc());
3037 NameInfo = ArgExpr->getNameInfo();
3038 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3039 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3040 if (ArgExpr->isImplicitAccess()) {
3041 SS.Adopt(ArgExpr->getQualifierLoc());
3042 NameInfo = ArgExpr->getMemberNameInfo();
3043 }
3044 }
3045
3046 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3047 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3048 LookupParsedName(Result, CurScope, &SS);
3049
3050 if (Result.getAsSingle<TypeDecl>() ||
3051 Result.getResultKind() ==
3052 LookupResult::NotFoundInCurrentInstantiation) {
3053 // Suggest that the user add 'typename' before the NNS.
3054 SourceLocation Loc = AL.getSourceRange().getBegin();
3055 Diag(Loc, getLangOpts().MSVCCompat
3056 ? diag::ext_ms_template_type_arg_missing_typename
3057 : diag::err_template_arg_must_be_type_suggest)
3058 << FixItHint::CreateInsertion(Loc, "typename ");
3059 Diag(Param->getLocation(), diag::note_template_param_here);
3060
3061 // Recover by synthesizing a type using the location information that we
3062 // already have.
3063 ArgType =
3064 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3065 TypeLocBuilder TLB;
3066 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3067 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3068 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3069 TL.setNameLoc(NameInfo.getLoc());
3070 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3071
3072 // Overwrite our input TemplateArgumentLoc so that we can recover
3073 // properly.
3074 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3075 TemplateArgumentLocInfo(TSI));
3076
3077 break;
3078 }
3079 }
3080 // fallthrough
3081 }
3082 default: {
3083 // We have a template type parameter but the template argument
3084 // is not a type.
3085 SourceRange SR = AL.getSourceRange();
3086 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3087 Diag(Param->getLocation(), diag::note_template_param_here);
3088
3089 return true;
3090 }
3091 }
3092
3093 if (CheckTemplateArgument(Param, TSI))
3094 return true;
3095
3096 // Add the converted template type argument.
3097 ArgType = Context.getCanonicalType(ArgType);
3098
3099 // Objective-C ARC:
3100 // If an explicitly-specified template argument type is a lifetime type
3101 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3102 if (getLangOpts().ObjCAutoRefCount &&
3103 ArgType->isObjCLifetimeType() &&
3104 !ArgType.getObjCLifetime()) {
3105 Qualifiers Qs;
3106 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3107 ArgType = Context.getQualifiedType(ArgType, Qs);
3108 }
3109
3110 Converted.push_back(TemplateArgument(ArgType));
3111 return false;
3112}
3113
3114/// \brief Substitute template arguments into the default template argument for
3115/// the given template type parameter.
3116///
3117/// \param SemaRef the semantic analysis object for which we are performing
3118/// the substitution.
3119///
3120/// \param Template the template that we are synthesizing template arguments
3121/// for.
3122///
3123/// \param TemplateLoc the location of the template name that started the
3124/// template-id we are checking.
3125///
3126/// \param RAngleLoc the location of the right angle bracket ('>') that
3127/// terminates the template-id.
3128///
3129/// \param Param the template template parameter whose default we are
3130/// substituting into.
3131///
3132/// \param Converted the list of template arguments provided for template
3133/// parameters that precede \p Param in the template parameter list.
3134/// \returns the substituted template argument, or NULL if an error occurred.
3135static TypeSourceInfo *
3136SubstDefaultTemplateArgument(Sema &SemaRef,
3137 TemplateDecl *Template,
3138 SourceLocation TemplateLoc,
3139 SourceLocation RAngleLoc,
3140 TemplateTypeParmDecl *Param,
3141 SmallVectorImpl<TemplateArgument> &Converted) {
3142 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3143
3144 // If the argument type is dependent, instantiate it now based
3145 // on the previously-computed template arguments.
3146 if (ArgType->getType()->isDependentType()) {
3147 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3148 Template, Converted,
3149 SourceRange(TemplateLoc, RAngleLoc));
3150 if (Inst.isInvalid())
3151 return nullptr;
3152
3153 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3154 Converted.data(), Converted.size());
3155
3156 // Only substitute for the innermost template argument list.
3157 MultiLevelTemplateArgumentList TemplateArgLists;
3158 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3159 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3160 TemplateArgLists.addOuterTemplateArguments(None);
3161
3162 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3163 ArgType =
3164 SemaRef.SubstType(ArgType, TemplateArgLists,
3165 Param->getDefaultArgumentLoc(), Param->getDeclName());
3166 }
3167
3168 return ArgType;
3169}
3170
3171/// \brief Substitute template arguments into the default template argument for
3172/// the given non-type template parameter.
3173///
3174/// \param SemaRef the semantic analysis object for which we are performing
3175/// the substitution.
3176///
3177/// \param Template the template that we are synthesizing template arguments
3178/// for.
3179///
3180/// \param TemplateLoc the location of the template name that started the
3181/// template-id we are checking.
3182///
3183/// \param RAngleLoc the location of the right angle bracket ('>') that
3184/// terminates the template-id.
3185///
3186/// \param Param the non-type template parameter whose default we are
3187/// substituting into.
3188///
3189/// \param Converted the list of template arguments provided for template
3190/// parameters that precede \p Param in the template parameter list.
3191///
3192/// \returns the substituted template argument, or NULL if an error occurred.
3193static ExprResult
3194SubstDefaultTemplateArgument(Sema &SemaRef,
3195 TemplateDecl *Template,
3196 SourceLocation TemplateLoc,
3197 SourceLocation RAngleLoc,
3198 NonTypeTemplateParmDecl *Param,
3199 SmallVectorImpl<TemplateArgument> &Converted) {
3200 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3201 Template, Converted,
3202 SourceRange(TemplateLoc, RAngleLoc));
3203 if (Inst.isInvalid())
3204 return ExprError();
3205
3206 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3207 Converted.data(), Converted.size());
3208
3209 // Only substitute for the innermost template argument list.
3210 MultiLevelTemplateArgumentList TemplateArgLists;
3211 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3212 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3213 TemplateArgLists.addOuterTemplateArguments(None);
3214
3215 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3216 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3217 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3218}
3219
3220/// \brief Substitute template arguments into the default template argument for
3221/// the given template template parameter.
3222///
3223/// \param SemaRef the semantic analysis object for which we are performing
3224/// the substitution.
3225///
3226/// \param Template the template that we are synthesizing template arguments
3227/// for.
3228///
3229/// \param TemplateLoc the location of the template name that started the
3230/// template-id we are checking.
3231///
3232/// \param RAngleLoc the location of the right angle bracket ('>') that
3233/// terminates the template-id.
3234///
3235/// \param Param the template template parameter whose default we are
3236/// substituting into.
3237///
3238/// \param Converted the list of template arguments provided for template
3239/// parameters that precede \p Param in the template parameter list.
3240///
3241/// \param QualifierLoc Will be set to the nested-name-specifier (with
3242/// source-location information) that precedes the template name.
3243///
3244/// \returns the substituted template argument, or NULL if an error occurred.
3245static TemplateName
3246SubstDefaultTemplateArgument(Sema &SemaRef,
3247 TemplateDecl *Template,
3248 SourceLocation TemplateLoc,
3249 SourceLocation RAngleLoc,
3250 TemplateTemplateParmDecl *Param,
3251 SmallVectorImpl<TemplateArgument> &Converted,
3252 NestedNameSpecifierLoc &QualifierLoc) {
3253 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3254 SourceRange(TemplateLoc, RAngleLoc));
3255 if (Inst.isInvalid())
3256 return TemplateName();
3257
3258 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3259 Converted.data(), Converted.size());
3260
3261 // Only substitute for the innermost template argument list.
3262 MultiLevelTemplateArgumentList TemplateArgLists;
3263 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3264 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3265 TemplateArgLists.addOuterTemplateArguments(None);
3266
3267 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3268 // Substitute into the nested-name-specifier first,
3269 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3270 if (QualifierLoc) {
3271 QualifierLoc =
3272 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3273 if (!QualifierLoc)
3274 return TemplateName();
3275 }
3276
3277 return SemaRef.SubstTemplateName(
3278 QualifierLoc,
3279 Param->getDefaultArgument().getArgument().getAsTemplate(),
3280 Param->getDefaultArgument().getTemplateNameLoc(),
3281 TemplateArgLists);
3282}
3283
3284/// \brief If the given template parameter has a default template
3285/// argument, substitute into that default template argument and
3286/// return the corresponding template argument.
3287TemplateArgumentLoc
3288Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3289 SourceLocation TemplateLoc,
3290 SourceLocation RAngleLoc,
3291 Decl *Param,
3292 SmallVectorImpl<TemplateArgument>
3293 &Converted,
3294 bool &HasDefaultArg) {
3295 HasDefaultArg = false;
3296
3297 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3298 if (!TypeParm->hasDefaultArgument())
3299 return TemplateArgumentLoc();
3300
3301 HasDefaultArg = true;
3302 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3303 TemplateLoc,
3304 RAngleLoc,
3305 TypeParm,
3306 Converted);
3307 if (DI)
3308 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3309
3310 return TemplateArgumentLoc();
3311 }
3312
3313 if (NonTypeTemplateParmDecl *NonTypeParm
3314 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3315 if (!NonTypeParm->hasDefaultArgument())
3316 return TemplateArgumentLoc();
3317
3318 HasDefaultArg = true;
3319 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3320 TemplateLoc,
3321 RAngleLoc,
3322 NonTypeParm,
3323 Converted);
3324 if (Arg.isInvalid())
3325 return TemplateArgumentLoc();
3326
3327 Expr *ArgE = Arg.getAs<Expr>();
3328 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3329 }
3330
3331 TemplateTemplateParmDecl *TempTempParm
3332 = cast<TemplateTemplateParmDecl>(Param);
3333 if (!TempTempParm->hasDefaultArgument())
3334 return TemplateArgumentLoc();
3335
3336 HasDefaultArg = true;
3337 NestedNameSpecifierLoc QualifierLoc;
3338 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3339 TemplateLoc,
3340 RAngleLoc,
3341 TempTempParm,
3342 Converted,
3343 QualifierLoc);
3344 if (TName.isNull())
3345 return TemplateArgumentLoc();
3346
3347 return TemplateArgumentLoc(TemplateArgument(TName),
3348 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3349 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3350}
3351
3352/// \brief Check that the given template argument corresponds to the given
3353/// template parameter.
3354///
3355/// \param Param The template parameter against which the argument will be
3356/// checked.
3357///
3358/// \param Arg The template argument.
3358/// \param Arg The template argument, which may be updated due to conversions.
3359///
3360/// \param Template The template in which the template argument resides.
3361///
3362/// \param TemplateLoc The location of the template name for the template
3363/// whose argument list we're matching.
3364///
3365/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3366/// the template argument list.
3367///
3368/// \param ArgumentPackIndex The index into the argument pack where this
3369/// argument will be placed. Only valid if the parameter is a parameter pack.
3370///
3371/// \param Converted The checked, converted argument will be added to the
3372/// end of this small vector.
3373///
3374/// \param CTAK Describes how we arrived at this particular template argument:
3375/// explicitly written, deduced, etc.
3376///
3377/// \returns true on error, false otherwise.
3378bool Sema::CheckTemplateArgument(NamedDecl *Param,
3379 TemplateArgumentLoc &Arg,
3380 NamedDecl *Template,
3381 SourceLocation TemplateLoc,
3382 SourceLocation RAngleLoc,
3383 unsigned ArgumentPackIndex,
3384 SmallVectorImpl<TemplateArgument> &Converted,
3385 CheckTemplateArgumentKind CTAK) {
3386 // Check template type parameters.
3387 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3388 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3389
3390 // Check non-type template parameters.
3391 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3392 // Do substitution on the type of the non-type template parameter
3393 // with the template arguments we've seen thus far. But if the
3394 // template has a dependent context then we cannot substitute yet.
3395 QualType NTTPType = NTTP->getType();
3396 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3397 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3398
3399 if (NTTPType->isDependentType() &&
3400 !isa<TemplateTemplateParmDecl>(Template) &&
3401 !Template->getDeclContext()->isDependentContext()) {
3402 // Do substitution on the type of the non-type template parameter.
3403 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3404 NTTP, Converted,
3405 SourceRange(TemplateLoc, RAngleLoc));
3406 if (Inst.isInvalid())
3407 return true;
3408
3409 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3410 Converted.data(), Converted.size());
3411 NTTPType = SubstType(NTTPType,
3412 MultiLevelTemplateArgumentList(TemplateArgs),
3413 NTTP->getLocation(),
3414 NTTP->getDeclName());
3415 // If that worked, check the non-type template parameter type
3416 // for validity.
3417 if (!NTTPType.isNull())
3418 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3419 NTTP->getLocation());
3420 if (NTTPType.isNull())
3421 return true;
3422 }
3423
3424 switch (Arg.getArgument().getKind()) {
3425 case TemplateArgument::Null:
3426 llvm_unreachable("Should never see a NULL template argument here");
3427
3428 case TemplateArgument::Expression: {
3429 TemplateArgument Result;
3430 ExprResult Res =
3431 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3432 Result, CTAK);
3433 if (Res.isInvalid())
3434 return true;
3435
3359///
3360/// \param Template The template in which the template argument resides.
3361///
3362/// \param TemplateLoc The location of the template name for the template
3363/// whose argument list we're matching.
3364///
3365/// \param RAngleLoc The location of the right angle bracket ('>') that closes
3366/// the template argument list.
3367///
3368/// \param ArgumentPackIndex The index into the argument pack where this
3369/// argument will be placed. Only valid if the parameter is a parameter pack.
3370///
3371/// \param Converted The checked, converted argument will be added to the
3372/// end of this small vector.
3373///
3374/// \param CTAK Describes how we arrived at this particular template argument:
3375/// explicitly written, deduced, etc.
3376///
3377/// \returns true on error, false otherwise.
3378bool Sema::CheckTemplateArgument(NamedDecl *Param,
3379 TemplateArgumentLoc &Arg,
3380 NamedDecl *Template,
3381 SourceLocation TemplateLoc,
3382 SourceLocation RAngleLoc,
3383 unsigned ArgumentPackIndex,
3384 SmallVectorImpl<TemplateArgument> &Converted,
3385 CheckTemplateArgumentKind CTAK) {
3386 // Check template type parameters.
3387 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3388 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3389
3390 // Check non-type template parameters.
3391 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3392 // Do substitution on the type of the non-type template parameter
3393 // with the template arguments we've seen thus far. But if the
3394 // template has a dependent context then we cannot substitute yet.
3395 QualType NTTPType = NTTP->getType();
3396 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3397 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3398
3399 if (NTTPType->isDependentType() &&
3400 !isa<TemplateTemplateParmDecl>(Template) &&
3401 !Template->getDeclContext()->isDependentContext()) {
3402 // Do substitution on the type of the non-type template parameter.
3403 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3404 NTTP, Converted,
3405 SourceRange(TemplateLoc, RAngleLoc));
3406 if (Inst.isInvalid())
3407 return true;
3408
3409 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3410 Converted.data(), Converted.size());
3411 NTTPType = SubstType(NTTPType,
3412 MultiLevelTemplateArgumentList(TemplateArgs),
3413 NTTP->getLocation(),
3414 NTTP->getDeclName());
3415 // If that worked, check the non-type template parameter type
3416 // for validity.
3417 if (!NTTPType.isNull())
3418 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3419 NTTP->getLocation());
3420 if (NTTPType.isNull())
3421 return true;
3422 }
3423
3424 switch (Arg.getArgument().getKind()) {
3425 case TemplateArgument::Null:
3426 llvm_unreachable("Should never see a NULL template argument here");
3427
3428 case TemplateArgument::Expression: {
3429 TemplateArgument Result;
3430 ExprResult Res =
3431 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3432 Result, CTAK);
3433 if (Res.isInvalid())
3434 return true;
3435
3436 // If the resulting expression is new, then use it in place of the
3437 // old expression in the template argument.
3438 if (Res.get() != Arg.getArgument().getAsExpr()) {
3439 TemplateArgument TA(Res.get());
3440 Arg = TemplateArgumentLoc(TA, Res.get());
3441 }
3442
3436 Converted.push_back(Result);
3437 break;
3438 }
3439
3440 case TemplateArgument::Declaration:
3441 case TemplateArgument::Integral:
3442 case TemplateArgument::NullPtr:
3443 // We've already checked this template argument, so just copy
3444 // it to the list of converted arguments.
3445 Converted.push_back(Arg.getArgument());
3446 break;
3447
3448 case TemplateArgument::Template:
3449 case TemplateArgument::TemplateExpansion:
3450 // We were given a template template argument. It may not be ill-formed;
3451 // see below.
3452 if (DependentTemplateName *DTN
3453 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3454 .getAsDependentTemplateName()) {
3455 // We have a template argument such as \c T::template X, which we
3456 // parsed as a template template argument. However, since we now
3457 // know that we need a non-type template argument, convert this
3458 // template name into an expression.
3459
3460 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3461 Arg.getTemplateNameLoc());
3462
3463 CXXScopeSpec SS;
3464 SS.Adopt(Arg.getTemplateQualifierLoc());
3465 // FIXME: the template-template arg was a DependentTemplateName,
3466 // so it was provided with a template keyword. However, its source
3467 // location is not stored in the template argument structure.
3468 SourceLocation TemplateKWLoc;
3469 ExprResult E = DependentScopeDeclRefExpr::Create(
3470 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3471 nullptr);
3472
3473 // If we parsed the template argument as a pack expansion, create a
3474 // pack expansion expression.
3475 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3476 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3477 if (E.isInvalid())
3478 return true;
3479 }
3480
3481 TemplateArgument Result;
3482 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3483 if (E.isInvalid())
3484 return true;
3485
3486 Converted.push_back(Result);
3487 break;
3488 }
3489
3490 // We have a template argument that actually does refer to a class
3491 // template, alias template, or template template parameter, and
3492 // therefore cannot be a non-type template argument.
3493 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3494 << Arg.getSourceRange();
3495
3496 Diag(Param->getLocation(), diag::note_template_param_here);
3497 return true;
3498
3499 case TemplateArgument::Type: {
3500 // We have a non-type template parameter but the template
3501 // argument is a type.
3502
3503 // C++ [temp.arg]p2:
3504 // In a template-argument, an ambiguity between a type-id and
3505 // an expression is resolved to a type-id, regardless of the
3506 // form of the corresponding template-parameter.
3507 //
3508 // We warn specifically about this case, since it can be rather
3509 // confusing for users.
3510 QualType T = Arg.getArgument().getAsType();
3511 SourceRange SR = Arg.getSourceRange();
3512 if (T->isFunctionType())
3513 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3514 else
3515 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3516 Diag(Param->getLocation(), diag::note_template_param_here);
3517 return true;
3518 }
3519
3520 case TemplateArgument::Pack:
3521 llvm_unreachable("Caller must expand template argument packs");
3522 }
3523
3524 return false;
3525 }
3526
3527
3528 // Check template template parameters.
3529 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3530
3531 // Substitute into the template parameter list of the template
3532 // template parameter, since previously-supplied template arguments
3533 // may appear within the template template parameter.
3534 {
3535 // Set up a template instantiation context.
3536 LocalInstantiationScope Scope(*this);
3537 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3538 TempParm, Converted,
3539 SourceRange(TemplateLoc, RAngleLoc));
3540 if (Inst.isInvalid())
3541 return true;
3542
3543 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3544 Converted.data(), Converted.size());
3545 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3546 SubstDecl(TempParm, CurContext,
3547 MultiLevelTemplateArgumentList(TemplateArgs)));
3548 if (!TempParm)
3549 return true;
3550 }
3551
3552 switch (Arg.getArgument().getKind()) {
3553 case TemplateArgument::Null:
3554 llvm_unreachable("Should never see a NULL template argument here");
3555
3556 case TemplateArgument::Template:
3557 case TemplateArgument::TemplateExpansion:
3558 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3559 return true;
3560
3561 Converted.push_back(Arg.getArgument());
3562 break;
3563
3564 case TemplateArgument::Expression:
3565 case TemplateArgument::Type:
3566 // We have a template template parameter but the template
3567 // argument does not refer to a template.
3568 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3569 << getLangOpts().CPlusPlus11;
3570 return true;
3571
3572 case TemplateArgument::Declaration:
3573 llvm_unreachable("Declaration argument with template template parameter");
3574 case TemplateArgument::Integral:
3575 llvm_unreachable("Integral argument with template template parameter");
3576 case TemplateArgument::NullPtr:
3577 llvm_unreachable("Null pointer argument with template template parameter");
3578
3579 case TemplateArgument::Pack:
3580 llvm_unreachable("Caller must expand template argument packs");
3581 }
3582
3583 return false;
3584}
3585
3586/// \brief Diagnose an arity mismatch in the
3587static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3588 SourceLocation TemplateLoc,
3589 TemplateArgumentListInfo &TemplateArgs) {
3590 TemplateParameterList *Params = Template->getTemplateParameters();
3591 unsigned NumParams = Params->size();
3592 unsigned NumArgs = TemplateArgs.size();
3593
3594 SourceRange Range;
3595 if (NumArgs > NumParams)
3596 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3597 TemplateArgs.getRAngleLoc());
3598 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3599 << (NumArgs > NumParams)
3600 << (isa<ClassTemplateDecl>(Template)? 0 :
3601 isa<FunctionTemplateDecl>(Template)? 1 :
3602 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3603 << Template << Range;
3604 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3605 << Params->getSourceRange();
3606 return true;
3607}
3608
3609/// \brief Check whether the template parameter is a pack expansion, and if so,
3610/// determine the number of parameters produced by that expansion. For instance:
3611///
3612/// \code
3613/// template<typename ...Ts> struct A {
3614/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3615/// };
3616/// \endcode
3617///
3618/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3619/// is not a pack expansion, so returns an empty Optional.
3620static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3621 if (NonTypeTemplateParmDecl *NTTP
3622 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3623 if (NTTP->isExpandedParameterPack())
3624 return NTTP->getNumExpansionTypes();
3625 }
3626
3627 if (TemplateTemplateParmDecl *TTP
3628 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3629 if (TTP->isExpandedParameterPack())
3630 return TTP->getNumExpansionTemplateParameters();
3631 }
3632
3633 return None;
3634}
3635
3636/// \brief Check that the given template argument list is well-formed
3637/// for specializing the given template.
3638bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3639 SourceLocation TemplateLoc,
3640 TemplateArgumentListInfo &TemplateArgs,
3641 bool PartialTemplateArgs,
3642 SmallVectorImpl<TemplateArgument> &Converted) {
3443 Converted.push_back(Result);
3444 break;
3445 }
3446
3447 case TemplateArgument::Declaration:
3448 case TemplateArgument::Integral:
3449 case TemplateArgument::NullPtr:
3450 // We've already checked this template argument, so just copy
3451 // it to the list of converted arguments.
3452 Converted.push_back(Arg.getArgument());
3453 break;
3454
3455 case TemplateArgument::Template:
3456 case TemplateArgument::TemplateExpansion:
3457 // We were given a template template argument. It may not be ill-formed;
3458 // see below.
3459 if (DependentTemplateName *DTN
3460 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3461 .getAsDependentTemplateName()) {
3462 // We have a template argument such as \c T::template X, which we
3463 // parsed as a template template argument. However, since we now
3464 // know that we need a non-type template argument, convert this
3465 // template name into an expression.
3466
3467 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3468 Arg.getTemplateNameLoc());
3469
3470 CXXScopeSpec SS;
3471 SS.Adopt(Arg.getTemplateQualifierLoc());
3472 // FIXME: the template-template arg was a DependentTemplateName,
3473 // so it was provided with a template keyword. However, its source
3474 // location is not stored in the template argument structure.
3475 SourceLocation TemplateKWLoc;
3476 ExprResult E = DependentScopeDeclRefExpr::Create(
3477 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3478 nullptr);
3479
3480 // If we parsed the template argument as a pack expansion, create a
3481 // pack expansion expression.
3482 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3483 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3484 if (E.isInvalid())
3485 return true;
3486 }
3487
3488 TemplateArgument Result;
3489 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3490 if (E.isInvalid())
3491 return true;
3492
3493 Converted.push_back(Result);
3494 break;
3495 }
3496
3497 // We have a template argument that actually does refer to a class
3498 // template, alias template, or template template parameter, and
3499 // therefore cannot be a non-type template argument.
3500 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3501 << Arg.getSourceRange();
3502
3503 Diag(Param->getLocation(), diag::note_template_param_here);
3504 return true;
3505
3506 case TemplateArgument::Type: {
3507 // We have a non-type template parameter but the template
3508 // argument is a type.
3509
3510 // C++ [temp.arg]p2:
3511 // In a template-argument, an ambiguity between a type-id and
3512 // an expression is resolved to a type-id, regardless of the
3513 // form of the corresponding template-parameter.
3514 //
3515 // We warn specifically about this case, since it can be rather
3516 // confusing for users.
3517 QualType T = Arg.getArgument().getAsType();
3518 SourceRange SR = Arg.getSourceRange();
3519 if (T->isFunctionType())
3520 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3521 else
3522 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3523 Diag(Param->getLocation(), diag::note_template_param_here);
3524 return true;
3525 }
3526
3527 case TemplateArgument::Pack:
3528 llvm_unreachable("Caller must expand template argument packs");
3529 }
3530
3531 return false;
3532 }
3533
3534
3535 // Check template template parameters.
3536 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3537
3538 // Substitute into the template parameter list of the template
3539 // template parameter, since previously-supplied template arguments
3540 // may appear within the template template parameter.
3541 {
3542 // Set up a template instantiation context.
3543 LocalInstantiationScope Scope(*this);
3544 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3545 TempParm, Converted,
3546 SourceRange(TemplateLoc, RAngleLoc));
3547 if (Inst.isInvalid())
3548 return true;
3549
3550 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3551 Converted.data(), Converted.size());
3552 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3553 SubstDecl(TempParm, CurContext,
3554 MultiLevelTemplateArgumentList(TemplateArgs)));
3555 if (!TempParm)
3556 return true;
3557 }
3558
3559 switch (Arg.getArgument().getKind()) {
3560 case TemplateArgument::Null:
3561 llvm_unreachable("Should never see a NULL template argument here");
3562
3563 case TemplateArgument::Template:
3564 case TemplateArgument::TemplateExpansion:
3565 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3566 return true;
3567
3568 Converted.push_back(Arg.getArgument());
3569 break;
3570
3571 case TemplateArgument::Expression:
3572 case TemplateArgument::Type:
3573 // We have a template template parameter but the template
3574 // argument does not refer to a template.
3575 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3576 << getLangOpts().CPlusPlus11;
3577 return true;
3578
3579 case TemplateArgument::Declaration:
3580 llvm_unreachable("Declaration argument with template template parameter");
3581 case TemplateArgument::Integral:
3582 llvm_unreachable("Integral argument with template template parameter");
3583 case TemplateArgument::NullPtr:
3584 llvm_unreachable("Null pointer argument with template template parameter");
3585
3586 case TemplateArgument::Pack:
3587 llvm_unreachable("Caller must expand template argument packs");
3588 }
3589
3590 return false;
3591}
3592
3593/// \brief Diagnose an arity mismatch in the
3594static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3595 SourceLocation TemplateLoc,
3596 TemplateArgumentListInfo &TemplateArgs) {
3597 TemplateParameterList *Params = Template->getTemplateParameters();
3598 unsigned NumParams = Params->size();
3599 unsigned NumArgs = TemplateArgs.size();
3600
3601 SourceRange Range;
3602 if (NumArgs > NumParams)
3603 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3604 TemplateArgs.getRAngleLoc());
3605 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3606 << (NumArgs > NumParams)
3607 << (isa<ClassTemplateDecl>(Template)? 0 :
3608 isa<FunctionTemplateDecl>(Template)? 1 :
3609 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3610 << Template << Range;
3611 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3612 << Params->getSourceRange();
3613 return true;
3614}
3615
3616/// \brief Check whether the template parameter is a pack expansion, and if so,
3617/// determine the number of parameters produced by that expansion. For instance:
3618///
3619/// \code
3620/// template<typename ...Ts> struct A {
3621/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3622/// };
3623/// \endcode
3624///
3625/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3626/// is not a pack expansion, so returns an empty Optional.
3627static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3628 if (NonTypeTemplateParmDecl *NTTP
3629 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3630 if (NTTP->isExpandedParameterPack())
3631 return NTTP->getNumExpansionTypes();
3632 }
3633
3634 if (TemplateTemplateParmDecl *TTP
3635 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3636 if (TTP->isExpandedParameterPack())
3637 return TTP->getNumExpansionTemplateParameters();
3638 }
3639
3640 return None;
3641}
3642
3643/// \brief Check that the given template argument list is well-formed
3644/// for specializing the given template.
3645bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3646 SourceLocation TemplateLoc,
3647 TemplateArgumentListInfo &TemplateArgs,
3648 bool PartialTemplateArgs,
3649 SmallVectorImpl<TemplateArgument> &Converted) {
3650 // Make a copy of the template arguments for processing. Only make the
3651 // changes at the end when successful in matching the arguments to the
3652 // template.
3653 TemplateArgumentListInfo NewArgs = TemplateArgs;
3654
3643 TemplateParameterList *Params = Template->getTemplateParameters();
3644
3655 TemplateParameterList *Params = Template->getTemplateParameters();
3656
3645 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3657 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3646
3647 // C++ [temp.arg]p1:
3648 // [...] The type and form of each template-argument specified in
3649 // a template-id shall match the type and form specified for the
3650 // corresponding parameter declared by the template in its
3651 // template-parameter-list.
3652 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3653 SmallVector<TemplateArgument, 2> ArgumentPack;
3658
3659 // C++ [temp.arg]p1:
3660 // [...] The type and form of each template-argument specified in
3661 // a template-id shall match the type and form specified for the
3662 // corresponding parameter declared by the template in its
3663 // template-parameter-list.
3664 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3665 SmallVector<TemplateArgument, 2> ArgumentPack;
3654 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
3666 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3655 LocalInstantiationScope InstScope(*this, true);
3656 for (TemplateParameterList::iterator Param = Params->begin(),
3657 ParamEnd = Params->end();
3658 Param != ParamEnd; /* increment in loop */) {
3659 // If we have an expanded parameter pack, make sure we don't have too
3660 // many arguments.
3661 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3662 if (*Expansions == ArgumentPack.size()) {
3663 // We're done with this parameter pack. Pack up its arguments and add
3664 // them to the list.
3665 Converted.push_back(
3666 TemplateArgument::CreatePackCopy(Context,
3667 ArgumentPack.data(),
3668 ArgumentPack.size()));
3669 ArgumentPack.clear();
3670
3671 // This argument is assigned to the next parameter.
3672 ++Param;
3673 continue;
3674 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3675 // Not enough arguments for this parameter pack.
3676 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3677 << false
3678 << (isa<ClassTemplateDecl>(Template)? 0 :
3679 isa<FunctionTemplateDecl>(Template)? 1 :
3680 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3681 << Template;
3682 Diag(Template->getLocation(), diag::note_template_decl_here)
3683 << Params->getSourceRange();
3684 return true;
3685 }
3686 }
3687
3688 if (ArgIdx < NumArgs) {
3689 // Check the template argument we were given.
3667 LocalInstantiationScope InstScope(*this, true);
3668 for (TemplateParameterList::iterator Param = Params->begin(),
3669 ParamEnd = Params->end();
3670 Param != ParamEnd; /* increment in loop */) {
3671 // If we have an expanded parameter pack, make sure we don't have too
3672 // many arguments.
3673 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3674 if (*Expansions == ArgumentPack.size()) {
3675 // We're done with this parameter pack. Pack up its arguments and add
3676 // them to the list.
3677 Converted.push_back(
3678 TemplateArgument::CreatePackCopy(Context,
3679 ArgumentPack.data(),
3680 ArgumentPack.size()));
3681 ArgumentPack.clear();
3682
3683 // This argument is assigned to the next parameter.
3684 ++Param;
3685 continue;
3686 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3687 // Not enough arguments for this parameter pack.
3688 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3689 << false
3690 << (isa<ClassTemplateDecl>(Template)? 0 :
3691 isa<FunctionTemplateDecl>(Template)? 1 :
3692 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3693 << Template;
3694 Diag(Template->getLocation(), diag::note_template_decl_here)
3695 << Params->getSourceRange();
3696 return true;
3697 }
3698 }
3699
3700 if (ArgIdx < NumArgs) {
3701 // Check the template argument we were given.
3690 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3702 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3691 TemplateLoc, RAngleLoc,
3692 ArgumentPack.size(), Converted))
3693 return true;
3694
3695 bool PackExpansionIntoNonPack =
3703 TemplateLoc, RAngleLoc,
3704 ArgumentPack.size(), Converted))
3705 return true;
3706
3707 bool PackExpansionIntoNonPack =
3696 TemplateArgs[ArgIdx].getArgument().isPackExpansion() &&
3708 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3697 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3698 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3699 // Core issue 1430: we have a pack expansion as an argument to an
3700 // alias template, and it's not part of a parameter pack. This
3701 // can't be canonicalized, so reject it now.
3709 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3710 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3711 // Core issue 1430: we have a pack expansion as an argument to an
3712 // alias template, and it's not part of a parameter pack. This
3713 // can't be canonicalized, so reject it now.
3702 Diag(TemplateArgs[ArgIdx].getLocation(),
3714 Diag(NewArgs[ArgIdx].getLocation(),
3703 diag::err_alias_template_expansion_into_fixed_list)
3715 diag::err_alias_template_expansion_into_fixed_list)
3704 << TemplateArgs[ArgIdx].getSourceRange();
3716 << NewArgs[ArgIdx].getSourceRange();
3705 Diag((*Param)->getLocation(), diag::note_template_param_here);
3706 return true;
3707 }
3708
3709 // We're now done with this argument.
3710 ++ArgIdx;
3711
3712 if ((*Param)->isTemplateParameterPack()) {
3713 // The template parameter was a template parameter pack, so take the
3714 // deduced argument and place it on the argument pack. Note that we
3715 // stay on the same template parameter so that we can deduce more
3716 // arguments.
3717 ArgumentPack.push_back(Converted.pop_back_val());
3718 } else {
3719 // Move to the next template parameter.
3720 ++Param;
3721 }
3722
3723 // If we just saw a pack expansion into a non-pack, then directly convert
3724 // the remaining arguments, because we don't know what parameters they'll
3725 // match up with.
3726 if (PackExpansionIntoNonPack) {
3727 if (!ArgumentPack.empty()) {
3728 // If we were part way through filling in an expanded parameter pack,
3729 // fall back to just producing individual arguments.
3730 Converted.insert(Converted.end(),
3731 ArgumentPack.begin(), ArgumentPack.end());
3732 ArgumentPack.clear();
3733 }
3734
3735 while (ArgIdx < NumArgs) {
3717 Diag((*Param)->getLocation(), diag::note_template_param_here);
3718 return true;
3719 }
3720
3721 // We're now done with this argument.
3722 ++ArgIdx;
3723
3724 if ((*Param)->isTemplateParameterPack()) {
3725 // The template parameter was a template parameter pack, so take the
3726 // deduced argument and place it on the argument pack. Note that we
3727 // stay on the same template parameter so that we can deduce more
3728 // arguments.
3729 ArgumentPack.push_back(Converted.pop_back_val());
3730 } else {
3731 // Move to the next template parameter.
3732 ++Param;
3733 }
3734
3735 // If we just saw a pack expansion into a non-pack, then directly convert
3736 // the remaining arguments, because we don't know what parameters they'll
3737 // match up with.
3738 if (PackExpansionIntoNonPack) {
3739 if (!ArgumentPack.empty()) {
3740 // If we were part way through filling in an expanded parameter pack,
3741 // fall back to just producing individual arguments.
3742 Converted.insert(Converted.end(),
3743 ArgumentPack.begin(), ArgumentPack.end());
3744 ArgumentPack.clear();
3745 }
3746
3747 while (ArgIdx < NumArgs) {
3736 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3748 Converted.push_back(NewArgs[ArgIdx].getArgument());
3737 ++ArgIdx;
3738 }
3739
3740 return false;
3741 }
3742
3743 continue;
3744 }
3745
3746 // If we're checking a partial template argument list, we're done.
3747 if (PartialTemplateArgs) {
3748 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3749 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3750 ArgumentPack.data(),
3751 ArgumentPack.size()));
3752
3753 return false;
3754 }
3755
3756 // If we have a template parameter pack with no more corresponding
3757 // arguments, just break out now and we'll fill in the argument pack below.
3758 if ((*Param)->isTemplateParameterPack()) {
3759 assert(!getExpandedPackSize(*Param) &&
3760 "Should have dealt with this already");
3761
3762 // A non-expanded parameter pack before the end of the parameter list
3763 // only occurs for an ill-formed template parameter list, unless we've
3764 // got a partial argument list for a function template, so just bail out.
3765 if (Param + 1 != ParamEnd)
3766 return true;
3767
3768 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3769 ArgumentPack.data(),
3770 ArgumentPack.size()));
3771 ArgumentPack.clear();
3772
3773 ++Param;
3774 continue;
3775 }
3776
3777 // Check whether we have a default argument.
3778 TemplateArgumentLoc Arg;
3779
3780 // Retrieve the default template argument from the template
3781 // parameter. For each kind of template parameter, we substitute the
3782 // template arguments provided thus far and any "outer" template arguments
3783 // (when the template parameter was part of a nested template) into
3784 // the default argument.
3785 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3786 if (!TTP->hasDefaultArgument())
3749 ++ArgIdx;
3750 }
3751
3752 return false;
3753 }
3754
3755 continue;
3756 }
3757
3758 // If we're checking a partial template argument list, we're done.
3759 if (PartialTemplateArgs) {
3760 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3761 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3762 ArgumentPack.data(),
3763 ArgumentPack.size()));
3764
3765 return false;
3766 }
3767
3768 // If we have a template parameter pack with no more corresponding
3769 // arguments, just break out now and we'll fill in the argument pack below.
3770 if ((*Param)->isTemplateParameterPack()) {
3771 assert(!getExpandedPackSize(*Param) &&
3772 "Should have dealt with this already");
3773
3774 // A non-expanded parameter pack before the end of the parameter list
3775 // only occurs for an ill-formed template parameter list, unless we've
3776 // got a partial argument list for a function template, so just bail out.
3777 if (Param + 1 != ParamEnd)
3778 return true;
3779
3780 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3781 ArgumentPack.data(),
3782 ArgumentPack.size()));
3783 ArgumentPack.clear();
3784
3785 ++Param;
3786 continue;
3787 }
3788
3789 // Check whether we have a default argument.
3790 TemplateArgumentLoc Arg;
3791
3792 // Retrieve the default template argument from the template
3793 // parameter. For each kind of template parameter, we substitute the
3794 // template arguments provided thus far and any "outer" template arguments
3795 // (when the template parameter was part of a nested template) into
3796 // the default argument.
3797 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3798 if (!TTP->hasDefaultArgument())
3787 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3788 TemplateArgs);
3799 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3789
3790 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3791 Template,
3792 TemplateLoc,
3793 RAngleLoc,
3794 TTP,
3795 Converted);
3796 if (!ArgType)
3797 return true;
3798
3799 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3800 ArgType);
3801 } else if (NonTypeTemplateParmDecl *NTTP
3802 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3803 if (!NTTP->hasDefaultArgument())
3800
3801 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3802 Template,
3803 TemplateLoc,
3804 RAngleLoc,
3805 TTP,
3806 Converted);
3807 if (!ArgType)
3808 return true;
3809
3810 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3811 ArgType);
3812 } else if (NonTypeTemplateParmDecl *NTTP
3813 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3814 if (!NTTP->hasDefaultArgument())
3804 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3805 TemplateArgs);
3815 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3806
3807 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3808 TemplateLoc,
3809 RAngleLoc,
3810 NTTP,
3811 Converted);
3812 if (E.isInvalid())
3813 return true;
3814
3815 Expr *Ex = E.getAs<Expr>();
3816 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3817 } else {
3818 TemplateTemplateParmDecl *TempParm
3819 = cast<TemplateTemplateParmDecl>(*Param);
3820
3821 if (!TempParm->hasDefaultArgument())
3816
3817 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3818 TemplateLoc,
3819 RAngleLoc,
3820 NTTP,
3821 Converted);
3822 if (E.isInvalid())
3823 return true;
3824
3825 Expr *Ex = E.getAs<Expr>();
3826 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3827 } else {
3828 TemplateTemplateParmDecl *TempParm
3829 = cast<TemplateTemplateParmDecl>(*Param);
3830
3831 if (!TempParm->hasDefaultArgument())
3822 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3823 TemplateArgs);
3832 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3824
3825 NestedNameSpecifierLoc QualifierLoc;
3826 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3827 TemplateLoc,
3828 RAngleLoc,
3829 TempParm,
3830 Converted,
3831 QualifierLoc);
3832 if (Name.isNull())
3833 return true;
3834
3835 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3836 TempParm->getDefaultArgument().getTemplateNameLoc());
3837 }
3838
3839 // Introduce an instantiation record that describes where we are using
3840 // the default template argument.
3841 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3842 SourceRange(TemplateLoc, RAngleLoc));
3843 if (Inst.isInvalid())
3844 return true;
3845
3846 // Check the default template argument.
3847 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3848 RAngleLoc, 0, Converted))
3849 return true;
3850
3833
3834 NestedNameSpecifierLoc QualifierLoc;
3835 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3836 TemplateLoc,
3837 RAngleLoc,
3838 TempParm,
3839 Converted,
3840 QualifierLoc);
3841 if (Name.isNull())
3842 return true;
3843
3844 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3845 TempParm->getDefaultArgument().getTemplateNameLoc());
3846 }
3847
3848 // Introduce an instantiation record that describes where we are using
3849 // the default template argument.
3850 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3851 SourceRange(TemplateLoc, RAngleLoc));
3852 if (Inst.isInvalid())
3853 return true;
3854
3855 // Check the default template argument.
3856 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3857 RAngleLoc, 0, Converted))
3858 return true;
3859
3851 // Core issue 150 (assumed resolution): if this is a template template
3852 // parameter, keep track of the default template arguments from the
3860 // Core issue 150 (assumed resolution): if this is a template template
3861 // parameter, keep track of the default template arguments from the
3853 // template definition.
3854 if (isTemplateTemplateParameter)
3862 // template definition.
3863 if (isTemplateTemplateParameter)
3855 TemplateArgs.addArgument(Arg);
3856
3864 NewArgs.addArgument(Arg);
3865
3857 // Move to the next template parameter and argument.
3858 ++Param;
3859 ++ArgIdx;
3860 }
3861
3862 // If we're performing a partial argument substitution, allow any trailing
3863 // pack expansions; they might be empty. This can happen even if
3864 // PartialTemplateArgs is false (the list of arguments is complete but
3865 // still dependent).
3866 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3867 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3866 // Move to the next template parameter and argument.
3867 ++Param;
3868 ++ArgIdx;
3869 }
3870
3871 // If we're performing a partial argument substitution, allow any trailing
3872 // pack expansions; they might be empty. This can happen even if
3873 // PartialTemplateArgs is false (the list of arguments is complete but
3874 // still dependent).
3875 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3876 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3868 while (ArgIdx < NumArgs &&
3869 TemplateArgs[ArgIdx].getArgument().isPackExpansion())
3870 Converted.push_back(TemplateArgs[ArgIdx++].getArgument());
3877 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3878 Converted.push_back(NewArgs[ArgIdx++].getArgument());
3871 }
3872
3873 // If we have any leftover arguments, then there were too many arguments.
3874 // Complain and fail.
3875 if (ArgIdx < NumArgs)
3879 }
3880
3881 // If we have any leftover arguments, then there were too many arguments.
3882 // Complain and fail.
3883 if (ArgIdx < NumArgs)
3876 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
3884 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3877
3885
3886 // No problems found with the new argument list, propagate changes back
3887 // to caller.
3888 TemplateArgs = NewArgs;
3889
3878 return false;
3879}
3880
3881namespace {
3882 class UnnamedLocalNoLinkageFinder
3883 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3884 {
3885 Sema &S;
3886 SourceRange SR;
3887
3888 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3889
3890 public:
3891 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3892
3893 bool Visit(QualType T) {
3894 return inherited::Visit(T.getTypePtr());
3895 }
3896
3897#define TYPE(Class, Parent) \
3898 bool Visit##Class##Type(const Class##Type *);
3899#define ABSTRACT_TYPE(Class, Parent) \
3900 bool Visit##Class##Type(const Class##Type *) { return false; }
3901#define NON_CANONICAL_TYPE(Class, Parent) \
3902 bool Visit##Class##Type(const Class##Type *) { return false; }
3903#include "clang/AST/TypeNodes.def"
3904
3905 bool VisitTagDecl(const TagDecl *Tag);
3906 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3907 };
3908}
3909
3910bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3911 return false;
3912}
3913
3914bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3915 return Visit(T->getElementType());
3916}
3917
3918bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3919 return Visit(T->getPointeeType());
3920}
3921
3922bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3923 const BlockPointerType* T) {
3924 return Visit(T->getPointeeType());
3925}
3926
3927bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3928 const LValueReferenceType* T) {
3929 return Visit(T->getPointeeType());
3930}
3931
3932bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3933 const RValueReferenceType* T) {
3934 return Visit(T->getPointeeType());
3935}
3936
3937bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3938 const MemberPointerType* T) {
3939 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3940}
3941
3942bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3943 const ConstantArrayType* T) {
3944 return Visit(T->getElementType());
3945}
3946
3947bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3948 const IncompleteArrayType* T) {
3949 return Visit(T->getElementType());
3950}
3951
3952bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3953 const VariableArrayType* T) {
3954 return Visit(T->getElementType());
3955}
3956
3957bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3958 const DependentSizedArrayType* T) {
3959 return Visit(T->getElementType());
3960}
3961
3962bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3963 const DependentSizedExtVectorType* T) {
3964 return Visit(T->getElementType());
3965}
3966
3967bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3968 return Visit(T->getElementType());
3969}
3970
3971bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3972 return Visit(T->getElementType());
3973}
3974
3975bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3976 const FunctionProtoType* T) {
3977 for (const auto &A : T->param_types()) {
3978 if (Visit(A))
3979 return true;
3980 }
3981
3982 return Visit(T->getReturnType());
3983}
3984
3985bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3986 const FunctionNoProtoType* T) {
3987 return Visit(T->getReturnType());
3988}
3989
3990bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3991 const UnresolvedUsingType*) {
3992 return false;
3993}
3994
3995bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3996 return false;
3997}
3998
3999bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4000 return Visit(T->getUnderlyingType());
4001}
4002
4003bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4004 return false;
4005}
4006
4007bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4008 const UnaryTransformType*) {
4009 return false;
4010}
4011
4012bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4013 return Visit(T->getDeducedType());
4014}
4015
4016bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4017 return VisitTagDecl(T->getDecl());
4018}
4019
4020bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4021 return VisitTagDecl(T->getDecl());
4022}
4023
4024bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4025 const TemplateTypeParmType*) {
4026 return false;
4027}
4028
4029bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4030 const SubstTemplateTypeParmPackType *) {
4031 return false;
4032}
4033
4034bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4035 const TemplateSpecializationType*) {
4036 return false;
4037}
4038
4039bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4040 const InjectedClassNameType* T) {
4041 return VisitTagDecl(T->getDecl());
4042}
4043
4044bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4045 const DependentNameType* T) {
4046 return VisitNestedNameSpecifier(T->getQualifier());
4047}
4048
4049bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4050 const DependentTemplateSpecializationType* T) {
4051 return VisitNestedNameSpecifier(T->getQualifier());
4052}
4053
4054bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4055 const PackExpansionType* T) {
4056 return Visit(T->getPattern());
4057}
4058
4059bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4060 return false;
4061}
4062
4063bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4064 const ObjCInterfaceType *) {
4065 return false;
4066}
4067
4068bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4069 const ObjCObjectPointerType *) {
4070 return false;
4071}
4072
4073bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4074 return Visit(T->getValueType());
4075}
4076
4077bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4078 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4079 S.Diag(SR.getBegin(),
4080 S.getLangOpts().CPlusPlus11 ?
4081 diag::warn_cxx98_compat_template_arg_local_type :
4082 diag::ext_template_arg_local_type)
4083 << S.Context.getTypeDeclType(Tag) << SR;
4084 return true;
4085 }
4086
4087 if (!Tag->hasNameForLinkage()) {
4088 S.Diag(SR.getBegin(),
4089 S.getLangOpts().CPlusPlus11 ?
4090 diag::warn_cxx98_compat_template_arg_unnamed_type :
4091 diag::ext_template_arg_unnamed_type) << SR;
4092 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4093 return true;
4094 }
4095
4096 return false;
4097}
4098
4099bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4100 NestedNameSpecifier *NNS) {
4101 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4102 return true;
4103
4104 switch (NNS->getKind()) {
4105 case NestedNameSpecifier::Identifier:
4106 case NestedNameSpecifier::Namespace:
4107 case NestedNameSpecifier::NamespaceAlias:
4108 case NestedNameSpecifier::Global:
4109 case NestedNameSpecifier::Super:
4110 return false;
4111
4112 case NestedNameSpecifier::TypeSpec:
4113 case NestedNameSpecifier::TypeSpecWithTemplate:
4114 return Visit(QualType(NNS->getAsType(), 0));
4115 }
4116 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4117}
4118
4119
4120/// \brief Check a template argument against its corresponding
4121/// template type parameter.
4122///
4123/// This routine implements the semantics of C++ [temp.arg.type]. It
4124/// returns true if an error occurred, and false otherwise.
4125bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4126 TypeSourceInfo *ArgInfo) {
4127 assert(ArgInfo && "invalid TypeSourceInfo");
4128 QualType Arg = ArgInfo->getType();
4129 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4130
4131 if (Arg->isVariablyModifiedType()) {
4132 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4133 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4134 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4135 }
4136
4137 // C++03 [temp.arg.type]p2:
4138 // A local type, a type with no linkage, an unnamed type or a type
4139 // compounded from any of these types shall not be used as a
4140 // template-argument for a template type-parameter.
4141 //
4142 // C++11 allows these, and even in C++03 we allow them as an extension with
4143 // a warning.
4144 bool NeedsCheck;
4145 if (LangOpts.CPlusPlus11)
4146 NeedsCheck =
4147 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4148 SR.getBegin()) ||
4149 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4150 SR.getBegin());
4151 else
4152 NeedsCheck = Arg->hasUnnamedOrLocalType();
4153
4154 if (NeedsCheck) {
4155 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4156 (void)Finder.Visit(Context.getCanonicalType(Arg));
4157 }
4158
4159 return false;
4160}
4161
4162enum NullPointerValueKind {
4163 NPV_NotNullPointer,
4164 NPV_NullPointer,
4165 NPV_Error
4166};
4167
4168/// \brief Determine whether the given template argument is a null pointer
4169/// value of the appropriate type.
4170static NullPointerValueKind
4171isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4172 QualType ParamType, Expr *Arg) {
4173 if (Arg->isValueDependent() || Arg->isTypeDependent())
4174 return NPV_NotNullPointer;
4175
4176 if (!S.getLangOpts().CPlusPlus11)
4177 return NPV_NotNullPointer;
4178
4179 // Determine whether we have a constant expression.
4180 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4181 if (ArgRV.isInvalid())
4182 return NPV_Error;
4183 Arg = ArgRV.get();
4184
4185 Expr::EvalResult EvalResult;
4186 SmallVector<PartialDiagnosticAt, 8> Notes;
4187 EvalResult.Diag = &Notes;
4188 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4189 EvalResult.HasSideEffects) {
4190 SourceLocation DiagLoc = Arg->getExprLoc();
4191
4192 // If our only note is the usual "invalid subexpression" note, just point
4193 // the caret at its location rather than producing an essentially
4194 // redundant note.
4195 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4196 diag::note_invalid_subexpr_in_const_expr) {
4197 DiagLoc = Notes[0].first;
4198 Notes.clear();
4199 }
4200
4201 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4202 << Arg->getType() << Arg->getSourceRange();
4203 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4204 S.Diag(Notes[I].first, Notes[I].second);
4205
4206 S.Diag(Param->getLocation(), diag::note_template_param_here);
4207 return NPV_Error;
4208 }
4209
4210 // C++11 [temp.arg.nontype]p1:
4211 // - an address constant expression of type std::nullptr_t
4212 if (Arg->getType()->isNullPtrType())
4213 return NPV_NullPointer;
4214
4215 // - a constant expression that evaluates to a null pointer value (4.10); or
4216 // - a constant expression that evaluates to a null member pointer value
4217 // (4.11); or
4218 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4219 (EvalResult.Val.isMemberPointer() &&
4220 !EvalResult.Val.getMemberPointerDecl())) {
4221 // If our expression has an appropriate type, we've succeeded.
4222 bool ObjCLifetimeConversion;
4223 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4224 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4225 ObjCLifetimeConversion))
4226 return NPV_NullPointer;
4227
4228 // The types didn't match, but we know we got a null pointer; complain,
4229 // then recover as if the types were correct.
4230 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4231 << Arg->getType() << ParamType << Arg->getSourceRange();
4232 S.Diag(Param->getLocation(), diag::note_template_param_here);
4233 return NPV_NullPointer;
4234 }
4235
4236 // If we don't have a null pointer value, but we do have a NULL pointer
4237 // constant, suggest a cast to the appropriate type.
4238 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4239 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4240 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4241 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4242 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4243 ")");
4244 S.Diag(Param->getLocation(), diag::note_template_param_here);
4245 return NPV_NullPointer;
4246 }
4247
4248 // FIXME: If we ever want to support general, address-constant expressions
4249 // as non-type template arguments, we should return the ExprResult here to
4250 // be interpreted by the caller.
4251 return NPV_NotNullPointer;
4252}
4253
4254/// \brief Checks whether the given template argument is compatible with its
4255/// template parameter.
4256static bool CheckTemplateArgumentIsCompatibleWithParameter(
4257 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4258 Expr *Arg, QualType ArgType) {
4259 bool ObjCLifetimeConversion;
4260 if (ParamType->isPointerType() &&
4261 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4262 S.IsQualificationConversion(ArgType, ParamType, false,
4263 ObjCLifetimeConversion)) {
4264 // For pointer-to-object types, qualification conversions are
4265 // permitted.
4266 } else {
4267 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4268 if (!ParamRef->getPointeeType()->isFunctionType()) {
4269 // C++ [temp.arg.nontype]p5b3:
4270 // For a non-type template-parameter of type reference to
4271 // object, no conversions apply. The type referred to by the
4272 // reference may be more cv-qualified than the (otherwise
4273 // identical) type of the template- argument. The
4274 // template-parameter is bound directly to the
4275 // template-argument, which shall be an lvalue.
4276
4277 // FIXME: Other qualifiers?
4278 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4279 unsigned ArgQuals = ArgType.getCVRQualifiers();
4280
4281 if ((ParamQuals | ArgQuals) != ParamQuals) {
4282 S.Diag(Arg->getLocStart(),
4283 diag::err_template_arg_ref_bind_ignores_quals)
4284 << ParamType << Arg->getType() << Arg->getSourceRange();
4285 S.Diag(Param->getLocation(), diag::note_template_param_here);
4286 return true;
4287 }
4288 }
4289 }
4290
4291 // At this point, the template argument refers to an object or
4292 // function with external linkage. We now need to check whether the
4293 // argument and parameter types are compatible.
4294 if (!S.Context.hasSameUnqualifiedType(ArgType,
4295 ParamType.getNonReferenceType())) {
4296 // We can't perform this conversion or binding.
4297 if (ParamType->isReferenceType())
4298 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4299 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4300 else
4301 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4302 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4303 S.Diag(Param->getLocation(), diag::note_template_param_here);
4304 return true;
4305 }
4306 }
4307
4308 return false;
4309}
4310
4311/// \brief Checks whether the given template argument is the address
4312/// of an object or function according to C++ [temp.arg.nontype]p1.
4313static bool
4314CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4315 NonTypeTemplateParmDecl *Param,
4316 QualType ParamType,
4317 Expr *ArgIn,
4318 TemplateArgument &Converted) {
4319 bool Invalid = false;
4320 Expr *Arg = ArgIn;
4321 QualType ArgType = Arg->getType();
4322
4323 bool AddressTaken = false;
4324 SourceLocation AddrOpLoc;
4325 if (S.getLangOpts().MicrosoftExt) {
4326 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4327 // dereference and address-of operators.
4328 Arg = Arg->IgnoreParenCasts();
4329
4330 bool ExtWarnMSTemplateArg = false;
4331 UnaryOperatorKind FirstOpKind;
4332 SourceLocation FirstOpLoc;
4333 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4334 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4335 if (UnOpKind == UO_Deref)
4336 ExtWarnMSTemplateArg = true;
4337 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4338 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4339 if (!AddrOpLoc.isValid()) {
4340 FirstOpKind = UnOpKind;
4341 FirstOpLoc = UnOp->getOperatorLoc();
4342 }
4343 } else
4344 break;
4345 }
4346 if (FirstOpLoc.isValid()) {
4347 if (ExtWarnMSTemplateArg)
4348 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4349 << ArgIn->getSourceRange();
4350
4351 if (FirstOpKind == UO_AddrOf)
4352 AddressTaken = true;
4353 else if (Arg->getType()->isPointerType()) {
4354 // We cannot let pointers get dereferenced here, that is obviously not a
4355 // constant expression.
4356 assert(FirstOpKind == UO_Deref);
4357 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4358 << Arg->getSourceRange();
4359 }
4360 }
4361 } else {
4362 // See through any implicit casts we added to fix the type.
4363 Arg = Arg->IgnoreImpCasts();
4364
4365 // C++ [temp.arg.nontype]p1:
4366 //
4367 // A template-argument for a non-type, non-template
4368 // template-parameter shall be one of: [...]
4369 //
4370 // -- the address of an object or function with external
4371 // linkage, including function templates and function
4372 // template-ids but excluding non-static class members,
4373 // expressed as & id-expression where the & is optional if
4374 // the name refers to a function or array, or if the
4375 // corresponding template-parameter is a reference; or
4376
4377 // In C++98/03 mode, give an extension warning on any extra parentheses.
4378 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4379 bool ExtraParens = false;
4380 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4381 if (!Invalid && !ExtraParens) {
4382 S.Diag(Arg->getLocStart(),
4383 S.getLangOpts().CPlusPlus11
4384 ? diag::warn_cxx98_compat_template_arg_extra_parens
4385 : diag::ext_template_arg_extra_parens)
4386 << Arg->getSourceRange();
4387 ExtraParens = true;
4388 }
4389
4390 Arg = Parens->getSubExpr();
4391 }
4392
4393 while (SubstNonTypeTemplateParmExpr *subst =
4394 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4395 Arg = subst->getReplacement()->IgnoreImpCasts();
4396
4397 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4398 if (UnOp->getOpcode() == UO_AddrOf) {
4399 Arg = UnOp->getSubExpr();
4400 AddressTaken = true;
4401 AddrOpLoc = UnOp->getOperatorLoc();
4402 }
4403 }
4404
4405 while (SubstNonTypeTemplateParmExpr *subst =
4406 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4407 Arg = subst->getReplacement()->IgnoreImpCasts();
4408 }
4409
4410 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4411 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4412
4413 // If our parameter has pointer type, check for a null template value.
4414 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4415 NullPointerValueKind NPV;
4416 // dllimport'd entities aren't constant but are available inside of template
4417 // arguments.
4418 if (Entity && Entity->hasAttr<DLLImportAttr>())
4419 NPV = NPV_NotNullPointer;
4420 else
4421 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4422 switch (NPV) {
4423 case NPV_NullPointer:
4424 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4425 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4426 /*isNullPtr=*/true);
4427 return false;
4428
4429 case NPV_Error:
4430 return true;
4431
4432 case NPV_NotNullPointer:
4433 break;
4434 }
4435 }
4436
4437 // Stop checking the precise nature of the argument if it is value dependent,
4438 // it should be checked when instantiated.
4439 if (Arg->isValueDependent()) {
4440 Converted = TemplateArgument(ArgIn);
4441 return false;
4442 }
4443
4444 if (isa<CXXUuidofExpr>(Arg)) {
4445 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4446 ArgIn, Arg, ArgType))
4447 return true;
4448
4449 Converted = TemplateArgument(ArgIn);
4450 return false;
4451 }
4452
4453 if (!DRE) {
4454 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4455 << Arg->getSourceRange();
4456 S.Diag(Param->getLocation(), diag::note_template_param_here);
4457 return true;
4458 }
4459
4460 // Cannot refer to non-static data members
4461 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4462 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4463 << Entity << Arg->getSourceRange();
4464 S.Diag(Param->getLocation(), diag::note_template_param_here);
4465 return true;
4466 }
4467
4468 // Cannot refer to non-static member functions
4469 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4470 if (!Method->isStatic()) {
4471 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4472 << Method << Arg->getSourceRange();
4473 S.Diag(Param->getLocation(), diag::note_template_param_here);
4474 return true;
4475 }
4476 }
4477
4478 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4479 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4480
4481 // A non-type template argument must refer to an object or function.
4482 if (!Func && !Var) {
4483 // We found something, but we don't know specifically what it is.
4484 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4485 << Arg->getSourceRange();
4486 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4487 return true;
4488 }
4489
4490 // Address / reference template args must have external linkage in C++98.
4491 if (Entity->getFormalLinkage() == InternalLinkage) {
4492 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4493 diag::warn_cxx98_compat_template_arg_object_internal :
4494 diag::ext_template_arg_object_internal)
4495 << !Func << Entity << Arg->getSourceRange();
4496 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4497 << !Func;
4498 } else if (!Entity->hasLinkage()) {
4499 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4500 << !Func << Entity << Arg->getSourceRange();
4501 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4502 << !Func;
4503 return true;
4504 }
4505
4506 if (Func) {
4507 // If the template parameter has pointer type, the function decays.
4508 if (ParamType->isPointerType() && !AddressTaken)
4509 ArgType = S.Context.getPointerType(Func->getType());
4510 else if (AddressTaken && ParamType->isReferenceType()) {
4511 // If we originally had an address-of operator, but the
4512 // parameter has reference type, complain and (if things look
4513 // like they will work) drop the address-of operator.
4514 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4515 ParamType.getNonReferenceType())) {
4516 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4517 << ParamType;
4518 S.Diag(Param->getLocation(), diag::note_template_param_here);
4519 return true;
4520 }
4521
4522 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4523 << ParamType
4524 << FixItHint::CreateRemoval(AddrOpLoc);
4525 S.Diag(Param->getLocation(), diag::note_template_param_here);
4526
4527 ArgType = Func->getType();
4528 }
4529 } else {
4530 // A value of reference type is not an object.
4531 if (Var->getType()->isReferenceType()) {
4532 S.Diag(Arg->getLocStart(),
4533 diag::err_template_arg_reference_var)
4534 << Var->getType() << Arg->getSourceRange();
4535 S.Diag(Param->getLocation(), diag::note_template_param_here);
4536 return true;
4537 }
4538
4539 // A template argument must have static storage duration.
4540 if (Var->getTLSKind()) {
4541 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4542 << Arg->getSourceRange();
4543 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4544 return true;
4545 }
4546
4547 // If the template parameter has pointer type, we must have taken
4548 // the address of this object.
4549 if (ParamType->isReferenceType()) {
4550 if (AddressTaken) {
4551 // If we originally had an address-of operator, but the
4552 // parameter has reference type, complain and (if things look
4553 // like they will work) drop the address-of operator.
4554 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4555 ParamType.getNonReferenceType())) {
4556 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4557 << ParamType;
4558 S.Diag(Param->getLocation(), diag::note_template_param_here);
4559 return true;
4560 }
4561
4562 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4563 << ParamType
4564 << FixItHint::CreateRemoval(AddrOpLoc);
4565 S.Diag(Param->getLocation(), diag::note_template_param_here);
4566
4567 ArgType = Var->getType();
4568 }
4569 } else if (!AddressTaken && ParamType->isPointerType()) {
4570 if (Var->getType()->isArrayType()) {
4571 // Array-to-pointer decay.
4572 ArgType = S.Context.getArrayDecayedType(Var->getType());
4573 } else {
4574 // If the template parameter has pointer type but the address of
4575 // this object was not taken, complain and (possibly) recover by
4576 // taking the address of the entity.
4577 ArgType = S.Context.getPointerType(Var->getType());
4578 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4579 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4580 << ParamType;
4581 S.Diag(Param->getLocation(), diag::note_template_param_here);
4582 return true;
4583 }
4584
4585 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4586 << ParamType
4587 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4588
4589 S.Diag(Param->getLocation(), diag::note_template_param_here);
4590 }
4591 }
4592 }
4593
4594 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4595 Arg, ArgType))
4596 return true;
4597
4598 // Create the template argument.
4599 Converted =
4600 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4601 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4602 return false;
4603}
4604
4605/// \brief Checks whether the given template argument is a pointer to
4606/// member constant according to C++ [temp.arg.nontype]p1.
4607static bool CheckTemplateArgumentPointerToMember(Sema &S,
4608 NonTypeTemplateParmDecl *Param,
4609 QualType ParamType,
4610 Expr *&ResultArg,
4611 TemplateArgument &Converted) {
4612 bool Invalid = false;
4613
4614 // Check for a null pointer value.
4615 Expr *Arg = ResultArg;
4616 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4617 case NPV_Error:
4618 return true;
4619 case NPV_NullPointer:
4620 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4621 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4622 /*isNullPtr*/true);
4623 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4624 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
4625 return false;
4626 case NPV_NotNullPointer:
4627 break;
4628 }
4629
4630 bool ObjCLifetimeConversion;
4631 if (S.IsQualificationConversion(Arg->getType(),
4632 ParamType.getNonReferenceType(),
4633 false, ObjCLifetimeConversion)) {
4634 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4635 Arg->getValueKind()).get();
4636 ResultArg = Arg;
4637 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4638 ParamType.getNonReferenceType())) {
4639 // We can't perform this conversion.
4640 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4641 << Arg->getType() << ParamType << Arg->getSourceRange();
4642 S.Diag(Param->getLocation(), diag::note_template_param_here);
4643 return true;
4644 }
4645
4646 // See through any implicit casts we added to fix the type.
4647 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4648 Arg = Cast->getSubExpr();
4649
4650 // C++ [temp.arg.nontype]p1:
4651 //
4652 // A template-argument for a non-type, non-template
4653 // template-parameter shall be one of: [...]
4654 //
4655 // -- a pointer to member expressed as described in 5.3.1.
4656 DeclRefExpr *DRE = nullptr;
4657
4658 // In C++98/03 mode, give an extension warning on any extra parentheses.
4659 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4660 bool ExtraParens = false;
4661 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4662 if (!Invalid && !ExtraParens) {
4663 S.Diag(Arg->getLocStart(),
4664 S.getLangOpts().CPlusPlus11 ?
4665 diag::warn_cxx98_compat_template_arg_extra_parens :
4666 diag::ext_template_arg_extra_parens)
4667 << Arg->getSourceRange();
4668 ExtraParens = true;
4669 }
4670
4671 Arg = Parens->getSubExpr();
4672 }
4673
4674 while (SubstNonTypeTemplateParmExpr *subst =
4675 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4676 Arg = subst->getReplacement()->IgnoreImpCasts();
4677
4678 // A pointer-to-member constant written &Class::member.
4679 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4680 if (UnOp->getOpcode() == UO_AddrOf) {
4681 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4682 if (DRE && !DRE->getQualifier())
4683 DRE = nullptr;
4684 }
4685 }
4686 // A constant of pointer-to-member type.
4687 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4688 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4689 if (VD->getType()->isMemberPointerType()) {
4690 if (isa<NonTypeTemplateParmDecl>(VD)) {
4691 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4692 Converted = TemplateArgument(Arg);
4693 } else {
4694 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4695 Converted = TemplateArgument(VD, ParamType);
4696 }
4697 return Invalid;
4698 }
4699 }
4700 }
4701
4702 DRE = nullptr;
4703 }
4704
4705 if (!DRE)
4706 return S.Diag(Arg->getLocStart(),
4707 diag::err_template_arg_not_pointer_to_member_form)
4708 << Arg->getSourceRange();
4709
4710 if (isa<FieldDecl>(DRE->getDecl()) ||
4711 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4712 isa<CXXMethodDecl>(DRE->getDecl())) {
4713 assert((isa<FieldDecl>(DRE->getDecl()) ||
4714 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4715 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4716 "Only non-static member pointers can make it here");
4717
4718 // Okay: this is the address of a non-static member, and therefore
4719 // a member pointer constant.
4720 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4721 Converted = TemplateArgument(Arg);
4722 } else {
4723 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4724 Converted = TemplateArgument(D, ParamType);
4725 }
4726 return Invalid;
4727 }
4728
4729 // We found something else, but we don't know specifically what it is.
4730 S.Diag(Arg->getLocStart(),
4731 diag::err_template_arg_not_pointer_to_member_form)
4732 << Arg->getSourceRange();
4733 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4734 return true;
4735}
4736
4737/// \brief Check a template argument against its corresponding
4738/// non-type template parameter.
4739///
4740/// This routine implements the semantics of C++ [temp.arg.nontype].
4741/// If an error occurred, it returns ExprError(); otherwise, it
4742/// returns the converted template argument. \p ParamType is the
4743/// type of the non-type template parameter after it has been instantiated.
4744ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4745 QualType ParamType, Expr *Arg,
4746 TemplateArgument &Converted,
4747 CheckTemplateArgumentKind CTAK) {
4748 SourceLocation StartLoc = Arg->getLocStart();
4749
4750 // If either the parameter has a dependent type or the argument is
4751 // type-dependent, there's nothing we can check now.
4752 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4753 // FIXME: Produce a cloned, canonical expression?
4754 Converted = TemplateArgument(Arg);
4755 return Arg;
4756 }
4757
4758 // We should have already dropped all cv-qualifiers by now.
4759 assert(!ParamType.hasQualifiers() &&
4760 "non-type template parameter type cannot be qualified");
4761
4762 if (CTAK == CTAK_Deduced &&
4763 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4764 // C++ [temp.deduct.type]p17:
4765 // If, in the declaration of a function template with a non-type
4766 // template-parameter, the non-type template-parameter is used
4767 // in an expression in the function parameter-list and, if the
4768 // corresponding template-argument is deduced, the
4769 // template-argument type shall match the type of the
4770 // template-parameter exactly, except that a template-argument
4771 // deduced from an array bound may be of any integral type.
4772 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4773 << Arg->getType().getUnqualifiedType()
4774 << ParamType.getUnqualifiedType();
4775 Diag(Param->getLocation(), diag::note_template_param_here);
4776 return ExprError();
4777 }
4778
4779 if (getLangOpts().CPlusPlus1z) {
4780 // FIXME: We can do some limited checking for a value-dependent but not
4781 // type-dependent argument.
4782 if (Arg->isValueDependent()) {
4783 Converted = TemplateArgument(Arg);
4784 return Arg;
4785 }
4786
4787 // C++1z [temp.arg.nontype]p1:
4788 // A template-argument for a non-type template parameter shall be
4789 // a converted constant expression of the type of the template-parameter.
4790 APValue Value;
4791 ExprResult ArgResult = CheckConvertedConstantExpression(
4792 Arg, ParamType, Value, CCEK_TemplateArg);
4793 if (ArgResult.isInvalid())
4794 return ExprError();
4795
4796 QualType CanonParamType = Context.getCanonicalType(ParamType);
4797
4798 // Convert the APValue to a TemplateArgument.
4799 switch (Value.getKind()) {
4800 case APValue::Uninitialized:
4801 assert(ParamType->isNullPtrType());
4802 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4803 break;
4804 case APValue::Int:
4805 assert(ParamType->isIntegralOrEnumerationType());
4806 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4807 break;
4808 case APValue::MemberPointer: {
4809 assert(ParamType->isMemberPointerType());
4810
4811 // FIXME: We need TemplateArgument representation and mangling for these.
4812 if (!Value.getMemberPointerPath().empty()) {
4813 Diag(Arg->getLocStart(),
4814 diag::err_template_arg_member_ptr_base_derived_not_supported)
4815 << Value.getMemberPointerDecl() << ParamType
4816 << Arg->getSourceRange();
4817 return ExprError();
4818 }
4819
4820 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4821 Converted = VD ? TemplateArgument(VD, CanonParamType)
4822 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4823 break;
4824 }
4825 case APValue::LValue: {
4826 // For a non-type template-parameter of pointer or reference type,
4827 // the value of the constant expression shall not refer to
4828 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4829 ParamType->isNullPtrType());
4830 // -- a temporary object
4831 // -- a string literal
4832 // -- the result of a typeid expression, or
4833 // -- a predefind __func__ variable
4834 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4835 if (isa<CXXUuidofExpr>(E)) {
4836 Converted = TemplateArgument(const_cast<Expr*>(E));
4837 break;
4838 }
4839 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4840 << Arg->getSourceRange();
4841 return ExprError();
4842 }
4843 auto *VD = const_cast<ValueDecl *>(
4844 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4845 // -- a subobject
4846 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4847 VD && VD->getType()->isArrayType() &&
4848 Value.getLValuePath()[0].ArrayIndex == 0 &&
4849 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4850 // Per defect report (no number yet):
4851 // ... other than a pointer to the first element of a complete array
4852 // object.
4853 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4854 Value.isLValueOnePastTheEnd()) {
4855 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4856 << Value.getAsString(Context, ParamType);
4857 return ExprError();
4858 }
4859 assert((VD || !ParamType->isReferenceType()) &&
4860 "null reference should not be a constant expression");
4861 assert((!VD || !ParamType->isNullPtrType()) &&
4862 "non-null value of type nullptr_t?");
4863 Converted = VD ? TemplateArgument(VD, CanonParamType)
4864 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4865 break;
4866 }
4867 case APValue::AddrLabelDiff:
4868 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4869 case APValue::Float:
4870 case APValue::ComplexInt:
4871 case APValue::ComplexFloat:
4872 case APValue::Vector:
4873 case APValue::Array:
4874 case APValue::Struct:
4875 case APValue::Union:
4876 llvm_unreachable("invalid kind for template argument");
4877 }
4878
4879 return ArgResult.get();
4880 }
4881
4882 // C++ [temp.arg.nontype]p5:
4883 // The following conversions are performed on each expression used
4884 // as a non-type template-argument. If a non-type
4885 // template-argument cannot be converted to the type of the
4886 // corresponding template-parameter then the program is
4887 // ill-formed.
4888 if (ParamType->isIntegralOrEnumerationType()) {
4889 // C++11:
4890 // -- for a non-type template-parameter of integral or
4891 // enumeration type, conversions permitted in a converted
4892 // constant expression are applied.
4893 //
4894 // C++98:
4895 // -- for a non-type template-parameter of integral or
4896 // enumeration type, integral promotions (4.5) and integral
4897 // conversions (4.7) are applied.
4898
4899 if (getLangOpts().CPlusPlus11) {
4900 // We can't check arbitrary value-dependent arguments.
4901 // FIXME: If there's no viable conversion to the template parameter type,
4902 // we should be able to diagnose that prior to instantiation.
4903 if (Arg->isValueDependent()) {
4904 Converted = TemplateArgument(Arg);
4905 return Arg;
4906 }
4907
4908 // C++ [temp.arg.nontype]p1:
4909 // A template-argument for a non-type, non-template template-parameter
4910 // shall be one of:
4911 //
4912 // -- for a non-type template-parameter of integral or enumeration
4913 // type, a converted constant expression of the type of the
4914 // template-parameter; or
4915 llvm::APSInt Value;
4916 ExprResult ArgResult =
4917 CheckConvertedConstantExpression(Arg, ParamType, Value,
4918 CCEK_TemplateArg);
4919 if (ArgResult.isInvalid())
4920 return ExprError();
4921
4922 // Widen the argument value to sizeof(parameter type). This is almost
4923 // always a no-op, except when the parameter type is bool. In
4924 // that case, this may extend the argument from 1 bit to 8 bits.
4925 QualType IntegerType = ParamType;
4926 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4927 IntegerType = Enum->getDecl()->getIntegerType();
4928 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4929
4930 Converted = TemplateArgument(Context, Value,
4931 Context.getCanonicalType(ParamType));
4932 return ArgResult;
4933 }
4934
4935 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4936 if (ArgResult.isInvalid())
4937 return ExprError();
4938 Arg = ArgResult.get();
4939
4940 QualType ArgType = Arg->getType();
4941
4942 // C++ [temp.arg.nontype]p1:
4943 // A template-argument for a non-type, non-template
4944 // template-parameter shall be one of:
4945 //
4946 // -- an integral constant-expression of integral or enumeration
4947 // type; or
4948 // -- the name of a non-type template-parameter; or
4949 SourceLocation NonConstantLoc;
4950 llvm::APSInt Value;
4951 if (!ArgType->isIntegralOrEnumerationType()) {
4952 Diag(Arg->getLocStart(),
4953 diag::err_template_arg_not_integral_or_enumeral)
4954 << ArgType << Arg->getSourceRange();
4955 Diag(Param->getLocation(), diag::note_template_param_here);
4956 return ExprError();
4957 } else if (!Arg->isValueDependent()) {
4958 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4959 QualType T;
4960
4961 public:
4962 TmplArgICEDiagnoser(QualType T) : T(T) { }
4963
4964 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4965 SourceRange SR) override {
4966 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4967 }
4968 } Diagnoser(ArgType);
4969
4970 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4971 false).get();
4972 if (!Arg)
4973 return ExprError();
4974 }
4975
4976 // From here on out, all we care about is the unqualified form
4977 // of the argument type.
4978 ArgType = ArgType.getUnqualifiedType();
4979
4980 // Try to convert the argument to the parameter's type.
4981 if (Context.hasSameType(ParamType, ArgType)) {
4982 // Okay: no conversion necessary
4983 } else if (ParamType->isBooleanType()) {
4984 // This is an integral-to-boolean conversion.
4985 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
4986 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4987 !ParamType->isEnumeralType()) {
4988 // This is an integral promotion or conversion.
4989 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
4990 } else {
4991 // We can't perform this conversion.
4992 Diag(Arg->getLocStart(),
4993 diag::err_template_arg_not_convertible)
4994 << Arg->getType() << ParamType << Arg->getSourceRange();
4995 Diag(Param->getLocation(), diag::note_template_param_here);
4996 return ExprError();
4997 }
4998
4999 // Add the value of this argument to the list of converted
5000 // arguments. We use the bitwidth and signedness of the template
5001 // parameter.
5002 if (Arg->isValueDependent()) {
5003 // The argument is value-dependent. Create a new
5004 // TemplateArgument with the converted expression.
5005 Converted = TemplateArgument(Arg);
5006 return Arg;
5007 }
5008
5009 QualType IntegerType = Context.getCanonicalType(ParamType);
5010 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5011 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5012
5013 if (ParamType->isBooleanType()) {
5014 // Value must be zero or one.
5015 Value = Value != 0;
5016 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5017 if (Value.getBitWidth() != AllowedBits)
5018 Value = Value.extOrTrunc(AllowedBits);
5019 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5020 } else {
5021 llvm::APSInt OldValue = Value;
5022
5023 // Coerce the template argument's value to the value it will have
5024 // based on the template parameter's type.
5025 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5026 if (Value.getBitWidth() != AllowedBits)
5027 Value = Value.extOrTrunc(AllowedBits);
5028 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5029
5030 // Complain if an unsigned parameter received a negative value.
5031 if (IntegerType->isUnsignedIntegerOrEnumerationType()
5032 && (OldValue.isSigned() && OldValue.isNegative())) {
5033 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5034 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5035 << Arg->getSourceRange();
5036 Diag(Param->getLocation(), diag::note_template_param_here);
5037 }
5038
5039 // Complain if we overflowed the template parameter's type.
5040 unsigned RequiredBits;
5041 if (IntegerType->isUnsignedIntegerOrEnumerationType())
5042 RequiredBits = OldValue.getActiveBits();
5043 else if (OldValue.isUnsigned())
5044 RequiredBits = OldValue.getActiveBits() + 1;
5045 else
5046 RequiredBits = OldValue.getMinSignedBits();
5047 if (RequiredBits > AllowedBits) {
5048 Diag(Arg->getLocStart(),
5049 diag::warn_template_arg_too_large)
5050 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5051 << Arg->getSourceRange();
5052 Diag(Param->getLocation(), diag::note_template_param_here);
5053 }
5054 }
5055
5056 Converted = TemplateArgument(Context, Value,
5057 ParamType->isEnumeralType()
5058 ? Context.getCanonicalType(ParamType)
5059 : IntegerType);
5060 return Arg;
5061 }
5062
5063 QualType ArgType = Arg->getType();
5064 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5065
5066 // Handle pointer-to-function, reference-to-function, and
5067 // pointer-to-member-function all in (roughly) the same way.
5068 if (// -- For a non-type template-parameter of type pointer to
5069 // function, only the function-to-pointer conversion (4.3) is
5070 // applied. If the template-argument represents a set of
5071 // overloaded functions (or a pointer to such), the matching
5072 // function is selected from the set (13.4).
5073 (ParamType->isPointerType() &&
5074 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5075 // -- For a non-type template-parameter of type reference to
5076 // function, no conversions apply. If the template-argument
5077 // represents a set of overloaded functions, the matching
5078 // function is selected from the set (13.4).
5079 (ParamType->isReferenceType() &&
5080 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5081 // -- For a non-type template-parameter of type pointer to
5082 // member function, no conversions apply. If the
5083 // template-argument represents a set of overloaded member
5084 // functions, the matching member function is selected from
5085 // the set (13.4).
5086 (ParamType->isMemberPointerType() &&
5087 ParamType->getAs<MemberPointerType>()->getPointeeType()
5088 ->isFunctionType())) {
5089
5090 if (Arg->getType() == Context.OverloadTy) {
5091 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5092 true,
5093 FoundResult)) {
5094 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5095 return ExprError();
5096
5097 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5098 ArgType = Arg->getType();
5099 } else
5100 return ExprError();
5101 }
5102
5103 if (!ParamType->isMemberPointerType()) {
5104 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5105 ParamType,
5106 Arg, Converted))
5107 return ExprError();
5108 return Arg;
5109 }
5110
5111 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5112 Converted))
5113 return ExprError();
5114 return Arg;
5115 }
5116
5117 if (ParamType->isPointerType()) {
5118 // -- for a non-type template-parameter of type pointer to
5119 // object, qualification conversions (4.4) and the
5120 // array-to-pointer conversion (4.2) are applied.
5121 // C++0x also allows a value of std::nullptr_t.
5122 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5123 "Only object pointers allowed here");
5124
5125 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5126 ParamType,
5127 Arg, Converted))
5128 return ExprError();
5129 return Arg;
5130 }
5131
5132 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5133 // -- For a non-type template-parameter of type reference to
5134 // object, no conversions apply. The type referred to by the
5135 // reference may be more cv-qualified than the (otherwise
5136 // identical) type of the template-argument. The
5137 // template-parameter is bound directly to the
5138 // template-argument, which must be an lvalue.
5139 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5140 "Only object references allowed here");
5141
5142 if (Arg->getType() == Context.OverloadTy) {
5143 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5144 ParamRefType->getPointeeType(),
5145 true,
5146 FoundResult)) {
5147 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5148 return ExprError();
5149
5150 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5151 ArgType = Arg->getType();
5152 } else
5153 return ExprError();
5154 }
5155
5156 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5157 ParamType,
5158 Arg, Converted))
5159 return ExprError();
5160 return Arg;
5161 }
5162
5163 // Deal with parameters of type std::nullptr_t.
5164 if (ParamType->isNullPtrType()) {
5165 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5166 Converted = TemplateArgument(Arg);
5167 return Arg;
5168 }
5169
5170 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5171 case NPV_NotNullPointer:
5172 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5173 << Arg->getType() << ParamType;
5174 Diag(Param->getLocation(), diag::note_template_param_here);
5175 return ExprError();
5176
5177 case NPV_Error:
5178 return ExprError();
5179
5180 case NPV_NullPointer:
5181 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5182 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5183 /*isNullPtr*/true);
5184 return Arg;
5185 }
5186 }
5187
5188 // -- For a non-type template-parameter of type pointer to data
5189 // member, qualification conversions (4.4) are applied.
5190 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5191
5192 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5193 Converted))
5194 return ExprError();
5195 return Arg;
5196}
5197
5198/// \brief Check a template argument against its corresponding
5199/// template template parameter.
5200///
5201/// This routine implements the semantics of C++ [temp.arg.template].
5202/// It returns true if an error occurred, and false otherwise.
5203bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5204 TemplateArgumentLoc &Arg,
5205 unsigned ArgumentPackIndex) {
5206 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5207 TemplateDecl *Template = Name.getAsTemplateDecl();
5208 if (!Template) {
5209 // Any dependent template name is fine.
5210 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5211 return false;
5212 }
5213
5214 // C++0x [temp.arg.template]p1:
5215 // A template-argument for a template template-parameter shall be
5216 // the name of a class template or an alias template, expressed as an
5217 // id-expression. When the template-argument names a class template, only
5218 // primary class templates are considered when matching the
5219 // template template argument with the corresponding parameter;
5220 // partial specializations are not considered even if their
5221 // parameter lists match that of the template template parameter.
5222 //
5223 // Note that we also allow template template parameters here, which
5224 // will happen when we are dealing with, e.g., class template
5225 // partial specializations.
5226 if (!isa<ClassTemplateDecl>(Template) &&
5227 !isa<TemplateTemplateParmDecl>(Template) &&
5228 !isa<TypeAliasTemplateDecl>(Template)) {
5229 assert(isa<FunctionTemplateDecl>(Template) &&
5230 "Only function templates are possible here");
5231 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5232 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5233 << Template;
5234 }
5235
5236 TemplateParameterList *Params = Param->getTemplateParameters();
5237 if (Param->isExpandedParameterPack())
5238 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5239
5240 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5241 Params,
5242 true,
5243 TPL_TemplateTemplateArgumentMatch,
5244 Arg.getLocation());
5245}
5246
5247/// \brief Given a non-type template argument that refers to a
5248/// declaration and the type of its corresponding non-type template
5249/// parameter, produce an expression that properly refers to that
5250/// declaration.
5251ExprResult
5252Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5253 QualType ParamType,
5254 SourceLocation Loc) {
5255 // C++ [temp.param]p8:
5256 //
5257 // A non-type template-parameter of type "array of T" or
5258 // "function returning T" is adjusted to be of type "pointer to
5259 // T" or "pointer to function returning T", respectively.
5260 if (ParamType->isArrayType())
5261 ParamType = Context.getArrayDecayedType(ParamType);
5262 else if (ParamType->isFunctionType())
5263 ParamType = Context.getPointerType(ParamType);
5264
5265 // For a NULL non-type template argument, return nullptr casted to the
5266 // parameter's type.
5267 if (Arg.getKind() == TemplateArgument::NullPtr) {
5268 return ImpCastExprToType(
5269 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5270 ParamType,
5271 ParamType->getAs<MemberPointerType>()
5272 ? CK_NullToMemberPointer
5273 : CK_NullToPointer);
5274 }
5275 assert(Arg.getKind() == TemplateArgument::Declaration &&
5276 "Only declaration template arguments permitted here");
5277
5278 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5279
5280 if (VD->getDeclContext()->isRecord() &&
5281 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5282 isa<IndirectFieldDecl>(VD))) {
5283 // If the value is a class member, we might have a pointer-to-member.
5284 // Determine whether the non-type template template parameter is of
5285 // pointer-to-member type. If so, we need to build an appropriate
5286 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5287 // would refer to the member itself.
5288 if (ParamType->isMemberPointerType()) {
5289 QualType ClassType
5290 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5291 NestedNameSpecifier *Qualifier
5292 = NestedNameSpecifier::Create(Context, nullptr, false,
5293 ClassType.getTypePtr());
5294 CXXScopeSpec SS;
5295 SS.MakeTrivial(Context, Qualifier, Loc);
5296
5297 // The actual value-ness of this is unimportant, but for
5298 // internal consistency's sake, references to instance methods
5299 // are r-values.
5300 ExprValueKind VK = VK_LValue;
5301 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5302 VK = VK_RValue;
5303
5304 ExprResult RefExpr = BuildDeclRefExpr(VD,
5305 VD->getType().getNonReferenceType(),
5306 VK,
5307 Loc,
5308 &SS);
5309 if (RefExpr.isInvalid())
5310 return ExprError();
5311
5312 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5313
5314 // We might need to perform a trailing qualification conversion, since
5315 // the element type on the parameter could be more qualified than the
5316 // element type in the expression we constructed.
5317 bool ObjCLifetimeConversion;
5318 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5319 ParamType.getUnqualifiedType(), false,
5320 ObjCLifetimeConversion))
5321 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5322
5323 assert(!RefExpr.isInvalid() &&
5324 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5325 ParamType.getUnqualifiedType()));
5326 return RefExpr;
5327 }
5328 }
5329
5330 QualType T = VD->getType().getNonReferenceType();
5331
5332 if (ParamType->isPointerType()) {
5333 // When the non-type template parameter is a pointer, take the
5334 // address of the declaration.
5335 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5336 if (RefExpr.isInvalid())
5337 return ExprError();
5338
5339 if (T->isFunctionType() || T->isArrayType()) {
5340 // Decay functions and arrays.
5341 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5342 if (RefExpr.isInvalid())
5343 return ExprError();
5344
5345 return RefExpr;
5346 }
5347
5348 // Take the address of everything else
5349 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5350 }
5351
5352 ExprValueKind VK = VK_RValue;
5353
5354 // If the non-type template parameter has reference type, qualify the
5355 // resulting declaration reference with the extra qualifiers on the
5356 // type that the reference refers to.
5357 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5358 VK = VK_LValue;
5359 T = Context.getQualifiedType(T,
5360 TargetRef->getPointeeType().getQualifiers());
5361 } else if (isa<FunctionDecl>(VD)) {
5362 // References to functions are always lvalues.
5363 VK = VK_LValue;
5364 }
5365
5366 return BuildDeclRefExpr(VD, T, VK, Loc);
5367}
5368
5369/// \brief Construct a new expression that refers to the given
5370/// integral template argument with the given source-location
5371/// information.
5372///
5373/// This routine takes care of the mapping from an integral template
5374/// argument (which may have any integral type) to the appropriate
5375/// literal value.
5376ExprResult
5377Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5378 SourceLocation Loc) {
5379 assert(Arg.getKind() == TemplateArgument::Integral &&
5380 "Operation is only valid for integral template arguments");
5381 QualType OrigT = Arg.getIntegralType();
5382
5383 // If this is an enum type that we're instantiating, we need to use an integer
5384 // type the same size as the enumerator. We don't want to build an
5385 // IntegerLiteral with enum type. The integer type of an enum type can be of
5386 // any integral type with C++11 enum classes, make sure we create the right
5387 // type of literal for it.
5388 QualType T = OrigT;
5389 if (const EnumType *ET = OrigT->getAs<EnumType>())
5390 T = ET->getDecl()->getIntegerType();
5391
5392 Expr *E;
5393 if (T->isAnyCharacterType()) {
5394 CharacterLiteral::CharacterKind Kind;
5395 if (T->isWideCharType())
5396 Kind = CharacterLiteral::Wide;
5397 else if (T->isChar16Type())
5398 Kind = CharacterLiteral::UTF16;
5399 else if (T->isChar32Type())
5400 Kind = CharacterLiteral::UTF32;
5401 else
5402 Kind = CharacterLiteral::Ascii;
5403
5404 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5405 Kind, T, Loc);
5406 } else if (T->isBooleanType()) {
5407 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5408 T, Loc);
5409 } else if (T->isNullPtrType()) {
5410 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5411 } else {
5412 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5413 }
5414
5415 if (OrigT->isEnumeralType()) {
5416 // FIXME: This is a hack. We need a better way to handle substituted
5417 // non-type template parameters.
5418 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5419 nullptr,
5420 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5421 Loc, Loc);
5422 }
5423
5424 return E;
5425}
5426
5427/// \brief Match two template parameters within template parameter lists.
5428static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5429 bool Complain,
5430 Sema::TemplateParameterListEqualKind Kind,
5431 SourceLocation TemplateArgLoc) {
5432 // Check the actual kind (type, non-type, template).
5433 if (Old->getKind() != New->getKind()) {
5434 if (Complain) {
5435 unsigned NextDiag = diag::err_template_param_different_kind;
5436 if (TemplateArgLoc.isValid()) {
5437 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5438 NextDiag = diag::note_template_param_different_kind;
5439 }
5440 S.Diag(New->getLocation(), NextDiag)
5441 << (Kind != Sema::TPL_TemplateMatch);
5442 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5443 << (Kind != Sema::TPL_TemplateMatch);
5444 }
5445
5446 return false;
5447 }
5448
5449 // Check that both are parameter packs are neither are parameter packs.
5450 // However, if we are matching a template template argument to a
5451 // template template parameter, the template template parameter can have
5452 // a parameter pack where the template template argument does not.
5453 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5454 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5455 Old->isTemplateParameterPack())) {
5456 if (Complain) {
5457 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5458 if (TemplateArgLoc.isValid()) {
5459 S.Diag(TemplateArgLoc,
5460 diag::err_template_arg_template_params_mismatch);
5461 NextDiag = diag::note_template_parameter_pack_non_pack;
5462 }
5463
5464 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5465 : isa<NonTypeTemplateParmDecl>(New)? 1
5466 : 2;
5467 S.Diag(New->getLocation(), NextDiag)
5468 << ParamKind << New->isParameterPack();
5469 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5470 << ParamKind << Old->isParameterPack();
5471 }
5472
5473 return false;
5474 }
5475
5476 // For non-type template parameters, check the type of the parameter.
5477 if (NonTypeTemplateParmDecl *OldNTTP
5478 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5479 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5480
5481 // If we are matching a template template argument to a template
5482 // template parameter and one of the non-type template parameter types
5483 // is dependent, then we must wait until template instantiation time
5484 // to actually compare the arguments.
5485 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5486 (OldNTTP->getType()->isDependentType() ||
5487 NewNTTP->getType()->isDependentType()))
5488 return true;
5489
5490 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5491 if (Complain) {
5492 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5493 if (TemplateArgLoc.isValid()) {
5494 S.Diag(TemplateArgLoc,
5495 diag::err_template_arg_template_params_mismatch);
5496 NextDiag = diag::note_template_nontype_parm_different_type;
5497 }
5498 S.Diag(NewNTTP->getLocation(), NextDiag)
5499 << NewNTTP->getType()
5500 << (Kind != Sema::TPL_TemplateMatch);
5501 S.Diag(OldNTTP->getLocation(),
5502 diag::note_template_nontype_parm_prev_declaration)
5503 << OldNTTP->getType();
5504 }
5505
5506 return false;
5507 }
5508
5509 return true;
5510 }
5511
5512 // For template template parameters, check the template parameter types.
5513 // The template parameter lists of template template
5514 // parameters must agree.
5515 if (TemplateTemplateParmDecl *OldTTP
5516 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5517 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5518 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5519 OldTTP->getTemplateParameters(),
5520 Complain,
5521 (Kind == Sema::TPL_TemplateMatch
5522 ? Sema::TPL_TemplateTemplateParmMatch
5523 : Kind),
5524 TemplateArgLoc);
5525 }
5526
5527 return true;
5528}
5529
5530/// \brief Diagnose a known arity mismatch when comparing template argument
5531/// lists.
5532static
5533void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5534 TemplateParameterList *New,
5535 TemplateParameterList *Old,
5536 Sema::TemplateParameterListEqualKind Kind,
5537 SourceLocation TemplateArgLoc) {
5538 unsigned NextDiag = diag::err_template_param_list_different_arity;
5539 if (TemplateArgLoc.isValid()) {
5540 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5541 NextDiag = diag::note_template_param_list_different_arity;
5542 }
5543 S.Diag(New->getTemplateLoc(), NextDiag)
5544 << (New->size() > Old->size())
5545 << (Kind != Sema::TPL_TemplateMatch)
5546 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5547 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5548 << (Kind != Sema::TPL_TemplateMatch)
5549 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5550}
5551
5552/// \brief Determine whether the given template parameter lists are
5553/// equivalent.
5554///
5555/// \param New The new template parameter list, typically written in the
5556/// source code as part of a new template declaration.
5557///
5558/// \param Old The old template parameter list, typically found via
5559/// name lookup of the template declared with this template parameter
5560/// list.
5561///
5562/// \param Complain If true, this routine will produce a diagnostic if
5563/// the template parameter lists are not equivalent.
5564///
5565/// \param Kind describes how we are to match the template parameter lists.
5566///
5567/// \param TemplateArgLoc If this source location is valid, then we
5568/// are actually checking the template parameter list of a template
5569/// argument (New) against the template parameter list of its
5570/// corresponding template template parameter (Old). We produce
5571/// slightly different diagnostics in this scenario.
5572///
5573/// \returns True if the template parameter lists are equal, false
5574/// otherwise.
5575bool
5576Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5577 TemplateParameterList *Old,
5578 bool Complain,
5579 TemplateParameterListEqualKind Kind,
5580 SourceLocation TemplateArgLoc) {
5581 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5582 if (Complain)
5583 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5584 TemplateArgLoc);
5585
5586 return false;
5587 }
5588
5589 // C++0x [temp.arg.template]p3:
5590 // A template-argument matches a template template-parameter (call it P)
5591 // when each of the template parameters in the template-parameter-list of
5592 // the template-argument's corresponding class template or alias template
5593 // (call it A) matches the corresponding template parameter in the
5594 // template-parameter-list of P. [...]
5595 TemplateParameterList::iterator NewParm = New->begin();
5596 TemplateParameterList::iterator NewParmEnd = New->end();
5597 for (TemplateParameterList::iterator OldParm = Old->begin(),
5598 OldParmEnd = Old->end();
5599 OldParm != OldParmEnd; ++OldParm) {
5600 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5601 !(*OldParm)->isTemplateParameterPack()) {
5602 if (NewParm == NewParmEnd) {
5603 if (Complain)
5604 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5605 TemplateArgLoc);
5606
5607 return false;
5608 }
5609
5610 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5611 Kind, TemplateArgLoc))
5612 return false;
5613
5614 ++NewParm;
5615 continue;
5616 }
5617
5618 // C++0x [temp.arg.template]p3:
5619 // [...] When P's template- parameter-list contains a template parameter
5620 // pack (14.5.3), the template parameter pack will match zero or more
5621 // template parameters or template parameter packs in the
5622 // template-parameter-list of A with the same type and form as the
5623 // template parameter pack in P (ignoring whether those template
5624 // parameters are template parameter packs).
5625 for (; NewParm != NewParmEnd; ++NewParm) {
5626 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5627 Kind, TemplateArgLoc))
5628 return false;
5629 }
5630 }
5631
5632 // Make sure we exhausted all of the arguments.
5633 if (NewParm != NewParmEnd) {
5634 if (Complain)
5635 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5636 TemplateArgLoc);
5637
5638 return false;
5639 }
5640
5641 return true;
5642}
5643
5644/// \brief Check whether a template can be declared within this scope.
5645///
5646/// If the template declaration is valid in this scope, returns
5647/// false. Otherwise, issues a diagnostic and returns true.
5648bool
5649Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5650 if (!S)
5651 return false;
5652
5653 // Find the nearest enclosing declaration scope.
5654 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5655 (S->getFlags() & Scope::TemplateParamScope) != 0)
5656 S = S->getParent();
5657
5658 // C++ [temp]p4:
5659 // A template [...] shall not have C linkage.
5660 DeclContext *Ctx = S->getEntity();
5661 if (Ctx && Ctx->isExternCContext())
5662 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5663 << TemplateParams->getSourceRange();
5664
5665 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5666 Ctx = Ctx->getParent();
5667
5668 // C++ [temp]p2:
5669 // A template-declaration can appear only as a namespace scope or
5670 // class scope declaration.
5671 if (Ctx) {
5672 if (Ctx->isFileContext())
5673 return false;
5674 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5675 // C++ [temp.mem]p2:
5676 // A local class shall not have member templates.
5677 if (RD->isLocalClass())
5678 return Diag(TemplateParams->getTemplateLoc(),
5679 diag::err_template_inside_local_class)
5680 << TemplateParams->getSourceRange();
5681 else
5682 return false;
5683 }
5684 }
5685
5686 return Diag(TemplateParams->getTemplateLoc(),
5687 diag::err_template_outside_namespace_or_class_scope)
5688 << TemplateParams->getSourceRange();
5689}
5690
5691/// \brief Determine what kind of template specialization the given declaration
5692/// is.
5693static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5694 if (!D)
5695 return TSK_Undeclared;
5696
5697 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5698 return Record->getTemplateSpecializationKind();
5699 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5700 return Function->getTemplateSpecializationKind();
5701 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5702 return Var->getTemplateSpecializationKind();
5703
5704 return TSK_Undeclared;
5705}
5706
5707/// \brief Check whether a specialization is well-formed in the current
5708/// context.
5709///
5710/// This routine determines whether a template specialization can be declared
5711/// in the current context (C++ [temp.expl.spec]p2).
5712///
5713/// \param S the semantic analysis object for which this check is being
5714/// performed.
5715///
5716/// \param Specialized the entity being specialized or instantiated, which
5717/// may be a kind of template (class template, function template, etc.) or
5718/// a member of a class template (member function, static data member,
5719/// member class).
5720///
5721/// \param PrevDecl the previous declaration of this entity, if any.
5722///
5723/// \param Loc the location of the explicit specialization or instantiation of
5724/// this entity.
5725///
5726/// \param IsPartialSpecialization whether this is a partial specialization of
5727/// a class template.
5728///
5729/// \returns true if there was an error that we cannot recover from, false
5730/// otherwise.
5731static bool CheckTemplateSpecializationScope(Sema &S,
5732 NamedDecl *Specialized,
5733 NamedDecl *PrevDecl,
5734 SourceLocation Loc,
5735 bool IsPartialSpecialization) {
5736 // Keep these "kind" numbers in sync with the %select statements in the
5737 // various diagnostics emitted by this routine.
5738 int EntityKind = 0;
5739 if (isa<ClassTemplateDecl>(Specialized))
5740 EntityKind = IsPartialSpecialization? 1 : 0;
5741 else if (isa<VarTemplateDecl>(Specialized))
5742 EntityKind = IsPartialSpecialization ? 3 : 2;
5743 else if (isa<FunctionTemplateDecl>(Specialized))
5744 EntityKind = 4;
5745 else if (isa<CXXMethodDecl>(Specialized))
5746 EntityKind = 5;
5747 else if (isa<VarDecl>(Specialized))
5748 EntityKind = 6;
5749 else if (isa<RecordDecl>(Specialized))
5750 EntityKind = 7;
5751 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5752 EntityKind = 8;
5753 else {
5754 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5755 << S.getLangOpts().CPlusPlus11;
5756 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5757 return true;
5758 }
5759
5760 // C++ [temp.expl.spec]p2:
5761 // An explicit specialization shall be declared in the namespace
5762 // of which the template is a member, or, for member templates, in
5763 // the namespace of which the enclosing class or enclosing class
5764 // template is a member. An explicit specialization of a member
5765 // function, member class or static data member of a class
5766 // template shall be declared in the namespace of which the class
5767 // template is a member. Such a declaration may also be a
5768 // definition. If the declaration is not a definition, the
5769 // specialization may be defined later in the name- space in which
5770 // the explicit specialization was declared, or in a namespace
5771 // that encloses the one in which the explicit specialization was
5772 // declared.
5773 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5774 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5775 << Specialized;
5776 return true;
5777 }
5778
5779 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5780 if (S.getLangOpts().MicrosoftExt) {
5781 // Do not warn for class scope explicit specialization during
5782 // instantiation, warning was already emitted during pattern
5783 // semantic analysis.
5784 if (!S.ActiveTemplateInstantiations.size())
5785 S.Diag(Loc, diag::ext_function_specialization_in_class)
5786 << Specialized;
5787 } else {
5788 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5789 << Specialized;
5790 return true;
5791 }
5792 }
5793
5794 if (S.CurContext->isRecord() &&
5795 !S.CurContext->Equals(Specialized->getDeclContext())) {
5796 // Make sure that we're specializing in the right record context.
5797 // Otherwise, things can go horribly wrong.
5798 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5799 << Specialized;
5800 return true;
5801 }
5802
5803 // C++ [temp.class.spec]p6:
5804 // A class template partial specialization may be declared or redeclared
5805 // in any namespace scope in which its definition may be defined (14.5.1
5806 // and 14.5.2).
5807 DeclContext *SpecializedContext
5808 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5809 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5810
5811 // Make sure that this redeclaration (or definition) occurs in an enclosing
5812 // namespace.
5813 // Note that HandleDeclarator() performs this check for explicit
5814 // specializations of function templates, static data members, and member
5815 // functions, so we skip the check here for those kinds of entities.
5816 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5817 // Should we refactor that check, so that it occurs later?
5818 if (!DC->Encloses(SpecializedContext) &&
5819 !(isa<FunctionTemplateDecl>(Specialized) ||
5820 isa<FunctionDecl>(Specialized) ||
5821 isa<VarTemplateDecl>(Specialized) ||
5822 isa<VarDecl>(Specialized))) {
5823 if (isa<TranslationUnitDecl>(SpecializedContext))
5824 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5825 << EntityKind << Specialized;
5826 else if (isa<NamespaceDecl>(SpecializedContext))
5827 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5828 << EntityKind << Specialized
5829 << cast<NamedDecl>(SpecializedContext);
5830 else
5831 llvm_unreachable("unexpected namespace context for specialization");
5832
5833 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5834 } else if ((!PrevDecl ||
5835 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5836 getTemplateSpecializationKind(PrevDecl) ==
5837 TSK_ImplicitInstantiation)) {
5838 // C++ [temp.exp.spec]p2:
5839 // An explicit specialization shall be declared in the namespace of which
5840 // the template is a member, or, for member templates, in the namespace
5841 // of which the enclosing class or enclosing class template is a member.
5842 // An explicit specialization of a member function, member class or
5843 // static data member of a class template shall be declared in the
5844 // namespace of which the class template is a member.
5845 //
5846 // C++11 [temp.expl.spec]p2:
5847 // An explicit specialization shall be declared in a namespace enclosing
5848 // the specialized template.
5849 // C++11 [temp.explicit]p3:
5850 // An explicit instantiation shall appear in an enclosing namespace of its
5851 // template.
5852 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5853 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5854 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5855 assert(!IsCPlusPlus11Extension &&
5856 "DC encloses TU but isn't in enclosing namespace set");
5857 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5858 << EntityKind << Specialized;
5859 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5860 int Diag;
5861 if (!IsCPlusPlus11Extension)
5862 Diag = diag::err_template_spec_decl_out_of_scope;
5863 else if (!S.getLangOpts().CPlusPlus11)
5864 Diag = diag::ext_template_spec_decl_out_of_scope;
5865 else
5866 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5867 S.Diag(Loc, Diag)
5868 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5869 }
5870
5871 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5872 }
5873 }
5874
5875 return false;
5876}
5877
5878static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5879 if (!E->isInstantiationDependent())
5880 return SourceLocation();
5881 DependencyChecker Checker(Depth);
5882 Checker.TraverseStmt(E);
5883 if (Checker.Match && Checker.MatchLoc.isInvalid())
5884 return E->getSourceRange();
5885 return Checker.MatchLoc;
5886}
5887
5888static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5889 if (!TL.getType()->isDependentType())
5890 return SourceLocation();
5891 DependencyChecker Checker(Depth);
5892 Checker.TraverseTypeLoc(TL);
5893 if (Checker.Match && Checker.MatchLoc.isInvalid())
5894 return TL.getSourceRange();
5895 return Checker.MatchLoc;
5896}
5897
5898/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
5899/// that checks non-type template partial specialization arguments.
5900static bool CheckNonTypeTemplatePartialSpecializationArgs(
5901 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5902 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
5903 for (unsigned I = 0; I != NumArgs; ++I) {
5904 if (Args[I].getKind() == TemplateArgument::Pack) {
5905 if (CheckNonTypeTemplatePartialSpecializationArgs(
5906 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5907 Args[I].pack_size(), IsDefaultArgument))
5908 return true;
5909
5910 continue;
5911 }
5912
5913 if (Args[I].getKind() != TemplateArgument::Expression)
5914 continue;
5915
5916 Expr *ArgExpr = Args[I].getAsExpr();
5917
5918 // We can have a pack expansion of any of the bullets below.
5919 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5920 ArgExpr = Expansion->getPattern();
5921
5922 // Strip off any implicit casts we added as part of type checking.
5923 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5924 ArgExpr = ICE->getSubExpr();
5925
5926 // C++ [temp.class.spec]p8:
5927 // A non-type argument is non-specialized if it is the name of a
5928 // non-type parameter. All other non-type arguments are
5929 // specialized.
5930 //
5931 // Below, we check the two conditions that only apply to
5932 // specialized non-type arguments, so skip any non-specialized
5933 // arguments.
5934 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5935 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5936 continue;
5937
5938 // C++ [temp.class.spec]p9:
5939 // Within the argument list of a class template partial
5940 // specialization, the following restrictions apply:
5941 // -- A partially specialized non-type argument expression
5942 // shall not involve a template parameter of the partial
5943 // specialization except when the argument expression is a
5944 // simple identifier.
5945 SourceRange ParamUseRange =
5946 findTemplateParameter(Param->getDepth(), ArgExpr);
5947 if (ParamUseRange.isValid()) {
5948 if (IsDefaultArgument) {
5949 S.Diag(TemplateNameLoc,
5950 diag::err_dependent_non_type_arg_in_partial_spec);
5951 S.Diag(ParamUseRange.getBegin(),
5952 diag::note_dependent_non_type_default_arg_in_partial_spec)
5953 << ParamUseRange;
5954 } else {
5955 S.Diag(ParamUseRange.getBegin(),
5956 diag::err_dependent_non_type_arg_in_partial_spec)
5957 << ParamUseRange;
5958 }
5959 return true;
5960 }
5961
5962 // -- The type of a template parameter corresponding to a
5963 // specialized non-type argument shall not be dependent on a
5964 // parameter of the specialization.
5965 //
5966 // FIXME: We need to delay this check until instantiation in some cases:
5967 //
5968 // template<template<typename> class X> struct A {
5969 // template<typename T, X<T> N> struct B;
5970 // template<typename T> struct B<T, 0>;
5971 // };
5972 // template<typename> using X = int;
5973 // A<X>::B<int, 0> b;
5974 ParamUseRange = findTemplateParameter(
5975 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
5976 if (ParamUseRange.isValid()) {
5977 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
5978 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5979 << Param->getType() << ParamUseRange;
5980 S.Diag(Param->getLocation(), diag::note_template_param_here)
5981 << (IsDefaultArgument ? ParamUseRange : SourceRange());
5982 return true;
5983 }
5984 }
5985
5986 return false;
5987}
5988
5989/// \brief Check the non-type template arguments of a class template
5990/// partial specialization according to C++ [temp.class.spec]p9.
5991///
5992/// \param TemplateNameLoc the location of the template name.
5993/// \param TemplateParams the template parameters of the primary class
5994/// template.
5995/// \param NumExplicit the number of explicitly-specified template arguments.
5996/// \param TemplateArgs the template arguments of the class template
5997/// partial specialization.
5998///
5999/// \returns \c true if there was an error, \c false otherwise.
6000static bool CheckTemplatePartialSpecializationArgs(
6001 Sema &S, SourceLocation TemplateNameLoc,
6002 TemplateParameterList *TemplateParams, unsigned NumExplicit,
6003 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6004 const TemplateArgument *ArgList = TemplateArgs.data();
6005
6006 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6007 NonTypeTemplateParmDecl *Param
6008 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6009 if (!Param)
6010 continue;
6011
6012 if (CheckNonTypeTemplatePartialSpecializationArgs(
6013 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6014 return true;
6015 }
6016
6017 return false;
6018}
6019
6020DeclResult
6021Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6022 TagUseKind TUK,
6023 SourceLocation KWLoc,
6024 SourceLocation ModulePrivateLoc,
6025 TemplateIdAnnotation &TemplateId,
6026 AttributeList *Attr,
6027 MultiTemplateParamsArg TemplateParameterLists) {
6028 assert(TUK != TUK_Reference && "References are not specializations");
6029
6030 CXXScopeSpec &SS = TemplateId.SS;
6031
6032 // NOTE: KWLoc is the location of the tag keyword. This will instead
6033 // store the location of the outermost template keyword in the declaration.
6034 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6035 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6036 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6037 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6038 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6039
6040 // Find the class template we're specializing
6041 TemplateName Name = TemplateId.Template.get();
6042 ClassTemplateDecl *ClassTemplate
6043 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6044
6045 if (!ClassTemplate) {
6046 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6047 << (Name.getAsTemplateDecl() &&
6048 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6049 return true;
6050 }
6051
6052 bool isExplicitSpecialization = false;
6053 bool isPartialSpecialization = false;
6054
6055 // Check the validity of the template headers that introduce this
6056 // template.
6057 // FIXME: We probably shouldn't complain about these headers for
6058 // friend declarations.
6059 bool Invalid = false;
6060 TemplateParameterList *TemplateParams =
6061 MatchTemplateParametersToScopeSpecifier(
6062 KWLoc, TemplateNameLoc, SS, &TemplateId,
6063 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6064 Invalid);
6065 if (Invalid)
6066 return true;
6067
6068 if (TemplateParams && TemplateParams->size() > 0) {
6069 isPartialSpecialization = true;
6070
6071 if (TUK == TUK_Friend) {
6072 Diag(KWLoc, diag::err_partial_specialization_friend)
6073 << SourceRange(LAngleLoc, RAngleLoc);
6074 return true;
6075 }
6076
6077 // C++ [temp.class.spec]p10:
6078 // The template parameter list of a specialization shall not
6079 // contain default template argument values.
6080 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6081 Decl *Param = TemplateParams->getParam(I);
6082 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6083 if (TTP->hasDefaultArgument()) {
6084 Diag(TTP->getDefaultArgumentLoc(),
6085 diag::err_default_arg_in_partial_spec);
6086 TTP->removeDefaultArgument();
6087 }
6088 } else if (NonTypeTemplateParmDecl *NTTP
6089 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6090 if (Expr *DefArg = NTTP->getDefaultArgument()) {
6091 Diag(NTTP->getDefaultArgumentLoc(),
6092 diag::err_default_arg_in_partial_spec)
6093 << DefArg->getSourceRange();
6094 NTTP->removeDefaultArgument();
6095 }
6096 } else {
6097 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6098 if (TTP->hasDefaultArgument()) {
6099 Diag(TTP->getDefaultArgument().getLocation(),
6100 diag::err_default_arg_in_partial_spec)
6101 << TTP->getDefaultArgument().getSourceRange();
6102 TTP->removeDefaultArgument();
6103 }
6104 }
6105 }
6106 } else if (TemplateParams) {
6107 if (TUK == TUK_Friend)
6108 Diag(KWLoc, diag::err_template_spec_friend)
6109 << FixItHint::CreateRemoval(
6110 SourceRange(TemplateParams->getTemplateLoc(),
6111 TemplateParams->getRAngleLoc()))
6112 << SourceRange(LAngleLoc, RAngleLoc);
6113 else
6114 isExplicitSpecialization = true;
6115 } else {
6116 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6117 }
6118
6119 // Check that the specialization uses the same tag kind as the
6120 // original template.
6121 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6122 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6123 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6124 Kind, TUK == TUK_Definition, KWLoc,
6125 *ClassTemplate->getIdentifier())) {
6126 Diag(KWLoc, diag::err_use_with_wrong_tag)
6127 << ClassTemplate
6128 << FixItHint::CreateReplacement(KWLoc,
6129 ClassTemplate->getTemplatedDecl()->getKindName());
6130 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6131 diag::note_previous_use);
6132 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6133 }
6134
6135 // Translate the parser's template argument list in our AST format.
6136 TemplateArgumentListInfo TemplateArgs =
6137 makeTemplateArgumentListInfo(*this, TemplateId);
6138
6139 // Check for unexpanded parameter packs in any of the template arguments.
6140 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6141 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6142 UPPC_PartialSpecialization))
6143 return true;
6144
6145 // Check that the template argument list is well-formed for this
6146 // template.
6147 SmallVector<TemplateArgument, 4> Converted;
6148 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6149 TemplateArgs, false, Converted))
6150 return true;
6151
6152 // Find the class template (partial) specialization declaration that
6153 // corresponds to these arguments.
6154 if (isPartialSpecialization) {
6155 if (CheckTemplatePartialSpecializationArgs(
6156 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6157 TemplateArgs.size(), Converted))
6158 return true;
6159
6160 bool InstantiationDependent;
6161 if (!Name.isDependent() &&
6162 !TemplateSpecializationType::anyDependentTemplateArguments(
6163 TemplateArgs.getArgumentArray(),
6164 TemplateArgs.size(),
6165 InstantiationDependent)) {
6166 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6167 << ClassTemplate->getDeclName();
6168 isPartialSpecialization = false;
6169 }
6170 }
6171
6172 void *InsertPos = nullptr;
6173 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6174
6175 if (isPartialSpecialization)
6176 // FIXME: Template parameter list matters, too
6177 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6178 else
6179 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6180
6181 ClassTemplateSpecializationDecl *Specialization = nullptr;
6182
6183 // Check whether we can declare a class template specialization in
6184 // the current scope.
6185 if (TUK != TUK_Friend &&
6186 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6187 TemplateNameLoc,
6188 isPartialSpecialization))
6189 return true;
6190
6191 // The canonical type
6192 QualType CanonType;
6193 if (isPartialSpecialization) {
6194 // Build the canonical type that describes the converted template
6195 // arguments of the class template partial specialization.
6196 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6197 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6198 Converted.data(),
6199 Converted.size());
6200
6201 if (Context.hasSameType(CanonType,
6202 ClassTemplate->getInjectedClassNameSpecialization())) {
6203 // C++ [temp.class.spec]p9b3:
6204 //
6205 // -- The argument list of the specialization shall not be identical
6206 // to the implicit argument list of the primary template.
6207 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6208 << /*class template*/0 << (TUK == TUK_Definition)
6209 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6210 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6211 ClassTemplate->getIdentifier(),
6212 TemplateNameLoc,
6213 Attr,
6214 TemplateParams,
6215 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6216 /*FriendLoc*/SourceLocation(),
6217 TemplateParameterLists.size() - 1,
6218 TemplateParameterLists.data());
6219 }
6220
6221 // Create a new class template partial specialization declaration node.
6222 ClassTemplatePartialSpecializationDecl *PrevPartial
6223 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6224 ClassTemplatePartialSpecializationDecl *Partial
6225 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6226 ClassTemplate->getDeclContext(),
6227 KWLoc, TemplateNameLoc,
6228 TemplateParams,
6229 ClassTemplate,
6230 Converted.data(),
6231 Converted.size(),
6232 TemplateArgs,
6233 CanonType,
6234 PrevPartial);
6235 SetNestedNameSpecifier(Partial, SS);
6236 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6237 Partial->setTemplateParameterListsInfo(Context,
6238 TemplateParameterLists.size() - 1,
6239 TemplateParameterLists.data());
6240 }
6241
6242 if (!PrevPartial)
6243 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6244 Specialization = Partial;
6245
6246 // If we are providing an explicit specialization of a member class
6247 // template specialization, make a note of that.
6248 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6249 PrevPartial->setMemberSpecialization();
6250
6251 // Check that all of the template parameters of the class template
6252 // partial specialization are deducible from the template
6253 // arguments. If not, this class template partial specialization
6254 // will never be used.
6255 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6256 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6257 TemplateParams->getDepth(),
6258 DeducibleParams);
6259
6260 if (!DeducibleParams.all()) {
6261 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6262 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6263 << /*class template*/0 << (NumNonDeducible > 1)
6264 << SourceRange(TemplateNameLoc, RAngleLoc);
6265 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6266 if (!DeducibleParams[I]) {
6267 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6268 if (Param->getDeclName())
6269 Diag(Param->getLocation(),
6270 diag::note_partial_spec_unused_parameter)
6271 << Param->getDeclName();
6272 else
6273 Diag(Param->getLocation(),
6274 diag::note_partial_spec_unused_parameter)
6275 << "(anonymous)";
6276 }
6277 }
6278 }
6279 } else {
6280 // Create a new class template specialization declaration node for
6281 // this explicit specialization or friend declaration.
6282 Specialization
6283 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6284 ClassTemplate->getDeclContext(),
6285 KWLoc, TemplateNameLoc,
6286 ClassTemplate,
6287 Converted.data(),
6288 Converted.size(),
6289 PrevDecl);
6290 SetNestedNameSpecifier(Specialization, SS);
6291 if (TemplateParameterLists.size() > 0) {
6292 Specialization->setTemplateParameterListsInfo(Context,
6293 TemplateParameterLists.size(),
6294 TemplateParameterLists.data());
6295 }
6296
6297 if (!PrevDecl)
6298 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6299
6300 CanonType = Context.getTypeDeclType(Specialization);
6301 }
6302
6303 // C++ [temp.expl.spec]p6:
6304 // If a template, a member template or the member of a class template is
6305 // explicitly specialized then that specialization shall be declared
6306 // before the first use of that specialization that would cause an implicit
6307 // instantiation to take place, in every translation unit in which such a
6308 // use occurs; no diagnostic is required.
6309 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6310 bool Okay = false;
6311 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6312 // Is there any previous explicit specialization declaration?
6313 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6314 Okay = true;
6315 break;
6316 }
6317 }
6318
6319 if (!Okay) {
6320 SourceRange Range(TemplateNameLoc, RAngleLoc);
6321 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6322 << Context.getTypeDeclType(Specialization) << Range;
6323
6324 Diag(PrevDecl->getPointOfInstantiation(),
6325 diag::note_instantiation_required_here)
6326 << (PrevDecl->getTemplateSpecializationKind()
6327 != TSK_ImplicitInstantiation);
6328 return true;
6329 }
6330 }
6331
6332 // If this is not a friend, note that this is an explicit specialization.
6333 if (TUK != TUK_Friend)
6334 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6335
6336 // Check that this isn't a redefinition of this specialization.
6337 if (TUK == TUK_Definition) {
6338 if (RecordDecl *Def = Specialization->getDefinition()) {
6339 SourceRange Range(TemplateNameLoc, RAngleLoc);
6340 Diag(TemplateNameLoc, diag::err_redefinition)
6341 << Context.getTypeDeclType(Specialization) << Range;
6342 Diag(Def->getLocation(), diag::note_previous_definition);
6343 Specialization->setInvalidDecl();
6344 return true;
6345 }
6346 }
6347
6348 if (Attr)
6349 ProcessDeclAttributeList(S, Specialization, Attr);
6350
6351 // Add alignment attributes if necessary; these attributes are checked when
6352 // the ASTContext lays out the structure.
6353 if (TUK == TUK_Definition) {
6354 AddAlignmentAttributesForRecord(Specialization);
6355 AddMsStructLayoutForRecord(Specialization);
6356 }
6357
6358 if (ModulePrivateLoc.isValid())
6359 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6360 << (isPartialSpecialization? 1 : 0)
6361 << FixItHint::CreateRemoval(ModulePrivateLoc);
6362
6363 // Build the fully-sugared type for this class template
6364 // specialization as the user wrote in the specialization
6365 // itself. This means that we'll pretty-print the type retrieved
6366 // from the specialization's declaration the way that the user
6367 // actually wrote the specialization, rather than formatting the
6368 // name based on the "canonical" representation used to store the
6369 // template arguments in the specialization.
6370 TypeSourceInfo *WrittenTy
6371 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6372 TemplateArgs, CanonType);
6373 if (TUK != TUK_Friend) {
6374 Specialization->setTypeAsWritten(WrittenTy);
6375 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6376 }
6377
6378 // C++ [temp.expl.spec]p9:
6379 // A template explicit specialization is in the scope of the
6380 // namespace in which the template was defined.
6381 //
6382 // We actually implement this paragraph where we set the semantic
6383 // context (in the creation of the ClassTemplateSpecializationDecl),
6384 // but we also maintain the lexical context where the actual
6385 // definition occurs.
6386 Specialization->setLexicalDeclContext(CurContext);
6387
6388 // We may be starting the definition of this specialization.
6389 if (TUK == TUK_Definition)
6390 Specialization->startDefinition();
6391
6392 if (TUK == TUK_Friend) {
6393 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6394 TemplateNameLoc,
6395 WrittenTy,
6396 /*FIXME:*/KWLoc);
6397 Friend->setAccess(AS_public);
6398 CurContext->addDecl(Friend);
6399 } else {
6400 // Add the specialization into its lexical context, so that it can
6401 // be seen when iterating through the list of declarations in that
6402 // context. However, specializations are not found by name lookup.
6403 CurContext->addDecl(Specialization);
6404 }
6405 return Specialization;
6406}
6407
6408Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6409 MultiTemplateParamsArg TemplateParameterLists,
6410 Declarator &D) {
6411 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6412 ActOnDocumentableDecl(NewDecl);
6413 return NewDecl;
6414}
6415
6416Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
6417 MultiTemplateParamsArg TemplateParameterLists,
6418 Declarator &D) {
6419 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
6420 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6421
6422 if (FTI.hasPrototype) {
6423 // FIXME: Diagnose arguments without names in C.
6424 }
6425
6426 Scope *ParentScope = FnBodyScope->getParent();
6427
6428 D.setFunctionDefinitionKind(FDK_Definition);
6429 Decl *DP = HandleDeclarator(ParentScope, D,
6430 TemplateParameterLists);
6431 return ActOnStartOfFunctionDef(FnBodyScope, DP);
6432}
6433
6434/// \brief Strips various properties off an implicit instantiation
6435/// that has just been explicitly specialized.
6436static void StripImplicitInstantiation(NamedDecl *D) {
6437 D->dropAttr<DLLImportAttr>();
6438 D->dropAttr<DLLExportAttr>();
6439
6440 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6441 FD->setInlineSpecified(false);
6442}
6443
6444/// \brief Compute the diagnostic location for an explicit instantiation
6445// declaration or definition.
6446static SourceLocation DiagLocForExplicitInstantiation(
6447 NamedDecl* D, SourceLocation PointOfInstantiation) {
6448 // Explicit instantiations following a specialization have no effect and
6449 // hence no PointOfInstantiation. In that case, walk decl backwards
6450 // until a valid name loc is found.
6451 SourceLocation PrevDiagLoc = PointOfInstantiation;
6452 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6453 Prev = Prev->getPreviousDecl()) {
6454 PrevDiagLoc = Prev->getLocation();
6455 }
6456 assert(PrevDiagLoc.isValid() &&
6457 "Explicit instantiation without point of instantiation?");
6458 return PrevDiagLoc;
6459}
6460
6461/// \brief Diagnose cases where we have an explicit template specialization
6462/// before/after an explicit template instantiation, producing diagnostics
6463/// for those cases where they are required and determining whether the
6464/// new specialization/instantiation will have any effect.
6465///
6466/// \param NewLoc the location of the new explicit specialization or
6467/// instantiation.
6468///
6469/// \param NewTSK the kind of the new explicit specialization or instantiation.
6470///
6471/// \param PrevDecl the previous declaration of the entity.
6472///
6473/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6474///
6475/// \param PrevPointOfInstantiation if valid, indicates where the previus
6476/// declaration was instantiated (either implicitly or explicitly).
6477///
6478/// \param HasNoEffect will be set to true to indicate that the new
6479/// specialization or instantiation has no effect and should be ignored.
6480///
6481/// \returns true if there was an error that should prevent the introduction of
6482/// the new declaration into the AST, false otherwise.
6483bool
6484Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6485 TemplateSpecializationKind NewTSK,
6486 NamedDecl *PrevDecl,
6487 TemplateSpecializationKind PrevTSK,
6488 SourceLocation PrevPointOfInstantiation,
6489 bool &HasNoEffect) {
6490 HasNoEffect = false;
6491
6492 switch (NewTSK) {
6493 case TSK_Undeclared:
6494 case TSK_ImplicitInstantiation:
6495 assert(
6496 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6497 "previous declaration must be implicit!");
6498 return false;
6499
6500 case TSK_ExplicitSpecialization:
6501 switch (PrevTSK) {
6502 case TSK_Undeclared:
6503 case TSK_ExplicitSpecialization:
6504 // Okay, we're just specializing something that is either already
6505 // explicitly specialized or has merely been mentioned without any
6506 // instantiation.
6507 return false;
6508
6509 case TSK_ImplicitInstantiation:
6510 if (PrevPointOfInstantiation.isInvalid()) {
6511 // The declaration itself has not actually been instantiated, so it is
6512 // still okay to specialize it.
6513 StripImplicitInstantiation(PrevDecl);
6514 return false;
6515 }
6516 // Fall through
6517
6518 case TSK_ExplicitInstantiationDeclaration:
6519 case TSK_ExplicitInstantiationDefinition:
6520 assert((PrevTSK == TSK_ImplicitInstantiation ||
6521 PrevPointOfInstantiation.isValid()) &&
6522 "Explicit instantiation without point of instantiation?");
6523
6524 // C++ [temp.expl.spec]p6:
6525 // If a template, a member template or the member of a class template
6526 // is explicitly specialized then that specialization shall be declared
6527 // before the first use of that specialization that would cause an
6528 // implicit instantiation to take place, in every translation unit in
6529 // which such a use occurs; no diagnostic is required.
6530 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6531 // Is there any previous explicit specialization declaration?
6532 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6533 return false;
6534 }
6535
6536 Diag(NewLoc, diag::err_specialization_after_instantiation)
6537 << PrevDecl;
6538 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6539 << (PrevTSK != TSK_ImplicitInstantiation);
6540
6541 return true;
6542 }
6543
6544 case TSK_ExplicitInstantiationDeclaration:
6545 switch (PrevTSK) {
6546 case TSK_ExplicitInstantiationDeclaration:
6547 // This explicit instantiation declaration is redundant (that's okay).
6548 HasNoEffect = true;
6549 return false;
6550
6551 case TSK_Undeclared:
6552 case TSK_ImplicitInstantiation:
6553 // We're explicitly instantiating something that may have already been
6554 // implicitly instantiated; that's fine.
6555 return false;
6556
6557 case TSK_ExplicitSpecialization:
6558 // C++0x [temp.explicit]p4:
6559 // For a given set of template parameters, if an explicit instantiation
6560 // of a template appears after a declaration of an explicit
6561 // specialization for that template, the explicit instantiation has no
6562 // effect.
6563 HasNoEffect = true;
6564 return false;
6565
6566 case TSK_ExplicitInstantiationDefinition:
6567 // C++0x [temp.explicit]p10:
6568 // If an entity is the subject of both an explicit instantiation
6569 // declaration and an explicit instantiation definition in the same
6570 // translation unit, the definition shall follow the declaration.
6571 Diag(NewLoc,
6572 diag::err_explicit_instantiation_declaration_after_definition);
6573
6574 // Explicit instantiations following a specialization have no effect and
6575 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6576 // until a valid name loc is found.
6577 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6578 diag::note_explicit_instantiation_definition_here);
6579 HasNoEffect = true;
6580 return false;
6581 }
6582
6583 case TSK_ExplicitInstantiationDefinition:
6584 switch (PrevTSK) {
6585 case TSK_Undeclared:
6586 case TSK_ImplicitInstantiation:
6587 // We're explicitly instantiating something that may have already been
6588 // implicitly instantiated; that's fine.
6589 return false;
6590
6591 case TSK_ExplicitSpecialization:
6592 // C++ DR 259, C++0x [temp.explicit]p4:
6593 // For a given set of template parameters, if an explicit
6594 // instantiation of a template appears after a declaration of
6595 // an explicit specialization for that template, the explicit
6596 // instantiation has no effect.
6597 //
6598 // In C++98/03 mode, we only give an extension warning here, because it
6599 // is not harmful to try to explicitly instantiate something that
6600 // has been explicitly specialized.
6601 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6602 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6603 diag::ext_explicit_instantiation_after_specialization)
6604 << PrevDecl;
6605 Diag(PrevDecl->getLocation(),
6606 diag::note_previous_template_specialization);
6607 HasNoEffect = true;
6608 return false;
6609
6610 case TSK_ExplicitInstantiationDeclaration:
6611 // We're explicity instantiating a definition for something for which we
6612 // were previously asked to suppress instantiations. That's fine.
6613
6614 // C++0x [temp.explicit]p4:
6615 // For a given set of template parameters, if an explicit instantiation
6616 // of a template appears after a declaration of an explicit
6617 // specialization for that template, the explicit instantiation has no
6618 // effect.
6619 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6620 // Is there any previous explicit specialization declaration?
6621 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6622 HasNoEffect = true;
6623 break;
6624 }
6625 }
6626
6627 return false;
6628
6629 case TSK_ExplicitInstantiationDefinition:
6630 // C++0x [temp.spec]p5:
6631 // For a given template and a given set of template-arguments,
6632 // - an explicit instantiation definition shall appear at most once
6633 // in a program,
6634
6635 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6636 Diag(NewLoc, (getLangOpts().MSVCCompat)
6637 ? diag::ext_explicit_instantiation_duplicate
6638 : diag::err_explicit_instantiation_duplicate)
6639 << PrevDecl;
6640 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6641 diag::note_previous_explicit_instantiation);
6642 HasNoEffect = true;
6643 return false;
6644 }
6645 }
6646
6647 llvm_unreachable("Missing specialization/instantiation case?");
6648}
6649
6650/// \brief Perform semantic analysis for the given dependent function
6651/// template specialization.
6652///
6653/// The only possible way to get a dependent function template specialization
6654/// is with a friend declaration, like so:
6655///
6656/// \code
6657/// template \<class T> void foo(T);
6658/// template \<class T> class A {
6659/// friend void foo<>(T);
6660/// };
6661/// \endcode
6662///
6663/// There really isn't any useful analysis we can do here, so we
6664/// just store the information.
6665bool
6666Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6667 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6668 LookupResult &Previous) {
6669 // Remove anything from Previous that isn't a function template in
6670 // the correct context.
6671 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6672 LookupResult::Filter F = Previous.makeFilter();
6673 while (F.hasNext()) {
6674 NamedDecl *D = F.next()->getUnderlyingDecl();
6675 if (!isa<FunctionTemplateDecl>(D) ||
6676 !FDLookupContext->InEnclosingNamespaceSetOf(
6677 D->getDeclContext()->getRedeclContext()))
6678 F.erase();
6679 }
6680 F.done();
6681
6682 // Should this be diagnosed here?
6683 if (Previous.empty()) return true;
6684
6685 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6686 ExplicitTemplateArgs);
6687 return false;
6688}
6689
6690/// \brief Perform semantic analysis for the given function template
6691/// specialization.
6692///
6693/// This routine performs all of the semantic analysis required for an
6694/// explicit function template specialization. On successful completion,
6695/// the function declaration \p FD will become a function template
6696/// specialization.
6697///
6698/// \param FD the function declaration, which will be updated to become a
6699/// function template specialization.
6700///
6701/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6702/// if any. Note that this may be valid info even when 0 arguments are
6703/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6704/// as it anyway contains info on the angle brackets locations.
6705///
6706/// \param Previous the set of declarations that may be specialized by
6707/// this function specialization.
6708bool Sema::CheckFunctionTemplateSpecialization(
6709 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6710 LookupResult &Previous) {
6711 // The set of function template specializations that could match this
6712 // explicit function template specialization.
6713 UnresolvedSet<8> Candidates;
6714 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
6715
6716 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6717 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6718 I != E; ++I) {
6719 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6720 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6721 // Only consider templates found within the same semantic lookup scope as
6722 // FD.
6723 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6724 Ovl->getDeclContext()->getRedeclContext()))
6725 continue;
6726
6727 // When matching a constexpr member function template specialization
6728 // against the primary template, we don't yet know whether the
6729 // specialization has an implicit 'const' (because we don't know whether
6730 // it will be a static member function until we know which template it
6731 // specializes), so adjust it now assuming it specializes this template.
6732 QualType FT = FD->getType();
6733 if (FD->isConstexpr()) {
6734 CXXMethodDecl *OldMD =
6735 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6736 if (OldMD && OldMD->isConst()) {
6737 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6738 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6739 EPI.TypeQuals |= Qualifiers::Const;
6740 FT = Context.getFunctionType(FPT->getReturnType(),
6741 FPT->getParamTypes(), EPI);
6742 }
6743 }
6744
6745 // C++ [temp.expl.spec]p11:
6746 // A trailing template-argument can be left unspecified in the
6747 // template-id naming an explicit function template specialization
6748 // provided it can be deduced from the function argument type.
6749 // Perform template argument deduction to determine whether we may be
6750 // specializing this template.
6751 // FIXME: It is somewhat wasteful to build
6752 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6753 FunctionDecl *Specialization = nullptr;
6754 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6755 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6756 ExplicitTemplateArgs, FT, Specialization, Info)) {
6757 // Template argument deduction failed; record why it failed, so
6758 // that we can provide nifty diagnostics.
6759 FailedCandidates.addCandidate()
6760 .set(FunTmpl->getTemplatedDecl(),
6761 MakeDeductionFailureInfo(Context, TDK, Info));
6762 (void)TDK;
6763 continue;
6764 }
6765
6766 // Record this candidate.
6767 Candidates.addDecl(Specialization, I.getAccess());
6768 }
6769 }
6770
6771 // Find the most specialized function template.
6772 UnresolvedSetIterator Result = getMostSpecialized(
6773 Candidates.begin(), Candidates.end(), FailedCandidates,
6774 FD->getLocation(),
6775 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6776 PDiag(diag::err_function_template_spec_ambiguous)
6777 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6778 PDiag(diag::note_function_template_spec_matched));
6779
6780 if (Result == Candidates.end())
6781 return true;
6782
6783 // Ignore access information; it doesn't figure into redeclaration checking.
6784 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6785
6786 FunctionTemplateSpecializationInfo *SpecInfo
6787 = Specialization->getTemplateSpecializationInfo();
6788 assert(SpecInfo && "Function template specialization info missing?");
6789
6790 // Note: do not overwrite location info if previous template
6791 // specialization kind was explicit.
6792 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6793 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6794 Specialization->setLocation(FD->getLocation());
6795 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6796 // function can differ from the template declaration with respect to
6797 // the constexpr specifier.
6798 Specialization->setConstexpr(FD->isConstexpr());
6799 }
6800
6801 // FIXME: Check if the prior specialization has a point of instantiation.
6802 // If so, we have run afoul of .
6803
6804 // If this is a friend declaration, then we're not really declaring
6805 // an explicit specialization.
6806 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6807
6808 // Check the scope of this explicit specialization.
6809 if (!isFriend &&
6810 CheckTemplateSpecializationScope(*this,
6811 Specialization->getPrimaryTemplate(),
6812 Specialization, FD->getLocation(),
6813 false))
6814 return true;
6815
6816 // C++ [temp.expl.spec]p6:
6817 // If a template, a member template or the member of a class template is
6818 // explicitly specialized then that specialization shall be declared
6819 // before the first use of that specialization that would cause an implicit
6820 // instantiation to take place, in every translation unit in which such a
6821 // use occurs; no diagnostic is required.
6822 bool HasNoEffect = false;
6823 if (!isFriend &&
6824 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6825 TSK_ExplicitSpecialization,
6826 Specialization,
6827 SpecInfo->getTemplateSpecializationKind(),
6828 SpecInfo->getPointOfInstantiation(),
6829 HasNoEffect))
6830 return true;
6831
6832 // Mark the prior declaration as an explicit specialization, so that later
6833 // clients know that this is an explicit specialization.
6834 if (!isFriend) {
6835 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6836 MarkUnusedFileScopedDecl(Specialization);
6837 }
6838
6839 // Turn the given function declaration into a function template
6840 // specialization, with the template arguments from the previous
6841 // specialization.
6842 // Take copies of (semantic and syntactic) template argument lists.
6843 const TemplateArgumentList* TemplArgs = new (Context)
6844 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6845 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6846 TemplArgs, /*InsertPos=*/nullptr,
6847 SpecInfo->getTemplateSpecializationKind(),
6848 ExplicitTemplateArgs);
6849
6850 // The "previous declaration" for this function template specialization is
6851 // the prior function template specialization.
6852 Previous.clear();
6853 Previous.addDecl(Specialization);
6854 return false;
6855}
6856
6857/// \brief Perform semantic analysis for the given non-template member
6858/// specialization.
6859///
6860/// This routine performs all of the semantic analysis required for an
6861/// explicit member function specialization. On successful completion,
6862/// the function declaration \p FD will become a member function
6863/// specialization.
6864///
6865/// \param Member the member declaration, which will be updated to become a
6866/// specialization.
6867///
6868/// \param Previous the set of declarations, one of which may be specialized
6869/// by this function specialization; the set will be modified to contain the
6870/// redeclared member.
6871bool
6872Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6873 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6874
6875 // Try to find the member we are instantiating.
6876 NamedDecl *Instantiation = nullptr;
6877 NamedDecl *InstantiatedFrom = nullptr;
6878 MemberSpecializationInfo *MSInfo = nullptr;
6879
6880 if (Previous.empty()) {
6881 // Nowhere to look anyway.
6882 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6883 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6884 I != E; ++I) {
6885 NamedDecl *D = (*I)->getUnderlyingDecl();
6886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6887 QualType Adjusted = Function->getType();
6888 if (!hasExplicitCallingConv(Adjusted))
6889 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6890 if (Context.hasSameType(Adjusted, Method->getType())) {
6891 Instantiation = Method;
6892 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6893 MSInfo = Method->getMemberSpecializationInfo();
6894 break;
6895 }
6896 }
6897 }
6898 } else if (isa<VarDecl>(Member)) {
6899 VarDecl *PrevVar;
6900 if (Previous.isSingleResult() &&
6901 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6902 if (PrevVar->isStaticDataMember()) {
6903 Instantiation = PrevVar;
6904 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6905 MSInfo = PrevVar->getMemberSpecializationInfo();
6906 }
6907 } else if (isa<RecordDecl>(Member)) {
6908 CXXRecordDecl *PrevRecord;
6909 if (Previous.isSingleResult() &&
6910 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6911 Instantiation = PrevRecord;
6912 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6913 MSInfo = PrevRecord->getMemberSpecializationInfo();
6914 }
6915 } else if (isa<EnumDecl>(Member)) {
6916 EnumDecl *PrevEnum;
6917 if (Previous.isSingleResult() &&
6918 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6919 Instantiation = PrevEnum;
6920 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6921 MSInfo = PrevEnum->getMemberSpecializationInfo();
6922 }
6923 }
6924
6925 if (!Instantiation) {
6926 // There is no previous declaration that matches. Since member
6927 // specializations are always out-of-line, the caller will complain about
6928 // this mismatch later.
6929 return false;
6930 }
6931
6932 // If this is a friend, just bail out here before we start turning
6933 // things into explicit specializations.
6934 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6935 // Preserve instantiation information.
6936 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6937 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6938 cast<CXXMethodDecl>(InstantiatedFrom),
6939 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6940 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6941 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6942 cast<CXXRecordDecl>(InstantiatedFrom),
6943 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6944 }
6945
6946 Previous.clear();
6947 Previous.addDecl(Instantiation);
6948 return false;
6949 }
6950
6951 // Make sure that this is a specialization of a member.
6952 if (!InstantiatedFrom) {
6953 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6954 << Member;
6955 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6956 return true;
6957 }
6958
6959 // C++ [temp.expl.spec]p6:
6960 // If a template, a member template or the member of a class template is
6961 // explicitly specialized then that specialization shall be declared
6962 // before the first use of that specialization that would cause an implicit
6963 // instantiation to take place, in every translation unit in which such a
6964 // use occurs; no diagnostic is required.
6965 assert(MSInfo && "Member specialization info missing?");
6966
6967 bool HasNoEffect = false;
6968 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6969 TSK_ExplicitSpecialization,
6970 Instantiation,
6971 MSInfo->getTemplateSpecializationKind(),
6972 MSInfo->getPointOfInstantiation(),
6973 HasNoEffect))
6974 return true;
6975
6976 // Check the scope of this explicit specialization.
6977 if (CheckTemplateSpecializationScope(*this,
6978 InstantiatedFrom,
6979 Instantiation, Member->getLocation(),
6980 false))
6981 return true;
6982
6983 // Note that this is an explicit instantiation of a member.
6984 // the original declaration to note that it is an explicit specialization
6985 // (if it was previously an implicit instantiation). This latter step
6986 // makes bookkeeping easier.
6987 if (isa<FunctionDecl>(Member)) {
6988 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6989 if (InstantiationFunction->getTemplateSpecializationKind() ==
6990 TSK_ImplicitInstantiation) {
6991 InstantiationFunction->setTemplateSpecializationKind(
6992 TSK_ExplicitSpecialization);
6993 InstantiationFunction->setLocation(Member->getLocation());
6994 }
6995
6996 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6997 cast<CXXMethodDecl>(InstantiatedFrom),
6998 TSK_ExplicitSpecialization);
6999 MarkUnusedFileScopedDecl(InstantiationFunction);
7000 } else if (isa<VarDecl>(Member)) {
7001 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7002 if (InstantiationVar->getTemplateSpecializationKind() ==
7003 TSK_ImplicitInstantiation) {
7004 InstantiationVar->setTemplateSpecializationKind(
7005 TSK_ExplicitSpecialization);
7006 InstantiationVar->setLocation(Member->getLocation());
7007 }
7008
7009 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7010 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7011 MarkUnusedFileScopedDecl(InstantiationVar);
7012 } else if (isa<CXXRecordDecl>(Member)) {
7013 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7014 if (InstantiationClass->getTemplateSpecializationKind() ==
7015 TSK_ImplicitInstantiation) {
7016 InstantiationClass->setTemplateSpecializationKind(
7017 TSK_ExplicitSpecialization);
7018 InstantiationClass->setLocation(Member->getLocation());
7019 }
7020
7021 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7022 cast<CXXRecordDecl>(InstantiatedFrom),
7023 TSK_ExplicitSpecialization);
7024 } else {
7025 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7026 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7027 if (InstantiationEnum->getTemplateSpecializationKind() ==
7028 TSK_ImplicitInstantiation) {
7029 InstantiationEnum->setTemplateSpecializationKind(
7030 TSK_ExplicitSpecialization);
7031 InstantiationEnum->setLocation(Member->getLocation());
7032 }
7033
7034 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7035 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7036 }
7037
7038 // Save the caller the trouble of having to figure out which declaration
7039 // this specialization matches.
7040 Previous.clear();
7041 Previous.addDecl(Instantiation);
7042 return false;
7043}
7044
7045/// \brief Check the scope of an explicit instantiation.
7046///
7047/// \returns true if a serious error occurs, false otherwise.
7048static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7049 SourceLocation InstLoc,
7050 bool WasQualifiedName) {
7051 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7052 DeclContext *CurContext = S.CurContext->getRedeclContext();
7053
7054 if (CurContext->isRecord()) {
7055 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7056 << D;
7057 return true;
7058 }
7059
7060 // C++11 [temp.explicit]p3:
7061 // An explicit instantiation shall appear in an enclosing namespace of its
7062 // template. If the name declared in the explicit instantiation is an
7063 // unqualified name, the explicit instantiation shall appear in the
7064 // namespace where its template is declared or, if that namespace is inline
7065 // (7.3.1), any namespace from its enclosing namespace set.
7066 //
7067 // This is DR275, which we do not retroactively apply to C++98/03.
7068 if (WasQualifiedName) {
7069 if (CurContext->Encloses(OrigContext))
7070 return false;
7071 } else {
7072 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7073 return false;
7074 }
7075
7076 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7077 if (WasQualifiedName)
7078 S.Diag(InstLoc,
7079 S.getLangOpts().CPlusPlus11?
7080 diag::err_explicit_instantiation_out_of_scope :
7081 diag::warn_explicit_instantiation_out_of_scope_0x)
7082 << D << NS;
7083 else
7084 S.Diag(InstLoc,
7085 S.getLangOpts().CPlusPlus11?
7086 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7087 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7088 << D << NS;
7089 } else
7090 S.Diag(InstLoc,
7091 S.getLangOpts().CPlusPlus11?
7092 diag::err_explicit_instantiation_must_be_global :
7093 diag::warn_explicit_instantiation_must_be_global_0x)
7094 << D;
7095 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7096 return false;
7097}
7098
7099/// \brief Determine whether the given scope specifier has a template-id in it.
7100static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7101 if (!SS.isSet())
7102 return false;
7103
7104 // C++11 [temp.explicit]p3:
7105 // If the explicit instantiation is for a member function, a member class
7106 // or a static data member of a class template specialization, the name of
7107 // the class template specialization in the qualified-id for the member
7108 // name shall be a simple-template-id.
7109 //
7110 // C++98 has the same restriction, just worded differently.
7111 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7112 NNS = NNS->getPrefix())
7113 if (const Type *T = NNS->getAsType())
7114 if (isa<TemplateSpecializationType>(T))
7115 return true;
7116
7117 return false;
7118}
7119
7120// Explicit instantiation of a class template specialization
7121DeclResult
7122Sema::ActOnExplicitInstantiation(Scope *S,
7123 SourceLocation ExternLoc,
7124 SourceLocation TemplateLoc,
7125 unsigned TagSpec,
7126 SourceLocation KWLoc,
7127 const CXXScopeSpec &SS,
7128 TemplateTy TemplateD,
7129 SourceLocation TemplateNameLoc,
7130 SourceLocation LAngleLoc,
7131 ASTTemplateArgsPtr TemplateArgsIn,
7132 SourceLocation RAngleLoc,
7133 AttributeList *Attr) {
7134 // Find the class template we're specializing
7135 TemplateName Name = TemplateD.get();
7136 TemplateDecl *TD = Name.getAsTemplateDecl();
7137 // Check that the specialization uses the same tag kind as the
7138 // original template.
7139 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7140 assert(Kind != TTK_Enum &&
7141 "Invalid enum tag in class template explicit instantiation!");
7142
7143 if (isa<TypeAliasTemplateDecl>(TD)) {
7144 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7145 Diag(TD->getTemplatedDecl()->getLocation(),
7146 diag::note_previous_use);
7147 return true;
7148 }
7149
7150 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7151
7152 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7153 Kind, /*isDefinition*/false, KWLoc,
7154 *ClassTemplate->getIdentifier())) {
7155 Diag(KWLoc, diag::err_use_with_wrong_tag)
7156 << ClassTemplate
7157 << FixItHint::CreateReplacement(KWLoc,
7158 ClassTemplate->getTemplatedDecl()->getKindName());
7159 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7160 diag::note_previous_use);
7161 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7162 }
7163
7164 // C++0x [temp.explicit]p2:
7165 // There are two forms of explicit instantiation: an explicit instantiation
7166 // definition and an explicit instantiation declaration. An explicit
7167 // instantiation declaration begins with the extern keyword. [...]
7168 TemplateSpecializationKind TSK
7169 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7170 : TSK_ExplicitInstantiationDeclaration;
7171
7172 // Translate the parser's template argument list in our AST format.
7173 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7174 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7175
7176 // Check that the template argument list is well-formed for this
7177 // template.
7178 SmallVector<TemplateArgument, 4> Converted;
7179 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7180 TemplateArgs, false, Converted))
7181 return true;
7182
7183 // Find the class template specialization declaration that
7184 // corresponds to these arguments.
7185 void *InsertPos = nullptr;
7186 ClassTemplateSpecializationDecl *PrevDecl
7187 = ClassTemplate->findSpecialization(Converted, InsertPos);
7188
7189 TemplateSpecializationKind PrevDecl_TSK
7190 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7191
7192 // C++0x [temp.explicit]p2:
7193 // [...] An explicit instantiation shall appear in an enclosing
7194 // namespace of its template. [...]
7195 //
7196 // This is C++ DR 275.
7197 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7198 SS.isSet()))
7199 return true;
7200
7201 ClassTemplateSpecializationDecl *Specialization = nullptr;
7202
7203 bool HasNoEffect = false;
7204 if (PrevDecl) {
7205 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7206 PrevDecl, PrevDecl_TSK,
7207 PrevDecl->getPointOfInstantiation(),
7208 HasNoEffect))
7209 return PrevDecl;
7210
7211 // Even though HasNoEffect == true means that this explicit instantiation
7212 // has no effect on semantics, we go on to put its syntax in the AST.
7213
7214 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7215 PrevDecl_TSK == TSK_Undeclared) {
7216 // Since the only prior class template specialization with these
7217 // arguments was referenced but not declared, reuse that
7218 // declaration node as our own, updating the source location
7219 // for the template name to reflect our new declaration.
7220 // (Other source locations will be updated later.)
7221 Specialization = PrevDecl;
7222 Specialization->setLocation(TemplateNameLoc);
7223 PrevDecl = nullptr;
7224 }
7225 }
7226
7227 if (!Specialization) {
7228 // Create a new class template specialization declaration node for
7229 // this explicit specialization.
7230 Specialization
7231 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7232 ClassTemplate->getDeclContext(),
7233 KWLoc, TemplateNameLoc,
7234 ClassTemplate,
7235 Converted.data(),
7236 Converted.size(),
7237 PrevDecl);
7238 SetNestedNameSpecifier(Specialization, SS);
7239
7240 if (!HasNoEffect && !PrevDecl) {
7241 // Insert the new specialization.
7242 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7243 }
7244 }
7245
7246 // Build the fully-sugared type for this explicit instantiation as
7247 // the user wrote in the explicit instantiation itself. This means
7248 // that we'll pretty-print the type retrieved from the
7249 // specialization's declaration the way that the user actually wrote
7250 // the explicit instantiation, rather than formatting the name based
7251 // on the "canonical" representation used to store the template
7252 // arguments in the specialization.
7253 TypeSourceInfo *WrittenTy
7254 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7255 TemplateArgs,
7256 Context.getTypeDeclType(Specialization));
7257 Specialization->setTypeAsWritten(WrittenTy);
7258
7259 // Set source locations for keywords.
7260 Specialization->setExternLoc(ExternLoc);
7261 Specialization->setTemplateKeywordLoc(TemplateLoc);
7262 Specialization->setRBraceLoc(SourceLocation());
7263
7264 if (Attr)
7265 ProcessDeclAttributeList(S, Specialization, Attr);
7266
7267 // Add the explicit instantiation into its lexical context. However,
7268 // since explicit instantiations are never found by name lookup, we
7269 // just put it into the declaration context directly.
7270 Specialization->setLexicalDeclContext(CurContext);
7271 CurContext->addDecl(Specialization);
7272
7273 // Syntax is now OK, so return if it has no other effect on semantics.
7274 if (HasNoEffect) {
7275 // Set the template specialization kind.
7276 Specialization->setTemplateSpecializationKind(TSK);
7277 return Specialization;
7278 }
7279
7280 // C++ [temp.explicit]p3:
7281 // A definition of a class template or class member template
7282 // shall be in scope at the point of the explicit instantiation of
7283 // the class template or class member template.
7284 //
7285 // This check comes when we actually try to perform the
7286 // instantiation.
7287 ClassTemplateSpecializationDecl *Def
7288 = cast_or_null<ClassTemplateSpecializationDecl>(
7289 Specialization->getDefinition());
7290 if (!Def)
7291 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7292 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7293 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7294 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7295 }
7296
7297 // Instantiate the members of this class template specialization.
7298 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7299 Specialization->getDefinition());
7300 if (Def) {
7301 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7302
7303 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7304 // TSK_ExplicitInstantiationDefinition
7305 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7306 TSK == TSK_ExplicitInstantiationDefinition)
7307 // FIXME: Need to notify the ASTMutationListener that we did this.
7308 Def->setTemplateSpecializationKind(TSK);
7309
7310 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7311 }
7312
7313 // Set the template specialization kind.
7314 Specialization->setTemplateSpecializationKind(TSK);
7315 return Specialization;
7316}
7317
7318// Explicit instantiation of a member class of a class template.
7319DeclResult
7320Sema::ActOnExplicitInstantiation(Scope *S,
7321 SourceLocation ExternLoc,
7322 SourceLocation TemplateLoc,
7323 unsigned TagSpec,
7324 SourceLocation KWLoc,
7325 CXXScopeSpec &SS,
7326 IdentifierInfo *Name,
7327 SourceLocation NameLoc,
7328 AttributeList *Attr) {
7329
7330 bool Owned = false;
7331 bool IsDependent = false;
7332 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7333 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7334 /*ModulePrivateLoc=*/SourceLocation(),
7335 MultiTemplateParamsArg(), Owned, IsDependent,
7336 SourceLocation(), false, TypeResult(),
7337 /*IsTypeSpecifier*/false);
7338 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7339
7340 if (!TagD)
7341 return true;
7342
7343 TagDecl *Tag = cast<TagDecl>(TagD);
7344 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7345
7346 if (Tag->isInvalidDecl())
7347 return true;
7348
7349 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7350 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7351 if (!Pattern) {
7352 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7353 << Context.getTypeDeclType(Record);
7354 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7355 return true;
7356 }
7357
7358 // C++0x [temp.explicit]p2:
7359 // If the explicit instantiation is for a class or member class, the
7360 // elaborated-type-specifier in the declaration shall include a
7361 // simple-template-id.
7362 //
7363 // C++98 has the same restriction, just worded differently.
7364 if (!ScopeSpecifierHasTemplateId(SS))
7365 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7366 << Record << SS.getRange();
7367
7368 // C++0x [temp.explicit]p2:
7369 // There are two forms of explicit instantiation: an explicit instantiation
7370 // definition and an explicit instantiation declaration. An explicit
7371 // instantiation declaration begins with the extern keyword. [...]
7372 TemplateSpecializationKind TSK
7373 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7374 : TSK_ExplicitInstantiationDeclaration;
7375
7376 // C++0x [temp.explicit]p2:
7377 // [...] An explicit instantiation shall appear in an enclosing
7378 // namespace of its template. [...]
7379 //
7380 // This is C++ DR 275.
7381 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7382
7383 // Verify that it is okay to explicitly instantiate here.
7384 CXXRecordDecl *PrevDecl
7385 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7386 if (!PrevDecl && Record->getDefinition())
7387 PrevDecl = Record;
7388 if (PrevDecl) {
7389 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7390 bool HasNoEffect = false;
7391 assert(MSInfo && "No member specialization information?");
7392 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7393 PrevDecl,
7394 MSInfo->getTemplateSpecializationKind(),
7395 MSInfo->getPointOfInstantiation(),
7396 HasNoEffect))
7397 return true;
7398 if (HasNoEffect)
7399 return TagD;
7400 }
7401
7402 CXXRecordDecl *RecordDef
7403 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7404 if (!RecordDef) {
7405 // C++ [temp.explicit]p3:
7406 // A definition of a member class of a class template shall be in scope
7407 // at the point of an explicit instantiation of the member class.
7408 CXXRecordDecl *Def
7409 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7410 if (!Def) {
7411 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7412 << 0 << Record->getDeclName() << Record->getDeclContext();
7413 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7414 << Pattern;
7415 return true;
7416 } else {
7417 if (InstantiateClass(NameLoc, Record, Def,
7418 getTemplateInstantiationArgs(Record),
7419 TSK))
7420 return true;
7421
7422 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7423 if (!RecordDef)
7424 return true;
7425 }
7426 }
7427
7428 // Instantiate all of the members of the class.
7429 InstantiateClassMembers(NameLoc, RecordDef,
7430 getTemplateInstantiationArgs(Record), TSK);
7431
7432 if (TSK == TSK_ExplicitInstantiationDefinition)
7433 MarkVTableUsed(NameLoc, RecordDef, true);
7434
7435 // FIXME: We don't have any representation for explicit instantiations of
7436 // member classes. Such a representation is not needed for compilation, but it
7437 // should be available for clients that want to see all of the declarations in
7438 // the source code.
7439 return TagD;
7440}
7441
7442DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7443 SourceLocation ExternLoc,
7444 SourceLocation TemplateLoc,
7445 Declarator &D) {
7446 // Explicit instantiations always require a name.
7447 // TODO: check if/when DNInfo should replace Name.
7448 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7449 DeclarationName Name = NameInfo.getName();
7450 if (!Name) {
7451 if (!D.isInvalidType())
7452 Diag(D.getDeclSpec().getLocStart(),
7453 diag::err_explicit_instantiation_requires_name)
7454 << D.getDeclSpec().getSourceRange()
7455 << D.getSourceRange();
7456
7457 return true;
7458 }
7459
7460 // The scope passed in may not be a decl scope. Zip up the scope tree until
7461 // we find one that is.
7462 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7463 (S->getFlags() & Scope::TemplateParamScope) != 0)
7464 S = S->getParent();
7465
7466 // Determine the type of the declaration.
7467 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7468 QualType R = T->getType();
7469 if (R.isNull())
7470 return true;
7471
7472 // C++ [dcl.stc]p1:
7473 // A storage-class-specifier shall not be specified in [...] an explicit
7474 // instantiation (14.7.2) directive.
7475 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7476 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7477 << Name;
7478 return true;
7479 } else if (D.getDeclSpec().getStorageClassSpec()
7480 != DeclSpec::SCS_unspecified) {
7481 // Complain about then remove the storage class specifier.
7482 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7483 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7484
7485 D.getMutableDeclSpec().ClearStorageClassSpecs();
7486 }
7487
7488 // C++0x [temp.explicit]p1:
7489 // [...] An explicit instantiation of a function template shall not use the
7490 // inline or constexpr specifiers.
7491 // Presumably, this also applies to member functions of class templates as
7492 // well.
7493 if (D.getDeclSpec().isInlineSpecified())
7494 Diag(D.getDeclSpec().getInlineSpecLoc(),
7495 getLangOpts().CPlusPlus11 ?
7496 diag::err_explicit_instantiation_inline :
7497 diag::warn_explicit_instantiation_inline_0x)
7498 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7499 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7500 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7501 // not already specified.
7502 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7503 diag::err_explicit_instantiation_constexpr);
7504
7505 // C++0x [temp.explicit]p2:
7506 // There are two forms of explicit instantiation: an explicit instantiation
7507 // definition and an explicit instantiation declaration. An explicit
7508 // instantiation declaration begins with the extern keyword. [...]
7509 TemplateSpecializationKind TSK
7510 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7511 : TSK_ExplicitInstantiationDeclaration;
7512
7513 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7514 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7515
7516 if (!R->isFunctionType()) {
7517 // C++ [temp.explicit]p1:
7518 // A [...] static data member of a class template can be explicitly
7519 // instantiated from the member definition associated with its class
7520 // template.
7521 // C++1y [temp.explicit]p1:
7522 // A [...] variable [...] template specialization can be explicitly
7523 // instantiated from its template.
7524 if (Previous.isAmbiguous())
7525 return true;
7526
7527 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7528 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7529
7530 if (!PrevTemplate) {
7531 if (!Prev || !Prev->isStaticDataMember()) {
7532 // We expect to see a data data member here.
7533 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7534 << Name;
7535 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7536 P != PEnd; ++P)
7537 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7538 return true;
7539 }
7540
7541 if (!Prev->getInstantiatedFromStaticDataMember()) {
7542 // FIXME: Check for explicit specialization?
7543 Diag(D.getIdentifierLoc(),
7544 diag::err_explicit_instantiation_data_member_not_instantiated)
7545 << Prev;
7546 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7547 // FIXME: Can we provide a note showing where this was declared?
7548 return true;
7549 }
7550 } else {
7551 // Explicitly instantiate a variable template.
7552
7553 // C++1y [dcl.spec.auto]p6:
7554 // ... A program that uses auto or decltype(auto) in a context not
7555 // explicitly allowed in this section is ill-formed.
7556 //
7557 // This includes auto-typed variable template instantiations.
7558 if (R->isUndeducedType()) {
7559 Diag(T->getTypeLoc().getLocStart(),
7560 diag::err_auto_not_allowed_var_inst);
7561 return true;
7562 }
7563
7564 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7565 // C++1y [temp.explicit]p3:
7566 // If the explicit instantiation is for a variable, the unqualified-id
7567 // in the declaration shall be a template-id.
7568 Diag(D.getIdentifierLoc(),
7569 diag::err_explicit_instantiation_without_template_id)
7570 << PrevTemplate;
7571 Diag(PrevTemplate->getLocation(),
7572 diag::note_explicit_instantiation_here);
7573 return true;
7574 }
7575
7576 // Translate the parser's template argument list into our AST format.
7577 TemplateArgumentListInfo TemplateArgs =
7578 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7579
7580 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7581 D.getIdentifierLoc(), TemplateArgs);
7582 if (Res.isInvalid())
7583 return true;
7584
7585 // Ignore access control bits, we don't need them for redeclaration
7586 // checking.
7587 Prev = cast<VarDecl>(Res.get());
7588 }
7589
7590 // C++0x [temp.explicit]p2:
7591 // If the explicit instantiation is for a member function, a member class
7592 // or a static data member of a class template specialization, the name of
7593 // the class template specialization in the qualified-id for the member
7594 // name shall be a simple-template-id.
7595 //
7596 // C++98 has the same restriction, just worded differently.
7597 //
7598 // This does not apply to variable template specializations, where the
7599 // template-id is in the unqualified-id instead.
7600 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7601 Diag(D.getIdentifierLoc(),
7602 diag::ext_explicit_instantiation_without_qualified_id)
7603 << Prev << D.getCXXScopeSpec().getRange();
7604
7605 // Check the scope of this explicit instantiation.
7606 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7607
7608 // Verify that it is okay to explicitly instantiate here.
7609 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7610 SourceLocation POI = Prev->getPointOfInstantiation();
7611 bool HasNoEffect = false;
7612 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7613 PrevTSK, POI, HasNoEffect))
7614 return true;
7615
7616 if (!HasNoEffect) {
7617 // Instantiate static data member or variable template.
7618
7619 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7620 if (PrevTemplate) {
7621 // Merge attributes.
7622 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7623 ProcessDeclAttributeList(S, Prev, Attr);
7624 }
7625 if (TSK == TSK_ExplicitInstantiationDefinition)
7626 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7627 }
7628
7629 // Check the new variable specialization against the parsed input.
7630 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7631 Diag(T->getTypeLoc().getLocStart(),
7632 diag::err_invalid_var_template_spec_type)
7633 << 0 << PrevTemplate << R << Prev->getType();
7634 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7635 << 2 << PrevTemplate->getDeclName();
7636 return true;
7637 }
7638
7639 // FIXME: Create an ExplicitInstantiation node?
7640 return (Decl*) nullptr;
7641 }
7642
7643 // If the declarator is a template-id, translate the parser's template
7644 // argument list into our AST format.
7645 bool HasExplicitTemplateArgs = false;
7646 TemplateArgumentListInfo TemplateArgs;
7647 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7648 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7649 HasExplicitTemplateArgs = true;
7650 }
7651
7652 // C++ [temp.explicit]p1:
7653 // A [...] function [...] can be explicitly instantiated from its template.
7654 // A member function [...] of a class template can be explicitly
7655 // instantiated from the member definition associated with its class
7656 // template.
7657 UnresolvedSet<8> Matches;
7658 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7659 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7660 P != PEnd; ++P) {
7661 NamedDecl *Prev = *P;
7662 if (!HasExplicitTemplateArgs) {
7663 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7664 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7665 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7666 Matches.clear();
7667
7668 Matches.addDecl(Method, P.getAccess());
7669 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7670 break;
7671 }
7672 }
7673 }
7674
7675 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7676 if (!FunTmpl)
7677 continue;
7678
7679 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7680 FunctionDecl *Specialization = nullptr;
7681 if (TemplateDeductionResult TDK
7682 = DeduceTemplateArguments(FunTmpl,
7683 (HasExplicitTemplateArgs ? &TemplateArgs
7684 : nullptr),
7685 R, Specialization, Info)) {
7686 // Keep track of almost-matches.
7687 FailedCandidates.addCandidate()
7688 .set(FunTmpl->getTemplatedDecl(),
7689 MakeDeductionFailureInfo(Context, TDK, Info));
7690 (void)TDK;
7691 continue;
7692 }
7693
7694 Matches.addDecl(Specialization, P.getAccess());
7695 }
7696
7697 // Find the most specialized function template specialization.
7698 UnresolvedSetIterator Result = getMostSpecialized(
7699 Matches.begin(), Matches.end(), FailedCandidates,
7700 D.getIdentifierLoc(),
7701 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7702 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7703 PDiag(diag::note_explicit_instantiation_candidate));
7704
7705 if (Result == Matches.end())
7706 return true;
7707
7708 // Ignore access control bits, we don't need them for redeclaration checking.
7709 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7710
7711 // C++11 [except.spec]p4
7712 // In an explicit instantiation an exception-specification may be specified,
7713 // but is not required.
7714 // If an exception-specification is specified in an explicit instantiation
7715 // directive, it shall be compatible with the exception-specifications of
7716 // other declarations of that function.
7717 if (auto *FPT = R->getAs<FunctionProtoType>())
7718 if (FPT->hasExceptionSpec()) {
7719 unsigned DiagID =
7720 diag::err_mismatched_exception_spec_explicit_instantiation;
7721 if (getLangOpts().MicrosoftExt)
7722 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7723 bool Result = CheckEquivalentExceptionSpec(
7724 PDiag(DiagID) << Specialization->getType(),
7725 PDiag(diag::note_explicit_instantiation_here),
7726 Specialization->getType()->getAs<FunctionProtoType>(),
7727 Specialization->getLocation(), FPT, D.getLocStart());
7728 // In Microsoft mode, mismatching exception specifications just cause a
7729 // warning.
7730 if (!getLangOpts().MicrosoftExt && Result)
7731 return true;
7732 }
7733
7734 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7735 Diag(D.getIdentifierLoc(),
7736 diag::err_explicit_instantiation_member_function_not_instantiated)
7737 << Specialization
7738 << (Specialization->getTemplateSpecializationKind() ==
7739 TSK_ExplicitSpecialization);
7740 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7741 return true;
7742 }
7743
7744 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7745 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7746 PrevDecl = Specialization;
7747
7748 if (PrevDecl) {
7749 bool HasNoEffect = false;
7750 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7751 PrevDecl,
7752 PrevDecl->getTemplateSpecializationKind(),
7753 PrevDecl->getPointOfInstantiation(),
7754 HasNoEffect))
7755 return true;
7756
7757 // FIXME: We may still want to build some representation of this
7758 // explicit specialization.
7759 if (HasNoEffect)
7760 return (Decl*) nullptr;
7761 }
7762
7763 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7764 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7765 if (Attr)
7766 ProcessDeclAttributeList(S, Specialization, Attr);
7767
7768 if (Specialization->isDefined()) {
7769 // Let the ASTConsumer know that this function has been explicitly
7770 // instantiated now, and its linkage might have changed.
7771 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7772 } else if (TSK == TSK_ExplicitInstantiationDefinition)
7773 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7774
7775 // C++0x [temp.explicit]p2:
7776 // If the explicit instantiation is for a member function, a member class
7777 // or a static data member of a class template specialization, the name of
7778 // the class template specialization in the qualified-id for the member
7779 // name shall be a simple-template-id.
7780 //
7781 // C++98 has the same restriction, just worded differently.
7782 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7783 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7784 D.getCXXScopeSpec().isSet() &&
7785 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7786 Diag(D.getIdentifierLoc(),
7787 diag::ext_explicit_instantiation_without_qualified_id)
7788 << Specialization << D.getCXXScopeSpec().getRange();
7789
7790 CheckExplicitInstantiationScope(*this,
7791 FunTmpl? (NamedDecl *)FunTmpl
7792 : Specialization->getInstantiatedFromMemberFunction(),
7793 D.getIdentifierLoc(),
7794 D.getCXXScopeSpec().isSet());
7795
7796 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7797 return (Decl*) nullptr;
7798}
7799
7800TypeResult
7801Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7802 const CXXScopeSpec &SS, IdentifierInfo *Name,
7803 SourceLocation TagLoc, SourceLocation NameLoc) {
7804 // This has to hold, because SS is expected to be defined.
7805 assert(Name && "Expected a name in a dependent tag");
7806
7807 NestedNameSpecifier *NNS = SS.getScopeRep();
7808 if (!NNS)
7809 return true;
7810
7811 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7812
7813 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7814 Diag(NameLoc, diag::err_dependent_tag_decl)
7815 << (TUK == TUK_Definition) << Kind << SS.getRange();
7816 return true;
7817 }
7818
7819 // Create the resulting type.
7820 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7821 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7822
7823 // Create type-source location information for this type.
7824 TypeLocBuilder TLB;
7825 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
7826 TL.setElaboratedKeywordLoc(TagLoc);
7827 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7828 TL.setNameLoc(NameLoc);
7829 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
7830}
7831
7832TypeResult
7833Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7834 const CXXScopeSpec &SS, const IdentifierInfo &II,
7835 SourceLocation IdLoc) {
7836 if (SS.isInvalid())
7837 return true;
7838
7839 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7840 Diag(TypenameLoc,
7841 getLangOpts().CPlusPlus11 ?
7842 diag::warn_cxx98_compat_typename_outside_of_template :
7843 diag::ext_typename_outside_of_template)
7844 << FixItHint::CreateRemoval(TypenameLoc);
7845
7846 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7847 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7848 TypenameLoc, QualifierLoc, II, IdLoc);
7849 if (T.isNull())
7850 return true;
7851
7852 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7853 if (isa<DependentNameType>(T)) {
7854 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
7855 TL.setElaboratedKeywordLoc(TypenameLoc);
7856 TL.setQualifierLoc(QualifierLoc);
7857 TL.setNameLoc(IdLoc);
7858 } else {
7859 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
7860 TL.setElaboratedKeywordLoc(TypenameLoc);
7861 TL.setQualifierLoc(QualifierLoc);
7862 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
7863 }
7864
7865 return CreateParsedType(T, TSI);
7866}
7867
7868TypeResult
7869Sema::ActOnTypenameType(Scope *S,
7870 SourceLocation TypenameLoc,
7871 const CXXScopeSpec &SS,
7872 SourceLocation TemplateKWLoc,
7873 TemplateTy TemplateIn,
7874 SourceLocation TemplateNameLoc,
7875 SourceLocation LAngleLoc,
7876 ASTTemplateArgsPtr TemplateArgsIn,
7877 SourceLocation RAngleLoc) {
7878 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7879 Diag(TypenameLoc,
7880 getLangOpts().CPlusPlus11 ?
7881 diag::warn_cxx98_compat_typename_outside_of_template :
7882 diag::ext_typename_outside_of_template)
7883 << FixItHint::CreateRemoval(TypenameLoc);
7884
7885 // Translate the parser's template argument list in our AST format.
7886 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7887 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7888
7889 TemplateName Template = TemplateIn.get();
7890 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7891 // Construct a dependent template specialization type.
7892 assert(DTN && "dependent template has non-dependent name?");
7893 assert(DTN->getQualifier() == SS.getScopeRep());
7894 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7895 DTN->getQualifier(),
7896 DTN->getIdentifier(),
7897 TemplateArgs);
7898
7899 // Create source-location information for this type.
7900 TypeLocBuilder Builder;
7901 DependentTemplateSpecializationTypeLoc SpecTL
7902 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7903 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7904 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7905 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7906 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7907 SpecTL.setLAngleLoc(LAngleLoc);
7908 SpecTL.setRAngleLoc(RAngleLoc);
7909 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7910 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7911 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7912 }
7913
7914 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7915 if (T.isNull())
7916 return true;
7917
7918 // Provide source-location information for the template specialization type.
7919 TypeLocBuilder Builder;
7920 TemplateSpecializationTypeLoc SpecTL
7921 = Builder.push<TemplateSpecializationTypeLoc>(T);
7922 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7923 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7924 SpecTL.setLAngleLoc(LAngleLoc);
7925 SpecTL.setRAngleLoc(RAngleLoc);
7926 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7927 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7928
7929 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7930 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
7931 TL.setElaboratedKeywordLoc(TypenameLoc);
7932 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7933
7934 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7935 return CreateParsedType(T, TSI);
7936}
7937
7938
7939/// Determine whether this failed name lookup should be treated as being
7940/// disabled by a usage of std::enable_if.
7941static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7942 SourceRange &CondRange) {
7943 // We must be looking for a ::type...
7944 if (!II.isStr("type"))
7945 return false;
7946
7947 // ... within an explicitly-written template specialization...
7948 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7949 return false;
7950 TypeLoc EnableIfTy = NNS.getTypeLoc();
7951 TemplateSpecializationTypeLoc EnableIfTSTLoc =
7952 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7953 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
7954 return false;
7955 const TemplateSpecializationType *EnableIfTST =
7956 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
7957
7958 // ... which names a complete class template declaration...
7959 const TemplateDecl *EnableIfDecl =
7960 EnableIfTST->getTemplateName().getAsTemplateDecl();
7961 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7962 return false;
7963
7964 // ... called "enable_if".
7965 const IdentifierInfo *EnableIfII =
7966 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7967 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7968 return false;
7969
7970 // Assume the first template argument is the condition.
7971 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
7972 return true;
7973}
7974
7975/// \brief Build the type that describes a C++ typename specifier,
7976/// e.g., "typename T::type".
7977QualType
7978Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7979 SourceLocation KeywordLoc,
7980 NestedNameSpecifierLoc QualifierLoc,
7981 const IdentifierInfo &II,
7982 SourceLocation IILoc) {
7983 CXXScopeSpec SS;
7984 SS.Adopt(QualifierLoc);
7985
7986 DeclContext *Ctx = computeDeclContext(SS);
7987 if (!Ctx) {
7988 // If the nested-name-specifier is dependent and couldn't be
7989 // resolved to a type, build a typename type.
7990 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7991 return Context.getDependentNameType(Keyword,
7992 QualifierLoc.getNestedNameSpecifier(),
7993 &II);
7994 }
7995
7996 // If the nested-name-specifier refers to the current instantiation,
7997 // the "typename" keyword itself is superfluous. In C++03, the
7998 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7999 // allows such extraneous "typename" keywords, and we retroactively
8000 // apply this DR to C++03 code with only a warning. In any case we continue.
8001
8002 if (RequireCompleteDeclContext(SS, Ctx))
8003 return QualType();
8004
8005 DeclarationName Name(&II);
8006 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8007 LookupQualifiedName(Result, Ctx, SS);
8008 unsigned DiagID = 0;
8009 Decl *Referenced = nullptr;
8010 switch (Result.getResultKind()) {
8011 case LookupResult::NotFound: {
8012 // If we're looking up 'type' within a template named 'enable_if', produce
8013 // a more specific diagnostic.
8014 SourceRange CondRange;
8015 if (isEnableIf(QualifierLoc, II, CondRange)) {
8016 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8017 << Ctx << CondRange;
8018 return QualType();
8019 }
8020
8021 DiagID = diag::err_typename_nested_not_found;
8022 break;
8023 }
8024
8025 case LookupResult::FoundUnresolvedValue: {
8026 // We found a using declaration that is a value. Most likely, the using
8027 // declaration itself is meant to have the 'typename' keyword.
8028 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8029 IILoc);
8030 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8031 << Name << Ctx << FullRange;
8032 if (UnresolvedUsingValueDecl *Using
8033 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8034 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8035 Diag(Loc, diag::note_using_value_decl_missing_typename)
8036 << FixItHint::CreateInsertion(Loc, "typename ");
8037 }
8038 }
8039 // Fall through to create a dependent typename type, from which we can recover
8040 // better.
8041
8042 case LookupResult::NotFoundInCurrentInstantiation:
8043 // Okay, it's a member of an unknown instantiation.
8044 return Context.getDependentNameType(Keyword,
8045 QualifierLoc.getNestedNameSpecifier(),
8046 &II);
8047
8048 case LookupResult::Found:
8049 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8050 // We found a type. Build an ElaboratedType, since the
8051 // typename-specifier was just sugar.
8052 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8053 return Context.getElaboratedType(ETK_Typename,
8054 QualifierLoc.getNestedNameSpecifier(),
8055 Context.getTypeDeclType(Type));
8056 }
8057
8058 DiagID = diag::err_typename_nested_not_type;
8059 Referenced = Result.getFoundDecl();
8060 break;
8061
8062 case LookupResult::FoundOverloaded:
8063 DiagID = diag::err_typename_nested_not_type;
8064 Referenced = *Result.begin();
8065 break;
8066
8067 case LookupResult::Ambiguous:
8068 return QualType();
8069 }
8070
8071 // If we get here, it's because name lookup did not find a
8072 // type. Emit an appropriate diagnostic and return an error.
8073 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8074 IILoc);
8075 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8076 if (Referenced)
8077 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8078 << Name;
8079 return QualType();
8080}
8081
8082namespace {
8083 // See Sema::RebuildTypeInCurrentInstantiation
8084 class CurrentInstantiationRebuilder
8085 : public TreeTransform<CurrentInstantiationRebuilder> {
8086 SourceLocation Loc;
8087 DeclarationName Entity;
8088
8089 public:
8090 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8091
8092 CurrentInstantiationRebuilder(Sema &SemaRef,
8093 SourceLocation Loc,
8094 DeclarationName Entity)
8095 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8096 Loc(Loc), Entity(Entity) { }
8097
8098 /// \brief Determine whether the given type \p T has already been
8099 /// transformed.
8100 ///
8101 /// For the purposes of type reconstruction, a type has already been
8102 /// transformed if it is NULL or if it is not dependent.
8103 bool AlreadyTransformed(QualType T) {
8104 return T.isNull() || !T->isDependentType();
8105 }
8106
8107 /// \brief Returns the location of the entity whose type is being
8108 /// rebuilt.
8109 SourceLocation getBaseLocation() { return Loc; }
8110
8111 /// \brief Returns the name of the entity whose type is being rebuilt.
8112 DeclarationName getBaseEntity() { return Entity; }
8113
8114 /// \brief Sets the "base" location and entity when that
8115 /// information is known based on another transformation.
8116 void setBase(SourceLocation Loc, DeclarationName Entity) {
8117 this->Loc = Loc;
8118 this->Entity = Entity;
8119 }
8120
8121 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8122 // Lambdas never need to be transformed.
8123 return E;
8124 }
8125 };
8126}
8127
8128/// \brief Rebuilds a type within the context of the current instantiation.
8129///
8130/// The type \p T is part of the type of an out-of-line member definition of
8131/// a class template (or class template partial specialization) that was parsed
8132/// and constructed before we entered the scope of the class template (or
8133/// partial specialization thereof). This routine will rebuild that type now
8134/// that we have entered the declarator's scope, which may produce different
8135/// canonical types, e.g.,
8136///
8137/// \code
8138/// template<typename T>
8139/// struct X {
8140/// typedef T* pointer;
8141/// pointer data();
8142/// };
8143///
8144/// template<typename T>
8145/// typename X<T>::pointer X<T>::data() { ... }
8146/// \endcode
8147///
8148/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8149/// since we do not know that we can look into X<T> when we parsed the type.
8150/// This function will rebuild the type, performing the lookup of "pointer"
8151/// in X<T> and returning an ElaboratedType whose canonical type is the same
8152/// as the canonical type of T*, allowing the return types of the out-of-line
8153/// definition and the declaration to match.
8154TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8155 SourceLocation Loc,
8156 DeclarationName Name) {
8157 if (!T || !T->getType()->isDependentType())
8158 return T;
8159
8160 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8161 return Rebuilder.TransformType(T);
8162}
8163
8164ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8165 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8166 DeclarationName());
8167 return Rebuilder.TransformExpr(E);
8168}
8169
8170bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8171 if (SS.isInvalid())
8172 return true;
8173
8174 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8175 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8176 DeclarationName());
8177 NestedNameSpecifierLoc Rebuilt
8178 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8179 if (!Rebuilt)
8180 return true;
8181
8182 SS.Adopt(Rebuilt);
8183 return false;
8184}
8185
8186/// \brief Rebuild the template parameters now that we know we're in a current
8187/// instantiation.
8188bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8189 TemplateParameterList *Params) {
8190 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8191 Decl *Param = Params->getParam(I);
8192
8193 // There is nothing to rebuild in a type parameter.
8194 if (isa<TemplateTypeParmDecl>(Param))
8195 continue;
8196
8197 // Rebuild the template parameter list of a template template parameter.
8198 if (TemplateTemplateParmDecl *TTP
8199 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8200 if (RebuildTemplateParamsInCurrentInstantiation(
8201 TTP->getTemplateParameters()))
8202 return true;
8203
8204 continue;
8205 }
8206
8207 // Rebuild the type of a non-type template parameter.
8208 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8209 TypeSourceInfo *NewTSI
8210 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8211 NTTP->getLocation(),
8212 NTTP->getDeclName());
8213 if (!NewTSI)
8214 return true;
8215
8216 if (NewTSI != NTTP->getTypeSourceInfo()) {
8217 NTTP->setTypeSourceInfo(NewTSI);
8218 NTTP->setType(NewTSI->getType());
8219 }
8220 }
8221
8222 return false;
8223}
8224
8225/// \brief Produces a formatted string that describes the binding of
8226/// template parameters to template arguments.
8227std::string
8228Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8229 const TemplateArgumentList &Args) {
8230 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8231}
8232
8233std::string
8234Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8235 const TemplateArgument *Args,
8236 unsigned NumArgs) {
8237 SmallString<128> Str;
8238 llvm::raw_svector_ostream Out(Str);
8239
8240 if (!Params || Params->size() == 0 || NumArgs == 0)
8241 return std::string();
8242
8243 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8244 if (I >= NumArgs)
8245 break;
8246
8247 if (I == 0)
8248 Out << "[with ";
8249 else
8250 Out << ", ";
8251
8252 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8253 Out << Id->getName();
8254 } else {
8255 Out << '$' << I;
8256 }
8257
8258 Out << " = ";
8259 Args[I].print(getPrintingPolicy(), Out);
8260 }
8261
8262 Out << ']';
8263 return Out.str();
8264}
8265
8266void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8267 CachedTokens &Toks) {
8268 if (!FD)
8269 return;
8270
8271 LateParsedTemplate *LPT = new LateParsedTemplate;
8272
8273 // Take tokens to avoid allocations
8274 LPT->Toks.swap(Toks);
8275 LPT->D = FnD;
8276 LateParsedTemplateMap[FD] = LPT;
8277
8278 FD->setLateTemplateParsed(true);
8279}
8280
8281void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8282 if (!FD)
8283 return;
8284 FD->setLateTemplateParsed(false);
8285}
8286
8287bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8288 DeclContext *DC = CurContext;
8289
8290 while (DC) {
8291 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8292 const FunctionDecl *FD = RD->isLocalClass();
8293 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8294 } else if (DC->isTranslationUnit() || DC->isNamespace())
8295 return false;
8296
8297 DC = DC->getParent();
8298 }
8299 return false;
8300}
3890 return false;
3891}
3892
3893namespace {
3894 class UnnamedLocalNoLinkageFinder
3895 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3896 {
3897 Sema &S;
3898 SourceRange SR;
3899
3900 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3901
3902 public:
3903 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3904
3905 bool Visit(QualType T) {
3906 return inherited::Visit(T.getTypePtr());
3907 }
3908
3909#define TYPE(Class, Parent) \
3910 bool Visit##Class##Type(const Class##Type *);
3911#define ABSTRACT_TYPE(Class, Parent) \
3912 bool Visit##Class##Type(const Class##Type *) { return false; }
3913#define NON_CANONICAL_TYPE(Class, Parent) \
3914 bool Visit##Class##Type(const Class##Type *) { return false; }
3915#include "clang/AST/TypeNodes.def"
3916
3917 bool VisitTagDecl(const TagDecl *Tag);
3918 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3919 };
3920}
3921
3922bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3923 return false;
3924}
3925
3926bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3927 return Visit(T->getElementType());
3928}
3929
3930bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3931 return Visit(T->getPointeeType());
3932}
3933
3934bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3935 const BlockPointerType* T) {
3936 return Visit(T->getPointeeType());
3937}
3938
3939bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3940 const LValueReferenceType* T) {
3941 return Visit(T->getPointeeType());
3942}
3943
3944bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3945 const RValueReferenceType* T) {
3946 return Visit(T->getPointeeType());
3947}
3948
3949bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3950 const MemberPointerType* T) {
3951 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3952}
3953
3954bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3955 const ConstantArrayType* T) {
3956 return Visit(T->getElementType());
3957}
3958
3959bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3960 const IncompleteArrayType* T) {
3961 return Visit(T->getElementType());
3962}
3963
3964bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3965 const VariableArrayType* T) {
3966 return Visit(T->getElementType());
3967}
3968
3969bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3970 const DependentSizedArrayType* T) {
3971 return Visit(T->getElementType());
3972}
3973
3974bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3975 const DependentSizedExtVectorType* T) {
3976 return Visit(T->getElementType());
3977}
3978
3979bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3980 return Visit(T->getElementType());
3981}
3982
3983bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3984 return Visit(T->getElementType());
3985}
3986
3987bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3988 const FunctionProtoType* T) {
3989 for (const auto &A : T->param_types()) {
3990 if (Visit(A))
3991 return true;
3992 }
3993
3994 return Visit(T->getReturnType());
3995}
3996
3997bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3998 const FunctionNoProtoType* T) {
3999 return Visit(T->getReturnType());
4000}
4001
4002bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4003 const UnresolvedUsingType*) {
4004 return false;
4005}
4006
4007bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4008 return false;
4009}
4010
4011bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4012 return Visit(T->getUnderlyingType());
4013}
4014
4015bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4016 return false;
4017}
4018
4019bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4020 const UnaryTransformType*) {
4021 return false;
4022}
4023
4024bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4025 return Visit(T->getDeducedType());
4026}
4027
4028bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4029 return VisitTagDecl(T->getDecl());
4030}
4031
4032bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4033 return VisitTagDecl(T->getDecl());
4034}
4035
4036bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4037 const TemplateTypeParmType*) {
4038 return false;
4039}
4040
4041bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4042 const SubstTemplateTypeParmPackType *) {
4043 return false;
4044}
4045
4046bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4047 const TemplateSpecializationType*) {
4048 return false;
4049}
4050
4051bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4052 const InjectedClassNameType* T) {
4053 return VisitTagDecl(T->getDecl());
4054}
4055
4056bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4057 const DependentNameType* T) {
4058 return VisitNestedNameSpecifier(T->getQualifier());
4059}
4060
4061bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4062 const DependentTemplateSpecializationType* T) {
4063 return VisitNestedNameSpecifier(T->getQualifier());
4064}
4065
4066bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4067 const PackExpansionType* T) {
4068 return Visit(T->getPattern());
4069}
4070
4071bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4072 return false;
4073}
4074
4075bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4076 const ObjCInterfaceType *) {
4077 return false;
4078}
4079
4080bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4081 const ObjCObjectPointerType *) {
4082 return false;
4083}
4084
4085bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4086 return Visit(T->getValueType());
4087}
4088
4089bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4090 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4091 S.Diag(SR.getBegin(),
4092 S.getLangOpts().CPlusPlus11 ?
4093 diag::warn_cxx98_compat_template_arg_local_type :
4094 diag::ext_template_arg_local_type)
4095 << S.Context.getTypeDeclType(Tag) << SR;
4096 return true;
4097 }
4098
4099 if (!Tag->hasNameForLinkage()) {
4100 S.Diag(SR.getBegin(),
4101 S.getLangOpts().CPlusPlus11 ?
4102 diag::warn_cxx98_compat_template_arg_unnamed_type :
4103 diag::ext_template_arg_unnamed_type) << SR;
4104 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4105 return true;
4106 }
4107
4108 return false;
4109}
4110
4111bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4112 NestedNameSpecifier *NNS) {
4113 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4114 return true;
4115
4116 switch (NNS->getKind()) {
4117 case NestedNameSpecifier::Identifier:
4118 case NestedNameSpecifier::Namespace:
4119 case NestedNameSpecifier::NamespaceAlias:
4120 case NestedNameSpecifier::Global:
4121 case NestedNameSpecifier::Super:
4122 return false;
4123
4124 case NestedNameSpecifier::TypeSpec:
4125 case NestedNameSpecifier::TypeSpecWithTemplate:
4126 return Visit(QualType(NNS->getAsType(), 0));
4127 }
4128 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4129}
4130
4131
4132/// \brief Check a template argument against its corresponding
4133/// template type parameter.
4134///
4135/// This routine implements the semantics of C++ [temp.arg.type]. It
4136/// returns true if an error occurred, and false otherwise.
4137bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4138 TypeSourceInfo *ArgInfo) {
4139 assert(ArgInfo && "invalid TypeSourceInfo");
4140 QualType Arg = ArgInfo->getType();
4141 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4142
4143 if (Arg->isVariablyModifiedType()) {
4144 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4145 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4146 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4147 }
4148
4149 // C++03 [temp.arg.type]p2:
4150 // A local type, a type with no linkage, an unnamed type or a type
4151 // compounded from any of these types shall not be used as a
4152 // template-argument for a template type-parameter.
4153 //
4154 // C++11 allows these, and even in C++03 we allow them as an extension with
4155 // a warning.
4156 bool NeedsCheck;
4157 if (LangOpts.CPlusPlus11)
4158 NeedsCheck =
4159 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4160 SR.getBegin()) ||
4161 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4162 SR.getBegin());
4163 else
4164 NeedsCheck = Arg->hasUnnamedOrLocalType();
4165
4166 if (NeedsCheck) {
4167 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4168 (void)Finder.Visit(Context.getCanonicalType(Arg));
4169 }
4170
4171 return false;
4172}
4173
4174enum NullPointerValueKind {
4175 NPV_NotNullPointer,
4176 NPV_NullPointer,
4177 NPV_Error
4178};
4179
4180/// \brief Determine whether the given template argument is a null pointer
4181/// value of the appropriate type.
4182static NullPointerValueKind
4183isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4184 QualType ParamType, Expr *Arg) {
4185 if (Arg->isValueDependent() || Arg->isTypeDependent())
4186 return NPV_NotNullPointer;
4187
4188 if (!S.getLangOpts().CPlusPlus11)
4189 return NPV_NotNullPointer;
4190
4191 // Determine whether we have a constant expression.
4192 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4193 if (ArgRV.isInvalid())
4194 return NPV_Error;
4195 Arg = ArgRV.get();
4196
4197 Expr::EvalResult EvalResult;
4198 SmallVector<PartialDiagnosticAt, 8> Notes;
4199 EvalResult.Diag = &Notes;
4200 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4201 EvalResult.HasSideEffects) {
4202 SourceLocation DiagLoc = Arg->getExprLoc();
4203
4204 // If our only note is the usual "invalid subexpression" note, just point
4205 // the caret at its location rather than producing an essentially
4206 // redundant note.
4207 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4208 diag::note_invalid_subexpr_in_const_expr) {
4209 DiagLoc = Notes[0].first;
4210 Notes.clear();
4211 }
4212
4213 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4214 << Arg->getType() << Arg->getSourceRange();
4215 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4216 S.Diag(Notes[I].first, Notes[I].second);
4217
4218 S.Diag(Param->getLocation(), diag::note_template_param_here);
4219 return NPV_Error;
4220 }
4221
4222 // C++11 [temp.arg.nontype]p1:
4223 // - an address constant expression of type std::nullptr_t
4224 if (Arg->getType()->isNullPtrType())
4225 return NPV_NullPointer;
4226
4227 // - a constant expression that evaluates to a null pointer value (4.10); or
4228 // - a constant expression that evaluates to a null member pointer value
4229 // (4.11); or
4230 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4231 (EvalResult.Val.isMemberPointer() &&
4232 !EvalResult.Val.getMemberPointerDecl())) {
4233 // If our expression has an appropriate type, we've succeeded.
4234 bool ObjCLifetimeConversion;
4235 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4236 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4237 ObjCLifetimeConversion))
4238 return NPV_NullPointer;
4239
4240 // The types didn't match, but we know we got a null pointer; complain,
4241 // then recover as if the types were correct.
4242 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4243 << Arg->getType() << ParamType << Arg->getSourceRange();
4244 S.Diag(Param->getLocation(), diag::note_template_param_here);
4245 return NPV_NullPointer;
4246 }
4247
4248 // If we don't have a null pointer value, but we do have a NULL pointer
4249 // constant, suggest a cast to the appropriate type.
4250 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4251 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4252 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4253 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4254 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4255 ")");
4256 S.Diag(Param->getLocation(), diag::note_template_param_here);
4257 return NPV_NullPointer;
4258 }
4259
4260 // FIXME: If we ever want to support general, address-constant expressions
4261 // as non-type template arguments, we should return the ExprResult here to
4262 // be interpreted by the caller.
4263 return NPV_NotNullPointer;
4264}
4265
4266/// \brief Checks whether the given template argument is compatible with its
4267/// template parameter.
4268static bool CheckTemplateArgumentIsCompatibleWithParameter(
4269 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4270 Expr *Arg, QualType ArgType) {
4271 bool ObjCLifetimeConversion;
4272 if (ParamType->isPointerType() &&
4273 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4274 S.IsQualificationConversion(ArgType, ParamType, false,
4275 ObjCLifetimeConversion)) {
4276 // For pointer-to-object types, qualification conversions are
4277 // permitted.
4278 } else {
4279 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4280 if (!ParamRef->getPointeeType()->isFunctionType()) {
4281 // C++ [temp.arg.nontype]p5b3:
4282 // For a non-type template-parameter of type reference to
4283 // object, no conversions apply. The type referred to by the
4284 // reference may be more cv-qualified than the (otherwise
4285 // identical) type of the template- argument. The
4286 // template-parameter is bound directly to the
4287 // template-argument, which shall be an lvalue.
4288
4289 // FIXME: Other qualifiers?
4290 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4291 unsigned ArgQuals = ArgType.getCVRQualifiers();
4292
4293 if ((ParamQuals | ArgQuals) != ParamQuals) {
4294 S.Diag(Arg->getLocStart(),
4295 diag::err_template_arg_ref_bind_ignores_quals)
4296 << ParamType << Arg->getType() << Arg->getSourceRange();
4297 S.Diag(Param->getLocation(), diag::note_template_param_here);
4298 return true;
4299 }
4300 }
4301 }
4302
4303 // At this point, the template argument refers to an object or
4304 // function with external linkage. We now need to check whether the
4305 // argument and parameter types are compatible.
4306 if (!S.Context.hasSameUnqualifiedType(ArgType,
4307 ParamType.getNonReferenceType())) {
4308 // We can't perform this conversion or binding.
4309 if (ParamType->isReferenceType())
4310 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4311 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4312 else
4313 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4314 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4315 S.Diag(Param->getLocation(), diag::note_template_param_here);
4316 return true;
4317 }
4318 }
4319
4320 return false;
4321}
4322
4323/// \brief Checks whether the given template argument is the address
4324/// of an object or function according to C++ [temp.arg.nontype]p1.
4325static bool
4326CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4327 NonTypeTemplateParmDecl *Param,
4328 QualType ParamType,
4329 Expr *ArgIn,
4330 TemplateArgument &Converted) {
4331 bool Invalid = false;
4332 Expr *Arg = ArgIn;
4333 QualType ArgType = Arg->getType();
4334
4335 bool AddressTaken = false;
4336 SourceLocation AddrOpLoc;
4337 if (S.getLangOpts().MicrosoftExt) {
4338 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4339 // dereference and address-of operators.
4340 Arg = Arg->IgnoreParenCasts();
4341
4342 bool ExtWarnMSTemplateArg = false;
4343 UnaryOperatorKind FirstOpKind;
4344 SourceLocation FirstOpLoc;
4345 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4346 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4347 if (UnOpKind == UO_Deref)
4348 ExtWarnMSTemplateArg = true;
4349 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4350 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4351 if (!AddrOpLoc.isValid()) {
4352 FirstOpKind = UnOpKind;
4353 FirstOpLoc = UnOp->getOperatorLoc();
4354 }
4355 } else
4356 break;
4357 }
4358 if (FirstOpLoc.isValid()) {
4359 if (ExtWarnMSTemplateArg)
4360 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4361 << ArgIn->getSourceRange();
4362
4363 if (FirstOpKind == UO_AddrOf)
4364 AddressTaken = true;
4365 else if (Arg->getType()->isPointerType()) {
4366 // We cannot let pointers get dereferenced here, that is obviously not a
4367 // constant expression.
4368 assert(FirstOpKind == UO_Deref);
4369 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4370 << Arg->getSourceRange();
4371 }
4372 }
4373 } else {
4374 // See through any implicit casts we added to fix the type.
4375 Arg = Arg->IgnoreImpCasts();
4376
4377 // C++ [temp.arg.nontype]p1:
4378 //
4379 // A template-argument for a non-type, non-template
4380 // template-parameter shall be one of: [...]
4381 //
4382 // -- the address of an object or function with external
4383 // linkage, including function templates and function
4384 // template-ids but excluding non-static class members,
4385 // expressed as & id-expression where the & is optional if
4386 // the name refers to a function or array, or if the
4387 // corresponding template-parameter is a reference; or
4388
4389 // In C++98/03 mode, give an extension warning on any extra parentheses.
4390 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4391 bool ExtraParens = false;
4392 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4393 if (!Invalid && !ExtraParens) {
4394 S.Diag(Arg->getLocStart(),
4395 S.getLangOpts().CPlusPlus11
4396 ? diag::warn_cxx98_compat_template_arg_extra_parens
4397 : diag::ext_template_arg_extra_parens)
4398 << Arg->getSourceRange();
4399 ExtraParens = true;
4400 }
4401
4402 Arg = Parens->getSubExpr();
4403 }
4404
4405 while (SubstNonTypeTemplateParmExpr *subst =
4406 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4407 Arg = subst->getReplacement()->IgnoreImpCasts();
4408
4409 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4410 if (UnOp->getOpcode() == UO_AddrOf) {
4411 Arg = UnOp->getSubExpr();
4412 AddressTaken = true;
4413 AddrOpLoc = UnOp->getOperatorLoc();
4414 }
4415 }
4416
4417 while (SubstNonTypeTemplateParmExpr *subst =
4418 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4419 Arg = subst->getReplacement()->IgnoreImpCasts();
4420 }
4421
4422 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4423 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4424
4425 // If our parameter has pointer type, check for a null template value.
4426 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4427 NullPointerValueKind NPV;
4428 // dllimport'd entities aren't constant but are available inside of template
4429 // arguments.
4430 if (Entity && Entity->hasAttr<DLLImportAttr>())
4431 NPV = NPV_NotNullPointer;
4432 else
4433 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4434 switch (NPV) {
4435 case NPV_NullPointer:
4436 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4437 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4438 /*isNullPtr=*/true);
4439 return false;
4440
4441 case NPV_Error:
4442 return true;
4443
4444 case NPV_NotNullPointer:
4445 break;
4446 }
4447 }
4448
4449 // Stop checking the precise nature of the argument if it is value dependent,
4450 // it should be checked when instantiated.
4451 if (Arg->isValueDependent()) {
4452 Converted = TemplateArgument(ArgIn);
4453 return false;
4454 }
4455
4456 if (isa<CXXUuidofExpr>(Arg)) {
4457 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4458 ArgIn, Arg, ArgType))
4459 return true;
4460
4461 Converted = TemplateArgument(ArgIn);
4462 return false;
4463 }
4464
4465 if (!DRE) {
4466 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4467 << Arg->getSourceRange();
4468 S.Diag(Param->getLocation(), diag::note_template_param_here);
4469 return true;
4470 }
4471
4472 // Cannot refer to non-static data members
4473 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4474 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4475 << Entity << Arg->getSourceRange();
4476 S.Diag(Param->getLocation(), diag::note_template_param_here);
4477 return true;
4478 }
4479
4480 // Cannot refer to non-static member functions
4481 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4482 if (!Method->isStatic()) {
4483 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4484 << Method << Arg->getSourceRange();
4485 S.Diag(Param->getLocation(), diag::note_template_param_here);
4486 return true;
4487 }
4488 }
4489
4490 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4491 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4492
4493 // A non-type template argument must refer to an object or function.
4494 if (!Func && !Var) {
4495 // We found something, but we don't know specifically what it is.
4496 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4497 << Arg->getSourceRange();
4498 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4499 return true;
4500 }
4501
4502 // Address / reference template args must have external linkage in C++98.
4503 if (Entity->getFormalLinkage() == InternalLinkage) {
4504 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4505 diag::warn_cxx98_compat_template_arg_object_internal :
4506 diag::ext_template_arg_object_internal)
4507 << !Func << Entity << Arg->getSourceRange();
4508 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4509 << !Func;
4510 } else if (!Entity->hasLinkage()) {
4511 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4512 << !Func << Entity << Arg->getSourceRange();
4513 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4514 << !Func;
4515 return true;
4516 }
4517
4518 if (Func) {
4519 // If the template parameter has pointer type, the function decays.
4520 if (ParamType->isPointerType() && !AddressTaken)
4521 ArgType = S.Context.getPointerType(Func->getType());
4522 else if (AddressTaken && ParamType->isReferenceType()) {
4523 // If we originally had an address-of operator, but the
4524 // parameter has reference type, complain and (if things look
4525 // like they will work) drop the address-of operator.
4526 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4527 ParamType.getNonReferenceType())) {
4528 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4529 << ParamType;
4530 S.Diag(Param->getLocation(), diag::note_template_param_here);
4531 return true;
4532 }
4533
4534 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4535 << ParamType
4536 << FixItHint::CreateRemoval(AddrOpLoc);
4537 S.Diag(Param->getLocation(), diag::note_template_param_here);
4538
4539 ArgType = Func->getType();
4540 }
4541 } else {
4542 // A value of reference type is not an object.
4543 if (Var->getType()->isReferenceType()) {
4544 S.Diag(Arg->getLocStart(),
4545 diag::err_template_arg_reference_var)
4546 << Var->getType() << Arg->getSourceRange();
4547 S.Diag(Param->getLocation(), diag::note_template_param_here);
4548 return true;
4549 }
4550
4551 // A template argument must have static storage duration.
4552 if (Var->getTLSKind()) {
4553 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4554 << Arg->getSourceRange();
4555 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4556 return true;
4557 }
4558
4559 // If the template parameter has pointer type, we must have taken
4560 // the address of this object.
4561 if (ParamType->isReferenceType()) {
4562 if (AddressTaken) {
4563 // If we originally had an address-of operator, but the
4564 // parameter has reference type, complain and (if things look
4565 // like they will work) drop the address-of operator.
4566 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4567 ParamType.getNonReferenceType())) {
4568 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4569 << ParamType;
4570 S.Diag(Param->getLocation(), diag::note_template_param_here);
4571 return true;
4572 }
4573
4574 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4575 << ParamType
4576 << FixItHint::CreateRemoval(AddrOpLoc);
4577 S.Diag(Param->getLocation(), diag::note_template_param_here);
4578
4579 ArgType = Var->getType();
4580 }
4581 } else if (!AddressTaken && ParamType->isPointerType()) {
4582 if (Var->getType()->isArrayType()) {
4583 // Array-to-pointer decay.
4584 ArgType = S.Context.getArrayDecayedType(Var->getType());
4585 } else {
4586 // If the template parameter has pointer type but the address of
4587 // this object was not taken, complain and (possibly) recover by
4588 // taking the address of the entity.
4589 ArgType = S.Context.getPointerType(Var->getType());
4590 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4591 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4592 << ParamType;
4593 S.Diag(Param->getLocation(), diag::note_template_param_here);
4594 return true;
4595 }
4596
4597 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4598 << ParamType
4599 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4600
4601 S.Diag(Param->getLocation(), diag::note_template_param_here);
4602 }
4603 }
4604 }
4605
4606 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4607 Arg, ArgType))
4608 return true;
4609
4610 // Create the template argument.
4611 Converted =
4612 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4613 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4614 return false;
4615}
4616
4617/// \brief Checks whether the given template argument is a pointer to
4618/// member constant according to C++ [temp.arg.nontype]p1.
4619static bool CheckTemplateArgumentPointerToMember(Sema &S,
4620 NonTypeTemplateParmDecl *Param,
4621 QualType ParamType,
4622 Expr *&ResultArg,
4623 TemplateArgument &Converted) {
4624 bool Invalid = false;
4625
4626 // Check for a null pointer value.
4627 Expr *Arg = ResultArg;
4628 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4629 case NPV_Error:
4630 return true;
4631 case NPV_NullPointer:
4632 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4633 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4634 /*isNullPtr*/true);
4635 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4636 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
4637 return false;
4638 case NPV_NotNullPointer:
4639 break;
4640 }
4641
4642 bool ObjCLifetimeConversion;
4643 if (S.IsQualificationConversion(Arg->getType(),
4644 ParamType.getNonReferenceType(),
4645 false, ObjCLifetimeConversion)) {
4646 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4647 Arg->getValueKind()).get();
4648 ResultArg = Arg;
4649 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4650 ParamType.getNonReferenceType())) {
4651 // We can't perform this conversion.
4652 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4653 << Arg->getType() << ParamType << Arg->getSourceRange();
4654 S.Diag(Param->getLocation(), diag::note_template_param_here);
4655 return true;
4656 }
4657
4658 // See through any implicit casts we added to fix the type.
4659 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4660 Arg = Cast->getSubExpr();
4661
4662 // C++ [temp.arg.nontype]p1:
4663 //
4664 // A template-argument for a non-type, non-template
4665 // template-parameter shall be one of: [...]
4666 //
4667 // -- a pointer to member expressed as described in 5.3.1.
4668 DeclRefExpr *DRE = nullptr;
4669
4670 // In C++98/03 mode, give an extension warning on any extra parentheses.
4671 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4672 bool ExtraParens = false;
4673 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4674 if (!Invalid && !ExtraParens) {
4675 S.Diag(Arg->getLocStart(),
4676 S.getLangOpts().CPlusPlus11 ?
4677 diag::warn_cxx98_compat_template_arg_extra_parens :
4678 diag::ext_template_arg_extra_parens)
4679 << Arg->getSourceRange();
4680 ExtraParens = true;
4681 }
4682
4683 Arg = Parens->getSubExpr();
4684 }
4685
4686 while (SubstNonTypeTemplateParmExpr *subst =
4687 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4688 Arg = subst->getReplacement()->IgnoreImpCasts();
4689
4690 // A pointer-to-member constant written &Class::member.
4691 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4692 if (UnOp->getOpcode() == UO_AddrOf) {
4693 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4694 if (DRE && !DRE->getQualifier())
4695 DRE = nullptr;
4696 }
4697 }
4698 // A constant of pointer-to-member type.
4699 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4700 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4701 if (VD->getType()->isMemberPointerType()) {
4702 if (isa<NonTypeTemplateParmDecl>(VD)) {
4703 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4704 Converted = TemplateArgument(Arg);
4705 } else {
4706 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4707 Converted = TemplateArgument(VD, ParamType);
4708 }
4709 return Invalid;
4710 }
4711 }
4712 }
4713
4714 DRE = nullptr;
4715 }
4716
4717 if (!DRE)
4718 return S.Diag(Arg->getLocStart(),
4719 diag::err_template_arg_not_pointer_to_member_form)
4720 << Arg->getSourceRange();
4721
4722 if (isa<FieldDecl>(DRE->getDecl()) ||
4723 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4724 isa<CXXMethodDecl>(DRE->getDecl())) {
4725 assert((isa<FieldDecl>(DRE->getDecl()) ||
4726 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4727 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4728 "Only non-static member pointers can make it here");
4729
4730 // Okay: this is the address of a non-static member, and therefore
4731 // a member pointer constant.
4732 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4733 Converted = TemplateArgument(Arg);
4734 } else {
4735 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4736 Converted = TemplateArgument(D, ParamType);
4737 }
4738 return Invalid;
4739 }
4740
4741 // We found something else, but we don't know specifically what it is.
4742 S.Diag(Arg->getLocStart(),
4743 diag::err_template_arg_not_pointer_to_member_form)
4744 << Arg->getSourceRange();
4745 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4746 return true;
4747}
4748
4749/// \brief Check a template argument against its corresponding
4750/// non-type template parameter.
4751///
4752/// This routine implements the semantics of C++ [temp.arg.nontype].
4753/// If an error occurred, it returns ExprError(); otherwise, it
4754/// returns the converted template argument. \p ParamType is the
4755/// type of the non-type template parameter after it has been instantiated.
4756ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4757 QualType ParamType, Expr *Arg,
4758 TemplateArgument &Converted,
4759 CheckTemplateArgumentKind CTAK) {
4760 SourceLocation StartLoc = Arg->getLocStart();
4761
4762 // If either the parameter has a dependent type or the argument is
4763 // type-dependent, there's nothing we can check now.
4764 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4765 // FIXME: Produce a cloned, canonical expression?
4766 Converted = TemplateArgument(Arg);
4767 return Arg;
4768 }
4769
4770 // We should have already dropped all cv-qualifiers by now.
4771 assert(!ParamType.hasQualifiers() &&
4772 "non-type template parameter type cannot be qualified");
4773
4774 if (CTAK == CTAK_Deduced &&
4775 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4776 // C++ [temp.deduct.type]p17:
4777 // If, in the declaration of a function template with a non-type
4778 // template-parameter, the non-type template-parameter is used
4779 // in an expression in the function parameter-list and, if the
4780 // corresponding template-argument is deduced, the
4781 // template-argument type shall match the type of the
4782 // template-parameter exactly, except that a template-argument
4783 // deduced from an array bound may be of any integral type.
4784 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4785 << Arg->getType().getUnqualifiedType()
4786 << ParamType.getUnqualifiedType();
4787 Diag(Param->getLocation(), diag::note_template_param_here);
4788 return ExprError();
4789 }
4790
4791 if (getLangOpts().CPlusPlus1z) {
4792 // FIXME: We can do some limited checking for a value-dependent but not
4793 // type-dependent argument.
4794 if (Arg->isValueDependent()) {
4795 Converted = TemplateArgument(Arg);
4796 return Arg;
4797 }
4798
4799 // C++1z [temp.arg.nontype]p1:
4800 // A template-argument for a non-type template parameter shall be
4801 // a converted constant expression of the type of the template-parameter.
4802 APValue Value;
4803 ExprResult ArgResult = CheckConvertedConstantExpression(
4804 Arg, ParamType, Value, CCEK_TemplateArg);
4805 if (ArgResult.isInvalid())
4806 return ExprError();
4807
4808 QualType CanonParamType = Context.getCanonicalType(ParamType);
4809
4810 // Convert the APValue to a TemplateArgument.
4811 switch (Value.getKind()) {
4812 case APValue::Uninitialized:
4813 assert(ParamType->isNullPtrType());
4814 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4815 break;
4816 case APValue::Int:
4817 assert(ParamType->isIntegralOrEnumerationType());
4818 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4819 break;
4820 case APValue::MemberPointer: {
4821 assert(ParamType->isMemberPointerType());
4822
4823 // FIXME: We need TemplateArgument representation and mangling for these.
4824 if (!Value.getMemberPointerPath().empty()) {
4825 Diag(Arg->getLocStart(),
4826 diag::err_template_arg_member_ptr_base_derived_not_supported)
4827 << Value.getMemberPointerDecl() << ParamType
4828 << Arg->getSourceRange();
4829 return ExprError();
4830 }
4831
4832 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4833 Converted = VD ? TemplateArgument(VD, CanonParamType)
4834 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4835 break;
4836 }
4837 case APValue::LValue: {
4838 // For a non-type template-parameter of pointer or reference type,
4839 // the value of the constant expression shall not refer to
4840 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4841 ParamType->isNullPtrType());
4842 // -- a temporary object
4843 // -- a string literal
4844 // -- the result of a typeid expression, or
4845 // -- a predefind __func__ variable
4846 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4847 if (isa<CXXUuidofExpr>(E)) {
4848 Converted = TemplateArgument(const_cast<Expr*>(E));
4849 break;
4850 }
4851 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4852 << Arg->getSourceRange();
4853 return ExprError();
4854 }
4855 auto *VD = const_cast<ValueDecl *>(
4856 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4857 // -- a subobject
4858 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4859 VD && VD->getType()->isArrayType() &&
4860 Value.getLValuePath()[0].ArrayIndex == 0 &&
4861 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4862 // Per defect report (no number yet):
4863 // ... other than a pointer to the first element of a complete array
4864 // object.
4865 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4866 Value.isLValueOnePastTheEnd()) {
4867 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4868 << Value.getAsString(Context, ParamType);
4869 return ExprError();
4870 }
4871 assert((VD || !ParamType->isReferenceType()) &&
4872 "null reference should not be a constant expression");
4873 assert((!VD || !ParamType->isNullPtrType()) &&
4874 "non-null value of type nullptr_t?");
4875 Converted = VD ? TemplateArgument(VD, CanonParamType)
4876 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4877 break;
4878 }
4879 case APValue::AddrLabelDiff:
4880 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4881 case APValue::Float:
4882 case APValue::ComplexInt:
4883 case APValue::ComplexFloat:
4884 case APValue::Vector:
4885 case APValue::Array:
4886 case APValue::Struct:
4887 case APValue::Union:
4888 llvm_unreachable("invalid kind for template argument");
4889 }
4890
4891 return ArgResult.get();
4892 }
4893
4894 // C++ [temp.arg.nontype]p5:
4895 // The following conversions are performed on each expression used
4896 // as a non-type template-argument. If a non-type
4897 // template-argument cannot be converted to the type of the
4898 // corresponding template-parameter then the program is
4899 // ill-formed.
4900 if (ParamType->isIntegralOrEnumerationType()) {
4901 // C++11:
4902 // -- for a non-type template-parameter of integral or
4903 // enumeration type, conversions permitted in a converted
4904 // constant expression are applied.
4905 //
4906 // C++98:
4907 // -- for a non-type template-parameter of integral or
4908 // enumeration type, integral promotions (4.5) and integral
4909 // conversions (4.7) are applied.
4910
4911 if (getLangOpts().CPlusPlus11) {
4912 // We can't check arbitrary value-dependent arguments.
4913 // FIXME: If there's no viable conversion to the template parameter type,
4914 // we should be able to diagnose that prior to instantiation.
4915 if (Arg->isValueDependent()) {
4916 Converted = TemplateArgument(Arg);
4917 return Arg;
4918 }
4919
4920 // C++ [temp.arg.nontype]p1:
4921 // A template-argument for a non-type, non-template template-parameter
4922 // shall be one of:
4923 //
4924 // -- for a non-type template-parameter of integral or enumeration
4925 // type, a converted constant expression of the type of the
4926 // template-parameter; or
4927 llvm::APSInt Value;
4928 ExprResult ArgResult =
4929 CheckConvertedConstantExpression(Arg, ParamType, Value,
4930 CCEK_TemplateArg);
4931 if (ArgResult.isInvalid())
4932 return ExprError();
4933
4934 // Widen the argument value to sizeof(parameter type). This is almost
4935 // always a no-op, except when the parameter type is bool. In
4936 // that case, this may extend the argument from 1 bit to 8 bits.
4937 QualType IntegerType = ParamType;
4938 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4939 IntegerType = Enum->getDecl()->getIntegerType();
4940 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4941
4942 Converted = TemplateArgument(Context, Value,
4943 Context.getCanonicalType(ParamType));
4944 return ArgResult;
4945 }
4946
4947 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4948 if (ArgResult.isInvalid())
4949 return ExprError();
4950 Arg = ArgResult.get();
4951
4952 QualType ArgType = Arg->getType();
4953
4954 // C++ [temp.arg.nontype]p1:
4955 // A template-argument for a non-type, non-template
4956 // template-parameter shall be one of:
4957 //
4958 // -- an integral constant-expression of integral or enumeration
4959 // type; or
4960 // -- the name of a non-type template-parameter; or
4961 SourceLocation NonConstantLoc;
4962 llvm::APSInt Value;
4963 if (!ArgType->isIntegralOrEnumerationType()) {
4964 Diag(Arg->getLocStart(),
4965 diag::err_template_arg_not_integral_or_enumeral)
4966 << ArgType << Arg->getSourceRange();
4967 Diag(Param->getLocation(), diag::note_template_param_here);
4968 return ExprError();
4969 } else if (!Arg->isValueDependent()) {
4970 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4971 QualType T;
4972
4973 public:
4974 TmplArgICEDiagnoser(QualType T) : T(T) { }
4975
4976 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4977 SourceRange SR) override {
4978 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4979 }
4980 } Diagnoser(ArgType);
4981
4982 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4983 false).get();
4984 if (!Arg)
4985 return ExprError();
4986 }
4987
4988 // From here on out, all we care about is the unqualified form
4989 // of the argument type.
4990 ArgType = ArgType.getUnqualifiedType();
4991
4992 // Try to convert the argument to the parameter's type.
4993 if (Context.hasSameType(ParamType, ArgType)) {
4994 // Okay: no conversion necessary
4995 } else if (ParamType->isBooleanType()) {
4996 // This is an integral-to-boolean conversion.
4997 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
4998 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4999 !ParamType->isEnumeralType()) {
5000 // This is an integral promotion or conversion.
5001 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5002 } else {
5003 // We can't perform this conversion.
5004 Diag(Arg->getLocStart(),
5005 diag::err_template_arg_not_convertible)
5006 << Arg->getType() << ParamType << Arg->getSourceRange();
5007 Diag(Param->getLocation(), diag::note_template_param_here);
5008 return ExprError();
5009 }
5010
5011 // Add the value of this argument to the list of converted
5012 // arguments. We use the bitwidth and signedness of the template
5013 // parameter.
5014 if (Arg->isValueDependent()) {
5015 // The argument is value-dependent. Create a new
5016 // TemplateArgument with the converted expression.
5017 Converted = TemplateArgument(Arg);
5018 return Arg;
5019 }
5020
5021 QualType IntegerType = Context.getCanonicalType(ParamType);
5022 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5023 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5024
5025 if (ParamType->isBooleanType()) {
5026 // Value must be zero or one.
5027 Value = Value != 0;
5028 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5029 if (Value.getBitWidth() != AllowedBits)
5030 Value = Value.extOrTrunc(AllowedBits);
5031 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5032 } else {
5033 llvm::APSInt OldValue = Value;
5034
5035 // Coerce the template argument's value to the value it will have
5036 // based on the template parameter's type.
5037 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5038 if (Value.getBitWidth() != AllowedBits)
5039 Value = Value.extOrTrunc(AllowedBits);
5040 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5041
5042 // Complain if an unsigned parameter received a negative value.
5043 if (IntegerType->isUnsignedIntegerOrEnumerationType()
5044 && (OldValue.isSigned() && OldValue.isNegative())) {
5045 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5046 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5047 << Arg->getSourceRange();
5048 Diag(Param->getLocation(), diag::note_template_param_here);
5049 }
5050
5051 // Complain if we overflowed the template parameter's type.
5052 unsigned RequiredBits;
5053 if (IntegerType->isUnsignedIntegerOrEnumerationType())
5054 RequiredBits = OldValue.getActiveBits();
5055 else if (OldValue.isUnsigned())
5056 RequiredBits = OldValue.getActiveBits() + 1;
5057 else
5058 RequiredBits = OldValue.getMinSignedBits();
5059 if (RequiredBits > AllowedBits) {
5060 Diag(Arg->getLocStart(),
5061 diag::warn_template_arg_too_large)
5062 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5063 << Arg->getSourceRange();
5064 Diag(Param->getLocation(), diag::note_template_param_here);
5065 }
5066 }
5067
5068 Converted = TemplateArgument(Context, Value,
5069 ParamType->isEnumeralType()
5070 ? Context.getCanonicalType(ParamType)
5071 : IntegerType);
5072 return Arg;
5073 }
5074
5075 QualType ArgType = Arg->getType();
5076 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5077
5078 // Handle pointer-to-function, reference-to-function, and
5079 // pointer-to-member-function all in (roughly) the same way.
5080 if (// -- For a non-type template-parameter of type pointer to
5081 // function, only the function-to-pointer conversion (4.3) is
5082 // applied. If the template-argument represents a set of
5083 // overloaded functions (or a pointer to such), the matching
5084 // function is selected from the set (13.4).
5085 (ParamType->isPointerType() &&
5086 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5087 // -- For a non-type template-parameter of type reference to
5088 // function, no conversions apply. If the template-argument
5089 // represents a set of overloaded functions, the matching
5090 // function is selected from the set (13.4).
5091 (ParamType->isReferenceType() &&
5092 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5093 // -- For a non-type template-parameter of type pointer to
5094 // member function, no conversions apply. If the
5095 // template-argument represents a set of overloaded member
5096 // functions, the matching member function is selected from
5097 // the set (13.4).
5098 (ParamType->isMemberPointerType() &&
5099 ParamType->getAs<MemberPointerType>()->getPointeeType()
5100 ->isFunctionType())) {
5101
5102 if (Arg->getType() == Context.OverloadTy) {
5103 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5104 true,
5105 FoundResult)) {
5106 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5107 return ExprError();
5108
5109 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5110 ArgType = Arg->getType();
5111 } else
5112 return ExprError();
5113 }
5114
5115 if (!ParamType->isMemberPointerType()) {
5116 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5117 ParamType,
5118 Arg, Converted))
5119 return ExprError();
5120 return Arg;
5121 }
5122
5123 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5124 Converted))
5125 return ExprError();
5126 return Arg;
5127 }
5128
5129 if (ParamType->isPointerType()) {
5130 // -- for a non-type template-parameter of type pointer to
5131 // object, qualification conversions (4.4) and the
5132 // array-to-pointer conversion (4.2) are applied.
5133 // C++0x also allows a value of std::nullptr_t.
5134 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5135 "Only object pointers allowed here");
5136
5137 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5138 ParamType,
5139 Arg, Converted))
5140 return ExprError();
5141 return Arg;
5142 }
5143
5144 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5145 // -- For a non-type template-parameter of type reference to
5146 // object, no conversions apply. The type referred to by the
5147 // reference may be more cv-qualified than the (otherwise
5148 // identical) type of the template-argument. The
5149 // template-parameter is bound directly to the
5150 // template-argument, which must be an lvalue.
5151 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5152 "Only object references allowed here");
5153
5154 if (Arg->getType() == Context.OverloadTy) {
5155 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5156 ParamRefType->getPointeeType(),
5157 true,
5158 FoundResult)) {
5159 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5160 return ExprError();
5161
5162 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5163 ArgType = Arg->getType();
5164 } else
5165 return ExprError();
5166 }
5167
5168 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5169 ParamType,
5170 Arg, Converted))
5171 return ExprError();
5172 return Arg;
5173 }
5174
5175 // Deal with parameters of type std::nullptr_t.
5176 if (ParamType->isNullPtrType()) {
5177 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5178 Converted = TemplateArgument(Arg);
5179 return Arg;
5180 }
5181
5182 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5183 case NPV_NotNullPointer:
5184 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5185 << Arg->getType() << ParamType;
5186 Diag(Param->getLocation(), diag::note_template_param_here);
5187 return ExprError();
5188
5189 case NPV_Error:
5190 return ExprError();
5191
5192 case NPV_NullPointer:
5193 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5194 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5195 /*isNullPtr*/true);
5196 return Arg;
5197 }
5198 }
5199
5200 // -- For a non-type template-parameter of type pointer to data
5201 // member, qualification conversions (4.4) are applied.
5202 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5203
5204 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5205 Converted))
5206 return ExprError();
5207 return Arg;
5208}
5209
5210/// \brief Check a template argument against its corresponding
5211/// template template parameter.
5212///
5213/// This routine implements the semantics of C++ [temp.arg.template].
5214/// It returns true if an error occurred, and false otherwise.
5215bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5216 TemplateArgumentLoc &Arg,
5217 unsigned ArgumentPackIndex) {
5218 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5219 TemplateDecl *Template = Name.getAsTemplateDecl();
5220 if (!Template) {
5221 // Any dependent template name is fine.
5222 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5223 return false;
5224 }
5225
5226 // C++0x [temp.arg.template]p1:
5227 // A template-argument for a template template-parameter shall be
5228 // the name of a class template or an alias template, expressed as an
5229 // id-expression. When the template-argument names a class template, only
5230 // primary class templates are considered when matching the
5231 // template template argument with the corresponding parameter;
5232 // partial specializations are not considered even if their
5233 // parameter lists match that of the template template parameter.
5234 //
5235 // Note that we also allow template template parameters here, which
5236 // will happen when we are dealing with, e.g., class template
5237 // partial specializations.
5238 if (!isa<ClassTemplateDecl>(Template) &&
5239 !isa<TemplateTemplateParmDecl>(Template) &&
5240 !isa<TypeAliasTemplateDecl>(Template)) {
5241 assert(isa<FunctionTemplateDecl>(Template) &&
5242 "Only function templates are possible here");
5243 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5244 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5245 << Template;
5246 }
5247
5248 TemplateParameterList *Params = Param->getTemplateParameters();
5249 if (Param->isExpandedParameterPack())
5250 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5251
5252 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5253 Params,
5254 true,
5255 TPL_TemplateTemplateArgumentMatch,
5256 Arg.getLocation());
5257}
5258
5259/// \brief Given a non-type template argument that refers to a
5260/// declaration and the type of its corresponding non-type template
5261/// parameter, produce an expression that properly refers to that
5262/// declaration.
5263ExprResult
5264Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5265 QualType ParamType,
5266 SourceLocation Loc) {
5267 // C++ [temp.param]p8:
5268 //
5269 // A non-type template-parameter of type "array of T" or
5270 // "function returning T" is adjusted to be of type "pointer to
5271 // T" or "pointer to function returning T", respectively.
5272 if (ParamType->isArrayType())
5273 ParamType = Context.getArrayDecayedType(ParamType);
5274 else if (ParamType->isFunctionType())
5275 ParamType = Context.getPointerType(ParamType);
5276
5277 // For a NULL non-type template argument, return nullptr casted to the
5278 // parameter's type.
5279 if (Arg.getKind() == TemplateArgument::NullPtr) {
5280 return ImpCastExprToType(
5281 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5282 ParamType,
5283 ParamType->getAs<MemberPointerType>()
5284 ? CK_NullToMemberPointer
5285 : CK_NullToPointer);
5286 }
5287 assert(Arg.getKind() == TemplateArgument::Declaration &&
5288 "Only declaration template arguments permitted here");
5289
5290 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5291
5292 if (VD->getDeclContext()->isRecord() &&
5293 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5294 isa<IndirectFieldDecl>(VD))) {
5295 // If the value is a class member, we might have a pointer-to-member.
5296 // Determine whether the non-type template template parameter is of
5297 // pointer-to-member type. If so, we need to build an appropriate
5298 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5299 // would refer to the member itself.
5300 if (ParamType->isMemberPointerType()) {
5301 QualType ClassType
5302 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5303 NestedNameSpecifier *Qualifier
5304 = NestedNameSpecifier::Create(Context, nullptr, false,
5305 ClassType.getTypePtr());
5306 CXXScopeSpec SS;
5307 SS.MakeTrivial(Context, Qualifier, Loc);
5308
5309 // The actual value-ness of this is unimportant, but for
5310 // internal consistency's sake, references to instance methods
5311 // are r-values.
5312 ExprValueKind VK = VK_LValue;
5313 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5314 VK = VK_RValue;
5315
5316 ExprResult RefExpr = BuildDeclRefExpr(VD,
5317 VD->getType().getNonReferenceType(),
5318 VK,
5319 Loc,
5320 &SS);
5321 if (RefExpr.isInvalid())
5322 return ExprError();
5323
5324 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5325
5326 // We might need to perform a trailing qualification conversion, since
5327 // the element type on the parameter could be more qualified than the
5328 // element type in the expression we constructed.
5329 bool ObjCLifetimeConversion;
5330 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5331 ParamType.getUnqualifiedType(), false,
5332 ObjCLifetimeConversion))
5333 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5334
5335 assert(!RefExpr.isInvalid() &&
5336 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5337 ParamType.getUnqualifiedType()));
5338 return RefExpr;
5339 }
5340 }
5341
5342 QualType T = VD->getType().getNonReferenceType();
5343
5344 if (ParamType->isPointerType()) {
5345 // When the non-type template parameter is a pointer, take the
5346 // address of the declaration.
5347 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5348 if (RefExpr.isInvalid())
5349 return ExprError();
5350
5351 if (T->isFunctionType() || T->isArrayType()) {
5352 // Decay functions and arrays.
5353 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5354 if (RefExpr.isInvalid())
5355 return ExprError();
5356
5357 return RefExpr;
5358 }
5359
5360 // Take the address of everything else
5361 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5362 }
5363
5364 ExprValueKind VK = VK_RValue;
5365
5366 // If the non-type template parameter has reference type, qualify the
5367 // resulting declaration reference with the extra qualifiers on the
5368 // type that the reference refers to.
5369 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5370 VK = VK_LValue;
5371 T = Context.getQualifiedType(T,
5372 TargetRef->getPointeeType().getQualifiers());
5373 } else if (isa<FunctionDecl>(VD)) {
5374 // References to functions are always lvalues.
5375 VK = VK_LValue;
5376 }
5377
5378 return BuildDeclRefExpr(VD, T, VK, Loc);
5379}
5380
5381/// \brief Construct a new expression that refers to the given
5382/// integral template argument with the given source-location
5383/// information.
5384///
5385/// This routine takes care of the mapping from an integral template
5386/// argument (which may have any integral type) to the appropriate
5387/// literal value.
5388ExprResult
5389Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5390 SourceLocation Loc) {
5391 assert(Arg.getKind() == TemplateArgument::Integral &&
5392 "Operation is only valid for integral template arguments");
5393 QualType OrigT = Arg.getIntegralType();
5394
5395 // If this is an enum type that we're instantiating, we need to use an integer
5396 // type the same size as the enumerator. We don't want to build an
5397 // IntegerLiteral with enum type. The integer type of an enum type can be of
5398 // any integral type with C++11 enum classes, make sure we create the right
5399 // type of literal for it.
5400 QualType T = OrigT;
5401 if (const EnumType *ET = OrigT->getAs<EnumType>())
5402 T = ET->getDecl()->getIntegerType();
5403
5404 Expr *E;
5405 if (T->isAnyCharacterType()) {
5406 CharacterLiteral::CharacterKind Kind;
5407 if (T->isWideCharType())
5408 Kind = CharacterLiteral::Wide;
5409 else if (T->isChar16Type())
5410 Kind = CharacterLiteral::UTF16;
5411 else if (T->isChar32Type())
5412 Kind = CharacterLiteral::UTF32;
5413 else
5414 Kind = CharacterLiteral::Ascii;
5415
5416 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5417 Kind, T, Loc);
5418 } else if (T->isBooleanType()) {
5419 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5420 T, Loc);
5421 } else if (T->isNullPtrType()) {
5422 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5423 } else {
5424 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5425 }
5426
5427 if (OrigT->isEnumeralType()) {
5428 // FIXME: This is a hack. We need a better way to handle substituted
5429 // non-type template parameters.
5430 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5431 nullptr,
5432 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5433 Loc, Loc);
5434 }
5435
5436 return E;
5437}
5438
5439/// \brief Match two template parameters within template parameter lists.
5440static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5441 bool Complain,
5442 Sema::TemplateParameterListEqualKind Kind,
5443 SourceLocation TemplateArgLoc) {
5444 // Check the actual kind (type, non-type, template).
5445 if (Old->getKind() != New->getKind()) {
5446 if (Complain) {
5447 unsigned NextDiag = diag::err_template_param_different_kind;
5448 if (TemplateArgLoc.isValid()) {
5449 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5450 NextDiag = diag::note_template_param_different_kind;
5451 }
5452 S.Diag(New->getLocation(), NextDiag)
5453 << (Kind != Sema::TPL_TemplateMatch);
5454 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5455 << (Kind != Sema::TPL_TemplateMatch);
5456 }
5457
5458 return false;
5459 }
5460
5461 // Check that both are parameter packs are neither are parameter packs.
5462 // However, if we are matching a template template argument to a
5463 // template template parameter, the template template parameter can have
5464 // a parameter pack where the template template argument does not.
5465 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5466 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5467 Old->isTemplateParameterPack())) {
5468 if (Complain) {
5469 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5470 if (TemplateArgLoc.isValid()) {
5471 S.Diag(TemplateArgLoc,
5472 diag::err_template_arg_template_params_mismatch);
5473 NextDiag = diag::note_template_parameter_pack_non_pack;
5474 }
5475
5476 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5477 : isa<NonTypeTemplateParmDecl>(New)? 1
5478 : 2;
5479 S.Diag(New->getLocation(), NextDiag)
5480 << ParamKind << New->isParameterPack();
5481 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5482 << ParamKind << Old->isParameterPack();
5483 }
5484
5485 return false;
5486 }
5487
5488 // For non-type template parameters, check the type of the parameter.
5489 if (NonTypeTemplateParmDecl *OldNTTP
5490 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5491 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5492
5493 // If we are matching a template template argument to a template
5494 // template parameter and one of the non-type template parameter types
5495 // is dependent, then we must wait until template instantiation time
5496 // to actually compare the arguments.
5497 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5498 (OldNTTP->getType()->isDependentType() ||
5499 NewNTTP->getType()->isDependentType()))
5500 return true;
5501
5502 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5503 if (Complain) {
5504 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5505 if (TemplateArgLoc.isValid()) {
5506 S.Diag(TemplateArgLoc,
5507 diag::err_template_arg_template_params_mismatch);
5508 NextDiag = diag::note_template_nontype_parm_different_type;
5509 }
5510 S.Diag(NewNTTP->getLocation(), NextDiag)
5511 << NewNTTP->getType()
5512 << (Kind != Sema::TPL_TemplateMatch);
5513 S.Diag(OldNTTP->getLocation(),
5514 diag::note_template_nontype_parm_prev_declaration)
5515 << OldNTTP->getType();
5516 }
5517
5518 return false;
5519 }
5520
5521 return true;
5522 }
5523
5524 // For template template parameters, check the template parameter types.
5525 // The template parameter lists of template template
5526 // parameters must agree.
5527 if (TemplateTemplateParmDecl *OldTTP
5528 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5529 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5530 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5531 OldTTP->getTemplateParameters(),
5532 Complain,
5533 (Kind == Sema::TPL_TemplateMatch
5534 ? Sema::TPL_TemplateTemplateParmMatch
5535 : Kind),
5536 TemplateArgLoc);
5537 }
5538
5539 return true;
5540}
5541
5542/// \brief Diagnose a known arity mismatch when comparing template argument
5543/// lists.
5544static
5545void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5546 TemplateParameterList *New,
5547 TemplateParameterList *Old,
5548 Sema::TemplateParameterListEqualKind Kind,
5549 SourceLocation TemplateArgLoc) {
5550 unsigned NextDiag = diag::err_template_param_list_different_arity;
5551 if (TemplateArgLoc.isValid()) {
5552 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5553 NextDiag = diag::note_template_param_list_different_arity;
5554 }
5555 S.Diag(New->getTemplateLoc(), NextDiag)
5556 << (New->size() > Old->size())
5557 << (Kind != Sema::TPL_TemplateMatch)
5558 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5559 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5560 << (Kind != Sema::TPL_TemplateMatch)
5561 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5562}
5563
5564/// \brief Determine whether the given template parameter lists are
5565/// equivalent.
5566///
5567/// \param New The new template parameter list, typically written in the
5568/// source code as part of a new template declaration.
5569///
5570/// \param Old The old template parameter list, typically found via
5571/// name lookup of the template declared with this template parameter
5572/// list.
5573///
5574/// \param Complain If true, this routine will produce a diagnostic if
5575/// the template parameter lists are not equivalent.
5576///
5577/// \param Kind describes how we are to match the template parameter lists.
5578///
5579/// \param TemplateArgLoc If this source location is valid, then we
5580/// are actually checking the template parameter list of a template
5581/// argument (New) against the template parameter list of its
5582/// corresponding template template parameter (Old). We produce
5583/// slightly different diagnostics in this scenario.
5584///
5585/// \returns True if the template parameter lists are equal, false
5586/// otherwise.
5587bool
5588Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5589 TemplateParameterList *Old,
5590 bool Complain,
5591 TemplateParameterListEqualKind Kind,
5592 SourceLocation TemplateArgLoc) {
5593 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5594 if (Complain)
5595 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5596 TemplateArgLoc);
5597
5598 return false;
5599 }
5600
5601 // C++0x [temp.arg.template]p3:
5602 // A template-argument matches a template template-parameter (call it P)
5603 // when each of the template parameters in the template-parameter-list of
5604 // the template-argument's corresponding class template or alias template
5605 // (call it A) matches the corresponding template parameter in the
5606 // template-parameter-list of P. [...]
5607 TemplateParameterList::iterator NewParm = New->begin();
5608 TemplateParameterList::iterator NewParmEnd = New->end();
5609 for (TemplateParameterList::iterator OldParm = Old->begin(),
5610 OldParmEnd = Old->end();
5611 OldParm != OldParmEnd; ++OldParm) {
5612 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5613 !(*OldParm)->isTemplateParameterPack()) {
5614 if (NewParm == NewParmEnd) {
5615 if (Complain)
5616 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5617 TemplateArgLoc);
5618
5619 return false;
5620 }
5621
5622 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5623 Kind, TemplateArgLoc))
5624 return false;
5625
5626 ++NewParm;
5627 continue;
5628 }
5629
5630 // C++0x [temp.arg.template]p3:
5631 // [...] When P's template- parameter-list contains a template parameter
5632 // pack (14.5.3), the template parameter pack will match zero or more
5633 // template parameters or template parameter packs in the
5634 // template-parameter-list of A with the same type and form as the
5635 // template parameter pack in P (ignoring whether those template
5636 // parameters are template parameter packs).
5637 for (; NewParm != NewParmEnd; ++NewParm) {
5638 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5639 Kind, TemplateArgLoc))
5640 return false;
5641 }
5642 }
5643
5644 // Make sure we exhausted all of the arguments.
5645 if (NewParm != NewParmEnd) {
5646 if (Complain)
5647 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5648 TemplateArgLoc);
5649
5650 return false;
5651 }
5652
5653 return true;
5654}
5655
5656/// \brief Check whether a template can be declared within this scope.
5657///
5658/// If the template declaration is valid in this scope, returns
5659/// false. Otherwise, issues a diagnostic and returns true.
5660bool
5661Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5662 if (!S)
5663 return false;
5664
5665 // Find the nearest enclosing declaration scope.
5666 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5667 (S->getFlags() & Scope::TemplateParamScope) != 0)
5668 S = S->getParent();
5669
5670 // C++ [temp]p4:
5671 // A template [...] shall not have C linkage.
5672 DeclContext *Ctx = S->getEntity();
5673 if (Ctx && Ctx->isExternCContext())
5674 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5675 << TemplateParams->getSourceRange();
5676
5677 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5678 Ctx = Ctx->getParent();
5679
5680 // C++ [temp]p2:
5681 // A template-declaration can appear only as a namespace scope or
5682 // class scope declaration.
5683 if (Ctx) {
5684 if (Ctx->isFileContext())
5685 return false;
5686 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5687 // C++ [temp.mem]p2:
5688 // A local class shall not have member templates.
5689 if (RD->isLocalClass())
5690 return Diag(TemplateParams->getTemplateLoc(),
5691 diag::err_template_inside_local_class)
5692 << TemplateParams->getSourceRange();
5693 else
5694 return false;
5695 }
5696 }
5697
5698 return Diag(TemplateParams->getTemplateLoc(),
5699 diag::err_template_outside_namespace_or_class_scope)
5700 << TemplateParams->getSourceRange();
5701}
5702
5703/// \brief Determine what kind of template specialization the given declaration
5704/// is.
5705static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5706 if (!D)
5707 return TSK_Undeclared;
5708
5709 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5710 return Record->getTemplateSpecializationKind();
5711 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5712 return Function->getTemplateSpecializationKind();
5713 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5714 return Var->getTemplateSpecializationKind();
5715
5716 return TSK_Undeclared;
5717}
5718
5719/// \brief Check whether a specialization is well-formed in the current
5720/// context.
5721///
5722/// This routine determines whether a template specialization can be declared
5723/// in the current context (C++ [temp.expl.spec]p2).
5724///
5725/// \param S the semantic analysis object for which this check is being
5726/// performed.
5727///
5728/// \param Specialized the entity being specialized or instantiated, which
5729/// may be a kind of template (class template, function template, etc.) or
5730/// a member of a class template (member function, static data member,
5731/// member class).
5732///
5733/// \param PrevDecl the previous declaration of this entity, if any.
5734///
5735/// \param Loc the location of the explicit specialization or instantiation of
5736/// this entity.
5737///
5738/// \param IsPartialSpecialization whether this is a partial specialization of
5739/// a class template.
5740///
5741/// \returns true if there was an error that we cannot recover from, false
5742/// otherwise.
5743static bool CheckTemplateSpecializationScope(Sema &S,
5744 NamedDecl *Specialized,
5745 NamedDecl *PrevDecl,
5746 SourceLocation Loc,
5747 bool IsPartialSpecialization) {
5748 // Keep these "kind" numbers in sync with the %select statements in the
5749 // various diagnostics emitted by this routine.
5750 int EntityKind = 0;
5751 if (isa<ClassTemplateDecl>(Specialized))
5752 EntityKind = IsPartialSpecialization? 1 : 0;
5753 else if (isa<VarTemplateDecl>(Specialized))
5754 EntityKind = IsPartialSpecialization ? 3 : 2;
5755 else if (isa<FunctionTemplateDecl>(Specialized))
5756 EntityKind = 4;
5757 else if (isa<CXXMethodDecl>(Specialized))
5758 EntityKind = 5;
5759 else if (isa<VarDecl>(Specialized))
5760 EntityKind = 6;
5761 else if (isa<RecordDecl>(Specialized))
5762 EntityKind = 7;
5763 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5764 EntityKind = 8;
5765 else {
5766 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5767 << S.getLangOpts().CPlusPlus11;
5768 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5769 return true;
5770 }
5771
5772 // C++ [temp.expl.spec]p2:
5773 // An explicit specialization shall be declared in the namespace
5774 // of which the template is a member, or, for member templates, in
5775 // the namespace of which the enclosing class or enclosing class
5776 // template is a member. An explicit specialization of a member
5777 // function, member class or static data member of a class
5778 // template shall be declared in the namespace of which the class
5779 // template is a member. Such a declaration may also be a
5780 // definition. If the declaration is not a definition, the
5781 // specialization may be defined later in the name- space in which
5782 // the explicit specialization was declared, or in a namespace
5783 // that encloses the one in which the explicit specialization was
5784 // declared.
5785 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5786 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5787 << Specialized;
5788 return true;
5789 }
5790
5791 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5792 if (S.getLangOpts().MicrosoftExt) {
5793 // Do not warn for class scope explicit specialization during
5794 // instantiation, warning was already emitted during pattern
5795 // semantic analysis.
5796 if (!S.ActiveTemplateInstantiations.size())
5797 S.Diag(Loc, diag::ext_function_specialization_in_class)
5798 << Specialized;
5799 } else {
5800 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5801 << Specialized;
5802 return true;
5803 }
5804 }
5805
5806 if (S.CurContext->isRecord() &&
5807 !S.CurContext->Equals(Specialized->getDeclContext())) {
5808 // Make sure that we're specializing in the right record context.
5809 // Otherwise, things can go horribly wrong.
5810 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5811 << Specialized;
5812 return true;
5813 }
5814
5815 // C++ [temp.class.spec]p6:
5816 // A class template partial specialization may be declared or redeclared
5817 // in any namespace scope in which its definition may be defined (14.5.1
5818 // and 14.5.2).
5819 DeclContext *SpecializedContext
5820 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5821 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5822
5823 // Make sure that this redeclaration (or definition) occurs in an enclosing
5824 // namespace.
5825 // Note that HandleDeclarator() performs this check for explicit
5826 // specializations of function templates, static data members, and member
5827 // functions, so we skip the check here for those kinds of entities.
5828 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5829 // Should we refactor that check, so that it occurs later?
5830 if (!DC->Encloses(SpecializedContext) &&
5831 !(isa<FunctionTemplateDecl>(Specialized) ||
5832 isa<FunctionDecl>(Specialized) ||
5833 isa<VarTemplateDecl>(Specialized) ||
5834 isa<VarDecl>(Specialized))) {
5835 if (isa<TranslationUnitDecl>(SpecializedContext))
5836 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5837 << EntityKind << Specialized;
5838 else if (isa<NamespaceDecl>(SpecializedContext))
5839 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5840 << EntityKind << Specialized
5841 << cast<NamedDecl>(SpecializedContext);
5842 else
5843 llvm_unreachable("unexpected namespace context for specialization");
5844
5845 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5846 } else if ((!PrevDecl ||
5847 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5848 getTemplateSpecializationKind(PrevDecl) ==
5849 TSK_ImplicitInstantiation)) {
5850 // C++ [temp.exp.spec]p2:
5851 // An explicit specialization shall be declared in the namespace of which
5852 // the template is a member, or, for member templates, in the namespace
5853 // of which the enclosing class or enclosing class template is a member.
5854 // An explicit specialization of a member function, member class or
5855 // static data member of a class template shall be declared in the
5856 // namespace of which the class template is a member.
5857 //
5858 // C++11 [temp.expl.spec]p2:
5859 // An explicit specialization shall be declared in a namespace enclosing
5860 // the specialized template.
5861 // C++11 [temp.explicit]p3:
5862 // An explicit instantiation shall appear in an enclosing namespace of its
5863 // template.
5864 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5865 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5866 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5867 assert(!IsCPlusPlus11Extension &&
5868 "DC encloses TU but isn't in enclosing namespace set");
5869 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5870 << EntityKind << Specialized;
5871 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5872 int Diag;
5873 if (!IsCPlusPlus11Extension)
5874 Diag = diag::err_template_spec_decl_out_of_scope;
5875 else if (!S.getLangOpts().CPlusPlus11)
5876 Diag = diag::ext_template_spec_decl_out_of_scope;
5877 else
5878 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5879 S.Diag(Loc, Diag)
5880 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5881 }
5882
5883 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5884 }
5885 }
5886
5887 return false;
5888}
5889
5890static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5891 if (!E->isInstantiationDependent())
5892 return SourceLocation();
5893 DependencyChecker Checker(Depth);
5894 Checker.TraverseStmt(E);
5895 if (Checker.Match && Checker.MatchLoc.isInvalid())
5896 return E->getSourceRange();
5897 return Checker.MatchLoc;
5898}
5899
5900static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5901 if (!TL.getType()->isDependentType())
5902 return SourceLocation();
5903 DependencyChecker Checker(Depth);
5904 Checker.TraverseTypeLoc(TL);
5905 if (Checker.Match && Checker.MatchLoc.isInvalid())
5906 return TL.getSourceRange();
5907 return Checker.MatchLoc;
5908}
5909
5910/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
5911/// that checks non-type template partial specialization arguments.
5912static bool CheckNonTypeTemplatePartialSpecializationArgs(
5913 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5914 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
5915 for (unsigned I = 0; I != NumArgs; ++I) {
5916 if (Args[I].getKind() == TemplateArgument::Pack) {
5917 if (CheckNonTypeTemplatePartialSpecializationArgs(
5918 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5919 Args[I].pack_size(), IsDefaultArgument))
5920 return true;
5921
5922 continue;
5923 }
5924
5925 if (Args[I].getKind() != TemplateArgument::Expression)
5926 continue;
5927
5928 Expr *ArgExpr = Args[I].getAsExpr();
5929
5930 // We can have a pack expansion of any of the bullets below.
5931 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5932 ArgExpr = Expansion->getPattern();
5933
5934 // Strip off any implicit casts we added as part of type checking.
5935 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5936 ArgExpr = ICE->getSubExpr();
5937
5938 // C++ [temp.class.spec]p8:
5939 // A non-type argument is non-specialized if it is the name of a
5940 // non-type parameter. All other non-type arguments are
5941 // specialized.
5942 //
5943 // Below, we check the two conditions that only apply to
5944 // specialized non-type arguments, so skip any non-specialized
5945 // arguments.
5946 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5947 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5948 continue;
5949
5950 // C++ [temp.class.spec]p9:
5951 // Within the argument list of a class template partial
5952 // specialization, the following restrictions apply:
5953 // -- A partially specialized non-type argument expression
5954 // shall not involve a template parameter of the partial
5955 // specialization except when the argument expression is a
5956 // simple identifier.
5957 SourceRange ParamUseRange =
5958 findTemplateParameter(Param->getDepth(), ArgExpr);
5959 if (ParamUseRange.isValid()) {
5960 if (IsDefaultArgument) {
5961 S.Diag(TemplateNameLoc,
5962 diag::err_dependent_non_type_arg_in_partial_spec);
5963 S.Diag(ParamUseRange.getBegin(),
5964 diag::note_dependent_non_type_default_arg_in_partial_spec)
5965 << ParamUseRange;
5966 } else {
5967 S.Diag(ParamUseRange.getBegin(),
5968 diag::err_dependent_non_type_arg_in_partial_spec)
5969 << ParamUseRange;
5970 }
5971 return true;
5972 }
5973
5974 // -- The type of a template parameter corresponding to a
5975 // specialized non-type argument shall not be dependent on a
5976 // parameter of the specialization.
5977 //
5978 // FIXME: We need to delay this check until instantiation in some cases:
5979 //
5980 // template<template<typename> class X> struct A {
5981 // template<typename T, X<T> N> struct B;
5982 // template<typename T> struct B<T, 0>;
5983 // };
5984 // template<typename> using X = int;
5985 // A<X>::B<int, 0> b;
5986 ParamUseRange = findTemplateParameter(
5987 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
5988 if (ParamUseRange.isValid()) {
5989 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
5990 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5991 << Param->getType() << ParamUseRange;
5992 S.Diag(Param->getLocation(), diag::note_template_param_here)
5993 << (IsDefaultArgument ? ParamUseRange : SourceRange());
5994 return true;
5995 }
5996 }
5997
5998 return false;
5999}
6000
6001/// \brief Check the non-type template arguments of a class template
6002/// partial specialization according to C++ [temp.class.spec]p9.
6003///
6004/// \param TemplateNameLoc the location of the template name.
6005/// \param TemplateParams the template parameters of the primary class
6006/// template.
6007/// \param NumExplicit the number of explicitly-specified template arguments.
6008/// \param TemplateArgs the template arguments of the class template
6009/// partial specialization.
6010///
6011/// \returns \c true if there was an error, \c false otherwise.
6012static bool CheckTemplatePartialSpecializationArgs(
6013 Sema &S, SourceLocation TemplateNameLoc,
6014 TemplateParameterList *TemplateParams, unsigned NumExplicit,
6015 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6016 const TemplateArgument *ArgList = TemplateArgs.data();
6017
6018 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6019 NonTypeTemplateParmDecl *Param
6020 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6021 if (!Param)
6022 continue;
6023
6024 if (CheckNonTypeTemplatePartialSpecializationArgs(
6025 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6026 return true;
6027 }
6028
6029 return false;
6030}
6031
6032DeclResult
6033Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6034 TagUseKind TUK,
6035 SourceLocation KWLoc,
6036 SourceLocation ModulePrivateLoc,
6037 TemplateIdAnnotation &TemplateId,
6038 AttributeList *Attr,
6039 MultiTemplateParamsArg TemplateParameterLists) {
6040 assert(TUK != TUK_Reference && "References are not specializations");
6041
6042 CXXScopeSpec &SS = TemplateId.SS;
6043
6044 // NOTE: KWLoc is the location of the tag keyword. This will instead
6045 // store the location of the outermost template keyword in the declaration.
6046 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6047 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6048 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6049 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6050 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6051
6052 // Find the class template we're specializing
6053 TemplateName Name = TemplateId.Template.get();
6054 ClassTemplateDecl *ClassTemplate
6055 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6056
6057 if (!ClassTemplate) {
6058 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6059 << (Name.getAsTemplateDecl() &&
6060 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6061 return true;
6062 }
6063
6064 bool isExplicitSpecialization = false;
6065 bool isPartialSpecialization = false;
6066
6067 // Check the validity of the template headers that introduce this
6068 // template.
6069 // FIXME: We probably shouldn't complain about these headers for
6070 // friend declarations.
6071 bool Invalid = false;
6072 TemplateParameterList *TemplateParams =
6073 MatchTemplateParametersToScopeSpecifier(
6074 KWLoc, TemplateNameLoc, SS, &TemplateId,
6075 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6076 Invalid);
6077 if (Invalid)
6078 return true;
6079
6080 if (TemplateParams && TemplateParams->size() > 0) {
6081 isPartialSpecialization = true;
6082
6083 if (TUK == TUK_Friend) {
6084 Diag(KWLoc, diag::err_partial_specialization_friend)
6085 << SourceRange(LAngleLoc, RAngleLoc);
6086 return true;
6087 }
6088
6089 // C++ [temp.class.spec]p10:
6090 // The template parameter list of a specialization shall not
6091 // contain default template argument values.
6092 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6093 Decl *Param = TemplateParams->getParam(I);
6094 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6095 if (TTP->hasDefaultArgument()) {
6096 Diag(TTP->getDefaultArgumentLoc(),
6097 diag::err_default_arg_in_partial_spec);
6098 TTP->removeDefaultArgument();
6099 }
6100 } else if (NonTypeTemplateParmDecl *NTTP
6101 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6102 if (Expr *DefArg = NTTP->getDefaultArgument()) {
6103 Diag(NTTP->getDefaultArgumentLoc(),
6104 diag::err_default_arg_in_partial_spec)
6105 << DefArg->getSourceRange();
6106 NTTP->removeDefaultArgument();
6107 }
6108 } else {
6109 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6110 if (TTP->hasDefaultArgument()) {
6111 Diag(TTP->getDefaultArgument().getLocation(),
6112 diag::err_default_arg_in_partial_spec)
6113 << TTP->getDefaultArgument().getSourceRange();
6114 TTP->removeDefaultArgument();
6115 }
6116 }
6117 }
6118 } else if (TemplateParams) {
6119 if (TUK == TUK_Friend)
6120 Diag(KWLoc, diag::err_template_spec_friend)
6121 << FixItHint::CreateRemoval(
6122 SourceRange(TemplateParams->getTemplateLoc(),
6123 TemplateParams->getRAngleLoc()))
6124 << SourceRange(LAngleLoc, RAngleLoc);
6125 else
6126 isExplicitSpecialization = true;
6127 } else {
6128 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6129 }
6130
6131 // Check that the specialization uses the same tag kind as the
6132 // original template.
6133 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6134 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6135 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6136 Kind, TUK == TUK_Definition, KWLoc,
6137 *ClassTemplate->getIdentifier())) {
6138 Diag(KWLoc, diag::err_use_with_wrong_tag)
6139 << ClassTemplate
6140 << FixItHint::CreateReplacement(KWLoc,
6141 ClassTemplate->getTemplatedDecl()->getKindName());
6142 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6143 diag::note_previous_use);
6144 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6145 }
6146
6147 // Translate the parser's template argument list in our AST format.
6148 TemplateArgumentListInfo TemplateArgs =
6149 makeTemplateArgumentListInfo(*this, TemplateId);
6150
6151 // Check for unexpanded parameter packs in any of the template arguments.
6152 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6153 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6154 UPPC_PartialSpecialization))
6155 return true;
6156
6157 // Check that the template argument list is well-formed for this
6158 // template.
6159 SmallVector<TemplateArgument, 4> Converted;
6160 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6161 TemplateArgs, false, Converted))
6162 return true;
6163
6164 // Find the class template (partial) specialization declaration that
6165 // corresponds to these arguments.
6166 if (isPartialSpecialization) {
6167 if (CheckTemplatePartialSpecializationArgs(
6168 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6169 TemplateArgs.size(), Converted))
6170 return true;
6171
6172 bool InstantiationDependent;
6173 if (!Name.isDependent() &&
6174 !TemplateSpecializationType::anyDependentTemplateArguments(
6175 TemplateArgs.getArgumentArray(),
6176 TemplateArgs.size(),
6177 InstantiationDependent)) {
6178 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6179 << ClassTemplate->getDeclName();
6180 isPartialSpecialization = false;
6181 }
6182 }
6183
6184 void *InsertPos = nullptr;
6185 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6186
6187 if (isPartialSpecialization)
6188 // FIXME: Template parameter list matters, too
6189 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6190 else
6191 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6192
6193 ClassTemplateSpecializationDecl *Specialization = nullptr;
6194
6195 // Check whether we can declare a class template specialization in
6196 // the current scope.
6197 if (TUK != TUK_Friend &&
6198 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6199 TemplateNameLoc,
6200 isPartialSpecialization))
6201 return true;
6202
6203 // The canonical type
6204 QualType CanonType;
6205 if (isPartialSpecialization) {
6206 // Build the canonical type that describes the converted template
6207 // arguments of the class template partial specialization.
6208 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6209 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6210 Converted.data(),
6211 Converted.size());
6212
6213 if (Context.hasSameType(CanonType,
6214 ClassTemplate->getInjectedClassNameSpecialization())) {
6215 // C++ [temp.class.spec]p9b3:
6216 //
6217 // -- The argument list of the specialization shall not be identical
6218 // to the implicit argument list of the primary template.
6219 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6220 << /*class template*/0 << (TUK == TUK_Definition)
6221 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6222 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6223 ClassTemplate->getIdentifier(),
6224 TemplateNameLoc,
6225 Attr,
6226 TemplateParams,
6227 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6228 /*FriendLoc*/SourceLocation(),
6229 TemplateParameterLists.size() - 1,
6230 TemplateParameterLists.data());
6231 }
6232
6233 // Create a new class template partial specialization declaration node.
6234 ClassTemplatePartialSpecializationDecl *PrevPartial
6235 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6236 ClassTemplatePartialSpecializationDecl *Partial
6237 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6238 ClassTemplate->getDeclContext(),
6239 KWLoc, TemplateNameLoc,
6240 TemplateParams,
6241 ClassTemplate,
6242 Converted.data(),
6243 Converted.size(),
6244 TemplateArgs,
6245 CanonType,
6246 PrevPartial);
6247 SetNestedNameSpecifier(Partial, SS);
6248 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6249 Partial->setTemplateParameterListsInfo(Context,
6250 TemplateParameterLists.size() - 1,
6251 TemplateParameterLists.data());
6252 }
6253
6254 if (!PrevPartial)
6255 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6256 Specialization = Partial;
6257
6258 // If we are providing an explicit specialization of a member class
6259 // template specialization, make a note of that.
6260 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6261 PrevPartial->setMemberSpecialization();
6262
6263 // Check that all of the template parameters of the class template
6264 // partial specialization are deducible from the template
6265 // arguments. If not, this class template partial specialization
6266 // will never be used.
6267 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6268 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6269 TemplateParams->getDepth(),
6270 DeducibleParams);
6271
6272 if (!DeducibleParams.all()) {
6273 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6274 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6275 << /*class template*/0 << (NumNonDeducible > 1)
6276 << SourceRange(TemplateNameLoc, RAngleLoc);
6277 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6278 if (!DeducibleParams[I]) {
6279 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6280 if (Param->getDeclName())
6281 Diag(Param->getLocation(),
6282 diag::note_partial_spec_unused_parameter)
6283 << Param->getDeclName();
6284 else
6285 Diag(Param->getLocation(),
6286 diag::note_partial_spec_unused_parameter)
6287 << "(anonymous)";
6288 }
6289 }
6290 }
6291 } else {
6292 // Create a new class template specialization declaration node for
6293 // this explicit specialization or friend declaration.
6294 Specialization
6295 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6296 ClassTemplate->getDeclContext(),
6297 KWLoc, TemplateNameLoc,
6298 ClassTemplate,
6299 Converted.data(),
6300 Converted.size(),
6301 PrevDecl);
6302 SetNestedNameSpecifier(Specialization, SS);
6303 if (TemplateParameterLists.size() > 0) {
6304 Specialization->setTemplateParameterListsInfo(Context,
6305 TemplateParameterLists.size(),
6306 TemplateParameterLists.data());
6307 }
6308
6309 if (!PrevDecl)
6310 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6311
6312 CanonType = Context.getTypeDeclType(Specialization);
6313 }
6314
6315 // C++ [temp.expl.spec]p6:
6316 // If a template, a member template or the member of a class template is
6317 // explicitly specialized then that specialization shall be declared
6318 // before the first use of that specialization that would cause an implicit
6319 // instantiation to take place, in every translation unit in which such a
6320 // use occurs; no diagnostic is required.
6321 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6322 bool Okay = false;
6323 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6324 // Is there any previous explicit specialization declaration?
6325 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6326 Okay = true;
6327 break;
6328 }
6329 }
6330
6331 if (!Okay) {
6332 SourceRange Range(TemplateNameLoc, RAngleLoc);
6333 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6334 << Context.getTypeDeclType(Specialization) << Range;
6335
6336 Diag(PrevDecl->getPointOfInstantiation(),
6337 diag::note_instantiation_required_here)
6338 << (PrevDecl->getTemplateSpecializationKind()
6339 != TSK_ImplicitInstantiation);
6340 return true;
6341 }
6342 }
6343
6344 // If this is not a friend, note that this is an explicit specialization.
6345 if (TUK != TUK_Friend)
6346 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6347
6348 // Check that this isn't a redefinition of this specialization.
6349 if (TUK == TUK_Definition) {
6350 if (RecordDecl *Def = Specialization->getDefinition()) {
6351 SourceRange Range(TemplateNameLoc, RAngleLoc);
6352 Diag(TemplateNameLoc, diag::err_redefinition)
6353 << Context.getTypeDeclType(Specialization) << Range;
6354 Diag(Def->getLocation(), diag::note_previous_definition);
6355 Specialization->setInvalidDecl();
6356 return true;
6357 }
6358 }
6359
6360 if (Attr)
6361 ProcessDeclAttributeList(S, Specialization, Attr);
6362
6363 // Add alignment attributes if necessary; these attributes are checked when
6364 // the ASTContext lays out the structure.
6365 if (TUK == TUK_Definition) {
6366 AddAlignmentAttributesForRecord(Specialization);
6367 AddMsStructLayoutForRecord(Specialization);
6368 }
6369
6370 if (ModulePrivateLoc.isValid())
6371 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6372 << (isPartialSpecialization? 1 : 0)
6373 << FixItHint::CreateRemoval(ModulePrivateLoc);
6374
6375 // Build the fully-sugared type for this class template
6376 // specialization as the user wrote in the specialization
6377 // itself. This means that we'll pretty-print the type retrieved
6378 // from the specialization's declaration the way that the user
6379 // actually wrote the specialization, rather than formatting the
6380 // name based on the "canonical" representation used to store the
6381 // template arguments in the specialization.
6382 TypeSourceInfo *WrittenTy
6383 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6384 TemplateArgs, CanonType);
6385 if (TUK != TUK_Friend) {
6386 Specialization->setTypeAsWritten(WrittenTy);
6387 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6388 }
6389
6390 // C++ [temp.expl.spec]p9:
6391 // A template explicit specialization is in the scope of the
6392 // namespace in which the template was defined.
6393 //
6394 // We actually implement this paragraph where we set the semantic
6395 // context (in the creation of the ClassTemplateSpecializationDecl),
6396 // but we also maintain the lexical context where the actual
6397 // definition occurs.
6398 Specialization->setLexicalDeclContext(CurContext);
6399
6400 // We may be starting the definition of this specialization.
6401 if (TUK == TUK_Definition)
6402 Specialization->startDefinition();
6403
6404 if (TUK == TUK_Friend) {
6405 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6406 TemplateNameLoc,
6407 WrittenTy,
6408 /*FIXME:*/KWLoc);
6409 Friend->setAccess(AS_public);
6410 CurContext->addDecl(Friend);
6411 } else {
6412 // Add the specialization into its lexical context, so that it can
6413 // be seen when iterating through the list of declarations in that
6414 // context. However, specializations are not found by name lookup.
6415 CurContext->addDecl(Specialization);
6416 }
6417 return Specialization;
6418}
6419
6420Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6421 MultiTemplateParamsArg TemplateParameterLists,
6422 Declarator &D) {
6423 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6424 ActOnDocumentableDecl(NewDecl);
6425 return NewDecl;
6426}
6427
6428Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
6429 MultiTemplateParamsArg TemplateParameterLists,
6430 Declarator &D) {
6431 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
6432 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6433
6434 if (FTI.hasPrototype) {
6435 // FIXME: Diagnose arguments without names in C.
6436 }
6437
6438 Scope *ParentScope = FnBodyScope->getParent();
6439
6440 D.setFunctionDefinitionKind(FDK_Definition);
6441 Decl *DP = HandleDeclarator(ParentScope, D,
6442 TemplateParameterLists);
6443 return ActOnStartOfFunctionDef(FnBodyScope, DP);
6444}
6445
6446/// \brief Strips various properties off an implicit instantiation
6447/// that has just been explicitly specialized.
6448static void StripImplicitInstantiation(NamedDecl *D) {
6449 D->dropAttr<DLLImportAttr>();
6450 D->dropAttr<DLLExportAttr>();
6451
6452 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6453 FD->setInlineSpecified(false);
6454}
6455
6456/// \brief Compute the diagnostic location for an explicit instantiation
6457// declaration or definition.
6458static SourceLocation DiagLocForExplicitInstantiation(
6459 NamedDecl* D, SourceLocation PointOfInstantiation) {
6460 // Explicit instantiations following a specialization have no effect and
6461 // hence no PointOfInstantiation. In that case, walk decl backwards
6462 // until a valid name loc is found.
6463 SourceLocation PrevDiagLoc = PointOfInstantiation;
6464 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6465 Prev = Prev->getPreviousDecl()) {
6466 PrevDiagLoc = Prev->getLocation();
6467 }
6468 assert(PrevDiagLoc.isValid() &&
6469 "Explicit instantiation without point of instantiation?");
6470 return PrevDiagLoc;
6471}
6472
6473/// \brief Diagnose cases where we have an explicit template specialization
6474/// before/after an explicit template instantiation, producing diagnostics
6475/// for those cases where they are required and determining whether the
6476/// new specialization/instantiation will have any effect.
6477///
6478/// \param NewLoc the location of the new explicit specialization or
6479/// instantiation.
6480///
6481/// \param NewTSK the kind of the new explicit specialization or instantiation.
6482///
6483/// \param PrevDecl the previous declaration of the entity.
6484///
6485/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6486///
6487/// \param PrevPointOfInstantiation if valid, indicates where the previus
6488/// declaration was instantiated (either implicitly or explicitly).
6489///
6490/// \param HasNoEffect will be set to true to indicate that the new
6491/// specialization or instantiation has no effect and should be ignored.
6492///
6493/// \returns true if there was an error that should prevent the introduction of
6494/// the new declaration into the AST, false otherwise.
6495bool
6496Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6497 TemplateSpecializationKind NewTSK,
6498 NamedDecl *PrevDecl,
6499 TemplateSpecializationKind PrevTSK,
6500 SourceLocation PrevPointOfInstantiation,
6501 bool &HasNoEffect) {
6502 HasNoEffect = false;
6503
6504 switch (NewTSK) {
6505 case TSK_Undeclared:
6506 case TSK_ImplicitInstantiation:
6507 assert(
6508 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6509 "previous declaration must be implicit!");
6510 return false;
6511
6512 case TSK_ExplicitSpecialization:
6513 switch (PrevTSK) {
6514 case TSK_Undeclared:
6515 case TSK_ExplicitSpecialization:
6516 // Okay, we're just specializing something that is either already
6517 // explicitly specialized or has merely been mentioned without any
6518 // instantiation.
6519 return false;
6520
6521 case TSK_ImplicitInstantiation:
6522 if (PrevPointOfInstantiation.isInvalid()) {
6523 // The declaration itself has not actually been instantiated, so it is
6524 // still okay to specialize it.
6525 StripImplicitInstantiation(PrevDecl);
6526 return false;
6527 }
6528 // Fall through
6529
6530 case TSK_ExplicitInstantiationDeclaration:
6531 case TSK_ExplicitInstantiationDefinition:
6532 assert((PrevTSK == TSK_ImplicitInstantiation ||
6533 PrevPointOfInstantiation.isValid()) &&
6534 "Explicit instantiation without point of instantiation?");
6535
6536 // C++ [temp.expl.spec]p6:
6537 // If a template, a member template or the member of a class template
6538 // is explicitly specialized then that specialization shall be declared
6539 // before the first use of that specialization that would cause an
6540 // implicit instantiation to take place, in every translation unit in
6541 // which such a use occurs; no diagnostic is required.
6542 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6543 // Is there any previous explicit specialization declaration?
6544 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6545 return false;
6546 }
6547
6548 Diag(NewLoc, diag::err_specialization_after_instantiation)
6549 << PrevDecl;
6550 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6551 << (PrevTSK != TSK_ImplicitInstantiation);
6552
6553 return true;
6554 }
6555
6556 case TSK_ExplicitInstantiationDeclaration:
6557 switch (PrevTSK) {
6558 case TSK_ExplicitInstantiationDeclaration:
6559 // This explicit instantiation declaration is redundant (that's okay).
6560 HasNoEffect = true;
6561 return false;
6562
6563 case TSK_Undeclared:
6564 case TSK_ImplicitInstantiation:
6565 // We're explicitly instantiating something that may have already been
6566 // implicitly instantiated; that's fine.
6567 return false;
6568
6569 case TSK_ExplicitSpecialization:
6570 // C++0x [temp.explicit]p4:
6571 // For a given set of template parameters, if an explicit instantiation
6572 // of a template appears after a declaration of an explicit
6573 // specialization for that template, the explicit instantiation has no
6574 // effect.
6575 HasNoEffect = true;
6576 return false;
6577
6578 case TSK_ExplicitInstantiationDefinition:
6579 // C++0x [temp.explicit]p10:
6580 // If an entity is the subject of both an explicit instantiation
6581 // declaration and an explicit instantiation definition in the same
6582 // translation unit, the definition shall follow the declaration.
6583 Diag(NewLoc,
6584 diag::err_explicit_instantiation_declaration_after_definition);
6585
6586 // Explicit instantiations following a specialization have no effect and
6587 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6588 // until a valid name loc is found.
6589 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6590 diag::note_explicit_instantiation_definition_here);
6591 HasNoEffect = true;
6592 return false;
6593 }
6594
6595 case TSK_ExplicitInstantiationDefinition:
6596 switch (PrevTSK) {
6597 case TSK_Undeclared:
6598 case TSK_ImplicitInstantiation:
6599 // We're explicitly instantiating something that may have already been
6600 // implicitly instantiated; that's fine.
6601 return false;
6602
6603 case TSK_ExplicitSpecialization:
6604 // C++ DR 259, C++0x [temp.explicit]p4:
6605 // For a given set of template parameters, if an explicit
6606 // instantiation of a template appears after a declaration of
6607 // an explicit specialization for that template, the explicit
6608 // instantiation has no effect.
6609 //
6610 // In C++98/03 mode, we only give an extension warning here, because it
6611 // is not harmful to try to explicitly instantiate something that
6612 // has been explicitly specialized.
6613 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6614 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6615 diag::ext_explicit_instantiation_after_specialization)
6616 << PrevDecl;
6617 Diag(PrevDecl->getLocation(),
6618 diag::note_previous_template_specialization);
6619 HasNoEffect = true;
6620 return false;
6621
6622 case TSK_ExplicitInstantiationDeclaration:
6623 // We're explicity instantiating a definition for something for which we
6624 // were previously asked to suppress instantiations. That's fine.
6625
6626 // C++0x [temp.explicit]p4:
6627 // For a given set of template parameters, if an explicit instantiation
6628 // of a template appears after a declaration of an explicit
6629 // specialization for that template, the explicit instantiation has no
6630 // effect.
6631 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6632 // Is there any previous explicit specialization declaration?
6633 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6634 HasNoEffect = true;
6635 break;
6636 }
6637 }
6638
6639 return false;
6640
6641 case TSK_ExplicitInstantiationDefinition:
6642 // C++0x [temp.spec]p5:
6643 // For a given template and a given set of template-arguments,
6644 // - an explicit instantiation definition shall appear at most once
6645 // in a program,
6646
6647 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6648 Diag(NewLoc, (getLangOpts().MSVCCompat)
6649 ? diag::ext_explicit_instantiation_duplicate
6650 : diag::err_explicit_instantiation_duplicate)
6651 << PrevDecl;
6652 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6653 diag::note_previous_explicit_instantiation);
6654 HasNoEffect = true;
6655 return false;
6656 }
6657 }
6658
6659 llvm_unreachable("Missing specialization/instantiation case?");
6660}
6661
6662/// \brief Perform semantic analysis for the given dependent function
6663/// template specialization.
6664///
6665/// The only possible way to get a dependent function template specialization
6666/// is with a friend declaration, like so:
6667///
6668/// \code
6669/// template \<class T> void foo(T);
6670/// template \<class T> class A {
6671/// friend void foo<>(T);
6672/// };
6673/// \endcode
6674///
6675/// There really isn't any useful analysis we can do here, so we
6676/// just store the information.
6677bool
6678Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6679 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6680 LookupResult &Previous) {
6681 // Remove anything from Previous that isn't a function template in
6682 // the correct context.
6683 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6684 LookupResult::Filter F = Previous.makeFilter();
6685 while (F.hasNext()) {
6686 NamedDecl *D = F.next()->getUnderlyingDecl();
6687 if (!isa<FunctionTemplateDecl>(D) ||
6688 !FDLookupContext->InEnclosingNamespaceSetOf(
6689 D->getDeclContext()->getRedeclContext()))
6690 F.erase();
6691 }
6692 F.done();
6693
6694 // Should this be diagnosed here?
6695 if (Previous.empty()) return true;
6696
6697 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6698 ExplicitTemplateArgs);
6699 return false;
6700}
6701
6702/// \brief Perform semantic analysis for the given function template
6703/// specialization.
6704///
6705/// This routine performs all of the semantic analysis required for an
6706/// explicit function template specialization. On successful completion,
6707/// the function declaration \p FD will become a function template
6708/// specialization.
6709///
6710/// \param FD the function declaration, which will be updated to become a
6711/// function template specialization.
6712///
6713/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6714/// if any. Note that this may be valid info even when 0 arguments are
6715/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6716/// as it anyway contains info on the angle brackets locations.
6717///
6718/// \param Previous the set of declarations that may be specialized by
6719/// this function specialization.
6720bool Sema::CheckFunctionTemplateSpecialization(
6721 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6722 LookupResult &Previous) {
6723 // The set of function template specializations that could match this
6724 // explicit function template specialization.
6725 UnresolvedSet<8> Candidates;
6726 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
6727
6728 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6729 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6730 I != E; ++I) {
6731 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6732 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6733 // Only consider templates found within the same semantic lookup scope as
6734 // FD.
6735 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6736 Ovl->getDeclContext()->getRedeclContext()))
6737 continue;
6738
6739 // When matching a constexpr member function template specialization
6740 // against the primary template, we don't yet know whether the
6741 // specialization has an implicit 'const' (because we don't know whether
6742 // it will be a static member function until we know which template it
6743 // specializes), so adjust it now assuming it specializes this template.
6744 QualType FT = FD->getType();
6745 if (FD->isConstexpr()) {
6746 CXXMethodDecl *OldMD =
6747 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6748 if (OldMD && OldMD->isConst()) {
6749 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6750 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6751 EPI.TypeQuals |= Qualifiers::Const;
6752 FT = Context.getFunctionType(FPT->getReturnType(),
6753 FPT->getParamTypes(), EPI);
6754 }
6755 }
6756
6757 // C++ [temp.expl.spec]p11:
6758 // A trailing template-argument can be left unspecified in the
6759 // template-id naming an explicit function template specialization
6760 // provided it can be deduced from the function argument type.
6761 // Perform template argument deduction to determine whether we may be
6762 // specializing this template.
6763 // FIXME: It is somewhat wasteful to build
6764 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6765 FunctionDecl *Specialization = nullptr;
6766 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6767 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6768 ExplicitTemplateArgs, FT, Specialization, Info)) {
6769 // Template argument deduction failed; record why it failed, so
6770 // that we can provide nifty diagnostics.
6771 FailedCandidates.addCandidate()
6772 .set(FunTmpl->getTemplatedDecl(),
6773 MakeDeductionFailureInfo(Context, TDK, Info));
6774 (void)TDK;
6775 continue;
6776 }
6777
6778 // Record this candidate.
6779 Candidates.addDecl(Specialization, I.getAccess());
6780 }
6781 }
6782
6783 // Find the most specialized function template.
6784 UnresolvedSetIterator Result = getMostSpecialized(
6785 Candidates.begin(), Candidates.end(), FailedCandidates,
6786 FD->getLocation(),
6787 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6788 PDiag(diag::err_function_template_spec_ambiguous)
6789 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6790 PDiag(diag::note_function_template_spec_matched));
6791
6792 if (Result == Candidates.end())
6793 return true;
6794
6795 // Ignore access information; it doesn't figure into redeclaration checking.
6796 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6797
6798 FunctionTemplateSpecializationInfo *SpecInfo
6799 = Specialization->getTemplateSpecializationInfo();
6800 assert(SpecInfo && "Function template specialization info missing?");
6801
6802 // Note: do not overwrite location info if previous template
6803 // specialization kind was explicit.
6804 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6805 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6806 Specialization->setLocation(FD->getLocation());
6807 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6808 // function can differ from the template declaration with respect to
6809 // the constexpr specifier.
6810 Specialization->setConstexpr(FD->isConstexpr());
6811 }
6812
6813 // FIXME: Check if the prior specialization has a point of instantiation.
6814 // If so, we have run afoul of .
6815
6816 // If this is a friend declaration, then we're not really declaring
6817 // an explicit specialization.
6818 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6819
6820 // Check the scope of this explicit specialization.
6821 if (!isFriend &&
6822 CheckTemplateSpecializationScope(*this,
6823 Specialization->getPrimaryTemplate(),
6824 Specialization, FD->getLocation(),
6825 false))
6826 return true;
6827
6828 // C++ [temp.expl.spec]p6:
6829 // If a template, a member template or the member of a class template is
6830 // explicitly specialized then that specialization shall be declared
6831 // before the first use of that specialization that would cause an implicit
6832 // instantiation to take place, in every translation unit in which such a
6833 // use occurs; no diagnostic is required.
6834 bool HasNoEffect = false;
6835 if (!isFriend &&
6836 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6837 TSK_ExplicitSpecialization,
6838 Specialization,
6839 SpecInfo->getTemplateSpecializationKind(),
6840 SpecInfo->getPointOfInstantiation(),
6841 HasNoEffect))
6842 return true;
6843
6844 // Mark the prior declaration as an explicit specialization, so that later
6845 // clients know that this is an explicit specialization.
6846 if (!isFriend) {
6847 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6848 MarkUnusedFileScopedDecl(Specialization);
6849 }
6850
6851 // Turn the given function declaration into a function template
6852 // specialization, with the template arguments from the previous
6853 // specialization.
6854 // Take copies of (semantic and syntactic) template argument lists.
6855 const TemplateArgumentList* TemplArgs = new (Context)
6856 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6857 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6858 TemplArgs, /*InsertPos=*/nullptr,
6859 SpecInfo->getTemplateSpecializationKind(),
6860 ExplicitTemplateArgs);
6861
6862 // The "previous declaration" for this function template specialization is
6863 // the prior function template specialization.
6864 Previous.clear();
6865 Previous.addDecl(Specialization);
6866 return false;
6867}
6868
6869/// \brief Perform semantic analysis for the given non-template member
6870/// specialization.
6871///
6872/// This routine performs all of the semantic analysis required for an
6873/// explicit member function specialization. On successful completion,
6874/// the function declaration \p FD will become a member function
6875/// specialization.
6876///
6877/// \param Member the member declaration, which will be updated to become a
6878/// specialization.
6879///
6880/// \param Previous the set of declarations, one of which may be specialized
6881/// by this function specialization; the set will be modified to contain the
6882/// redeclared member.
6883bool
6884Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6885 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6886
6887 // Try to find the member we are instantiating.
6888 NamedDecl *Instantiation = nullptr;
6889 NamedDecl *InstantiatedFrom = nullptr;
6890 MemberSpecializationInfo *MSInfo = nullptr;
6891
6892 if (Previous.empty()) {
6893 // Nowhere to look anyway.
6894 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6895 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6896 I != E; ++I) {
6897 NamedDecl *D = (*I)->getUnderlyingDecl();
6898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6899 QualType Adjusted = Function->getType();
6900 if (!hasExplicitCallingConv(Adjusted))
6901 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6902 if (Context.hasSameType(Adjusted, Method->getType())) {
6903 Instantiation = Method;
6904 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6905 MSInfo = Method->getMemberSpecializationInfo();
6906 break;
6907 }
6908 }
6909 }
6910 } else if (isa<VarDecl>(Member)) {
6911 VarDecl *PrevVar;
6912 if (Previous.isSingleResult() &&
6913 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6914 if (PrevVar->isStaticDataMember()) {
6915 Instantiation = PrevVar;
6916 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6917 MSInfo = PrevVar->getMemberSpecializationInfo();
6918 }
6919 } else if (isa<RecordDecl>(Member)) {
6920 CXXRecordDecl *PrevRecord;
6921 if (Previous.isSingleResult() &&
6922 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6923 Instantiation = PrevRecord;
6924 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6925 MSInfo = PrevRecord->getMemberSpecializationInfo();
6926 }
6927 } else if (isa<EnumDecl>(Member)) {
6928 EnumDecl *PrevEnum;
6929 if (Previous.isSingleResult() &&
6930 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6931 Instantiation = PrevEnum;
6932 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6933 MSInfo = PrevEnum->getMemberSpecializationInfo();
6934 }
6935 }
6936
6937 if (!Instantiation) {
6938 // There is no previous declaration that matches. Since member
6939 // specializations are always out-of-line, the caller will complain about
6940 // this mismatch later.
6941 return false;
6942 }
6943
6944 // If this is a friend, just bail out here before we start turning
6945 // things into explicit specializations.
6946 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6947 // Preserve instantiation information.
6948 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6949 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6950 cast<CXXMethodDecl>(InstantiatedFrom),
6951 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6952 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6953 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6954 cast<CXXRecordDecl>(InstantiatedFrom),
6955 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6956 }
6957
6958 Previous.clear();
6959 Previous.addDecl(Instantiation);
6960 return false;
6961 }
6962
6963 // Make sure that this is a specialization of a member.
6964 if (!InstantiatedFrom) {
6965 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6966 << Member;
6967 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6968 return true;
6969 }
6970
6971 // C++ [temp.expl.spec]p6:
6972 // If a template, a member template or the member of a class template is
6973 // explicitly specialized then that specialization shall be declared
6974 // before the first use of that specialization that would cause an implicit
6975 // instantiation to take place, in every translation unit in which such a
6976 // use occurs; no diagnostic is required.
6977 assert(MSInfo && "Member specialization info missing?");
6978
6979 bool HasNoEffect = false;
6980 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6981 TSK_ExplicitSpecialization,
6982 Instantiation,
6983 MSInfo->getTemplateSpecializationKind(),
6984 MSInfo->getPointOfInstantiation(),
6985 HasNoEffect))
6986 return true;
6987
6988 // Check the scope of this explicit specialization.
6989 if (CheckTemplateSpecializationScope(*this,
6990 InstantiatedFrom,
6991 Instantiation, Member->getLocation(),
6992 false))
6993 return true;
6994
6995 // Note that this is an explicit instantiation of a member.
6996 // the original declaration to note that it is an explicit specialization
6997 // (if it was previously an implicit instantiation). This latter step
6998 // makes bookkeeping easier.
6999 if (isa<FunctionDecl>(Member)) {
7000 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7001 if (InstantiationFunction->getTemplateSpecializationKind() ==
7002 TSK_ImplicitInstantiation) {
7003 InstantiationFunction->setTemplateSpecializationKind(
7004 TSK_ExplicitSpecialization);
7005 InstantiationFunction->setLocation(Member->getLocation());
7006 }
7007
7008 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7009 cast<CXXMethodDecl>(InstantiatedFrom),
7010 TSK_ExplicitSpecialization);
7011 MarkUnusedFileScopedDecl(InstantiationFunction);
7012 } else if (isa<VarDecl>(Member)) {
7013 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7014 if (InstantiationVar->getTemplateSpecializationKind() ==
7015 TSK_ImplicitInstantiation) {
7016 InstantiationVar->setTemplateSpecializationKind(
7017 TSK_ExplicitSpecialization);
7018 InstantiationVar->setLocation(Member->getLocation());
7019 }
7020
7021 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7022 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7023 MarkUnusedFileScopedDecl(InstantiationVar);
7024 } else if (isa<CXXRecordDecl>(Member)) {
7025 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7026 if (InstantiationClass->getTemplateSpecializationKind() ==
7027 TSK_ImplicitInstantiation) {
7028 InstantiationClass->setTemplateSpecializationKind(
7029 TSK_ExplicitSpecialization);
7030 InstantiationClass->setLocation(Member->getLocation());
7031 }
7032
7033 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7034 cast<CXXRecordDecl>(InstantiatedFrom),
7035 TSK_ExplicitSpecialization);
7036 } else {
7037 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7038 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7039 if (InstantiationEnum->getTemplateSpecializationKind() ==
7040 TSK_ImplicitInstantiation) {
7041 InstantiationEnum->setTemplateSpecializationKind(
7042 TSK_ExplicitSpecialization);
7043 InstantiationEnum->setLocation(Member->getLocation());
7044 }
7045
7046 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7047 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7048 }
7049
7050 // Save the caller the trouble of having to figure out which declaration
7051 // this specialization matches.
7052 Previous.clear();
7053 Previous.addDecl(Instantiation);
7054 return false;
7055}
7056
7057/// \brief Check the scope of an explicit instantiation.
7058///
7059/// \returns true if a serious error occurs, false otherwise.
7060static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7061 SourceLocation InstLoc,
7062 bool WasQualifiedName) {
7063 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7064 DeclContext *CurContext = S.CurContext->getRedeclContext();
7065
7066 if (CurContext->isRecord()) {
7067 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7068 << D;
7069 return true;
7070 }
7071
7072 // C++11 [temp.explicit]p3:
7073 // An explicit instantiation shall appear in an enclosing namespace of its
7074 // template. If the name declared in the explicit instantiation is an
7075 // unqualified name, the explicit instantiation shall appear in the
7076 // namespace where its template is declared or, if that namespace is inline
7077 // (7.3.1), any namespace from its enclosing namespace set.
7078 //
7079 // This is DR275, which we do not retroactively apply to C++98/03.
7080 if (WasQualifiedName) {
7081 if (CurContext->Encloses(OrigContext))
7082 return false;
7083 } else {
7084 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7085 return false;
7086 }
7087
7088 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7089 if (WasQualifiedName)
7090 S.Diag(InstLoc,
7091 S.getLangOpts().CPlusPlus11?
7092 diag::err_explicit_instantiation_out_of_scope :
7093 diag::warn_explicit_instantiation_out_of_scope_0x)
7094 << D << NS;
7095 else
7096 S.Diag(InstLoc,
7097 S.getLangOpts().CPlusPlus11?
7098 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7099 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7100 << D << NS;
7101 } else
7102 S.Diag(InstLoc,
7103 S.getLangOpts().CPlusPlus11?
7104 diag::err_explicit_instantiation_must_be_global :
7105 diag::warn_explicit_instantiation_must_be_global_0x)
7106 << D;
7107 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7108 return false;
7109}
7110
7111/// \brief Determine whether the given scope specifier has a template-id in it.
7112static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7113 if (!SS.isSet())
7114 return false;
7115
7116 // C++11 [temp.explicit]p3:
7117 // If the explicit instantiation is for a member function, a member class
7118 // or a static data member of a class template specialization, the name of
7119 // the class template specialization in the qualified-id for the member
7120 // name shall be a simple-template-id.
7121 //
7122 // C++98 has the same restriction, just worded differently.
7123 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7124 NNS = NNS->getPrefix())
7125 if (const Type *T = NNS->getAsType())
7126 if (isa<TemplateSpecializationType>(T))
7127 return true;
7128
7129 return false;
7130}
7131
7132// Explicit instantiation of a class template specialization
7133DeclResult
7134Sema::ActOnExplicitInstantiation(Scope *S,
7135 SourceLocation ExternLoc,
7136 SourceLocation TemplateLoc,
7137 unsigned TagSpec,
7138 SourceLocation KWLoc,
7139 const CXXScopeSpec &SS,
7140 TemplateTy TemplateD,
7141 SourceLocation TemplateNameLoc,
7142 SourceLocation LAngleLoc,
7143 ASTTemplateArgsPtr TemplateArgsIn,
7144 SourceLocation RAngleLoc,
7145 AttributeList *Attr) {
7146 // Find the class template we're specializing
7147 TemplateName Name = TemplateD.get();
7148 TemplateDecl *TD = Name.getAsTemplateDecl();
7149 // Check that the specialization uses the same tag kind as the
7150 // original template.
7151 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7152 assert(Kind != TTK_Enum &&
7153 "Invalid enum tag in class template explicit instantiation!");
7154
7155 if (isa<TypeAliasTemplateDecl>(TD)) {
7156 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7157 Diag(TD->getTemplatedDecl()->getLocation(),
7158 diag::note_previous_use);
7159 return true;
7160 }
7161
7162 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7163
7164 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7165 Kind, /*isDefinition*/false, KWLoc,
7166 *ClassTemplate->getIdentifier())) {
7167 Diag(KWLoc, diag::err_use_with_wrong_tag)
7168 << ClassTemplate
7169 << FixItHint::CreateReplacement(KWLoc,
7170 ClassTemplate->getTemplatedDecl()->getKindName());
7171 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7172 diag::note_previous_use);
7173 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7174 }
7175
7176 // C++0x [temp.explicit]p2:
7177 // There are two forms of explicit instantiation: an explicit instantiation
7178 // definition and an explicit instantiation declaration. An explicit
7179 // instantiation declaration begins with the extern keyword. [...]
7180 TemplateSpecializationKind TSK
7181 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7182 : TSK_ExplicitInstantiationDeclaration;
7183
7184 // Translate the parser's template argument list in our AST format.
7185 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7186 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7187
7188 // Check that the template argument list is well-formed for this
7189 // template.
7190 SmallVector<TemplateArgument, 4> Converted;
7191 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7192 TemplateArgs, false, Converted))
7193 return true;
7194
7195 // Find the class template specialization declaration that
7196 // corresponds to these arguments.
7197 void *InsertPos = nullptr;
7198 ClassTemplateSpecializationDecl *PrevDecl
7199 = ClassTemplate->findSpecialization(Converted, InsertPos);
7200
7201 TemplateSpecializationKind PrevDecl_TSK
7202 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7203
7204 // C++0x [temp.explicit]p2:
7205 // [...] An explicit instantiation shall appear in an enclosing
7206 // namespace of its template. [...]
7207 //
7208 // This is C++ DR 275.
7209 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7210 SS.isSet()))
7211 return true;
7212
7213 ClassTemplateSpecializationDecl *Specialization = nullptr;
7214
7215 bool HasNoEffect = false;
7216 if (PrevDecl) {
7217 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7218 PrevDecl, PrevDecl_TSK,
7219 PrevDecl->getPointOfInstantiation(),
7220 HasNoEffect))
7221 return PrevDecl;
7222
7223 // Even though HasNoEffect == true means that this explicit instantiation
7224 // has no effect on semantics, we go on to put its syntax in the AST.
7225
7226 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7227 PrevDecl_TSK == TSK_Undeclared) {
7228 // Since the only prior class template specialization with these
7229 // arguments was referenced but not declared, reuse that
7230 // declaration node as our own, updating the source location
7231 // for the template name to reflect our new declaration.
7232 // (Other source locations will be updated later.)
7233 Specialization = PrevDecl;
7234 Specialization->setLocation(TemplateNameLoc);
7235 PrevDecl = nullptr;
7236 }
7237 }
7238
7239 if (!Specialization) {
7240 // Create a new class template specialization declaration node for
7241 // this explicit specialization.
7242 Specialization
7243 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7244 ClassTemplate->getDeclContext(),
7245 KWLoc, TemplateNameLoc,
7246 ClassTemplate,
7247 Converted.data(),
7248 Converted.size(),
7249 PrevDecl);
7250 SetNestedNameSpecifier(Specialization, SS);
7251
7252 if (!HasNoEffect && !PrevDecl) {
7253 // Insert the new specialization.
7254 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7255 }
7256 }
7257
7258 // Build the fully-sugared type for this explicit instantiation as
7259 // the user wrote in the explicit instantiation itself. This means
7260 // that we'll pretty-print the type retrieved from the
7261 // specialization's declaration the way that the user actually wrote
7262 // the explicit instantiation, rather than formatting the name based
7263 // on the "canonical" representation used to store the template
7264 // arguments in the specialization.
7265 TypeSourceInfo *WrittenTy
7266 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7267 TemplateArgs,
7268 Context.getTypeDeclType(Specialization));
7269 Specialization->setTypeAsWritten(WrittenTy);
7270
7271 // Set source locations for keywords.
7272 Specialization->setExternLoc(ExternLoc);
7273 Specialization->setTemplateKeywordLoc(TemplateLoc);
7274 Specialization->setRBraceLoc(SourceLocation());
7275
7276 if (Attr)
7277 ProcessDeclAttributeList(S, Specialization, Attr);
7278
7279 // Add the explicit instantiation into its lexical context. However,
7280 // since explicit instantiations are never found by name lookup, we
7281 // just put it into the declaration context directly.
7282 Specialization->setLexicalDeclContext(CurContext);
7283 CurContext->addDecl(Specialization);
7284
7285 // Syntax is now OK, so return if it has no other effect on semantics.
7286 if (HasNoEffect) {
7287 // Set the template specialization kind.
7288 Specialization->setTemplateSpecializationKind(TSK);
7289 return Specialization;
7290 }
7291
7292 // C++ [temp.explicit]p3:
7293 // A definition of a class template or class member template
7294 // shall be in scope at the point of the explicit instantiation of
7295 // the class template or class member template.
7296 //
7297 // This check comes when we actually try to perform the
7298 // instantiation.
7299 ClassTemplateSpecializationDecl *Def
7300 = cast_or_null<ClassTemplateSpecializationDecl>(
7301 Specialization->getDefinition());
7302 if (!Def)
7303 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7304 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7305 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7306 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7307 }
7308
7309 // Instantiate the members of this class template specialization.
7310 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7311 Specialization->getDefinition());
7312 if (Def) {
7313 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7314
7315 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7316 // TSK_ExplicitInstantiationDefinition
7317 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7318 TSK == TSK_ExplicitInstantiationDefinition)
7319 // FIXME: Need to notify the ASTMutationListener that we did this.
7320 Def->setTemplateSpecializationKind(TSK);
7321
7322 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7323 }
7324
7325 // Set the template specialization kind.
7326 Specialization->setTemplateSpecializationKind(TSK);
7327 return Specialization;
7328}
7329
7330// Explicit instantiation of a member class of a class template.
7331DeclResult
7332Sema::ActOnExplicitInstantiation(Scope *S,
7333 SourceLocation ExternLoc,
7334 SourceLocation TemplateLoc,
7335 unsigned TagSpec,
7336 SourceLocation KWLoc,
7337 CXXScopeSpec &SS,
7338 IdentifierInfo *Name,
7339 SourceLocation NameLoc,
7340 AttributeList *Attr) {
7341
7342 bool Owned = false;
7343 bool IsDependent = false;
7344 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7345 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7346 /*ModulePrivateLoc=*/SourceLocation(),
7347 MultiTemplateParamsArg(), Owned, IsDependent,
7348 SourceLocation(), false, TypeResult(),
7349 /*IsTypeSpecifier*/false);
7350 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7351
7352 if (!TagD)
7353 return true;
7354
7355 TagDecl *Tag = cast<TagDecl>(TagD);
7356 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7357
7358 if (Tag->isInvalidDecl())
7359 return true;
7360
7361 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7362 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7363 if (!Pattern) {
7364 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7365 << Context.getTypeDeclType(Record);
7366 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7367 return true;
7368 }
7369
7370 // C++0x [temp.explicit]p2:
7371 // If the explicit instantiation is for a class or member class, the
7372 // elaborated-type-specifier in the declaration shall include a
7373 // simple-template-id.
7374 //
7375 // C++98 has the same restriction, just worded differently.
7376 if (!ScopeSpecifierHasTemplateId(SS))
7377 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7378 << Record << SS.getRange();
7379
7380 // C++0x [temp.explicit]p2:
7381 // There are two forms of explicit instantiation: an explicit instantiation
7382 // definition and an explicit instantiation declaration. An explicit
7383 // instantiation declaration begins with the extern keyword. [...]
7384 TemplateSpecializationKind TSK
7385 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7386 : TSK_ExplicitInstantiationDeclaration;
7387
7388 // C++0x [temp.explicit]p2:
7389 // [...] An explicit instantiation shall appear in an enclosing
7390 // namespace of its template. [...]
7391 //
7392 // This is C++ DR 275.
7393 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7394
7395 // Verify that it is okay to explicitly instantiate here.
7396 CXXRecordDecl *PrevDecl
7397 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7398 if (!PrevDecl && Record->getDefinition())
7399 PrevDecl = Record;
7400 if (PrevDecl) {
7401 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7402 bool HasNoEffect = false;
7403 assert(MSInfo && "No member specialization information?");
7404 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7405 PrevDecl,
7406 MSInfo->getTemplateSpecializationKind(),
7407 MSInfo->getPointOfInstantiation(),
7408 HasNoEffect))
7409 return true;
7410 if (HasNoEffect)
7411 return TagD;
7412 }
7413
7414 CXXRecordDecl *RecordDef
7415 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7416 if (!RecordDef) {
7417 // C++ [temp.explicit]p3:
7418 // A definition of a member class of a class template shall be in scope
7419 // at the point of an explicit instantiation of the member class.
7420 CXXRecordDecl *Def
7421 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7422 if (!Def) {
7423 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7424 << 0 << Record->getDeclName() << Record->getDeclContext();
7425 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7426 << Pattern;
7427 return true;
7428 } else {
7429 if (InstantiateClass(NameLoc, Record, Def,
7430 getTemplateInstantiationArgs(Record),
7431 TSK))
7432 return true;
7433
7434 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7435 if (!RecordDef)
7436 return true;
7437 }
7438 }
7439
7440 // Instantiate all of the members of the class.
7441 InstantiateClassMembers(NameLoc, RecordDef,
7442 getTemplateInstantiationArgs(Record), TSK);
7443
7444 if (TSK == TSK_ExplicitInstantiationDefinition)
7445 MarkVTableUsed(NameLoc, RecordDef, true);
7446
7447 // FIXME: We don't have any representation for explicit instantiations of
7448 // member classes. Such a representation is not needed for compilation, but it
7449 // should be available for clients that want to see all of the declarations in
7450 // the source code.
7451 return TagD;
7452}
7453
7454DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7455 SourceLocation ExternLoc,
7456 SourceLocation TemplateLoc,
7457 Declarator &D) {
7458 // Explicit instantiations always require a name.
7459 // TODO: check if/when DNInfo should replace Name.
7460 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7461 DeclarationName Name = NameInfo.getName();
7462 if (!Name) {
7463 if (!D.isInvalidType())
7464 Diag(D.getDeclSpec().getLocStart(),
7465 diag::err_explicit_instantiation_requires_name)
7466 << D.getDeclSpec().getSourceRange()
7467 << D.getSourceRange();
7468
7469 return true;
7470 }
7471
7472 // The scope passed in may not be a decl scope. Zip up the scope tree until
7473 // we find one that is.
7474 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7475 (S->getFlags() & Scope::TemplateParamScope) != 0)
7476 S = S->getParent();
7477
7478 // Determine the type of the declaration.
7479 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7480 QualType R = T->getType();
7481 if (R.isNull())
7482 return true;
7483
7484 // C++ [dcl.stc]p1:
7485 // A storage-class-specifier shall not be specified in [...] an explicit
7486 // instantiation (14.7.2) directive.
7487 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7488 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7489 << Name;
7490 return true;
7491 } else if (D.getDeclSpec().getStorageClassSpec()
7492 != DeclSpec::SCS_unspecified) {
7493 // Complain about then remove the storage class specifier.
7494 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7495 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7496
7497 D.getMutableDeclSpec().ClearStorageClassSpecs();
7498 }
7499
7500 // C++0x [temp.explicit]p1:
7501 // [...] An explicit instantiation of a function template shall not use the
7502 // inline or constexpr specifiers.
7503 // Presumably, this also applies to member functions of class templates as
7504 // well.
7505 if (D.getDeclSpec().isInlineSpecified())
7506 Diag(D.getDeclSpec().getInlineSpecLoc(),
7507 getLangOpts().CPlusPlus11 ?
7508 diag::err_explicit_instantiation_inline :
7509 diag::warn_explicit_instantiation_inline_0x)
7510 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7511 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7512 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7513 // not already specified.
7514 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7515 diag::err_explicit_instantiation_constexpr);
7516
7517 // C++0x [temp.explicit]p2:
7518 // There are two forms of explicit instantiation: an explicit instantiation
7519 // definition and an explicit instantiation declaration. An explicit
7520 // instantiation declaration begins with the extern keyword. [...]
7521 TemplateSpecializationKind TSK
7522 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7523 : TSK_ExplicitInstantiationDeclaration;
7524
7525 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7526 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7527
7528 if (!R->isFunctionType()) {
7529 // C++ [temp.explicit]p1:
7530 // A [...] static data member of a class template can be explicitly
7531 // instantiated from the member definition associated with its class
7532 // template.
7533 // C++1y [temp.explicit]p1:
7534 // A [...] variable [...] template specialization can be explicitly
7535 // instantiated from its template.
7536 if (Previous.isAmbiguous())
7537 return true;
7538
7539 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7540 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7541
7542 if (!PrevTemplate) {
7543 if (!Prev || !Prev->isStaticDataMember()) {
7544 // We expect to see a data data member here.
7545 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7546 << Name;
7547 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7548 P != PEnd; ++P)
7549 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7550 return true;
7551 }
7552
7553 if (!Prev->getInstantiatedFromStaticDataMember()) {
7554 // FIXME: Check for explicit specialization?
7555 Diag(D.getIdentifierLoc(),
7556 diag::err_explicit_instantiation_data_member_not_instantiated)
7557 << Prev;
7558 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7559 // FIXME: Can we provide a note showing where this was declared?
7560 return true;
7561 }
7562 } else {
7563 // Explicitly instantiate a variable template.
7564
7565 // C++1y [dcl.spec.auto]p6:
7566 // ... A program that uses auto or decltype(auto) in a context not
7567 // explicitly allowed in this section is ill-formed.
7568 //
7569 // This includes auto-typed variable template instantiations.
7570 if (R->isUndeducedType()) {
7571 Diag(T->getTypeLoc().getLocStart(),
7572 diag::err_auto_not_allowed_var_inst);
7573 return true;
7574 }
7575
7576 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7577 // C++1y [temp.explicit]p3:
7578 // If the explicit instantiation is for a variable, the unqualified-id
7579 // in the declaration shall be a template-id.
7580 Diag(D.getIdentifierLoc(),
7581 diag::err_explicit_instantiation_without_template_id)
7582 << PrevTemplate;
7583 Diag(PrevTemplate->getLocation(),
7584 diag::note_explicit_instantiation_here);
7585 return true;
7586 }
7587
7588 // Translate the parser's template argument list into our AST format.
7589 TemplateArgumentListInfo TemplateArgs =
7590 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7591
7592 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7593 D.getIdentifierLoc(), TemplateArgs);
7594 if (Res.isInvalid())
7595 return true;
7596
7597 // Ignore access control bits, we don't need them for redeclaration
7598 // checking.
7599 Prev = cast<VarDecl>(Res.get());
7600 }
7601
7602 // C++0x [temp.explicit]p2:
7603 // If the explicit instantiation is for a member function, a member class
7604 // or a static data member of a class template specialization, the name of
7605 // the class template specialization in the qualified-id for the member
7606 // name shall be a simple-template-id.
7607 //
7608 // C++98 has the same restriction, just worded differently.
7609 //
7610 // This does not apply to variable template specializations, where the
7611 // template-id is in the unqualified-id instead.
7612 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7613 Diag(D.getIdentifierLoc(),
7614 diag::ext_explicit_instantiation_without_qualified_id)
7615 << Prev << D.getCXXScopeSpec().getRange();
7616
7617 // Check the scope of this explicit instantiation.
7618 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7619
7620 // Verify that it is okay to explicitly instantiate here.
7621 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7622 SourceLocation POI = Prev->getPointOfInstantiation();
7623 bool HasNoEffect = false;
7624 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7625 PrevTSK, POI, HasNoEffect))
7626 return true;
7627
7628 if (!HasNoEffect) {
7629 // Instantiate static data member or variable template.
7630
7631 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7632 if (PrevTemplate) {
7633 // Merge attributes.
7634 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7635 ProcessDeclAttributeList(S, Prev, Attr);
7636 }
7637 if (TSK == TSK_ExplicitInstantiationDefinition)
7638 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7639 }
7640
7641 // Check the new variable specialization against the parsed input.
7642 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7643 Diag(T->getTypeLoc().getLocStart(),
7644 diag::err_invalid_var_template_spec_type)
7645 << 0 << PrevTemplate << R << Prev->getType();
7646 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7647 << 2 << PrevTemplate->getDeclName();
7648 return true;
7649 }
7650
7651 // FIXME: Create an ExplicitInstantiation node?
7652 return (Decl*) nullptr;
7653 }
7654
7655 // If the declarator is a template-id, translate the parser's template
7656 // argument list into our AST format.
7657 bool HasExplicitTemplateArgs = false;
7658 TemplateArgumentListInfo TemplateArgs;
7659 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7660 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7661 HasExplicitTemplateArgs = true;
7662 }
7663
7664 // C++ [temp.explicit]p1:
7665 // A [...] function [...] can be explicitly instantiated from its template.
7666 // A member function [...] of a class template can be explicitly
7667 // instantiated from the member definition associated with its class
7668 // template.
7669 UnresolvedSet<8> Matches;
7670 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7671 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7672 P != PEnd; ++P) {
7673 NamedDecl *Prev = *P;
7674 if (!HasExplicitTemplateArgs) {
7675 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7676 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7677 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7678 Matches.clear();
7679
7680 Matches.addDecl(Method, P.getAccess());
7681 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7682 break;
7683 }
7684 }
7685 }
7686
7687 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7688 if (!FunTmpl)
7689 continue;
7690
7691 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7692 FunctionDecl *Specialization = nullptr;
7693 if (TemplateDeductionResult TDK
7694 = DeduceTemplateArguments(FunTmpl,
7695 (HasExplicitTemplateArgs ? &TemplateArgs
7696 : nullptr),
7697 R, Specialization, Info)) {
7698 // Keep track of almost-matches.
7699 FailedCandidates.addCandidate()
7700 .set(FunTmpl->getTemplatedDecl(),
7701 MakeDeductionFailureInfo(Context, TDK, Info));
7702 (void)TDK;
7703 continue;
7704 }
7705
7706 Matches.addDecl(Specialization, P.getAccess());
7707 }
7708
7709 // Find the most specialized function template specialization.
7710 UnresolvedSetIterator Result = getMostSpecialized(
7711 Matches.begin(), Matches.end(), FailedCandidates,
7712 D.getIdentifierLoc(),
7713 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7714 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7715 PDiag(diag::note_explicit_instantiation_candidate));
7716
7717 if (Result == Matches.end())
7718 return true;
7719
7720 // Ignore access control bits, we don't need them for redeclaration checking.
7721 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7722
7723 // C++11 [except.spec]p4
7724 // In an explicit instantiation an exception-specification may be specified,
7725 // but is not required.
7726 // If an exception-specification is specified in an explicit instantiation
7727 // directive, it shall be compatible with the exception-specifications of
7728 // other declarations of that function.
7729 if (auto *FPT = R->getAs<FunctionProtoType>())
7730 if (FPT->hasExceptionSpec()) {
7731 unsigned DiagID =
7732 diag::err_mismatched_exception_spec_explicit_instantiation;
7733 if (getLangOpts().MicrosoftExt)
7734 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7735 bool Result = CheckEquivalentExceptionSpec(
7736 PDiag(DiagID) << Specialization->getType(),
7737 PDiag(diag::note_explicit_instantiation_here),
7738 Specialization->getType()->getAs<FunctionProtoType>(),
7739 Specialization->getLocation(), FPT, D.getLocStart());
7740 // In Microsoft mode, mismatching exception specifications just cause a
7741 // warning.
7742 if (!getLangOpts().MicrosoftExt && Result)
7743 return true;
7744 }
7745
7746 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7747 Diag(D.getIdentifierLoc(),
7748 diag::err_explicit_instantiation_member_function_not_instantiated)
7749 << Specialization
7750 << (Specialization->getTemplateSpecializationKind() ==
7751 TSK_ExplicitSpecialization);
7752 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7753 return true;
7754 }
7755
7756 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7757 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7758 PrevDecl = Specialization;
7759
7760 if (PrevDecl) {
7761 bool HasNoEffect = false;
7762 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7763 PrevDecl,
7764 PrevDecl->getTemplateSpecializationKind(),
7765 PrevDecl->getPointOfInstantiation(),
7766 HasNoEffect))
7767 return true;
7768
7769 // FIXME: We may still want to build some representation of this
7770 // explicit specialization.
7771 if (HasNoEffect)
7772 return (Decl*) nullptr;
7773 }
7774
7775 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7776 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7777 if (Attr)
7778 ProcessDeclAttributeList(S, Specialization, Attr);
7779
7780 if (Specialization->isDefined()) {
7781 // Let the ASTConsumer know that this function has been explicitly
7782 // instantiated now, and its linkage might have changed.
7783 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7784 } else if (TSK == TSK_ExplicitInstantiationDefinition)
7785 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7786
7787 // C++0x [temp.explicit]p2:
7788 // If the explicit instantiation is for a member function, a member class
7789 // or a static data member of a class template specialization, the name of
7790 // the class template specialization in the qualified-id for the member
7791 // name shall be a simple-template-id.
7792 //
7793 // C++98 has the same restriction, just worded differently.
7794 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7795 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7796 D.getCXXScopeSpec().isSet() &&
7797 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7798 Diag(D.getIdentifierLoc(),
7799 diag::ext_explicit_instantiation_without_qualified_id)
7800 << Specialization << D.getCXXScopeSpec().getRange();
7801
7802 CheckExplicitInstantiationScope(*this,
7803 FunTmpl? (NamedDecl *)FunTmpl
7804 : Specialization->getInstantiatedFromMemberFunction(),
7805 D.getIdentifierLoc(),
7806 D.getCXXScopeSpec().isSet());
7807
7808 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7809 return (Decl*) nullptr;
7810}
7811
7812TypeResult
7813Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7814 const CXXScopeSpec &SS, IdentifierInfo *Name,
7815 SourceLocation TagLoc, SourceLocation NameLoc) {
7816 // This has to hold, because SS is expected to be defined.
7817 assert(Name && "Expected a name in a dependent tag");
7818
7819 NestedNameSpecifier *NNS = SS.getScopeRep();
7820 if (!NNS)
7821 return true;
7822
7823 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7824
7825 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7826 Diag(NameLoc, diag::err_dependent_tag_decl)
7827 << (TUK == TUK_Definition) << Kind << SS.getRange();
7828 return true;
7829 }
7830
7831 // Create the resulting type.
7832 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7833 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7834
7835 // Create type-source location information for this type.
7836 TypeLocBuilder TLB;
7837 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
7838 TL.setElaboratedKeywordLoc(TagLoc);
7839 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7840 TL.setNameLoc(NameLoc);
7841 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
7842}
7843
7844TypeResult
7845Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7846 const CXXScopeSpec &SS, const IdentifierInfo &II,
7847 SourceLocation IdLoc) {
7848 if (SS.isInvalid())
7849 return true;
7850
7851 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7852 Diag(TypenameLoc,
7853 getLangOpts().CPlusPlus11 ?
7854 diag::warn_cxx98_compat_typename_outside_of_template :
7855 diag::ext_typename_outside_of_template)
7856 << FixItHint::CreateRemoval(TypenameLoc);
7857
7858 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7859 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7860 TypenameLoc, QualifierLoc, II, IdLoc);
7861 if (T.isNull())
7862 return true;
7863
7864 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7865 if (isa<DependentNameType>(T)) {
7866 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
7867 TL.setElaboratedKeywordLoc(TypenameLoc);
7868 TL.setQualifierLoc(QualifierLoc);
7869 TL.setNameLoc(IdLoc);
7870 } else {
7871 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
7872 TL.setElaboratedKeywordLoc(TypenameLoc);
7873 TL.setQualifierLoc(QualifierLoc);
7874 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
7875 }
7876
7877 return CreateParsedType(T, TSI);
7878}
7879
7880TypeResult
7881Sema::ActOnTypenameType(Scope *S,
7882 SourceLocation TypenameLoc,
7883 const CXXScopeSpec &SS,
7884 SourceLocation TemplateKWLoc,
7885 TemplateTy TemplateIn,
7886 SourceLocation TemplateNameLoc,
7887 SourceLocation LAngleLoc,
7888 ASTTemplateArgsPtr TemplateArgsIn,
7889 SourceLocation RAngleLoc) {
7890 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7891 Diag(TypenameLoc,
7892 getLangOpts().CPlusPlus11 ?
7893 diag::warn_cxx98_compat_typename_outside_of_template :
7894 diag::ext_typename_outside_of_template)
7895 << FixItHint::CreateRemoval(TypenameLoc);
7896
7897 // Translate the parser's template argument list in our AST format.
7898 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7899 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7900
7901 TemplateName Template = TemplateIn.get();
7902 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7903 // Construct a dependent template specialization type.
7904 assert(DTN && "dependent template has non-dependent name?");
7905 assert(DTN->getQualifier() == SS.getScopeRep());
7906 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7907 DTN->getQualifier(),
7908 DTN->getIdentifier(),
7909 TemplateArgs);
7910
7911 // Create source-location information for this type.
7912 TypeLocBuilder Builder;
7913 DependentTemplateSpecializationTypeLoc SpecTL
7914 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7915 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7916 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7917 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7918 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7919 SpecTL.setLAngleLoc(LAngleLoc);
7920 SpecTL.setRAngleLoc(RAngleLoc);
7921 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7922 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7923 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7924 }
7925
7926 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7927 if (T.isNull())
7928 return true;
7929
7930 // Provide source-location information for the template specialization type.
7931 TypeLocBuilder Builder;
7932 TemplateSpecializationTypeLoc SpecTL
7933 = Builder.push<TemplateSpecializationTypeLoc>(T);
7934 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7935 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7936 SpecTL.setLAngleLoc(LAngleLoc);
7937 SpecTL.setRAngleLoc(RAngleLoc);
7938 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7939 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7940
7941 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7942 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
7943 TL.setElaboratedKeywordLoc(TypenameLoc);
7944 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7945
7946 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7947 return CreateParsedType(T, TSI);
7948}
7949
7950
7951/// Determine whether this failed name lookup should be treated as being
7952/// disabled by a usage of std::enable_if.
7953static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7954 SourceRange &CondRange) {
7955 // We must be looking for a ::type...
7956 if (!II.isStr("type"))
7957 return false;
7958
7959 // ... within an explicitly-written template specialization...
7960 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7961 return false;
7962 TypeLoc EnableIfTy = NNS.getTypeLoc();
7963 TemplateSpecializationTypeLoc EnableIfTSTLoc =
7964 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7965 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
7966 return false;
7967 const TemplateSpecializationType *EnableIfTST =
7968 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
7969
7970 // ... which names a complete class template declaration...
7971 const TemplateDecl *EnableIfDecl =
7972 EnableIfTST->getTemplateName().getAsTemplateDecl();
7973 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7974 return false;
7975
7976 // ... called "enable_if".
7977 const IdentifierInfo *EnableIfII =
7978 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7979 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7980 return false;
7981
7982 // Assume the first template argument is the condition.
7983 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
7984 return true;
7985}
7986
7987/// \brief Build the type that describes a C++ typename specifier,
7988/// e.g., "typename T::type".
7989QualType
7990Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7991 SourceLocation KeywordLoc,
7992 NestedNameSpecifierLoc QualifierLoc,
7993 const IdentifierInfo &II,
7994 SourceLocation IILoc) {
7995 CXXScopeSpec SS;
7996 SS.Adopt(QualifierLoc);
7997
7998 DeclContext *Ctx = computeDeclContext(SS);
7999 if (!Ctx) {
8000 // If the nested-name-specifier is dependent and couldn't be
8001 // resolved to a type, build a typename type.
8002 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8003 return Context.getDependentNameType(Keyword,
8004 QualifierLoc.getNestedNameSpecifier(),
8005 &II);
8006 }
8007
8008 // If the nested-name-specifier refers to the current instantiation,
8009 // the "typename" keyword itself is superfluous. In C++03, the
8010 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8011 // allows such extraneous "typename" keywords, and we retroactively
8012 // apply this DR to C++03 code with only a warning. In any case we continue.
8013
8014 if (RequireCompleteDeclContext(SS, Ctx))
8015 return QualType();
8016
8017 DeclarationName Name(&II);
8018 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8019 LookupQualifiedName(Result, Ctx, SS);
8020 unsigned DiagID = 0;
8021 Decl *Referenced = nullptr;
8022 switch (Result.getResultKind()) {
8023 case LookupResult::NotFound: {
8024 // If we're looking up 'type' within a template named 'enable_if', produce
8025 // a more specific diagnostic.
8026 SourceRange CondRange;
8027 if (isEnableIf(QualifierLoc, II, CondRange)) {
8028 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8029 << Ctx << CondRange;
8030 return QualType();
8031 }
8032
8033 DiagID = diag::err_typename_nested_not_found;
8034 break;
8035 }
8036
8037 case LookupResult::FoundUnresolvedValue: {
8038 // We found a using declaration that is a value. Most likely, the using
8039 // declaration itself is meant to have the 'typename' keyword.
8040 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8041 IILoc);
8042 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8043 << Name << Ctx << FullRange;
8044 if (UnresolvedUsingValueDecl *Using
8045 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8046 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8047 Diag(Loc, diag::note_using_value_decl_missing_typename)
8048 << FixItHint::CreateInsertion(Loc, "typename ");
8049 }
8050 }
8051 // Fall through to create a dependent typename type, from which we can recover
8052 // better.
8053
8054 case LookupResult::NotFoundInCurrentInstantiation:
8055 // Okay, it's a member of an unknown instantiation.
8056 return Context.getDependentNameType(Keyword,
8057 QualifierLoc.getNestedNameSpecifier(),
8058 &II);
8059
8060 case LookupResult::Found:
8061 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8062 // We found a type. Build an ElaboratedType, since the
8063 // typename-specifier was just sugar.
8064 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8065 return Context.getElaboratedType(ETK_Typename,
8066 QualifierLoc.getNestedNameSpecifier(),
8067 Context.getTypeDeclType(Type));
8068 }
8069
8070 DiagID = diag::err_typename_nested_not_type;
8071 Referenced = Result.getFoundDecl();
8072 break;
8073
8074 case LookupResult::FoundOverloaded:
8075 DiagID = diag::err_typename_nested_not_type;
8076 Referenced = *Result.begin();
8077 break;
8078
8079 case LookupResult::Ambiguous:
8080 return QualType();
8081 }
8082
8083 // If we get here, it's because name lookup did not find a
8084 // type. Emit an appropriate diagnostic and return an error.
8085 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8086 IILoc);
8087 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8088 if (Referenced)
8089 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8090 << Name;
8091 return QualType();
8092}
8093
8094namespace {
8095 // See Sema::RebuildTypeInCurrentInstantiation
8096 class CurrentInstantiationRebuilder
8097 : public TreeTransform<CurrentInstantiationRebuilder> {
8098 SourceLocation Loc;
8099 DeclarationName Entity;
8100
8101 public:
8102 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8103
8104 CurrentInstantiationRebuilder(Sema &SemaRef,
8105 SourceLocation Loc,
8106 DeclarationName Entity)
8107 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8108 Loc(Loc), Entity(Entity) { }
8109
8110 /// \brief Determine whether the given type \p T has already been
8111 /// transformed.
8112 ///
8113 /// For the purposes of type reconstruction, a type has already been
8114 /// transformed if it is NULL or if it is not dependent.
8115 bool AlreadyTransformed(QualType T) {
8116 return T.isNull() || !T->isDependentType();
8117 }
8118
8119 /// \brief Returns the location of the entity whose type is being
8120 /// rebuilt.
8121 SourceLocation getBaseLocation() { return Loc; }
8122
8123 /// \brief Returns the name of the entity whose type is being rebuilt.
8124 DeclarationName getBaseEntity() { return Entity; }
8125
8126 /// \brief Sets the "base" location and entity when that
8127 /// information is known based on another transformation.
8128 void setBase(SourceLocation Loc, DeclarationName Entity) {
8129 this->Loc = Loc;
8130 this->Entity = Entity;
8131 }
8132
8133 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8134 // Lambdas never need to be transformed.
8135 return E;
8136 }
8137 };
8138}
8139
8140/// \brief Rebuilds a type within the context of the current instantiation.
8141///
8142/// The type \p T is part of the type of an out-of-line member definition of
8143/// a class template (or class template partial specialization) that was parsed
8144/// and constructed before we entered the scope of the class template (or
8145/// partial specialization thereof). This routine will rebuild that type now
8146/// that we have entered the declarator's scope, which may produce different
8147/// canonical types, e.g.,
8148///
8149/// \code
8150/// template<typename T>
8151/// struct X {
8152/// typedef T* pointer;
8153/// pointer data();
8154/// };
8155///
8156/// template<typename T>
8157/// typename X<T>::pointer X<T>::data() { ... }
8158/// \endcode
8159///
8160/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8161/// since we do not know that we can look into X<T> when we parsed the type.
8162/// This function will rebuild the type, performing the lookup of "pointer"
8163/// in X<T> and returning an ElaboratedType whose canonical type is the same
8164/// as the canonical type of T*, allowing the return types of the out-of-line
8165/// definition and the declaration to match.
8166TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8167 SourceLocation Loc,
8168 DeclarationName Name) {
8169 if (!T || !T->getType()->isDependentType())
8170 return T;
8171
8172 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8173 return Rebuilder.TransformType(T);
8174}
8175
8176ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8177 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8178 DeclarationName());
8179 return Rebuilder.TransformExpr(E);
8180}
8181
8182bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8183 if (SS.isInvalid())
8184 return true;
8185
8186 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8187 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8188 DeclarationName());
8189 NestedNameSpecifierLoc Rebuilt
8190 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8191 if (!Rebuilt)
8192 return true;
8193
8194 SS.Adopt(Rebuilt);
8195 return false;
8196}
8197
8198/// \brief Rebuild the template parameters now that we know we're in a current
8199/// instantiation.
8200bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8201 TemplateParameterList *Params) {
8202 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8203 Decl *Param = Params->getParam(I);
8204
8205 // There is nothing to rebuild in a type parameter.
8206 if (isa<TemplateTypeParmDecl>(Param))
8207 continue;
8208
8209 // Rebuild the template parameter list of a template template parameter.
8210 if (TemplateTemplateParmDecl *TTP
8211 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8212 if (RebuildTemplateParamsInCurrentInstantiation(
8213 TTP->getTemplateParameters()))
8214 return true;
8215
8216 continue;
8217 }
8218
8219 // Rebuild the type of a non-type template parameter.
8220 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8221 TypeSourceInfo *NewTSI
8222 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8223 NTTP->getLocation(),
8224 NTTP->getDeclName());
8225 if (!NewTSI)
8226 return true;
8227
8228 if (NewTSI != NTTP->getTypeSourceInfo()) {
8229 NTTP->setTypeSourceInfo(NewTSI);
8230 NTTP->setType(NewTSI->getType());
8231 }
8232 }
8233
8234 return false;
8235}
8236
8237/// \brief Produces a formatted string that describes the binding of
8238/// template parameters to template arguments.
8239std::string
8240Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8241 const TemplateArgumentList &Args) {
8242 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8243}
8244
8245std::string
8246Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8247 const TemplateArgument *Args,
8248 unsigned NumArgs) {
8249 SmallString<128> Str;
8250 llvm::raw_svector_ostream Out(Str);
8251
8252 if (!Params || Params->size() == 0 || NumArgs == 0)
8253 return std::string();
8254
8255 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8256 if (I >= NumArgs)
8257 break;
8258
8259 if (I == 0)
8260 Out << "[with ";
8261 else
8262 Out << ", ";
8263
8264 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8265 Out << Id->getName();
8266 } else {
8267 Out << '$' << I;
8268 }
8269
8270 Out << " = ";
8271 Args[I].print(getPrintingPolicy(), Out);
8272 }
8273
8274 Out << ']';
8275 return Out.str();
8276}
8277
8278void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8279 CachedTokens &Toks) {
8280 if (!FD)
8281 return;
8282
8283 LateParsedTemplate *LPT = new LateParsedTemplate;
8284
8285 // Take tokens to avoid allocations
8286 LPT->Toks.swap(Toks);
8287 LPT->D = FnD;
8288 LateParsedTemplateMap[FD] = LPT;
8289
8290 FD->setLateTemplateParsed(true);
8291}
8292
8293void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8294 if (!FD)
8295 return;
8296 FD->setLateTemplateParsed(false);
8297}
8298
8299bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8300 DeclContext *DC = CurContext;
8301
8302 while (DC) {
8303 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8304 const FunctionDecl *FD = RD->isLocalClass();
8305 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8306 } else if (DC->isTranslationUnit() || DC->isNamespace())
8307 return false;
8308
8309 DC = DC->getParent();
8310 }
8311 return false;
8312}