Bug Summary

File:tools/clang/lib/Sema/SemaTemplate.cpp
Warning:line 3767, column 8
Forming reference to null pointer

Annotated Source Code

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/Builtins.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/ParsedTemplate.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateDeduction.h"
32#include "llvm/ADT/SmallBitVector.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/StringExtras.h"
35
36#include <iterator>
37using namespace clang;
38using namespace sema;
39
40// Exported for use by Parser.
41SourceRange
42clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 unsigned N) {
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
46}
47
48namespace clang {
49/// \brief [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.")((!FD && "Cannot collect constraints from function declaration yet."
) ? static_cast<void> (0) : __assert_fail ("!FD && \"Cannot collect constraints from function declaration yet.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 64, __PRETTY_FUNCTION__))
;
65 return Params->getRequiresClause();
66}
67
68/// \brief Determine whether the declaration found is acceptable as the name
69/// of a template and, if so, return that template declaration. Otherwise,
70/// returns NULL.
71static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
72 NamedDecl *Orig,
73 bool AllowFunctionTemplates) {
74 NamedDecl *D = Orig->getUnderlyingDecl();
75
76 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
78 return nullptr;
79
80 return Orig;
81 }
82
83 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
94 // specialization.
95 if (Record->isInjectedClassName()) {
96 Record = cast<CXXRecordDecl>(Record->getDeclContext());
97 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
99
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
103 }
104
105 return nullptr;
106 }
107
108 return nullptr;
109}
110
111void Sema::FilterAcceptableTemplateNames(LookupResult &R,
112 bool AllowFunctionTemplates) {
113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
119 AllowFunctionTemplates);
120 if (!Repl)
121 filter.erase();
122 else if (Repl != Orig) {
123
124 // C++ [temp.local]p3:
125 // A lookup that finds an injected-class-name (10.2) can result in an
126 // ambiguity in certain cases (for example, if it is found in more than
127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
131 // ambiguous.
132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
133 if (!ClassTemplates.insert(ClassTmpl).second) {
134 filter.erase();
135 continue;
136 }
137
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
144 }
145 }
146 filter.done();
147}
148
149bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
153 return true;
154
155 return false;
156}
157
158TemplateNameKind Sema::isTemplateName(Scope *S,
159 CXXScopeSpec &SS,
160 bool hasTemplateKeyword,
161 UnqualifiedId &Name,
162 ParsedType ObjectTypePtr,
163 bool EnteringContext,
164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
166 assert(getLangOpts().CPlusPlus && "No template names in C!")((getLangOpts().CPlusPlus && "No template names in C!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 166, __PRETTY_FUNCTION__))
;
167
168 DeclarationName TName;
169 MemberOfUnknownSpecialization = false;
170
171 switch (Name.getKind()) {
172 case UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
175
176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
181 case UnqualifiedId::IK_LiteralOperatorId:
182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
183 break;
184
185 default:
186 return TNK_Non_template;
187 }
188
189 QualType ObjectType = ObjectTypePtr.get();
190
191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
197 R.suppressDiagnostics();
198
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
201 return TNK_Non_template;
202 }
203
204 TemplateName Template;
205 TemplateNameKind TemplateKind;
206
207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
213
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
216 } else {
217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218
219 if (SS.isSet() && !SS.isInvalid()) {
220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
223 } else {
224 Template = TemplateName(TD);
225 }
226
227 if (isa<FunctionTemplateDecl>(TD)) {
228 TemplateKind = TNK_Function_template;
229
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
232 } else {
233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD)) ? static_cast
<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __PRETTY_FUNCTION__))
234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD)) ? static_cast
<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __PRETTY_FUNCTION__))
235 isa<BuiltinTemplateDecl>(TD))((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD)) ? static_cast
<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __PRETTY_FUNCTION__))
;
236 TemplateKind =
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
238 }
239 }
240
241 TemplateResult = TemplateTy::make(Template);
242 return TemplateKind;
243}
244
245bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
248 CXXScopeSpec SS;
249 bool MemberOfUnknownSpecialization = false;
250
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
257
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
262 return false;
263 }
264
265 // We only treat template-names that name type templates as valid deduction
266 // guide names.
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
269 return false;
270
271 if (Template)
272 *Template = TemplateTy::make(TemplateName(TD));
273 return true;
274}
275
276bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
277 SourceLocation IILoc,
278 Scope *S,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
283 // template name.
284 // FIXME: Typo correction?
285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
287 return false;
288
289 // The code is missing a 'template' keyword prior to the dependent template
290 // name.
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
294 << FixItHint::CreateInsertion(IILoc, "template ");
295 SuggestedTemplate
296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
298 return true;
299}
300
301void Sema::LookupTemplateName(LookupResult &Found,
302 Scope *S, CXXScopeSpec &SS,
303 QualType ObjectType,
304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
306 // Determine where to perform name lookup
307 MemberOfUnknownSpecialization = false;
308 DeclContext *LookupCtx = nullptr;
309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist")((!SS.isSet() && "ObjectType and scope specifier cannot coexist"
) ? static_cast<void> (0) : __assert_fail ("!SS.isSet() && \"ObjectType and scope specifier cannot coexist\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 313, __PRETTY_FUNCTION__))
;
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
316 assert((isDependent || !ObjectType->isIncompleteType() ||(((isDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __PRETTY_FUNCTION__))
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&(((isDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __PRETTY_FUNCTION__))
318 "Caller should have completed object type")(((isDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __PRETTY_FUNCTION__))
;
319
320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
322 Found.clear();
323 return;
324 }
325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
330
331 // The declaration context must be complete.
332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
333 return;
334 }
335
336 bool ObjectTypeSearchedInScope = false;
337 bool AllowFunctionTemplatesInLookup = true;
338 if (LookupCtx) {
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
356 AllowFunctionTemplatesInLookup = false;
357 }
358 } else if (isDependent && (!S || ObjectType.isNull())) {
359 // We cannot look into a dependent object type or nested nme
360 // specifier.
361 MemberOfUnknownSpecialization = true;
362 return;
363 } else {
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
366
367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
369 }
370
371 if (Found.empty() && !isDependent) {
372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
374 Found.clear();
375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
384 Found.setLookupName(Corrected.getCorrection());
385 if (auto *ND = Corrected.getFoundDecl())
386 Found.addDecl(ND);
387 FilterAcceptableTemplateNames(Found);
388 if (!Found.empty()) {
389 if (LookupCtx) {
390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
392 Name.getAsString() == CorrectedStr;
393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
395 << SS.getRange());
396 } else {
397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
398 }
399 }
400 } else {
401 Found.setLookupName(Name);
402 }
403 }
404
405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
406 if (Found.empty()) {
407 if (isDependent)
408 MemberOfUnknownSpecialization = true;
409 return;
410 }
411
412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
413 !getLangOpts().CPlusPlus11) {
414 // C++03 [basic.lookup.classref]p1:
415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
418 //
419 // Note: C++11 does not perform this second lookup.
420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421 LookupOrdinaryName);
422 LookupName(FoundOuter, S);
423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
424
425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
433 FoundOuter.clear();
434 } else if (!Found.isSuppressingDiagnostics()) {
435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
441 Diag(Found.getNameLoc(),
442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
444 << ObjectType;
445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
447 << ObjectType;
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
450
451 // Recover by taking the template that we found in the object
452 // expression's type.
453 }
454 }
455 }
456}
457
458void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
459 SourceLocation Less,
460 SourceLocation Greater) {
461 if (TemplateName.isInvalid())
462 return;
463
464 DeclarationNameInfo NameInfo;
465 CXXScopeSpec SS;
466 LookupNameKind LookupKind;
467
468 DeclContext *LookupCtx = nullptr;
469 NamedDecl *Found = nullptr;
470
471 // Figure out what name we looked up.
472 if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473 NameInfo = ME->getMemberNameInfo();
474 SS.Adopt(ME->getQualifierLoc());
475 LookupKind = LookupMemberName;
476 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477 Found = ME->getMemberDecl();
478 } else {
479 auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480 NameInfo = DRE->getNameInfo();
481 SS.Adopt(DRE->getQualifierLoc());
482 LookupKind = LookupOrdinaryName;
483 Found = DRE->getFoundDecl();
484 }
485
486 // Try to correct the name by looking for templates and C++ named casts.
487 struct TemplateCandidateFilter : CorrectionCandidateCallback {
488 TemplateCandidateFilter() {
489 WantTypeSpecifiers = false;
490 WantExpressionKeywords = false;
491 WantRemainingKeywords = false;
492 WantCXXNamedCasts = true;
493 };
494 bool ValidateCandidate(const TypoCorrection &Candidate) override {
495 if (auto *ND = Candidate.getCorrectionDecl())
496 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497 return Candidate.isKeyword();
498 }
499 };
500
501 DeclarationName Name = NameInfo.getName();
502 if (TypoCorrection Corrected =
503 CorrectTypo(NameInfo, LookupKind, S, &SS,
504 llvm::make_unique<TemplateCandidateFilter>(),
505 CTK_ErrorRecovery, LookupCtx)) {
506 auto *ND = Corrected.getFoundDecl();
507 if (ND)
508 ND = isAcceptableTemplateName(Context, ND,
509 /*AllowFunctionTemplates*/ true);
510 if (ND || Corrected.isKeyword()) {
511 if (LookupCtx) {
512 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514 Name.getAsString() == CorrectedStr;
515 diagnoseTypo(Corrected,
516 PDiag(diag::err_non_template_in_member_template_id_suggest)
517 << Name << LookupCtx << DroppedSpecifier
518 << SS.getRange(), false);
519 } else {
520 diagnoseTypo(Corrected,
521 PDiag(diag::err_non_template_in_template_id_suggest)
522 << Name, false);
523 }
524 if (Found)
525 Diag(Found->getLocation(),
526 diag::note_non_template_in_template_id_found);
527 return;
528 }
529 }
530
531 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532 << Name << SourceRange(Less, Greater);
533 if (Found)
534 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
535}
536
537/// ActOnDependentIdExpression - Handle a dependent id-expression that
538/// was just parsed. This is only possible with an explicit scope
539/// specifier naming a dependent type.
540ExprResult
541Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
542 SourceLocation TemplateKWLoc,
543 const DeclarationNameInfo &NameInfo,
544 bool isAddressOfOperand,
545 const TemplateArgumentListInfo *TemplateArgs) {
546 DeclContext *DC = getFunctionLevelDeclContext();
547
548 // C++11 [expr.prim.general]p12:
549 // An id-expression that denotes a non-static data member or non-static
550 // member function of a class can only be used:
551 // (...)
552 // - if that id-expression denotes a non-static data member and it
553 // appears in an unevaluated operand.
554 //
555 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556 // CXXDependentScopeMemberExpr. The former can instantiate to either
557 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558 // always a MemberExpr.
559 bool MightBeCxx11UnevalField =
560 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
561
562 // Check if the nested name specifier is an enum type.
563 bool IsEnum = false;
564 if (NestedNameSpecifier *NNS = SS.getScopeRep())
565 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
566
567 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
568 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
569 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
570
571 // Since the 'this' expression is synthesized, we don't need to
572 // perform the double-lookup check.
573 NamedDecl *FirstQualifierInScope = nullptr;
574
575 return CXXDependentScopeMemberExpr::Create(
576 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578 FirstQualifierInScope, NameInfo, TemplateArgs);
579 }
580
581 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
582}
583
584ExprResult
585Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
586 SourceLocation TemplateKWLoc,
587 const DeclarationNameInfo &NameInfo,
588 const TemplateArgumentListInfo *TemplateArgs) {
589 return DependentScopeDeclRefExpr::Create(
590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
591 TemplateArgs);
592}
593
594
595/// Determine whether we would be unable to instantiate this template (because
596/// it either has no definition, or is in the process of being instantiated).
597bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
598 NamedDecl *Instantiation,
599 bool InstantiatedFromMember,
600 const NamedDecl *Pattern,
601 const NamedDecl *PatternDef,
602 TemplateSpecializationKind TSK,
603 bool Complain /*= true*/) {
604 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||((isa<TagDecl>(Instantiation) || isa<FunctionDecl>
(Instantiation) || isa<VarDecl>(Instantiation)) ? static_cast
<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 605, __PRETTY_FUNCTION__))
605 isa<VarDecl>(Instantiation))((isa<TagDecl>(Instantiation) || isa<FunctionDecl>
(Instantiation) || isa<VarDecl>(Instantiation)) ? static_cast
<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 605, __PRETTY_FUNCTION__))
;
606
607 bool IsEntityBeingDefined = false;
608 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609 IsEntityBeingDefined = TD->isBeingDefined();
610
611 if (PatternDef && !IsEntityBeingDefined) {
612 NamedDecl *SuggestedDef = nullptr;
613 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614 /*OnlyNeedComplete*/false)) {
615 // If we're allowed to diagnose this and recover, do so.
616 bool Recover = Complain && !isSFINAEContext();
617 if (Complain)
618 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
619 Sema::MissingImportKind::Definition, Recover);
620 return !Recover;
621 }
622 return false;
623 }
624
625 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
626 return true;
627
628 llvm::Optional<unsigned> Note;
629 QualType InstantiationTy;
630 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631 InstantiationTy = Context.getTypeDeclType(TD);
632 if (PatternDef) {
633 Diag(PointOfInstantiation,
634 diag::err_template_instantiate_within_definition)
635 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
636 << InstantiationTy;
637 // Not much point in noting the template declaration here, since
638 // we're lexically inside it.
639 Instantiation->setInvalidDecl();
640 } else if (InstantiatedFromMember) {
641 if (isa<FunctionDecl>(Instantiation)) {
642 Diag(PointOfInstantiation,
643 diag::err_explicit_instantiation_undefined_member)
644 << /*member function*/ 1 << Instantiation->getDeclName()
645 << Instantiation->getDeclContext();
646 Note = diag::note_explicit_instantiation_here;
647 } else {
648 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!")((isa<TagDecl>(Instantiation) && "Must be a TagDecl!"
) ? static_cast<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 648, __PRETTY_FUNCTION__))
;
649 Diag(PointOfInstantiation,
650 diag::err_implicit_instantiate_member_undefined)
651 << InstantiationTy;
652 Note = diag::note_member_declared_at;
653 }
654 } else {
655 if (isa<FunctionDecl>(Instantiation)) {
656 Diag(PointOfInstantiation,
657 diag::err_explicit_instantiation_undefined_func_template)
658 << Pattern;
659 Note = diag::note_explicit_instantiation_here;
660 } else if (isa<TagDecl>(Instantiation)) {
661 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662 << (TSK != TSK_ImplicitInstantiation)
663 << InstantiationTy;
664 Note = diag::note_template_decl_here;
665 } else {
666 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!")((isa<VarDecl>(Instantiation) && "Must be a VarDecl!"
) ? static_cast<void> (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 666, __PRETTY_FUNCTION__))
;
667 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668 Diag(PointOfInstantiation,
669 diag::err_explicit_instantiation_undefined_var_template)
670 << Instantiation;
671 Instantiation->setInvalidDecl();
672 } else
673 Diag(PointOfInstantiation,
674 diag::err_explicit_instantiation_undefined_member)
675 << /*static data member*/ 2 << Instantiation->getDeclName()
676 << Instantiation->getDeclContext();
677 Note = diag::note_explicit_instantiation_here;
678 }
679 }
680 if (Note) // Diagnostics were emitted.
681 Diag(Pattern->getLocation(), Note.getValue());
682
683 // In general, Instantiation isn't marked invalid to get more than one
684 // error for multiple undefined instantiations. But the code that does
685 // explicit declaration -> explicit definition conversion can't handle
686 // invalid declarations, so mark as invalid in that case.
687 if (TSK == TSK_ExplicitInstantiationDeclaration)
688 Instantiation->setInvalidDecl();
689 return true;
690}
691
692/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693/// that the template parameter 'PrevDecl' is being shadowed by a new
694/// declaration at location Loc. Returns true to indicate that this is
695/// an error, and false otherwise.
696void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
697 assert(PrevDecl->isTemplateParameter() && "Not a template parameter")((PrevDecl->isTemplateParameter() && "Not a template parameter"
) ? static_cast<void> (0) : __assert_fail ("PrevDecl->isTemplateParameter() && \"Not a template parameter\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 697, __PRETTY_FUNCTION__))
;
698
699 // Microsoft Visual C++ permits template parameters to be shadowed.
700 if (getLangOpts().MicrosoftExt)
701 return;
702
703 // C++ [temp.local]p4:
704 // A template-parameter shall not be redeclared within its
705 // scope (including nested scopes).
706 Diag(Loc, diag::err_template_param_shadow)
707 << cast<NamedDecl>(PrevDecl)->getDeclName();
708 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
709}
710
711/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
712/// the parameter D to reference the templated declaration and return a pointer
713/// to the template declaration. Otherwise, do nothing to D and return null.
714TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
715 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716 D = Temp->getTemplatedDecl();
717 return Temp;
718 }
719 return nullptr;
720}
721
722ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
723 SourceLocation EllipsisLoc) const {
724 assert(Kind == Template &&((Kind == Template && "Only template template arguments can be pack expansions here"
) ? static_cast<void> (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 725, __PRETTY_FUNCTION__))
725 "Only template template arguments can be pack expansions here")((Kind == Template && "Only template template arguments can be pack expansions here"
) ? static_cast<void> (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 725, __PRETTY_FUNCTION__))
;
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&((getAsTemplate().get().containsUnexpandedParameterPack() &&
"Template template argument pack expansion without packs") ?
static_cast<void> (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 727, __PRETTY_FUNCTION__))
727 "Template template argument pack expansion without packs")((getAsTemplate().get().containsUnexpandedParameterPack() &&
"Template template argument pack expansion without packs") ?
static_cast<void> (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 727, __PRETTY_FUNCTION__))
;
728 ParsedTemplateArgument Result(*this);
729 Result.EllipsisLoc = EllipsisLoc;
730 return Result;
731}
732
733static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
734 const ParsedTemplateArgument &Arg) {
735
736 switch (Arg.getKind()) {
737 case ParsedTemplateArgument::Type: {
738 TypeSourceInfo *DI;
739 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
740 if (!DI)
741 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
742 return TemplateArgumentLoc(TemplateArgument(T), DI);
743 }
744
745 case ParsedTemplateArgument::NonType: {
746 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
747 return TemplateArgumentLoc(TemplateArgument(E), E);
748 }
749
750 case ParsedTemplateArgument::Template: {
751 TemplateName Template = Arg.getAsTemplate().get();
752 TemplateArgument TArg;
753 if (Arg.getEllipsisLoc().isValid())
754 TArg = TemplateArgument(Template, Optional<unsigned int>());
755 else
756 TArg = Template;
757 return TemplateArgumentLoc(TArg,
758 Arg.getScopeSpec().getWithLocInContext(
759 SemaRef.Context),
760 Arg.getLocation(),
761 Arg.getEllipsisLoc());
762 }
763 }
764
765 llvm_unreachable("Unhandled parsed template argument")::llvm::llvm_unreachable_internal("Unhandled parsed template argument"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 765)
;
766}
767
768/// \brief Translates template arguments as provided by the parser
769/// into template arguments used by semantic analysis.
770void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
771 TemplateArgumentListInfo &TemplateArgs) {
772 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
773 TemplateArgs.addArgument(translateTemplateArgument(*this,
774 TemplateArgsIn[I]));
775}
776
777static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
778 SourceLocation Loc,
779 IdentifierInfo *Name) {
780 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
781 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
784}
785
786/// ActOnTypeParameter - Called when a C++ template type parameter
787/// (e.g., "typename T") has been parsed. Typename specifies whether
788/// the keyword "typename" was used to declare the type parameter
789/// (otherwise, "class" was used), and KeyLoc is the location of the
790/// "class" or "typename" keyword. ParamName is the name of the
791/// parameter (NULL indicates an unnamed template parameter) and
792/// ParamNameLoc is the location of the parameter name (if any).
793/// If the type parameter has a default argument, it will be added
794/// later via ActOnTypeParameterDefault.
795Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
796 SourceLocation EllipsisLoc,
797 SourceLocation KeyLoc,
798 IdentifierInfo *ParamName,
799 SourceLocation ParamNameLoc,
800 unsigned Depth, unsigned Position,
801 SourceLocation EqualLoc,
802 ParsedType DefaultArg) {
803 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 804, __PRETTY_FUNCTION__))
804 "Template type parameter not in template parameter scope!")((S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 804, __PRETTY_FUNCTION__))
;
805
806 SourceLocation Loc = ParamNameLoc;
807 if (!ParamName)
808 Loc = KeyLoc;
809
810 bool IsParameterPack = EllipsisLoc.isValid();
811 TemplateTypeParmDecl *Param
812 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
813 KeyLoc, Loc, Depth, Position, ParamName,
814 Typename, IsParameterPack);
815 Param->setAccess(AS_public);
816
817 if (ParamName) {
818 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
819
820 // Add the template parameter into the current scope.
821 S->AddDecl(Param);
822 IdResolver.AddDecl(Param);
823 }
824
825 // C++0x [temp.param]p9:
826 // A default template-argument may be specified for any kind of
827 // template-parameter that is not a template parameter pack.
828 if (DefaultArg && IsParameterPack) {
829 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
830 DefaultArg = nullptr;
831 }
832
833 // Handle the default argument, if provided.
834 if (DefaultArg) {
835 TypeSourceInfo *DefaultTInfo;
836 GetTypeFromParser(DefaultArg, &DefaultTInfo);
837
838 assert(DefaultTInfo && "expected source information for type")((DefaultTInfo && "expected source information for type"
) ? static_cast<void> (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 838, __PRETTY_FUNCTION__))
;
839
840 // Check for unexpanded parameter packs.
841 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
842 UPPC_DefaultArgument))
843 return Param;
844
845 // Check the template argument itself.
846 if (CheckTemplateArgument(Param, DefaultTInfo)) {
847 Param->setInvalidDecl();
848 return Param;
849 }
850
851 Param->setDefaultArgument(DefaultTInfo);
852 }
853
854 return Param;
855}
856
857/// \brief Check that the type of a non-type template parameter is
858/// well-formed.
859///
860/// \returns the (possibly-promoted) parameter type if valid;
861/// otherwise, produces a diagnostic and returns a NULL type.
862QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
863 SourceLocation Loc) {
864 if (TSI->getType()->isUndeducedType()) {
865 // C++1z [temp.dep.expr]p3:
866 // An id-expression is type-dependent if it contains
867 // - an identifier associated by name lookup with a non-type
868 // template-parameter declared with a type that contains a
869 // placeholder type (7.1.7.4),
870 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
871 }
872
873 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
874}
875
876QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
877 SourceLocation Loc) {
878 // We don't allow variably-modified types as the type of non-type template
879 // parameters.
880 if (T->isVariablyModifiedType()) {
881 Diag(Loc, diag::err_variably_modified_nontype_template_param)
882 << T;
883 return QualType();
884 }
885
886 // C++ [temp.param]p4:
887 //
888 // A non-type template-parameter shall have one of the following
889 // (optionally cv-qualified) types:
890 //
891 // -- integral or enumeration type,
892 if (T->isIntegralOrEnumerationType() ||
893 // -- pointer to object or pointer to function,
894 T->isPointerType() ||
895 // -- reference to object or reference to function,
896 T->isReferenceType() ||
897 // -- pointer to member,
898 T->isMemberPointerType() ||
899 // -- std::nullptr_t.
900 T->isNullPtrType() ||
901 // If T is a dependent type, we can't do the check now, so we
902 // assume that it is well-formed.
903 T->isDependentType() ||
904 // Allow use of auto in template parameter declarations.
905 T->isUndeducedType()) {
906 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907 // are ignored when determining its type.
908 return T.getUnqualifiedType();
909 }
910
911 // C++ [temp.param]p8:
912 //
913 // A non-type template-parameter of type "array of T" or
914 // "function returning T" is adjusted to be of type "pointer to
915 // T" or "pointer to function returning T", respectively.
916 else if (T->isArrayType() || T->isFunctionType())
917 return Context.getDecayedType(T);
918
919 Diag(Loc, diag::err_template_nontype_parm_bad_type)
920 << T;
921
922 return QualType();
923}
924
925Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
926 unsigned Depth,
927 unsigned Position,
928 SourceLocation EqualLoc,
929 Expr *Default) {
930 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
931
932 if (TInfo->getType()->isUndeducedType()) {
933 Diag(D.getIdentifierLoc(),
934 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
935 << QualType(TInfo->getType()->getContainedAutoType(), 0);
936 }
937
938 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 939, __PRETTY_FUNCTION__))
939 "Non-type template parameter not in template parameter scope!")((S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 939, __PRETTY_FUNCTION__))
;
940 bool Invalid = false;
941
942 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
943 if (T.isNull()) {
944 T = Context.IntTy; // Recover with an 'int' type.
945 Invalid = true;
946 }
947
948 IdentifierInfo *ParamName = D.getIdentifier();
949 bool IsParameterPack = D.hasEllipsis();
950 NonTypeTemplateParmDecl *Param
951 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
952 D.getLocStart(),
953 D.getIdentifierLoc(),
954 Depth, Position, ParamName, T,
955 IsParameterPack, TInfo);
956 Param->setAccess(AS_public);
957
958 if (Invalid)
959 Param->setInvalidDecl();
960
961 if (ParamName) {
962 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
963 ParamName);
964
965 // Add the template parameter into the current scope.
966 S->AddDecl(Param);
967 IdResolver.AddDecl(Param);
968 }
969
970 // C++0x [temp.param]p9:
971 // A default template-argument may be specified for any kind of
972 // template-parameter that is not a template parameter pack.
973 if (Default && IsParameterPack) {
974 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
975 Default = nullptr;
976 }
977
978 // Check the well-formedness of the default template argument, if provided.
979 if (Default) {
980 // Check for unexpanded parameter packs.
981 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
982 return Param;
983
984 TemplateArgument Converted;
985 ExprResult DefaultRes =
986 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
987 if (DefaultRes.isInvalid()) {
988 Param->setInvalidDecl();
989 return Param;
990 }
991 Default = DefaultRes.get();
992
993 Param->setDefaultArgument(Default);
994 }
995
996 return Param;
997}
998
999/// ActOnTemplateTemplateParameter - Called when a C++ template template
1000/// parameter (e.g. T in template <template \<typename> class T> class array)
1001/// has been parsed. S is the current scope.
1002Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1003 SourceLocation TmpLoc,
1004 TemplateParameterList *Params,
1005 SourceLocation EllipsisLoc,
1006 IdentifierInfo *Name,
1007 SourceLocation NameLoc,
1008 unsigned Depth,
1009 unsigned Position,
1010 SourceLocation EqualLoc,
1011 ParsedTemplateArgument Default) {
1012 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1013, __PRETTY_FUNCTION__))
1013 "Template template parameter not in template parameter scope!")((S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1013, __PRETTY_FUNCTION__))
;
1014
1015 // Construct the parameter object.
1016 bool IsParameterPack = EllipsisLoc.isValid();
1017 TemplateTemplateParmDecl *Param =
1018 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1019 NameLoc.isInvalid()? TmpLoc : NameLoc,
1020 Depth, Position, IsParameterPack,
1021 Name, Params);
1022 Param->setAccess(AS_public);
1023
1024 // If the template template parameter has a name, then link the identifier
1025 // into the scope and lookup mechanisms.
1026 if (Name) {
1027 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1028
1029 S->AddDecl(Param);
1030 IdResolver.AddDecl(Param);
1031 }
1032
1033 if (Params->size() == 0) {
1034 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1035 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1036 Param->setInvalidDecl();
1037 }
1038
1039 // C++0x [temp.param]p9:
1040 // A default template-argument may be specified for any kind of
1041 // template-parameter that is not a template parameter pack.
1042 if (IsParameterPack && !Default.isInvalid()) {
1043 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1044 Default = ParsedTemplateArgument();
1045 }
1046
1047 if (!Default.isInvalid()) {
1048 // Check only that we have a template template argument. We don't want to
1049 // try to check well-formedness now, because our template template parameter
1050 // might have dependent types in its template parameters, which we wouldn't
1051 // be able to match now.
1052 //
1053 // If none of the template template parameter's template arguments mention
1054 // other template parameters, we could actually perform more checking here.
1055 // However, it isn't worth doing.
1056 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1057 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1058 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1059 << DefaultArg.getSourceRange();
1060 return Param;
1061 }
1062
1063 // Check for unexpanded parameter packs.
1064 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1065 DefaultArg.getArgument().getAsTemplate(),
1066 UPPC_DefaultArgument))
1067 return Param;
1068
1069 Param->setDefaultArgument(Context, DefaultArg);
1070 }
1071
1072 return Param;
1073}
1074
1075/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1076/// constrained by RequiresClause, that contains the template parameters in
1077/// Params.
1078TemplateParameterList *
1079Sema::ActOnTemplateParameterList(unsigned Depth,
1080 SourceLocation ExportLoc,
1081 SourceLocation TemplateLoc,
1082 SourceLocation LAngleLoc,
1083 ArrayRef<Decl *> Params,
1084 SourceLocation RAngleLoc,
1085 Expr *RequiresClause) {
1086 if (ExportLoc.isValid())
1087 Diag(ExportLoc, diag::warn_template_export_unsupported);
1088
1089 return TemplateParameterList::Create(
1090 Context, TemplateLoc, LAngleLoc,
1091 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
1092 RAngleLoc, RequiresClause);
1093}
1094
1095static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1096 if (SS.isSet())
1097 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1098}
1099
1100DeclResult
1101Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1102 SourceLocation KWLoc, CXXScopeSpec &SS,
1103 IdentifierInfo *Name, SourceLocation NameLoc,
1104 AttributeList *Attr,
1105 TemplateParameterList *TemplateParams,
1106 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1107 SourceLocation FriendLoc,
1108 unsigned NumOuterTemplateParamLists,
1109 TemplateParameterList** OuterTemplateParamLists,
1110 SkipBodyInfo *SkipBody) {
1111 assert(TemplateParams && TemplateParams->size() > 0 &&((TemplateParams && TemplateParams->size() > 0 &&
"No template parameters") ? static_cast<void> (0) : __assert_fail
("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1112, __PRETTY_FUNCTION__))
1112 "No template parameters")((TemplateParams && TemplateParams->size() > 0 &&
"No template parameters") ? static_cast<void> (0) : __assert_fail
("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1112, __PRETTY_FUNCTION__))
;
1113 assert(TUK != TUK_Reference && "Can only declare or define class templates")((TUK != TUK_Reference && "Can only declare or define class templates"
) ? static_cast<void> (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1113, __PRETTY_FUNCTION__))
;
1114 bool Invalid = false;
1115
1116 // Check that we can declare a template here.
1117 if (CheckTemplateDeclScope(S, TemplateParams))
1118 return true;
1119
1120 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1121 assert(Kind != TTK_Enum && "can't build template of enumerated type")((Kind != TTK_Enum && "can't build template of enumerated type"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1121, __PRETTY_FUNCTION__))
;
1122
1123 // There is no such thing as an unnamed class template.
1124 if (!Name) {
1125 Diag(KWLoc, diag::err_template_unnamed_class);
1126 return true;
1127 }
1128
1129 // Find any previous declaration with this name. For a friend with no
1130 // scope explicitly specified, we only look for tag declarations (per
1131 // C++11 [basic.lookup.elab]p2).
1132 DeclContext *SemanticContext;
1133 LookupResult Previous(*this, Name, NameLoc,
1134 (SS.isEmpty() && TUK == TUK_Friend)
1135 ? LookupTagName : LookupOrdinaryName,
1136 ForRedeclaration);
1137 if (SS.isNotEmpty() && !SS.isInvalid()) {
1138 SemanticContext = computeDeclContext(SS, true);
1139 if (!SemanticContext) {
1140 // FIXME: Horrible, horrible hack! We can't currently represent this
1141 // in the AST, and historically we have just ignored such friend
1142 // class templates, so don't complain here.
1143 Diag(NameLoc, TUK == TUK_Friend
1144 ? diag::warn_template_qualified_friend_ignored
1145 : diag::err_template_qualified_declarator_no_match)
1146 << SS.getScopeRep() << SS.getRange();
1147 return TUK != TUK_Friend;
1148 }
1149
1150 if (RequireCompleteDeclContext(SS, SemanticContext))
1151 return true;
1152
1153 // If we're adding a template to a dependent context, we may need to
1154 // rebuilding some of the types used within the template parameter list,
1155 // now that we know what the current instantiation is.
1156 if (SemanticContext->isDependentContext()) {
1157 ContextRAII SavedContext(*this, SemanticContext);
1158 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1159 Invalid = true;
1160 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1161 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1162
1163 LookupQualifiedName(Previous, SemanticContext);
1164 } else {
1165 SemanticContext = CurContext;
1166
1167 // C++14 [class.mem]p14:
1168 // If T is the name of a class, then each of the following shall have a
1169 // name different from T:
1170 // -- every member template of class T
1171 if (TUK != TUK_Friend &&
1172 DiagnoseClassNameShadow(SemanticContext,
1173 DeclarationNameInfo(Name, NameLoc)))
1174 return true;
1175
1176 LookupName(Previous, S);
1177 }
1178
1179 if (Previous.isAmbiguous())
1180 return true;
1181
1182 NamedDecl *PrevDecl = nullptr;
1183 if (Previous.begin() != Previous.end())
1184 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1185
1186 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1187 // Maybe we will complain about the shadowed template parameter.
1188 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1189 // Just pretend that we didn't see the previous declaration.
1190 PrevDecl = nullptr;
1191 }
1192
1193 // If there is a previous declaration with the same name, check
1194 // whether this is a valid redeclaration.
1195 ClassTemplateDecl *PrevClassTemplate
1196 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1197
1198 // We may have found the injected-class-name of a class template,
1199 // class template partial specialization, or class template specialization.
1200 // In these cases, grab the template that is being defined or specialized.
1201 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1202 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1203 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1204 PrevClassTemplate
1205 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1206 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1207 PrevClassTemplate
1208 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1209 ->getSpecializedTemplate();
1210 }
1211 }
1212
1213 if (TUK == TUK_Friend) {
1214 // C++ [namespace.memdef]p3:
1215 // [...] When looking for a prior declaration of a class or a function
1216 // declared as a friend, and when the name of the friend class or
1217 // function is neither a qualified name nor a template-id, scopes outside
1218 // the innermost enclosing namespace scope are not considered.
1219 if (!SS.isSet()) {
1220 DeclContext *OutermostContext = CurContext;
1221 while (!OutermostContext->isFileContext())
1222 OutermostContext = OutermostContext->getLookupParent();
1223
1224 if (PrevDecl &&
1225 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1226 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1227 SemanticContext = PrevDecl->getDeclContext();
1228 } else {
1229 // Declarations in outer scopes don't matter. However, the outermost
1230 // context we computed is the semantic context for our new
1231 // declaration.
1232 PrevDecl = PrevClassTemplate = nullptr;
1233 SemanticContext = OutermostContext;
1234
1235 // Check that the chosen semantic context doesn't already contain a
1236 // declaration of this name as a non-tag type.
1237 Previous.clear(LookupOrdinaryName);
1238 DeclContext *LookupContext = SemanticContext;
1239 while (LookupContext->isTransparentContext())
1240 LookupContext = LookupContext->getLookupParent();
1241 LookupQualifiedName(Previous, LookupContext);
1242
1243 if (Previous.isAmbiguous())
1244 return true;
1245
1246 if (Previous.begin() != Previous.end())
1247 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1248 }
1249 }
1250 } else if (PrevDecl &&
1251 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1252 S, SS.isValid()))
1253 PrevDecl = PrevClassTemplate = nullptr;
1254
1255 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1256 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1257 if (SS.isEmpty() &&
1258 !(PrevClassTemplate &&
1259 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1260 SemanticContext->getRedeclContext()))) {
1261 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1262 Diag(Shadow->getTargetDecl()->getLocation(),
1263 diag::note_using_decl_target);
1264 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1265 // Recover by ignoring the old declaration.
1266 PrevDecl = PrevClassTemplate = nullptr;
1267 }
1268 }
1269
1270 // TODO Memory management; associated constraints are not always stored.
1271 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1272
1273 if (PrevClassTemplate) {
1274 // Ensure that the template parameter lists are compatible. Skip this check
1275 // for a friend in a dependent context: the template parameter list itself
1276 // could be dependent.
1277 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1278 !TemplateParameterListsAreEqual(TemplateParams,
1279 PrevClassTemplate->getTemplateParameters(),
1280 /*Complain=*/true,
1281 TPL_TemplateMatch))
1282 return true;
1283
1284 // Check for matching associated constraints on redeclarations.
1285 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1286 const bool RedeclACMismatch = [&] {
1287 if (!(CurAC || PrevAC))
1288 return false; // Nothing to check; no mismatch.
1289 if (CurAC && PrevAC) {
1290 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1291 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1292 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1293 if (CurACInfo == PrevACInfo)
1294 return false; // All good; no mismatch.
1295 }
1296 return true;
1297 }();
1298
1299 if (RedeclACMismatch) {
1300 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1301 diag::err_template_different_associated_constraints);
1302 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1303 diag::note_template_prev_declaration) << /*declaration*/0;
1304 return true;
1305 }
1306
1307 // C++ [temp.class]p4:
1308 // In a redeclaration, partial specialization, explicit
1309 // specialization or explicit instantiation of a class template,
1310 // the class-key shall agree in kind with the original class
1311 // template declaration (7.1.5.3).
1312 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1313 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1314 TUK == TUK_Definition, KWLoc, Name)) {
1315 Diag(KWLoc, diag::err_use_with_wrong_tag)
1316 << Name
1317 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1318 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1319 Kind = PrevRecordDecl->getTagKind();
1320 }
1321
1322 // Check for redefinition of this class template.
1323 if (TUK == TUK_Definition) {
1324 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1325 // If we have a prior definition that is not visible, treat this as
1326 // simply making that previous definition visible.
1327 NamedDecl *Hidden = nullptr;
1328 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1329 SkipBody->ShouldSkip = true;
1330 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1331 assert(Tmpl && "original definition of a class template is not a "((Tmpl && "original definition of a class template is not a "
"class template?") ? static_cast<void> (0) : __assert_fail
("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1332, __PRETTY_FUNCTION__))
1332 "class template?")((Tmpl && "original definition of a class template is not a "
"class template?") ? static_cast<void> (0) : __assert_fail
("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1332, __PRETTY_FUNCTION__))
;
1333 makeMergedDefinitionVisible(Hidden);
1334 makeMergedDefinitionVisible(Tmpl);
1335 return Def;
1336 }
1337
1338 Diag(NameLoc, diag::err_redefinition) << Name;
1339 Diag(Def->getLocation(), diag::note_previous_definition);
1340 // FIXME: Would it make sense to try to "forget" the previous
1341 // definition, as part of error recovery?
1342 return true;
1343 }
1344 }
1345 } else if (PrevDecl) {
1346 // C++ [temp]p5:
1347 // A class template shall not have the same name as any other
1348 // template, class, function, object, enumeration, enumerator,
1349 // namespace, or type in the same scope (3.3), except as specified
1350 // in (14.5.4).
1351 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1352 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1353 return true;
1354 }
1355
1356 // Check the template parameter list of this declaration, possibly
1357 // merging in the template parameter list from the previous class
1358 // template declaration. Skip this check for a friend in a dependent
1359 // context, because the template parameter list might be dependent.
1360 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1361 CheckTemplateParameterList(
1362 TemplateParams,
1363 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1364 : nullptr,
1365 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1366 SemanticContext->isDependentContext())
1367 ? TPC_ClassTemplateMember
1368 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1369 : TPC_ClassTemplate))
1370 Invalid = true;
1371
1372 if (SS.isSet()) {
1373 // If the name of the template was qualified, we must be defining the
1374 // template out-of-line.
1375 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1376 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1377 : diag::err_member_decl_does_not_match)
1378 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1379 Invalid = true;
1380 }
1381 }
1382
1383 // If this is a templated friend in a dependent context we should not put it
1384 // on the redecl chain. In some cases, the templated friend can be the most
1385 // recent declaration tricking the template instantiator to make substitutions
1386 // there.
1387 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1388 bool ShouldAddRedecl
1389 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1390
1391 CXXRecordDecl *NewClass =
1392 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1393 PrevClassTemplate && ShouldAddRedecl ?
1394 PrevClassTemplate->getTemplatedDecl() : nullptr,
1395 /*DelayTypeCreation=*/true);
1396 SetNestedNameSpecifier(NewClass, SS);
1397 if (NumOuterTemplateParamLists > 0)
1398 NewClass->setTemplateParameterListsInfo(
1399 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1400 NumOuterTemplateParamLists));
1401
1402 // Add alignment attributes if necessary; these attributes are checked when
1403 // the ASTContext lays out the structure.
1404 if (TUK == TUK_Definition) {
1405 AddAlignmentAttributesForRecord(NewClass);
1406 AddMsStructLayoutForRecord(NewClass);
1407 }
1408
1409 // Attach the associated constraints when the declaration will not be part of
1410 // a decl chain.
1411 Expr *const ACtoAttach =
1412 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1413
1414 ClassTemplateDecl *NewTemplate
1415 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1416 DeclarationName(Name), TemplateParams,
1417 NewClass, ACtoAttach);
1418
1419 if (ShouldAddRedecl)
1420 NewTemplate->setPreviousDecl(PrevClassTemplate);
1421
1422 NewClass->setDescribedClassTemplate(NewTemplate);
1423
1424 if (ModulePrivateLoc.isValid())
1425 NewTemplate->setModulePrivate();
1426
1427 // Build the type for the class template declaration now.
1428 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1429 T = Context.getInjectedClassNameType(NewClass, T);
1430 assert(T->isDependentType() && "Class template type is not dependent?")((T->isDependentType() && "Class template type is not dependent?"
) ? static_cast<void> (0) : __assert_fail ("T->isDependentType() && \"Class template type is not dependent?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1430, __PRETTY_FUNCTION__))
;
1431 (void)T;
1432
1433 // If we are providing an explicit specialization of a member that is a
1434 // class template, make a note of that.
1435 if (PrevClassTemplate &&
1436 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1437 PrevClassTemplate->setMemberSpecialization();
1438
1439 // Set the access specifier.
1440 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1441 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1442
1443 // Set the lexical context of these templates
1444 NewClass->setLexicalDeclContext(CurContext);
1445 NewTemplate->setLexicalDeclContext(CurContext);
1446
1447 if (TUK == TUK_Definition)
1448 NewClass->startDefinition();
1449
1450 if (Attr)
1451 ProcessDeclAttributeList(S, NewClass, Attr);
1452
1453 if (PrevClassTemplate)
1454 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1455
1456 AddPushedVisibilityAttribute(NewClass);
1457
1458 if (TUK != TUK_Friend) {
1459 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1460 Scope *Outer = S;
1461 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1462 Outer = Outer->getParent();
1463 PushOnScopeChains(NewTemplate, Outer);
1464 } else {
1465 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1466 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1467 NewClass->setAccess(PrevClassTemplate->getAccess());
1468 }
1469
1470 NewTemplate->setObjectOfFriendDecl();
1471
1472 // Friend templates are visible in fairly strange ways.
1473 if (!CurContext->isDependentContext()) {
1474 DeclContext *DC = SemanticContext->getRedeclContext();
1475 DC->makeDeclVisibleInContext(NewTemplate);
1476 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1477 PushOnScopeChains(NewTemplate, EnclosingScope,
1478 /* AddToContext = */ false);
1479 }
1480
1481 FriendDecl *Friend = FriendDecl::Create(
1482 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1483 Friend->setAccess(AS_public);
1484 CurContext->addDecl(Friend);
1485 }
1486
1487 if (Invalid) {
1488 NewTemplate->setInvalidDecl();
1489 NewClass->setInvalidDecl();
1490 }
1491
1492 ActOnDocumentableDecl(NewTemplate);
1493
1494 return NewTemplate;
1495}
1496
1497namespace {
1498/// Transform to convert portions of a constructor declaration into the
1499/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1500struct ConvertConstructorToDeductionGuideTransform {
1501 ConvertConstructorToDeductionGuideTransform(Sema &S,
1502 ClassTemplateDecl *Template)
1503 : SemaRef(S), Template(Template) {}
1504
1505 Sema &SemaRef;
1506 ClassTemplateDecl *Template;
1507
1508 DeclContext *DC = Template->getDeclContext();
1509 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1510 DeclarationName DeductionGuideName =
1511 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1512
1513 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1514
1515 // Index adjustment to apply to convert depth-1 template parameters into
1516 // depth-0 template parameters.
1517 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1518
1519 /// Transform a constructor declaration into a deduction guide.
1520 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1521 CXXConstructorDecl *CD) {
1522 SmallVector<TemplateArgument, 16> SubstArgs;
1523
1524 LocalInstantiationScope Scope(SemaRef);
1525
1526 // C++ [over.match.class.deduct]p1:
1527 // -- For each constructor of the class template designated by the
1528 // template-name, a function template with the following properties:
1529
1530 // -- The template parameters are the template parameters of the class
1531 // template followed by the template parameters (including default
1532 // template arguments) of the constructor, if any.
1533 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1534 if (FTD) {
1535 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1536 SmallVector<NamedDecl *, 16> AllParams;
1537 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1538 AllParams.insert(AllParams.begin(),
1539 TemplateParams->begin(), TemplateParams->end());
1540 SubstArgs.reserve(InnerParams->size());
1541
1542 // Later template parameters could refer to earlier ones, so build up
1543 // a list of substituted template arguments as we go.
1544 for (NamedDecl *Param : *InnerParams) {
1545 MultiLevelTemplateArgumentList Args;
1546 Args.addOuterTemplateArguments(SubstArgs);
1547 Args.addOuterRetainedLevel();
1548 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1549 if (!NewParam)
1550 return nullptr;
1551 AllParams.push_back(NewParam);
1552 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1553 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1554 }
1555 TemplateParams = TemplateParameterList::Create(
1556 SemaRef.Context, InnerParams->getTemplateLoc(),
1557 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1558 /*FIXME: RequiresClause*/ nullptr);
1559 }
1560
1561 // If we built a new template-parameter-list, track that we need to
1562 // substitute references to the old parameters into references to the
1563 // new ones.
1564 MultiLevelTemplateArgumentList Args;
1565 if (FTD) {
1566 Args.addOuterTemplateArguments(SubstArgs);
1567 Args.addOuterRetainedLevel();
1568 }
1569
1570 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1571 .getAsAdjusted<FunctionProtoTypeLoc>();
1572 assert(FPTL && "no prototype for constructor declaration")((FPTL && "no prototype for constructor declaration")
? static_cast<void> (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1572, __PRETTY_FUNCTION__))
;
1573
1574 // Transform the type of the function, adjusting the return type and
1575 // replacing references to the old parameters with references to the
1576 // new ones.
1577 TypeLocBuilder TLB;
1578 SmallVector<ParmVarDecl*, 8> Params;
1579 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1580 if (NewType.isNull())
1581 return nullptr;
1582 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1583
1584 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1585 CD->getLocStart(), CD->getLocation(),
1586 CD->getLocEnd());
1587 }
1588
1589 /// Build a deduction guide with the specified parameter types.
1590 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1591 SourceLocation Loc = Template->getLocation();
1592
1593 // Build the requested type.
1594 FunctionProtoType::ExtProtoInfo EPI;
1595 EPI.HasTrailingReturn = true;
1596 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1597 DeductionGuideName, EPI);
1598 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1599
1600 FunctionProtoTypeLoc FPTL =
1601 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1602
1603 // Build the parameters, needed during deduction / substitution.
1604 SmallVector<ParmVarDecl*, 4> Params;
1605 for (auto T : ParamTypes) {
1606 ParmVarDecl *NewParam = ParmVarDecl::Create(
1607 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1608 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1609 NewParam->setScopeInfo(0, Params.size());
1610 FPTL.setParam(Params.size(), NewParam);
1611 Params.push_back(NewParam);
1612 }
1613
1614 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1615 Loc, Loc, Loc);
1616 }
1617
1618private:
1619 /// Transform a constructor template parameter into a deduction guide template
1620 /// parameter, rebuilding any internal references to earlier parameters and
1621 /// renumbering as we go.
1622 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1623 MultiLevelTemplateArgumentList &Args) {
1624 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1625 // TemplateTypeParmDecl's index cannot be changed after creation, so
1626 // substitute it directly.
1627 auto *NewTTP = TemplateTypeParmDecl::Create(
1628 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1629 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1630 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1631 TTP->isParameterPack());
1632 if (TTP->hasDefaultArgument()) {
1633 TypeSourceInfo *InstantiatedDefaultArg =
1634 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1635 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1636 if (InstantiatedDefaultArg)
1637 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1638 }
1639 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1640 NewTTP);
1641 return NewTTP;
1642 }
1643
1644 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1645 return transformTemplateParameterImpl(TTP, Args);
1646
1647 return transformTemplateParameterImpl(
1648 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1649 }
1650 template<typename TemplateParmDecl>
1651 TemplateParmDecl *
1652 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1653 MultiLevelTemplateArgumentList &Args) {
1654 // Ask the template instantiator to do the heavy lifting for us, then adjust
1655 // the index of the parameter once it's done.
1656 auto *NewParam =
1657 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1658 assert(NewParam->getDepth() == 0 && "unexpected template param depth")((NewParam->getDepth() == 0 && "unexpected template param depth"
) ? static_cast<void> (0) : __assert_fail ("NewParam->getDepth() == 0 && \"unexpected template param depth\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1658, __PRETTY_FUNCTION__))
;
1659 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1660 return NewParam;
1661 }
1662
1663 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1664 FunctionProtoTypeLoc TL,
1665 SmallVectorImpl<ParmVarDecl*> &Params,
1666 MultiLevelTemplateArgumentList &Args) {
1667 SmallVector<QualType, 4> ParamTypes;
1668 const FunctionProtoType *T = TL.getTypePtr();
1669
1670 // -- The types of the function parameters are those of the constructor.
1671 for (auto *OldParam : TL.getParams()) {
1672 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1673 if (!NewParam)
1674 return QualType();
1675 ParamTypes.push_back(NewParam->getType());
1676 Params.push_back(NewParam);
1677 }
1678
1679 // -- The return type is the class template specialization designated by
1680 // the template-name and template arguments corresponding to the
1681 // template parameters obtained from the class template.
1682 //
1683 // We use the injected-class-name type of the primary template instead.
1684 // This has the convenient property that it is different from any type that
1685 // the user can write in a deduction-guide (because they cannot enter the
1686 // context of the template), so implicit deduction guides can never collide
1687 // with explicit ones.
1688 QualType ReturnType = DeducedType;
1689 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1690
1691 // Resolving a wording defect, we also inherit the variadicness of the
1692 // constructor.
1693 FunctionProtoType::ExtProtoInfo EPI;
1694 EPI.Variadic = T->isVariadic();
1695 EPI.HasTrailingReturn = true;
1696
1697 QualType Result = SemaRef.BuildFunctionType(
1698 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1699 if (Result.isNull())
1700 return QualType();
1701
1702 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1703 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1704 NewTL.setLParenLoc(TL.getLParenLoc());
1705 NewTL.setRParenLoc(TL.getRParenLoc());
1706 NewTL.setExceptionSpecRange(SourceRange());
1707 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1708 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1709 NewTL.setParam(I, Params[I]);
1710
1711 return Result;
1712 }
1713
1714 ParmVarDecl *
1715 transformFunctionTypeParam(ParmVarDecl *OldParam,
1716 MultiLevelTemplateArgumentList &Args) {
1717 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1718 TypeSourceInfo *NewDI;
1719 if (!Args.getNumLevels())
1720 NewDI = OldDI;
1721 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1722 // Expand out the one and only element in each inner pack.
1723 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1724 NewDI =
1725 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1726 OldParam->getLocation(), OldParam->getDeclName());
1727 if (!NewDI) return nullptr;
1728 NewDI =
1729 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1730 PackTL.getTypePtr()->getNumExpansions());
1731 } else
1732 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1733 OldParam->getDeclName());
1734 if (!NewDI)
1735 return nullptr;
1736
1737 // Canonicalize the type. This (for instance) replaces references to
1738 // typedef members of the current instantiations with the definitions of
1739 // those typedefs, avoiding triggering instantiation of the deduced type
1740 // during deduction.
1741 // FIXME: It would be preferable to retain type sugar and source
1742 // information here (and handle this in substitution instead).
1743 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1744 SemaRef.Context.getCanonicalType(NewDI->getType()),
1745 OldParam->getLocation());
1746
1747 // Resolving a wording defect, we also inherit default arguments from the
1748 // constructor.
1749 ExprResult NewDefArg;
1750 if (OldParam->hasDefaultArg()) {
1751 NewDefArg = Args.getNumLevels()
1752 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1753 : OldParam->getDefaultArg();
1754 if (NewDefArg.isInvalid())
1755 return nullptr;
1756 }
1757
1758 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1759 OldParam->getInnerLocStart(),
1760 OldParam->getLocation(),
1761 OldParam->getIdentifier(),
1762 NewDI->getType(),
1763 NewDI,
1764 OldParam->getStorageClass(),
1765 NewDefArg.get());
1766 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1767 OldParam->getFunctionScopeIndex());
1768 return NewParam;
1769 }
1770
1771 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1772 bool Explicit, TypeSourceInfo *TInfo,
1773 SourceLocation LocStart, SourceLocation Loc,
1774 SourceLocation LocEnd) {
1775 DeclarationNameInfo Name(DeductionGuideName, Loc);
1776 ArrayRef<ParmVarDecl *> Params =
1777 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1778
1779 // Build the implicit deduction guide template.
1780 auto *Guide =
1781 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1782 Name, TInfo->getType(), TInfo, LocEnd);
1783 Guide->setImplicit();
1784 Guide->setParams(Params);
1785
1786 for (auto *Param : Params)
1787 Param->setDeclContext(Guide);
1788
1789 auto *GuideTemplate = FunctionTemplateDecl::Create(
1790 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1791 GuideTemplate->setImplicit();
1792 Guide->setDescribedFunctionTemplate(GuideTemplate);
1793
1794 if (isa<CXXRecordDecl>(DC)) {
1795 Guide->setAccess(AS_public);
1796 GuideTemplate->setAccess(AS_public);
1797 }
1798
1799 DC->addDecl(GuideTemplate);
1800 return GuideTemplate;
1801 }
1802};
1803}
1804
1805void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1806 SourceLocation Loc) {
1807 DeclContext *DC = Template->getDeclContext();
1808 if (DC->isDependentContext())
1809 return;
1810
1811 ConvertConstructorToDeductionGuideTransform Transform(
1812 *this, cast<ClassTemplateDecl>(Template));
1813 if (!isCompleteType(Loc, Transform.DeducedType))
1814 return;
1815
1816 // Check whether we've already declared deduction guides for this template.
1817 // FIXME: Consider storing a flag on the template to indicate this.
1818 auto Existing = DC->lookup(Transform.DeductionGuideName);
1819 for (auto *D : Existing)
1820 if (D->isImplicit())
1821 return;
1822
1823 // In case we were expanding a pack when we attempted to declare deduction
1824 // guides, turn off pack expansion for everything we're about to do.
1825 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1826 // Create a template instantiation record to track the "instantiation" of
1827 // constructors into deduction guides.
1828 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1829 // this substitution process actually fail?
1830 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1831
1832 // Convert declared constructors into deduction guide templates.
1833 // FIXME: Skip constructors for which deduction must necessarily fail (those
1834 // for which some class template parameter without a default argument never
1835 // appears in a deduced context).
1836 bool AddedAny = false;
1837 bool AddedCopyOrMove = false;
1838 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1839 D = D->getUnderlyingDecl();
1840 if (D->isInvalidDecl() || D->isImplicit())
1841 continue;
1842 D = cast<NamedDecl>(D->getCanonicalDecl());
1843
1844 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1845 auto *CD =
1846 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1847 // Class-scope explicit specializations (MS extension) do not result in
1848 // deduction guides.
1849 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1850 continue;
1851
1852 Transform.transformConstructor(FTD, CD);
1853 AddedAny = true;
1854
1855 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1856 }
1857
1858 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1859 // FIXME: The standard doesn't say (how) to do this.
1860 if (!AddedAny)
1861 Transform.buildSimpleDeductionGuide(None);
1862
1863 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1864 // resembling a copy or move constructor.
1865 // FIXME: The standard doesn't say (how) to do this.
1866 if (!AddedCopyOrMove)
1867 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1868}
1869
1870/// \brief Diagnose the presence of a default template argument on a
1871/// template parameter, which is ill-formed in certain contexts.
1872///
1873/// \returns true if the default template argument should be dropped.
1874static bool DiagnoseDefaultTemplateArgument(Sema &S,
1875 Sema::TemplateParamListContext TPC,
1876 SourceLocation ParamLoc,
1877 SourceRange DefArgRange) {
1878 switch (TPC) {
1879 case Sema::TPC_ClassTemplate:
1880 case Sema::TPC_VarTemplate:
1881 case Sema::TPC_TypeAliasTemplate:
1882 return false;
1883
1884 case Sema::TPC_FunctionTemplate:
1885 case Sema::TPC_FriendFunctionTemplateDefinition:
1886 // C++ [temp.param]p9:
1887 // A default template-argument shall not be specified in a
1888 // function template declaration or a function template
1889 // definition [...]
1890 // If a friend function template declaration specifies a default
1891 // template-argument, that declaration shall be a definition and shall be
1892 // the only declaration of the function template in the translation unit.
1893 // (C++98/03 doesn't have this wording; see DR226).
1894 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1895 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1896 : diag::ext_template_parameter_default_in_function_template)
1897 << DefArgRange;
1898 return false;
1899
1900 case Sema::TPC_ClassTemplateMember:
1901 // C++0x [temp.param]p9:
1902 // A default template-argument shall not be specified in the
1903 // template-parameter-lists of the definition of a member of a
1904 // class template that appears outside of the member's class.
1905 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1906 << DefArgRange;
1907 return true;
1908
1909 case Sema::TPC_FriendClassTemplate:
1910 case Sema::TPC_FriendFunctionTemplate:
1911 // C++ [temp.param]p9:
1912 // A default template-argument shall not be specified in a
1913 // friend template declaration.
1914 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1915 << DefArgRange;
1916 return true;
1917
1918 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1919 // for friend function templates if there is only a single
1920 // declaration (and it is a definition). Strange!
1921 }
1922
1923 llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1923)
;
1924}
1925
1926/// \brief Check for unexpanded parameter packs within the template parameters
1927/// of a template template parameter, recursively.
1928static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1929 TemplateTemplateParmDecl *TTP) {
1930 // A template template parameter which is a parameter pack is also a pack
1931 // expansion.
1932 if (TTP->isParameterPack())
1933 return false;
1934
1935 TemplateParameterList *Params = TTP->getTemplateParameters();
1936 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1937 NamedDecl *P = Params->getParam(I);
1938 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1939 if (!NTTP->isParameterPack() &&
1940 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1941 NTTP->getTypeSourceInfo(),
1942 Sema::UPPC_NonTypeTemplateParameterType))
1943 return true;
1944
1945 continue;
1946 }
1947
1948 if (TemplateTemplateParmDecl *InnerTTP
1949 = dyn_cast<TemplateTemplateParmDecl>(P))
1950 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1951 return true;
1952 }
1953
1954 return false;
1955}
1956
1957/// \brief Checks the validity of a template parameter list, possibly
1958/// considering the template parameter list from a previous
1959/// declaration.
1960///
1961/// If an "old" template parameter list is provided, it must be
1962/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1963/// template parameter list.
1964///
1965/// \param NewParams Template parameter list for a new template
1966/// declaration. This template parameter list will be updated with any
1967/// default arguments that are carried through from the previous
1968/// template parameter list.
1969///
1970/// \param OldParams If provided, template parameter list from a
1971/// previous declaration of the same template. Default template
1972/// arguments will be merged from the old template parameter list to
1973/// the new template parameter list.
1974///
1975/// \param TPC Describes the context in which we are checking the given
1976/// template parameter list.
1977///
1978/// \returns true if an error occurred, false otherwise.
1979bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1980 TemplateParameterList *OldParams,
1981 TemplateParamListContext TPC) {
1982 bool Invalid = false;
1983
1984 // C++ [temp.param]p10:
1985 // The set of default template-arguments available for use with a
1986 // template declaration or definition is obtained by merging the
1987 // default arguments from the definition (if in scope) and all
1988 // declarations in scope in the same way default function
1989 // arguments are (8.3.6).
1990 bool SawDefaultArgument = false;
1991 SourceLocation PreviousDefaultArgLoc;
1992
1993 // Dummy initialization to avoid warnings.
1994 TemplateParameterList::iterator OldParam = NewParams->end();
1995 if (OldParams)
1996 OldParam = OldParams->begin();
1997
1998 bool RemoveDefaultArguments = false;
1999 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2000 NewParamEnd = NewParams->end();
2001 NewParam != NewParamEnd; ++NewParam) {
2002 // Variables used to diagnose redundant default arguments
2003 bool RedundantDefaultArg = false;
2004 SourceLocation OldDefaultLoc;
2005 SourceLocation NewDefaultLoc;
2006
2007 // Variable used to diagnose missing default arguments
2008 bool MissingDefaultArg = false;
2009
2010 // Variable used to diagnose non-final parameter packs
2011 bool SawParameterPack = false;
2012
2013 if (TemplateTypeParmDecl *NewTypeParm
2014 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2015 // Check the presence of a default argument here.
2016 if (NewTypeParm->hasDefaultArgument() &&
2017 DiagnoseDefaultTemplateArgument(*this, TPC,
2018 NewTypeParm->getLocation(),
2019 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2020 .getSourceRange()))
2021 NewTypeParm->removeDefaultArgument();
2022
2023 // Merge default arguments for template type parameters.
2024 TemplateTypeParmDecl *OldTypeParm
2025 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2026 if (NewTypeParm->isParameterPack()) {
2027 assert(!NewTypeParm->hasDefaultArgument() &&((!NewTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2028, __PRETTY_FUNCTION__))
2028 "Parameter packs can't have a default argument!")((!NewTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2028, __PRETTY_FUNCTION__))
;
2029 SawParameterPack = true;
2030 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2031 NewTypeParm->hasDefaultArgument()) {
2032 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2033 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2034 SawDefaultArgument = true;
2035 RedundantDefaultArg = true;
2036 PreviousDefaultArgLoc = NewDefaultLoc;
2037 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2038 // Merge the default argument from the old declaration to the
2039 // new declaration.
2040 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2041 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2042 } else if (NewTypeParm->hasDefaultArgument()) {
2043 SawDefaultArgument = true;
2044 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2045 } else if (SawDefaultArgument)
2046 MissingDefaultArg = true;
2047 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2048 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2049 // Check for unexpanded parameter packs.
2050 if (!NewNonTypeParm->isParameterPack() &&
2051 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2052 NewNonTypeParm->getTypeSourceInfo(),
2053 UPPC_NonTypeTemplateParameterType)) {
2054 Invalid = true;
2055 continue;
2056 }
2057
2058 // Check the presence of a default argument here.
2059 if (NewNonTypeParm->hasDefaultArgument() &&
2060 DiagnoseDefaultTemplateArgument(*this, TPC,
2061 NewNonTypeParm->getLocation(),
2062 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2063 NewNonTypeParm->removeDefaultArgument();
2064 }
2065
2066 // Merge default arguments for non-type template parameters
2067 NonTypeTemplateParmDecl *OldNonTypeParm
2068 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2069 if (NewNonTypeParm->isParameterPack()) {
2070 assert(!NewNonTypeParm->hasDefaultArgument() &&((!NewNonTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2071, __PRETTY_FUNCTION__))
2071 "Parameter packs can't have a default argument!")((!NewNonTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2071, __PRETTY_FUNCTION__))
;
2072 if (!NewNonTypeParm->isPackExpansion())
2073 SawParameterPack = true;
2074 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2075 NewNonTypeParm->hasDefaultArgument()) {
2076 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2077 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2078 SawDefaultArgument = true;
2079 RedundantDefaultArg = true;
2080 PreviousDefaultArgLoc = NewDefaultLoc;
2081 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2082 // Merge the default argument from the old declaration to the
2083 // new declaration.
2084 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2085 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2086 } else if (NewNonTypeParm->hasDefaultArgument()) {
2087 SawDefaultArgument = true;
2088 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2089 } else if (SawDefaultArgument)
2090 MissingDefaultArg = true;
2091 } else {
2092 TemplateTemplateParmDecl *NewTemplateParm
2093 = cast<TemplateTemplateParmDecl>(*NewParam);
2094
2095 // Check for unexpanded parameter packs, recursively.
2096 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2097 Invalid = true;
2098 continue;
2099 }
2100
2101 // Check the presence of a default argument here.
2102 if (NewTemplateParm->hasDefaultArgument() &&
2103 DiagnoseDefaultTemplateArgument(*this, TPC,
2104 NewTemplateParm->getLocation(),
2105 NewTemplateParm->getDefaultArgument().getSourceRange()))
2106 NewTemplateParm->removeDefaultArgument();
2107
2108 // Merge default arguments for template template parameters
2109 TemplateTemplateParmDecl *OldTemplateParm
2110 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2111 if (NewTemplateParm->isParameterPack()) {
2112 assert(!NewTemplateParm->hasDefaultArgument() &&((!NewTemplateParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2113, __PRETTY_FUNCTION__))
2113 "Parameter packs can't have a default argument!")((!NewTemplateParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2113, __PRETTY_FUNCTION__))
;
2114 if (!NewTemplateParm->isPackExpansion())
2115 SawParameterPack = true;
2116 } else if (OldTemplateParm &&
2117 hasVisibleDefaultArgument(OldTemplateParm) &&
2118 NewTemplateParm->hasDefaultArgument()) {
2119 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2120 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2121 SawDefaultArgument = true;
2122 RedundantDefaultArg = true;
2123 PreviousDefaultArgLoc = NewDefaultLoc;
2124 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2125 // Merge the default argument from the old declaration to the
2126 // new declaration.
2127 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2128 PreviousDefaultArgLoc
2129 = OldTemplateParm->getDefaultArgument().getLocation();
2130 } else if (NewTemplateParm->hasDefaultArgument()) {
2131 SawDefaultArgument = true;
2132 PreviousDefaultArgLoc
2133 = NewTemplateParm->getDefaultArgument().getLocation();
2134 } else if (SawDefaultArgument)
2135 MissingDefaultArg = true;
2136 }
2137
2138 // C++11 [temp.param]p11:
2139 // If a template parameter of a primary class template or alias template
2140 // is a template parameter pack, it shall be the last template parameter.
2141 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2142 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2143 TPC == TPC_TypeAliasTemplate)) {
2144 Diag((*NewParam)->getLocation(),
2145 diag::err_template_param_pack_must_be_last_template_parameter);
2146 Invalid = true;
2147 }
2148
2149 if (RedundantDefaultArg) {
2150 // C++ [temp.param]p12:
2151 // A template-parameter shall not be given default arguments
2152 // by two different declarations in the same scope.
2153 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2154 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2155 Invalid = true;
2156 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2157 // C++ [temp.param]p11:
2158 // If a template-parameter of a class template has a default
2159 // template-argument, each subsequent template-parameter shall either
2160 // have a default template-argument supplied or be a template parameter
2161 // pack.
2162 Diag((*NewParam)->getLocation(),
2163 diag::err_template_param_default_arg_missing);
2164 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2165 Invalid = true;
2166 RemoveDefaultArguments = true;
2167 }
2168
2169 // If we have an old template parameter list that we're merging
2170 // in, move on to the next parameter.
2171 if (OldParams)
2172 ++OldParam;
2173 }
2174
2175 // We were missing some default arguments at the end of the list, so remove
2176 // all of the default arguments.
2177 if (RemoveDefaultArguments) {
2178 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2179 NewParamEnd = NewParams->end();
2180 NewParam != NewParamEnd; ++NewParam) {
2181 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2182 TTP->removeDefaultArgument();
2183 else if (NonTypeTemplateParmDecl *NTTP
2184 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2185 NTTP->removeDefaultArgument();
2186 else
2187 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2188 }
2189 }
2190
2191 return Invalid;
2192}
2193
2194namespace {
2195
2196/// A class which looks for a use of a certain level of template
2197/// parameter.
2198struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2199 typedef RecursiveASTVisitor<DependencyChecker> super;
2200
2201 unsigned Depth;
2202
2203 // Whether we're looking for a use of a template parameter that makes the
2204 // overall construct type-dependent / a dependent type. This is strictly
2205 // best-effort for now; we may fail to match at all for a dependent type
2206 // in some cases if this is set.
2207 bool IgnoreNonTypeDependent;
2208
2209 bool Match;
2210 SourceLocation MatchLoc;
2211
2212 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2213 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2214 Match(false) {}
2215
2216 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2217 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2218 NamedDecl *ND = Params->getParam(0);
2219 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2220 Depth = PD->getDepth();
2221 } else if (NonTypeTemplateParmDecl *PD =
2222 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2223 Depth = PD->getDepth();
2224 } else {
2225 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2226 }
2227 }
2228
2229 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2230 if (ParmDepth >= Depth) {
2231 Match = true;
2232 MatchLoc = Loc;
2233 return true;
2234 }
2235 return false;
2236 }
2237
2238 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2239 // Prune out non-type-dependent expressions if requested. This can
2240 // sometimes result in us failing to find a template parameter reference
2241 // (if a value-dependent expression creates a dependent type), but this
2242 // mode is best-effort only.
2243 if (auto *E = dyn_cast_or_null<Expr>(S))
2244 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2245 return true;
2246 return super::TraverseStmt(S, Q);
2247 }
2248
2249 bool TraverseTypeLoc(TypeLoc TL) {
2250 if (IgnoreNonTypeDependent && !TL.isNull() &&
2251 !TL.getType()->isDependentType())
2252 return true;
2253 return super::TraverseTypeLoc(TL);
2254 }
2255
2256 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2257 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2258 }
2259
2260 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2261 // For a best-effort search, keep looking until we find a location.
2262 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2263 }
2264
2265 bool TraverseTemplateName(TemplateName N) {
2266 if (TemplateTemplateParmDecl *PD =
2267 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2268 if (Matches(PD->getDepth()))
2269 return false;
2270 return super::TraverseTemplateName(N);
2271 }
2272
2273 bool VisitDeclRefExpr(DeclRefExpr *E) {
2274 if (NonTypeTemplateParmDecl *PD =
2275 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2276 if (Matches(PD->getDepth(), E->getExprLoc()))
2277 return false;
2278 return super::VisitDeclRefExpr(E);
2279 }
2280
2281 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2282 return TraverseType(T->getReplacementType());
2283 }
2284
2285 bool
2286 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2287 return TraverseTemplateArgument(T->getArgumentPack());
2288 }
2289
2290 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2291 return TraverseType(T->getInjectedSpecializationType());
2292 }
2293};
2294} // end anonymous namespace
2295
2296/// Determines whether a given type depends on the given parameter
2297/// list.
2298static bool
2299DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2300 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2301 Checker.TraverseType(T);
2302 return Checker.Match;
2303}
2304
2305// Find the source range corresponding to the named type in the given
2306// nested-name-specifier, if any.
2307static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2308 QualType T,
2309 const CXXScopeSpec &SS) {
2310 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2311 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2312 if (const Type *CurType = NNS->getAsType()) {
2313 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2314 return NNSLoc.getTypeLoc().getSourceRange();
2315 } else
2316 break;
2317
2318 NNSLoc = NNSLoc.getPrefix();
2319 }
2320
2321 return SourceRange();
2322}
2323
2324/// \brief Match the given template parameter lists to the given scope
2325/// specifier, returning the template parameter list that applies to the
2326/// name.
2327///
2328/// \param DeclStartLoc the start of the declaration that has a scope
2329/// specifier or a template parameter list.
2330///
2331/// \param DeclLoc The location of the declaration itself.
2332///
2333/// \param SS the scope specifier that will be matched to the given template
2334/// parameter lists. This scope specifier precedes a qualified name that is
2335/// being declared.
2336///
2337/// \param TemplateId The template-id following the scope specifier, if there
2338/// is one. Used to check for a missing 'template<>'.
2339///
2340/// \param ParamLists the template parameter lists, from the outermost to the
2341/// innermost template parameter lists.
2342///
2343/// \param IsFriend Whether to apply the slightly different rules for
2344/// matching template parameters to scope specifiers in friend
2345/// declarations.
2346///
2347/// \param IsMemberSpecialization will be set true if the scope specifier
2348/// denotes a fully-specialized type, and therefore this is a declaration of
2349/// a member specialization.
2350///
2351/// \returns the template parameter list, if any, that corresponds to the
2352/// name that is preceded by the scope specifier @p SS. This template
2353/// parameter list may have template parameters (if we're declaring a
2354/// template) or may have no template parameters (if we're declaring a
2355/// template specialization), or may be NULL (if what we're declaring isn't
2356/// itself a template).
2357TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2358 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2359 TemplateIdAnnotation *TemplateId,
2360 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2361 bool &IsMemberSpecialization, bool &Invalid) {
2362 IsMemberSpecialization = false;
2363 Invalid = false;
2364
2365 // The sequence of nested types to which we will match up the template
2366 // parameter lists. We first build this list by starting with the type named
2367 // by the nested-name-specifier and walking out until we run out of types.
2368 SmallVector<QualType, 4> NestedTypes;
2369 QualType T;
2370 if (SS.getScopeRep()) {
2371 if (CXXRecordDecl *Record
2372 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2373 T = Context.getTypeDeclType(Record);
2374 else
2375 T = QualType(SS.getScopeRep()->getAsType(), 0);
2376 }
2377
2378 // If we found an explicit specialization that prevents us from needing
2379 // 'template<>' headers, this will be set to the location of that
2380 // explicit specialization.
2381 SourceLocation ExplicitSpecLoc;
2382
2383 while (!T.isNull()) {
2384 NestedTypes.push_back(T);
2385
2386 // Retrieve the parent of a record type.
2387 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2388 // If this type is an explicit specialization, we're done.
2389 if (ClassTemplateSpecializationDecl *Spec
2390 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2391 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2392 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2393 ExplicitSpecLoc = Spec->getLocation();
2394 break;
2395 }
2396 } else if (Record->getTemplateSpecializationKind()
2397 == TSK_ExplicitSpecialization) {
2398 ExplicitSpecLoc = Record->getLocation();
2399 break;
2400 }
2401
2402 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2403 T = Context.getTypeDeclType(Parent);
2404 else
2405 T = QualType();
2406 continue;
2407 }
2408
2409 if (const TemplateSpecializationType *TST
2410 = T->getAs<TemplateSpecializationType>()) {
2411 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2412 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2413 T = Context.getTypeDeclType(Parent);
2414 else
2415 T = QualType();
2416 continue;
2417 }
2418 }
2419
2420 // Look one step prior in a dependent template specialization type.
2421 if (const DependentTemplateSpecializationType *DependentTST
2422 = T->getAs<DependentTemplateSpecializationType>()) {
2423 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2424 T = QualType(NNS->getAsType(), 0);
2425 else
2426 T = QualType();
2427 continue;
2428 }
2429
2430 // Look one step prior in a dependent name type.
2431 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2432 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2433 T = QualType(NNS->getAsType(), 0);
2434 else
2435 T = QualType();
2436 continue;
2437 }
2438
2439 // Retrieve the parent of an enumeration type.
2440 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2441 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2442 // check here.
2443 EnumDecl *Enum = EnumT->getDecl();
2444
2445 // Get to the parent type.
2446 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2447 T = Context.getTypeDeclType(Parent);
2448 else
2449 T = QualType();
2450 continue;
2451 }
2452
2453 T = QualType();
2454 }
2455 // Reverse the nested types list, since we want to traverse from the outermost
2456 // to the innermost while checking template-parameter-lists.
2457 std::reverse(NestedTypes.begin(), NestedTypes.end());
2458
2459 // C++0x [temp.expl.spec]p17:
2460 // A member or a member template may be nested within many
2461 // enclosing class templates. In an explicit specialization for
2462 // such a member, the member declaration shall be preceded by a
2463 // template<> for each enclosing class template that is
2464 // explicitly specialized.
2465 bool SawNonEmptyTemplateParameterList = false;
2466
2467 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2468 if (SawNonEmptyTemplateParameterList) {
2469 Diag(DeclLoc, diag::err_specialize_member_of_template)
2470 << !Recovery << Range;
2471 Invalid = true;
2472 IsMemberSpecialization = false;
2473 return true;
2474 }
2475
2476 return false;
2477 };
2478
2479 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2480 // Check that we can have an explicit specialization here.
2481 if (CheckExplicitSpecialization(Range, true))
2482 return true;
2483
2484 // We don't have a template header, but we should.
2485 SourceLocation ExpectedTemplateLoc;
2486 if (!ParamLists.empty())
2487 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2488 else
2489 ExpectedTemplateLoc = DeclStartLoc;
2490
2491 Diag(DeclLoc, diag::err_template_spec_needs_header)
2492 << Range
2493 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2494 return false;
2495 };
2496
2497 unsigned ParamIdx = 0;
2498 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2499 ++TypeIdx) {
2500 T = NestedTypes[TypeIdx];
2501
2502 // Whether we expect a 'template<>' header.
2503 bool NeedEmptyTemplateHeader = false;
2504
2505 // Whether we expect a template header with parameters.
2506 bool NeedNonemptyTemplateHeader = false;
2507
2508 // For a dependent type, the set of template parameters that we
2509 // expect to see.
2510 TemplateParameterList *ExpectedTemplateParams = nullptr;
2511
2512 // C++0x [temp.expl.spec]p15:
2513 // A member or a member template may be nested within many enclosing
2514 // class templates. In an explicit specialization for such a member, the
2515 // member declaration shall be preceded by a template<> for each
2516 // enclosing class template that is explicitly specialized.
2517 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2518 if (ClassTemplatePartialSpecializationDecl *Partial
2519 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2520 ExpectedTemplateParams = Partial->getTemplateParameters();
2521 NeedNonemptyTemplateHeader = true;
2522 } else if (Record->isDependentType()) {
2523 if (Record->getDescribedClassTemplate()) {
2524 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2525 ->getTemplateParameters();
2526 NeedNonemptyTemplateHeader = true;
2527 }
2528 } else if (ClassTemplateSpecializationDecl *Spec
2529 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2530 // C++0x [temp.expl.spec]p4:
2531 // Members of an explicitly specialized class template are defined
2532 // in the same manner as members of normal classes, and not using
2533 // the template<> syntax.
2534 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2535 NeedEmptyTemplateHeader = true;
2536 else
2537 continue;
2538 } else if (Record->getTemplateSpecializationKind()) {
2539 if (Record->getTemplateSpecializationKind()
2540 != TSK_ExplicitSpecialization &&
2541 TypeIdx == NumTypes - 1)
2542 IsMemberSpecialization = true;
2543
2544 continue;
2545 }
2546 } else if (const TemplateSpecializationType *TST
2547 = T->getAs<TemplateSpecializationType>()) {
2548 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2549 ExpectedTemplateParams = Template->getTemplateParameters();
2550 NeedNonemptyTemplateHeader = true;
2551 }
2552 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2553 // FIXME: We actually could/should check the template arguments here
2554 // against the corresponding template parameter list.
2555 NeedNonemptyTemplateHeader = false;
2556 }
2557
2558 // C++ [temp.expl.spec]p16:
2559 // In an explicit specialization declaration for a member of a class
2560 // template or a member template that ap- pears in namespace scope, the
2561 // member template and some of its enclosing class templates may remain
2562 // unspecialized, except that the declaration shall not explicitly
2563 // specialize a class member template if its en- closing class templates
2564 // are not explicitly specialized as well.
2565 if (ParamIdx < ParamLists.size()) {
2566 if (ParamLists[ParamIdx]->size() == 0) {
2567 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2568 false))
2569 return nullptr;
2570 } else
2571 SawNonEmptyTemplateParameterList = true;
2572 }
2573
2574 if (NeedEmptyTemplateHeader) {
2575 // If we're on the last of the types, and we need a 'template<>' header
2576 // here, then it's a member specialization.
2577 if (TypeIdx == NumTypes - 1)
2578 IsMemberSpecialization = true;
2579
2580 if (ParamIdx < ParamLists.size()) {
2581 if (ParamLists[ParamIdx]->size() > 0) {
2582 // The header has template parameters when it shouldn't. Complain.
2583 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2584 diag::err_template_param_list_matches_nontemplate)
2585 << T
2586 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2587 ParamLists[ParamIdx]->getRAngleLoc())
2588 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2589 Invalid = true;
2590 return nullptr;
2591 }
2592
2593 // Consume this template header.
2594 ++ParamIdx;
2595 continue;
2596 }
2597
2598 if (!IsFriend)
2599 if (DiagnoseMissingExplicitSpecialization(
2600 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2601 return nullptr;
2602
2603 continue;
2604 }
2605
2606 if (NeedNonemptyTemplateHeader) {
2607 // In friend declarations we can have template-ids which don't
2608 // depend on the corresponding template parameter lists. But
2609 // assume that empty parameter lists are supposed to match this
2610 // template-id.
2611 if (IsFriend && T->isDependentType()) {
2612 if (ParamIdx < ParamLists.size() &&
2613 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2614 ExpectedTemplateParams = nullptr;
2615 else
2616 continue;
2617 }
2618
2619 if (ParamIdx < ParamLists.size()) {
2620 // Check the template parameter list, if we can.
2621 if (ExpectedTemplateParams &&
2622 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2623 ExpectedTemplateParams,
2624 true, TPL_TemplateMatch))
2625 Invalid = true;
2626
2627 if (!Invalid &&
2628 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2629 TPC_ClassTemplateMember))
2630 Invalid = true;
2631
2632 ++ParamIdx;
2633 continue;
2634 }
2635
2636 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2637 << T
2638 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2639 Invalid = true;
2640 continue;
2641 }
2642 }
2643
2644 // If there were at least as many template-ids as there were template
2645 // parameter lists, then there are no template parameter lists remaining for
2646 // the declaration itself.
2647 if (ParamIdx >= ParamLists.size()) {
2648 if (TemplateId && !IsFriend) {
2649 // We don't have a template header for the declaration itself, but we
2650 // should.
2651 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2652 TemplateId->RAngleLoc));
2653
2654 // Fabricate an empty template parameter list for the invented header.
2655 return TemplateParameterList::Create(Context, SourceLocation(),
2656 SourceLocation(), None,
2657 SourceLocation(), nullptr);
2658 }
2659
2660 return nullptr;
2661 }
2662
2663 // If there were too many template parameter lists, complain about that now.
2664 if (ParamIdx < ParamLists.size() - 1) {
2665 bool HasAnyExplicitSpecHeader = false;
2666 bool AllExplicitSpecHeaders = true;
2667 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2668 if (ParamLists[I]->size() == 0)
2669 HasAnyExplicitSpecHeader = true;
2670 else
2671 AllExplicitSpecHeaders = false;
2672 }
2673
2674 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2675 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2676 : diag::err_template_spec_extra_headers)
2677 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2678 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2679
2680 // If there was a specialization somewhere, such that 'template<>' is
2681 // not required, and there were any 'template<>' headers, note where the
2682 // specialization occurred.
2683 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2684 Diag(ExplicitSpecLoc,
2685 diag::note_explicit_template_spec_does_not_need_header)
2686 << NestedTypes.back();
2687
2688 // We have a template parameter list with no corresponding scope, which
2689 // means that the resulting template declaration can't be instantiated
2690 // properly (we'll end up with dependent nodes when we shouldn't).
2691 if (!AllExplicitSpecHeaders)
2692 Invalid = true;
2693 }
2694
2695 // C++ [temp.expl.spec]p16:
2696 // In an explicit specialization declaration for a member of a class
2697 // template or a member template that ap- pears in namespace scope, the
2698 // member template and some of its enclosing class templates may remain
2699 // unspecialized, except that the declaration shall not explicitly
2700 // specialize a class member template if its en- closing class templates
2701 // are not explicitly specialized as well.
2702 if (ParamLists.back()->size() == 0 &&
2703 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2704 false))
2705 return nullptr;
2706
2707 // Return the last template parameter list, which corresponds to the
2708 // entity being declared.
2709 return ParamLists.back();
2710}
2711
2712void Sema::NoteAllFoundTemplates(TemplateName Name) {
2713 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2714 Diag(Template->getLocation(), diag::note_template_declared_here)
2715 << (isa<FunctionTemplateDecl>(Template)
2716 ? 0
2717 : isa<ClassTemplateDecl>(Template)
2718 ? 1
2719 : isa<VarTemplateDecl>(Template)
2720 ? 2
2721 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2722 << Template->getDeclName();
2723 return;
2724 }
2725
2726 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2727 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2728 IEnd = OST->end();
2729 I != IEnd; ++I)
2730 Diag((*I)->getLocation(), diag::note_template_declared_here)
2731 << 0 << (*I)->getDeclName();
2732
2733 return;
2734 }
2735}
2736
2737static QualType
2738checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2739 const SmallVectorImpl<TemplateArgument> &Converted,
2740 SourceLocation TemplateLoc,
2741 TemplateArgumentListInfo &TemplateArgs) {
2742 ASTContext &Context = SemaRef.getASTContext();
2743 switch (BTD->getBuiltinTemplateKind()) {
2744 case BTK__make_integer_seq: {
2745 // Specializations of __make_integer_seq<S, T, N> are treated like
2746 // S<T, 0, ..., N-1>.
2747
2748 // C++14 [inteseq.intseq]p1:
2749 // T shall be an integer type.
2750 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2751 SemaRef.Diag(TemplateArgs[1].getLocation(),
2752 diag::err_integer_sequence_integral_element_type);
2753 return QualType();
2754 }
2755
2756 // C++14 [inteseq.make]p1:
2757 // If N is negative the program is ill-formed.
2758 TemplateArgument NumArgsArg = Converted[2];
2759 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2760 if (NumArgs < 0) {
2761 SemaRef.Diag(TemplateArgs[2].getLocation(),
2762 diag::err_integer_sequence_negative_length);
2763 return QualType();
2764 }
2765
2766 QualType ArgTy = NumArgsArg.getIntegralType();
2767 TemplateArgumentListInfo SyntheticTemplateArgs;
2768 // The type argument gets reused as the first template argument in the
2769 // synthetic template argument list.
2770 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2771 // Expand N into 0 ... N-1.
2772 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2773 I < NumArgs; ++I) {
2774 TemplateArgument TA(Context, I, ArgTy);
2775 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2776 TA, ArgTy, TemplateArgs[2].getLocation()));
2777 }
2778 // The first template argument will be reused as the template decl that
2779 // our synthetic template arguments will be applied to.
2780 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2781 TemplateLoc, SyntheticTemplateArgs);
2782 }
2783
2784 case BTK__type_pack_element:
2785 // Specializations of
2786 // __type_pack_element<Index, T_1, ..., T_N>
2787 // are treated like T_Index.
2788 assert(Converted.size() == 2 &&((Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? static_cast<void> (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2789, __PRETTY_FUNCTION__))
2789 "__type_pack_element should be given an index and a parameter pack")((Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? static_cast<void> (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2789, __PRETTY_FUNCTION__))
;
2790
2791 // If the Index is out of bounds, the program is ill-formed.
2792 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2793 llvm::APSInt Index = IndexArg.getAsIntegral();
2794 assert(Index >= 0 && "the index used with __type_pack_element should be of "((Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? static_cast
<void> (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2795, __PRETTY_FUNCTION__))
2795 "type std::size_t, and hence be non-negative")((Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? static_cast
<void> (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2795, __PRETTY_FUNCTION__))
;
2796 if (Index >= Ts.pack_size()) {
2797 SemaRef.Diag(TemplateArgs[0].getLocation(),
2798 diag::err_type_pack_element_out_of_bounds);
2799 return QualType();
2800 }
2801
2802 // We simply return the type at index `Index`.
2803 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2804 return Nth->getAsType();
2805 }
2806 llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2806)
;
2807}
2808
2809QualType Sema::CheckTemplateIdType(TemplateName Name,
2810 SourceLocation TemplateLoc,
2811 TemplateArgumentListInfo &TemplateArgs) {
2812 DependentTemplateName *DTN
2813 = Name.getUnderlying().getAsDependentTemplateName();
2814 if (DTN && DTN->isIdentifier())
2815 // When building a template-id where the template-name is dependent,
2816 // assume the template is a type template. Either our assumption is
2817 // correct, or the code is ill-formed and will be diagnosed when the
2818 // dependent name is substituted.
2819 return Context.getDependentTemplateSpecializationType(ETK_None,
2820 DTN->getQualifier(),
2821 DTN->getIdentifier(),
2822 TemplateArgs);
2823
2824 TemplateDecl *Template = Name.getAsTemplateDecl();
2825 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2826 isa<VarTemplateDecl>(Template)) {
2827 // We might have a substituted template template parameter pack. If so,
2828 // build a template specialization type for it.
2829 if (Name.getAsSubstTemplateTemplateParmPack())
2830 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2831
2832 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2833 << Name;
2834 NoteAllFoundTemplates(Name);
2835 return QualType();
2836 }
2837
2838 // Check that the template argument list is well-formed for this
2839 // template.
2840 SmallVector<TemplateArgument, 4> Converted;
2841 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2842 false, Converted))
2843 return QualType();
2844
2845 QualType CanonType;
2846
2847 bool InstantiationDependent = false;
2848 if (TypeAliasTemplateDecl *AliasTemplate =
2849 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2850 // Find the canonical type for this type alias template specialization.
2851 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2852 if (Pattern->isInvalidDecl())
2853 return QualType();
2854
2855 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2856 Converted);
2857
2858 // Only substitute for the innermost template argument list.
2859 MultiLevelTemplateArgumentList TemplateArgLists;
2860 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2861 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2862 for (unsigned I = 0; I < Depth; ++I)
2863 TemplateArgLists.addOuterTemplateArguments(None);
2864
2865 LocalInstantiationScope Scope(*this);
2866 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2867 if (Inst.isInvalid())
2868 return QualType();
2869
2870 CanonType = SubstType(Pattern->getUnderlyingType(),
2871 TemplateArgLists, AliasTemplate->getLocation(),
2872 AliasTemplate->getDeclName());
2873 if (CanonType.isNull())
2874 return QualType();
2875 } else if (Name.isDependent() ||
2876 TemplateSpecializationType::anyDependentTemplateArguments(
2877 TemplateArgs, InstantiationDependent)) {
2878 // This class template specialization is a dependent
2879 // type. Therefore, its canonical type is another class template
2880 // specialization type that contains all of the converted
2881 // arguments in canonical form. This ensures that, e.g., A<T> and
2882 // A<T, T> have identical types when A is declared as:
2883 //
2884 // template<typename T, typename U = T> struct A;
2885 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
2886
2887 // This might work out to be a current instantiation, in which
2888 // case the canonical type needs to be the InjectedClassNameType.
2889 //
2890 // TODO: in theory this could be a simple hashtable lookup; most
2891 // changes to CurContext don't change the set of current
2892 // instantiations.
2893 if (isa<ClassTemplateDecl>(Template)) {
2894 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2895 // If we get out to a namespace, we're done.
2896 if (Ctx->isFileContext()) break;
2897
2898 // If this isn't a record, keep looking.
2899 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2900 if (!Record) continue;
2901
2902 // Look for one of the two cases with InjectedClassNameTypes
2903 // and check whether it's the same template.
2904 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2905 !Record->getDescribedClassTemplate())
2906 continue;
2907
2908 // Fetch the injected class name type and check whether its
2909 // injected type is equal to the type we just built.
2910 QualType ICNT = Context.getTypeDeclType(Record);
2911 QualType Injected = cast<InjectedClassNameType>(ICNT)
2912 ->getInjectedSpecializationType();
2913
2914 if (CanonType != Injected->getCanonicalTypeInternal())
2915 continue;
2916
2917 // If so, the canonical type of this TST is the injected
2918 // class name type of the record we just found.
2919 assert(ICNT.isCanonical())((ICNT.isCanonical()) ? static_cast<void> (0) : __assert_fail
("ICNT.isCanonical()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2919, __PRETTY_FUNCTION__))
;
2920 CanonType = ICNT;
2921 break;
2922 }
2923 }
2924 } else if (ClassTemplateDecl *ClassTemplate
2925 = dyn_cast<ClassTemplateDecl>(Template)) {
2926 // Find the class template specialization declaration that
2927 // corresponds to these arguments.
2928 void *InsertPos = nullptr;
2929 ClassTemplateSpecializationDecl *Decl
2930 = ClassTemplate->findSpecialization(Converted, InsertPos);
2931 if (!Decl) {
2932 // This is the first time we have referenced this class template
2933 // specialization. Create the canonical declaration and add it to
2934 // the set of specializations.
2935 Decl = ClassTemplateSpecializationDecl::Create(Context,
2936 ClassTemplate->getTemplatedDecl()->getTagKind(),
2937 ClassTemplate->getDeclContext(),
2938 ClassTemplate->getTemplatedDecl()->getLocStart(),
2939 ClassTemplate->getLocation(),
2940 ClassTemplate,
2941 Converted, nullptr);
2942 ClassTemplate->AddSpecialization(Decl, InsertPos);
2943 if (ClassTemplate->isOutOfLine())
2944 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2945 }
2946
2947 if (Decl->getSpecializationKind() == TSK_Undeclared) {
2948 MultiLevelTemplateArgumentList TemplateArgLists;
2949 TemplateArgLists.addOuterTemplateArguments(Converted);
2950 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
2951 Decl);
2952 }
2953
2954 // Diagnose uses of this specialization.
2955 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2956
2957 CanonType = Context.getTypeDeclType(Decl);
2958 assert(isa<RecordType>(CanonType) &&((isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2959, __PRETTY_FUNCTION__))
2959 "type of non-dependent specialization is not a RecordType")((isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2959, __PRETTY_FUNCTION__))
;
2960 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2961 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2962 TemplateArgs);
2963 }
2964
2965 // Build the fully-sugared type for this class template
2966 // specialization, which refers back to the class template
2967 // specialization we created or found.
2968 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2969}
2970
2971TypeResult
2972Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2973 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2974 SourceLocation TemplateIILoc,
2975 SourceLocation LAngleLoc,
2976 ASTTemplateArgsPtr TemplateArgsIn,
2977 SourceLocation RAngleLoc,
2978 bool IsCtorOrDtorName, bool IsClassName) {
2979 if (SS.isInvalid())
2980 return true;
2981
2982 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2983 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2984
2985 // C++ [temp.res]p3:
2986 // A qualified-id that refers to a type and in which the
2987 // nested-name-specifier depends on a template-parameter (14.6.2)
2988 // shall be prefixed by the keyword typename to indicate that the
2989 // qualified-id denotes a type, forming an
2990 // elaborated-type-specifier (7.1.5.3).
2991 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
2992 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
2993 << SS.getScopeRep() << TemplateII->getName();
2994 // Recover as if 'typename' were specified.
2995 // FIXME: This is not quite correct recovery as we don't transform SS
2996 // into the corresponding dependent form (and we don't diagnose missing
2997 // 'template' keywords within SS as a result).
2998 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2999 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3000 TemplateArgsIn, RAngleLoc);
3001 }
3002
3003 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3004 // it's not actually allowed to be used as a type in most cases. Because
3005 // we annotate it before we know whether it's valid, we have to check for
3006 // this case here.
3007 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3008 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3009 Diag(TemplateIILoc,
3010 TemplateKWLoc.isInvalid()
3011 ? diag::err_out_of_line_qualified_id_type_names_constructor
3012 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3013 << TemplateII << 0 /*injected-class-name used as template name*/
3014 << 1 /*if any keyword was present, it was 'template'*/;
3015 }
3016 }
3017
3018 TemplateName Template = TemplateD.get();
3019
3020 // Translate the parser's template argument list in our AST format.
3021 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3022 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3023
3024 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3025 QualType T
3026 = Context.getDependentTemplateSpecializationType(ETK_None,
3027 DTN->getQualifier(),
3028 DTN->getIdentifier(),
3029 TemplateArgs);
3030 // Build type-source information.
3031 TypeLocBuilder TLB;
3032 DependentTemplateSpecializationTypeLoc SpecTL
3033 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3034 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3035 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3036 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3037 SpecTL.setTemplateNameLoc(TemplateIILoc);
3038 SpecTL.setLAngleLoc(LAngleLoc);
3039 SpecTL.setRAngleLoc(RAngleLoc);
3040 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3041 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3042 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3043 }
3044
3045 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3046 if (Result.isNull())
3047 return true;
3048
3049 // Build type-source information.
3050 TypeLocBuilder TLB;
3051 TemplateSpecializationTypeLoc SpecTL
3052 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3053 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3054 SpecTL.setTemplateNameLoc(TemplateIILoc);
3055 SpecTL.setLAngleLoc(LAngleLoc);
3056 SpecTL.setRAngleLoc(RAngleLoc);
3057 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3058 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3059
3060 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3061 // constructor or destructor name (in such a case, the scope specifier
3062 // will be attached to the enclosing Decl or Expr node).
3063 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3064 // Create an elaborated-type-specifier containing the nested-name-specifier.
3065 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3066 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3067 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3068 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3069 }
3070
3071 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3072}
3073
3074TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3075 TypeSpecifierType TagSpec,
3076 SourceLocation TagLoc,
3077 CXXScopeSpec &SS,
3078 SourceLocation TemplateKWLoc,
3079 TemplateTy TemplateD,
3080 SourceLocation TemplateLoc,
3081 SourceLocation LAngleLoc,
3082 ASTTemplateArgsPtr TemplateArgsIn,
3083 SourceLocation RAngleLoc) {
3084 TemplateName Template = TemplateD.get();
3085
3086 // Translate the parser's template argument list in our AST format.
3087 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3088 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3089
3090 // Determine the tag kind
3091 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3092 ElaboratedTypeKeyword Keyword
3093 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3094
3095 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3096 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3097 DTN->getQualifier(),
3098 DTN->getIdentifier(),
3099 TemplateArgs);
3100
3101 // Build type-source information.
3102 TypeLocBuilder TLB;
3103 DependentTemplateSpecializationTypeLoc SpecTL
3104 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3105 SpecTL.setElaboratedKeywordLoc(TagLoc);
3106 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3107 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3108 SpecTL.setTemplateNameLoc(TemplateLoc);
3109 SpecTL.setLAngleLoc(LAngleLoc);
3110 SpecTL.setRAngleLoc(RAngleLoc);
3111 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3112 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3113 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3114 }
3115
3116 if (TypeAliasTemplateDecl *TAT =
3117 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3118 // C++0x [dcl.type.elab]p2:
3119 // If the identifier resolves to a typedef-name or the simple-template-id
3120 // resolves to an alias template specialization, the
3121 // elaborated-type-specifier is ill-formed.
3122 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3123 << TAT << NTK_TypeAliasTemplate << TagKind;
3124 Diag(TAT->getLocation(), diag::note_declared_at);
3125 }
3126
3127 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3128 if (Result.isNull())
3129 return TypeResult(true);
3130
3131 // Check the tag kind
3132 if (const RecordType *RT = Result->getAs<RecordType>()) {
3133 RecordDecl *D = RT->getDecl();
3134
3135 IdentifierInfo *Id = D->getIdentifier();
3136 assert(Id && "templated class must have an identifier")((Id && "templated class must have an identifier") ? static_cast
<void> (0) : __assert_fail ("Id && \"templated class must have an identifier\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3136, __PRETTY_FUNCTION__))
;
3137
3138 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3139 TagLoc, Id)) {
3140 Diag(TagLoc, diag::err_use_with_wrong_tag)
3141 << Result
3142 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3143 Diag(D->getLocation(), diag::note_previous_use);
3144 }
3145 }
3146
3147 // Provide source-location information for the template specialization.
3148 TypeLocBuilder TLB;
3149 TemplateSpecializationTypeLoc SpecTL
3150 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3151 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3152 SpecTL.setTemplateNameLoc(TemplateLoc);
3153 SpecTL.setLAngleLoc(LAngleLoc);
3154 SpecTL.setRAngleLoc(RAngleLoc);
3155 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3156 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3157
3158 // Construct an elaborated type containing the nested-name-specifier (if any)
3159 // and tag keyword.
3160 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3161 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3162 ElabTL.setElaboratedKeywordLoc(TagLoc);
3163 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3164 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3165}
3166
3167static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3168 NamedDecl *PrevDecl,
3169 SourceLocation Loc,
3170 bool IsPartialSpecialization);
3171
3172static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3173
3174static bool isTemplateArgumentTemplateParameter(
3175 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3176 switch (Arg.getKind()) {
3177 case TemplateArgument::Null:
3178 case TemplateArgument::NullPtr:
3179 case TemplateArgument::Integral:
3180 case TemplateArgument::Declaration:
3181 case TemplateArgument::Pack:
3182 case TemplateArgument::TemplateExpansion:
3183 return false;
3184
3185 case TemplateArgument::Type: {
3186 QualType Type = Arg.getAsType();
3187 const TemplateTypeParmType *TPT =
3188 Arg.getAsType()->getAs<TemplateTypeParmType>();
3189 return TPT && !Type.hasQualifiers() &&
3190 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3191 }
3192
3193 case TemplateArgument::Expression: {
3194 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3195 if (!DRE || !DRE->getDecl())
3196 return false;
3197 const NonTypeTemplateParmDecl *NTTP =
3198 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3199 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3200 }
3201
3202 case TemplateArgument::Template:
3203 const TemplateTemplateParmDecl *TTP =
3204 dyn_cast_or_null<TemplateTemplateParmDecl>(
3205 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3206 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3207 }
3208 llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3208)
;
3209}
3210
3211static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3212 ArrayRef<TemplateArgument> Args) {
3213 if (Params->size() != Args.size())
3214 return false;
3215
3216 unsigned Depth = Params->getDepth();
3217
3218 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3219 TemplateArgument Arg = Args[I];
3220
3221 // If the parameter is a pack expansion, the argument must be a pack
3222 // whose only element is a pack expansion.
3223 if (Params->getParam(I)->isParameterPack()) {
3224 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3225 !Arg.pack_begin()->isPackExpansion())
3226 return false;
3227 Arg = Arg.pack_begin()->getPackExpansionPattern();
3228 }
3229
3230 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3231 return false;
3232 }
3233
3234 return true;
3235}
3236
3237/// Convert the parser's template argument list representation into our form.
3238static TemplateArgumentListInfo
3239makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3240 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3241 TemplateId.RAngleLoc);
3242 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3243 TemplateId.NumArgs);
3244 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3245 return TemplateArgs;
3246}
3247
3248template<typename PartialSpecDecl>
3249static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3250 if (Partial->getDeclContext()->isDependentContext())
3251 return;
3252
3253 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3254 // for non-substitution-failure issues?
3255 TemplateDeductionInfo Info(Partial->getLocation());
3256 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3257 return;
3258
3259 auto *Template = Partial->getSpecializedTemplate();
3260 S.Diag(Partial->getLocation(),
3261 diag::ext_partial_spec_not_more_specialized_than_primary)
3262 << isa<VarTemplateDecl>(Template);
3263
3264 if (Info.hasSFINAEDiagnostic()) {
3265 PartialDiagnosticAt Diag = {SourceLocation(),
3266 PartialDiagnostic::NullDiagnostic()};
3267 Info.takeSFINAEDiagnostic(Diag);
3268 SmallString<128> SFINAEArgString;
3269 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3270 S.Diag(Diag.first,
3271 diag::note_partial_spec_not_more_specialized_than_primary)
3272 << SFINAEArgString;
3273 }
3274
3275 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3276}
3277
3278static void
3279noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3280 const llvm::SmallBitVector &DeducibleParams) {
3281 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3282 if (!DeducibleParams[I]) {
3283 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3284 if (Param->getDeclName())
3285 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3286 << Param->getDeclName();
3287 else
3288 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3289 << "(anonymous)";
3290 }
3291 }
3292}
3293
3294
3295template<typename PartialSpecDecl>
3296static void checkTemplatePartialSpecialization(Sema &S,
3297 PartialSpecDecl *Partial) {
3298 // C++1z [temp.class.spec]p8: (DR1495)
3299 // - The specialization shall be more specialized than the primary
3300 // template (14.5.5.2).
3301 checkMoreSpecializedThanPrimary(S, Partial);
3302
3303 // C++ [temp.class.spec]p8: (DR1315)
3304 // - Each template-parameter shall appear at least once in the
3305 // template-id outside a non-deduced context.
3306 // C++1z [temp.class.spec.match]p3 (P0127R2)
3307 // If the template arguments of a partial specialization cannot be
3308 // deduced because of the structure of its template-parameter-list
3309 // and the template-id, the program is ill-formed.
3310 auto *TemplateParams = Partial->getTemplateParameters();
3311 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3312 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3313 TemplateParams->getDepth(), DeducibleParams);
3314
3315 if (!DeducibleParams.all()) {
3316 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3317 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3318 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3319 << (NumNonDeducible > 1)
3320 << SourceRange(Partial->getLocation(),
3321 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3322 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3323 }
3324}
3325
3326void Sema::CheckTemplatePartialSpecialization(
3327 ClassTemplatePartialSpecializationDecl *Partial) {
3328 checkTemplatePartialSpecialization(*this, Partial);
3329}
3330
3331void Sema::CheckTemplatePartialSpecialization(
3332 VarTemplatePartialSpecializationDecl *Partial) {
3333 checkTemplatePartialSpecialization(*this, Partial);
3334}
3335
3336void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3337 // C++1z [temp.param]p11:
3338 // A template parameter of a deduction guide template that does not have a
3339 // default-argument shall be deducible from the parameter-type-list of the
3340 // deduction guide template.
3341 auto *TemplateParams = TD->getTemplateParameters();
3342 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3343 MarkDeducedTemplateParameters(TD, DeducibleParams);
3344 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3345 // A parameter pack is deducible (to an empty pack).
3346 auto *Param = TemplateParams->getParam(I);
3347 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3348 DeducibleParams[I] = true;
3349 }
3350
3351 if (!DeducibleParams.all()) {
3352 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3353 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3354 << (NumNonDeducible > 1);
3355 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3356 }
3357}
3358
3359DeclResult Sema::ActOnVarTemplateSpecialization(
3360 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3361 TemplateParameterList *TemplateParams, StorageClass SC,
3362 bool IsPartialSpecialization) {
3363 // D must be variable template id.
3364 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&((D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
"Variable template specialization is declared with a template it."
) ? static_cast<void> (0) : __assert_fail ("D.getName().getKind() == UnqualifiedId::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3365, __PRETTY_FUNCTION__))
3365 "Variable template specialization is declared with a template it.")((D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
"Variable template specialization is declared with a template it."
) ? static_cast<void> (0) : __assert_fail ("D.getName().getKind() == UnqualifiedId::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3365, __PRETTY_FUNCTION__))
;
3366
3367 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3368 TemplateArgumentListInfo TemplateArgs =
3369 makeTemplateArgumentListInfo(*this, *TemplateId);
3370 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3371 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3372 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3373
3374 TemplateName Name = TemplateId->Template.get();
3375
3376 // The template-id must name a variable template.
3377 VarTemplateDecl *VarTemplate =
3378 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3379 if (!VarTemplate) {
3380 NamedDecl *FnTemplate;
3381 if (auto *OTS = Name.getAsOverloadedTemplate())
3382 FnTemplate = *OTS->begin();
3383 else
3384 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3385 if (FnTemplate)
3386 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3387 << FnTemplate->getDeclName();
3388 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3389 << IsPartialSpecialization;
3390 }
3391
3392 // Check for unexpanded parameter packs in any of the template arguments.
3393 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3394 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3395 UPPC_PartialSpecialization))
3396 return true;
3397
3398 // Check that the template argument list is well-formed for this
3399 // template.
3400 SmallVector<TemplateArgument, 4> Converted;
3401 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3402 false, Converted))
3403 return true;
3404
3405 // Find the variable template (partial) specialization declaration that
3406 // corresponds to these arguments.
3407 if (IsPartialSpecialization) {
3408 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3409 TemplateArgs.size(), Converted))
3410 return true;
3411
3412 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3413 // also do them during instantiation.
3414 bool InstantiationDependent;
3415 if (!Name.isDependent() &&
3416 !TemplateSpecializationType::anyDependentTemplateArguments(
3417 TemplateArgs.arguments(),
3418 InstantiationDependent)) {
3419 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3420 << VarTemplate->getDeclName();
3421 IsPartialSpecialization = false;
3422 }
3423
3424 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3425 Converted)) {
3426 // C++ [temp.class.spec]p9b3:
3427 //
3428 // -- The argument list of the specialization shall not be identical
3429 // to the implicit argument list of the primary template.
3430 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3431 << /*variable template*/ 1
3432 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3433 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3434 // FIXME: Recover from this by treating the declaration as a redeclaration
3435 // of the primary template.
3436 return true;
3437 }
3438 }
3439
3440 void *InsertPos = nullptr;
3441 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3442
3443 if (IsPartialSpecialization)
3444 // FIXME: Template parameter list matters too
3445 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3446 else
3447 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3448
3449 VarTemplateSpecializationDecl *Specialization = nullptr;
3450
3451 // Check whether we can declare a variable template specialization in
3452 // the current scope.
3453 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3454 TemplateNameLoc,
3455 IsPartialSpecialization))
3456 return true;
3457
3458 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3459 // Since the only prior variable template specialization with these
3460 // arguments was referenced but not declared, reuse that
3461 // declaration node as our own, updating its source location and
3462 // the list of outer template parameters to reflect our new declaration.
3463 Specialization = PrevDecl;
3464 Specialization->setLocation(TemplateNameLoc);
3465 PrevDecl = nullptr;
3466 } else if (IsPartialSpecialization) {
3467 // Create a new class template partial specialization declaration node.
3468 VarTemplatePartialSpecializationDecl *PrevPartial =
3469 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3470 VarTemplatePartialSpecializationDecl *Partial =
3471 VarTemplatePartialSpecializationDecl::Create(
3472 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3473 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3474 Converted, TemplateArgs);
3475
3476 if (!PrevPartial)
3477 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3478 Specialization = Partial;
3479
3480 // If we are providing an explicit specialization of a member variable
3481 // template specialization, make a note of that.
3482 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3483 PrevPartial->setMemberSpecialization();
3484
3485 CheckTemplatePartialSpecialization(Partial);
3486 } else {
3487 // Create a new class template specialization declaration node for
3488 // this explicit specialization or friend declaration.
3489 Specialization = VarTemplateSpecializationDecl::Create(
3490 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3491 VarTemplate, DI->getType(), DI, SC, Converted);
3492 Specialization->setTemplateArgsInfo(TemplateArgs);
3493
3494 if (!PrevDecl)
3495 VarTemplate->AddSpecialization(Specialization, InsertPos);
3496 }
3497
3498 // C++ [temp.expl.spec]p6:
3499 // If a template, a member template or the member of a class template is
3500 // explicitly specialized then that specialization shall be declared
3501 // before the first use of that specialization that would cause an implicit
3502 // instantiation to take place, in every translation unit in which such a
3503 // use occurs; no diagnostic is required.
3504 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3505 bool Okay = false;
3506 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3507 // Is there any previous explicit specialization declaration?
3508 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3509 Okay = true;
3510 break;
3511 }
3512 }
3513
3514 if (!Okay) {
3515 SourceRange Range(TemplateNameLoc, RAngleLoc);
3516 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3517 << Name << Range;
3518
3519 Diag(PrevDecl->getPointOfInstantiation(),
3520 diag::note_instantiation_required_here)
3521 << (PrevDecl->getTemplateSpecializationKind() !=
3522 TSK_ImplicitInstantiation);
3523 return true;
3524 }
3525 }
3526
3527 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3528 Specialization->setLexicalDeclContext(CurContext);
3529
3530 // Add the specialization into its lexical context, so that it can
3531 // be seen when iterating through the list of declarations in that
3532 // context. However, specializations are not found by name lookup.
3533 CurContext->addDecl(Specialization);
3534
3535 // Note that this is an explicit specialization.
3536 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3537
3538 if (PrevDecl) {
3539 // Check that this isn't a redefinition of this specialization,
3540 // merging with previous declarations.
3541 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3542 ForRedeclaration);
3543 PrevSpec.addDecl(PrevDecl);
3544 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3545 } else if (Specialization->isStaticDataMember() &&
3546 Specialization->isOutOfLine()) {
3547 Specialization->setAccess(VarTemplate->getAccess());
3548 }
3549
3550 // Link instantiations of static data members back to the template from
3551 // which they were instantiated.
3552 if (Specialization->isStaticDataMember())
3553 Specialization->setInstantiationOfStaticDataMember(
3554 VarTemplate->getTemplatedDecl(),
3555 Specialization->getSpecializationKind());
3556
3557 return Specialization;
3558}
3559
3560namespace {
3561/// \brief A partial specialization whose template arguments have matched
3562/// a given template-id.
3563struct PartialSpecMatchResult {
3564 VarTemplatePartialSpecializationDecl *Partial;
3565 TemplateArgumentList *Args;
3566};
3567} // end anonymous namespace
3568
3569DeclResult
3570Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3571 SourceLocation TemplateNameLoc,
3572 const TemplateArgumentListInfo &TemplateArgs) {
3573 assert(Template && "A variable template id without template?")((Template && "A variable template id without template?"
) ? static_cast<void> (0) : __assert_fail ("Template && \"A variable template id without template?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3573, __PRETTY_FUNCTION__))
;
3574
3575 // Check that the template argument list is well-formed for this template.
3576 SmallVector<TemplateArgument, 4> Converted;
3577 if (CheckTemplateArgumentList(
3578 Template, TemplateNameLoc,
3579 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3580 Converted))
3581 return true;
3582
3583 // Find the variable template specialization declaration that
3584 // corresponds to these arguments.
3585 void *InsertPos = nullptr;
3586 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3587 Converted, InsertPos)) {
3588 checkSpecializationVisibility(TemplateNameLoc, Spec);
3589 // If we already have a variable template specialization, return it.
3590 return Spec;
3591 }
3592
3593 // This is the first time we have referenced this variable template
3594 // specialization. Create the canonical declaration and add it to
3595 // the set of specializations, based on the closest partial specialization
3596 // that it represents. That is,
3597 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3598 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3599 Converted);
3600 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3601 bool AmbiguousPartialSpec = false;
3602 typedef PartialSpecMatchResult MatchResult;
3603 SmallVector<MatchResult, 4> Matched;
3604 SourceLocation PointOfInstantiation = TemplateNameLoc;
3605 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3606 /*ForTakingAddress=*/false);
3607
3608 // 1. Attempt to find the closest partial specialization that this
3609 // specializes, if any.
3610 // If any of the template arguments is dependent, then this is probably
3611 // a placeholder for an incomplete declarative context; which must be
3612 // complete by instantiation time. Thus, do not search through the partial
3613 // specializations yet.
3614 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3615 // Perhaps better after unification of DeduceTemplateArguments() and
3616 // getMoreSpecializedPartialSpecialization().
3617 bool InstantiationDependent = false;
3618 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3619 TemplateArgs, InstantiationDependent)) {
3620
3621 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3622 Template->getPartialSpecializations(PartialSpecs);
3623
3624 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3625 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3626 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3627
3628 if (TemplateDeductionResult Result =
3629 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3630 // Store the failed-deduction information for use in diagnostics, later.
3631 // TODO: Actually use the failed-deduction info?
3632 FailedCandidates.addCandidate().set(
3633 DeclAccessPair::make(Template, AS_public), Partial,
3634 MakeDeductionFailureInfo(Context, Result, Info));
3635 (void)Result;
3636 } else {
3637 Matched.push_back(PartialSpecMatchResult());
3638 Matched.back().Partial = Partial;
3639 Matched.back().Args = Info.take();
3640 }
3641 }
3642
3643 if (Matched.size() >= 1) {
3644 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3645 if (Matched.size() == 1) {
3646 // -- If exactly one matching specialization is found, the
3647 // instantiation is generated from that specialization.
3648 // We don't need to do anything for this.
3649 } else {
3650 // -- If more than one matching specialization is found, the
3651 // partial order rules (14.5.4.2) are used to determine
3652 // whether one of the specializations is more specialized
3653 // than the others. If none of the specializations is more
3654 // specialized than all of the other matching
3655 // specializations, then the use of the variable template is
3656 // ambiguous and the program is ill-formed.
3657 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3658 PEnd = Matched.end();
3659 P != PEnd; ++P) {
3660 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3661 PointOfInstantiation) ==
3662 P->Partial)
3663 Best = P;
3664 }
3665
3666 // Determine if the best partial specialization is more specialized than
3667 // the others.
3668 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3669 PEnd = Matched.end();
3670 P != PEnd; ++P) {
3671 if (P != Best && getMoreSpecializedPartialSpecialization(
3672 P->Partial, Best->Partial,
3673 PointOfInstantiation) != Best->Partial) {
3674 AmbiguousPartialSpec = true;
3675 break;
3676 }
3677 }
3678 }
3679
3680 // Instantiate using the best variable template partial specialization.
3681 InstantiationPattern = Best->Partial;
3682 InstantiationArgs = Best->Args;
3683 } else {
3684 // -- If no match is found, the instantiation is generated
3685 // from the primary template.
3686 // InstantiationPattern = Template->getTemplatedDecl();
3687 }
3688 }
3689
3690 // 2. Create the canonical declaration.
3691 // Note that we do not instantiate a definition until we see an odr-use
3692 // in DoMarkVarDeclReferenced().
3693 // FIXME: LateAttrs et al.?
3694 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3695 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3696 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3697 if (!Decl)
3698 return true;
3699
3700 if (AmbiguousPartialSpec) {
3701 // Partial ordering did not produce a clear winner. Complain.
3702 Decl->setInvalidDecl();
3703 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3704 << Decl;
3705
3706 // Print the matching partial specializations.
3707 for (MatchResult P : Matched)
3708 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3709 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3710 *P.Args);
3711 return true;
3712 }
3713
3714 if (VarTemplatePartialSpecializationDecl *D =
3715 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3716 Decl->setInstantiationOf(D, InstantiationArgs);
3717
3718 checkSpecializationVisibility(TemplateNameLoc, Decl);
3719
3720 assert(Decl && "No variable template specialization?")((Decl && "No variable template specialization?") ? static_cast
<void> (0) : __assert_fail ("Decl && \"No variable template specialization?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3720, __PRETTY_FUNCTION__))
;
3721 return Decl;
3722}
3723
3724ExprResult
3725Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3726 const DeclarationNameInfo &NameInfo,
3727 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3728 const TemplateArgumentListInfo *TemplateArgs) {
3729
3730 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3731 *TemplateArgs);
3732 if (Decl.isInvalid())
3733 return ExprError();
3734
3735 VarDecl *Var = cast<VarDecl>(Decl.get());
3736 if (!Var->getTemplateSpecializationKind())
3737 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3738 NameInfo.getLoc());
3739
3740 // Build an ordinary singleton decl ref.
3741 return BuildDeclarationNameExpr(SS, NameInfo, Var,
3742 /*FoundD=*/nullptr, TemplateArgs);
3743}
3744
3745ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
3746 SourceLocation TemplateKWLoc,
3747 LookupResult &R,
3748 bool RequiresADL,
3749 const TemplateArgumentListInfo *TemplateArgs) {
3750 // FIXME: Can we do any checking at this point? I guess we could check the
3751 // template arguments that we have against the template name, if the template
3752 // name refers to a single template. That's not a terribly common case,
3753 // though.
3754 // foo<int> could identify a single function unambiguously
3755 // This approach does NOT work, since f<int>(1);
3756 // gets resolved prior to resorting to overload resolution
3757 // i.e., template<class T> void f(double);
3758 // vs template<class T, class U> void f(U);
3759
3760 // These should be filtered out by our callers.
3761 assert(!R.empty() && "empty lookup results when building templateid")((!R.empty() && "empty lookup results when building templateid"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"empty lookup results when building templateid\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3761, __PRETTY_FUNCTION__))
;
3762 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")((!R.isAmbiguous() && "ambiguous lookup when building templateid"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3762, __PRETTY_FUNCTION__))
;
3763
3764 // In C++1y, check variable template ids.
3765 bool InstantiationDependent;
3766 if (R.getAsSingle<VarTemplateDecl>() &&
14
Assuming the condition is true
3767 !TemplateSpecializationType::anyDependentTemplateArguments(
15
Forming reference to null pointer
3768 *TemplateArgs, InstantiationDependent)) {
3769 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3770 R.getAsSingle<VarTemplateDecl>(),
3771 TemplateKWLoc, TemplateArgs);
3772 }
3773
3774 // We don't want lookup warnings at this point.
3775 R.suppressDiagnostics();
3776
3777 UnresolvedLookupExpr *ULE
3778 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3779 SS.getWithLocInContext(Context),
3780 TemplateKWLoc,
3781 R.getLookupNameInfo(),
3782 RequiresADL, TemplateArgs,
3783 R.begin(), R.end());
3784
3785 return ULE;
3786}
3787
3788// We actually only call this from template instantiation.
3789ExprResult
3790Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3791 SourceLocation TemplateKWLoc,
3792 const DeclarationNameInfo &NameInfo,
3793 const TemplateArgumentListInfo *TemplateArgs) {
3794
3795 assert(TemplateArgs || TemplateKWLoc.isValid())((TemplateArgs || TemplateKWLoc.isValid()) ? static_cast<void
> (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3795, __PRETTY_FUNCTION__))
;
1
Within the expansion of the macro 'assert':
a
Assuming 'TemplateArgs' is null
3796 DeclContext *DC;
3797 if (!(DC = computeDeclContext(SS, false)) ||
2
Assuming 'DC' is not null
5
Taking false branch
3798 DC->isDependentContext() ||
3
Assuming the condition is false
3799 RequireCompleteDeclContext(SS, DC))
4
Assuming the condition is false
3800 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3801
3802 bool MemberOfUnknownSpecialization;
3803 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3804 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
3805 MemberOfUnknownSpecialization);
3806
3807 if (R.isAmbiguous())
6
Assuming the condition is false
7
Taking false branch
3808 return ExprError();
3809
3810 if (R.empty()) {
8
Assuming the condition is false
9
Taking false branch
3811 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3812 << NameInfo.getName() << SS.getRange();
3813 return ExprError();
3814 }
3815
3816 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
10
Assuming 'Temp' is null
11
Taking false branch
3817 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
3818 << SS.getScopeRep()
3819 << NameInfo.getName().getAsString() << SS.getRange();
3820 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3821 return ExprError();
3822 }
3823
3824 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
12
Passing null pointer value via 5th parameter 'TemplateArgs'
13
Calling 'Sema::BuildTemplateIdExpr'
3825}
3826
3827/// \brief Form a dependent template name.
3828///
3829/// This action forms a dependent template name given the template
3830/// name and its (presumably dependent) scope specifier. For
3831/// example, given "MetaFun::template apply", the scope specifier \p
3832/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3833/// of the "template" keyword, and "apply" is the \p Name.
3834TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
3835 CXXScopeSpec &SS,
3836 SourceLocation TemplateKWLoc,
3837 UnqualifiedId &Name,
3838 ParsedType ObjectType,
3839 bool EnteringContext,
3840 TemplateTy &Result,
3841 bool AllowInjectedClassName) {
3842 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3843 Diag(TemplateKWLoc,
3844 getLangOpts().CPlusPlus11 ?
3845 diag::warn_cxx98_compat_template_outside_of_template :
3846 diag::ext_template_outside_of_template)
3847 << FixItHint::CreateRemoval(TemplateKWLoc);
3848
3849 DeclContext *LookupCtx = nullptr;
3850 if (SS.isSet())
3851 LookupCtx = computeDeclContext(SS, EnteringContext);
3852 if (!LookupCtx && ObjectType)
3853 LookupCtx = computeDeclContext(ObjectType.get());
3854 if (LookupCtx) {
3855 // C++0x [temp.names]p5:
3856 // If a name prefixed by the keyword template is not the name of
3857 // a template, the program is ill-formed. [Note: the keyword
3858 // template may not be applied to non-template members of class
3859 // templates. -end note ] [ Note: as is the case with the
3860 // typename prefix, the template prefix is allowed in cases
3861 // where it is not strictly necessary; i.e., when the
3862 // nested-name-specifier or the expression on the left of the ->
3863 // or . is not dependent on a template-parameter, or the use
3864 // does not appear in the scope of a template. -end note]
3865 //
3866 // Note: C++03 was more strict here, because it banned the use of
3867 // the "template" keyword prior to a template-name that was not a
3868 // dependent name. C++ DR468 relaxed this requirement (the
3869 // "template" keyword is now permitted). We follow the C++0x
3870 // rules, even in C++03 mode with a warning, retroactively applying the DR.
3871 bool MemberOfUnknownSpecialization;
3872 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
3873 ObjectType, EnteringContext, Result,
3874 MemberOfUnknownSpecialization);
3875 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3876 isa<CXXRecordDecl>(LookupCtx) &&
3877 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3878 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
3879 // This is a dependent template. Handle it below.
3880 } else if (TNK == TNK_Non_template) {
3881 Diag(Name.getLocStart(),
3882 diag::err_template_kw_refers_to_non_template)
3883 << GetNameFromUnqualifiedId(Name).getName()
3884 << Name.getSourceRange()
3885 << TemplateKWLoc;
3886 return TNK_Non_template;
3887 } else {
3888 // We found something; return it.
3889 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3890 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3891 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3892 LookupRD->getIdentifier() == Name.Identifier) {
3893 // C++14 [class.qual]p2:
3894 // In a lookup in which function names are not ignored and the
3895 // nested-name-specifier nominates a class C, if the name specified
3896 // [...] is the injected-class-name of C, [...] the name is instead
3897 // considered to name the constructor
3898 //
3899 // We don't get here if naming the constructor would be valid, so we
3900 // just reject immediately and recover by treating the
3901 // injected-class-name as naming the template.
3902 Diag(Name.getLocStart(),
3903 diag::ext_out_of_line_qualified_id_type_names_constructor)
3904 << Name.Identifier << 0 /*injected-class-name used as template name*/
3905 << 1 /*'template' keyword was used*/;
3906 }
3907 return TNK;
3908 }
3909 }
3910
3911 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3912
3913 switch (Name.getKind()) {
3914 case UnqualifiedId::IK_Identifier:
3915 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3916 Name.Identifier));
3917 return TNK_Dependent_template_name;
3918
3919 case UnqualifiedId::IK_OperatorFunctionId:
3920 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3921 Name.OperatorFunctionId.Operator));
3922 return TNK_Function_template;
3923
3924 case UnqualifiedId::IK_LiteralOperatorId:
3925 llvm_unreachable("literal operator id cannot have a dependent scope")::llvm::llvm_unreachable_internal("literal operator id cannot have a dependent scope"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3925)
;
3926
3927 default:
3928 break;
3929 }
3930
3931 Diag(Name.getLocStart(),
3932 diag::err_template_kw_refers_to_non_template)
3933 << GetNameFromUnqualifiedId(Name).getName()
3934 << Name.getSourceRange()
3935 << TemplateKWLoc;
3936 return TNK_Non_template;
3937}
3938
3939bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3940 TemplateArgumentLoc &AL,
3941 SmallVectorImpl<TemplateArgument> &Converted) {
3942 const TemplateArgument &Arg = AL.getArgument();
3943 QualType ArgType;
3944 TypeSourceInfo *TSI = nullptr;
3945
3946 // Check template type parameter.
3947 switch(Arg.getKind()) {
3948 case TemplateArgument::Type:
3949 // C++ [temp.arg.type]p1:
3950 // A template-argument for a template-parameter which is a
3951 // type shall be a type-id.
3952 ArgType = Arg.getAsType();
3953 TSI = AL.getTypeSourceInfo();
3954 break;
3955 case TemplateArgument::Template: {
3956 // We have a template type parameter but the template argument
3957 // is a template without any arguments.
3958 SourceRange SR = AL.getSourceRange();
3959 TemplateName Name = Arg.getAsTemplate();
3960 Diag(SR.getBegin(), diag::err_template_missing_args)
3961 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
3962 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3963 Diag(Decl->getLocation(), diag::note_template_decl_here);
3964
3965 return true;
3966 }
3967 case TemplateArgument::Expression: {
3968 // We have a template type parameter but the template argument is an
3969 // expression; see if maybe it is missing the "typename" keyword.
3970 CXXScopeSpec SS;
3971 DeclarationNameInfo NameInfo;
3972
3973 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3974 SS.Adopt(ArgExpr->getQualifierLoc());
3975 NameInfo = ArgExpr->getNameInfo();
3976 } else if (DependentScopeDeclRefExpr *ArgExpr =
3977 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3978 SS.Adopt(ArgExpr->getQualifierLoc());
3979 NameInfo = ArgExpr->getNameInfo();
3980 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3981 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3982 if (ArgExpr->isImplicitAccess()) {
3983 SS.Adopt(ArgExpr->getQualifierLoc());
3984 NameInfo = ArgExpr->getMemberNameInfo();
3985 }
3986 }
3987
3988 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3989 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3990 LookupParsedName(Result, CurScope, &SS);
3991
3992 if (Result.getAsSingle<TypeDecl>() ||
3993 Result.getResultKind() ==
3994 LookupResult::NotFoundInCurrentInstantiation) {
3995 // Suggest that the user add 'typename' before the NNS.
3996 SourceLocation Loc = AL.getSourceRange().getBegin();
3997 Diag(Loc, getLangOpts().MSVCCompat
3998 ? diag::ext_ms_template_type_arg_missing_typename
3999 : diag::err_template_arg_must_be_type_suggest)
4000 << FixItHint::CreateInsertion(Loc, "typename ");
4001 Diag(Param->getLocation(), diag::note_template_param_here);
4002
4003 // Recover by synthesizing a type using the location information that we
4004 // already have.
4005 ArgType =
4006 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4007 TypeLocBuilder TLB;
4008 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4009 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4010 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4011 TL.setNameLoc(NameInfo.getLoc());
4012 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4013
4014 // Overwrite our input TemplateArgumentLoc so that we can recover
4015 // properly.
4016 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4017 TemplateArgumentLocInfo(TSI));
4018
4019 break;
4020 }
4021 }
4022 // fallthrough
4023 }
4024 default: {
4025 // We have a template type parameter but the template argument
4026 // is not a type.
4027 SourceRange SR = AL.getSourceRange();
4028 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4029 Diag(Param->getLocation(), diag::note_template_param_here);
4030
4031 return true;
4032 }
4033 }
4034
4035 if (CheckTemplateArgument(Param, TSI))
4036 return true;
4037
4038 // Add the converted template type argument.
4039 ArgType = Context.getCanonicalType(ArgType);
4040
4041 // Objective-C ARC:
4042 // If an explicitly-specified template argument type is a lifetime type
4043 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4044 if (getLangOpts().ObjCAutoRefCount &&
4045 ArgType->isObjCLifetimeType() &&
4046 !ArgType.getObjCLifetime()) {
4047 Qualifiers Qs;
4048 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4049 ArgType = Context.getQualifiedType(ArgType, Qs);
4050 }
4051
4052 Converted.push_back(TemplateArgument(ArgType));
4053 return false;
4054}
4055
4056/// \brief Substitute template arguments into the default template argument for
4057/// the given template type parameter.
4058///
4059/// \param SemaRef the semantic analysis object for which we are performing
4060/// the substitution.
4061///
4062/// \param Template the template that we are synthesizing template arguments
4063/// for.
4064///
4065/// \param TemplateLoc the location of the template name that started the
4066/// template-id we are checking.
4067///
4068/// \param RAngleLoc the location of the right angle bracket ('>') that
4069/// terminates the template-id.
4070///
4071/// \param Param the template template parameter whose default we are
4072/// substituting into.
4073///
4074/// \param Converted the list of template arguments provided for template
4075/// parameters that precede \p Param in the template parameter list.
4076/// \returns the substituted template argument, or NULL if an error occurred.
4077static TypeSourceInfo *
4078SubstDefaultTemplateArgument(Sema &SemaRef,
4079 TemplateDecl *Template,
4080 SourceLocation TemplateLoc,
4081 SourceLocation RAngleLoc,
4082 TemplateTypeParmDecl *Param,
4083 SmallVectorImpl<TemplateArgument> &Converted) {
4084 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4085
4086 // If the argument type is dependent, instantiate it now based
4087 // on the previously-computed template arguments.
4088 if (ArgType->getType()->isDependentType()) {
4089 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4090 Param, Template, Converted,
4091 SourceRange(TemplateLoc, RAngleLoc));
4092 if (Inst.isInvalid())
4093 return nullptr;
4094
4095 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4096
4097 // Only substitute for the innermost template argument list.
4098 MultiLevelTemplateArgumentList TemplateArgLists;
4099 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4100 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4101 TemplateArgLists.addOuterTemplateArguments(None);
4102
4103 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4104 ArgType =
4105 SemaRef.SubstType(ArgType, TemplateArgLists,
4106 Param->getDefaultArgumentLoc(), Param->getDeclName());
4107 }
4108
4109 return ArgType;
4110}
4111
4112/// \brief Substitute template arguments into the default template argument for
4113/// the given non-type template parameter.
4114///
4115/// \param SemaRef the semantic analysis object for which we are performing
4116/// the substitution.
4117///
4118/// \param Template the template that we are synthesizing template arguments
4119/// for.
4120///
4121/// \param TemplateLoc the location of the template name that started the
4122/// template-id we are checking.
4123///
4124/// \param RAngleLoc the location of the right angle bracket ('>') that
4125/// terminates the template-id.
4126///
4127/// \param Param the non-type template parameter whose default we are
4128/// substituting into.
4129///
4130/// \param Converted the list of template arguments provided for template
4131/// parameters that precede \p Param in the template parameter list.
4132///
4133/// \returns the substituted template argument, or NULL if an error occurred.
4134static ExprResult
4135SubstDefaultTemplateArgument(Sema &SemaRef,
4136 TemplateDecl *Template,
4137 SourceLocation TemplateLoc,
4138 SourceLocation RAngleLoc,
4139 NonTypeTemplateParmDecl *Param,
4140 SmallVectorImpl<TemplateArgument> &Converted) {
4141 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4142 Param, Template, Converted,
4143 SourceRange(TemplateLoc, RAngleLoc));
4144 if (Inst.isInvalid())
4145 return ExprError();
4146
4147 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4148
4149 // Only substitute for the innermost template argument list.
4150 MultiLevelTemplateArgumentList TemplateArgLists;
4151 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4152 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4153 TemplateArgLists.addOuterTemplateArguments(None);
4154
4155 EnterExpressionEvaluationContext ConstantEvaluated(
4156 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4157 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4158}
4159
4160/// \brief Substitute template arguments into the default template argument for
4161/// the given template template parameter.
4162///
4163/// \param SemaRef the semantic analysis object for which we are performing
4164/// the substitution.
4165///
4166/// \param Template the template that we are synthesizing template arguments
4167/// for.
4168///
4169/// \param TemplateLoc the location of the template name that started the
4170/// template-id we are checking.
4171///
4172/// \param RAngleLoc the location of the right angle bracket ('>') that
4173/// terminates the template-id.
4174///
4175/// \param Param the template template parameter whose default we are
4176/// substituting into.
4177///
4178/// \param Converted the list of template arguments provided for template
4179/// parameters that precede \p Param in the template parameter list.
4180///
4181/// \param QualifierLoc Will be set to the nested-name-specifier (with
4182/// source-location information) that precedes the template name.
4183///
4184/// \returns the substituted template argument, or NULL if an error occurred.
4185static TemplateName
4186SubstDefaultTemplateArgument(Sema &SemaRef,
4187 TemplateDecl *Template,
4188 SourceLocation TemplateLoc,
4189 SourceLocation RAngleLoc,
4190 TemplateTemplateParmDecl *Param,
4191 SmallVectorImpl<TemplateArgument> &Converted,
4192 NestedNameSpecifierLoc &QualifierLoc) {
4193 Sema::InstantiatingTemplate Inst(
4194 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4195 SourceRange(TemplateLoc, RAngleLoc));
4196 if (Inst.isInvalid())
4197 return TemplateName();
4198
4199 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4200
4201 // Only substitute for the innermost template argument list.
4202 MultiLevelTemplateArgumentList TemplateArgLists;
4203 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4204 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4205 TemplateArgLists.addOuterTemplateArguments(None);
4206
4207 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4208 // Substitute into the nested-name-specifier first,
4209 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4210 if (QualifierLoc) {
4211 QualifierLoc =
4212 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4213 if (!QualifierLoc)
4214 return TemplateName();
4215 }
4216
4217 return SemaRef.SubstTemplateName(
4218 QualifierLoc,
4219 Param->getDefaultArgument().getArgument().getAsTemplate(),
4220 Param->getDefaultArgument().getTemplateNameLoc(),
4221 TemplateArgLists);
4222}
4223
4224/// \brief If the given template parameter has a default template
4225/// argument, substitute into that default template argument and
4226/// return the corresponding template argument.
4227TemplateArgumentLoc
4228Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4229 SourceLocation TemplateLoc,
4230 SourceLocation RAngleLoc,
4231 Decl *Param,
4232 SmallVectorImpl<TemplateArgument>
4233 &Converted,
4234 bool &HasDefaultArg) {
4235 HasDefaultArg = false;
4236
4237 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4238 if (!hasVisibleDefaultArgument(TypeParm))
4239 return TemplateArgumentLoc();
4240
4241 HasDefaultArg = true;
4242 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4243 TemplateLoc,
4244 RAngleLoc,
4245 TypeParm,
4246 Converted);
4247 if (DI)
4248 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4249
4250 return TemplateArgumentLoc();
4251 }
4252
4253 if (NonTypeTemplateParmDecl *NonTypeParm
4254 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4255 if (!hasVisibleDefaultArgument(NonTypeParm))
4256 return TemplateArgumentLoc();
4257
4258 HasDefaultArg = true;
4259 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4260 TemplateLoc,
4261 RAngleLoc,
4262 NonTypeParm,
4263 Converted);
4264 if (Arg.isInvalid())
4265 return TemplateArgumentLoc();
4266
4267 Expr *ArgE = Arg.getAs<Expr>();
4268 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4269 }
4270
4271 TemplateTemplateParmDecl *TempTempParm
4272 = cast<TemplateTemplateParmDecl>(Param);
4273 if (!hasVisibleDefaultArgument(TempTempParm))
4274 return TemplateArgumentLoc();
4275
4276 HasDefaultArg = true;
4277 NestedNameSpecifierLoc QualifierLoc;
4278 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4279 TemplateLoc,
4280 RAngleLoc,
4281 TempTempParm,
4282 Converted,
4283 QualifierLoc);
4284 if (TName.isNull())
4285 return TemplateArgumentLoc();
4286
4287 return TemplateArgumentLoc(TemplateArgument(TName),
4288 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4289 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4290}
4291
4292/// Convert a template-argument that we parsed as a type into a template, if
4293/// possible. C++ permits injected-class-names to perform dual service as
4294/// template template arguments and as template type arguments.
4295static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4296 // Extract and step over any surrounding nested-name-specifier.
4297 NestedNameSpecifierLoc QualLoc;
4298 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4299 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4300 return TemplateArgumentLoc();
4301
4302 QualLoc = ETLoc.getQualifierLoc();
4303 TLoc = ETLoc.getNamedTypeLoc();
4304 }
4305
4306 // If this type was written as an injected-class-name, it can be used as a
4307 // template template argument.
4308 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4309 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4310 QualLoc, InjLoc.getNameLoc());
4311
4312 // If this type was written as an injected-class-name, it may have been
4313 // converted to a RecordType during instantiation. If the RecordType is
4314 // *not* wrapped in a TemplateSpecializationType and denotes a class
4315 // template specialization, it must have come from an injected-class-name.
4316 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4317 if (auto *CTSD =
4318 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4319 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4320 QualLoc, RecLoc.getNameLoc());
4321
4322 return TemplateArgumentLoc();
4323}
4324
4325/// \brief Check that the given template argument corresponds to the given
4326/// template parameter.
4327///
4328/// \param Param The template parameter against which the argument will be
4329/// checked.
4330///
4331/// \param Arg The template argument, which may be updated due to conversions.
4332///
4333/// \param Template The template in which the template argument resides.
4334///
4335/// \param TemplateLoc The location of the template name for the template
4336/// whose argument list we're matching.
4337///
4338/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4339/// the template argument list.
4340///
4341/// \param ArgumentPackIndex The index into the argument pack where this
4342/// argument will be placed. Only valid if the parameter is a parameter pack.
4343///
4344/// \param Converted The checked, converted argument will be added to the
4345/// end of this small vector.
4346///
4347/// \param CTAK Describes how we arrived at this particular template argument:
4348/// explicitly written, deduced, etc.
4349///
4350/// \returns true on error, false otherwise.
4351bool Sema::CheckTemplateArgument(NamedDecl *Param,
4352 TemplateArgumentLoc &Arg,
4353 NamedDecl *Template,
4354 SourceLocation TemplateLoc,
4355 SourceLocation RAngleLoc,
4356 unsigned ArgumentPackIndex,
4357 SmallVectorImpl<TemplateArgument> &Converted,
4358 CheckTemplateArgumentKind CTAK) {
4359 // Check template type parameters.
4360 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4361 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4362
4363 // Check non-type template parameters.
4364 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4365 // Do substitution on the type of the non-type template parameter
4366 // with the template arguments we've seen thus far. But if the
4367 // template has a dependent context then we cannot substitute yet.
4368 QualType NTTPType = NTTP->getType();
4369 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4370 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4371
4372 if (NTTPType->isDependentType() &&
4373 !isa<TemplateTemplateParmDecl>(Template) &&
4374 !Template->getDeclContext()->isDependentContext()) {
4375 // Do substitution on the type of the non-type template parameter.
4376 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4377 NTTP, Converted,
4378 SourceRange(TemplateLoc, RAngleLoc));
4379 if (Inst.isInvalid())
4380 return true;
4381
4382 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4383 Converted);
4384 NTTPType = SubstType(NTTPType,
4385 MultiLevelTemplateArgumentList(TemplateArgs),
4386 NTTP->getLocation(),
4387 NTTP->getDeclName());
4388 // If that worked, check the non-type template parameter type
4389 // for validity.
4390 if (!NTTPType.isNull())
4391 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4392 NTTP->getLocation());
4393 if (NTTPType.isNull())
4394 return true;
4395 }
4396
4397 switch (Arg.getArgument().getKind()) {
4398 case TemplateArgument::Null:
4399 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4399)
;
4400
4401 case TemplateArgument::Expression: {
4402 TemplateArgument Result;
4403 ExprResult Res =
4404 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4405 Result, CTAK);
4406 if (Res.isInvalid())
4407 return true;
4408
4409 // If the resulting expression is new, then use it in place of the
4410 // old expression in the template argument.
4411 if (Res.get() != Arg.getArgument().getAsExpr()) {
4412 TemplateArgument TA(Res.get());
4413 Arg = TemplateArgumentLoc(TA, Res.get());
4414 }
4415
4416 Converted.push_back(Result);
4417 break;
4418 }
4419
4420 case TemplateArgument::Declaration:
4421 case TemplateArgument::Integral:
4422 case TemplateArgument::NullPtr:
4423 // We've already checked this template argument, so just copy
4424 // it to the list of converted arguments.
4425 Converted.push_back(Arg.getArgument());
4426 break;
4427
4428 case TemplateArgument::Template:
4429 case TemplateArgument::TemplateExpansion:
4430 // We were given a template template argument. It may not be ill-formed;
4431 // see below.
4432 if (DependentTemplateName *DTN
4433 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4434 .getAsDependentTemplateName()) {
4435 // We have a template argument such as \c T::template X, which we
4436 // parsed as a template template argument. However, since we now
4437 // know that we need a non-type template argument, convert this
4438 // template name into an expression.
4439
4440 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4441 Arg.getTemplateNameLoc());
4442
4443 CXXScopeSpec SS;
4444 SS.Adopt(Arg.getTemplateQualifierLoc());
4445 // FIXME: the template-template arg was a DependentTemplateName,
4446 // so it was provided with a template keyword. However, its source
4447 // location is not stored in the template argument structure.
4448 SourceLocation TemplateKWLoc;
4449 ExprResult E = DependentScopeDeclRefExpr::Create(
4450 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4451 nullptr);
4452
4453 // If we parsed the template argument as a pack expansion, create a
4454 // pack expansion expression.
4455 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4456 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4457 if (E.isInvalid())
4458 return true;
4459 }
4460
4461 TemplateArgument Result;
4462 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4463 if (E.isInvalid())
4464 return true;
4465
4466 Converted.push_back(Result);
4467 break;
4468 }
4469
4470 // We have a template argument that actually does refer to a class
4471 // template, alias template, or template template parameter, and
4472 // therefore cannot be a non-type template argument.
4473 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4474 << Arg.getSourceRange();
4475
4476 Diag(Param->getLocation(), diag::note_template_param_here);
4477 return true;
4478
4479 case TemplateArgument::Type: {
4480 // We have a non-type template parameter but the template
4481 // argument is a type.
4482
4483 // C++ [temp.arg]p2:
4484 // In a template-argument, an ambiguity between a type-id and
4485 // an expression is resolved to a type-id, regardless of the
4486 // form of the corresponding template-parameter.
4487 //
4488 // We warn specifically about this case, since it can be rather
4489 // confusing for users.
4490 QualType T = Arg.getArgument().getAsType();
4491 SourceRange SR = Arg.getSourceRange();
4492 if (T->isFunctionType())
4493 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4494 else
4495 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4496 Diag(Param->getLocation(), diag::note_template_param_here);
4497 return true;
4498 }
4499
4500 case TemplateArgument::Pack:
4501 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4501)
;
4502 }
4503
4504 return false;
4505 }
4506
4507
4508 // Check template template parameters.
4509 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4510
4511 // Substitute into the template parameter list of the template
4512 // template parameter, since previously-supplied template arguments
4513 // may appear within the template template parameter.
4514 {
4515 // Set up a template instantiation context.
4516 LocalInstantiationScope Scope(*this);
4517 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4518 TempParm, Converted,
4519 SourceRange(TemplateLoc, RAngleLoc));
4520 if (Inst.isInvalid())
4521 return true;
4522
4523 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4524 TempParm = cast_or_null<TemplateTemplateParmDecl>(
4525 SubstDecl(TempParm, CurContext,
4526 MultiLevelTemplateArgumentList(TemplateArgs)));
4527 if (!TempParm)
4528 return true;
4529 }
4530
4531 // C++1z [temp.local]p1: (DR1004)
4532 // When [the injected-class-name] is used [...] as a template-argument for
4533 // a template template-parameter [...] it refers to the class template
4534 // itself.
4535 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4536 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4537 Arg.getTypeSourceInfo()->getTypeLoc());
4538 if (!ConvertedArg.getArgument().isNull())
4539 Arg = ConvertedArg;
4540 }
4541
4542 switch (Arg.getArgument().getKind()) {
4543 case TemplateArgument::Null:
4544 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4544)
;
4545
4546 case TemplateArgument::Template:
4547 case TemplateArgument::TemplateExpansion:
4548 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4549 return true;
4550
4551 Converted.push_back(Arg.getArgument());
4552 break;
4553
4554 case TemplateArgument::Expression:
4555 case TemplateArgument::Type:
4556 // We have a template template parameter but the template
4557 // argument does not refer to a template.
4558 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4559 << getLangOpts().CPlusPlus11;
4560 return true;
4561
4562 case TemplateArgument::Declaration:
4563 llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4563)
;
4564 case TemplateArgument::Integral:
4565 llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4565)
;
4566 case TemplateArgument::NullPtr:
4567 llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4567)
;
4568
4569 case TemplateArgument::Pack:
4570 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4570)
;
4571 }
4572
4573 return false;
4574}
4575
4576/// \brief Diagnose an arity mismatch in the
4577static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4578 SourceLocation TemplateLoc,
4579 TemplateArgumentListInfo &TemplateArgs) {
4580 TemplateParameterList *Params = Template->getTemplateParameters();
4581 unsigned NumParams = Params->size();
4582 unsigned NumArgs = TemplateArgs.size();
4583
4584 SourceRange Range;
4585 if (NumArgs > NumParams)
4586 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4587 TemplateArgs.getRAngleLoc());
4588 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4589 << (NumArgs > NumParams)
4590 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4591 << Template << Range;
4592 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4593 << Params->getSourceRange();
4594 return true;
4595}
4596
4597/// \brief Check whether the template parameter is a pack expansion, and if so,
4598/// determine the number of parameters produced by that expansion. For instance:
4599///
4600/// \code
4601/// template<typename ...Ts> struct A {
4602/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4603/// };
4604/// \endcode
4605///
4606/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4607/// is not a pack expansion, so returns an empty Optional.
4608static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4609 if (NonTypeTemplateParmDecl *NTTP
4610 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4611 if (NTTP->isExpandedParameterPack())
4612 return NTTP->getNumExpansionTypes();
4613 }
4614
4615 if (TemplateTemplateParmDecl *TTP
4616 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4617 if (TTP->isExpandedParameterPack())
4618 return TTP->getNumExpansionTemplateParameters();
4619 }
4620
4621 return None;
4622}
4623
4624/// Diagnose a missing template argument.
4625template<typename TemplateParmDecl>
4626static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4627 TemplateDecl *TD,
4628 const TemplateParmDecl *D,
4629 TemplateArgumentListInfo &Args) {
4630 // Dig out the most recent declaration of the template parameter; there may be
4631 // declarations of the template that are more recent than TD.
4632 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4633 ->getTemplateParameters()
4634 ->getParam(D->getIndex()));
4635
4636 // If there's a default argument that's not visible, diagnose that we're
4637 // missing a module import.
4638 llvm::SmallVector<Module*, 8> Modules;
4639 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4640 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4641 D->getDefaultArgumentLoc(), Modules,
4642 Sema::MissingImportKind::DefaultArgument,
4643 /*Recover*/true);
4644 return true;
4645 }
4646
4647 // FIXME: If there's a more recent default argument that *is* visible,
4648 // diagnose that it was declared too late.
4649
4650 return diagnoseArityMismatch(S, TD, Loc, Args);
4651}
4652
4653/// \brief Check that the given template argument list is well-formed
4654/// for specializing the given template.
4655bool Sema::CheckTemplateArgumentList(
4656 TemplateDecl *Template, SourceLocation TemplateLoc,
4657 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4658 SmallVectorImpl<TemplateArgument> &Converted,
4659 bool UpdateArgsWithConversions) {
4660 // Make a copy of the template arguments for processing. Only make the
4661 // changes at the end when successful in matching the arguments to the
4662 // template.
4663 TemplateArgumentListInfo NewArgs = TemplateArgs;
4664
4665 TemplateParameterList *Params = Template->getTemplateParameters();
4666
4667 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4668
4669 // C++ [temp.arg]p1:
4670 // [...] The type and form of each template-argument specified in
4671 // a template-id shall match the type and form specified for the
4672 // corresponding parameter declared by the template in its
4673 // template-parameter-list.
4674 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4675 SmallVector<TemplateArgument, 2> ArgumentPack;
4676 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4677 LocalInstantiationScope InstScope(*this, true);
4678 for (TemplateParameterList::iterator Param = Params->begin(),
4679 ParamEnd = Params->end();
4680 Param != ParamEnd; /* increment in loop */) {
4681 // If we have an expanded parameter pack, make sure we don't have too
4682 // many arguments.
4683 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4684 if (*Expansions == ArgumentPack.size()) {
4685 // We're done with this parameter pack. Pack up its arguments and add
4686 // them to the list.
4687 Converted.push_back(
4688 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4689 ArgumentPack.clear();
4690
4691 // This argument is assigned to the next parameter.
4692 ++Param;
4693 continue;
4694 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4695 // Not enough arguments for this parameter pack.
4696 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4697 << false
4698 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4699 << Template;
4700 Diag(Template->getLocation(), diag::note_template_decl_here)
4701 << Params->getSourceRange();
4702 return true;
4703 }
4704 }
4705
4706 if (ArgIdx < NumArgs) {
4707 // Check the template argument we were given.
4708 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4709 TemplateLoc, RAngleLoc,
4710 ArgumentPack.size(), Converted))
4711 return true;
4712
4713 bool PackExpansionIntoNonPack =
4714 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4715 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4716 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4717 // Core issue 1430: we have a pack expansion as an argument to an
4718 // alias template, and it's not part of a parameter pack. This
4719 // can't be canonicalized, so reject it now.
4720 Diag(NewArgs[ArgIdx].getLocation(),
4721 diag::err_alias_template_expansion_into_fixed_list)
4722 << NewArgs[ArgIdx].getSourceRange();
4723 Diag((*Param)->getLocation(), diag::note_template_param_here);
4724 return true;
4725 }
4726
4727 // We're now done with this argument.
4728 ++ArgIdx;
4729
4730 if ((*Param)->isTemplateParameterPack()) {
4731 // The template parameter was a template parameter pack, so take the
4732 // deduced argument and place it on the argument pack. Note that we
4733 // stay on the same template parameter so that we can deduce more
4734 // arguments.
4735 ArgumentPack.push_back(Converted.pop_back_val());
4736 } else {
4737 // Move to the next template parameter.
4738 ++Param;
4739 }
4740
4741 // If we just saw a pack expansion into a non-pack, then directly convert
4742 // the remaining arguments, because we don't know what parameters they'll
4743 // match up with.
4744 if (PackExpansionIntoNonPack) {
4745 if (!ArgumentPack.empty()) {
4746 // If we were part way through filling in an expanded parameter pack,
4747 // fall back to just producing individual arguments.
4748 Converted.insert(Converted.end(),
4749 ArgumentPack.begin(), ArgumentPack.end());
4750 ArgumentPack.clear();
4751 }
4752
4753 while (ArgIdx < NumArgs) {
4754 Converted.push_back(NewArgs[ArgIdx].getArgument());
4755 ++ArgIdx;
4756 }
4757
4758 return false;
4759 }
4760
4761 continue;
4762 }
4763
4764 // If we're checking a partial template argument list, we're done.
4765 if (PartialTemplateArgs) {
4766 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4767 Converted.push_back(
4768 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4769
4770 return false;
4771 }
4772
4773 // If we have a template parameter pack with no more corresponding
4774 // arguments, just break out now and we'll fill in the argument pack below.
4775 if ((*Param)->isTemplateParameterPack()) {
4776 assert(!getExpandedPackSize(*Param) &&((!getExpandedPackSize(*Param) && "Should have dealt with this already"
) ? static_cast<void> (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4777, __PRETTY_FUNCTION__))
4777 "Should have dealt with this already")((!getExpandedPackSize(*Param) && "Should have dealt with this already"
) ? static_cast<void> (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4777, __PRETTY_FUNCTION__))
;
4778
4779 // A non-expanded parameter pack before the end of the parameter list
4780 // only occurs for an ill-formed template parameter list, unless we've
4781 // got a partial argument list for a function template, so just bail out.
4782 if (Param + 1 != ParamEnd)
4783 return true;
4784
4785 Converted.push_back(
4786 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4787 ArgumentPack.clear();
4788
4789 ++Param;
4790 continue;
4791 }
4792
4793 // Check whether we have a default argument.
4794 TemplateArgumentLoc Arg;
4795
4796 // Retrieve the default template argument from the template
4797 // parameter. For each kind of template parameter, we substitute the
4798 // template arguments provided thus far and any "outer" template arguments
4799 // (when the template parameter was part of a nested template) into
4800 // the default argument.
4801 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
4802 if (!hasVisibleDefaultArgument(TTP))
4803 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4804 NewArgs);
4805
4806 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
4807 Template,
4808 TemplateLoc,
4809 RAngleLoc,
4810 TTP,
4811 Converted);
4812 if (!ArgType)
4813 return true;
4814
4815 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4816 ArgType);
4817 } else if (NonTypeTemplateParmDecl *NTTP
4818 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
4819 if (!hasVisibleDefaultArgument(NTTP))
4820 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4821 NewArgs);
4822
4823 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
4824 TemplateLoc,
4825 RAngleLoc,
4826 NTTP,
4827 Converted);
4828 if (E.isInvalid())
4829 return true;
4830
4831 Expr *Ex = E.getAs<Expr>();
4832 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4833 } else {
4834 TemplateTemplateParmDecl *TempParm
4835 = cast<TemplateTemplateParmDecl>(*Param);
4836
4837 if (!hasVisibleDefaultArgument(TempParm))
4838 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4839 NewArgs);
4840
4841 NestedNameSpecifierLoc QualifierLoc;
4842 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
4843 TemplateLoc,
4844 RAngleLoc,
4845 TempParm,
4846 Converted,
4847 QualifierLoc);
4848 if (Name.isNull())
4849 return true;
4850
4851 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4852 TempParm->getDefaultArgument().getTemplateNameLoc());
4853 }
4854
4855 // Introduce an instantiation record that describes where we are using
4856 // the default template argument. We're not actually instantiating a
4857 // template here, we just create this object to put a note into the
4858 // context stack.
4859 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4860 SourceRange(TemplateLoc, RAngleLoc));
4861 if (Inst.isInvalid())
4862 return true;
4863
4864 // Check the default template argument.
4865 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
4866 RAngleLoc, 0, Converted))
4867 return true;
4868
4869 // Core issue 150 (assumed resolution): if this is a template template
4870 // parameter, keep track of the default template arguments from the
4871 // template definition.
4872 if (isTemplateTemplateParameter)
4873 NewArgs.addArgument(Arg);
4874
4875 // Move to the next template parameter and argument.
4876 ++Param;
4877 ++ArgIdx;
4878 }
4879
4880 // If we're performing a partial argument substitution, allow any trailing
4881 // pack expansions; they might be empty. This can happen even if
4882 // PartialTemplateArgs is false (the list of arguments is complete but
4883 // still dependent).
4884 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4885 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
4886 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4887 Converted.push_back(NewArgs[ArgIdx++].getArgument());
4888 }
4889
4890 // If we have any leftover arguments, then there were too many arguments.
4891 // Complain and fail.
4892 if (ArgIdx < NumArgs)
4893 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4894
4895 // No problems found with the new argument list, propagate changes back
4896 // to caller.
4897 if (UpdateArgsWithConversions)
4898 TemplateArgs = std::move(NewArgs);
4899
4900 return false;
4901}
4902
4903namespace {
4904 class UnnamedLocalNoLinkageFinder
4905 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
4906 {
4907 Sema &S;
4908 SourceRange SR;
4909
4910 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
4911
4912 public:
4913 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4914
4915 bool Visit(QualType T) {
4916 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
4917 }
4918
4919#define TYPE(Class, Parent) \
4920 bool Visit##Class##Type(const Class##Type *);
4921#define ABSTRACT_TYPE(Class, Parent) \
4922 bool Visit##Class##Type(const Class##Type *) { return false; }
4923#define NON_CANONICAL_TYPE(Class, Parent) \
4924 bool Visit##Class##Type(const Class##Type *) { return false; }
4925#include "clang/AST/TypeNodes.def"
4926
4927 bool VisitTagDecl(const TagDecl *Tag);
4928 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4929 };
4930} // end anonymous namespace
4931
4932bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
4933 return false;
4934}
4935
4936bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4937 return Visit(T->getElementType());
4938}
4939
4940bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
4941 return Visit(T->getPointeeType());
4942}
4943
4944bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
4945 const BlockPointerType* T) {
4946 return Visit(T->getPointeeType());
4947}
4948
4949bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
4950 const LValueReferenceType* T) {
4951 return Visit(T->getPointeeType());
4952}
4953
4954bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
4955 const RValueReferenceType* T) {
4956 return Visit(T->getPointeeType());
4957}
4958
4959bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
4960 const MemberPointerType* T) {
4961 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4962}
4963
4964bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
4965 const ConstantArrayType* T) {
4966 return Visit(T->getElementType());
4967}
4968
4969bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
4970 const IncompleteArrayType* T) {
4971 return Visit(T->getElementType());
4972}
4973
4974bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4975 const VariableArrayType* T) {
4976 return Visit(T->getElementType());
4977}
4978
4979bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4980 const DependentSizedArrayType* T) {
4981 return Visit(T->getElementType());
4982}
4983
4984bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4985 const DependentSizedExtVectorType* T) {
4986 return Visit(T->getElementType());
4987}
4988
4989bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4990 return Visit(T->getElementType());
4991}
4992
4993bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4994 return Visit(T->getElementType());
4995}
4996
4997bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4998 const FunctionProtoType* T) {
4999 for (const auto &A : T->param_types()) {
5000 if (Visit(A))
5001 return true;
5002 }
5003
5004 return Visit(T->getReturnType());
5005}
5006
5007bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5008 const FunctionNoProtoType* T) {
5009 return Visit(T->getReturnType());
5010}
5011
5012bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5013 const UnresolvedUsingType*) {
5014 return false;
5015}
5016
5017bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5018 return false;
5019}
5020
5021bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5022 return Visit(T->getUnderlyingType());
5023}
5024
5025bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5026 return false;
5027}
5028
5029bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5030 const UnaryTransformType*) {
5031 return false;
5032}
5033
5034bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5035 return Visit(T->getDeducedType());
5036}
5037
5038bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5039 const DeducedTemplateSpecializationType *T) {
5040 return Visit(T->getDeducedType());
5041}
5042
5043bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5044 return VisitTagDecl(T->getDecl());
5045}
5046
5047bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5048 return VisitTagDecl(T->getDecl());
5049}
5050
5051bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5052 const TemplateTypeParmType*) {
5053 return false;
5054}
5055
5056bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5057 const SubstTemplateTypeParmPackType *) {
5058 return false;
5059}
5060
5061bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5062 const TemplateSpecializationType*) {
5063 return false;
5064}
5065
5066bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5067 const InjectedClassNameType* T) {
5068 return VisitTagDecl(T->getDecl());
5069}
5070
5071bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5072 const DependentNameType* T) {
5073 return VisitNestedNameSpecifier(T->getQualifier());
5074}
5075
5076bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5077 const DependentTemplateSpecializationType* T) {
5078 return VisitNestedNameSpecifier(T->getQualifier());
5079}
5080
5081bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5082 const PackExpansionType* T) {
5083 return Visit(T->getPattern());
5084}
5085
5086bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5087 return false;
5088}
5089
5090bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5091 const ObjCInterfaceType *) {
5092 return false;
5093}
5094
5095bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5096 const ObjCObjectPointerType *) {
5097 return false;
5098}
5099
5100bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5101 return Visit(T->getValueType());
5102}
5103
5104bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5105 return false;
5106}
5107
5108bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5109 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5110 S.Diag(SR.getBegin(),
5111 S.getLangOpts().CPlusPlus11 ?
5112 diag::warn_cxx98_compat_template_arg_local_type :
5113 diag::ext_template_arg_local_type)
5114 << S.Context.getTypeDeclType(Tag) << SR;
5115 return true;
5116 }
5117
5118 if (!Tag->hasNameForLinkage()) {
5119 S.Diag(SR.getBegin(),
5120 S.getLangOpts().CPlusPlus11 ?
5121 diag::warn_cxx98_compat_template_arg_unnamed_type :
5122 diag::ext_template_arg_unnamed_type) << SR;
5123 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5124 return true;
5125 }
5126
5127 return false;
5128}
5129
5130bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5131 NestedNameSpecifier *NNS) {
5132 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5133 return true;
5134
5135 switch (NNS->getKind()) {
5136 case NestedNameSpecifier::Identifier:
5137 case NestedNameSpecifier::Namespace:
5138 case NestedNameSpecifier::NamespaceAlias:
5139 case NestedNameSpecifier::Global:
5140 case NestedNameSpecifier::Super:
5141 return false;
5142
5143 case NestedNameSpecifier::TypeSpec:
5144 case NestedNameSpecifier::TypeSpecWithTemplate:
5145 return Visit(QualType(NNS->getAsType(), 0));
5146 }
5147 llvm_unreachable("Invalid NestedNameSpecifier::Kind!")::llvm::llvm_unreachable_internal("Invalid NestedNameSpecifier::Kind!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5147)
;
5148}
5149
5150/// \brief Check a template argument against its corresponding
5151/// template type parameter.
5152///
5153/// This routine implements the semantics of C++ [temp.arg.type]. It
5154/// returns true if an error occurred, and false otherwise.
5155bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5156 TypeSourceInfo *ArgInfo) {
5157 assert(ArgInfo && "invalid TypeSourceInfo")((ArgInfo && "invalid TypeSourceInfo") ? static_cast<
void> (0) : __assert_fail ("ArgInfo && \"invalid TypeSourceInfo\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5157, __PRETTY_FUNCTION__))
;
5158 QualType Arg = ArgInfo->getType();
5159 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5160
5161 if (Arg->isVariablyModifiedType()) {
5162 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5163 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5164 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5165 }
5166
5167 // C++03 [temp.arg.type]p2:
5168 // A local type, a type with no linkage, an unnamed type or a type
5169 // compounded from any of these types shall not be used as a
5170 // template-argument for a template type-parameter.
5171 //
5172 // C++11 allows these, and even in C++03 we allow them as an extension with
5173 // a warning.
5174 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5175 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5176 (void)Finder.Visit(Context.getCanonicalType(Arg));
5177 }
5178
5179 return false;
5180}
5181
5182enum NullPointerValueKind {
5183 NPV_NotNullPointer,
5184 NPV_NullPointer,
5185 NPV_Error
5186};
5187
5188/// \brief Determine whether the given template argument is a null pointer
5189/// value of the appropriate type.
5190static NullPointerValueKind
5191isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5192 QualType ParamType, Expr *Arg) {
5193 if (Arg->isValueDependent() || Arg->isTypeDependent())
5194 return NPV_NotNullPointer;
5195
5196 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5197 llvm_unreachable(::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5198)
5198 "Incomplete parameter type in isNullPointerValueTemplateArgument!")::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5198)
;
5199
5200 if (!S.getLangOpts().CPlusPlus11)
5201 return NPV_NotNullPointer;
5202
5203 // Determine whether we have a constant expression.
5204 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5205 if (ArgRV.isInvalid())
5206 return NPV_Error;
5207 Arg = ArgRV.get();
5208
5209 Expr::EvalResult EvalResult;
5210 SmallVector<PartialDiagnosticAt, 8> Notes;
5211 EvalResult.Diag = &Notes;
5212 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5213 EvalResult.HasSideEffects) {
5214 SourceLocation DiagLoc = Arg->getExprLoc();
5215
5216 // If our only note is the usual "invalid subexpression" note, just point
5217 // the caret at its location rather than producing an essentially
5218 // redundant note.
5219 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5220 diag::note_invalid_subexpr_in_const_expr) {
5221 DiagLoc = Notes[0].first;
5222 Notes.clear();
5223 }
5224
5225 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5226 << Arg->getType() << Arg->getSourceRange();
5227 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5228 S.Diag(Notes[I].first, Notes[I].second);
5229
5230 S.Diag(Param->getLocation(), diag::note_template_param_here);
5231 return NPV_Error;
5232 }
5233
5234 // C++11 [temp.arg.nontype]p1:
5235 // - an address constant expression of type std::nullptr_t
5236 if (Arg->getType()->isNullPtrType())
5237 return NPV_NullPointer;
5238
5239 // - a constant expression that evaluates to a null pointer value (4.10); or
5240 // - a constant expression that evaluates to a null member pointer value
5241 // (4.11); or
5242 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5243 (EvalResult.Val.isMemberPointer() &&
5244 !EvalResult.Val.getMemberPointerDecl())) {
5245 // If our expression has an appropriate type, we've succeeded.
5246 bool ObjCLifetimeConversion;
5247 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5248 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5249 ObjCLifetimeConversion))
5250 return NPV_NullPointer;
5251
5252 // The types didn't match, but we know we got a null pointer; complain,
5253 // then recover as if the types were correct.
5254 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5255 << Arg->getType() << ParamType << Arg->getSourceRange();
5256 S.Diag(Param->getLocation(), diag::note_template_param_here);
5257 return NPV_NullPointer;
5258 }
5259
5260 // If we don't have a null pointer value, but we do have a NULL pointer
5261 // constant, suggest a cast to the appropriate type.
5262 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5263 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5264 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5265 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5266 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5267 ")");
5268 S.Diag(Param->getLocation(), diag::note_template_param_here);
5269 return NPV_NullPointer;
5270 }
5271
5272 // FIXME: If we ever want to support general, address-constant expressions
5273 // as non-type template arguments, we should return the ExprResult here to
5274 // be interpreted by the caller.
5275 return NPV_NotNullPointer;
5276}
5277
5278/// \brief Checks whether the given template argument is compatible with its
5279/// template parameter.
5280static bool CheckTemplateArgumentIsCompatibleWithParameter(
5281 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5282 Expr *Arg, QualType ArgType) {
5283 bool ObjCLifetimeConversion;
5284 if (ParamType->isPointerType() &&
5285 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5286 S.IsQualificationConversion(ArgType, ParamType, false,
5287 ObjCLifetimeConversion)) {
5288 // For pointer-to-object types, qualification conversions are
5289 // permitted.
5290 } else {
5291 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5292 if (!ParamRef->getPointeeType()->isFunctionType()) {
5293 // C++ [temp.arg.nontype]p5b3:
5294 // For a non-type template-parameter of type reference to
5295 // object, no conversions apply. The type referred to by the
5296 // reference may be more cv-qualified than the (otherwise
5297 // identical) type of the template- argument. The
5298 // template-parameter is bound directly to the
5299 // template-argument, which shall be an lvalue.
5300
5301 // FIXME: Other qualifiers?
5302 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5303 unsigned ArgQuals = ArgType.getCVRQualifiers();
5304
5305 if ((ParamQuals | ArgQuals) != ParamQuals) {
5306 S.Diag(Arg->getLocStart(),
5307 diag::err_template_arg_ref_bind_ignores_quals)
5308 << ParamType << Arg->getType() << Arg->getSourceRange();
5309 S.Diag(Param->getLocation(), diag::note_template_param_here);
5310 return true;
5311 }
5312 }
5313 }
5314
5315 // At this point, the template argument refers to an object or
5316 // function with external linkage. We now need to check whether the
5317 // argument and parameter types are compatible.
5318 if (!S.Context.hasSameUnqualifiedType(ArgType,
5319 ParamType.getNonReferenceType())) {
5320 // We can't perform this conversion or binding.
5321 if (ParamType->isReferenceType())
5322 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5323 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5324 else
5325 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5326 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5327 S.Diag(Param->getLocation(), diag::note_template_param_here);
5328 return true;
5329 }
5330 }
5331
5332 return false;
5333}
5334
5335/// \brief Checks whether the given template argument is the address
5336/// of an object or function according to C++ [temp.arg.nontype]p1.
5337static bool
5338CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5339 NonTypeTemplateParmDecl *Param,
5340 QualType ParamType,
5341 Expr *ArgIn,
5342 TemplateArgument &Converted) {
5343 bool Invalid = false;
5344 Expr *Arg = ArgIn;
5345 QualType ArgType = Arg->getType();
5346
5347 bool AddressTaken = false;
5348 SourceLocation AddrOpLoc;
5349 if (S.getLangOpts().MicrosoftExt) {
5350 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5351 // dereference and address-of operators.
5352 Arg = Arg->IgnoreParenCasts();
5353
5354 bool ExtWarnMSTemplateArg = false;
5355 UnaryOperatorKind FirstOpKind;
5356 SourceLocation FirstOpLoc;
5357 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5358 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5359 if (UnOpKind == UO_Deref)
5360 ExtWarnMSTemplateArg = true;
5361 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5362 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5363 if (!AddrOpLoc.isValid()) {
5364 FirstOpKind = UnOpKind;
5365 FirstOpLoc = UnOp->getOperatorLoc();
5366 }
5367 } else
5368 break;
5369 }
5370 if (FirstOpLoc.isValid()) {
5371 if (ExtWarnMSTemplateArg)
5372 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5373 << ArgIn->getSourceRange();
5374
5375 if (FirstOpKind == UO_AddrOf)
5376 AddressTaken = true;
5377 else if (Arg->getType()->isPointerType()) {
5378 // We cannot let pointers get dereferenced here, that is obviously not a
5379 // constant expression.
5380 assert(FirstOpKind == UO_Deref)((FirstOpKind == UO_Deref) ? static_cast<void> (0) : __assert_fail
("FirstOpKind == UO_Deref", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5380, __PRETTY_FUNCTION__))
;
5381 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5382 << Arg->getSourceRange();
5383 }
5384 }
5385 } else {
5386 // See through any implicit casts we added to fix the type.
5387 Arg = Arg->IgnoreImpCasts();
5388
5389 // C++ [temp.arg.nontype]p1:
5390 //
5391 // A template-argument for a non-type, non-template
5392 // template-parameter shall be one of: [...]
5393 //
5394 // -- the address of an object or function with external
5395 // linkage, including function templates and function
5396 // template-ids but excluding non-static class members,
5397 // expressed as & id-expression where the & is optional if
5398 // the name refers to a function or array, or if the
5399 // corresponding template-parameter is a reference; or
5400
5401 // In C++98/03 mode, give an extension warning on any extra parentheses.
5402 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5403 bool ExtraParens = false;
5404 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5405 if (!Invalid && !ExtraParens) {
5406 S.Diag(Arg->getLocStart(),
5407 S.getLangOpts().CPlusPlus11
5408 ? diag::warn_cxx98_compat_template_arg_extra_parens
5409 : diag::ext_template_arg_extra_parens)
5410 << Arg->getSourceRange();
5411 ExtraParens = true;
5412 }
5413
5414 Arg = Parens->getSubExpr();
5415 }
5416
5417 while (SubstNonTypeTemplateParmExpr *subst =
5418 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5419 Arg = subst->getReplacement()->IgnoreImpCasts();
5420
5421 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5422 if (UnOp->getOpcode() == UO_AddrOf) {
5423 Arg = UnOp->getSubExpr();
5424 AddressTaken = true;
5425 AddrOpLoc = UnOp->getOperatorLoc();
5426 }
5427 }
5428
5429 while (SubstNonTypeTemplateParmExpr *subst =
5430 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5431 Arg = subst->getReplacement()->IgnoreImpCasts();
5432 }
5433
5434 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5435 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5436
5437 // If our parameter has pointer type, check for a null template value.
5438 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5439 NullPointerValueKind NPV;
5440 // dllimport'd entities aren't constant but are available inside of template
5441 // arguments.
5442 if (Entity && Entity->hasAttr<DLLImportAttr>())
5443 NPV = NPV_NotNullPointer;
5444 else
5445 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5446 switch (NPV) {
5447 case NPV_NullPointer:
5448 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5449 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5450 /*isNullPtr=*/true);
5451 return false;
5452
5453 case NPV_Error:
5454 return true;
5455
5456 case NPV_NotNullPointer:
5457 break;
5458 }
5459 }
5460
5461 // Stop checking the precise nature of the argument if it is value dependent,
5462 // it should be checked when instantiated.
5463 if (Arg->isValueDependent()) {
5464 Converted = TemplateArgument(ArgIn);
5465 return false;
5466 }
5467
5468 if (isa<CXXUuidofExpr>(Arg)) {
5469 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5470 ArgIn, Arg, ArgType))
5471 return true;
5472
5473 Converted = TemplateArgument(ArgIn);
5474 return false;
5475 }
5476
5477 if (!DRE) {
5478 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5479 << Arg->getSourceRange();
5480 S.Diag(Param->getLocation(), diag::note_template_param_here);
5481 return true;
5482 }
5483
5484 // Cannot refer to non-static data members
5485 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5486 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5487 << Entity << Arg->getSourceRange();
5488 S.Diag(Param->getLocation(), diag::note_template_param_here);
5489 return true;
5490 }
5491
5492 // Cannot refer to non-static member functions
5493 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5494 if (!Method->isStatic()) {
5495 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5496 << Method << Arg->getSourceRange();
5497 S.Diag(Param->getLocation(), diag::note_template_param_here);
5498 return true;
5499 }
5500 }
5501
5502 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5503 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5504
5505 // A non-type template argument must refer to an object or function.
5506 if (!Func && !Var) {
5507 // We found something, but we don't know specifically what it is.
5508 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5509 << Arg->getSourceRange();
5510 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5511 return true;
5512 }
5513
5514 // Address / reference template args must have external linkage in C++98.
5515 if (Entity->getFormalLinkage() == InternalLinkage) {
5516 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5517 diag::warn_cxx98_compat_template_arg_object_internal :
5518 diag::ext_template_arg_object_internal)
5519 << !Func << Entity << Arg->getSourceRange();
5520 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5521 << !Func;
5522 } else if (!Entity->hasLinkage()) {
5523 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5524 << !Func << Entity << Arg->getSourceRange();
5525 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5526 << !Func;
5527 return true;
5528 }
5529
5530 if (Func) {
5531 // If the template parameter has pointer type, the function decays.
5532 if (ParamType->isPointerType() && !AddressTaken)
5533 ArgType = S.Context.getPointerType(Func->getType());
5534 else if (AddressTaken && ParamType->isReferenceType()) {
5535 // If we originally had an address-of operator, but the
5536 // parameter has reference type, complain and (if things look
5537 // like they will work) drop the address-of operator.
5538 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5539 ParamType.getNonReferenceType())) {
5540 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5541 << ParamType;
5542 S.Diag(Param->getLocation(), diag::note_template_param_here);
5543 return true;
5544 }
5545
5546 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5547 << ParamType
5548 << FixItHint::CreateRemoval(AddrOpLoc);
5549 S.Diag(Param->getLocation(), diag::note_template_param_here);
5550
5551 ArgType = Func->getType();
5552 }
5553 } else {
5554 // A value of reference type is not an object.
5555 if (Var->getType()->isReferenceType()) {
5556 S.Diag(Arg->getLocStart(),
5557 diag::err_template_arg_reference_var)
5558 << Var->getType() << Arg->getSourceRange();
5559 S.Diag(Param->getLocation(), diag::note_template_param_here);
5560 return true;
5561 }
5562
5563 // A template argument must have static storage duration.
5564 if (Var->getTLSKind()) {
5565 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5566 << Arg->getSourceRange();
5567 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5568 return true;
5569 }
5570
5571 // If the template parameter has pointer type, we must have taken
5572 // the address of this object.
5573 if (ParamType->isReferenceType()) {
5574 if (AddressTaken) {
5575 // If we originally had an address-of operator, but the
5576 // parameter has reference type, complain and (if things look
5577 // like they will work) drop the address-of operator.
5578 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5579 ParamType.getNonReferenceType())) {
5580 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5581 << ParamType;
5582 S.Diag(Param->getLocation(), diag::note_template_param_here);
5583 return true;
5584 }
5585
5586 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5587 << ParamType
5588 << FixItHint::CreateRemoval(AddrOpLoc);
5589 S.Diag(Param->getLocation(), diag::note_template_param_here);
5590
5591 ArgType = Var->getType();
5592 }
5593 } else if (!AddressTaken && ParamType->isPointerType()) {
5594 if (Var->getType()->isArrayType()) {
5595 // Array-to-pointer decay.
5596 ArgType = S.Context.getArrayDecayedType(Var->getType());
5597 } else {
5598 // If the template parameter has pointer type but the address of
5599 // this object was not taken, complain and (possibly) recover by
5600 // taking the address of the entity.
5601 ArgType = S.Context.getPointerType(Var->getType());
5602 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5603 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5604 << ParamType;
5605 S.Diag(Param->getLocation(), diag::note_template_param_here);
5606 return true;
5607 }
5608
5609 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5610 << ParamType
5611 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5612
5613 S.Diag(Param->getLocation(), diag::note_template_param_here);
5614 }
5615 }
5616 }
5617
5618 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5619 Arg, ArgType))
5620 return true;
5621
5622 // Create the template argument.
5623 Converted =
5624 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5625 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5626 return false;
5627}
5628
5629/// \brief Checks whether the given template argument is a pointer to
5630/// member constant according to C++ [temp.arg.nontype]p1.
5631static bool CheckTemplateArgumentPointerToMember(Sema &S,
5632 NonTypeTemplateParmDecl *Param,
5633 QualType ParamType,
5634 Expr *&ResultArg,
5635 TemplateArgument &Converted) {
5636 bool Invalid = false;
5637
5638 // Check for a null pointer value.
5639 Expr *Arg = ResultArg;
5640 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5641 case NPV_Error:
5642 return true;
5643 case NPV_NullPointer:
5644 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5645 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5646 /*isNullPtr*/true);
5647 return false;
5648 case NPV_NotNullPointer:
5649 break;
5650 }
5651
5652 bool ObjCLifetimeConversion;
5653 if (S.IsQualificationConversion(Arg->getType(),
5654 ParamType.getNonReferenceType(),
5655 false, ObjCLifetimeConversion)) {
5656 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
5657 Arg->getValueKind()).get();
5658 ResultArg = Arg;
5659 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5660 ParamType.getNonReferenceType())) {
5661 // We can't perform this conversion.
5662 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5663 << Arg->getType() << ParamType << Arg->getSourceRange();
5664 S.Diag(Param->getLocation(), diag::note_template_param_here);
5665 return true;
5666 }
5667
5668 // See through any implicit casts we added to fix the type.
5669 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
5670 Arg = Cast->getSubExpr();
5671
5672 // C++ [temp.arg.nontype]p1:
5673 //
5674 // A template-argument for a non-type, non-template
5675 // template-parameter shall be one of: [...]
5676 //
5677 // -- a pointer to member expressed as described in 5.3.1.
5678 DeclRefExpr *DRE = nullptr;
5679
5680 // In C++98/03 mode, give an extension warning on any extra parentheses.
5681 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5682 bool ExtraParens = false;
5683 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5684 if (!Invalid && !ExtraParens) {
5685 S.Diag(Arg->getLocStart(),
5686 S.getLangOpts().CPlusPlus11 ?
5687 diag::warn_cxx98_compat_template_arg_extra_parens :
5688 diag::ext_template_arg_extra_parens)
5689 << Arg->getSourceRange();
5690 ExtraParens = true;
5691 }
5692
5693 Arg = Parens->getSubExpr();
5694 }
5695
5696 while (SubstNonTypeTemplateParmExpr *subst =
5697 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5698 Arg = subst->getReplacement()->IgnoreImpCasts();
5699
5700 // A pointer-to-member constant written &Class::member.
5701 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5702 if (UnOp->getOpcode() == UO_AddrOf) {
5703 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5704 if (DRE && !DRE->getQualifier())
5705 DRE = nullptr;
5706 }
5707 }
5708 // A constant of pointer-to-member type.
5709 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5710 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5711 if (VD->getType()->isMemberPointerType()) {
5712 if (isa<NonTypeTemplateParmDecl>(VD)) {
5713 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5714 Converted = TemplateArgument(Arg);
5715 } else {
5716 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5717 Converted = TemplateArgument(VD, ParamType);
5718 }
5719 return Invalid;
5720 }
5721 }
5722 }
5723
5724 DRE = nullptr;
5725 }
5726
5727 if (!DRE)
5728 return S.Diag(Arg->getLocStart(),
5729 diag::err_template_arg_not_pointer_to_member_form)
5730 << Arg->getSourceRange();
5731
5732 if (isa<FieldDecl>(DRE->getDecl()) ||
5733 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5734 isa<CXXMethodDecl>(DRE->getDecl())) {
5735 assert((isa<FieldDecl>(DRE->getDecl()) ||(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5738, __PRETTY_FUNCTION__))
5736 isa<IndirectFieldDecl>(DRE->getDecl()) ||(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5738, __PRETTY_FUNCTION__))
5737 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5738, __PRETTY_FUNCTION__))
5738 "Only non-static member pointers can make it here")(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5738, __PRETTY_FUNCTION__))
;
5739
5740 // Okay: this is the address of a non-static member, and therefore
5741 // a member pointer constant.
5742 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5743 Converted = TemplateArgument(Arg);
5744 } else {
5745 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5746 Converted = TemplateArgument(D, ParamType);
5747 }
5748 return Invalid;
5749 }
5750
5751 // We found something else, but we don't know specifically what it is.
5752 S.Diag(Arg->getLocStart(),
5753 diag::err_template_arg_not_pointer_to_member_form)
5754 << Arg->getSourceRange();
5755 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5756 return true;
5757}
5758
5759/// \brief Check a template argument against its corresponding
5760/// non-type template parameter.
5761///
5762/// This routine implements the semantics of C++ [temp.arg.nontype].
5763/// If an error occurred, it returns ExprError(); otherwise, it
5764/// returns the converted template argument. \p ParamType is the
5765/// type of the non-type template parameter after it has been instantiated.
5766ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5767 QualType ParamType, Expr *Arg,
5768 TemplateArgument &Converted,
5769 CheckTemplateArgumentKind CTAK) {
5770 SourceLocation StartLoc = Arg->getLocStart();
5771
5772 // If the parameter type somehow involves auto, deduce the type now.
5773 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
5774 // During template argument deduction, we allow 'decltype(auto)' to
5775 // match an arbitrary dependent argument.
5776 // FIXME: The language rules don't say what happens in this case.
5777 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5778 // expression is merely instantiation-dependent; is this enough?
5779 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5780 auto *AT = dyn_cast<AutoType>(ParamType);
5781 if (AT && AT->isDecltypeAuto()) {
5782 Converted = TemplateArgument(Arg);
5783 return Arg;
5784 }
5785 }
5786
5787 // When checking a deduced template argument, deduce from its type even if
5788 // the type is dependent, in order to check the types of non-type template
5789 // arguments line up properly in partial ordering.
5790 Optional<unsigned> Depth;
5791 if (CTAK != CTAK_Specified)
5792 Depth = Param->getDepth() + 1;
5793 if (DeduceAutoType(
5794 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
5795 Arg, ParamType, Depth) == DAR_Failed) {
5796 Diag(Arg->getExprLoc(),
5797 diag::err_non_type_template_parm_type_deduction_failure)
5798 << Param->getDeclName() << Param->getType() << Arg->getType()
5799 << Arg->getSourceRange();
5800 Diag(Param->getLocation(), diag::note_template_param_here);
5801 return ExprError();
5802 }
5803 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5804 // an error. The error message normally references the parameter
5805 // declaration, but here we'll pass the argument location because that's
5806 // where the parameter type is deduced.
5807 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5808 if (ParamType.isNull()) {
5809 Diag(Param->getLocation(), diag::note_template_param_here);
5810 return ExprError();
5811 }
5812 }
5813
5814 // We should have already dropped all cv-qualifiers by now.
5815 assert(!ParamType.hasQualifiers() &&((!ParamType.hasQualifiers() && "non-type template parameter type cannot be qualified"
) ? static_cast<void> (0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5816, __PRETTY_FUNCTION__))
5816 "non-type template parameter type cannot be qualified")((!ParamType.hasQualifiers() && "non-type template parameter type cannot be qualified"
) ? static_cast<void> (0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5816, __PRETTY_FUNCTION__))
;
5817
5818 if (CTAK == CTAK_Deduced &&
5819 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
5820 Arg->getType())) {
5821 // FIXME: If either type is dependent, we skip the check. This isn't
5822 // correct, since during deduction we're supposed to have replaced each
5823 // template parameter with some unique (non-dependent) placeholder.
5824 // FIXME: If the argument type contains 'auto', we carry on and fail the
5825 // type check in order to force specific types to be more specialized than
5826 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5827 // work.
5828 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5829 !Arg->getType()->getContainedAutoType()) {
5830 Converted = TemplateArgument(Arg);
5831 return Arg;
5832 }
5833 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5834 // we should actually be checking the type of the template argument in P,
5835 // not the type of the template argument deduced from A, against the
5836 // template parameter type.
5837 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5838 << Arg->getType()
5839 << ParamType.getUnqualifiedType();
5840 Diag(Param->getLocation(), diag::note_template_param_here);
5841 return ExprError();
5842 }
5843
5844 // If either the parameter has a dependent type or the argument is
5845 // type-dependent, there's nothing we can check now.
5846 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5847 // FIXME: Produce a cloned, canonical expression?
5848 Converted = TemplateArgument(Arg);
5849 return Arg;
5850 }
5851
5852 // The initialization of the parameter from the argument is
5853 // a constant-evaluated context.
5854 EnterExpressionEvaluationContext ConstantEvaluated(
5855 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5856
5857 if (getLangOpts().CPlusPlus1z) {
5858 // C++1z [temp.arg.nontype]p1:
5859 // A template-argument for a non-type template parameter shall be
5860 // a converted constant expression of the type of the template-parameter.
5861 APValue Value;
5862 ExprResult ArgResult = CheckConvertedConstantExpression(
5863 Arg, ParamType, Value, CCEK_TemplateArg);
5864 if (ArgResult.isInvalid())
5865 return ExprError();
5866
5867 // For a value-dependent argument, CheckConvertedConstantExpression is
5868 // permitted (and expected) to be unable to determine a value.
5869 if (ArgResult.get()->isValueDependent()) {
5870 Converted = TemplateArgument(ArgResult.get());
5871 return ArgResult;
5872 }
5873
5874 QualType CanonParamType = Context.getCanonicalType(ParamType);
5875
5876 // Convert the APValue to a TemplateArgument.
5877 switch (Value.getKind()) {
5878 case APValue::Uninitialized:
5879 assert(ParamType->isNullPtrType())((ParamType->isNullPtrType()) ? static_cast<void> (0
) : __assert_fail ("ParamType->isNullPtrType()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5879, __PRETTY_FUNCTION__))
;
5880 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
5881 break;
5882 case APValue::Int:
5883 assert(ParamType->isIntegralOrEnumerationType())((ParamType->isIntegralOrEnumerationType()) ? static_cast<
void> (0) : __assert_fail ("ParamType->isIntegralOrEnumerationType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5883, __PRETTY_FUNCTION__))
;
5884 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
5885 break;
5886 case APValue::MemberPointer: {
5887 assert(ParamType->isMemberPointerType())((ParamType->isMemberPointerType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isMemberPointerType()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5887, __PRETTY_FUNCTION__))
;
5888
5889 // FIXME: We need TemplateArgument representation and mangling for these.
5890 if (!Value.getMemberPointerPath().empty()) {
5891 Diag(Arg->getLocStart(),
5892 diag::err_template_arg_member_ptr_base_derived_not_supported)
5893 << Value.getMemberPointerDecl() << ParamType
5894 << Arg->getSourceRange();
5895 return ExprError();
5896 }
5897
5898 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
5899 Converted = VD ? TemplateArgument(VD, CanonParamType)
5900 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5901 break;
5902 }
5903 case APValue::LValue: {
5904 // For a non-type template-parameter of pointer or reference type,
5905 // the value of the constant expression shall not refer to
5906 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||((ParamType->isPointerType() || ParamType->isReferenceType
() || ParamType->isNullPtrType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5907, __PRETTY_FUNCTION__))
5907 ParamType->isNullPtrType())((ParamType->isPointerType() || ParamType->isReferenceType
() || ParamType->isNullPtrType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5907, __PRETTY_FUNCTION__))
;
5908 // -- a temporary object
5909 // -- a string literal
5910 // -- the result of a typeid expression, or
5911 // -- a predefined __func__ variable
5912 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5913 if (isa<CXXUuidofExpr>(E)) {
5914 Converted = TemplateArgument(const_cast<Expr*>(E));
5915 break;
5916 }
5917 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5918 << Arg->getSourceRange();
5919 return ExprError();
5920 }
5921 auto *VD = const_cast<ValueDecl *>(
5922 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5923 // -- a subobject
5924 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5925 VD && VD->getType()->isArrayType() &&
5926 Value.getLValuePath()[0].ArrayIndex == 0 &&
5927 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5928 // Per defect report (no number yet):
5929 // ... other than a pointer to the first element of a complete array
5930 // object.
5931 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5932 Value.isLValueOnePastTheEnd()) {
5933 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5934 << Value.getAsString(Context, ParamType);
5935 return ExprError();
5936 }
5937 assert((VD || !ParamType->isReferenceType()) &&(((VD || !ParamType->isReferenceType()) && "null reference should not be a constant expression"
) ? static_cast<void> (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5938, __PRETTY_FUNCTION__))
5938 "null reference should not be a constant expression")(((VD || !ParamType->isReferenceType()) && "null reference should not be a constant expression"
) ? static_cast<void> (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5938, __PRETTY_FUNCTION__))
;
5939 assert((!VD || !ParamType->isNullPtrType()) &&(((!VD || !ParamType->isNullPtrType()) && "non-null value of type nullptr_t?"
) ? static_cast<void> (0) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5940, __PRETTY_FUNCTION__))
5940 "non-null value of type nullptr_t?")(((!VD || !ParamType->isNullPtrType()) && "non-null value of type nullptr_t?"
) ? static_cast<void> (0) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5940, __PRETTY_FUNCTION__))
;
5941 Converted = VD ? TemplateArgument(VD, CanonParamType)
5942 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5943 break;
5944 }
5945 case APValue::AddrLabelDiff:
5946 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5947 case APValue::Float:
5948 case APValue::ComplexInt:
5949 case APValue::ComplexFloat:
5950 case APValue::Vector:
5951 case APValue::Array:
5952 case APValue::Struct:
5953 case APValue::Union:
5954 llvm_unreachable("invalid kind for template argument")::llvm::llvm_unreachable_internal("invalid kind for template argument"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5954)
;
5955 }
5956
5957 return ArgResult.get();
5958 }
5959
5960 // C++ [temp.arg.nontype]p5:
5961 // The following conversions are performed on each expression used
5962 // as a non-type template-argument. If a non-type
5963 // template-argument cannot be converted to the type of the
5964 // corresponding template-parameter then the program is
5965 // ill-formed.
5966 if (ParamType->isIntegralOrEnumerationType()) {
5967 // C++11:
5968 // -- for a non-type template-parameter of integral or
5969 // enumeration type, conversions permitted in a converted
5970 // constant expression are applied.
5971 //
5972 // C++98:
5973 // -- for a non-type template-parameter of integral or
5974 // enumeration type, integral promotions (4.5) and integral
5975 // conversions (4.7) are applied.
5976
5977 if (getLangOpts().CPlusPlus11) {
5978 // C++ [temp.arg.nontype]p1:
5979 // A template-argument for a non-type, non-template template-parameter
5980 // shall be one of:
5981 //
5982 // -- for a non-type template-parameter of integral or enumeration
5983 // type, a converted constant expression of the type of the
5984 // template-parameter; or
5985 llvm::APSInt Value;
5986 ExprResult ArgResult =
5987 CheckConvertedConstantExpression(Arg, ParamType, Value,
5988 CCEK_TemplateArg);
5989 if (ArgResult.isInvalid())
5990 return ExprError();
5991
5992 // We can't check arbitrary value-dependent arguments.
5993 if (ArgResult.get()->isValueDependent()) {
5994 Converted = TemplateArgument(ArgResult.get());
5995 return ArgResult;
5996 }
5997
5998 // Widen the argument value to sizeof(parameter type). This is almost
5999 // always a no-op, except when the parameter type is bool. In
6000 // that case, this may extend the argument from 1 bit to 8 bits.
6001 QualType IntegerType = ParamType;
6002 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6003 IntegerType = Enum->getDecl()->getIntegerType();
6004 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6005
6006 Converted = TemplateArgument(Context, Value,
6007 Context.getCanonicalType(ParamType));
6008 return ArgResult;
6009 }
6010
6011 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6012 if (ArgResult.isInvalid())
6013 return ExprError();
6014 Arg = ArgResult.get();
6015
6016 QualType ArgType = Arg->getType();
6017
6018 // C++ [temp.arg.nontype]p1:
6019 // A template-argument for a non-type, non-template
6020 // template-parameter shall be one of:
6021 //
6022 // -- an integral constant-expression of integral or enumeration
6023 // type; or
6024 // -- the name of a non-type template-parameter; or
6025 SourceLocation NonConstantLoc;
6026 llvm::APSInt Value;
6027 if (!ArgType->isIntegralOrEnumerationType()) {
6028 Diag(Arg->getLocStart(),
6029 diag::err_template_arg_not_integral_or_enumeral)
6030 << ArgType << Arg->getSourceRange();
6031 Diag(Param->getLocation(), diag::note_template_param_here);
6032 return ExprError();
6033 } else if (!Arg->isValueDependent()) {
6034 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6035 QualType T;
6036
6037 public:
6038 TmplArgICEDiagnoser(QualType T) : T(T) { }
6039
6040 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6041 SourceRange SR) override {
6042 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6043 }
6044 } Diagnoser(ArgType);
6045
6046 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6047 false).get();
6048 if (!Arg)
6049 return ExprError();
6050 }
6051
6052 // From here on out, all we care about is the unqualified form
6053 // of the argument type.
6054 ArgType = ArgType.getUnqualifiedType();
6055
6056 // Try to convert the argument to the parameter's type.
6057 if (Context.hasSameType(ParamType, ArgType)) {
6058 // Okay: no conversion necessary
6059 } else if (ParamType->isBooleanType()) {
6060 // This is an integral-to-boolean conversion.
6061 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6062 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6063 !ParamType->isEnumeralType()) {
6064 // This is an integral promotion or conversion.
6065 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6066 } else {
6067 // We can't perform this conversion.
6068 Diag(Arg->getLocStart(),
6069 diag::err_template_arg_not_convertible)
6070 << Arg->getType() << ParamType << Arg->getSourceRange();
6071 Diag(Param->getLocation(), diag::note_template_param_here);
6072 return ExprError();
6073 }
6074
6075 // Add the value of this argument to the list of converted
6076 // arguments. We use the bitwidth and signedness of the template
6077 // parameter.
6078 if (Arg->isValueDependent()) {
6079 // The argument is value-dependent. Create a new
6080 // TemplateArgument with the converted expression.
6081 Converted = TemplateArgument(Arg);
6082 return Arg;
6083 }
6084
6085 QualType IntegerType = Context.getCanonicalType(ParamType);
6086 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6087 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6088
6089 if (ParamType->isBooleanType()) {
6090 // Value must be zero or one.
6091 Value = Value != 0;
6092 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6093 if (Value.getBitWidth() != AllowedBits)
6094 Value = Value.extOrTrunc(AllowedBits);
6095 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6096 } else {
6097 llvm::APSInt OldValue = Value;
6098
6099 // Coerce the template argument's value to the value it will have
6100 // based on the template parameter's type.
6101 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6102 if (Value.getBitWidth() != AllowedBits)
6103 Value = Value.extOrTrunc(AllowedBits);
6104 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6105
6106 // Complain if an unsigned parameter received a negative value.
6107 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6108 && (OldValue.isSigned() && OldValue.isNegative())) {
6109 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6110 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6111 << Arg->getSourceRange();
6112 Diag(Param->getLocation(), diag::note_template_param_here);
6113 }
6114
6115 // Complain if we overflowed the template parameter's type.
6116 unsigned RequiredBits;
6117 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6118 RequiredBits = OldValue.getActiveBits();
6119 else if (OldValue.isUnsigned())
6120 RequiredBits = OldValue.getActiveBits() + 1;
6121 else
6122 RequiredBits = OldValue.getMinSignedBits();
6123 if (RequiredBits > AllowedBits) {
6124 Diag(Arg->getLocStart(),
6125 diag::warn_template_arg_too_large)
6126 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6127 << Arg->getSourceRange();
6128 Diag(Param->getLocation(), diag::note_template_param_here);
6129 }
6130 }
6131
6132 Converted = TemplateArgument(Context, Value,
6133 ParamType->isEnumeralType()
6134 ? Context.getCanonicalType(ParamType)
6135 : IntegerType);
6136 return Arg;
6137 }
6138
6139 QualType ArgType = Arg->getType();
6140 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6141
6142 // Handle pointer-to-function, reference-to-function, and
6143 // pointer-to-member-function all in (roughly) the same way.
6144 if (// -- For a non-type template-parameter of type pointer to
6145 // function, only the function-to-pointer conversion (4.3) is
6146 // applied. If the template-argument represents a set of
6147 // overloaded functions (or a pointer to such), the matching
6148 // function is selected from the set (13.4).
6149 (ParamType->isPointerType() &&
6150 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6151 // -- For a non-type template-parameter of type reference to
6152 // function, no conversions apply. If the template-argument
6153 // represents a set of overloaded functions, the matching
6154 // function is selected from the set (13.4).
6155 (ParamType->isReferenceType() &&
6156 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6157 // -- For a non-type template-parameter of type pointer to
6158 // member function, no conversions apply. If the
6159 // template-argument represents a set of overloaded member
6160 // functions, the matching member function is selected from
6161 // the set (13.4).
6162 (ParamType->isMemberPointerType() &&
6163 ParamType->getAs<MemberPointerType>()->getPointeeType()
6164 ->isFunctionType())) {
6165
6166 if (Arg->getType() == Context.OverloadTy) {
6167 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6168 true,
6169 FoundResult)) {
6170 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6171 return ExprError();
6172
6173 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6174 ArgType = Arg->getType();
6175 } else
6176 return ExprError();
6177 }
6178
6179 if (!ParamType->isMemberPointerType()) {
6180 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6181 ParamType,
6182 Arg, Converted))
6183 return ExprError();
6184 return Arg;
6185 }
6186
6187 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6188 Converted))
6189 return ExprError();
6190 return Arg;
6191 }
6192
6193 if (ParamType->isPointerType()) {
6194 // -- for a non-type template-parameter of type pointer to
6195 // object, qualification conversions (4.4) and the
6196 // array-to-pointer conversion (4.2) are applied.
6197 // C++0x also allows a value of std::nullptr_t.
6198 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&((ParamType->getPointeeType()->isIncompleteOrObjectType
() && "Only object pointers allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6199, __PRETTY_FUNCTION__))
6199 "Only object pointers allowed here")((ParamType->getPointeeType()->isIncompleteOrObjectType
() && "Only object pointers allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6199, __PRETTY_FUNCTION__))
;
6200
6201 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6202 ParamType,
6203 Arg, Converted))
6204 return ExprError();
6205 return Arg;
6206 }
6207
6208 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6209 // -- For a non-type template-parameter of type reference to
6210 // object, no conversions apply. The type referred to by the
6211 // reference may be more cv-qualified than the (otherwise
6212 // identical) type of the template-argument. The
6213 // template-parameter is bound directly to the
6214 // template-argument, which must be an lvalue.
6215 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&((ParamRefType->getPointeeType()->isIncompleteOrObjectType
() && "Only object references allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6216, __PRETTY_FUNCTION__))
6216 "Only object references allowed here")((ParamRefType->getPointeeType()->isIncompleteOrObjectType
() && "Only object references allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6216, __PRETTY_FUNCTION__))
;
6217
6218 if (Arg->getType() == Context.OverloadTy) {
6219 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6220 ParamRefType->getPointeeType(),
6221 true,
6222 FoundResult)) {
6223 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6224 return ExprError();
6225
6226 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6227 ArgType = Arg->getType();
6228 } else
6229 return ExprError();
6230 }
6231
6232 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6233 ParamType,
6234 Arg, Converted))
6235 return ExprError();
6236 return Arg;
6237 }
6238
6239 // Deal with parameters of type std::nullptr_t.
6240 if (ParamType->isNullPtrType()) {
6241 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6242 Converted = TemplateArgument(Arg);
6243 return Arg;
6244 }
6245
6246 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6247 case NPV_NotNullPointer:
6248 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6249 << Arg->getType() << ParamType;
6250 Diag(Param->getLocation(), diag::note_template_param_here);
6251 return ExprError();
6252
6253 case NPV_Error:
6254 return ExprError();
6255
6256 case NPV_NullPointer:
6257 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6258 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6259 /*isNullPtr*/true);
6260 return Arg;
6261 }
6262 }
6263
6264 // -- For a non-type template-parameter of type pointer to data
6265 // member, qualification conversions (4.4) are applied.
6266 assert(ParamType->isMemberPointerType() && "Only pointers to members remain")((ParamType->isMemberPointerType() && "Only pointers to members remain"
) ? static_cast<void> (0) : __assert_fail ("ParamType->isMemberPointerType() && \"Only pointers to members remain\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6266, __PRETTY_FUNCTION__))
;
6267
6268 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6269 Converted))
6270 return ExprError();
6271 return Arg;
6272}
6273
6274static void DiagnoseTemplateParameterListArityMismatch(
6275 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6276 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6277
6278/// \brief Check a template argument against its corresponding
6279/// template template parameter.
6280///
6281/// This routine implements the semantics of C++ [temp.arg.template].
6282/// It returns true if an error occurred, and false otherwise.
6283bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6284 TemplateArgumentLoc &Arg,
6285 unsigned ArgumentPackIndex) {
6286 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6287 TemplateDecl *Template = Name.getAsTemplateDecl();
6288 if (!Template) {
6289 // Any dependent template name is fine.
6290 assert(Name.isDependent() && "Non-dependent template isn't a declaration?")((Name.isDependent() && "Non-dependent template isn't a declaration?"
) ? static_cast<void> (0) : __assert_fail ("Name.isDependent() && \"Non-dependent template isn't a declaration?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6290, __PRETTY_FUNCTION__))
;
6291 return false;
6292 }
6293
6294 if (Template->isInvalidDecl())
6295 return true;
6296
6297 // C++0x [temp.arg.template]p1:
6298 // A template-argument for a template template-parameter shall be
6299 // the name of a class template or an alias template, expressed as an
6300 // id-expression. When the template-argument names a class template, only
6301 // primary class templates are considered when matching the
6302 // template template argument with the corresponding parameter;
6303 // partial specializations are not considered even if their
6304 // parameter lists match that of the template template parameter.
6305 //
6306 // Note that we also allow template template parameters here, which
6307 // will happen when we are dealing with, e.g., class template
6308 // partial specializations.
6309 if (!isa<ClassTemplateDecl>(Template) &&
6310 !isa<TemplateTemplateParmDecl>(Template) &&
6311 !isa<TypeAliasTemplateDecl>(Template) &&
6312 !isa<BuiltinTemplateDecl>(Template)) {
6313 assert(isa<FunctionTemplateDecl>(Template) &&((isa<FunctionTemplateDecl>(Template) && "Only function templates are possible here"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6314, __PRETTY_FUNCTION__))
6314 "Only function templates are possible here")((isa<FunctionTemplateDecl>(Template) && "Only function templates are possible here"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6314, __PRETTY_FUNCTION__))
;
6315 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6316 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6317 << Template;
6318 }
6319
6320 TemplateParameterList *Params = Param->getTemplateParameters();
6321 if (Param->isExpandedParameterPack())
6322 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6323
6324 // C++1z [temp.arg.template]p3: (DR 150)
6325 // A template-argument matches a template template-parameter P when P
6326 // is at least as specialized as the template-argument A.
6327 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6328 // Quick check for the common case:
6329 // If P contains a parameter pack, then A [...] matches P if each of A's
6330 // template parameters matches the corresponding template parameter in
6331 // the template-parameter-list of P.
6332 if (TemplateParameterListsAreEqual(
6333 Template->getTemplateParameters(), Params, false,
6334 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6335 return false;
6336
6337 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6338 Arg.getLocation()))
6339 return false;
6340 // FIXME: Produce better diagnostics for deduction failures.
6341 }
6342
6343 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6344 Params,
6345 true,
6346 TPL_TemplateTemplateArgumentMatch,
6347 Arg.getLocation());
6348}
6349
6350/// \brief Given a non-type template argument that refers to a
6351/// declaration and the type of its corresponding non-type template
6352/// parameter, produce an expression that properly refers to that
6353/// declaration.
6354ExprResult
6355Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6356 QualType ParamType,
6357 SourceLocation Loc) {
6358 // C++ [temp.param]p8:
6359 //
6360 // A non-type template-parameter of type "array of T" or
6361 // "function returning T" is adjusted to be of type "pointer to
6362 // T" or "pointer to function returning T", respectively.
6363 if (ParamType->isArrayType())
6364 ParamType = Context.getArrayDecayedType(ParamType);
6365 else if (ParamType->isFunctionType())
6366 ParamType = Context.getPointerType(ParamType);
6367
6368 // For a NULL non-type template argument, return nullptr casted to the
6369 // parameter's type.
6370 if (Arg.getKind() == TemplateArgument::NullPtr) {
6371 return ImpCastExprToType(
6372 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6373 ParamType,
6374 ParamType->getAs<MemberPointerType>()
6375 ? CK_NullToMemberPointer
6376 : CK_NullToPointer);
6377 }
6378 assert(Arg.getKind() == TemplateArgument::Declaration &&((Arg.getKind() == TemplateArgument::Declaration && "Only declaration template arguments permitted here"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6379, __PRETTY_FUNCTION__))
6379 "Only declaration template arguments permitted here")((Arg.getKind() == TemplateArgument::Declaration && "Only declaration template arguments permitted here"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6379, __PRETTY_FUNCTION__))
;
6380
6381 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6382
6383 if (VD->getDeclContext()->isRecord() &&
6384 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6385 isa<IndirectFieldDecl>(VD))) {
6386 // If the value is a class member, we might have a pointer-to-member.
6387 // Determine whether the non-type template template parameter is of
6388 // pointer-to-member type. If so, we need to build an appropriate
6389 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6390 // would refer to the member itself.
6391 if (ParamType->isMemberPointerType()) {
6392 QualType ClassType
6393 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6394 NestedNameSpecifier *Qualifier
6395 = NestedNameSpecifier::Create(Context, nullptr, false,
6396 ClassType.getTypePtr());
6397 CXXScopeSpec SS;
6398 SS.MakeTrivial(Context, Qualifier, Loc);
6399
6400 // The actual value-ness of this is unimportant, but for
6401 // internal consistency's sake, references to instance methods
6402 // are r-values.
6403 ExprValueKind VK = VK_LValue;
6404 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6405 VK = VK_RValue;
6406
6407 ExprResult RefExpr = BuildDeclRefExpr(VD,
6408 VD->getType().getNonReferenceType(),
6409 VK,
6410 Loc,
6411 &SS);
6412 if (RefExpr.isInvalid())
6413 return ExprError();
6414
6415 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6416
6417 // We might need to perform a trailing qualification conversion, since
6418 // the element type on the parameter could be more qualified than the
6419 // element type in the expression we constructed.
6420 bool ObjCLifetimeConversion;
6421 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6422 ParamType.getUnqualifiedType(), false,
6423 ObjCLifetimeConversion))
6424 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6425
6426 assert(!RefExpr.isInvalid() &&((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6428, __PRETTY_FUNCTION__))
6427 Context.hasSameType(((Expr*) RefExpr.get())->getType(),((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6428, __PRETTY_FUNCTION__))
6428 ParamType.getUnqualifiedType()))((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6428, __PRETTY_FUNCTION__))
;
6429 return RefExpr;
6430 }
6431 }
6432
6433 QualType T = VD->getType().getNonReferenceType();
6434
6435 if (ParamType->isPointerType()) {
6436 // When the non-type template parameter is a pointer, take the
6437 // address of the declaration.
6438 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6439 if (RefExpr.isInvalid())
6440 return ExprError();
6441
6442 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6443 (T->isFunctionType() || T->isArrayType())) {
6444 // Decay functions and arrays unless we're forming a pointer to array.
6445 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6446 if (RefExpr.isInvalid())
6447 return ExprError();
6448
6449 return RefExpr;
6450 }
6451
6452 // Take the address of everything else
6453 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6454 }
6455
6456 ExprValueKind VK = VK_RValue;
6457
6458 // If the non-type template parameter has reference type, qualify the
6459 // resulting declaration reference with the extra qualifiers on the
6460 // type that the reference refers to.
6461 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6462 VK = VK_LValue;
6463 T = Context.getQualifiedType(T,
6464 TargetRef->getPointeeType().getQualifiers());
6465 } else if (isa<FunctionDecl>(VD)) {
6466 // References to functions are always lvalues.
6467 VK = VK_LValue;
6468 }
6469
6470 return BuildDeclRefExpr(VD, T, VK, Loc);
6471}
6472
6473/// \brief Construct a new expression that refers to the given
6474/// integral template argument with the given source-location
6475/// information.
6476///
6477/// This routine takes care of the mapping from an integral template
6478/// argument (which may have any integral type) to the appropriate
6479/// literal value.
6480ExprResult
6481Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6482 SourceLocation Loc) {
6483 assert(Arg.getKind() == TemplateArgument::Integral &&((Arg.getKind() == TemplateArgument::Integral && "Operation is only valid for integral template arguments"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6484, __PRETTY_FUNCTION__))
6484 "Operation is only valid for integral template arguments")((Arg.getKind() == TemplateArgument::Integral && "Operation is only valid for integral template arguments"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6484, __PRETTY_FUNCTION__))
;
6485 QualType OrigT = Arg.getIntegralType();
6486
6487 // If this is an enum type that we're instantiating, we need to use an integer
6488 // type the same size as the enumerator. We don't want to build an
6489 // IntegerLiteral with enum type. The integer type of an enum type can be of
6490 // any integral type with C++11 enum classes, make sure we create the right
6491 // type of literal for it.
6492 QualType T = OrigT;
6493 if (const EnumType *ET = OrigT->getAs<EnumType>())
6494 T = ET->getDecl()->getIntegerType();
6495
6496 Expr *E;
6497 if (T->isAnyCharacterType()) {
6498 // This does not need to handle u8 character literals because those are
6499 // of type char, and so can also be covered by an ASCII character literal.
6500 CharacterLiteral::CharacterKind Kind;
6501 if (T->isWideCharType())
6502 Kind = CharacterLiteral::Wide;
6503 else if (T->isChar16Type())
6504 Kind = CharacterLiteral::UTF16;
6505 else if (T->isChar32Type())
6506 Kind = CharacterLiteral::UTF32;
6507 else
6508 Kind = CharacterLiteral::Ascii;
6509
6510 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6511 Kind, T, Loc);
6512 } else if (T->isBooleanType()) {
6513 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6514 T, Loc);
6515 } else if (T->isNullPtrType()) {
6516 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6517 } else {
6518 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6519 }
6520
6521 if (OrigT->isEnumeralType()) {
6522 // FIXME: This is a hack. We need a better way to handle substituted
6523 // non-type template parameters.
6524 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6525 nullptr,
6526 Context.getTrivialTypeSourceInfo(OrigT, Loc),
6527 Loc, Loc);
6528 }
6529
6530 return E;
6531}
6532
6533/// \brief Match two template parameters within template parameter lists.
6534static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6535 bool Complain,
6536 Sema::TemplateParameterListEqualKind Kind,
6537 SourceLocation TemplateArgLoc) {
6538 // Check the actual kind (type, non-type, template).
6539 if (Old->getKind() != New->getKind()) {
6540 if (Complain) {
6541 unsigned NextDiag = diag::err_template_param_different_kind;
6542 if (TemplateArgLoc.isValid()) {
6543 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6544 NextDiag = diag::note_template_param_different_kind;
6545 }
6546 S.Diag(New->getLocation(), NextDiag)
6547 << (Kind != Sema::TPL_TemplateMatch);
6548 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6549 << (Kind != Sema::TPL_TemplateMatch);
6550 }
6551
6552 return false;
6553 }
6554
6555 // Check that both are parameter packs or neither are parameter packs.
6556 // However, if we are matching a template template argument to a
6557 // template template parameter, the template template parameter can have
6558 // a parameter pack where the template template argument does not.
6559 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6560 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6561 Old->isTemplateParameterPack())) {
6562 if (Complain) {
6563 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6564 if (TemplateArgLoc.isValid()) {
6565 S.Diag(TemplateArgLoc,
6566 diag::err_template_arg_template_params_mismatch);
6567 NextDiag = diag::note_template_parameter_pack_non_pack;
6568 }
6569
6570 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6571 : isa<NonTypeTemplateParmDecl>(New)? 1
6572 : 2;
6573 S.Diag(New->getLocation(), NextDiag)
6574 << ParamKind << New->isParameterPack();
6575 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6576 << ParamKind << Old->isParameterPack();
6577 }
6578
6579 return false;
6580 }
6581
6582 // For non-type template parameters, check the type of the parameter.
6583 if (NonTypeTemplateParmDecl *OldNTTP
6584 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6585 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6586
6587 // If we are matching a template template argument to a template
6588 // template parameter and one of the non-type template parameter types
6589 // is dependent, then we must wait until template instantiation time
6590 // to actually compare the arguments.
6591 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6592 (OldNTTP->getType()->isDependentType() ||
6593 NewNTTP->getType()->isDependentType()))
6594 return true;
6595
6596 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6597 if (Complain) {
6598 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6599 if (TemplateArgLoc.isValid()) {
6600 S.Diag(TemplateArgLoc,
6601 diag::err_template_arg_template_params_mismatch);
6602 NextDiag = diag::note_template_nontype_parm_different_type;
6603 }
6604 S.Diag(NewNTTP->getLocation(), NextDiag)
6605 << NewNTTP->getType()
6606 << (Kind != Sema::TPL_TemplateMatch);
6607 S.Diag(OldNTTP->getLocation(),
6608 diag::note_template_nontype_parm_prev_declaration)
6609 << OldNTTP->getType();
6610 }
6611
6612 return false;
6613 }
6614
6615 return true;
6616 }
6617
6618 // For template template parameters, check the template parameter types.
6619 // The template parameter lists of template template
6620 // parameters must agree.
6621 if (TemplateTemplateParmDecl *OldTTP
6622 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6623 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6624 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6625 OldTTP->getTemplateParameters(),
6626 Complain,
6627 (Kind == Sema::TPL_TemplateMatch
6628 ? Sema::TPL_TemplateTemplateParmMatch
6629 : Kind),
6630 TemplateArgLoc);
6631 }
6632
6633 return true;
6634}
6635
6636/// \brief Diagnose a known arity mismatch when comparing template argument
6637/// lists.
6638static
6639void DiagnoseTemplateParameterListArityMismatch(Sema &S,
6640 TemplateParameterList *New,
6641 TemplateParameterList *Old,
6642 Sema::TemplateParameterListEqualKind Kind,
6643 SourceLocation TemplateArgLoc) {
6644 unsigned NextDiag = diag::err_template_param_list_different_arity;
6645 if (TemplateArgLoc.isValid()) {
6646 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6647 NextDiag = diag::note_template_param_list_different_arity;
6648 }
6649 S.Diag(New->getTemplateLoc(), NextDiag)
6650 << (New->size() > Old->size())
6651 << (Kind != Sema::TPL_TemplateMatch)
6652 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6653 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6654 << (Kind != Sema::TPL_TemplateMatch)
6655 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6656}
6657
6658/// \brief Determine whether the given template parameter lists are
6659/// equivalent.
6660///
6661/// \param New The new template parameter list, typically written in the
6662/// source code as part of a new template declaration.
6663///
6664/// \param Old The old template parameter list, typically found via
6665/// name lookup of the template declared with this template parameter
6666/// list.
6667///
6668/// \param Complain If true, this routine will produce a diagnostic if
6669/// the template parameter lists are not equivalent.
6670///
6671/// \param Kind describes how we are to match the template parameter lists.
6672///
6673/// \param TemplateArgLoc If this source location is valid, then we
6674/// are actually checking the template parameter list of a template
6675/// argument (New) against the template parameter list of its
6676/// corresponding template template parameter (Old). We produce
6677/// slightly different diagnostics in this scenario.
6678///
6679/// \returns True if the template parameter lists are equal, false
6680/// otherwise.
6681bool
6682Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6683 TemplateParameterList *Old,
6684 bool Complain,
6685 TemplateParameterListEqualKind Kind,
6686 SourceLocation TemplateArgLoc) {
6687 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6688 if (Complain)
6689 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6690 TemplateArgLoc);
6691
6692 return false;
6693 }
6694
6695 // C++0x [temp.arg.template]p3:
6696 // A template-argument matches a template template-parameter (call it P)
6697 // when each of the template parameters in the template-parameter-list of
6698 // the template-argument's corresponding class template or alias template
6699 // (call it A) matches the corresponding template parameter in the
6700 // template-parameter-list of P. [...]
6701 TemplateParameterList::iterator NewParm = New->begin();
6702 TemplateParameterList::iterator NewParmEnd = New->end();
6703 for (TemplateParameterList::iterator OldParm = Old->begin(),
6704 OldParmEnd = Old->end();
6705 OldParm != OldParmEnd; ++OldParm) {
6706 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6707 !(*OldParm)->isTemplateParameterPack()) {
6708 if (NewParm == NewParmEnd) {
6709 if (Complain)
6710 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6711 TemplateArgLoc);
6712
6713 return false;
6714 }
6715
6716 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6717 Kind, TemplateArgLoc))
6718 return false;
6719
6720 ++NewParm;
6721 continue;
6722 }
6723
6724 // C++0x [temp.arg.template]p3:
6725 // [...] When P's template- parameter-list contains a template parameter
6726 // pack (14.5.3), the template parameter pack will match zero or more
6727 // template parameters or template parameter packs in the
6728 // template-parameter-list of A with the same type and form as the
6729 // template parameter pack in P (ignoring whether those template
6730 // parameters are template parameter packs).
6731 for (; NewParm != NewParmEnd; ++NewParm) {
6732 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6733 Kind, TemplateArgLoc))
6734 return false;
6735 }
6736 }
6737
6738 // Make sure we exhausted all of the arguments.
6739 if (NewParm != NewParmEnd) {
6740 if (Complain)
6741 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6742 TemplateArgLoc);
6743
6744 return false;
6745 }
6746
6747 return true;
6748}
6749
6750/// \brief Check whether a template can be declared within this scope.
6751///
6752/// If the template declaration is valid in this scope, returns
6753/// false. Otherwise, issues a diagnostic and returns true.
6754bool
6755Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
6756 if (!S)
6757 return false;
6758
6759 // Find the nearest enclosing declaration scope.
6760 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6761 (S->getFlags() & Scope::TemplateParamScope) != 0)
6762 S = S->getParent();
6763
6764 // C++ [temp]p4:
6765 // A template [...] shall not have C linkage.
6766 DeclContext *Ctx = S->getEntity();
6767 if (Ctx && Ctx->isExternCContext()) {
6768 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6769 << TemplateParams->getSourceRange();
6770 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6771 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6772 return true;
6773 }
6774 Ctx = Ctx->getRedeclContext();
6775
6776 // C++ [temp]p2:
6777 // A template-declaration can appear only as a namespace scope or
6778 // class scope declaration.
6779 if (Ctx) {
6780 if (Ctx->isFileContext())
6781 return false;
6782 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6783 // C++ [temp.mem]p2:
6784 // A local class shall not have member templates.
6785 if (RD->isLocalClass())
6786 return Diag(TemplateParams->getTemplateLoc(),
6787 diag::err_template_inside_local_class)
6788 << TemplateParams->getSourceRange();
6789 else
6790 return false;
6791 }
6792 }
6793
6794 return Diag(TemplateParams->getTemplateLoc(),
6795 diag::err_template_outside_namespace_or_class_scope)
6796 << TemplateParams->getSourceRange();
6797}
6798
6799/// \brief Determine what kind of template specialization the given declaration
6800/// is.
6801static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
6802 if (!D)
6803 return TSK_Undeclared;
6804
6805 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6806 return Record->getTemplateSpecializationKind();
6807 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6808 return Function->getTemplateSpecializationKind();
6809 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6810 return Var->getTemplateSpecializationKind();
6811
6812 return TSK_Undeclared;
6813}
6814
6815/// \brief Check whether a specialization is well-formed in the current
6816/// context.
6817///
6818/// This routine determines whether a template specialization can be declared
6819/// in the current context (C++ [temp.expl.spec]p2).
6820///
6821/// \param S the semantic analysis object for which this check is being
6822/// performed.
6823///
6824/// \param Specialized the entity being specialized or instantiated, which
6825/// may be a kind of template (class template, function template, etc.) or
6826/// a member of a class template (member function, static data member,
6827/// member class).
6828///
6829/// \param PrevDecl the previous declaration of this entity, if any.
6830///
6831/// \param Loc the location of the explicit specialization or instantiation of
6832/// this entity.
6833///
6834/// \param IsPartialSpecialization whether this is a partial specialization of
6835/// a class template.
6836///
6837/// \returns true if there was an error that we cannot recover from, false
6838/// otherwise.
6839static bool CheckTemplateSpecializationScope(Sema &S,
6840 NamedDecl *Specialized,
6841 NamedDecl *PrevDecl,
6842 SourceLocation Loc,
6843 bool IsPartialSpecialization) {
6844 // Keep these "kind" numbers in sync with the %select statements in the
6845 // various diagnostics emitted by this routine.
6846 int EntityKind = 0;
6847 if (isa<ClassTemplateDecl>(Specialized))
6848 EntityKind = IsPartialSpecialization? 1 : 0;
6849 else if (isa<VarTemplateDecl>(Specialized))
6850 EntityKind = IsPartialSpecialization ? 3 : 2;
6851 else if (isa<FunctionTemplateDecl>(Specialized))
6852 EntityKind = 4;
6853 else if (isa<CXXMethodDecl>(Specialized))
6854 EntityKind = 5;
6855 else if (isa<VarDecl>(Specialized))
6856 EntityKind = 6;
6857 else if (isa<RecordDecl>(Specialized))
6858 EntityKind = 7;
6859 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6860 EntityKind = 8;
6861 else {
6862 S.Diag(Loc, diag::err_template_spec_unknown_kind)
6863 << S.getLangOpts().CPlusPlus11;
6864 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6865 return true;
6866 }
6867
6868 // C++ [temp.expl.spec]p2:
6869 // An explicit specialization shall be declared in the namespace
6870 // of which the template is a member, or, for member templates, in
6871 // the namespace of which the enclosing class or enclosing class
6872 // template is a member. An explicit specialization of a member
6873 // function, member class or static data member of a class
6874 // template shall be declared in the namespace of which the class
6875 // template is a member. Such a declaration may also be a
6876 // definition. If the declaration is not a definition, the
6877 // specialization may be defined later in the name- space in which
6878 // the explicit specialization was declared, or in a namespace
6879 // that encloses the one in which the explicit specialization was
6880 // declared.
6881 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6882 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
6883 << Specialized;
6884 return true;
6885 }
6886
6887 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
6888 if (S.getLangOpts().MicrosoftExt) {
6889 // Do not warn for class scope explicit specialization during
6890 // instantiation, warning was already emitted during pattern
6891 // semantic analysis.
6892 if (!S.inTemplateInstantiation())
6893 S.Diag(Loc, diag::ext_function_specialization_in_class)
6894 << Specialized;
6895 } else {
6896 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6897 << Specialized;
6898 return true;
6899 }
6900 }
6901
6902 if (S.CurContext->isRecord() &&
6903 !S.CurContext->Equals(Specialized->getDeclContext())) {
6904 // Make sure that we're specializing in the right record context.
6905 // Otherwise, things can go horribly wrong.
6906 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6907 << Specialized;
6908 return true;
6909 }
6910
6911 // C++ [temp.class.spec]p6:
6912 // A class template partial specialization may be declared or redeclared
6913 // in any namespace scope in which its definition may be defined (14.5.1
6914 // and 14.5.2).
6915 DeclContext *SpecializedContext
6916 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
6917 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
6918
6919 // Make sure that this redeclaration (or definition) occurs in an enclosing
6920 // namespace.
6921 // Note that HandleDeclarator() performs this check for explicit
6922 // specializations of function templates, static data members, and member
6923 // functions, so we skip the check here for those kinds of entities.
6924 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6925 // Should we refactor that check, so that it occurs later?
6926 if (!DC->Encloses(SpecializedContext) &&
6927 !(isa<FunctionTemplateDecl>(Specialized) ||
6928 isa<FunctionDecl>(Specialized) ||
6929 isa<VarTemplateDecl>(Specialized) ||
6930 isa<VarDecl>(Specialized))) {
6931 if (isa<TranslationUnitDecl>(SpecializedContext))
6932 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6933 << EntityKind << Specialized;
6934 else if (isa<NamespaceDecl>(SpecializedContext)) {
6935 int Diag = diag::err_template_spec_redecl_out_of_scope;
6936 if (S.getLangOpts().MicrosoftExt)
6937 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6938 S.Diag(Loc, Diag) << EntityKind << Specialized
6939 << cast<NamedDecl>(SpecializedContext);
6940 } else
6941 llvm_unreachable("unexpected namespace context for specialization")::llvm::llvm_unreachable_internal("unexpected namespace context for specialization"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6941)
;
6942
6943 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6944 } else if ((!PrevDecl ||
6945 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6946 getTemplateSpecializationKind(PrevDecl) ==
6947 TSK_ImplicitInstantiation)) {
6948 // C++ [temp.exp.spec]p2:
6949 // An explicit specialization shall be declared in the namespace of which
6950 // the template is a member, or, for member templates, in the namespace
6951 // of which the enclosing class or enclosing class template is a member.
6952 // An explicit specialization of a member function, member class or
6953 // static data member of a class template shall be declared in the
6954 // namespace of which the class template is a member.
6955 //
6956 // C++11 [temp.expl.spec]p2:
6957 // An explicit specialization shall be declared in a namespace enclosing
6958 // the specialized template.
6959 // C++11 [temp.explicit]p3:
6960 // An explicit instantiation shall appear in an enclosing namespace of its
6961 // template.
6962 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
6963 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
6964 if (isa<TranslationUnitDecl>(SpecializedContext)) {
6965 assert(!IsCPlusPlus11Extension &&((!IsCPlusPlus11Extension && "DC encloses TU but isn't in enclosing namespace set"
) ? static_cast<void> (0) : __assert_fail ("!IsCPlusPlus11Extension && \"DC encloses TU but isn't in enclosing namespace set\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6966, __PRETTY_FUNCTION__))
6966 "DC encloses TU but isn't in enclosing namespace set")((!IsCPlusPlus11Extension && "DC encloses TU but isn't in enclosing namespace set"
) ? static_cast<void> (0) : __assert_fail ("!IsCPlusPlus11Extension && \"DC encloses TU but isn't in enclosing namespace set\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6966, __PRETTY_FUNCTION__))
;
6967 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
6968 << EntityKind << Specialized;
6969 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6970 int Diag;
6971 if (!IsCPlusPlus11Extension)
6972 Diag = diag::err_template_spec_decl_out_of_scope;
6973 else if (!S.getLangOpts().CPlusPlus11)
6974 Diag = diag::ext_template_spec_decl_out_of_scope;
6975 else
6976 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6977 S.Diag(Loc, Diag)
6978 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6979 }
6980
6981 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6982 }
6983 }
6984
6985 return false;
6986}
6987
6988static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6989 if (!E->isTypeDependent())
6990 return SourceLocation();
6991 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
6992 Checker.TraverseStmt(E);
6993 if (Checker.MatchLoc.isInvalid())
6994 return E->getSourceRange();
6995 return Checker.MatchLoc;
6996}
6997
6998static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6999 if (!TL.getType()->isDependentType())
7000 return SourceLocation();
7001 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7002 Checker.TraverseTypeLoc(TL);
7003 if (Checker.MatchLoc.isInvalid())
7004 return TL.getSourceRange();
7005 return Checker.MatchLoc;
7006}
7007
7008/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7009/// that checks non-type template partial specialization arguments.
7010static bool CheckNonTypeTemplatePartialSpecializationArgs(
7011 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7012 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7013 for (unsigned I = 0; I != NumArgs; ++I) {
7014 if (Args[I].getKind() == TemplateArgument::Pack) {
7015 if (CheckNonTypeTemplatePartialSpecializationArgs(
7016 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7017 Args[I].pack_size(), IsDefaultArgument))
7018 return true;
7019
7020 continue;
7021 }
7022
7023 if (Args[I].getKind() != TemplateArgument::Expression)
7024 continue;
7025
7026 Expr *ArgExpr = Args[I].getAsExpr();
7027
7028 // We can have a pack expansion of any of the bullets below.
7029 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7030 ArgExpr = Expansion->getPattern();
7031
7032 // Strip off any implicit casts we added as part of type checking.
7033 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7034 ArgExpr = ICE->getSubExpr();
7035
7036 // C++ [temp.class.spec]p8:
7037 // A non-type argument is non-specialized if it is the name of a
7038 // non-type parameter. All other non-type arguments are
7039 // specialized.
7040 //
7041 // Below, we check the two conditions that only apply to
7042 // specialized non-type arguments, so skip any non-specialized
7043 // arguments.
7044 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7045 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7046 continue;
7047
7048 // C++ [temp.class.spec]p9:
7049 // Within the argument list of a class template partial
7050 // specialization, the following restrictions apply:
7051 // -- A partially specialized non-type argument expression
7052 // shall not involve a template parameter of the partial
7053 // specialization except when the argument expression is a
7054 // simple identifier.
7055 // -- The type of a template parameter corresponding to a
7056 // specialized non-type argument shall not be dependent on a
7057 // parameter of the specialization.
7058 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7059 // We implement a compromise between the original rules and DR1315:
7060 // -- A specialized non-type template argument shall not be
7061 // type-dependent and the corresponding template parameter
7062 // shall have a non-dependent type.
7063 SourceRange ParamUseRange =
7064 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7065 if (ParamUseRange.isValid()) {
7066 if (IsDefaultArgument) {
7067 S.Diag(TemplateNameLoc,
7068 diag::err_dependent_non_type_arg_in_partial_spec);
7069 S.Diag(ParamUseRange.getBegin(),
7070 diag::note_dependent_non_type_default_arg_in_partial_spec)
7071 << ParamUseRange;
7072 } else {
7073 S.Diag(ParamUseRange.getBegin(),
7074 diag::err_dependent_non_type_arg_in_partial_spec)
7075 << ParamUseRange;
7076 }
7077 return true;
7078 }
7079
7080 ParamUseRange = findTemplateParameter(
7081 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7082 if (ParamUseRange.isValid()) {
7083 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7084 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7085 << Param->getType();
7086 S.Diag(Param->getLocation(), diag::note_template_param_here)
7087 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7088 << ParamUseRange;
7089 return true;
7090 }
7091 }
7092
7093 return false;
7094}
7095
7096/// \brief Check the non-type template arguments of a class template
7097/// partial specialization according to C++ [temp.class.spec]p9.
7098///
7099/// \param TemplateNameLoc the location of the template name.
7100/// \param PrimaryTemplate the template parameters of the primary class
7101/// template.
7102/// \param NumExplicit the number of explicitly-specified template arguments.
7103/// \param TemplateArgs the template arguments of the class template
7104/// partial specialization.
7105///
7106/// \returns \c true if there was an error, \c false otherwise.
7107bool Sema::CheckTemplatePartialSpecializationArgs(
7108 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7109 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7110 // We have to be conservative when checking a template in a dependent
7111 // context.
7112 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7113 return false;
7114
7115 TemplateParameterList *TemplateParams =
7116 PrimaryTemplate->getTemplateParameters();
7117 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7118 NonTypeTemplateParmDecl *Param
7119 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7120 if (!Param)
7121 continue;
7122
7123 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7124 Param, &TemplateArgs[I],
7125 1, I >= NumExplicit))
7126 return true;
7127 }
7128
7129 return false;
7130}
7131
7132DeclResult
7133Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7134 TagUseKind TUK,
7135 SourceLocation KWLoc,
7136 SourceLocation ModulePrivateLoc,
7137 TemplateIdAnnotation &TemplateId,
7138 AttributeList *Attr,
7139 MultiTemplateParamsArg
7140 TemplateParameterLists,
7141 SkipBodyInfo *SkipBody) {
7142 assert(TUK != TUK_Reference && "References are not specializations")((TUK != TUK_Reference && "References are not specializations"
) ? static_cast<void> (0) : __assert_fail ("TUK != TUK_Reference && \"References are not specializations\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7142, __PRETTY_FUNCTION__))
;
7143
7144 CXXScopeSpec &SS = TemplateId.SS;
7145
7146 // NOTE: KWLoc is the location of the tag keyword. This will instead
7147 // store the location of the outermost template keyword in the declaration.
7148 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7149 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7150 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7151 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7152 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7153
7154 // Find the class template we're specializing
7155 TemplateName Name = TemplateId.Template.get();
7156 ClassTemplateDecl *ClassTemplate
7157 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7158
7159 if (!ClassTemplate) {
7160 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7161 << (Name.getAsTemplateDecl() &&
7162 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7163 return true;
7164 }
7165
7166 bool isMemberSpecialization = false;
7167 bool isPartialSpecialization = false;
7168
7169 // Check the validity of the template headers that introduce this
7170 // template.
7171 // FIXME: We probably shouldn't complain about these headers for
7172 // friend declarations.
7173 bool Invalid = false;
7174 TemplateParameterList *TemplateParams =
7175 MatchTemplateParametersToScopeSpecifier(
7176 KWLoc, TemplateNameLoc, SS, &TemplateId,
7177 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7178 Invalid);
7179 if (Invalid)
7180 return true;
7181
7182 if (TemplateParams && TemplateParams->size() > 0) {
7183 isPartialSpecialization = true;
7184
7185 if (TUK == TUK_Friend) {
7186 Diag(KWLoc, diag::err_partial_specialization_friend)
7187 << SourceRange(LAngleLoc, RAngleLoc);
7188 return true;
7189 }
7190
7191 // C++ [temp.class.spec]p10:
7192 // The template parameter list of a specialization shall not
7193 // contain default template argument values.
7194 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7195 Decl *Param = TemplateParams->getParam(I);
7196 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7197 if (TTP->hasDefaultArgument()) {
7198 Diag(TTP->getDefaultArgumentLoc(),
7199 diag::err_default_arg_in_partial_spec);
7200 TTP->removeDefaultArgument();
7201 }
7202 } else if (NonTypeTemplateParmDecl *NTTP
7203 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7204 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7205 Diag(NTTP->getDefaultArgumentLoc(),
7206 diag::err_default_arg_in_partial_spec)
7207 << DefArg->getSourceRange();
7208 NTTP->removeDefaultArgument();
7209 }
7210 } else {
7211 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7212 if (TTP->hasDefaultArgument()) {
7213 Diag(TTP->getDefaultArgument().getLocation(),
7214 diag::err_default_arg_in_partial_spec)
7215 << TTP->getDefaultArgument().getSourceRange();
7216 TTP->removeDefaultArgument();
7217 }
7218 }
7219 }
7220 } else if (TemplateParams) {
7221 if (TUK == TUK_Friend)
7222 Diag(KWLoc, diag::err_template_spec_friend)
7223 << FixItHint::CreateRemoval(
7224 SourceRange(TemplateParams->getTemplateLoc(),
7225 TemplateParams->getRAngleLoc()))
7226 << SourceRange(LAngleLoc, RAngleLoc);
7227 } else {
7228 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl")((TUK == TUK_Friend && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend && \"should have a 'template<>' for this decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7228, __PRETTY_FUNCTION__))
;
7229 }
7230
7231 // Check that the specialization uses the same tag kind as the
7232 // original template.
7233 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7234 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!")((Kind != TTK_Enum && "Invalid enum tag in class template spec!"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template spec!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7234, __PRETTY_FUNCTION__))
;
7235 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7236 Kind, TUK == TUK_Definition, KWLoc,
7237 ClassTemplate->getIdentifier())) {
7238 Diag(KWLoc, diag::err_use_with_wrong_tag)
7239 << ClassTemplate
7240 << FixItHint::CreateReplacement(KWLoc,
7241 ClassTemplate->getTemplatedDecl()->getKindName());
7242 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7243 diag::note_previous_use);
7244 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7245 }
7246
7247 // Translate the parser's template argument list in our AST format.
7248 TemplateArgumentListInfo TemplateArgs =
7249 makeTemplateArgumentListInfo(*this, TemplateId);
7250
7251 // Check for unexpanded parameter packs in any of the template arguments.
7252 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7253 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7254 UPPC_PartialSpecialization))
7255 return true;
7256
7257 // Check that the template argument list is well-formed for this
7258 // template.
7259 SmallVector<TemplateArgument, 4> Converted;
7260 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7261 TemplateArgs, false, Converted))
7262 return true;
7263
7264 // Find the class template (partial) specialization declaration that
7265 // corresponds to these arguments.
7266 if (isPartialSpecialization) {
7267 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7268 TemplateArgs.size(), Converted))
7269 return true;
7270
7271 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7272 // also do it during instantiation.
7273 bool InstantiationDependent;
7274 if (!Name.isDependent() &&
7275 !TemplateSpecializationType::anyDependentTemplateArguments(
7276 TemplateArgs.arguments(), InstantiationDependent)) {
7277 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7278 << ClassTemplate->getDeclName();
7279 isPartialSpecialization = false;
7280 }
7281 }
7282
7283 void *InsertPos = nullptr;
7284 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7285
7286 if (isPartialSpecialization)
7287 // FIXME: Template parameter list matters, too
7288 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7289 else
7290 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7291
7292 ClassTemplateSpecializationDecl *Specialization = nullptr;
7293
7294 // Check whether we can declare a class template specialization in
7295 // the current scope.
7296 if (TUK != TUK_Friend &&
7297 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7298 TemplateNameLoc,
7299 isPartialSpecialization))
7300 return true;
7301
7302 // The canonical type
7303 QualType CanonType;
7304 if (isPartialSpecialization) {
7305 // Build the canonical type that describes the converted template
7306 // arguments of the class template partial specialization.
7307 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7308 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7309 Converted);
7310
7311 if (Context.hasSameType(CanonType,
7312 ClassTemplate->getInjectedClassNameSpecialization())) {
7313 // C++ [temp.class.spec]p9b3:
7314 //
7315 // -- The argument list of the specialization shall not be identical
7316 // to the implicit argument list of the primary template.
7317 //
7318 // This rule has since been removed, because it's redundant given DR1495,
7319 // but we keep it because it produces better diagnostics and recovery.
7320 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7321 << /*class template*/0 << (TUK == TUK_Definition)
7322 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7323 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7324 ClassTemplate->getIdentifier(),
7325 TemplateNameLoc,
7326 Attr,
7327 TemplateParams,
7328 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7329 /*FriendLoc*/SourceLocation(),
7330 TemplateParameterLists.size() - 1,
7331 TemplateParameterLists.data());
7332 }
7333
7334 // Create a new class template partial specialization declaration node.
7335 ClassTemplatePartialSpecializationDecl *PrevPartial
7336 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7337 ClassTemplatePartialSpecializationDecl *Partial
7338 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7339 ClassTemplate->getDeclContext(),
7340 KWLoc, TemplateNameLoc,
7341 TemplateParams,
7342 ClassTemplate,
7343 Converted,
7344 TemplateArgs,
7345 CanonType,
7346 PrevPartial);
7347 SetNestedNameSpecifier(Partial, SS);
7348 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7349 Partial->setTemplateParameterListsInfo(
7350 Context, TemplateParameterLists.drop_back(1));
7351 }
7352
7353 if (!PrevPartial)
7354 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7355 Specialization = Partial;
7356
7357 // If we are providing an explicit specialization of a member class
7358 // template specialization, make a note of that.
7359 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7360 PrevPartial->setMemberSpecialization();
7361
7362 CheckTemplatePartialSpecialization(Partial);
7363 } else {
7364 // Create a new class template specialization declaration node for
7365 // this explicit specialization or friend declaration.
7366 Specialization
7367 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7368 ClassTemplate->getDeclContext(),
7369 KWLoc, TemplateNameLoc,
7370 ClassTemplate,
7371 Converted,
7372 PrevDecl);
7373 SetNestedNameSpecifier(Specialization, SS);
7374 if (TemplateParameterLists.size() > 0) {
7375 Specialization->setTemplateParameterListsInfo(Context,
7376 TemplateParameterLists);
7377 }
7378
7379 if (!PrevDecl)
7380 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7381
7382 if (CurContext->isDependentContext()) {
7383 // -fms-extensions permits specialization of nested classes without
7384 // fully specializing the outer class(es).
7385 assert(getLangOpts().MicrosoftExt &&((getLangOpts().MicrosoftExt && "Only possible with -fms-extensions!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MicrosoftExt && \"Only possible with -fms-extensions!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7386, __PRETTY_FUNCTION__))
7386 "Only possible with -fms-extensions!")((getLangOpts().MicrosoftExt && "Only possible with -fms-extensions!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MicrosoftExt && \"Only possible with -fms-extensions!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7386, __PRETTY_FUNCTION__))
;
7387 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7388 CanonType = Context.getTemplateSpecializationType(
7389 CanonTemplate, Converted);
7390 } else {
7391 CanonType = Context.getTypeDeclType(Specialization);
7392 }
7393 }
7394
7395 // C++ [temp.expl.spec]p6:
7396 // If a template, a member template or the member of a class template is
7397 // explicitly specialized then that specialization shall be declared
7398 // before the first use of that specialization that would cause an implicit
7399 // instantiation to take place, in every translation unit in which such a
7400 // use occurs; no diagnostic is required.
7401 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7402 bool Okay = false;
7403 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7404 // Is there any previous explicit specialization declaration?
7405 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7406 Okay = true;
7407 break;
7408 }
7409 }
7410
7411 if (!Okay) {
7412 SourceRange Range(TemplateNameLoc, RAngleLoc);
7413 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7414 << Context.getTypeDeclType(Specialization) << Range;
7415
7416 Diag(PrevDecl->getPointOfInstantiation(),
7417 diag::note_instantiation_required_here)
7418 << (PrevDecl->getTemplateSpecializationKind()
7419 != TSK_ImplicitInstantiation);
7420 return true;
7421 }
7422 }
7423
7424 // If this is not a friend, note that this is an explicit specialization.
7425 if (TUK != TUK_Friend)
7426 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7427
7428 // Check that this isn't a redefinition of this specialization.
7429 if (TUK == TUK_Definition) {
7430 RecordDecl *Def = Specialization->getDefinition();
7431 NamedDecl *Hidden = nullptr;
7432 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7433 SkipBody->ShouldSkip = true;
7434 makeMergedDefinitionVisible(Hidden);
7435 // From here on out, treat this as just a redeclaration.
7436 TUK = TUK_Declaration;
7437 } else if (Def) {
7438 SourceRange Range(TemplateNameLoc, RAngleLoc);
7439 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7440 Diag(Def->getLocation(), diag::note_previous_definition);
7441 Specialization->setInvalidDecl();
7442 return true;
7443 }
7444 }
7445
7446 if (Attr)
7447 ProcessDeclAttributeList(S, Specialization, Attr);
7448
7449 // Add alignment attributes if necessary; these attributes are checked when
7450 // the ASTContext lays out the structure.
7451 if (TUK == TUK_Definition) {
7452 AddAlignmentAttributesForRecord(Specialization);
7453 AddMsStructLayoutForRecord(Specialization);
7454 }
7455
7456 if (ModulePrivateLoc.isValid())
7457 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7458 << (isPartialSpecialization? 1 : 0)
7459 << FixItHint::CreateRemoval(ModulePrivateLoc);
7460
7461 // Build the fully-sugared type for this class template
7462 // specialization as the user wrote in the specialization
7463 // itself. This means that we'll pretty-print the type retrieved
7464 // from the specialization's declaration the way that the user
7465 // actually wrote the specialization, rather than formatting the
7466 // name based on the "canonical" representation used to store the
7467 // template arguments in the specialization.
7468 TypeSourceInfo *WrittenTy
7469 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7470 TemplateArgs, CanonType);
7471 if (TUK != TUK_Friend) {
7472 Specialization->setTypeAsWritten(WrittenTy);
7473 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7474 }
7475
7476 // C++ [temp.expl.spec]p9:
7477 // A template explicit specialization is in the scope of the
7478 // namespace in which the template was defined.
7479 //
7480 // We actually implement this paragraph where we set the semantic
7481 // context (in the creation of the ClassTemplateSpecializationDecl),
7482 // but we also maintain the lexical context where the actual
7483 // definition occurs.
7484 Specialization->setLexicalDeclContext(CurContext);
7485
7486 // We may be starting the definition of this specialization.
7487 if (TUK == TUK_Definition)
7488 Specialization->startDefinition();
7489
7490 if (TUK == TUK_Friend) {
7491 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7492 TemplateNameLoc,
7493 WrittenTy,
7494 /*FIXME:*/KWLoc);
7495 Friend->setAccess(AS_public);
7496 CurContext->addDecl(Friend);
7497 } else {
7498 // Add the specialization into its lexical context, so that it can
7499 // be seen when iterating through the list of declarations in that
7500 // context. However, specializations are not found by name lookup.
7501 CurContext->addDecl(Specialization);
7502 }
7503 return Specialization;
7504}
7505
7506Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7507 MultiTemplateParamsArg TemplateParameterLists,
7508 Declarator &D) {
7509 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7510 ActOnDocumentableDecl(NewDecl);
7511 return NewDecl;
7512}
7513
7514/// \brief Strips various properties off an implicit instantiation
7515/// that has just been explicitly specialized.
7516static void StripImplicitInstantiation(NamedDecl *D) {
7517 D->dropAttr<DLLImportAttr>();
7518 D->dropAttr<DLLExportAttr>();
7519
7520 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7521 FD->setInlineSpecified(false);
7522}
7523
7524/// \brief Compute the diagnostic location for an explicit instantiation
7525// declaration or definition.
7526static SourceLocation DiagLocForExplicitInstantiation(
7527 NamedDecl* D, SourceLocation PointOfInstantiation) {
7528 // Explicit instantiations following a specialization have no effect and
7529 // hence no PointOfInstantiation. In that case, walk decl backwards
7530 // until a valid name loc is found.
7531 SourceLocation PrevDiagLoc = PointOfInstantiation;
7532 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7533 Prev = Prev->getPreviousDecl()) {
7534 PrevDiagLoc = Prev->getLocation();
7535 }
7536 assert(PrevDiagLoc.isValid() &&((PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7537, __PRETTY_FUNCTION__))
7537 "Explicit instantiation without point of instantiation?")((PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7537, __PRETTY_FUNCTION__))
;
7538 return PrevDiagLoc;
7539}
7540
7541/// \brief Diagnose cases where we have an explicit template specialization
7542/// before/after an explicit template instantiation, producing diagnostics
7543/// for those cases where they are required and determining whether the
7544/// new specialization/instantiation will have any effect.
7545///
7546/// \param NewLoc the location of the new explicit specialization or
7547/// instantiation.
7548///
7549/// \param NewTSK the kind of the new explicit specialization or instantiation.
7550///
7551/// \param PrevDecl the previous declaration of the entity.
7552///
7553/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7554///
7555/// \param PrevPointOfInstantiation if valid, indicates where the previus
7556/// declaration was instantiated (either implicitly or explicitly).
7557///
7558/// \param HasNoEffect will be set to true to indicate that the new
7559/// specialization or instantiation has no effect and should be ignored.
7560///
7561/// \returns true if there was an error that should prevent the introduction of
7562/// the new declaration into the AST, false otherwise.
7563bool
7564Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7565 TemplateSpecializationKind NewTSK,
7566 NamedDecl *PrevDecl,
7567 TemplateSpecializationKind PrevTSK,
7568 SourceLocation PrevPointOfInstantiation,
7569 bool &HasNoEffect) {
7570 HasNoEffect = false;
7571
7572 switch (NewTSK) {
7573 case TSK_Undeclared:
7574 case TSK_ImplicitInstantiation:
7575 assert((((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7577, __PRETTY_FUNCTION__))
7576 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&(((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7577, __PRETTY_FUNCTION__))
7577 "previous declaration must be implicit!")(((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7577, __PRETTY_FUNCTION__))
;
7578 return false;
7579
7580 case TSK_ExplicitSpecialization:
7581 switch (PrevTSK) {
7582 case TSK_Undeclared:
7583 case TSK_ExplicitSpecialization:
7584 // Okay, we're just specializing something that is either already
7585 // explicitly specialized or has merely been mentioned without any
7586 // instantiation.
7587 return false;
7588
7589 case TSK_ImplicitInstantiation:
7590 if (PrevPointOfInstantiation.isInvalid()) {
7591 // The declaration itself has not actually been instantiated, so it is
7592 // still okay to specialize it.
7593 StripImplicitInstantiation(PrevDecl);
7594 return false;
7595 }
7596 // Fall through
7597
7598 case TSK_ExplicitInstantiationDeclaration:
7599 case TSK_ExplicitInstantiationDefinition:
7600 assert((PrevTSK == TSK_ImplicitInstantiation ||(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7602, __PRETTY_FUNCTION__))
7601 PrevPointOfInstantiation.isValid()) &&(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7602, __PRETTY_FUNCTION__))
7602 "Explicit instantiation without point of instantiation?")(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7602, __PRETTY_FUNCTION__))
;
7603
7604 // C++ [temp.expl.spec]p6:
7605 // If a template, a member template or the member of a class template
7606 // is explicitly specialized then that specialization shall be declared
7607 // before the first use of that specialization that would cause an
7608 // implicit instantiation to take place, in every translation unit in
7609 // which such a use occurs; no diagnostic is required.
7610 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7611 // Is there any previous explicit specialization declaration?
7612 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7613 return false;
7614 }
7615
7616 Diag(NewLoc, diag::err_specialization_after_instantiation)
7617 << PrevDecl;
7618 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7619 << (PrevTSK != TSK_ImplicitInstantiation);
7620
7621 return true;
7622 }
7623
7624 case TSK_ExplicitInstantiationDeclaration:
7625 switch (PrevTSK) {
7626 case TSK_ExplicitInstantiationDeclaration:
7627 // This explicit instantiation declaration is redundant (that's okay).
7628 HasNoEffect = true;
7629 return false;
7630
7631 case TSK_Undeclared:
7632 case TSK_ImplicitInstantiation:
7633 // We're explicitly instantiating something that may have already been
7634 // implicitly instantiated; that's fine.
7635 return false;
7636
7637 case TSK_ExplicitSpecialization:
7638 // C++0x [temp.explicit]p4:
7639 // For a given set of template parameters, if an explicit instantiation
7640 // of a template appears after a declaration of an explicit
7641 // specialization for that template, the explicit instantiation has no
7642 // effect.
7643 HasNoEffect = true;
7644 return false;
7645
7646 case TSK_ExplicitInstantiationDefinition:
7647 // C++0x [temp.explicit]p10:
7648 // If an entity is the subject of both an explicit instantiation
7649 // declaration and an explicit instantiation definition in the same
7650 // translation unit, the definition shall follow the declaration.
7651 Diag(NewLoc,
7652 diag::err_explicit_instantiation_declaration_after_definition);
7653
7654 // Explicit instantiations following a specialization have no effect and
7655 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7656 // until a valid name loc is found.
7657 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7658 diag::note_explicit_instantiation_definition_here);
7659 HasNoEffect = true;
7660 return false;
7661 }
7662
7663 case TSK_ExplicitInstantiationDefinition:
7664 switch (PrevTSK) {
7665 case TSK_Undeclared:
7666 case TSK_ImplicitInstantiation:
7667 // We're explicitly instantiating something that may have already been
7668 // implicitly instantiated; that's fine.
7669 return false;
7670
7671 case TSK_ExplicitSpecialization:
7672 // C++ DR 259, C++0x [temp.explicit]p4:
7673 // For a given set of template parameters, if an explicit
7674 // instantiation of a template appears after a declaration of
7675 // an explicit specialization for that template, the explicit
7676 // instantiation has no effect.
7677 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7678 << PrevDecl;
7679 Diag(PrevDecl->getLocation(),
7680 diag::note_previous_template_specialization);
7681 HasNoEffect = true;
7682 return false;
7683
7684 case TSK_ExplicitInstantiationDeclaration:
7685 // We're explicity instantiating a definition for something for which we
7686 // were previously asked to suppress instantiations. That's fine.
7687
7688 // C++0x [temp.explicit]p4:
7689 // For a given set of template parameters, if an explicit instantiation
7690 // of a template appears after a declaration of an explicit
7691 // specialization for that template, the explicit instantiation has no
7692 // effect.
7693 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7694 // Is there any previous explicit specialization declaration?
7695 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7696 HasNoEffect = true;
7697 break;
7698 }
7699 }
7700
7701 return false;
7702
7703 case TSK_ExplicitInstantiationDefinition:
7704 // C++0x [temp.spec]p5:
7705 // For a given template and a given set of template-arguments,
7706 // - an explicit instantiation definition shall appear at most once
7707 // in a program,
7708
7709 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7710 Diag(NewLoc, (getLangOpts().MSVCCompat)
7711 ? diag::ext_explicit_instantiation_duplicate
7712 : diag::err_explicit_instantiation_duplicate)
7713 << PrevDecl;
7714 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7715 diag::note_previous_explicit_instantiation);
7716 HasNoEffect = true;
7717 return false;
7718 }
7719 }
7720
7721 llvm_unreachable("Missing specialization/instantiation case?")::llvm::llvm_unreachable_internal("Missing specialization/instantiation case?"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn303373/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7721)
;
7722}
7723
7724/// \brief Perform semantic analysis for the given dependent function
7725/// template specialization.
7726///
7727/// The only possible way to get a dependent function template specialization
7728/// is with a friend declaration, like so:
7729///
7730/// \code
7731/// template \<class T> void foo(T);
7732/// template \<class T> class A {
7733/// friend void foo<>(T);
7734/// };
7735/// \endcode
7736///
7737/// There really isn't any useful analysis we can do here, so we
7738/// just store the information.
7739bool
7740Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7741 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7742 LookupResult &Previous) {
7743 // Remove anything from Previous that isn't a function template in
7744 // the correct context.
7745 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7746 LookupResult::Filter F = Previous.makeFilter();
7747 while (F.hasNext()) {
7748 NamedDecl *D = F.next()->getUnderlyingDecl();
7749 if (!isa<FunctionTemplateDecl>(D) ||
7750 !FDLookupContext->InEnclosingNamespaceSetOf(
7751 D->getDeclContext()->getRedeclContext()))
7752 F.erase();
7753 }
7754 F.done();
7755
7756 // Should this be diagnosed here?
7757 if (Previous.empty()) return true;
7758
7759 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7760 ExplicitTemplateArgs);
7761 return false;
7762}
7763
7764/// \brief Perform semantic analysis for the given function template
7765/// specialization.
7766///
7767/// This routine performs all of the semantic analysis