Bug Summary

File:tools/clang/lib/Sema/SemaTemplate.cpp
Warning:line 2665, column 31
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp

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.")(static_cast <bool> (!FD && "Cannot collect constraints from function declaration yet."
) ? void (0) : __assert_fail ("!FD && \"Cannot collect constraints from function declaration yet.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 64, __extension__ __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!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No template names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 166, __extension__ __PRETTY_FUNCTION__))
;
167
168 DeclarationName TName;
169 MemberOfUnknownSpecialization = false;
170
171 switch (Name.getKind()) {
172 case UnqualifiedIdKind::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
174 break;
175
176 case UnqualifiedIdKind::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
179 break;
180
181 case UnqualifiedIdKind::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) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __extension__ __PRETTY_FUNCTION__))
234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __extension__ __PRETTY_FUNCTION__))
235 isa<BuiltinTemplateDecl>(TD))(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD)) ? void (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 235, __extension__ __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")(static_cast <bool> (!SS.isSet() && "ObjectType and scope specifier cannot coexist"
) ? void (0) : __assert_fail ("!SS.isSet() && \"ObjectType and scope specifier cannot coexist\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 313, __extension__ __PRETTY_FUNCTION__))
;
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
316 assert((isDependent || !ObjectType->isIncompleteType() ||(static_cast <bool> ((isDependent || !ObjectType->isIncompleteType
() || ObjectType->castAs<TagType>()->isBeingDefined
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&(static_cast <bool> ((isDependent || !ObjectType->isIncompleteType
() || ObjectType->castAs<TagType>()->isBeingDefined
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
318 "Caller should have completed object type")(static_cast <bool> ((isDependent || !ObjectType->isIncompleteType
() || ObjectType->castAs<TagType>()->isBeingDefined
()) && "Caller should have completed object type") ? void
(0) : __assert_fail ("(isDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 318, __extension__ __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) ||(static_cast <bool> (isa<TagDecl>(Instantiation) ||
isa<FunctionDecl>(Instantiation) || isa<VarDecl>
(Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 605, __extension__ __PRETTY_FUNCTION__))
605 isa<VarDecl>(Instantiation))(static_cast <bool> (isa<TagDecl>(Instantiation) ||
isa<FunctionDecl>(Instantiation) || isa<VarDecl>
(Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 605, __extension__ __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!")(static_cast <bool> (isa<TagDecl>(Instantiation) &&
"Must be a TagDecl!") ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 648, __extension__ __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!")(static_cast <bool> (isa<VarDecl>(Instantiation) &&
"Must be a VarDecl!") ? void (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 666, __extension__ __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")(static_cast <bool> (PrevDecl->isTemplateParameter()
&& "Not a template parameter") ? void (0) : __assert_fail
("PrevDecl->isTemplateParameter() && \"Not a template parameter\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 697, __extension__ __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 &&(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here"
) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 725, __extension__ __PRETTY_FUNCTION__))
725 "Only template template arguments can be pack expansions here")(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here"
) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 725, __extension__ __PRETTY_FUNCTION__))
;
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack
() && "Template template argument pack expansion without packs"
) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 727, __extension__ __PRETTY_FUNCTION__))
727 "Template template argument pack expansion without packs")(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack
() && "Template template argument pack expansion without packs"
) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 727, __extension__ __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"
, "/build/llvm-toolchain-snapshot-7~svn326551/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::ForVisibleRedeclaration);
782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
784}
785
786/// Convert a parsed type into a parsed template argument. This is mostly
787/// trivial, except that we may have parsed a C++17 deduced class template
788/// specialization type, in which case we should form a template template
789/// argument instead of a type template argument.
790ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
791 TypeSourceInfo *TInfo;
792 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
793 if (T.isNull())
794 return ParsedTemplateArgument();
795 assert(TInfo && "template argument with no location")(static_cast <bool> (TInfo && "template argument with no location"
) ? void (0) : __assert_fail ("TInfo && \"template argument with no location\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 795, __extension__ __PRETTY_FUNCTION__))
;
796
797 // If we might have formed a deduced template specialization type, convert
798 // it to a template template argument.
799 if (getLangOpts().CPlusPlus17) {
800 TypeLoc TL = TInfo->getTypeLoc();
801 SourceLocation EllipsisLoc;
802 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
803 EllipsisLoc = PET.getEllipsisLoc();
804 TL = PET.getPatternLoc();
805 }
806
807 CXXScopeSpec SS;
808 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
809 SS.Adopt(ET.getQualifierLoc());
810 TL = ET.getNamedTypeLoc();
811 }
812
813 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
814 TemplateName Name = DTST.getTypePtr()->getTemplateName();
815 if (SS.isSet())
816 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
817 /*HasTemplateKeyword*/ false,
818 Name.getAsTemplateDecl());
819 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
820 DTST.getTemplateNameLoc());
821 if (EllipsisLoc.isValid())
822 Result = Result.getTemplatePackExpansion(EllipsisLoc);
823 return Result;
824 }
825 }
826
827 // This is a normal type template argument. Note, if the type template
828 // argument is an injected-class-name for a template, it has a dual nature
829 // and can be used as either a type or a template. We handle that in
830 // convertTypeTemplateArgumentToTemplate.
831 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
832 ParsedType.get().getAsOpaquePtr(),
833 TInfo->getTypeLoc().getLocStart());
834}
835
836/// ActOnTypeParameter - Called when a C++ template type parameter
837/// (e.g., "typename T") has been parsed. Typename specifies whether
838/// the keyword "typename" was used to declare the type parameter
839/// (otherwise, "class" was used), and KeyLoc is the location of the
840/// "class" or "typename" keyword. ParamName is the name of the
841/// parameter (NULL indicates an unnamed template parameter) and
842/// ParamNameLoc is the location of the parameter name (if any).
843/// If the type parameter has a default argument, it will be added
844/// later via ActOnTypeParameterDefault.
845NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
846 SourceLocation EllipsisLoc,
847 SourceLocation KeyLoc,
848 IdentifierInfo *ParamName,
849 SourceLocation ParamNameLoc,
850 unsigned Depth, unsigned Position,
851 SourceLocation EqualLoc,
852 ParsedType DefaultArg) {
853 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Template type parameter not in template parameter scope!") ?
void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 854, __extension__ __PRETTY_FUNCTION__))
854 "Template type parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Template type parameter not in template parameter scope!") ?
void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 854, __extension__ __PRETTY_FUNCTION__))
;
855
856 SourceLocation Loc = ParamNameLoc;
857 if (!ParamName)
858 Loc = KeyLoc;
859
860 bool IsParameterPack = EllipsisLoc.isValid();
861 TemplateTypeParmDecl *Param
862 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
863 KeyLoc, Loc, Depth, Position, ParamName,
864 Typename, IsParameterPack);
865 Param->setAccess(AS_public);
866
867 if (ParamName) {
868 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
869
870 // Add the template parameter into the current scope.
871 S->AddDecl(Param);
872 IdResolver.AddDecl(Param);
873 }
874
875 // C++0x [temp.param]p9:
876 // A default template-argument may be specified for any kind of
877 // template-parameter that is not a template parameter pack.
878 if (DefaultArg && IsParameterPack) {
879 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
880 DefaultArg = nullptr;
881 }
882
883 // Handle the default argument, if provided.
884 if (DefaultArg) {
885 TypeSourceInfo *DefaultTInfo;
886 GetTypeFromParser(DefaultArg, &DefaultTInfo);
887
888 assert(DefaultTInfo && "expected source information for type")(static_cast <bool> (DefaultTInfo && "expected source information for type"
) ? void (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 888, __extension__ __PRETTY_FUNCTION__))
;
889
890 // Check for unexpanded parameter packs.
891 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
892 UPPC_DefaultArgument))
893 return Param;
894
895 // Check the template argument itself.
896 if (CheckTemplateArgument(Param, DefaultTInfo)) {
897 Param->setInvalidDecl();
898 return Param;
899 }
900
901 Param->setDefaultArgument(DefaultTInfo);
902 }
903
904 return Param;
905}
906
907/// \brief Check that the type of a non-type template parameter is
908/// well-formed.
909///
910/// \returns the (possibly-promoted) parameter type if valid;
911/// otherwise, produces a diagnostic and returns a NULL type.
912QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
913 SourceLocation Loc) {
914 if (TSI->getType()->isUndeducedType()) {
915 // C++1z [temp.dep.expr]p3:
916 // An id-expression is type-dependent if it contains
917 // - an identifier associated by name lookup with a non-type
918 // template-parameter declared with a type that contains a
919 // placeholder type (7.1.7.4),
920 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
921 }
922
923 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
924}
925
926QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
927 SourceLocation Loc) {
928 // We don't allow variably-modified types as the type of non-type template
929 // parameters.
930 if (T->isVariablyModifiedType()) {
931 Diag(Loc, diag::err_variably_modified_nontype_template_param)
932 << T;
933 return QualType();
934 }
935
936 // C++ [temp.param]p4:
937 //
938 // A non-type template-parameter shall have one of the following
939 // (optionally cv-qualified) types:
940 //
941 // -- integral or enumeration type,
942 if (T->isIntegralOrEnumerationType() ||
943 // -- pointer to object or pointer to function,
944 T->isPointerType() ||
945 // -- reference to object or reference to function,
946 T->isReferenceType() ||
947 // -- pointer to member,
948 T->isMemberPointerType() ||
949 // -- std::nullptr_t.
950 T->isNullPtrType() ||
951 // If T is a dependent type, we can't do the check now, so we
952 // assume that it is well-formed.
953 T->isDependentType() ||
954 // Allow use of auto in template parameter declarations.
955 T->isUndeducedType()) {
956 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
957 // are ignored when determining its type.
958 return T.getUnqualifiedType();
959 }
960
961 // C++ [temp.param]p8:
962 //
963 // A non-type template-parameter of type "array of T" or
964 // "function returning T" is adjusted to be of type "pointer to
965 // T" or "pointer to function returning T", respectively.
966 else if (T->isArrayType() || T->isFunctionType())
967 return Context.getDecayedType(T);
968
969 Diag(Loc, diag::err_template_nontype_parm_bad_type)
970 << T;
971
972 return QualType();
973}
974
975NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
976 unsigned Depth,
977 unsigned Position,
978 SourceLocation EqualLoc,
979 Expr *Default) {
980 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
981
982 // Check that we have valid decl-specifiers specified.
983 auto CheckValidDeclSpecifiers = [this, &D] {
984 // C++ [temp.param]
985 // p1
986 // template-parameter:
987 // ...
988 // parameter-declaration
989 // p2
990 // ... A storage class shall not be specified in a template-parameter
991 // declaration.
992 // [dcl.typedef]p1:
993 // The typedef specifier [...] shall not be used in the decl-specifier-seq
994 // of a parameter-declaration
995 const DeclSpec &DS = D.getDeclSpec();
996 auto EmitDiag = [this](SourceLocation Loc) {
997 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
998 << FixItHint::CreateRemoval(Loc);
999 };
1000 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1001 EmitDiag(DS.getStorageClassSpecLoc());
1002
1003 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1004 EmitDiag(DS.getThreadStorageClassSpecLoc());
1005
1006 // [dcl.inline]p1:
1007 // The inline specifier can be applied only to the declaration or
1008 // definition of a variable or function.
1009
1010 if (DS.isInlineSpecified())
1011 EmitDiag(DS.getInlineSpecLoc());
1012
1013 // [dcl.constexpr]p1:
1014 // The constexpr specifier shall be applied only to the definition of a
1015 // variable or variable template or the declaration of a function or
1016 // function template.
1017
1018 if (DS.isConstexprSpecified())
1019 EmitDiag(DS.getConstexprSpecLoc());
1020
1021 // [dcl.fct.spec]p1:
1022 // Function-specifiers can be used only in function declarations.
1023
1024 if (DS.isVirtualSpecified())
1025 EmitDiag(DS.getVirtualSpecLoc());
1026
1027 if (DS.isExplicitSpecified())
1028 EmitDiag(DS.getExplicitSpecLoc());
1029
1030 if (DS.isNoreturnSpecified())
1031 EmitDiag(DS.getNoreturnSpecLoc());
1032 };
1033
1034 CheckValidDeclSpecifiers();
1035
1036 if (TInfo->getType()->isUndeducedType()) {
1037 Diag(D.getIdentifierLoc(),
1038 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1039 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1040 }
1041
1042 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Non-type template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1043, __extension__ __PRETTY_FUNCTION__))
1043 "Non-type template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Non-type template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1043, __extension__ __PRETTY_FUNCTION__))
;
1044 bool Invalid = false;
1045
1046 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1047 if (T.isNull()) {
1048 T = Context.IntTy; // Recover with an 'int' type.
1049 Invalid = true;
1050 }
1051
1052 IdentifierInfo *ParamName = D.getIdentifier();
1053 bool IsParameterPack = D.hasEllipsis();
1054 NonTypeTemplateParmDecl *Param
1055 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1056 D.getLocStart(),
1057 D.getIdentifierLoc(),
1058 Depth, Position, ParamName, T,
1059 IsParameterPack, TInfo);
1060 Param->setAccess(AS_public);
1061
1062 if (Invalid)
1063 Param->setInvalidDecl();
1064
1065 if (ParamName) {
1066 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1067 ParamName);
1068
1069 // Add the template parameter into the current scope.
1070 S->AddDecl(Param);
1071 IdResolver.AddDecl(Param);
1072 }
1073
1074 // C++0x [temp.param]p9:
1075 // A default template-argument may be specified for any kind of
1076 // template-parameter that is not a template parameter pack.
1077 if (Default && IsParameterPack) {
1078 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1079 Default = nullptr;
1080 }
1081
1082 // Check the well-formedness of the default template argument, if provided.
1083 if (Default) {
1084 // Check for unexpanded parameter packs.
1085 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1086 return Param;
1087
1088 TemplateArgument Converted;
1089 ExprResult DefaultRes =
1090 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1091 if (DefaultRes.isInvalid()) {
1092 Param->setInvalidDecl();
1093 return Param;
1094 }
1095 Default = DefaultRes.get();
1096
1097 Param->setDefaultArgument(Default);
1098 }
1099
1100 return Param;
1101}
1102
1103/// ActOnTemplateTemplateParameter - Called when a C++ template template
1104/// parameter (e.g. T in template <template \<typename> class T> class array)
1105/// has been parsed. S is the current scope.
1106NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1107 SourceLocation TmpLoc,
1108 TemplateParameterList *Params,
1109 SourceLocation EllipsisLoc,
1110 IdentifierInfo *Name,
1111 SourceLocation NameLoc,
1112 unsigned Depth,
1113 unsigned Position,
1114 SourceLocation EqualLoc,
1115 ParsedTemplateArgument Default) {
1116 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Template template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1117, __extension__ __PRETTY_FUNCTION__))
1117 "Template template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Template template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1117, __extension__ __PRETTY_FUNCTION__))
;
1118
1119 // Construct the parameter object.
1120 bool IsParameterPack = EllipsisLoc.isValid();
1121 TemplateTemplateParmDecl *Param =
1122 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1123 NameLoc.isInvalid()? TmpLoc : NameLoc,
1124 Depth, Position, IsParameterPack,
1125 Name, Params);
1126 Param->setAccess(AS_public);
1127
1128 // If the template template parameter has a name, then link the identifier
1129 // into the scope and lookup mechanisms.
1130 if (Name) {
1131 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1132
1133 S->AddDecl(Param);
1134 IdResolver.AddDecl(Param);
1135 }
1136
1137 if (Params->size() == 0) {
1138 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1139 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1140 Param->setInvalidDecl();
1141 }
1142
1143 // C++0x [temp.param]p9:
1144 // A default template-argument may be specified for any kind of
1145 // template-parameter that is not a template parameter pack.
1146 if (IsParameterPack && !Default.isInvalid()) {
1147 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1148 Default = ParsedTemplateArgument();
1149 }
1150
1151 if (!Default.isInvalid()) {
1152 // Check only that we have a template template argument. We don't want to
1153 // try to check well-formedness now, because our template template parameter
1154 // might have dependent types in its template parameters, which we wouldn't
1155 // be able to match now.
1156 //
1157 // If none of the template template parameter's template arguments mention
1158 // other template parameters, we could actually perform more checking here.
1159 // However, it isn't worth doing.
1160 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1161 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1162 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1163 << DefaultArg.getSourceRange();
1164 return Param;
1165 }
1166
1167 // Check for unexpanded parameter packs.
1168 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1169 DefaultArg.getArgument().getAsTemplate(),
1170 UPPC_DefaultArgument))
1171 return Param;
1172
1173 Param->setDefaultArgument(Context, DefaultArg);
1174 }
1175
1176 return Param;
1177}
1178
1179/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1180/// constrained by RequiresClause, that contains the template parameters in
1181/// Params.
1182TemplateParameterList *
1183Sema::ActOnTemplateParameterList(unsigned Depth,
1184 SourceLocation ExportLoc,
1185 SourceLocation TemplateLoc,
1186 SourceLocation LAngleLoc,
1187 ArrayRef<NamedDecl *> Params,
1188 SourceLocation RAngleLoc,
1189 Expr *RequiresClause) {
1190 if (ExportLoc.isValid())
1191 Diag(ExportLoc, diag::warn_template_export_unsupported);
1192
1193 return TemplateParameterList::Create(
1194 Context, TemplateLoc, LAngleLoc,
1195 llvm::makeArrayRef(Params.data(), Params.size()),
1196 RAngleLoc, RequiresClause);
1197}
1198
1199static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1200 if (SS.isSet())
1201 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1202}
1203
1204DeclResult
1205Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1206 SourceLocation KWLoc, CXXScopeSpec &SS,
1207 IdentifierInfo *Name, SourceLocation NameLoc,
1208 AttributeList *Attr,
1209 TemplateParameterList *TemplateParams,
1210 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1211 SourceLocation FriendLoc,
1212 unsigned NumOuterTemplateParamLists,
1213 TemplateParameterList** OuterTemplateParamLists,
1214 SkipBodyInfo *SkipBody) {
1215 assert(TemplateParams && TemplateParams->size() > 0 &&(static_cast <bool> (TemplateParams && TemplateParams
->size() > 0 && "No template parameters") ? void
(0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1216, __extension__ __PRETTY_FUNCTION__))
1216 "No template parameters")(static_cast <bool> (TemplateParams && TemplateParams
->size() > 0 && "No template parameters") ? void
(0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1216, __extension__ __PRETTY_FUNCTION__))
;
1217 assert(TUK != TUK_Reference && "Can only declare or define class templates")(static_cast <bool> (TUK != TUK_Reference && "Can only declare or define class templates"
) ? void (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1217, __extension__ __PRETTY_FUNCTION__))
;
1218 bool Invalid = false;
1219
1220 // Check that we can declare a template here.
1221 if (CheckTemplateDeclScope(S, TemplateParams))
1222 return true;
1223
1224 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1225 assert(Kind != TTK_Enum && "can't build template of enumerated type")(static_cast <bool> (Kind != TTK_Enum && "can't build template of enumerated type"
) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1225, __extension__ __PRETTY_FUNCTION__))
;
1226
1227 // There is no such thing as an unnamed class template.
1228 if (!Name) {
1229 Diag(KWLoc, diag::err_template_unnamed_class);
1230 return true;
1231 }
1232
1233 // Find any previous declaration with this name. For a friend with no
1234 // scope explicitly specified, we only look for tag declarations (per
1235 // C++11 [basic.lookup.elab]p2).
1236 DeclContext *SemanticContext;
1237 LookupResult Previous(*this, Name, NameLoc,
1238 (SS.isEmpty() && TUK == TUK_Friend)
1239 ? LookupTagName : LookupOrdinaryName,
1240 forRedeclarationInCurContext());
1241 if (SS.isNotEmpty() && !SS.isInvalid()) {
1242 SemanticContext = computeDeclContext(SS, true);
1243 if (!SemanticContext) {
1244 // FIXME: Horrible, horrible hack! We can't currently represent this
1245 // in the AST, and historically we have just ignored such friend
1246 // class templates, so don't complain here.
1247 Diag(NameLoc, TUK == TUK_Friend
1248 ? diag::warn_template_qualified_friend_ignored
1249 : diag::err_template_qualified_declarator_no_match)
1250 << SS.getScopeRep() << SS.getRange();
1251 return TUK != TUK_Friend;
1252 }
1253
1254 if (RequireCompleteDeclContext(SS, SemanticContext))
1255 return true;
1256
1257 // If we're adding a template to a dependent context, we may need to
1258 // rebuilding some of the types used within the template parameter list,
1259 // now that we know what the current instantiation is.
1260 if (SemanticContext->isDependentContext()) {
1261 ContextRAII SavedContext(*this, SemanticContext);
1262 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1263 Invalid = true;
1264 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1265 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1266
1267 LookupQualifiedName(Previous, SemanticContext);
1268 } else {
1269 SemanticContext = CurContext;
1270
1271 // C++14 [class.mem]p14:
1272 // If T is the name of a class, then each of the following shall have a
1273 // name different from T:
1274 // -- every member template of class T
1275 if (TUK != TUK_Friend &&
1276 DiagnoseClassNameShadow(SemanticContext,
1277 DeclarationNameInfo(Name, NameLoc)))
1278 return true;
1279
1280 LookupName(Previous, S);
1281 }
1282
1283 if (Previous.isAmbiguous())
1284 return true;
1285
1286 NamedDecl *PrevDecl = nullptr;
1287 if (Previous.begin() != Previous.end())
1288 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1289
1290 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1291 // Maybe we will complain about the shadowed template parameter.
1292 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1293 // Just pretend that we didn't see the previous declaration.
1294 PrevDecl = nullptr;
1295 }
1296
1297 // If there is a previous declaration with the same name, check
1298 // whether this is a valid redeclaration.
1299 ClassTemplateDecl *PrevClassTemplate =
1300 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1301
1302 // We may have found the injected-class-name of a class template,
1303 // class template partial specialization, or class template specialization.
1304 // In these cases, grab the template that is being defined or specialized.
1305 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1306 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1307 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1308 PrevClassTemplate
1309 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1310 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1311 PrevClassTemplate
1312 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1313 ->getSpecializedTemplate();
1314 }
1315 }
1316
1317 if (TUK == TUK_Friend) {
1318 // C++ [namespace.memdef]p3:
1319 // [...] When looking for a prior declaration of a class or a function
1320 // declared as a friend, and when the name of the friend class or
1321 // function is neither a qualified name nor a template-id, scopes outside
1322 // the innermost enclosing namespace scope are not considered.
1323 if (!SS.isSet()) {
1324 DeclContext *OutermostContext = CurContext;
1325 while (!OutermostContext->isFileContext())
1326 OutermostContext = OutermostContext->getLookupParent();
1327
1328 if (PrevDecl &&
1329 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1330 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1331 SemanticContext = PrevDecl->getDeclContext();
1332 } else {
1333 // Declarations in outer scopes don't matter. However, the outermost
1334 // context we computed is the semantic context for our new
1335 // declaration.
1336 PrevDecl = PrevClassTemplate = nullptr;
1337 SemanticContext = OutermostContext;
1338
1339 // Check that the chosen semantic context doesn't already contain a
1340 // declaration of this name as a non-tag type.
1341 Previous.clear(LookupOrdinaryName);
1342 DeclContext *LookupContext = SemanticContext;
1343 while (LookupContext->isTransparentContext())
1344 LookupContext = LookupContext->getLookupParent();
1345 LookupQualifiedName(Previous, LookupContext);
1346
1347 if (Previous.isAmbiguous())
1348 return true;
1349
1350 if (Previous.begin() != Previous.end())
1351 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1352 }
1353 }
1354 } else if (PrevDecl &&
1355 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1356 S, SS.isValid()))
1357 PrevDecl = PrevClassTemplate = nullptr;
1358
1359 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1360 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1361 if (SS.isEmpty() &&
1362 !(PrevClassTemplate &&
1363 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1364 SemanticContext->getRedeclContext()))) {
1365 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1366 Diag(Shadow->getTargetDecl()->getLocation(),
1367 diag::note_using_decl_target);
1368 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1369 // Recover by ignoring the old declaration.
1370 PrevDecl = PrevClassTemplate = nullptr;
1371 }
1372 }
1373
1374 // TODO Memory management; associated constraints are not always stored.
1375 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1376
1377 if (PrevClassTemplate) {
1378 // Ensure that the template parameter lists are compatible. Skip this check
1379 // for a friend in a dependent context: the template parameter list itself
1380 // could be dependent.
1381 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1382 !TemplateParameterListsAreEqual(TemplateParams,
1383 PrevClassTemplate->getTemplateParameters(),
1384 /*Complain=*/true,
1385 TPL_TemplateMatch))
1386 return true;
1387
1388 // Check for matching associated constraints on redeclarations.
1389 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1390 const bool RedeclACMismatch = [&] {
1391 if (!(CurAC || PrevAC))
1392 return false; // Nothing to check; no mismatch.
1393 if (CurAC && PrevAC) {
1394 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1395 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1396 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1397 if (CurACInfo == PrevACInfo)
1398 return false; // All good; no mismatch.
1399 }
1400 return true;
1401 }();
1402
1403 if (RedeclACMismatch) {
1404 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1405 diag::err_template_different_associated_constraints);
1406 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1407 diag::note_template_prev_declaration) << /*declaration*/0;
1408 return true;
1409 }
1410
1411 // C++ [temp.class]p4:
1412 // In a redeclaration, partial specialization, explicit
1413 // specialization or explicit instantiation of a class template,
1414 // the class-key shall agree in kind with the original class
1415 // template declaration (7.1.5.3).
1416 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1417 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1418 TUK == TUK_Definition, KWLoc, Name)) {
1419 Diag(KWLoc, diag::err_use_with_wrong_tag)
1420 << Name
1421 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1422 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1423 Kind = PrevRecordDecl->getTagKind();
1424 }
1425
1426 // Check for redefinition of this class template.
1427 if (TUK == TUK_Definition) {
1428 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1429 // If we have a prior definition that is not visible, treat this as
1430 // simply making that previous definition visible.
1431 NamedDecl *Hidden = nullptr;
1432 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1433 SkipBody->ShouldSkip = true;
1434 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1435 assert(Tmpl && "original definition of a class template is not a "(static_cast <bool> (Tmpl && "original definition of a class template is not a "
"class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1436, __extension__ __PRETTY_FUNCTION__))
1436 "class template?")(static_cast <bool> (Tmpl && "original definition of a class template is not a "
"class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1436, __extension__ __PRETTY_FUNCTION__))
;
1437 makeMergedDefinitionVisible(Hidden);
1438 makeMergedDefinitionVisible(Tmpl);
1439 return Def;
1440 }
1441
1442 Diag(NameLoc, diag::err_redefinition) << Name;
1443 Diag(Def->getLocation(), diag::note_previous_definition);
1444 // FIXME: Would it make sense to try to "forget" the previous
1445 // definition, as part of error recovery?
1446 return true;
1447 }
1448 }
1449 } else if (PrevDecl) {
1450 // C++ [temp]p5:
1451 // A class template shall not have the same name as any other
1452 // template, class, function, object, enumeration, enumerator,
1453 // namespace, or type in the same scope (3.3), except as specified
1454 // in (14.5.4).
1455 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1456 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1457 return true;
1458 }
1459
1460 // Check the template parameter list of this declaration, possibly
1461 // merging in the template parameter list from the previous class
1462 // template declaration. Skip this check for a friend in a dependent
1463 // context, because the template parameter list might be dependent.
1464 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1465 CheckTemplateParameterList(
1466 TemplateParams,
1467 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1468 : nullptr,
1469 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1470 SemanticContext->isDependentContext())
1471 ? TPC_ClassTemplateMember
1472 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1473 : TPC_ClassTemplate))
1474 Invalid = true;
1475
1476 if (SS.isSet()) {
1477 // If the name of the template was qualified, we must be defining the
1478 // template out-of-line.
1479 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1480 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1481 : diag::err_member_decl_does_not_match)
1482 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1483 Invalid = true;
1484 }
1485 }
1486
1487 // If this is a templated friend in a dependent context we should not put it
1488 // on the redecl chain. In some cases, the templated friend can be the most
1489 // recent declaration tricking the template instantiator to make substitutions
1490 // there.
1491 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1492 bool ShouldAddRedecl
1493 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1494
1495 CXXRecordDecl *NewClass =
1496 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1497 PrevClassTemplate && ShouldAddRedecl ?
1498 PrevClassTemplate->getTemplatedDecl() : nullptr,
1499 /*DelayTypeCreation=*/true);
1500 SetNestedNameSpecifier(NewClass, SS);
1501 if (NumOuterTemplateParamLists > 0)
1502 NewClass->setTemplateParameterListsInfo(
1503 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1504 NumOuterTemplateParamLists));
1505
1506 // Add alignment attributes if necessary; these attributes are checked when
1507 // the ASTContext lays out the structure.
1508 if (TUK == TUK_Definition) {
1509 AddAlignmentAttributesForRecord(NewClass);
1510 AddMsStructLayoutForRecord(NewClass);
1511 }
1512
1513 // Attach the associated constraints when the declaration will not be part of
1514 // a decl chain.
1515 Expr *const ACtoAttach =
1516 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1517
1518 ClassTemplateDecl *NewTemplate
1519 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1520 DeclarationName(Name), TemplateParams,
1521 NewClass, ACtoAttach);
1522
1523 if (ShouldAddRedecl)
1524 NewTemplate->setPreviousDecl(PrevClassTemplate);
1525
1526 NewClass->setDescribedClassTemplate(NewTemplate);
1527
1528 if (ModulePrivateLoc.isValid())
1529 NewTemplate->setModulePrivate();
1530
1531 // Build the type for the class template declaration now.
1532 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1533 T = Context.getInjectedClassNameType(NewClass, T);
1534 assert(T->isDependentType() && "Class template type is not dependent?")(static_cast <bool> (T->isDependentType() &&
"Class template type is not dependent?") ? void (0) : __assert_fail
("T->isDependentType() && \"Class template type is not dependent?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1534, __extension__ __PRETTY_FUNCTION__))
;
1535 (void)T;
1536
1537 // If we are providing an explicit specialization of a member that is a
1538 // class template, make a note of that.
1539 if (PrevClassTemplate &&
1540 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1541 PrevClassTemplate->setMemberSpecialization();
1542
1543 // Set the access specifier.
1544 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1545 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1546
1547 // Set the lexical context of these templates
1548 NewClass->setLexicalDeclContext(CurContext);
1549 NewTemplate->setLexicalDeclContext(CurContext);
1550
1551 if (TUK == TUK_Definition)
1552 NewClass->startDefinition();
1553
1554 if (Attr)
1555 ProcessDeclAttributeList(S, NewClass, Attr);
1556
1557 if (PrevClassTemplate)
1558 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1559
1560 AddPushedVisibilityAttribute(NewClass);
1561
1562 if (TUK != TUK_Friend) {
1563 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1564 Scope *Outer = S;
1565 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1566 Outer = Outer->getParent();
1567 PushOnScopeChains(NewTemplate, Outer);
1568 } else {
1569 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1570 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1571 NewClass->setAccess(PrevClassTemplate->getAccess());
1572 }
1573
1574 NewTemplate->setObjectOfFriendDecl();
1575
1576 // Friend templates are visible in fairly strange ways.
1577 if (!CurContext->isDependentContext()) {
1578 DeclContext *DC = SemanticContext->getRedeclContext();
1579 DC->makeDeclVisibleInContext(NewTemplate);
1580 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1581 PushOnScopeChains(NewTemplate, EnclosingScope,
1582 /* AddToContext = */ false);
1583 }
1584
1585 FriendDecl *Friend = FriendDecl::Create(
1586 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1587 Friend->setAccess(AS_public);
1588 CurContext->addDecl(Friend);
1589 }
1590
1591 if (PrevClassTemplate)
1592 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1593
1594 if (Invalid) {
1595 NewTemplate->setInvalidDecl();
1596 NewClass->setInvalidDecl();
1597 }
1598
1599 ActOnDocumentableDecl(NewTemplate);
1600
1601 return NewTemplate;
1602}
1603
1604namespace {
1605/// Transform to convert portions of a constructor declaration into the
1606/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1607struct ConvertConstructorToDeductionGuideTransform {
1608 ConvertConstructorToDeductionGuideTransform(Sema &S,
1609 ClassTemplateDecl *Template)
1610 : SemaRef(S), Template(Template) {}
1611
1612 Sema &SemaRef;
1613 ClassTemplateDecl *Template;
1614
1615 DeclContext *DC = Template->getDeclContext();
1616 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1617 DeclarationName DeductionGuideName =
1618 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1619
1620 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1621
1622 // Index adjustment to apply to convert depth-1 template parameters into
1623 // depth-0 template parameters.
1624 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1625
1626 /// Transform a constructor declaration into a deduction guide.
1627 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1628 CXXConstructorDecl *CD) {
1629 SmallVector<TemplateArgument, 16> SubstArgs;
1630
1631 LocalInstantiationScope Scope(SemaRef);
1632
1633 // C++ [over.match.class.deduct]p1:
1634 // -- For each constructor of the class template designated by the
1635 // template-name, a function template with the following properties:
1636
1637 // -- The template parameters are the template parameters of the class
1638 // template followed by the template parameters (including default
1639 // template arguments) of the constructor, if any.
1640 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1641 if (FTD) {
1642 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1643 SmallVector<NamedDecl *, 16> AllParams;
1644 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1645 AllParams.insert(AllParams.begin(),
1646 TemplateParams->begin(), TemplateParams->end());
1647 SubstArgs.reserve(InnerParams->size());
1648
1649 // Later template parameters could refer to earlier ones, so build up
1650 // a list of substituted template arguments as we go.
1651 for (NamedDecl *Param : *InnerParams) {
1652 MultiLevelTemplateArgumentList Args;
1653 Args.addOuterTemplateArguments(SubstArgs);
1654 Args.addOuterRetainedLevel();
1655 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1656 if (!NewParam)
1657 return nullptr;
1658 AllParams.push_back(NewParam);
1659 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1660 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1661 }
1662 TemplateParams = TemplateParameterList::Create(
1663 SemaRef.Context, InnerParams->getTemplateLoc(),
1664 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1665 /*FIXME: RequiresClause*/ nullptr);
1666 }
1667
1668 // If we built a new template-parameter-list, track that we need to
1669 // substitute references to the old parameters into references to the
1670 // new ones.
1671 MultiLevelTemplateArgumentList Args;
1672 if (FTD) {
1673 Args.addOuterTemplateArguments(SubstArgs);
1674 Args.addOuterRetainedLevel();
1675 }
1676
1677 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1678 .getAsAdjusted<FunctionProtoTypeLoc>();
1679 assert(FPTL && "no prototype for constructor declaration")(static_cast <bool> (FPTL && "no prototype for constructor declaration"
) ? void (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1679, __extension__ __PRETTY_FUNCTION__))
;
1680
1681 // Transform the type of the function, adjusting the return type and
1682 // replacing references to the old parameters with references to the
1683 // new ones.
1684 TypeLocBuilder TLB;
1685 SmallVector<ParmVarDecl*, 8> Params;
1686 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1687 if (NewType.isNull())
1688 return nullptr;
1689 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1690
1691 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1692 CD->getLocStart(), CD->getLocation(),
1693 CD->getLocEnd());
1694 }
1695
1696 /// Build a deduction guide with the specified parameter types.
1697 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1698 SourceLocation Loc = Template->getLocation();
1699
1700 // Build the requested type.
1701 FunctionProtoType::ExtProtoInfo EPI;
1702 EPI.HasTrailingReturn = true;
1703 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1704 DeductionGuideName, EPI);
1705 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1706
1707 FunctionProtoTypeLoc FPTL =
1708 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1709
1710 // Build the parameters, needed during deduction / substitution.
1711 SmallVector<ParmVarDecl*, 4> Params;
1712 for (auto T : ParamTypes) {
1713 ParmVarDecl *NewParam = ParmVarDecl::Create(
1714 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1715 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1716 NewParam->setScopeInfo(0, Params.size());
1717 FPTL.setParam(Params.size(), NewParam);
1718 Params.push_back(NewParam);
1719 }
1720
1721 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1722 Loc, Loc, Loc);
1723 }
1724
1725private:
1726 /// Transform a constructor template parameter into a deduction guide template
1727 /// parameter, rebuilding any internal references to earlier parameters and
1728 /// renumbering as we go.
1729 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1730 MultiLevelTemplateArgumentList &Args) {
1731 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1732 // TemplateTypeParmDecl's index cannot be changed after creation, so
1733 // substitute it directly.
1734 auto *NewTTP = TemplateTypeParmDecl::Create(
1735 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1736 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1737 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1738 TTP->isParameterPack());
1739 if (TTP->hasDefaultArgument()) {
1740 TypeSourceInfo *InstantiatedDefaultArg =
1741 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1742 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1743 if (InstantiatedDefaultArg)
1744 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1745 }
1746 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1747 NewTTP);
1748 return NewTTP;
1749 }
1750
1751 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1752 return transformTemplateParameterImpl(TTP, Args);
1753
1754 return transformTemplateParameterImpl(
1755 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1756 }
1757 template<typename TemplateParmDecl>
1758 TemplateParmDecl *
1759 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1760 MultiLevelTemplateArgumentList &Args) {
1761 // Ask the template instantiator to do the heavy lifting for us, then adjust
1762 // the index of the parameter once it's done.
1763 auto *NewParam =
1764 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1765 assert(NewParam->getDepth() == 0 && "unexpected template param depth")(static_cast <bool> (NewParam->getDepth() == 0 &&
"unexpected template param depth") ? void (0) : __assert_fail
("NewParam->getDepth() == 0 && \"unexpected template param depth\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1765, __extension__ __PRETTY_FUNCTION__))
;
1766 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1767 return NewParam;
1768 }
1769
1770 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1771 FunctionProtoTypeLoc TL,
1772 SmallVectorImpl<ParmVarDecl*> &Params,
1773 MultiLevelTemplateArgumentList &Args) {
1774 SmallVector<QualType, 4> ParamTypes;
1775 const FunctionProtoType *T = TL.getTypePtr();
1776
1777 // -- The types of the function parameters are those of the constructor.
1778 for (auto *OldParam : TL.getParams()) {
1779 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1780 if (!NewParam)
1781 return QualType();
1782 ParamTypes.push_back(NewParam->getType());
1783 Params.push_back(NewParam);
1784 }
1785
1786 // -- The return type is the class template specialization designated by
1787 // the template-name and template arguments corresponding to the
1788 // template parameters obtained from the class template.
1789 //
1790 // We use the injected-class-name type of the primary template instead.
1791 // This has the convenient property that it is different from any type that
1792 // the user can write in a deduction-guide (because they cannot enter the
1793 // context of the template), so implicit deduction guides can never collide
1794 // with explicit ones.
1795 QualType ReturnType = DeducedType;
1796 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1797
1798 // Resolving a wording defect, we also inherit the variadicness of the
1799 // constructor.
1800 FunctionProtoType::ExtProtoInfo EPI;
1801 EPI.Variadic = T->isVariadic();
1802 EPI.HasTrailingReturn = true;
1803
1804 QualType Result = SemaRef.BuildFunctionType(
1805 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1806 if (Result.isNull())
1807 return QualType();
1808
1809 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1810 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1811 NewTL.setLParenLoc(TL.getLParenLoc());
1812 NewTL.setRParenLoc(TL.getRParenLoc());
1813 NewTL.setExceptionSpecRange(SourceRange());
1814 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1815 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1816 NewTL.setParam(I, Params[I]);
1817
1818 return Result;
1819 }
1820
1821 ParmVarDecl *
1822 transformFunctionTypeParam(ParmVarDecl *OldParam,
1823 MultiLevelTemplateArgumentList &Args) {
1824 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1825 TypeSourceInfo *NewDI;
1826 if (!Args.getNumLevels())
1827 NewDI = OldDI;
1828 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1829 // Expand out the one and only element in each inner pack.
1830 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1831 NewDI =
1832 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1833 OldParam->getLocation(), OldParam->getDeclName());
1834 if (!NewDI) return nullptr;
1835 NewDI =
1836 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1837 PackTL.getTypePtr()->getNumExpansions());
1838 } else
1839 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1840 OldParam->getDeclName());
1841 if (!NewDI)
1842 return nullptr;
1843
1844 // Canonicalize the type. This (for instance) replaces references to
1845 // typedef members of the current instantiations with the definitions of
1846 // those typedefs, avoiding triggering instantiation of the deduced type
1847 // during deduction.
1848 // FIXME: It would be preferable to retain type sugar and source
1849 // information here (and handle this in substitution instead).
1850 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1851 SemaRef.Context.getCanonicalType(NewDI->getType()),
1852 OldParam->getLocation());
1853
1854 // Resolving a wording defect, we also inherit default arguments from the
1855 // constructor.
1856 ExprResult NewDefArg;
1857 if (OldParam->hasDefaultArg()) {
1858 NewDefArg = Args.getNumLevels()
1859 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1860 : OldParam->getDefaultArg();
1861 if (NewDefArg.isInvalid())
1862 return nullptr;
1863 }
1864
1865 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1866 OldParam->getInnerLocStart(),
1867 OldParam->getLocation(),
1868 OldParam->getIdentifier(),
1869 NewDI->getType(),
1870 NewDI,
1871 OldParam->getStorageClass(),
1872 NewDefArg.get());
1873 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1874 OldParam->getFunctionScopeIndex());
1875 return NewParam;
1876 }
1877
1878 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1879 bool Explicit, TypeSourceInfo *TInfo,
1880 SourceLocation LocStart, SourceLocation Loc,
1881 SourceLocation LocEnd) {
1882 DeclarationNameInfo Name(DeductionGuideName, Loc);
1883 ArrayRef<ParmVarDecl *> Params =
1884 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1885
1886 // Build the implicit deduction guide template.
1887 auto *Guide =
1888 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1889 Name, TInfo->getType(), TInfo, LocEnd);
1890 Guide->setImplicit();
1891 Guide->setParams(Params);
1892
1893 for (auto *Param : Params)
1894 Param->setDeclContext(Guide);
1895
1896 auto *GuideTemplate = FunctionTemplateDecl::Create(
1897 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1898 GuideTemplate->setImplicit();
1899 Guide->setDescribedFunctionTemplate(GuideTemplate);
1900
1901 if (isa<CXXRecordDecl>(DC)) {
1902 Guide->setAccess(AS_public);
1903 GuideTemplate->setAccess(AS_public);
1904 }
1905
1906 DC->addDecl(GuideTemplate);
1907 return GuideTemplate;
1908 }
1909};
1910}
1911
1912void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1913 SourceLocation Loc) {
1914 DeclContext *DC = Template->getDeclContext();
1915 if (DC->isDependentContext())
1916 return;
1917
1918 ConvertConstructorToDeductionGuideTransform Transform(
1919 *this, cast<ClassTemplateDecl>(Template));
1920 if (!isCompleteType(Loc, Transform.DeducedType))
1921 return;
1922
1923 // Check whether we've already declared deduction guides for this template.
1924 // FIXME: Consider storing a flag on the template to indicate this.
1925 auto Existing = DC->lookup(Transform.DeductionGuideName);
1926 for (auto *D : Existing)
1927 if (D->isImplicit())
1928 return;
1929
1930 // In case we were expanding a pack when we attempted to declare deduction
1931 // guides, turn off pack expansion for everything we're about to do.
1932 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1933 // Create a template instantiation record to track the "instantiation" of
1934 // constructors into deduction guides.
1935 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1936 // this substitution process actually fail?
1937 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1938
1939 // Convert declared constructors into deduction guide templates.
1940 // FIXME: Skip constructors for which deduction must necessarily fail (those
1941 // for which some class template parameter without a default argument never
1942 // appears in a deduced context).
1943 bool AddedAny = false;
1944 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1945 D = D->getUnderlyingDecl();
1946 if (D->isInvalidDecl() || D->isImplicit())
1947 continue;
1948 D = cast<NamedDecl>(D->getCanonicalDecl());
1949
1950 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1951 auto *CD =
1952 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1953 // Class-scope explicit specializations (MS extension) do not result in
1954 // deduction guides.
1955 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1956 continue;
1957
1958 Transform.transformConstructor(FTD, CD);
1959 AddedAny = true;
1960 }
1961
1962 // C++17 [over.match.class.deduct]
1963 // -- If C is not defined or does not declare any constructors, an
1964 // additional function template derived as above from a hypothetical
1965 // constructor C().
1966 if (!AddedAny)
1967 Transform.buildSimpleDeductionGuide(None);
1968
1969 // -- An additional function template derived as above from a hypothetical
1970 // constructor C(C), called the copy deduction candidate.
1971 cast<CXXDeductionGuideDecl>(
1972 cast<FunctionTemplateDecl>(
1973 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1974 ->getTemplatedDecl())
1975 ->setIsCopyDeductionCandidate();
1976}
1977
1978/// \brief Diagnose the presence of a default template argument on a
1979/// template parameter, which is ill-formed in certain contexts.
1980///
1981/// \returns true if the default template argument should be dropped.
1982static bool DiagnoseDefaultTemplateArgument(Sema &S,
1983 Sema::TemplateParamListContext TPC,
1984 SourceLocation ParamLoc,
1985 SourceRange DefArgRange) {
1986 switch (TPC) {
1987 case Sema::TPC_ClassTemplate:
1988 case Sema::TPC_VarTemplate:
1989 case Sema::TPC_TypeAliasTemplate:
1990 return false;
1991
1992 case Sema::TPC_FunctionTemplate:
1993 case Sema::TPC_FriendFunctionTemplateDefinition:
1994 // C++ [temp.param]p9:
1995 // A default template-argument shall not be specified in a
1996 // function template declaration or a function template
1997 // definition [...]
1998 // If a friend function template declaration specifies a default
1999 // template-argument, that declaration shall be a definition and shall be
2000 // the only declaration of the function template in the translation unit.
2001 // (C++98/03 doesn't have this wording; see DR226).
2002 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2003 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2004 : diag::ext_template_parameter_default_in_function_template)
2005 << DefArgRange;
2006 return false;
2007
2008 case Sema::TPC_ClassTemplateMember:
2009 // C++0x [temp.param]p9:
2010 // A default template-argument shall not be specified in the
2011 // template-parameter-lists of the definition of a member of a
2012 // class template that appears outside of the member's class.
2013 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2014 << DefArgRange;
2015 return true;
2016
2017 case Sema::TPC_FriendClassTemplate:
2018 case Sema::TPC_FriendFunctionTemplate:
2019 // C++ [temp.param]p9:
2020 // A default template-argument shall not be specified in a
2021 // friend template declaration.
2022 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2023 << DefArgRange;
2024 return true;
2025
2026 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2027 // for friend function templates if there is only a single
2028 // declaration (and it is a definition). Strange!
2029 }
2030
2031 llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2031)
;
2032}
2033
2034/// \brief Check for unexpanded parameter packs within the template parameters
2035/// of a template template parameter, recursively.
2036static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2037 TemplateTemplateParmDecl *TTP) {
2038 // A template template parameter which is a parameter pack is also a pack
2039 // expansion.
2040 if (TTP->isParameterPack())
2041 return false;
2042
2043 TemplateParameterList *Params = TTP->getTemplateParameters();
2044 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2045 NamedDecl *P = Params->getParam(I);
2046 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2047 if (!NTTP->isParameterPack() &&
2048 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2049 NTTP->getTypeSourceInfo(),
2050 Sema::UPPC_NonTypeTemplateParameterType))
2051 return true;
2052
2053 continue;
2054 }
2055
2056 if (TemplateTemplateParmDecl *InnerTTP
2057 = dyn_cast<TemplateTemplateParmDecl>(P))
2058 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2059 return true;
2060 }
2061
2062 return false;
2063}
2064
2065/// \brief Checks the validity of a template parameter list, possibly
2066/// considering the template parameter list from a previous
2067/// declaration.
2068///
2069/// If an "old" template parameter list is provided, it must be
2070/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2071/// template parameter list.
2072///
2073/// \param NewParams Template parameter list for a new template
2074/// declaration. This template parameter list will be updated with any
2075/// default arguments that are carried through from the previous
2076/// template parameter list.
2077///
2078/// \param OldParams If provided, template parameter list from a
2079/// previous declaration of the same template. Default template
2080/// arguments will be merged from the old template parameter list to
2081/// the new template parameter list.
2082///
2083/// \param TPC Describes the context in which we are checking the given
2084/// template parameter list.
2085///
2086/// \returns true if an error occurred, false otherwise.
2087bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2088 TemplateParameterList *OldParams,
2089 TemplateParamListContext TPC) {
2090 bool Invalid = false;
2091
2092 // C++ [temp.param]p10:
2093 // The set of default template-arguments available for use with a
2094 // template declaration or definition is obtained by merging the
2095 // default arguments from the definition (if in scope) and all
2096 // declarations in scope in the same way default function
2097 // arguments are (8.3.6).
2098 bool SawDefaultArgument = false;
2099 SourceLocation PreviousDefaultArgLoc;
2100
2101 // Dummy initialization to avoid warnings.
2102 TemplateParameterList::iterator OldParam = NewParams->end();
2103 if (OldParams)
2104 OldParam = OldParams->begin();
2105
2106 bool RemoveDefaultArguments = false;
2107 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2108 NewParamEnd = NewParams->end();
2109 NewParam != NewParamEnd; ++NewParam) {
2110 // Variables used to diagnose redundant default arguments
2111 bool RedundantDefaultArg = false;
2112 SourceLocation OldDefaultLoc;
2113 SourceLocation NewDefaultLoc;
2114
2115 // Variable used to diagnose missing default arguments
2116 bool MissingDefaultArg = false;
2117
2118 // Variable used to diagnose non-final parameter packs
2119 bool SawParameterPack = false;
2120
2121 if (TemplateTypeParmDecl *NewTypeParm
2122 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2123 // Check the presence of a default argument here.
2124 if (NewTypeParm->hasDefaultArgument() &&
2125 DiagnoseDefaultTemplateArgument(*this, TPC,
2126 NewTypeParm->getLocation(),
2127 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2128 .getSourceRange()))
2129 NewTypeParm->removeDefaultArgument();
2130
2131 // Merge default arguments for template type parameters.
2132 TemplateTypeParmDecl *OldTypeParm
2133 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2134 if (NewTypeParm->isParameterPack()) {
2135 assert(!NewTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2136, __extension__ __PRETTY_FUNCTION__))
2136 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2136, __extension__ __PRETTY_FUNCTION__))
;
2137 SawParameterPack = true;
2138 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2139 NewTypeParm->hasDefaultArgument()) {
2140 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2141 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2142 SawDefaultArgument = true;
2143 RedundantDefaultArg = true;
2144 PreviousDefaultArgLoc = NewDefaultLoc;
2145 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2146 // Merge the default argument from the old declaration to the
2147 // new declaration.
2148 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2149 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2150 } else if (NewTypeParm->hasDefaultArgument()) {
2151 SawDefaultArgument = true;
2152 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2153 } else if (SawDefaultArgument)
2154 MissingDefaultArg = true;
2155 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2156 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2157 // Check for unexpanded parameter packs.
2158 if (!NewNonTypeParm->isParameterPack() &&
2159 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2160 NewNonTypeParm->getTypeSourceInfo(),
2161 UPPC_NonTypeTemplateParameterType)) {
2162 Invalid = true;
2163 continue;
2164 }
2165
2166 // Check the presence of a default argument here.
2167 if (NewNonTypeParm->hasDefaultArgument() &&
2168 DiagnoseDefaultTemplateArgument(*this, TPC,
2169 NewNonTypeParm->getLocation(),
2170 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2171 NewNonTypeParm->removeDefaultArgument();
2172 }
2173
2174 // Merge default arguments for non-type template parameters
2175 NonTypeTemplateParmDecl *OldNonTypeParm
2176 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2177 if (NewNonTypeParm->isParameterPack()) {
2178 assert(!NewNonTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2179, __extension__ __PRETTY_FUNCTION__))
2179 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2179, __extension__ __PRETTY_FUNCTION__))
;
2180 if (!NewNonTypeParm->isPackExpansion())
2181 SawParameterPack = true;
2182 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2183 NewNonTypeParm->hasDefaultArgument()) {
2184 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2185 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2186 SawDefaultArgument = true;
2187 RedundantDefaultArg = true;
2188 PreviousDefaultArgLoc = NewDefaultLoc;
2189 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2190 // Merge the default argument from the old declaration to the
2191 // new declaration.
2192 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2193 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2194 } else if (NewNonTypeParm->hasDefaultArgument()) {
2195 SawDefaultArgument = true;
2196 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2197 } else if (SawDefaultArgument)
2198 MissingDefaultArg = true;
2199 } else {
2200 TemplateTemplateParmDecl *NewTemplateParm
2201 = cast<TemplateTemplateParmDecl>(*NewParam);
2202
2203 // Check for unexpanded parameter packs, recursively.
2204 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2205 Invalid = true;
2206 continue;
2207 }
2208
2209 // Check the presence of a default argument here.
2210 if (NewTemplateParm->hasDefaultArgument() &&
2211 DiagnoseDefaultTemplateArgument(*this, TPC,
2212 NewTemplateParm->getLocation(),
2213 NewTemplateParm->getDefaultArgument().getSourceRange()))
2214 NewTemplateParm->removeDefaultArgument();
2215
2216 // Merge default arguments for template template parameters
2217 TemplateTemplateParmDecl *OldTemplateParm
2218 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2219 if (NewTemplateParm->isParameterPack()) {
2220 assert(!NewTemplateParm->hasDefaultArgument() &&(static_cast <bool> (!NewTemplateParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2221, __extension__ __PRETTY_FUNCTION__))
2221 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTemplateParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2221, __extension__ __PRETTY_FUNCTION__))
;
2222 if (!NewTemplateParm->isPackExpansion())
2223 SawParameterPack = true;
2224 } else if (OldTemplateParm &&
2225 hasVisibleDefaultArgument(OldTemplateParm) &&
2226 NewTemplateParm->hasDefaultArgument()) {
2227 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2228 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2229 SawDefaultArgument = true;
2230 RedundantDefaultArg = true;
2231 PreviousDefaultArgLoc = NewDefaultLoc;
2232 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2233 // Merge the default argument from the old declaration to the
2234 // new declaration.
2235 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2236 PreviousDefaultArgLoc
2237 = OldTemplateParm->getDefaultArgument().getLocation();
2238 } else if (NewTemplateParm->hasDefaultArgument()) {
2239 SawDefaultArgument = true;
2240 PreviousDefaultArgLoc
2241 = NewTemplateParm->getDefaultArgument().getLocation();
2242 } else if (SawDefaultArgument)
2243 MissingDefaultArg = true;
2244 }
2245
2246 // C++11 [temp.param]p11:
2247 // If a template parameter of a primary class template or alias template
2248 // is a template parameter pack, it shall be the last template parameter.
2249 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2250 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2251 TPC == TPC_TypeAliasTemplate)) {
2252 Diag((*NewParam)->getLocation(),
2253 diag::err_template_param_pack_must_be_last_template_parameter);
2254 Invalid = true;
2255 }
2256
2257 if (RedundantDefaultArg) {
2258 // C++ [temp.param]p12:
2259 // A template-parameter shall not be given default arguments
2260 // by two different declarations in the same scope.
2261 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2262 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2263 Invalid = true;
2264 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2265 // C++ [temp.param]p11:
2266 // If a template-parameter of a class template has a default
2267 // template-argument, each subsequent template-parameter shall either
2268 // have a default template-argument supplied or be a template parameter
2269 // pack.
2270 Diag((*NewParam)->getLocation(),
2271 diag::err_template_param_default_arg_missing);
2272 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2273 Invalid = true;
2274 RemoveDefaultArguments = true;
2275 }
2276
2277 // If we have an old template parameter list that we're merging
2278 // in, move on to the next parameter.
2279 if (OldParams)
2280 ++OldParam;
2281 }
2282
2283 // We were missing some default arguments at the end of the list, so remove
2284 // all of the default arguments.
2285 if (RemoveDefaultArguments) {
2286 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2287 NewParamEnd = NewParams->end();
2288 NewParam != NewParamEnd; ++NewParam) {
2289 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2290 TTP->removeDefaultArgument();
2291 else if (NonTypeTemplateParmDecl *NTTP
2292 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2293 NTTP->removeDefaultArgument();
2294 else
2295 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2296 }
2297 }
2298
2299 return Invalid;
2300}
2301
2302namespace {
2303
2304/// A class which looks for a use of a certain level of template
2305/// parameter.
2306struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2307 typedef RecursiveASTVisitor<DependencyChecker> super;
2308
2309 unsigned Depth;
2310
2311 // Whether we're looking for a use of a template parameter that makes the
2312 // overall construct type-dependent / a dependent type. This is strictly
2313 // best-effort for now; we may fail to match at all for a dependent type
2314 // in some cases if this is set.
2315 bool IgnoreNonTypeDependent;
2316
2317 bool Match;
2318 SourceLocation MatchLoc;
2319
2320 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2321 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2322 Match(false) {}
2323
2324 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2325 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2326 NamedDecl *ND = Params->getParam(0);
2327 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2328 Depth = PD->getDepth();
2329 } else if (NonTypeTemplateParmDecl *PD =
2330 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2331 Depth = PD->getDepth();
2332 } else {
2333 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2334 }
2335 }
2336
2337 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2338 if (ParmDepth >= Depth) {
2339 Match = true;
2340 MatchLoc = Loc;
2341 return true;
2342 }
2343 return false;
2344 }
2345
2346 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2347 // Prune out non-type-dependent expressions if requested. This can
2348 // sometimes result in us failing to find a template parameter reference
2349 // (if a value-dependent expression creates a dependent type), but this
2350 // mode is best-effort only.
2351 if (auto *E = dyn_cast_or_null<Expr>(S))
2352 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2353 return true;
2354 return super::TraverseStmt(S, Q);
2355 }
2356
2357 bool TraverseTypeLoc(TypeLoc TL) {
2358 if (IgnoreNonTypeDependent && !TL.isNull() &&
2359 !TL.getType()->isDependentType())
2360 return true;
2361 return super::TraverseTypeLoc(TL);
2362 }
2363
2364 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2365 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2366 }
2367
2368 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2369 // For a best-effort search, keep looking until we find a location.
2370 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2371 }
2372
2373 bool TraverseTemplateName(TemplateName N) {
2374 if (TemplateTemplateParmDecl *PD =
2375 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2376 if (Matches(PD->getDepth()))
2377 return false;
2378 return super::TraverseTemplateName(N);
2379 }
2380
2381 bool VisitDeclRefExpr(DeclRefExpr *E) {
2382 if (NonTypeTemplateParmDecl *PD =
2383 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2384 if (Matches(PD->getDepth(), E->getExprLoc()))
2385 return false;
2386 return super::VisitDeclRefExpr(E);
2387 }
2388
2389 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2390 return TraverseType(T->getReplacementType());
2391 }
2392
2393 bool
2394 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2395 return TraverseTemplateArgument(T->getArgumentPack());
2396 }
2397
2398 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2399 return TraverseType(T->getInjectedSpecializationType());
2400 }
2401};
2402} // end anonymous namespace
2403
2404/// Determines whether a given type depends on the given parameter
2405/// list.
2406static bool
2407DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2408 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2409 Checker.TraverseType(T);
2410 return Checker.Match;
2411}
2412
2413// Find the source range corresponding to the named type in the given
2414// nested-name-specifier, if any.
2415static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2416 QualType T,
2417 const CXXScopeSpec &SS) {
2418 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2419 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2420 if (const Type *CurType = NNS->getAsType()) {
2421 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2422 return NNSLoc.getTypeLoc().getSourceRange();
2423 } else
2424 break;
2425
2426 NNSLoc = NNSLoc.getPrefix();
2427 }
2428
2429 return SourceRange();
2430}
2431
2432/// \brief Match the given template parameter lists to the given scope
2433/// specifier, returning the template parameter list that applies to the
2434/// name.
2435///
2436/// \param DeclStartLoc the start of the declaration that has a scope
2437/// specifier or a template parameter list.
2438///
2439/// \param DeclLoc The location of the declaration itself.
2440///
2441/// \param SS the scope specifier that will be matched to the given template
2442/// parameter lists. This scope specifier precedes a qualified name that is
2443/// being declared.
2444///
2445/// \param TemplateId The template-id following the scope specifier, if there
2446/// is one. Used to check for a missing 'template<>'.
2447///
2448/// \param ParamLists the template parameter lists, from the outermost to the
2449/// innermost template parameter lists.
2450///
2451/// \param IsFriend Whether to apply the slightly different rules for
2452/// matching template parameters to scope specifiers in friend
2453/// declarations.
2454///
2455/// \param IsMemberSpecialization will be set true if the scope specifier
2456/// denotes a fully-specialized type, and therefore this is a declaration of
2457/// a member specialization.
2458///
2459/// \returns the template parameter list, if any, that corresponds to the
2460/// name that is preceded by the scope specifier @p SS. This template
2461/// parameter list may have template parameters (if we're declaring a
2462/// template) or may have no template parameters (if we're declaring a
2463/// template specialization), or may be NULL (if what we're declaring isn't
2464/// itself a template).
2465TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2466 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2467 TemplateIdAnnotation *TemplateId,
2468 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2469 bool &IsMemberSpecialization, bool &Invalid) {
2470 IsMemberSpecialization = false;
2471 Invalid = false;
2472
2473 // The sequence of nested types to which we will match up the template
2474 // parameter lists. We first build this list by starting with the type named
2475 // by the nested-name-specifier and walking out until we run out of types.
2476 SmallVector<QualType, 4> NestedTypes;
2477 QualType T;
2478 if (SS.getScopeRep()) {
2479 if (CXXRecordDecl *Record
2480 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2481 T = Context.getTypeDeclType(Record);
2482 else
2483 T = QualType(SS.getScopeRep()->getAsType(), 0);
2484 }
2485
2486 // If we found an explicit specialization that prevents us from needing
2487 // 'template<>' headers, this will be set to the location of that
2488 // explicit specialization.
2489 SourceLocation ExplicitSpecLoc;
2490
2491 while (!T.isNull()) {
2492 NestedTypes.push_back(T);
2493
2494 // Retrieve the parent of a record type.
2495 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2496 // If this type is an explicit specialization, we're done.
2497 if (ClassTemplateSpecializationDecl *Spec
2498 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2499 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2500 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2501 ExplicitSpecLoc = Spec->getLocation();
2502 break;
2503 }
2504 } else if (Record->getTemplateSpecializationKind()
2505 == TSK_ExplicitSpecialization) {
2506 ExplicitSpecLoc = Record->getLocation();
2507 break;
2508 }
2509
2510 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2511 T = Context.getTypeDeclType(Parent);
2512 else
2513 T = QualType();
2514 continue;
2515 }
2516
2517 if (const TemplateSpecializationType *TST
2518 = T->getAs<TemplateSpecializationType>()) {
2519 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2520 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2521 T = Context.getTypeDeclType(Parent);
2522 else
2523 T = QualType();
2524 continue;
2525 }
2526 }
2527
2528 // Look one step prior in a dependent template specialization type.
2529 if (const DependentTemplateSpecializationType *DependentTST
2530 = T->getAs<DependentTemplateSpecializationType>()) {
2531 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2532 T = QualType(NNS->getAsType(), 0);
2533 else
2534 T = QualType();
2535 continue;
2536 }
2537
2538 // Look one step prior in a dependent name type.
2539 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2540 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2541 T = QualType(NNS->getAsType(), 0);
2542 else
2543 T = QualType();
2544 continue;
2545 }
2546
2547 // Retrieve the parent of an enumeration type.
2548 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2549 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2550 // check here.
2551 EnumDecl *Enum = EnumT->getDecl();
2552
2553 // Get to the parent type.
2554 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2555 T = Context.getTypeDeclType(Parent);
2556 else
2557 T = QualType();
2558 continue;
2559 }
2560
2561 T = QualType();
2562 }
2563 // Reverse the nested types list, since we want to traverse from the outermost
2564 // to the innermost while checking template-parameter-lists.
2565 std::reverse(NestedTypes.begin(), NestedTypes.end());
2566
2567 // C++0x [temp.expl.spec]p17:
2568 // A member or a member template may be nested within many
2569 // enclosing class templates. In an explicit specialization for
2570 // such a member, the member declaration shall be preceded by a
2571 // template<> for each enclosing class template that is
2572 // explicitly specialized.
2573 bool SawNonEmptyTemplateParameterList = false;
2574
2575 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2576 if (SawNonEmptyTemplateParameterList) {
2577 Diag(DeclLoc, diag::err_specialize_member_of_template)
2578 << !Recovery << Range;
2579 Invalid = true;
2580 IsMemberSpecialization = false;
2581 return true;
2582 }
2583
2584 return false;
2585 };
2586
2587 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2588 // Check that we can have an explicit specialization here.
2589 if (CheckExplicitSpecialization(Range, true))
2590 return true;
2591
2592 // We don't have a template header, but we should.
2593 SourceLocation ExpectedTemplateLoc;
2594 if (!ParamLists.empty())
2595 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2596 else
2597 ExpectedTemplateLoc = DeclStartLoc;
2598
2599 Diag(DeclLoc, diag::err_template_spec_needs_header)
2600 << Range
2601 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2602 return false;
2603 };
2604
2605 unsigned ParamIdx = 0;
2606 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2607 ++TypeIdx) {
2608 T = NestedTypes[TypeIdx];
2609
2610 // Whether we expect a 'template<>' header.
2611 bool NeedEmptyTemplateHeader = false;
2612
2613 // Whether we expect a template header with parameters.
2614 bool NeedNonemptyTemplateHeader = false;
2615
2616 // For a dependent type, the set of template parameters that we
2617 // expect to see.
2618 TemplateParameterList *ExpectedTemplateParams = nullptr;
2619
2620 // C++0x [temp.expl.spec]p15:
2621 // A member or a member template may be nested within many enclosing
2622 // class templates. In an explicit specialization for such a member, the
2623 // member declaration shall be preceded by a template<> for each
2624 // enclosing class template that is explicitly specialized.
2625 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2626 if (ClassTemplatePartialSpecializationDecl *Partial
2627 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2628 ExpectedTemplateParams = Partial->getTemplateParameters();
2629 NeedNonemptyTemplateHeader = true;
2630 } else if (Record->isDependentType()) {
2631 if (Record->getDescribedClassTemplate()) {
2632 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2633 ->getTemplateParameters();
2634 NeedNonemptyTemplateHeader = true;
2635 }
2636 } else if (ClassTemplateSpecializationDecl *Spec
2637 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2638 // C++0x [temp.expl.spec]p4:
2639 // Members of an explicitly specialized class template are defined
2640 // in the same manner as members of normal classes, and not using
2641 // the template<> syntax.
2642 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2643 NeedEmptyTemplateHeader = true;
2644 else
2645 continue;
2646 } else if (Record->getTemplateSpecializationKind()) {
2647 if (Record->getTemplateSpecializationKind()
2648 != TSK_ExplicitSpecialization &&
2649 TypeIdx == NumTypes - 1)
2650 IsMemberSpecialization = true;
2651
2652 continue;
2653 }
2654 } else if (const TemplateSpecializationType *TST
2655 = T->getAs<TemplateSpecializationType>()) {
2656 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2657 ExpectedTemplateParams = Template->getTemplateParameters();
2658 NeedNonemptyTemplateHeader = true;
2659 }
2660 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2661 // FIXME: We actually could/should check the template arguments here
2662 // against the corresponding template parameter list.
2663 NeedNonemptyTemplateHeader = false;
2664 }
2665
2666 // C++ [temp.expl.spec]p16:
2667 // In an explicit specialization declaration for a member of a class
2668 // template or a member template that ap- pears in namespace scope, the
2669 // member template and some of its enclosing class templates may remain
2670 // unspecialized, except that the declaration shall not explicitly
2671 // specialize a class member template if its en- closing class templates
2672 // are not explicitly specialized as well.
2673 if (ParamIdx < ParamLists.size()) {
2674 if (ParamLists[ParamIdx]->size() == 0) {
2675 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2676 false))
2677 return nullptr;
2678 } else
2679 SawNonEmptyTemplateParameterList = true;
2680 }
2681
2682 if (NeedEmptyTemplateHeader) {
2683 // If we're on the last of the types, and we need a 'template<>' header
2684 // here, then it's a member specialization.
2685 if (TypeIdx == NumTypes - 1)
2686 IsMemberSpecialization = true;
2687
2688 if (ParamIdx < ParamLists.size()) {
2689 if (ParamLists[ParamIdx]->size() > 0) {
2690 // The header has template parameters when it shouldn't. Complain.
2691 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2692 diag::err_template_param_list_matches_nontemplate)
2693 << T
2694 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2695 ParamLists[ParamIdx]->getRAngleLoc())
2696 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2697 Invalid = true;
2698 return nullptr;
2699 }
2700
2701 // Consume this template header.
2702 ++ParamIdx;
2703 continue;
2704 }
2705
2706 if (!IsFriend)
2707 if (DiagnoseMissingExplicitSpecialization(
2708 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2709 return nullptr;
2710
2711 continue;
2712 }
2713
2714 if (NeedNonemptyTemplateHeader) {
2715 // In friend declarations we can have template-ids which don't
2716 // depend on the corresponding template parameter lists. But
2717 // assume that empty parameter lists are supposed to match this
2718 // template-id.
2719 if (IsFriend && T->isDependentType()) {
2720 if (ParamIdx < ParamLists.size() &&
2721 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2722 ExpectedTemplateParams = nullptr;
2723 else
2724 continue;
2725 }
2726
2727 if (ParamIdx < ParamLists.size()) {
2728 // Check the template parameter list, if we can.
2729 if (ExpectedTemplateParams &&
2730 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2731 ExpectedTemplateParams,
2732 true, TPL_TemplateMatch))
2733 Invalid = true;
2734
2735 if (!Invalid &&
2736 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2737 TPC_ClassTemplateMember))
2738 Invalid = true;
2739
2740 ++ParamIdx;
2741 continue;
2742 }
2743
2744 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2745 << T
2746 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2747 Invalid = true;
2748 continue;
2749 }
2750 }
2751
2752 // If there were at least as many template-ids as there were template
2753 // parameter lists, then there are no template parameter lists remaining for
2754 // the declaration itself.
2755 if (ParamIdx >= ParamLists.size()) {
2756 if (TemplateId && !IsFriend) {
2757 // We don't have a template header for the declaration itself, but we
2758 // should.
2759 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2760 TemplateId->RAngleLoc));
2761
2762 // Fabricate an empty template parameter list for the invented header.
2763 return TemplateParameterList::Create(Context, SourceLocation(),
2764 SourceLocation(), None,
2765 SourceLocation(), nullptr);
2766 }
2767
2768 return nullptr;
2769 }
2770
2771 // If there were too many template parameter lists, complain about that now.
2772 if (ParamIdx < ParamLists.size() - 1) {
2773 bool HasAnyExplicitSpecHeader = false;
2774 bool AllExplicitSpecHeaders = true;
2775 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2776 if (ParamLists[I]->size() == 0)
2777 HasAnyExplicitSpecHeader = true;
2778 else
2779 AllExplicitSpecHeaders = false;
2780 }
2781
2782 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2783 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2784 : diag::err_template_spec_extra_headers)
2785 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2786 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2787
2788 // If there was a specialization somewhere, such that 'template<>' is
2789 // not required, and there were any 'template<>' headers, note where the
2790 // specialization occurred.
2791 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2792 Diag(ExplicitSpecLoc,
2793 diag::note_explicit_template_spec_does_not_need_header)
2794 << NestedTypes.back();
2795
2796 // We have a template parameter list with no corresponding scope, which
2797 // means that the resulting template declaration can't be instantiated
2798 // properly (we'll end up with dependent nodes when we shouldn't).
2799 if (!AllExplicitSpecHeaders)
2800 Invalid = true;
2801 }
2802
2803 // C++ [temp.expl.spec]p16:
2804 // In an explicit specialization declaration for a member of a class
2805 // template or a member template that ap- pears in namespace scope, the
2806 // member template and some of its enclosing class templates may remain
2807 // unspecialized, except that the declaration shall not explicitly
2808 // specialize a class member template if its en- closing class templates
2809 // are not explicitly specialized as well.
2810 if (ParamLists.back()->size() == 0 &&
2811 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2812 false))
2813 return nullptr;
2814
2815 // Return the last template parameter list, which corresponds to the
2816 // entity being declared.
2817 return ParamLists.back();
2818}
2819
2820void Sema::NoteAllFoundTemplates(TemplateName Name) {
2821 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2822 Diag(Template->getLocation(), diag::note_template_declared_here)
2823 << (isa<FunctionTemplateDecl>(Template)
2824 ? 0
2825 : isa<ClassTemplateDecl>(Template)
2826 ? 1
2827 : isa<VarTemplateDecl>(Template)
2828 ? 2
2829 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2830 << Template->getDeclName();
2831 return;
2832 }
2833
2834 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2835 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2836 IEnd = OST->end();
2837 I != IEnd; ++I)
2838 Diag((*I)->getLocation(), diag::note_template_declared_here)
2839 << 0 << (*I)->getDeclName();
2840
2841 return;
2842 }
2843}
2844
2845static QualType
2846checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2847 const SmallVectorImpl<TemplateArgument> &Converted,
2848 SourceLocation TemplateLoc,
2849 TemplateArgumentListInfo &TemplateArgs) {
2850 ASTContext &Context = SemaRef.getASTContext();
2851 switch (BTD->getBuiltinTemplateKind()) {
2852 case BTK__make_integer_seq: {
2853 // Specializations of __make_integer_seq<S, T, N> are treated like
2854 // S<T, 0, ..., N-1>.
2855
2856 // C++14 [inteseq.intseq]p1:
2857 // T shall be an integer type.
2858 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2859 SemaRef.Diag(TemplateArgs[1].getLocation(),
2860 diag::err_integer_sequence_integral_element_type);
2861 return QualType();
2862 }
2863
2864 // C++14 [inteseq.make]p1:
2865 // If N is negative the program is ill-formed.
2866 TemplateArgument NumArgsArg = Converted[2];
2867 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2868 if (NumArgs < 0) {
2869 SemaRef.Diag(TemplateArgs[2].getLocation(),
2870 diag::err_integer_sequence_negative_length);
2871 return QualType();
2872 }
2873
2874 QualType ArgTy = NumArgsArg.getIntegralType();
2875 TemplateArgumentListInfo SyntheticTemplateArgs;
2876 // The type argument gets reused as the first template argument in the
2877 // synthetic template argument list.
2878 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2879 // Expand N into 0 ... N-1.
2880 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2881 I < NumArgs; ++I) {
2882 TemplateArgument TA(Context, I, ArgTy);
2883 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2884 TA, ArgTy, TemplateArgs[2].getLocation()));
2885 }
2886 // The first template argument will be reused as the template decl that
2887 // our synthetic template arguments will be applied to.
2888 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2889 TemplateLoc, SyntheticTemplateArgs);
2890 }
2891
2892 case BTK__type_pack_element:
2893 // Specializations of
2894 // __type_pack_element<Index, T_1, ..., T_N>
2895 // are treated like T_Index.
2896 assert(Converted.size() == 2 &&(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2897, __extension__ __PRETTY_FUNCTION__))
2897 "__type_pack_element should be given an index and a parameter pack")(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2897, __extension__ __PRETTY_FUNCTION__))
;
2898
2899 // If the Index is out of bounds, the program is ill-formed.
2900 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2901 llvm::APSInt Index = IndexArg.getAsIntegral();
2902 assert(Index >= 0 && "the index used with __type_pack_element should be of "(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? 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\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2903, __extension__ __PRETTY_FUNCTION__))
2903 "type std::size_t, and hence be non-negative")(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? 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\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2903, __extension__ __PRETTY_FUNCTION__))
;
2904 if (Index >= Ts.pack_size()) {
2905 SemaRef.Diag(TemplateArgs[0].getLocation(),
2906 diag::err_type_pack_element_out_of_bounds);
2907 return QualType();
2908 }
2909
2910 // We simply return the type at index `Index`.
2911 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2912 return Nth->getAsType();
2913 }
2914 llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2914)
;
2915}
2916
2917/// Determine whether this alias template is "enable_if_t".
2918static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2919 return AliasTemplate->getName().equals("enable_if_t");
2920}
2921
2922/// Collect all of the separable terms in the given condition, which
2923/// might be a conjunction.
2924///
2925/// FIXME: The right answer is to convert the logical expression into
2926/// disjunctive normal form, so we can find the first failed term
2927/// within each possible clause.
2928static void collectConjunctionTerms(Expr *Clause,
2929 SmallVectorImpl<Expr *> &Terms) {
2930 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2931 if (BinOp->getOpcode() == BO_LAnd) {
2932 collectConjunctionTerms(BinOp->getLHS(), Terms);
2933 collectConjunctionTerms(BinOp->getRHS(), Terms);
2934 }
2935
2936 return;
2937 }
2938
2939 Terms.push_back(Clause);
2940}
2941
2942// The ranges-v3 library uses an odd pattern of a top-level "||" with
2943// a left-hand side that is value-dependent but never true. Identify
2944// the idiom and ignore that term.
2945static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
2946 // Top-level '||'.
2947 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2948 if (!BinOp) return Cond;
2949
2950 if (BinOp->getOpcode() != BO_LOr) return Cond;
2951
2952 // With an inner '==' that has a literal on the right-hand side.
2953 Expr *LHS = BinOp->getLHS();
2954 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
2955 if (!InnerBinOp) return Cond;
2956
2957 if (InnerBinOp->getOpcode() != BO_EQ ||
2958 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2959 return Cond;
2960
2961 // If the inner binary operation came from a macro expansion named
2962 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2963 // of the '||', which is the real, user-provided condition.
2964 SourceLocation Loc = InnerBinOp->getExprLoc();
2965 if (!Loc.isMacroID()) return Cond;
2966
2967 StringRef MacroName = PP.getImmediateMacroName(Loc);
2968 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2969 return BinOp->getRHS();
2970
2971 return Cond;
2972}
2973
2974std::pair<Expr *, std::string>
2975Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
2976 Cond = lookThroughRangesV3Condition(PP, Cond);
2977
2978 // Separate out all of the terms in a conjunction.
2979 SmallVector<Expr *, 4> Terms;
2980 collectConjunctionTerms(Cond, Terms);
2981
2982 // Determine which term failed.
2983 Expr *FailedCond = nullptr;
2984 for (Expr *Term : Terms) {
2985 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
2986
2987 // Literals are uninteresting.
2988 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
2989 isa<IntegerLiteral>(TermAsWritten))
2990 continue;
2991
2992 // The initialization of the parameter from the argument is
2993 // a constant-evaluated context.
2994 EnterExpressionEvaluationContext ConstantEvaluated(
2995 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2996
2997 bool Succeeded;
2998 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
2999 !Succeeded) {
3000 FailedCond = TermAsWritten;
3001 break;
3002 }
3003 }
3004
3005 if (!FailedCond) {
3006 if (!AllowTopLevelCond)
3007 return { nullptr, "" };
3008
3009 FailedCond = Cond->IgnoreParenImpCasts();
3010 }
3011
3012 std::string Description;
3013 {
3014 llvm::raw_string_ostream Out(Description);
3015 FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
3016 }
3017 return { FailedCond, Description };
3018}
3019
3020QualType Sema::CheckTemplateIdType(TemplateName Name,
3021 SourceLocation TemplateLoc,
3022 TemplateArgumentListInfo &TemplateArgs) {
3023 DependentTemplateName *DTN
3024 = Name.getUnderlying().getAsDependentTemplateName();
3025 if (DTN && DTN->isIdentifier())
3026 // When building a template-id where the template-name is dependent,
3027 // assume the template is a type template. Either our assumption is
3028 // correct, or the code is ill-formed and will be diagnosed when the
3029 // dependent name is substituted.
3030 return Context.getDependentTemplateSpecializationType(ETK_None,
3031 DTN->getQualifier(),
3032 DTN->getIdentifier(),
3033 TemplateArgs);
3034
3035 TemplateDecl *Template = Name.getAsTemplateDecl();
3036 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3037 isa<VarTemplateDecl>(Template)) {
3038 // We might have a substituted template template parameter pack. If so,
3039 // build a template specialization type for it.
3040 if (Name.getAsSubstTemplateTemplateParmPack())
3041 return Context.getTemplateSpecializationType(Name, TemplateArgs);
3042
3043 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3044 << Name;
3045 NoteAllFoundTemplates(Name);
3046 return QualType();
3047 }
3048
3049 // Check that the template argument list is well-formed for this
3050 // template.
3051 SmallVector<TemplateArgument, 4> Converted;
3052 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3053 false, Converted))
3054 return QualType();
3055
3056 QualType CanonType;
3057
3058 bool InstantiationDependent = false;
3059 if (TypeAliasTemplateDecl *AliasTemplate =
3060 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3061 // Find the canonical type for this type alias template specialization.
3062 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3063 if (Pattern->isInvalidDecl())
3064 return QualType();
3065
3066 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3067 Converted);
3068
3069 // Only substitute for the innermost template argument list.
3070 MultiLevelTemplateArgumentList TemplateArgLists;
3071 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3072 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3073 for (unsigned I = 0; I < Depth; ++I)
3074 TemplateArgLists.addOuterTemplateArguments(None);
3075
3076 LocalInstantiationScope Scope(*this);
3077 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3078 if (Inst.isInvalid())
3079 return QualType();
3080
3081 CanonType = SubstType(Pattern->getUnderlyingType(),
3082 TemplateArgLists, AliasTemplate->getLocation(),
3083 AliasTemplate->getDeclName());
3084 if (CanonType.isNull()) {
3085 // If this was enable_if and we failed to find the nested type
3086 // within enable_if in a SFINAE context, dig out the specific
3087 // enable_if condition that failed and present that instead.
3088 if (isEnableIfAliasTemplate(AliasTemplate)) {
3089 if (auto DeductionInfo = isSFINAEContext()) {
3090 if (*DeductionInfo &&
3091 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3092 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3093 diag::err_typename_nested_not_found_enable_if &&
3094 TemplateArgs[0].getArgument().getKind()
3095 == TemplateArgument::Expression) {
3096 Expr *FailedCond;
3097 std::string FailedDescription;
3098 std::tie(FailedCond, FailedDescription) =
3099 findFailedBooleanCondition(
3100 TemplateArgs[0].getSourceExpression(),
3101 /*AllowTopLevelCond=*/true);
3102
3103 // Remove the old SFINAE diagnostic.
3104 PartialDiagnosticAt OldDiag =
3105 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3106 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3107
3108 // Add a new SFINAE diagnostic specifying which condition
3109 // failed.
3110 (*DeductionInfo)->addSFINAEDiagnostic(
3111 OldDiag.first,
3112 PDiag(diag::err_typename_nested_not_found_requirement)
3113 << FailedDescription
3114 << FailedCond->getSourceRange());
3115 }
3116 }
3117 }
3118
3119 return QualType();
3120 }
3121 } else if (Name.isDependent() ||
3122 TemplateSpecializationType::anyDependentTemplateArguments(
3123 TemplateArgs, InstantiationDependent)) {
3124 // This class template specialization is a dependent
3125 // type. Therefore, its canonical type is another class template
3126 // specialization type that contains all of the converted
3127 // arguments in canonical form. This ensures that, e.g., A<T> and
3128 // A<T, T> have identical types when A is declared as:
3129 //
3130 // template<typename T, typename U = T> struct A;
3131 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3132
3133 // This might work out to be a current instantiation, in which
3134 // case the canonical type needs to be the InjectedClassNameType.
3135 //
3136 // TODO: in theory this could be a simple hashtable lookup; most
3137 // changes to CurContext don't change the set of current
3138 // instantiations.
3139 if (isa<ClassTemplateDecl>(Template)) {
3140 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3141 // If we get out to a namespace, we're done.
3142 if (Ctx->isFileContext()) break;
3143
3144 // If this isn't a record, keep looking.
3145 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3146 if (!Record) continue;
3147
3148 // Look for one of the two cases with InjectedClassNameTypes
3149 // and check whether it's the same template.
3150 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3151 !Record->getDescribedClassTemplate())
3152 continue;
3153
3154 // Fetch the injected class name type and check whether its
3155 // injected type is equal to the type we just built.
3156 QualType ICNT = Context.getTypeDeclType(Record);
3157 QualType Injected = cast<InjectedClassNameType>(ICNT)
3158 ->getInjectedSpecializationType();
3159
3160 if (CanonType != Injected->getCanonicalTypeInternal())
3161 continue;
3162
3163 // If so, the canonical type of this TST is the injected
3164 // class name type of the record we just found.
3165 assert(ICNT.isCanonical())(static_cast <bool> (ICNT.isCanonical()) ? void (0) : __assert_fail
("ICNT.isCanonical()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3165, __extension__ __PRETTY_FUNCTION__))
;
3166 CanonType = ICNT;
3167 break;
3168 }
3169 }
3170 } else if (ClassTemplateDecl *ClassTemplate
3171 = dyn_cast<ClassTemplateDecl>(Template)) {
3172 // Find the class template specialization declaration that
3173 // corresponds to these arguments.
3174 void *InsertPos = nullptr;
3175 ClassTemplateSpecializationDecl *Decl
3176 = ClassTemplate->findSpecialization(Converted, InsertPos);
3177 if (!Decl) {
3178 // This is the first time we have referenced this class template
3179 // specialization. Create the canonical declaration and add it to
3180 // the set of specializations.
3181 Decl = ClassTemplateSpecializationDecl::Create(Context,
3182 ClassTemplate->getTemplatedDecl()->getTagKind(),
3183 ClassTemplate->getDeclContext(),
3184 ClassTemplate->getTemplatedDecl()->getLocStart(),
3185 ClassTemplate->getLocation(),
3186 ClassTemplate,
3187 Converted, nullptr);
3188 ClassTemplate->AddSpecialization(Decl, InsertPos);
3189 if (ClassTemplate->isOutOfLine())
3190 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3191 }
3192
3193 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3194 MultiLevelTemplateArgumentList TemplateArgLists;
3195 TemplateArgLists.addOuterTemplateArguments(Converted);
3196 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3197 Decl);
3198 }
3199
3200 // Diagnose uses of this specialization.
3201 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3202
3203 CanonType = Context.getTypeDeclType(Decl);
3204 assert(isa<RecordType>(CanonType) &&(static_cast <bool> (isa<RecordType>(CanonType) &&
"type of non-dependent specialization is not a RecordType") ?
void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3205, __extension__ __PRETTY_FUNCTION__))
3205 "type of non-dependent specialization is not a RecordType")(static_cast <bool> (isa<RecordType>(CanonType) &&
"type of non-dependent specialization is not a RecordType") ?
void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3205, __extension__ __PRETTY_FUNCTION__))
;
3206 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3207 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3208 TemplateArgs);
3209 }
3210
3211 // Build the fully-sugared type for this class template
3212 // specialization, which refers back to the class template
3213 // specialization we created or found.
3214 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3215}
3216
3217TypeResult
3218Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3219 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3220 SourceLocation TemplateIILoc,
3221 SourceLocation LAngleLoc,
3222 ASTTemplateArgsPtr TemplateArgsIn,
3223 SourceLocation RAngleLoc,
3224 bool IsCtorOrDtorName, bool IsClassName) {
3225 if (SS.isInvalid())
3226 return true;
3227
3228 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3229 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3230
3231 // C++ [temp.res]p3:
3232 // A qualified-id that refers to a type and in which the
3233 // nested-name-specifier depends on a template-parameter (14.6.2)
3234 // shall be prefixed by the keyword typename to indicate that the
3235 // qualified-id denotes a type, forming an
3236 // elaborated-type-specifier (7.1.5.3).
3237 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3238 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3239 << SS.getScopeRep() << TemplateII->getName();
3240 // Recover as if 'typename' were specified.
3241 // FIXME: This is not quite correct recovery as we don't transform SS
3242 // into the corresponding dependent form (and we don't diagnose missing
3243 // 'template' keywords within SS as a result).
3244 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3245 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3246 TemplateArgsIn, RAngleLoc);
3247 }
3248
3249 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3250 // it's not actually allowed to be used as a type in most cases. Because
3251 // we annotate it before we know whether it's valid, we have to check for
3252 // this case here.
3253 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3254 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3255 Diag(TemplateIILoc,
3256 TemplateKWLoc.isInvalid()
3257 ? diag::err_out_of_line_qualified_id_type_names_constructor
3258 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3259 << TemplateII << 0 /*injected-class-name used as template name*/
3260 << 1 /*if any keyword was present, it was 'template'*/;
3261 }
3262 }
3263
3264 TemplateName Template = TemplateD.get();
3265
3266 // Translate the parser's template argument list in our AST format.
3267 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3268 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3269
3270 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3271 QualType T
3272 = Context.getDependentTemplateSpecializationType(ETK_None,
3273 DTN->getQualifier(),
3274 DTN->getIdentifier(),
3275 TemplateArgs);
3276 // Build type-source information.
3277 TypeLocBuilder TLB;
3278 DependentTemplateSpecializationTypeLoc SpecTL
3279 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3280 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3281 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3282 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3283 SpecTL.setTemplateNameLoc(TemplateIILoc);
3284 SpecTL.setLAngleLoc(LAngleLoc);
3285 SpecTL.setRAngleLoc(RAngleLoc);
3286 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3287 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3288 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3289 }
3290
3291 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3292 if (Result.isNull())
3293 return true;
3294
3295 // Build type-source information.
3296 TypeLocBuilder TLB;
3297 TemplateSpecializationTypeLoc SpecTL
3298 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3299 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3300 SpecTL.setTemplateNameLoc(TemplateIILoc);
3301 SpecTL.setLAngleLoc(LAngleLoc);
3302 SpecTL.setRAngleLoc(RAngleLoc);
3303 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3304 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3305
3306 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3307 // constructor or destructor name (in such a case, the scope specifier
3308 // will be attached to the enclosing Decl or Expr node).
3309 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3310 // Create an elaborated-type-specifier containing the nested-name-specifier.
3311 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3312 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3313 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3314 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3315 }
3316
3317 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3318}
3319
3320TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3321 TypeSpecifierType TagSpec,
3322 SourceLocation TagLoc,
3323 CXXScopeSpec &SS,
3324 SourceLocation TemplateKWLoc,
3325 TemplateTy TemplateD,
3326 SourceLocation TemplateLoc,
3327 SourceLocation LAngleLoc,
3328 ASTTemplateArgsPtr TemplateArgsIn,
3329 SourceLocation RAngleLoc) {
3330 TemplateName Template = TemplateD.get();
3331
3332 // Translate the parser's template argument list in our AST format.
3333 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3334 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3335
3336 // Determine the tag kind
3337 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3338 ElaboratedTypeKeyword Keyword
3339 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3340
3341 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3342 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3343 DTN->getQualifier(),
3344 DTN->getIdentifier(),
3345 TemplateArgs);
3346
3347 // Build type-source information.
3348 TypeLocBuilder TLB;
3349 DependentTemplateSpecializationTypeLoc SpecTL
3350 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3351 SpecTL.setElaboratedKeywordLoc(TagLoc);
3352 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3353 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3354 SpecTL.setTemplateNameLoc(TemplateLoc);
3355 SpecTL.setLAngleLoc(LAngleLoc);
3356 SpecTL.setRAngleLoc(RAngleLoc);
3357 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3358 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3359 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3360 }
3361
3362 if (TypeAliasTemplateDecl *TAT =
3363 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3364 // C++0x [dcl.type.elab]p2:
3365 // If the identifier resolves to a typedef-name or the simple-template-id
3366 // resolves to an alias template specialization, the
3367 // elaborated-type-specifier is ill-formed.
3368 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3369 << TAT << NTK_TypeAliasTemplate << TagKind;
3370 Diag(TAT->getLocation(), diag::note_declared_at);
3371 }
3372
3373 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3374 if (Result.isNull())
3375 return TypeResult(true);
3376
3377 // Check the tag kind
3378 if (const RecordType *RT = Result->getAs<RecordType>()) {
3379 RecordDecl *D = RT->getDecl();
3380
3381 IdentifierInfo *Id = D->getIdentifier();
3382 assert(Id && "templated class must have an identifier")(static_cast <bool> (Id && "templated class must have an identifier"
) ? void (0) : __assert_fail ("Id && \"templated class must have an identifier\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3382, __extension__ __PRETTY_FUNCTION__))
;
3383
3384 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3385 TagLoc, Id)) {
3386 Diag(TagLoc, diag::err_use_with_wrong_tag)
3387 << Result
3388 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3389 Diag(D->getLocation(), diag::note_previous_use);
3390 }
3391 }
3392
3393 // Provide source-location information for the template specialization.
3394 TypeLocBuilder TLB;
3395 TemplateSpecializationTypeLoc SpecTL
3396 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3397 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3398 SpecTL.setTemplateNameLoc(TemplateLoc);
3399 SpecTL.setLAngleLoc(LAngleLoc);
3400 SpecTL.setRAngleLoc(RAngleLoc);
3401 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3402 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3403
3404 // Construct an elaborated type containing the nested-name-specifier (if any)
3405 // and tag keyword.
3406 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3407 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3408 ElabTL.setElaboratedKeywordLoc(TagLoc);
3409 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3410 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3411}
3412
3413static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3414 NamedDecl *PrevDecl,
3415 SourceLocation Loc,
3416 bool IsPartialSpecialization);
3417
3418static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3419
3420static bool isTemplateArgumentTemplateParameter(
3421 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3422 switch (Arg.getKind()) {
3423 case TemplateArgument::Null:
3424 case TemplateArgument::NullPtr:
3425 case TemplateArgument::Integral:
3426 case TemplateArgument::Declaration:
3427 case TemplateArgument::Pack:
3428 case TemplateArgument::TemplateExpansion:
3429 return false;
3430
3431 case TemplateArgument::Type: {
3432 QualType Type = Arg.getAsType();
3433 const TemplateTypeParmType *TPT =
3434 Arg.getAsType()->getAs<TemplateTypeParmType>();
3435 return TPT && !Type.hasQualifiers() &&
3436 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3437 }
3438
3439 case TemplateArgument::Expression: {
3440 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3441 if (!DRE || !DRE->getDecl())
3442 return false;
3443 const NonTypeTemplateParmDecl *NTTP =
3444 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3445 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3446 }
3447
3448 case TemplateArgument::Template:
3449 const TemplateTemplateParmDecl *TTP =
3450 dyn_cast_or_null<TemplateTemplateParmDecl>(
3451 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3452 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3453 }
3454 llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3454)
;
3455}
3456
3457static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3458 ArrayRef<TemplateArgument> Args) {
3459 if (Params->size() != Args.size())
3460 return false;
3461
3462 unsigned Depth = Params->getDepth();
3463
3464 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3465 TemplateArgument Arg = Args[I];
3466
3467 // If the parameter is a pack expansion, the argument must be a pack
3468 // whose only element is a pack expansion.
3469 if (Params->getParam(I)->isParameterPack()) {
3470 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3471 !Arg.pack_begin()->isPackExpansion())
3472 return false;
3473 Arg = Arg.pack_begin()->getPackExpansionPattern();
3474 }
3475
3476 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3477 return false;
3478 }
3479
3480 return true;
3481}
3482
3483/// Convert the parser's template argument list representation into our form.
3484static TemplateArgumentListInfo
3485makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3486 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3487 TemplateId.RAngleLoc);
3488 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3489 TemplateId.NumArgs);
3490 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3491 return TemplateArgs;
3492}
3493
3494template<typename PartialSpecDecl>
3495static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3496 if (Partial->getDeclContext()->isDependentContext())
3497 return;
3498
3499 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3500 // for non-substitution-failure issues?
3501 TemplateDeductionInfo Info(Partial->getLocation());
3502 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3503 return;
3504
3505 auto *Template = Partial->getSpecializedTemplate();
3506 S.Diag(Partial->getLocation(),
3507 diag::ext_partial_spec_not_more_specialized_than_primary)
3508 << isa<VarTemplateDecl>(Template);
3509
3510 if (Info.hasSFINAEDiagnostic()) {
3511 PartialDiagnosticAt Diag = {SourceLocation(),
3512 PartialDiagnostic::NullDiagnostic()};
3513 Info.takeSFINAEDiagnostic(Diag);
3514 SmallString<128> SFINAEArgString;
3515 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3516 S.Diag(Diag.first,
3517 diag::note_partial_spec_not_more_specialized_than_primary)
3518 << SFINAEArgString;
3519 }
3520
3521 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3522}
3523
3524static void
3525noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3526 const llvm::SmallBitVector &DeducibleParams) {
3527 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3528 if (!DeducibleParams[I]) {
3529 NamedDecl *Param = TemplateParams->getParam(I);
3530 if (Param->getDeclName())
3531 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3532 << Param->getDeclName();
3533 else
3534 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3535 << "(anonymous)";
3536 }
3537 }
3538}
3539
3540
3541template<typename PartialSpecDecl>
3542static void checkTemplatePartialSpecialization(Sema &S,
3543 PartialSpecDecl *Partial) {
3544 // C++1z [temp.class.spec]p8: (DR1495)
3545 // - The specialization shall be more specialized than the primary
3546 // template (14.5.5.2).
3547 checkMoreSpecializedThanPrimary(S, Partial);
3548
3549 // C++ [temp.class.spec]p8: (DR1315)
3550 // - Each template-parameter shall appear at least once in the
3551 // template-id outside a non-deduced context.
3552 // C++1z [temp.class.spec.match]p3 (P0127R2)
3553 // If the template arguments of a partial specialization cannot be
3554 // deduced because of the structure of its template-parameter-list
3555 // and the template-id, the program is ill-formed.
3556 auto *TemplateParams = Partial->getTemplateParameters();
3557 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3558 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3559 TemplateParams->getDepth(), DeducibleParams);
3560
3561 if (!DeducibleParams.all()) {
3562 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3563 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3564 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3565 << (NumNonDeducible > 1)
3566 << SourceRange(Partial->getLocation(),
3567 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3568 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3569 }
3570}
3571
3572void Sema::CheckTemplatePartialSpecialization(
3573 ClassTemplatePartialSpecializationDecl *Partial) {
3574 checkTemplatePartialSpecialization(*this, Partial);
3575}
3576
3577void Sema::CheckTemplatePartialSpecialization(
3578 VarTemplatePartialSpecializationDecl *Partial) {
3579 checkTemplatePartialSpecialization(*this, Partial);
3580}
3581
3582void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3583 // C++1z [temp.param]p11:
3584 // A template parameter of a deduction guide template that does not have a
3585 // default-argument shall be deducible from the parameter-type-list of the
3586 // deduction guide template.
3587 auto *TemplateParams = TD->getTemplateParameters();
3588 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3589 MarkDeducedTemplateParameters(TD, DeducibleParams);
3590 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3591 // A parameter pack is deducible (to an empty pack).
3592 auto *Param = TemplateParams->getParam(I);
3593 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3594 DeducibleParams[I] = true;
3595 }
3596
3597 if (!DeducibleParams.all()) {
3598 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3599 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3600 << (NumNonDeducible > 1);
3601 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3602 }
3603}
3604
3605DeclResult Sema::ActOnVarTemplateSpecialization(
3606 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3607 TemplateParameterList *TemplateParams, StorageClass SC,
3608 bool IsPartialSpecialization) {
3609 // D must be variable template id.
3610 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind
::IK_TemplateId && "Variable template specialization is declared with a template it."
) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3611, __extension__ __PRETTY_FUNCTION__))
3611 "Variable template specialization is declared with a template it.")(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind
::IK_TemplateId && "Variable template specialization is declared with a template it."
) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3611, __extension__ __PRETTY_FUNCTION__))
;
3612
3613 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3614 TemplateArgumentListInfo TemplateArgs =
3615 makeTemplateArgumentListInfo(*this, *TemplateId);
3616 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3617 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3618 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3619
3620 TemplateName Name = TemplateId->Template.get();
3621
3622 // The template-id must name a variable template.
3623 VarTemplateDecl *VarTemplate =
3624 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3625 if (!VarTemplate) {
3626 NamedDecl *FnTemplate;
3627 if (auto *OTS = Name.getAsOverloadedTemplate())
3628 FnTemplate = *OTS->begin();
3629 else
3630 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3631 if (FnTemplate)
3632 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3633 << FnTemplate->getDeclName();
3634 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3635 << IsPartialSpecialization;
3636 }
3637
3638 // Check for unexpanded parameter packs in any of the template arguments.
3639 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3640 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3641 UPPC_PartialSpecialization))
3642 return true;
3643
3644 // Check that the template argument list is well-formed for this
3645 // template.
3646 SmallVector<TemplateArgument, 4> Converted;
3647 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3648 false, Converted))
3649 return true;
3650
3651 // Find the variable template (partial) specialization declaration that
3652 // corresponds to these arguments.
3653 if (IsPartialSpecialization) {
3654 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3655 TemplateArgs.size(), Converted))
3656 return true;
3657
3658 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3659 // also do them during instantiation.
3660 bool InstantiationDependent;
3661 if (!Name.isDependent() &&
3662 !TemplateSpecializationType::anyDependentTemplateArguments(
3663 TemplateArgs.arguments(),
3664 InstantiationDependent)) {
3665 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3666 << VarTemplate->getDeclName();
3667 IsPartialSpecialization = false;
3668 }
3669
3670 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3671 Converted)) {
3672 // C++ [temp.class.spec]p9b3:
3673 //
3674 // -- The argument list of the specialization shall not be identical
3675 // to the implicit argument list of the primary template.
3676 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3677 << /*variable template*/ 1
3678 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3679 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3680 // FIXME: Recover from this by treating the declaration as a redeclaration
3681 // of the primary template.
3682 return true;
3683 }
3684 }
3685
3686 void *InsertPos = nullptr;
3687 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3688
3689 if (IsPartialSpecialization)
3690 // FIXME: Template parameter list matters too
3691 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3692 else
3693 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3694
3695 VarTemplateSpecializationDecl *Specialization = nullptr;
3696
3697 // Check whether we can declare a variable template specialization in
3698 // the current scope.
3699 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3700 TemplateNameLoc,
3701 IsPartialSpecialization))
3702 return true;
3703
3704 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3705 // Since the only prior variable template specialization with these
3706 // arguments was referenced but not declared, reuse that
3707 // declaration node as our own, updating its source location and
3708 // the list of outer template parameters to reflect our new declaration.
3709 Specialization = PrevDecl;
3710 Specialization->setLocation(TemplateNameLoc);
3711 PrevDecl = nullptr;
3712 } else if (IsPartialSpecialization) {
3713 // Create a new class template partial specialization declaration node.
3714 VarTemplatePartialSpecializationDecl *PrevPartial =
3715 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3716 VarTemplatePartialSpecializationDecl *Partial =
3717 VarTemplatePartialSpecializationDecl::Create(
3718 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3719 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3720 Converted, TemplateArgs);
3721
3722 if (!PrevPartial)
3723 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3724 Specialization = Partial;
3725
3726 // If we are providing an explicit specialization of a member variable
3727 // template specialization, make a note of that.
3728 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3729 PrevPartial->setMemberSpecialization();
3730
3731 CheckTemplatePartialSpecialization(Partial);
3732 } else {
3733 // Create a new class template specialization declaration node for
3734 // this explicit specialization or friend declaration.
3735 Specialization = VarTemplateSpecializationDecl::Create(
3736 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3737 VarTemplate, DI->getType(), DI, SC, Converted);
3738 Specialization->setTemplateArgsInfo(TemplateArgs);
3739
3740 if (!PrevDecl)
3741 VarTemplate->AddSpecialization(Specialization, InsertPos);
3742 }
3743
3744 // C++ [temp.expl.spec]p6:
3745 // If a template, a member template or the member of a class template is
3746 // explicitly specialized then that specialization shall be declared
3747 // before the first use of that specialization that would cause an implicit
3748 // instantiation to take place, in every translation unit in which such a
3749 // use occurs; no diagnostic is required.
3750 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3751 bool Okay = false;
3752 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3753 // Is there any previous explicit specialization declaration?
3754 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3755 Okay = true;
3756 break;
3757 }
3758 }
3759
3760 if (!Okay) {
3761 SourceRange Range(TemplateNameLoc, RAngleLoc);
3762 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3763 << Name << Range;
3764
3765 Diag(PrevDecl->getPointOfInstantiation(),
3766 diag::note_instantiation_required_here)
3767 << (PrevDecl->getTemplateSpecializationKind() !=
3768 TSK_ImplicitInstantiation);
3769 return true;
3770 }
3771 }
3772
3773 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3774 Specialization->setLexicalDeclContext(CurContext);
3775
3776 // Add the specialization into its lexical context, so that it can
3777 // be seen when iterating through the list of declarations in that
3778 // context. However, specializations are not found by name lookup.
3779 CurContext->addDecl(Specialization);
3780
3781 // Note that this is an explicit specialization.
3782 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3783
3784 if (PrevDecl) {
3785 // Check that this isn't a redefinition of this specialization,
3786 // merging with previous declarations.
3787 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3788 forRedeclarationInCurContext());
3789 PrevSpec.addDecl(PrevDecl);
3790 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3791 } else if (Specialization->isStaticDataMember() &&
3792 Specialization->isOutOfLine()) {
3793 Specialization->setAccess(VarTemplate->getAccess());
3794 }
3795
3796 // Link instantiations of static data members back to the template from
3797 // which they were instantiated.
3798 if (Specialization->isStaticDataMember())
3799 Specialization->setInstantiationOfStaticDataMember(
3800 VarTemplate->getTemplatedDecl(),
3801 Specialization->getSpecializationKind());
3802
3803 return Specialization;
3804}
3805
3806namespace {
3807/// \brief A partial specialization whose template arguments have matched
3808/// a given template-id.
3809struct PartialSpecMatchResult {
3810 VarTemplatePartialSpecializationDecl *Partial;
3811 TemplateArgumentList *Args;
3812};
3813} // end anonymous namespace
3814
3815DeclResult
3816Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3817 SourceLocation TemplateNameLoc,
3818 const TemplateArgumentListInfo &TemplateArgs) {
3819 assert(Template && "A variable template id without template?")(static_cast <bool> (Template && "A variable template id without template?"
) ? void (0) : __assert_fail ("Template && \"A variable template id without template?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3819, __extension__ __PRETTY_FUNCTION__))
;
3820
3821 // Check that the template argument list is well-formed for this template.
3822 SmallVector<TemplateArgument, 4> Converted;
3823 if (CheckTemplateArgumentList(
24
Taking false branch
3824 Template, TemplateNameLoc,
3825 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3826 Converted))
3827 return true;
3828
3829 // Find the variable template specialization declaration that
3830 // corresponds to these arguments.
3831 void *InsertPos = nullptr;
3832 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
25
Assuming 'Spec' is null
26
Taking false branch
3833 Converted, InsertPos)) {
3834 checkSpecializationVisibility(TemplateNameLoc, Spec);
3835 // If we already have a variable template specialization, return it.
3836 return Spec;
3837 }
3838
3839 // This is the first time we have referenced this variable template
3840 // specialization. Create the canonical declaration and add it to
3841 // the set of specializations, based on the closest partial specialization
3842 // that it represents. That is,
3843 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3844 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3845 Converted);
3846 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3847 bool AmbiguousPartialSpec = false;
3848 typedef PartialSpecMatchResult MatchResult;
3849 SmallVector<MatchResult, 4> Matched;
3850 SourceLocation PointOfInstantiation = TemplateNameLoc;
3851 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3852 /*ForTakingAddress=*/false);
3853
3854 // 1. Attempt to find the closest partial specialization that this
3855 // specializes, if any.
3856 // If any of the template arguments is dependent, then this is probably
3857 // a placeholder for an incomplete declarative context; which must be
3858 // complete by instantiation time. Thus, do not search through the partial
3859 // specializations yet.
3860 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3861 // Perhaps better after unification of DeduceTemplateArguments() and
3862 // getMoreSpecializedPartialSpecialization().
3863 bool InstantiationDependent = false;
3864 if (!TemplateSpecializationType::anyDependentTemplateArguments(
27
Assuming the condition is false
28
Taking false branch
3865 TemplateArgs, InstantiationDependent)) {
3866
3867 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3868 Template->getPartialSpecializations(PartialSpecs);
3869
3870 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3871 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3872 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3873
3874 if (TemplateDeductionResult Result =
3875 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3876 // Store the failed-deduction information for use in diagnostics, later.
3877 // TODO: Actually use the failed-deduction info?
3878 FailedCandidates.addCandidate().set(
3879 DeclAccessPair::make(Template, AS_public), Partial,
3880 MakeDeductionFailureInfo(Context, Result, Info));
3881 (void)Result;
3882 } else {
3883 Matched.push_back(PartialSpecMatchResult());
3884 Matched.back().Partial = Partial;
3885 Matched.back().Args = Info.take();
3886 }
3887 }
3888
3889 if (Matched.size() >= 1) {
3890 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3891 if (Matched.size() == 1) {
3892 // -- If exactly one matching specialization is found, the
3893 // instantiation is generated from that specialization.
3894 // We don't need to do anything for this.
3895 } else {
3896 // -- If more than one matching specialization is found, the
3897 // partial order rules (14.5.4.2) are used to determine
3898 // whether one of the specializations is more specialized
3899 // than the others. If none of the specializations is more
3900 // specialized than all of the other matching
3901 // specializations, then the use of the variable template is
3902 // ambiguous and the program is ill-formed.
3903 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3904 PEnd = Matched.end();
3905 P != PEnd; ++P) {
3906 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3907 PointOfInstantiation) ==
3908 P->Partial)
3909 Best = P;
3910 }
3911
3912 // Determine if the best partial specialization is more specialized than
3913 // the others.
3914 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3915 PEnd = Matched.end();
3916 P != PEnd; ++P) {
3917 if (P != Best && getMoreSpecializedPartialSpecialization(
3918 P->Partial, Best->Partial,
3919 PointOfInstantiation) != Best->Partial) {
3920 AmbiguousPartialSpec = true;
3921 break;
3922 }
3923 }
3924 }
3925
3926 // Instantiate using the best variable template partial specialization.
3927 InstantiationPattern = Best->Partial;
3928 InstantiationArgs = Best->Args;
3929 } else {
3930 // -- If no match is found, the instantiation is generated
3931 // from the primary template.
3932 // InstantiationPattern = Template->getTemplatedDecl();
3933 }
3934 }
3935
3936 // 2. Create the canonical declaration.
3937 // Note that we do not instantiate a definition until we see an odr-use
3938 // in DoMarkVarDeclReferenced().
3939 // FIXME: LateAttrs et al.?
3940 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3941 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3942 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3943 if (!Decl)
29
Assuming 'Decl' is non-null
30
Taking false branch
3944 return true;
3945
3946 if (AmbiguousPartialSpec) {
31
Taking false branch
3947 // Partial ordering did not produce a clear winner. Complain.
3948 Decl->setInvalidDecl();
3949 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3950 << Decl;
3951
3952 // Print the matching partial specializations.
3953 for (MatchResult P : Matched)
3954 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3955 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3956 *P.Args);
3957 return true;
3958 }
3959
3960 if (VarTemplatePartialSpecializationDecl *D =
32
Assuming 'D' is non-null
33
Taking true branch
3961 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3962 Decl->setInstantiationOf(D, InstantiationArgs);
34
Calling 'VarTemplateSpecializationDecl::setInstantiationOf'
3963
3964 checkSpecializationVisibility(TemplateNameLoc, Decl);
3965
3966 assert(Decl && "No variable template specialization?")(static_cast <bool> (Decl && "No variable template specialization?"
) ? void (0) : __assert_fail ("Decl && \"No variable template specialization?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3966, __extension__ __PRETTY_FUNCTION__))
;
3967 return Decl;
3968}
3969
3970ExprResult
3971Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3972 const DeclarationNameInfo &NameInfo,
3973 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3974 const TemplateArgumentListInfo *TemplateArgs) {
3975
3976 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3977 *TemplateArgs);
3978 if (Decl.isInvalid())
3979 return ExprError();
3980
3981 VarDecl *Var = cast<VarDecl>(Decl.get());
3982 if (!Var->getTemplateSpecializationKind())
3983 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3984 NameInfo.getLoc());
3985
3986 // Build an ordinary singleton decl ref.
3987 return BuildDeclarationNameExpr(SS, NameInfo, Var,
3988 /*FoundD=*/nullptr, TemplateArgs);
3989}
3990
3991ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
3992 SourceLocation TemplateKWLoc,
3993 LookupResult &R,
3994 bool RequiresADL,
3995 const TemplateArgumentListInfo *TemplateArgs) {
3996 // FIXME: Can we do any checking at this point? I guess we could check the
3997 // template arguments that we have against the template name, if the template
3998 // name refers to a single template. That's not a terribly common case,
3999 // though.
4000 // foo<int> could identify a single function unambiguously
4001 // This approach does NOT work, since f<int>(1);
4002 // gets resolved prior to resorting to overload resolution
4003 // i.e., template<class T> void f(double);
4004 // vs template<class T, class U> void f(U);
4005
4006 // These should be filtered out by our callers.
4007 assert(!R.empty() && "empty lookup results when building templateid")(static_cast <bool> (!R.empty() && "empty lookup results when building templateid"
) ? void (0) : __assert_fail ("!R.empty() && \"empty lookup results when building templateid\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4007, __extension__ __PRETTY_FUNCTION__))
;
4008 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")(static_cast <bool> (!R.isAmbiguous() && "ambiguous lookup when building templateid"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4008, __extension__ __PRETTY_FUNCTION__))
;
4009
4010 // In C++1y, check variable template ids.
4011 bool InstantiationDependent;
4012 if (R.getAsSingle<VarTemplateDecl>() &&
4013 !TemplateSpecializationType::anyDependentTemplateArguments(
4014 *TemplateArgs, InstantiationDependent)) {
4015 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4016 R.getAsSingle<VarTemplateDecl>(),
4017 TemplateKWLoc, TemplateArgs);
4018 }
4019
4020 // We don't want lookup warnings at this point.
4021 R.suppressDiagnostics();
4022
4023 UnresolvedLookupExpr *ULE
4024 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4025 SS.getWithLocInContext(Context),
4026 TemplateKWLoc,
4027 R.getLookupNameInfo(),
4028 RequiresADL, TemplateArgs,
4029 R.begin(), R.end());
4030
4031 return ULE;
4032}
4033
4034// We actually only call this from template instantiation.
4035ExprResult
4036Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4037 SourceLocation TemplateKWLoc,
4038 const DeclarationNameInfo &NameInfo,
4039 const TemplateArgumentListInfo *TemplateArgs) {
4040
4041 assert(TemplateArgs || TemplateKWLoc.isValid())(static_cast <bool> (TemplateArgs || TemplateKWLoc.isValid
()) ? void (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4041, __extension__ __PRETTY_FUNCTION__))
;
4042 DeclContext *DC;
4043 if (!(DC = computeDeclContext(SS, false)) ||
4044 DC->isDependentContext() ||
4045 RequireCompleteDeclContext(SS, DC))
4046 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4047
4048 bool MemberOfUnknownSpecialization;
4049 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4050 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
4051 MemberOfUnknownSpecialization);
4052
4053 if (R.isAmbiguous())
4054 return ExprError();
4055
4056 if (R.empty()) {
4057 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
4058 << NameInfo.getName() << SS.getRange();
4059 return ExprError();
4060 }
4061
4062 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4063 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4064 << SS.getScopeRep()
4065 << NameInfo.getName().getAsString() << SS.getRange();
4066 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4067 return ExprError();
4068 }
4069
4070 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4071}
4072
4073/// \brief Form a dependent template name.
4074///
4075/// This action forms a dependent template name given the template
4076/// name and its (presumably dependent) scope specifier. For
4077/// example, given "MetaFun::template apply", the scope specifier \p
4078/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4079/// of the "template" keyword, and "apply" is the \p Name.
4080TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4081 CXXScopeSpec &SS,
4082 SourceLocation TemplateKWLoc,
4083 UnqualifiedId &Name,
4084 ParsedType ObjectType,
4085 bool EnteringContext,
4086 TemplateTy &Result,
4087 bool AllowInjectedClassName) {
4088 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4089 Diag(TemplateKWLoc,
4090 getLangOpts().CPlusPlus11 ?
4091 diag::warn_cxx98_compat_template_outside_of_template :
4092 diag::ext_template_outside_of_template)
4093 << FixItHint::CreateRemoval(TemplateKWLoc);
4094
4095 DeclContext *LookupCtx = nullptr;
4096 if (SS.isSet())
4097 LookupCtx = computeDeclContext(SS, EnteringContext);
4098 if (!LookupCtx && ObjectType)
4099 LookupCtx = computeDeclContext(ObjectType.get());
4100 if (LookupCtx) {
4101 // C++0x [temp.names]p5:
4102 // If a name prefixed by the keyword template is not the name of
4103 // a template, the program is ill-formed. [Note: the keyword
4104 // template may not be applied to non-template members of class
4105 // templates. -end note ] [ Note: as is the case with the
4106 // typename prefix, the template prefix is allowed in cases
4107 // where it is not strictly necessary; i.e., when the
4108 // nested-name-specifier or the expression on the left of the ->
4109 // or . is not dependent on a template-parameter, or the use
4110 // does not appear in the scope of a template. -end note]
4111 //
4112 // Note: C++03 was more strict here, because it banned the use of
4113 // the "template" keyword prior to a template-name that was not a
4114 // dependent name. C++ DR468 relaxed this requirement (the
4115 // "template" keyword is now permitted). We follow the C++0x
4116 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4117 bool MemberOfUnknownSpecialization;
4118 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4119 ObjectType, EnteringContext, Result,
4120 MemberOfUnknownSpecialization);
4121 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4122 isa<CXXRecordDecl>(LookupCtx) &&
4123 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4124 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
4125 // This is a dependent template. Handle it below.
4126 } else if (TNK == TNK_Non_template) {
4127 Diag(Name.getLocStart(),
4128 diag::err_template_kw_refers_to_non_template)
4129 << GetNameFromUnqualifiedId(Name).getName()
4130 << Name.getSourceRange()
4131 << TemplateKWLoc;
4132 return TNK_Non_template;
4133 } else {
4134 // We found something; return it.
4135 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4136 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4137 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4138 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4139 // C++14 [class.qual]p2:
4140 // In a lookup in which function names are not ignored and the
4141 // nested-name-specifier nominates a class C, if the name specified
4142 // [...] is the injected-class-name of C, [...] the name is instead
4143 // considered to name the constructor
4144 //
4145 // We don't get here if naming the constructor would be valid, so we
4146 // just reject immediately and recover by treating the
4147 // injected-class-name as naming the template.
4148 Diag(Name.getLocStart(),
4149 diag::ext_out_of_line_qualified_id_type_names_constructor)
4150 << Name.Identifier << 0 /*injected-class-name used as template name*/
4151 << 1 /*'template' keyword was used*/;
4152 }
4153 return TNK;
4154 }
4155 }
4156
4157 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4158
4159 switch (Name.getKind()) {
4160 case UnqualifiedIdKind::IK_Identifier:
4161 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4162 Name.Identifier));
4163 return TNK_Dependent_template_name;
4164
4165 case UnqualifiedIdKind::IK_OperatorFunctionId:
4166 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4167 Name.OperatorFunctionId.Operator));
4168 return TNK_Function_template;
4169
4170 case UnqualifiedIdKind::IK_LiteralOperatorId:
4171 llvm_unreachable("literal operator id cannot have a dependent scope")::llvm::llvm_unreachable_internal("literal operator id cannot have a dependent scope"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4171)
;
4172
4173 default:
4174 break;
4175 }
4176
4177 Diag(Name.getLocStart(),
4178 diag::err_template_kw_refers_to_non_template)
4179 << GetNameFromUnqualifiedId(Name).getName()
4180 << Name.getSourceRange()
4181 << TemplateKWLoc;
4182 return TNK_Non_template;
4183}
4184
4185bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4186 TemplateArgumentLoc &AL,
4187 SmallVectorImpl<TemplateArgument> &Converted) {
4188 const TemplateArgument &Arg = AL.getArgument();
4189 QualType ArgType;
4190 TypeSourceInfo *TSI = nullptr;
4191
4192 // Check template type parameter.
4193 switch(Arg.getKind()) {
4194 case TemplateArgument::Type:
4195 // C++ [temp.arg.type]p1:
4196 // A template-argument for a template-parameter which is a
4197 // type shall be a type-id.
4198 ArgType = Arg.getAsType();
4199 TSI = AL.getTypeSourceInfo();
4200 break;
4201 case TemplateArgument::Template:
4202 case TemplateArgument::TemplateExpansion: {
4203 // We have a template type parameter but the template argument
4204 // is a template without any arguments.
4205 SourceRange SR = AL.getSourceRange();
4206 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4207 Diag(SR.getBegin(), diag::err_template_missing_args)
4208 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
4209 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4210 Diag(Decl->getLocation(), diag::note_template_decl_here);
4211
4212 return true;
4213 }
4214 case TemplateArgument::Expression: {
4215 // We have a template type parameter but the template argument is an
4216 // expression; see if maybe it is missing the "typename" keyword.
4217 CXXScopeSpec SS;
4218 DeclarationNameInfo NameInfo;
4219
4220 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4221 SS.Adopt(ArgExpr->getQualifierLoc());
4222 NameInfo = ArgExpr->getNameInfo();
4223 } else if (DependentScopeDeclRefExpr *ArgExpr =
4224 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4225 SS.Adopt(ArgExpr->getQualifierLoc());
4226 NameInfo = ArgExpr->getNameInfo();
4227 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4228 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4229 if (ArgExpr->isImplicitAccess()) {
4230 SS.Adopt(ArgExpr->getQualifierLoc());
4231 NameInfo = ArgExpr->getMemberNameInfo();
4232 }
4233 }
4234
4235 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4236 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4237 LookupParsedName(Result, CurScope, &SS);
4238
4239 if (Result.getAsSingle<TypeDecl>() ||
4240 Result.getResultKind() ==
4241 LookupResult::NotFoundInCurrentInstantiation) {
4242 // Suggest that the user add 'typename' before the NNS.
4243 SourceLocation Loc = AL.getSourceRange().getBegin();
4244 Diag(Loc, getLangOpts().MSVCCompat
4245 ? diag::ext_ms_template_type_arg_missing_typename
4246 : diag::err_template_arg_must_be_type_suggest)
4247 << FixItHint::CreateInsertion(Loc, "typename ");
4248 Diag(Param->getLocation(), diag::note_template_param_here);
4249
4250 // Recover by synthesizing a type using the location information that we
4251 // already have.
4252 ArgType =
4253 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4254 TypeLocBuilder TLB;
4255 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4256 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4257 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4258 TL.setNameLoc(NameInfo.getLoc());
4259 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4260
4261 // Overwrite our input TemplateArgumentLoc so that we can recover
4262 // properly.
4263 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4264 TemplateArgumentLocInfo(TSI));
4265
4266 break;
4267 }
4268 }
4269 // fallthrough
4270 LLVM_FALLTHROUGH[[clang::fallthrough]];
4271 }
4272 default: {
4273 // We have a template type parameter but the template argument
4274 // is not a type.
4275 SourceRange SR = AL.getSourceRange();
4276 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4277 Diag(Param->getLocation(), diag::note_template_param_here);
4278
4279 return true;
4280 }
4281 }
4282
4283 if (CheckTemplateArgument(Param, TSI))
4284 return true;
4285
4286 // Add the converted template type argument.
4287 ArgType = Context.getCanonicalType(ArgType);
4288
4289 // Objective-C ARC:
4290 // If an explicitly-specified template argument type is a lifetime type
4291 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4292 if (getLangOpts().ObjCAutoRefCount &&
4293 ArgType->isObjCLifetimeType() &&
4294 !ArgType.getObjCLifetime()) {
4295 Qualifiers Qs;
4296 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4297 ArgType = Context.getQualifiedType(ArgType, Qs);
4298 }
4299
4300 Converted.push_back(TemplateArgument(ArgType));
4301 return false;
4302}
4303
4304/// \brief Substitute template arguments into the default template argument for
4305/// the given template type parameter.
4306///
4307/// \param SemaRef the semantic analysis object for which we are performing
4308/// the substitution.
4309///
4310/// \param Template the template that we are synthesizing template arguments
4311/// for.
4312///
4313/// \param TemplateLoc the location of the template name that started the
4314/// template-id we are checking.
4315///
4316/// \param RAngleLoc the location of the right angle bracket ('>') that
4317/// terminates the template-id.
4318///
4319/// \param Param the template template parameter whose default we are
4320/// substituting into.
4321///
4322/// \param Converted the list of template arguments provided for template
4323/// parameters that precede \p Param in the template parameter list.
4324/// \returns the substituted template argument, or NULL if an error occurred.
4325static TypeSourceInfo *
4326SubstDefaultTemplateArgument(Sema &SemaRef,
4327 TemplateDecl *Template,
4328 SourceLocation TemplateLoc,
4329 SourceLocation RAngleLoc,
4330 TemplateTypeParmDecl *Param,
4331 SmallVectorImpl<TemplateArgument> &Converted) {
4332 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4333
4334 // If the argument type is dependent, instantiate it now based
4335 // on the previously-computed template arguments.
4336 if (ArgType->getType()->isDependentType()) {
4337 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4338 Param, Template, Converted,
4339 SourceRange(TemplateLoc, RAngleLoc));
4340 if (Inst.isInvalid())
4341 return nullptr;
4342
4343 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4344
4345 // Only substitute for the innermost template argument list.
4346 MultiLevelTemplateArgumentList TemplateArgLists;
4347 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4348 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4349 TemplateArgLists.addOuterTemplateArguments(None);
4350
4351 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4352 ArgType =
4353 SemaRef.SubstType(ArgType, TemplateArgLists,
4354 Param->getDefaultArgumentLoc(), Param->getDeclName());
4355 }
4356
4357 return ArgType;
4358}
4359
4360/// \brief Substitute template arguments into the default template argument for
4361/// the given non-type template parameter.
4362///
4363/// \param SemaRef the semantic analysis object for which we are performing
4364/// the substitution.
4365///
4366/// \param Template the template that we are synthesizing template arguments
4367/// for.
4368///
4369/// \param TemplateLoc the location of the template name that started the
4370/// template-id we are checking.
4371///
4372/// \param RAngleLoc the location of the right angle bracket ('>') that
4373/// terminates the template-id.
4374///
4375/// \param Param the non-type template parameter whose default we are
4376/// substituting into.
4377///
4378/// \param Converted the list of template arguments provided for template
4379/// parameters that precede \p Param in the template parameter list.
4380///
4381/// \returns the substituted template argument, or NULL if an error occurred.
4382static ExprResult
4383SubstDefaultTemplateArgument(Sema &SemaRef,
4384 TemplateDecl *Template,
4385 SourceLocation TemplateLoc,
4386 SourceLocation RAngleLoc,
4387 NonTypeTemplateParmDecl *Param,
4388 SmallVectorImpl<TemplateArgument> &Converted) {
4389 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4390 Param, Template, Converted,
4391 SourceRange(TemplateLoc, RAngleLoc));
4392 if (Inst.isInvalid())
4393 return ExprError();
4394
4395 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4396
4397 // Only substitute for the innermost template argument list.
4398 MultiLevelTemplateArgumentList TemplateArgLists;
4399 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4400 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4401 TemplateArgLists.addOuterTemplateArguments(None);
4402
4403 EnterExpressionEvaluationContext ConstantEvaluated(
4404 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4405 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4406}
4407
4408/// \brief Substitute template arguments into the default template argument for
4409/// the given template template parameter.
4410///
4411/// \param SemaRef the semantic analysis object for which we are performing
4412/// the substitution.
4413///
4414/// \param Template the template that we are synthesizing template arguments
4415/// for.
4416///
4417/// \param TemplateLoc the location of the template name that started the
4418/// template-id we are checking.
4419///
4420/// \param RAngleLoc the location of the right angle bracket ('>') that
4421/// terminates the template-id.
4422///
4423/// \param Param the template template parameter whose default we are
4424/// substituting into.
4425///
4426/// \param Converted the list of template arguments provided for template
4427/// parameters that precede \p Param in the template parameter list.
4428///
4429/// \param QualifierLoc Will be set to the nested-name-specifier (with
4430/// source-location information) that precedes the template name.
4431///
4432/// \returns the substituted template argument, or NULL if an error occurred.
4433static TemplateName
4434SubstDefaultTemplateArgument(Sema &SemaRef,
4435 TemplateDecl *Template,
4436 SourceLocation TemplateLoc,
4437 SourceLocation RAngleLoc,
4438 TemplateTemplateParmDecl *Param,
4439 SmallVectorImpl<TemplateArgument> &Converted,
4440 NestedNameSpecifierLoc &QualifierLoc) {
4441 Sema::InstantiatingTemplate Inst(
4442 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4443 SourceRange(TemplateLoc, RAngleLoc));
4444 if (Inst.isInvalid())
4445 return TemplateName();
4446
4447 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4448
4449 // Only substitute for the innermost template argument list.
4450 MultiLevelTemplateArgumentList TemplateArgLists;
4451 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4452 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4453 TemplateArgLists.addOuterTemplateArguments(None);
4454
4455 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4456 // Substitute into the nested-name-specifier first,
4457 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4458 if (QualifierLoc) {
4459 QualifierLoc =
4460 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4461 if (!QualifierLoc)
4462 return TemplateName();
4463 }
4464
4465 return SemaRef.SubstTemplateName(
4466 QualifierLoc,
4467 Param->getDefaultArgument().getArgument().getAsTemplate(),
4468 Param->getDefaultArgument().getTemplateNameLoc(),
4469 TemplateArgLists);
4470}
4471
4472/// \brief If the given template parameter has a default template
4473/// argument, substitute into that default template argument and
4474/// return the corresponding template argument.
4475TemplateArgumentLoc
4476Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4477 SourceLocation TemplateLoc,
4478 SourceLocation RAngleLoc,
4479 Decl *Param,
4480 SmallVectorImpl<TemplateArgument>
4481 &Converted,
4482 bool &HasDefaultArg) {
4483 HasDefaultArg = false;
4484
4485 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4486 if (!hasVisibleDefaultArgument(TypeParm))
4487 return TemplateArgumentLoc();
4488
4489 HasDefaultArg = true;
4490 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4491 TemplateLoc,
4492 RAngleLoc,
4493 TypeParm,
4494 Converted);
4495 if (DI)
4496 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4497
4498 return TemplateArgumentLoc();
4499 }
4500
4501 if (NonTypeTemplateParmDecl *NonTypeParm
4502 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4503 if (!hasVisibleDefaultArgument(NonTypeParm))
4504 return TemplateArgumentLoc();
4505
4506 HasDefaultArg = true;
4507 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4508 TemplateLoc,
4509 RAngleLoc,
4510 NonTypeParm,
4511 Converted);
4512 if (Arg.isInvalid())
4513 return TemplateArgumentLoc();
4514
4515 Expr *ArgE = Arg.getAs<Expr>();
4516 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4517 }
4518
4519 TemplateTemplateParmDecl *TempTempParm
4520 = cast<TemplateTemplateParmDecl>(Param);
4521 if (!hasVisibleDefaultArgument(TempTempParm))
4522 return TemplateArgumentLoc();
4523
4524 HasDefaultArg = true;
4525 NestedNameSpecifierLoc QualifierLoc;
4526 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4527 TemplateLoc,
4528 RAngleLoc,
4529 TempTempParm,
4530 Converted,
4531 QualifierLoc);
4532 if (TName.isNull())
4533 return TemplateArgumentLoc();
4534
4535 return TemplateArgumentLoc(TemplateArgument(TName),
4536 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4537 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4538}
4539
4540/// Convert a template-argument that we parsed as a type into a template, if
4541/// possible. C++ permits injected-class-names to perform dual service as
4542/// template template arguments and as template type arguments.
4543static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4544 // Extract and step over any surrounding nested-name-specifier.
4545 NestedNameSpecifierLoc QualLoc;
4546 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4547 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4548 return TemplateArgumentLoc();
4549
4550 QualLoc = ETLoc.getQualifierLoc();
4551 TLoc = ETLoc.getNamedTypeLoc();
4552 }
4553
4554 // If this type was written as an injected-class-name, it can be used as a
4555 // template template argument.
4556 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4557 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4558 QualLoc, InjLoc.getNameLoc());
4559
4560 // If this type was written as an injected-class-name, it may have been
4561 // converted to a RecordType during instantiation. If the RecordType is
4562 // *not* wrapped in a TemplateSpecializationType and denotes a class
4563 // template specialization, it must have come from an injected-class-name.
4564 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4565 if (auto *CTSD =
4566 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4567 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4568 QualLoc, RecLoc.getNameLoc());
4569
4570 return TemplateArgumentLoc();
4571}
4572
4573/// \brief Check that the given template argument corresponds to the given
4574/// template parameter.
4575///
4576/// \param Param The template parameter against which the argument will be
4577/// checked.
4578///
4579/// \param Arg The template argument, which may be updated due to conversions.
4580///
4581/// \param Template The template in which the template argument resides.
4582///
4583/// \param TemplateLoc The location of the template name for the template
4584/// whose argument list we're matching.
4585///
4586/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4587/// the template argument list.
4588///
4589/// \param ArgumentPackIndex The index into the argument pack where this
4590/// argument will be placed. Only valid if the parameter is a parameter pack.
4591///
4592/// \param Converted The checked, converted argument will be added to the
4593/// end of this small vector.
4594///
4595/// \param CTAK Describes how we arrived at this particular template argument:
4596/// explicitly written, deduced, etc.
4597///
4598/// \returns true on error, false otherwise.
4599bool Sema::CheckTemplateArgument(NamedDecl *Param,
4600 TemplateArgumentLoc &Arg,
4601 NamedDecl *Template,
4602 SourceLocation TemplateLoc,
4603 SourceLocation RAngleLoc,
4604 unsigned ArgumentPackIndex,
4605 SmallVectorImpl<TemplateArgument> &Converted,
4606 CheckTemplateArgumentKind CTAK) {
4607 // Check template type parameters.
4608 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4609 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4610
4611 // Check non-type template parameters.
4612 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4613 // Do substitution on the type of the non-type template parameter
4614 // with the template arguments we've seen thus far. But if the
4615 // template has a dependent context then we cannot substitute yet.
4616 QualType NTTPType = NTTP->getType();
4617 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4618 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4619
4620 if (NTTPType->isDependentType() &&
4621 !isa<TemplateTemplateParmDecl>(Template) &&
4622 !Template->getDeclContext()->isDependentContext()) {
4623 // Do substitution on the type of the non-type template parameter.
4624 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4625 NTTP, Converted,
4626 SourceRange(TemplateLoc, RAngleLoc));
4627 if (Inst.isInvalid())
4628 return true;
4629
4630 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4631 Converted);
4632 NTTPType = SubstType(NTTPType,
4633 MultiLevelTemplateArgumentList(TemplateArgs),
4634 NTTP->getLocation(),
4635 NTTP->getDeclName());
4636 // If that worked, check the non-type template parameter type
4637 // for validity.
4638 if (!NTTPType.isNull())
4639 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4640 NTTP->getLocation());
4641 if (NTTPType.isNull())
4642 return true;
4643 }
4644
4645 switch (Arg.getArgument().getKind()) {
4646 case TemplateArgument::Null:
4647 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4647)
;
4648
4649 case TemplateArgument::Expression: {
4650 TemplateArgument Result;
4651 ExprResult Res =
4652 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4653 Result, CTAK);
4654 if (Res.isInvalid())
4655 return true;
4656
4657 // If the resulting expression is new, then use it in place of the
4658 // old expression in the template argument.
4659 if (Res.get() != Arg.getArgument().getAsExpr()) {
4660 TemplateArgument TA(Res.get());
4661 Arg = TemplateArgumentLoc(TA, Res.get());
4662 }
4663
4664 Converted.push_back(Result);
4665 break;
4666 }
4667
4668 case TemplateArgument::Declaration:
4669 case TemplateArgument::Integral:
4670 case TemplateArgument::NullPtr:
4671 // We've already checked this template argument, so just copy
4672 // it to the list of converted arguments.
4673 Converted.push_back(Arg.getArgument());
4674 break;
4675
4676 case TemplateArgument::Template:
4677 case TemplateArgument::TemplateExpansion:
4678 // We were given a template template argument. It may not be ill-formed;
4679 // see below.
4680 if (DependentTemplateName *DTN
4681 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4682 .getAsDependentTemplateName()) {
4683 // We have a template argument such as \c T::template X, which we
4684 // parsed as a template template argument. However, since we now
4685 // know that we need a non-type template argument, convert this
4686 // template name into an expression.
4687
4688 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4689 Arg.getTemplateNameLoc());
4690
4691 CXXScopeSpec SS;
4692 SS.Adopt(Arg.getTemplateQualifierLoc());
4693 // FIXME: the template-template arg was a DependentTemplateName,
4694 // so it was provided with a template keyword. However, its source
4695 // location is not stored in the template argument structure.
4696 SourceLocation TemplateKWLoc;
4697 ExprResult E = DependentScopeDeclRefExpr::Create(
4698 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4699 nullptr);
4700
4701 // If we parsed the template argument as a pack expansion, create a
4702 // pack expansion expression.
4703 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4704 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4705 if (E.isInvalid())
4706 return true;
4707 }
4708
4709 TemplateArgument Result;
4710 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4711 if (E.isInvalid())
4712 return true;
4713
4714 Converted.push_back(Result);
4715 break;
4716 }
4717
4718 // We have a template argument that actually does refer to a class
4719 // template, alias template, or template template parameter, and
4720 // therefore cannot be a non-type template argument.
4721 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4722 << Arg.getSourceRange();
4723
4724 Diag(Param->getLocation(), diag::note_template_param_here);
4725 return true;
4726
4727 case TemplateArgument::Type: {
4728 // We have a non-type template parameter but the template
4729 // argument is a type.
4730
4731 // C++ [temp.arg]p2:
4732 // In a template-argument, an ambiguity between a type-id and
4733 // an expression is resolved to a type-id, regardless of the
4734 // form of the corresponding template-parameter.
4735 //
4736 // We warn specifically about this case, since it can be rather
4737 // confusing for users.
4738 QualType T = Arg.getArgument().getAsType();
4739 SourceRange SR = Arg.getSourceRange();
4740 if (T->isFunctionType())
4741 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4742 else
4743 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4744 Diag(Param->getLocation(), diag::note_template_param_here);
4745 return true;
4746 }
4747
4748 case TemplateArgument::Pack:
4749 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4749)
;
4750 }
4751
4752 return false;
4753 }
4754
4755
4756 // Check template template parameters.
4757 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4758
4759 // Substitute into the template parameter list of the template
4760 // template parameter, since previously-supplied template arguments
4761 // may appear within the template template parameter.
4762 {
4763 // Set up a template instantiation context.
4764 LocalInstantiationScope Scope(*this);
4765 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4766 TempParm, Converted,
4767 SourceRange(TemplateLoc, RAngleLoc));
4768 if (Inst.isInvalid())
4769 return true;
4770
4771 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4772 TempParm = cast_or_null<TemplateTemplateParmDecl>(
4773 SubstDecl(TempParm, CurContext,
4774 MultiLevelTemplateArgumentList(TemplateArgs)));
4775 if (!TempParm)
4776 return true;
4777 }
4778
4779 // C++1z [temp.local]p1: (DR1004)
4780 // When [the injected-class-name] is used [...] as a template-argument for
4781 // a template template-parameter [...] it refers to the class template
4782 // itself.
4783 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4784 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4785 Arg.getTypeSourceInfo()->getTypeLoc());
4786 if (!ConvertedArg.getArgument().isNull())
4787 Arg = ConvertedArg;
4788 }
4789
4790 switch (Arg.getArgument().getKind()) {
4791 case TemplateArgument::Null:
4792 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4792)
;
4793
4794 case TemplateArgument::Template:
4795 case TemplateArgument::TemplateExpansion:
4796 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4797 return true;
4798
4799 Converted.push_back(Arg.getArgument());
4800 break;
4801
4802 case TemplateArgument::Expression:
4803 case TemplateArgument::Type:
4804 // We have a template template parameter but the template
4805 // argument does not refer to a template.
4806 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4807 << getLangOpts().CPlusPlus11;
4808 return true;
4809
4810 case TemplateArgument::Declaration:
4811 llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4811)
;
4812 case TemplateArgument::Integral:
4813 llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4813)
;
4814 case TemplateArgument::NullPtr:
4815 llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4815)
;
4816
4817 case TemplateArgument::Pack:
4818 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4818)
;
4819 }
4820
4821 return false;
4822}
4823
4824/// \brief Diagnose an arity mismatch in the
4825static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4826 SourceLocation TemplateLoc,
4827 TemplateArgumentListInfo &TemplateArgs) {
4828 TemplateParameterList *Params = Template->getTemplateParameters();
4829 unsigned NumParams = Params->size();
4830 unsigned NumArgs = TemplateArgs.size();
4831
4832 SourceRange Range;
4833 if (NumArgs > NumParams)
4834 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4835 TemplateArgs.getRAngleLoc());
4836 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4837 << (NumArgs > NumParams)
4838 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4839 << Template << Range;
4840 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4841 << Params->getSourceRange();
4842 return true;
4843}
4844
4845/// \brief Check whether the template parameter is a pack expansion, and if so,
4846/// determine the number of parameters produced by that expansion. For instance:
4847///
4848/// \code
4849/// template<typename ...Ts> struct A {
4850/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4851/// };
4852/// \endcode
4853///
4854/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4855/// is not a pack expansion, so returns an empty Optional.
4856static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4857 if (NonTypeTemplateParmDecl *NTTP
4858 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4859 if (NTTP->isExpandedParameterPack())
4860 return NTTP->getNumExpansionTypes();
4861 }
4862
4863 if (TemplateTemplateParmDecl *TTP
4864 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4865 if (TTP->isExpandedParameterPack())
4866 return TTP->getNumExpansionTemplateParameters();
4867 }
4868
4869 return None;
4870}
4871
4872/// Diagnose a missing template argument.
4873template<typename TemplateParmDecl>
4874static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4875 TemplateDecl *TD,
4876 const TemplateParmDecl *D,
4877 TemplateArgumentListInfo &Args) {
4878 // Dig out the most recent declaration of the template parameter; there may be
4879 // declarations of the template that are more recent than TD.
4880 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4881 ->getTemplateParameters()
4882 ->getParam(D->getIndex()));
4883
4884 // If there's a default argument that's not visible, diagnose that we're
4885 // missing a module import.
4886 llvm::SmallVector<Module*, 8> Modules;
4887 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4888 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4889 D->getDefaultArgumentLoc(), Modules,
4890 Sema::MissingImportKind::DefaultArgument,
4891 /*Recover*/true);
4892 return true;
4893 }
4894
4895 // FIXME: If there's a more recent default argument that *is* visible,
4896 // diagnose that it was declared too late.
4897
4898 return diagnoseArityMismatch(S, TD, Loc, Args);
4899}
4900
4901/// \brief Check that the given template argument list is well-formed
4902/// for specializing the given template.
4903bool Sema::CheckTemplateArgumentList(
4904 TemplateDecl *Template, SourceLocation TemplateLoc,
4905 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4906 SmallVectorImpl<TemplateArgument> &Converted,
4907 bool UpdateArgsWithConversions) {
4908 // Make a copy of the template arguments for processing. Only make the
4909 // changes at the end when successful in matching the arguments to the
4910 // template.
4911 TemplateArgumentListInfo NewArgs = TemplateArgs;
4912
4913 // Make sure we get the template parameter list from the most
4914 // recentdeclaration, since that is the only one that has is guaranteed to
4915 // have all the default template argument information.
4916 TemplateParameterList *Params =
4917 cast<TemplateDecl>(Template->getMostRecentDecl())
4918 ->getTemplateParameters();
4919
4920 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4921
4922 // C++ [temp.arg]p1:
4923 // [...] The type and form of each template-argument specified in
4924 // a template-id shall match the type and form specified for the
4925 // corresponding parameter declared by the template in its
4926 // template-parameter-list.
4927 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4928 SmallVector<TemplateArgument, 2> ArgumentPack;
4929 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4930 LocalInstantiationScope InstScope(*this, true);
4931 for (TemplateParameterList::iterator Param = Params->begin(),
4932 ParamEnd = Params->end();
4933 Param != ParamEnd; /* increment in loop */) {
4934 // If we have an expanded parameter pack, make sure we don't have too
4935 // many arguments.
4936 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4937 if (*Expansions == ArgumentPack.size()) {
4938 // We're done with this parameter pack. Pack up its arguments and add
4939 // them to the list.
4940 Converted.push_back(
4941 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4942 ArgumentPack.clear();
4943
4944 // This argument is assigned to the next parameter.
4945 ++Param;
4946 continue;
4947 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4948 // Not enough arguments for this parameter pack.
4949 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4950 << false
4951 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4952 << Template;
4953 Diag(Template->getLocation(), diag::note_template_decl_here)
4954 << Params->getSourceRange();
4955 return true;
4956 }
4957 }
4958
4959 if (ArgIdx < NumArgs) {
4960 // Check the template argument we were given.
4961 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4962 TemplateLoc, RAngleLoc,
4963 ArgumentPack.size(), Converted))
4964 return true;
4965
4966 bool PackExpansionIntoNonPack =
4967 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4968 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4969 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4970 // Core issue 1430: we have a pack expansion as an argument to an
4971 // alias template, and it's not part of a parameter pack. This
4972 // can't be canonicalized, so reject it now.
4973 Diag(NewArgs[ArgIdx].getLocation(),
4974 diag::err_alias_template_expansion_into_fixed_list)
4975 << NewArgs[ArgIdx].getSourceRange();
4976 Diag((*Param)->getLocation(), diag::note_template_param_here);
4977 return true;
4978 }
4979
4980 // We're now done with this argument.
4981 ++ArgIdx;
4982
4983 if ((*Param)->isTemplateParameterPack()) {
4984 // The template parameter was a template parameter pack, so take the
4985 // deduced argument and place it on the argument pack. Note that we
4986 // stay on the same template parameter so that we can deduce more
4987 // arguments.
4988 ArgumentPack.push_back(Converted.pop_back_val());
4989 } else {
4990 // Move to the next template parameter.
4991 ++Param;
4992 }
4993
4994 // If we just saw a pack expansion into a non-pack, then directly convert
4995 // the remaining arguments, because we don't know what parameters they'll
4996 // match up with.
4997 if (PackExpansionIntoNonPack) {
4998 if (!ArgumentPack.empty()) {
4999 // If we were part way through filling in an expanded parameter pack,
5000 // fall back to just producing individual arguments.
5001 Converted.insert(Converted.end(),
5002 ArgumentPack.begin(), ArgumentPack.end());
5003 ArgumentPack.clear();
5004 }
5005
5006 while (ArgIdx < NumArgs) {
5007 Converted.push_back(NewArgs[ArgIdx].getArgument());
5008 ++ArgIdx;
5009 }
5010
5011 return false;
5012 }
5013
5014 continue;
5015 }
5016
5017 // If we're checking a partial template argument list, we're done.
5018 if (PartialTemplateArgs) {
5019 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5020 Converted.push_back(
5021 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5022
5023 return false;
5024 }
5025
5026 // If we have a template parameter pack with no more corresponding
5027 // arguments, just break out now and we'll fill in the argument pack below.
5028 if ((*Param)->isTemplateParameterPack()) {
5029 assert(!getExpandedPackSize(*Param) &&(static_cast <bool> (!getExpandedPackSize(*Param) &&
"Should have dealt with this already") ? void (0) : __assert_fail
("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5030, __extension__ __PRETTY_FUNCTION__))
5030 "Should have dealt with this already")(static_cast <bool> (!getExpandedPackSize(*Param) &&
"Should have dealt with this already") ? void (0) : __assert_fail
("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5030, __extension__ __PRETTY_FUNCTION__))
;
5031
5032 // A non-expanded parameter pack before the end of the parameter list
5033 // only occurs for an ill-formed template parameter list, unless we've
5034 // got a partial argument list for a function template, so just bail out.
5035 if (Param + 1 != ParamEnd)
5036 return true;
5037
5038 Converted.push_back(
5039 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5040 ArgumentPack.clear();
5041
5042 ++Param;
5043 continue;
5044 }
5045
5046 // Check whether we have a default argument.
5047 TemplateArgumentLoc Arg;
5048
5049 // Retrieve the default template argument from the template
5050 // parameter. For each kind of template parameter, we substitute the
5051 // template arguments provided thus far and any "outer" template arguments
5052 // (when the template parameter was part of a nested template) into
5053 // the default argument.
5054 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5055 if (!hasVisibleDefaultArgument(TTP))
5056 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5057 NewArgs);
5058
5059 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5060 Template,
5061 TemplateLoc,
5062 RAngleLoc,
5063 TTP,
5064 Converted);
5065 if (!ArgType)
5066 return true;
5067
5068 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5069 ArgType);
5070 } else if (NonTypeTemplateParmDecl *NTTP
5071 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5072 if (!hasVisibleDefaultArgument(NTTP))
5073 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5074 NewArgs);
5075
5076 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5077 TemplateLoc,
5078 RAngleLoc,
5079 NTTP,
5080 Converted);
5081 if (E.isInvalid())
5082 return true;
5083
5084 Expr *Ex = E.getAs<Expr>();
5085 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5086 } else {
5087 TemplateTemplateParmDecl *TempParm
5088 = cast<TemplateTemplateParmDecl>(*Param);
5089
5090 if (!hasVisibleDefaultArgument(TempParm))
5091 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5092 NewArgs);
5093
5094 NestedNameSpecifierLoc QualifierLoc;
5095 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5096 TemplateLoc,
5097 RAngleLoc,
5098 TempParm,
5099 Converted,
5100 QualifierLoc);
5101 if (Name.isNull())
5102 return true;
5103
5104 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5105 TempParm->getDefaultArgument().getTemplateNameLoc());
5106 }
5107
5108 // Introduce an instantiation record that describes where we are using
5109 // the default template argument. We're not actually instantiating a
5110 // template here, we just create this object to put a note into the
5111 // context stack.
5112 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5113 SourceRange(TemplateLoc, RAngleLoc));
5114 if (Inst.isInvalid())
5115 return true;
5116
5117 // Check the default template argument.
5118 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5119 RAngleLoc, 0, Converted))
5120 return true;
5121
5122 // Core issue 150 (assumed resolution): if this is a template template
5123 // parameter, keep track of the default template arguments from the
5124 // template definition.
5125 if (isTemplateTemplateParameter)
5126 NewArgs.addArgument(Arg);
5127
5128 // Move to the next template parameter and argument.
5129 ++Param;
5130 ++ArgIdx;
5131 }
5132
5133 // If we're performing a partial argument substitution, allow any trailing
5134 // pack expansions; they might be empty. This can happen even if
5135 // PartialTemplateArgs is false (the list of arguments is complete but
5136 // still dependent).
5137 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5138 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5139 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5140 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5141 }
5142
5143 // If we have any leftover arguments, then there were too many arguments.
5144 // Complain and fail.
5145 if (ArgIdx < NumArgs)
5146 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5147
5148 // No problems found with the new argument list, propagate changes back
5149 // to caller.
5150 if (UpdateArgsWithConversions)
5151 TemplateArgs = std::move(NewArgs);
5152
5153 return false;
5154}
5155
5156namespace {
5157 class UnnamedLocalNoLinkageFinder
5158 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5159 {
5160 Sema &S;
5161 SourceRange SR;
5162
5163 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5164
5165 public:
5166 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5167
5168 bool Visit(QualType T) {
5169 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5170 }
5171
5172#define TYPE(Class, Parent) \
5173 bool Visit##Class##Type(const Class##Type *);
5174#define ABSTRACT_TYPE(Class, Parent) \
5175 bool Visit##Class##Type(const Class##Type *) { return false; }
5176#define NON_CANONICAL_TYPE(Class, Parent) \
5177 bool Visit##Class##Type(const Class##Type *) { return false; }
5178#include "clang/AST/TypeNodes.def"
5179
5180 bool VisitTagDecl(const TagDecl *Tag);
5181 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5182 };
5183} // end anonymous namespace
5184
5185bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5186 return false;
5187}
5188
5189bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5190 return Visit(T->getElementType());
5191}
5192
5193bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5194 return Visit(T->getPointeeType());
5195}
5196
5197bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5198 const BlockPointerType* T) {
5199 return Visit(T->getPointeeType());
5200}
5201
5202bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5203 const LValueReferenceType* T) {
5204 return Visit(T->getPointeeType());
5205}
5206
5207bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5208 const RValueReferenceType* T) {
5209 return Visit(T->getPointeeType());
5210}
5211
5212bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5213 const MemberPointerType* T) {
5214 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5215}
5216
5217bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5218 const ConstantArrayType* T) {
5219 return Visit(T->getElementType());
5220}
5221
5222bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5223 const IncompleteArrayType* T) {
5224 return Visit(T->getElementType());
5225}
5226
5227bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5228 const VariableArrayType* T) {
5229 return Visit(T->getElementType());
5230}
5231
5232bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5233 const DependentSizedArrayType* T) {
5234 return Visit(T->getElementType());
5235}
5236
5237bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5238 const DependentSizedExtVectorType* T) {
5239 return Visit(T->getElementType());
5240}
5241
5242bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5243 const DependentAddressSpaceType *T) {
5244 return Visit(T->getPointeeType());
5245}
5246
5247bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5248 return Visit(T->getElementType());
5249}
5250
5251bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5252 return Visit(T->getElementType());
5253}
5254
5255bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5256 const FunctionProtoType* T) {
5257 for (const auto &A : T->param_types()) {
5258 if (Visit(A))
5259 return true;
5260 }
5261
5262 return Visit(T->getReturnType());
5263}
5264
5265bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5266 const FunctionNoProtoType* T) {
5267 return Visit(T->getReturnType());
5268}
5269
5270bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5271 const UnresolvedUsingType*) {
5272 return false;
5273}
5274
5275bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5276 return false;
5277}
5278
5279bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5280 return Visit(T->getUnderlyingType());
5281}
5282
5283bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5284 return false;
5285}
5286
5287bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5288 const UnaryTransformType*) {
5289 return false;
5290}
5291
5292bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5293 return Visit(T->getDeducedType());
5294}
5295
5296bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5297 const DeducedTemplateSpecializationType *T) {
5298 return Visit(T->getDeducedType());
5299}
5300
5301bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5302 return VisitTagDecl(T->getDecl());
5303}
5304
5305bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5306 return VisitTagDecl(T->getDecl());
5307}
5308
5309bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5310 const TemplateTypeParmType*) {
5311 return false;
5312}
5313
5314bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5315 const SubstTemplateTypeParmPackType *) {
5316 return false;
5317}
5318
5319bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5320 const TemplateSpecializationType*) {
5321 return false;
5322}
5323
5324bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5325 const InjectedClassNameType* T) {
5326 return VisitTagDecl(T->getDecl());
5327}
5328
5329bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5330 const DependentNameType* T) {
5331 return VisitNestedNameSpecifier(T->getQualifier());
5332}
5333
5334bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5335 const DependentTemplateSpecializationType* T) {
5336 return VisitNestedNameSpecifier(T->getQualifier());
5337}
5338
5339bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5340 const PackExpansionType* T) {
5341 return Visit(T->getPattern());
5342}
5343
5344bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5345 return false;
5346}
5347
5348bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5349 const ObjCInterfaceType *) {
5350 return false;
5351}
5352
5353bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5354 const ObjCObjectPointerType *) {
5355 return false;
5356}
5357
5358bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5359 return Visit(T->getValueType());
5360}
5361
5362bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5363 return false;
5364}
5365
5366bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5367 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5368 S.Diag(SR.getBegin(),
5369 S.getLangOpts().CPlusPlus11 ?
5370 diag::warn_cxx98_compat_template_arg_local_type :
5371 diag::ext_template_arg_local_type)
5372 << S.Context.getTypeDeclType(Tag) << SR;
5373 return true;
5374 }
5375
5376 if (!Tag->hasNameForLinkage()) {
5377 S.Diag(SR.getBegin(),
5378 S.getLangOpts().CPlusPlus11 ?
5379 diag::warn_cxx98_compat_template_arg_unnamed_type :
5380 diag::ext_template_arg_unnamed_type) << SR;
5381 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5382 return true;
5383 }
5384
5385 return false;
5386}
5387
5388bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5389 NestedNameSpecifier *NNS) {
5390 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5391 return true;
5392
5393 switch (NNS->getKind()) {
5394 case NestedNameSpecifier::Identifier:
5395 case NestedNameSpecifier::Namespace:
5396 case NestedNameSpecifier::NamespaceAlias:
5397 case NestedNameSpecifier::Global:
5398 case NestedNameSpecifier::Super:
5399 return false;
5400
5401 case NestedNameSpecifier::TypeSpec:
5402 case NestedNameSpecifier::TypeSpecWithTemplate:
5403 return Visit(QualType(NNS->getAsType(), 0));
5404 }
5405 llvm_unreachable("Invalid NestedNameSpecifier::Kind!")::llvm::llvm_unreachable_internal("Invalid NestedNameSpecifier::Kind!"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5405)
;
5406}
5407
5408/// \brief Check a template argument against its corresponding
5409/// template type parameter.
5410///
5411/// This routine implements the semantics of C++ [temp.arg.type]. It
5412/// returns true if an error occurred, and false otherwise.
5413bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5414 TypeSourceInfo *ArgInfo) {
5415 assert(ArgInfo && "invalid TypeSourceInfo")(static_cast <bool> (ArgInfo && "invalid TypeSourceInfo"
) ? void (0) : __assert_fail ("ArgInfo && \"invalid TypeSourceInfo\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5415, __extension__ __PRETTY_FUNCTION__))
;
5416 QualType Arg = ArgInfo->getType();
5417 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5418
5419 if (Arg->isVariablyModifiedType()) {
5420 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5421 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5422 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5423 }
5424
5425 // C++03 [temp.arg.type]p2:
5426 // A local type, a type with no linkage, an unnamed type or a type
5427 // compounded from any of these types shall not be used as a
5428 // template-argument for a template type-parameter.
5429 //
5430 // C++11 allows these, and even in C++03 we allow them as an extension with
5431 // a warning.
5432 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5433 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5434 (void)Finder.Visit(Context.getCanonicalType(Arg));
5435 }
5436
5437 return false;
5438}
5439
5440enum NullPointerValueKind {
5441 NPV_NotNullPointer,
5442 NPV_NullPointer,
5443 NPV_Error
5444};
5445
5446/// \brief Determine whether the given template argument is a null pointer
5447/// value of the appropriate type.
5448static NullPointerValueKind
5449isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5450 QualType ParamType, Expr *Arg,
5451 Decl *Entity = nullptr) {
5452 if (Arg->isValueDependent() || Arg->isTypeDependent())
5453 return NPV_NotNullPointer;
5454
5455 // dllimport'd entities aren't constant but are available inside of template
5456 // arguments.
5457 if (Entity && Entity->hasAttr<DLLImportAttr>())
5458 return NPV_NotNullPointer;
5459
5460 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5461 llvm_unreachable(::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5462)
5462 "Incomplete parameter type in isNullPointerValueTemplateArgument!")::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5462)
;
5463
5464 if (!S.getLangOpts().CPlusPlus11)
5465 return NPV_NotNullPointer;
5466
5467 // Determine whether we have a constant expression.
5468 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5469 if (ArgRV.isInvalid())
5470 return NPV_Error;
5471 Arg = ArgRV.get();
5472
5473 Expr::EvalResult EvalResult;
5474 SmallVector<PartialDiagnosticAt, 8> Notes;
5475 EvalResult.Diag = &Notes;
5476 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5477 EvalResult.HasSideEffects) {
5478 SourceLocation DiagLoc = Arg->getExprLoc();
5479
5480 // If our only note is the usual "invalid subexpression" note, just point
5481 // the caret at its location rather than producing an essentially
5482 // redundant note.
5483 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5484 diag::note_invalid_subexpr_in_const_expr) {
5485 DiagLoc = Notes[0].first;
5486 Notes.clear();
5487 }
5488
5489 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5490 << Arg->getType() << Arg->getSourceRange();
5491 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5492 S.Diag(Notes[I].first, Notes[I].second);
5493
5494 S.Diag(Param->getLocation(), diag::note_template_param_here);
5495 return NPV_Error;
5496 }
5497
5498 // C++11 [temp.arg.nontype]p1:
5499 // - an address constant expression of type std::nullptr_t
5500 if (Arg->getType()->isNullPtrType())
5501 return NPV_NullPointer;
5502
5503 // - a constant expression that evaluates to a null pointer value (4.10); or
5504 // - a constant expression that evaluates to a null member pointer value
5505 // (4.11); or
5506 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5507 (EvalResult.Val.isMemberPointer() &&
5508 !EvalResult.Val.getMemberPointerDecl())) {
5509 // If our expression has an appropriate type, we've succeeded.
5510 bool ObjCLifetimeConversion;
5511 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5512 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5513 ObjCLifetimeConversion))
5514 return NPV_NullPointer;
5515
5516 // The types didn't match, but we know we got a null pointer; complain,
5517 // then recover as if the types were correct.
5518 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5519 << Arg->getType() << ParamType << Arg->getSourceRange();
5520 S.Diag(Param->getLocation(), diag::note_template_param_here);
5521 return NPV_NullPointer;
5522 }
5523
5524 // If we don't have a null pointer value, but we do have a NULL pointer
5525 // constant, suggest a cast to the appropriate type.
5526 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5527 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5528 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5529 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5530 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5531 ")");
5532 S.Diag(Param->getLocation(), diag::note_template_param_here);
5533 return NPV_NullPointer;
5534 }
5535
5536 // FIXME: If we ever want to support general, address-constant expressions
5537 // as non-type template arguments, we should return the ExprResult here to
5538 // be interpreted by the caller.
5539 return NPV_NotNullPointer;
5540}
5541
5542/// \brief Checks whether the given template argument is compatible with its
5543/// template parameter.
5544static bool CheckTemplateArgumentIsCompatibleWithParameter(
5545 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5546 Expr *Arg, QualType ArgType) {
5547 bool ObjCLifetimeConversion;
5548 if (ParamType->isPointerType() &&
5549 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5550 S.IsQualificationConversion(ArgType, ParamType, false,
5551 ObjCLifetimeConversion)) {
5552 // For pointer-to-object types, qualification conversions are
5553 // permitted.
5554 } else {
5555 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5556 if (!ParamRef->getPointeeType()->isFunctionType()) {
5557 // C++ [temp.arg.nontype]p5b3:
5558 // For a non-type template-parameter of type reference to
5559 // object, no conversions apply. The type referred to by the
5560 // reference may be more cv-qualified than the (otherwise
5561 // identical) type of the template- argument. The
5562 // template-parameter is bound directly to the
5563 // template-argument, which shall be an lvalue.
5564
5565 // FIXME: Other qualifiers?
5566 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5567 unsigned ArgQuals = ArgType.getCVRQualifiers();
5568
5569 if ((ParamQuals | ArgQuals) != ParamQuals) {
5570 S.Diag(Arg->getLocStart(),
5571 diag::err_template_arg_ref_bind_ignores_quals)
5572 << ParamType << Arg->getType() << Arg->getSourceRange();
5573 S.Diag(Param->getLocation(), diag::note_template_param_here);
5574 return true;
5575 }
5576 }
5577 }
5578
5579 // At this point, the template argument refers to an object or
5580 // function with external linkage. We now need to check whether the
5581 // argument and parameter types are compatible.
5582 if (!S.Context.hasSameUnqualifiedType(ArgType,
5583 ParamType.getNonReferenceType())) {
5584 // We can't perform this conversion or binding.
5585 if (ParamType->isReferenceType())
5586 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5587 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5588 else
5589 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5590 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5591 S.Diag(Param->getLocation(), diag::note_template_param_here);
5592 return true;
5593 }
5594 }
5595
5596 return false;
5597}
5598
5599/// \brief Checks whether the given template argument is the address
5600/// of an object or function according to C++ [temp.arg.nontype]p1.
5601static bool
5602CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5603 NonTypeTemplateParmDecl *Param,
5604 QualType ParamType,
5605 Expr *ArgIn,
5606 TemplateArgument &Converted) {
5607 bool Invalid = false;
5608 Expr *Arg = ArgIn;
5609 QualType ArgType = Arg->getType();
5610
5611 bool AddressTaken = false;
5612 SourceLocation AddrOpLoc;
5613 if (S.getLangOpts().MicrosoftExt) {
5614 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5615 // dereference and address-of operators.
5616 Arg = Arg->IgnoreParenCasts();
5617
5618 bool ExtWarnMSTemplateArg = false;
5619 UnaryOperatorKind FirstOpKind;
5620 SourceLocation FirstOpLoc;
5621 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5622 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5623 if (UnOpKind == UO_Deref)
5624 ExtWarnMSTemplateArg = true;
5625 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5626 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5627 if (!AddrOpLoc.isValid()) {
5628 FirstOpKind = UnOpKind;
5629 FirstOpLoc = UnOp->getOperatorLoc();
5630 }
5631 } else
5632 break;
5633 }
5634 if (FirstOpLoc.isValid()) {
5635 if (ExtWarnMSTemplateArg)
5636 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5637 << ArgIn->getSourceRange();
5638
5639 if (FirstOpKind == UO_AddrOf)
5640 AddressTaken = true;
5641 else if (Arg->getType()->isPointerType()) {
5642 // We cannot let pointers get dereferenced here, that is obviously not a
5643 // constant expression.
5644 assert(FirstOpKind == UO_Deref)(static_cast <bool> (FirstOpKind == UO_Deref) ? void (0
) : __assert_fail ("FirstOpKind == UO_Deref", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5644, __extension__ __PRETTY_FUNCTION__))
;
5645 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5646 << Arg->getSourceRange();
5647 }
5648 }
5649 } else {
5650 // See through any implicit casts we added to fix the type.
5651 Arg = Arg->IgnoreImpCasts();
5652
5653 // C++ [temp.arg.nontype]p1:
5654 //
5655 // A template-argument for a non-type, non-template
5656 // template-parameter shall be one of: [...]
5657 //
5658 // -- the address of an object or function with external
5659 // linkage, including function templates and function
5660 // template-ids but excluding non-static class members,
5661 // expressed as & id-expression where the & is optional if
5662 // the name refers to a function or array, or if the
5663 // corresponding template-parameter is a reference; or
5664
5665 // In C++98/03 mode, give an extension warning on any extra parentheses.
5666 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5667 bool ExtraParens = false;
5668 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5669 if (!Invalid && !ExtraParens) {
5670 S.Diag(Arg->getLocStart(),
5671 S.getLangOpts().CPlusPlus11
5672 ? diag::warn_cxx98_compat_template_arg_extra_parens
5673 : diag::ext_template_arg_extra_parens)
5674 << Arg->getSourceRange();
5675 ExtraParens = true;
5676 }
5677
5678 Arg = Parens->getSubExpr();
5679 }
5680
5681 while (SubstNonTypeTemplateParmExpr *subst =
5682 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5683 Arg = subst->getReplacement()->IgnoreImpCasts();
5684
5685 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5686 if (UnOp->getOpcode() == UO_AddrOf) {
5687 Arg = UnOp->getSubExpr();
5688 AddressTaken = true;
5689 AddrOpLoc = UnOp->getOperatorLoc();
5690 }
5691 }
5692
5693 while (SubstNonTypeTemplateParmExpr *subst =
5694 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5695 Arg = subst->getReplacement()->IgnoreImpCasts();
5696 }
5697
5698 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5699 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5700
5701 // If our parameter has pointer type, check for a null template value.
5702 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5703 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5704 Entity)) {
5705 case NPV_NullPointer:
5706 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5707 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5708 /*isNullPtr=*/true);
5709 return false;
5710
5711 case NPV_Error:
5712 return true;
5713
5714 case NPV_NotNullPointer:
5715 break;
5716 }
5717 }
5718
5719 // Stop checking the precise nature of the argument if it is value dependent,
5720 // it should be checked when instantiated.
5721 if (Arg->isValueDependent()) {
5722 Converted = TemplateArgument(ArgIn);
5723 return false;
5724 }
5725
5726 if (isa<CXXUuidofExpr>(Arg)) {
5727 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5728 ArgIn, Arg, ArgType))
5729 return true;
5730
5731 Converted = TemplateArgument(ArgIn);
5732 return false;
5733 }
5734
5735 if (!DRE) {
5736 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5737 << Arg->getSourceRange();
5738 S.Diag(Param->getLocation(), diag::note_template_param_here);
5739 return true;
5740 }
5741
5742 // Cannot refer to non-static data members
5743 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5744 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5745 << Entity << Arg->getSourceRange();
5746 S.Diag(Param->getLocation(), diag::note_template_param_here);
5747 return true;
5748 }
5749
5750 // Cannot refer to non-static member functions
5751 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5752 if (!Method->isStatic()) {
5753 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5754 << Method << Arg->getSourceRange();
5755 S.Diag(Param->getLocation(), diag::note_template_param_here);
5756 return true;
5757 }
5758 }
5759
5760 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5761 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5762
5763 // A non-type template argument must refer to an object or function.
5764 if (!Func && !Var) {
5765 // We found something, but we don't know specifically what it is.
5766 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5767 << Arg->getSourceRange();
5768 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5769 return true;
5770 }
5771
5772 // Address / reference template args must have external linkage in C++98.
5773 if (Entity->getFormalLinkage() == InternalLinkage) {
5774 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5775 diag::warn_cxx98_compat_template_arg_object_internal :
5776 diag::ext_template_arg_object_internal)
5777 << !Func << Entity << Arg->getSourceRange();
5778 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5779 << !Func;
5780 } else if (!Entity->hasLinkage()) {
5781 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5782 << !Func << Entity << Arg->getSourceRange();
5783 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5784 << !Func;
5785 return true;
5786 }
5787
5788 if (Func) {
5789 // If the template parameter has pointer type, the function decays.
5790 if (ParamType->isPointerType() && !AddressTaken)
5791 ArgType = S.Context.getPointerType(Func->getType());
5792 else if (AddressTaken && ParamType->isReferenceType()) {
5793 // If we originally had an address-of operator, but the
5794 // parameter has reference type, complain and (if things look
5795 // like they will work) drop the address-of operator.
5796 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5797 ParamType.getNonReferenceType())) {
5798 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5799 << ParamType;
5800 S.Diag(Param->getLocation(), diag::note_template_param_here);
5801 return true;
5802 }
5803
5804 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5805 << ParamType
5806 << FixItHint::CreateRemoval(AddrOpLoc);
5807 S.Diag(Param->getLocation(), diag::note_template_param_here);
5808
5809 ArgType = Func->getType();
5810 }
5811 } else {
5812 // A value of reference type is not an object.
5813 if (Var->getType()->isReferenceType()) {
5814 S.Diag(Arg->getLocStart(),
5815 diag::err_template_arg_reference_var)
5816 << Var->getType() << Arg->getSourceRange();
5817 S.Diag(Param->getLocation(), diag::note_template_param_here);
5818 return true;
5819 }
5820
5821 // A template argument must have static storage duration.
5822 if (Var->getTLSKind()) {
5823 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5824 << Arg->getSourceRange();
5825 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5826 return true;
5827 }
5828
5829 // If the template parameter has pointer type, we must have taken
5830 // the address of this object.
5831 if (ParamType->isReferenceType()) {
5832 if (AddressTaken) {
5833 // If we originally had an address-of operator, but the
5834 // parameter has reference type, complain and (if things look
5835 // like they will work) drop the address-of operator.
5836 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5837 ParamType.getNonReferenceType())) {
5838 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5839 << ParamType;
5840 S.Diag(Param->getLocation(), diag::note_template_param_here);
5841 return true;
5842 }
5843
5844 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5845 << ParamType
5846 << FixItHint::CreateRemoval(AddrOpLoc);
5847 S.Diag(Param->getLocation(), diag::note_template_param_here);
5848
5849 ArgType = Var->getType();
5850 }
5851 } else if (!AddressTaken && ParamType->isPointerType()) {
5852 if (Var->getType()->isArrayType()) {
5853 // Array-to-pointer decay.
5854 ArgType = S.Context.getArrayDecayedType(Var->getType());
5855 } else {
5856 // If the template parameter has pointer type but the address of
5857 // this object was not taken, complain and (possibly) recover by
5858 // taking the address of the entity.
5859 ArgType = S.Context.getPointerType(Var->getType());
5860 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5861 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5862 << ParamType;
5863 S.Diag(Param->getLocation(), diag::note_template_param_here);
5864 return true;
5865 }
5866
5867 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5868 << ParamType
5869 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5870
5871 S.Diag(Param->getLocation(), diag::note_template_param_here);
5872 }
5873 }
5874 }
5875
5876 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5877 Arg, ArgType))
5878 return true;
5879
5880 // Create the template argument.
5881 Converted =
5882 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5883 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5884 return false;
5885}
5886
5887/// \brief Checks whether the given template argument is a pointer to
5888/// member constant according to C++ [temp.arg.nontype]p1.
5889static bool CheckTemplateArgumentPointerToMember(Sema &S,
5890 NonTypeTemplateParmDecl *Param,
5891 QualType ParamType,
5892 Expr *&ResultArg,
5893 TemplateArgument &Converted) {
5894 bool Invalid = false;
5895
5896 Expr *Arg = ResultArg;
5897 bool ObjCLifetimeConversion;
5898
5899 // C++ [temp.arg.nontype]p1:
5900 //
5901 // A template-argument for a non-type, non-template
5902 // template-parameter shall be one of: [...]
5903 //
5904 // -- a pointer to member expressed as described in 5.3.1.
5905 DeclRefExpr *DRE = nullptr;
5906
5907 // In C++98/03 mode, give an extension warning on any extra parentheses.
5908 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5909 bool ExtraParens = false;
5910 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5911 if (!Invalid && !ExtraParens) {
5912 S.Diag(Arg->getLocStart(),
5913 S.getLangOpts().CPlusPlus11 ?
5914 diag::warn_cxx98_compat_template_arg_extra_parens :
5915 diag::ext_template_arg_extra_parens)
5916 << Arg->getSourceRange();
5917 ExtraParens = true;
5918 }
5919
5920 Arg = Parens->getSubExpr();
5921 }
5922
5923 while (SubstNonTypeTemplateParmExpr *subst =
5924 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5925 Arg = subst->getReplacement()->IgnoreImpCasts();
5926
5927 // A pointer-to-member constant written &Class::member.
5928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5929 if (UnOp->getOpcode() == UO_AddrOf) {
5930 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5931 if (DRE && !DRE->getQualifier())
5932 DRE = nullptr;
5933 }
5934 }
5935 // A constant of pointer-to-member type.
5936 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5937 ValueDecl *VD = DRE->getDecl();
5938 if (VD->getType()->isMemberPointerType()) {
5939 if (isa<NonTypeTemplateParmDecl>(VD)) {
5940 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5941 Converted = TemplateArgument(Arg);
5942 } else {
5943 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5944 Converted = TemplateArgument(VD, ParamType);
5945 }
5946 return Invalid;
5947 }
5948 }
5949
5950 DRE = nullptr;
5951 }
5952
5953 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5954
5955 // Check for a null pointer value.
5956 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
5957 Entity)) {
5958 case NPV_Error:
5959 return true;
5960 case NPV_NullPointer:
5961 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5962 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5963 /*isNullPtr*/true);
5964 return false;
5965 case NPV_NotNullPointer:
5966 break;
5967 }
5968
5969 if (S.IsQualificationConversion(ResultArg->getType(),
5970 ParamType.getNonReferenceType(), false,
5971 ObjCLifetimeConversion)) {
5972 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
5973 ResultArg->getValueKind())
5974 .get();
5975 } else if (!S.Context.hasSameUnqualifiedType(
5976 ResultArg->getType(), ParamType.getNonReferenceType())) {
5977 // We can't perform this conversion.
5978 S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
5979 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
5980 S.Diag(Param->getLocation(), diag::note_template_param_here);
5981 return true;
5982 }
5983
5984 if (!DRE)
5985 return S.Diag(Arg->getLocStart(),
5986 diag::err_template_arg_not_pointer_to_member_form)
5987 << Arg->getSourceRange();
5988
5989 if (isa<FieldDecl>(DRE->getDecl()) ||
5990 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5991 isa<CXXMethodDecl>(DRE->getDecl())) {
5992 assert((isa<FieldDecl>(DRE->getDecl()) ||(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl
()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast
<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
"Only non-static member pointers can make it here") ? 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\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5995, __extension__ __PRETTY_FUNCTION__))
5993 isa<IndirectFieldDecl>(DRE->getDecl()) ||(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl
()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast
<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
"Only non-static member pointers can make it here") ? 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\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5995, __extension__ __PRETTY_FUNCTION__))
5994 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl
()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast
<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
"Only non-static member pointers can make it here") ? 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\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5995, __extension__ __PRETTY_FUNCTION__))
5995 "Only non-static member pointers can make it here")(static_cast <bool> ((isa<FieldDecl>(DRE->getDecl
()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast
<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
"Only non-static member pointers can make it here") ? 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\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5995, __extension__ __PRETTY_FUNCTION__))
;
5996
5997 // Okay: this is the address of a non-static member, and therefore
5998 // a member pointer constant.
5999 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6000 Converted = TemplateArgument(Arg);
6001 } else {
6002 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
6003 Converted = TemplateArgument(D, ParamType);
6004 }
6005 return Invalid;
6006 }
6007
6008 // We found something else, but we don't know specifically what it is.
6009 S.Diag(Arg->getLocStart(),
6010 diag::err_template_arg_not_pointer_to_member_form)
6011 << Arg->getSourceRange();
6012 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6013 return true;
6014}
6015
6016/// \brief Check a template argument against its corresponding
6017/// non-type template parameter.
6018///
6019/// This routine implements the semantics of C++ [temp.arg.nontype].
6020/// If an error occurred, it returns ExprError(); otherwise, it
6021/// returns the converted template argument. \p ParamType is the
6022/// type of the non-type template parameter after it has been instantiated.
6023ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6024 QualType ParamType, Expr *Arg,
6025 TemplateArgument &Converted,
6026 CheckTemplateArgumentKind CTAK) {
6027 SourceLocation StartLoc = Arg->getLocStart();
6028
6029 // If the parameter type somehow involves auto, deduce the type now.
6030 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
6031 // During template argument deduction, we allow 'decltype(auto)' to
6032 // match an arbitrary dependent argument.
6033 // FIXME: The language rules don't say what happens in this case.
6034 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6035 // expression is merely instantiation-dependent; is this enough?
6036 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6037 auto *AT = dyn_cast<AutoType>(ParamType);
6038 if (AT && AT->isDecltypeAuto()) {
6039 Converted = TemplateArgument(Arg);
6040 return Arg;
6041 }
6042 }
6043
6044 // When checking a deduced template argument, deduce from its type even if
6045 // the type is dependent, in order to check the types of non-type template
6046 // arguments line up properly in partial ordering.
6047 Optional<unsigned> Depth;
6048 if (CTAK != CTAK_Specified)
6049 Depth = Param->getDepth() + 1;
6050 if (DeduceAutoType(
6051 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6052 Arg, ParamType, Depth) == DAR_Failed) {
6053 Diag(Arg->getExprLoc(),
6054 diag::err_non_type_template_parm_type_deduction_failure)
6055 << Param->getDeclName() << Param->getType() << Arg->getType()
6056 << Arg->getSourceRange();
6057 Diag(Param->getLocation(), diag::note_template_param_here);
6058 return ExprError();
6059 }
6060 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6061 // an error. The error message normally references the parameter
6062 // declaration, but here we'll pass the argument location because that's
6063 // where the parameter type is deduced.
6064 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6065 if (ParamType.isNull()) {
6066 Diag(Param->getLocation(), diag::note_template_param_here);
6067 return ExprError();
6068 }
6069 }
6070
6071 // We should have already dropped all cv-qualifiers by now.
6072 assert(!ParamType.hasQualifiers() &&(static_cast <bool> (!ParamType.hasQualifiers() &&
"non-type template parameter type cannot be qualified") ? void
(0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6073, __extension__ __PRETTY_FUNCTION__))
6073 "non-type template parameter type cannot be qualified")(static_cast <bool> (!ParamType.hasQualifiers() &&
"non-type template parameter type cannot be qualified") ? void
(0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6073, __extension__ __PRETTY_FUNCTION__))
;
6074
6075 if (CTAK == CTAK_Deduced &&
6076 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6077 Arg->getType())) {
6078 // FIXME: If either type is dependent, we skip the check. This isn't
6079 // correct, since during deduction we're supposed to have replaced each
6080 // template parameter with some unique (non-dependent) placeholder.
6081 // FIXME: If the argument type contains 'auto', we carry on and fail the
6082 // type check in order to force specific types to be more specialized than
6083 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6084 // work.
6085 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6086 !Arg->getType()->getContainedAutoType()) {
6087 Converted = TemplateArgument(Arg);
6088 return Arg;
6089 }
6090 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6091 // we should actually be checking the type of the template argument in P,
6092 // not the type of the template argument deduced from A, against the
6093 // template parameter type.
6094 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6095 << Arg->getType()
6096 << ParamType.getUnqualifiedType();
6097 Diag(Param->getLocation(), diag::note_template_param_here);
6098 return ExprError();
6099 }
6100
6101 // If either the parameter has a dependent type or the argument is
6102 // type-dependent, there's nothing we can check now.
6103 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6104 // FIXME: Produce a cloned, canonical expression?
6105 Converted = TemplateArgument(Arg);
6106 return Arg;
6107 }
6108
6109 // The initialization of the parameter from the argument is
6110 // a constant-evaluated context.
6111 EnterExpressionEvaluationContext ConstantEvaluated(
6112 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6113
6114 if (getLangOpts().CPlusPlus17) {
6115 // C++17 [temp.arg.nontype]p1:
6116 // A template-argument for a non-type template parameter shall be
6117 // a converted constant expression of the type of the template-parameter.
6118 APValue Value;
6119 ExprResult ArgResult = CheckConvertedConstantExpression(
6120 Arg, ParamType, Value, CCEK_TemplateArg);
6121 if (ArgResult.isInvalid())
6122 return ExprError();
6123
6124 // For a value-dependent argument, CheckConvertedConstantExpression is
6125 // permitted (and expected) to be unable to determine a value.
6126 if (ArgResult.get()->isValueDependent()) {
6127 Converted = TemplateArgument(ArgResult.get());
6128 return ArgResult;
6129 }
6130
6131 QualType CanonParamType = Context.getCanonicalType(ParamType);
6132
6133 // Convert the APValue to a TemplateArgument.
6134 switch (Value.getKind()) {
6135 case APValue::Uninitialized:
6136 assert(ParamType->isNullPtrType())(static_cast <bool> (ParamType->isNullPtrType()) ? void
(0) : __assert_fail ("ParamType->isNullPtrType()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6136, __extension__ __PRETTY_FUNCTION__))
;
6137 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6138 break;
6139 case APValue::Int:
6140 assert(ParamType->isIntegralOrEnumerationType())(static_cast <bool> (ParamType->isIntegralOrEnumerationType
()) ? void (0) : __assert_fail ("ParamType->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6140, __extension__ __PRETTY_FUNCTION__))
;
6141 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6142 break;
6143 case APValue::MemberPointer: {
6144 assert(ParamType->isMemberPointerType())(static_cast <bool> (ParamType->isMemberPointerType(
)) ? void (0) : __assert_fail ("ParamType->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6144, __extension__ __PRETTY_FUNCTION__))
;
6145
6146 // FIXME: We need TemplateArgument representation and mangling for these.
6147 if (!Value.getMemberPointerPath().empty()) {
6148 Diag(Arg->getLocStart(),
6149 diag::err_template_arg_member_ptr_base_derived_not_supported)
6150 << Value.getMemberPointerDecl() << ParamType
6151 << Arg->getSourceRange();
6152 return ExprError();
6153 }
6154
6155 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6156 Converted = VD ? TemplateArgument(VD, CanonParamType)
6157 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6158 break;
6159 }
6160 case APValue::LValue: {
6161 // For a non-type template-parameter of pointer or reference type,
6162 // the value of the constant expression shall not refer to
6163 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||(static_cast <bool> (ParamType->isPointerType() || ParamType
->isReferenceType() || ParamType->isNullPtrType()) ? void
(0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6164, __extension__ __PRETTY_FUNCTION__))
6164 ParamType->isNullPtrType())(static_cast <bool> (ParamType->isPointerType() || ParamType
->isReferenceType() || ParamType->isNullPtrType()) ? void
(0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6164, __extension__ __PRETTY_FUNCTION__))
;
6165 // -- a temporary object
6166 // -- a string literal
6167 // -- the result of a typeid expression, or
6168 // -- a predefined __func__ variable
6169 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6170 if (isa<CXXUuidofExpr>(E)) {
6171 Converted = TemplateArgument(const_cast<Expr*>(E));
6172 break;
6173 }
6174 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6175 << Arg->getSourceRange();
6176 return ExprError();
6177 }
6178 auto *VD = const_cast<ValueDecl *>(
6179 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6180 // -- a subobject
6181 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6182 VD && VD->getType()->isArrayType() &&
6183 Value.getLValuePath()[0].ArrayIndex == 0 &&
6184 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6185 // Per defect report (no number yet):
6186 // ... other than a pointer to the first element of a complete array
6187 // object.
6188 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6189 Value.isLValueOnePastTheEnd()) {
6190 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6191 << Value.getAsString(Context, ParamType);
6192 return ExprError();
6193 }
6194 assert((VD || !ParamType->isReferenceType()) &&(static_cast <bool> ((VD || !ParamType->isReferenceType
()) && "null reference should not be a constant expression"
) ? void (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6195, __extension__ __PRETTY_FUNCTION__))
6195 "null reference should not be a constant expression")(static_cast <bool> ((VD || !ParamType->isReferenceType
()) && "null reference should not be a constant expression"
) ? void (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6195, __extension__ __PRETTY_FUNCTION__))
;
6196 assert((!VD || !ParamType->isNullPtrType()) &&(static_cast <bool> ((!VD || !ParamType->isNullPtrType
()) && "non-null value of type nullptr_t?") ? void (0
) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6197, __extension__ __PRETTY_FUNCTION__))
6197 "non-null value of type nullptr_t?")(static_cast <bool> ((!VD || !ParamType->isNullPtrType
()) && "non-null value of type nullptr_t?") ? void (0
) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6197, __extension__ __PRETTY_FUNCTION__))
;
6198 Converted = VD ? TemplateArgument(VD, CanonParamType)
6199 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6200 break;
6201 }
6202 case APValue::AddrLabelDiff:
6203 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6204 case APValue::Float:
6205 case APValue::ComplexInt:
6206 case APValue::ComplexFloat:
6207 case APValue::Vector:
6208 case APValue::Array:
6209 case APValue::Struct:
6210 case APValue::Union:
6211 llvm_unreachable("invalid kind for template argument")::llvm::llvm_unreachable_internal("invalid kind for template argument"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6211)
;
6212 }
6213
6214 return ArgResult.get();
6215 }
6216
6217 // C++ [temp.arg.nontype]p5:
6218 // The following conversions are performed on each expression used
6219 // as a non-type template-argument. If a non-type
6220 // template-argument cannot be converted to the type of the
6221 // corresponding template-parameter then the program is
6222 // ill-formed.
6223 if (ParamType->isIntegralOrEnumerationType()) {
6224 // C++11:
6225 // -- for a non-type template-parameter of integral or
6226 // enumeration type, conversions permitted in a converted
6227 // constant expression are applied.
6228 //
6229 // C++98:
6230 // -- for a non-type template-parameter of integral or
6231 // enumeration type, integral promotions (4.5) and integral
6232 // conversions (4.7) are applied.
6233
6234 if (getLangOpts().CPlusPlus11) {
6235 // C++ [temp.arg.nontype]p1:
6236 // A template-argument for a non-type, non-template template-parameter
6237 // shall be one of:
6238 //
6239 // -- for a non-type template-parameter of integral or enumeration
6240 // type, a converted constant expression of the type of the
6241 // template-parameter; or
6242 llvm::APSInt Value;
6243 ExprResult ArgResult =
6244 CheckConvertedConstantExpression(Arg, ParamType, Value,
6245 CCEK_TemplateArg);
6246 if (ArgResult.isInvalid())
6247 return ExprError();
6248
6249 // We can't check arbitrary value-dependent arguments.
6250 if (ArgResult.get()->isValueDependent()) {
6251 Converted = TemplateArgument(ArgResult.get());
6252 return ArgResult;
6253 }
6254
6255 // Widen the argument value to sizeof(parameter type). This is almost
6256 // always a no-op, except when the parameter type is bool. In
6257 // that case, this may extend the argument from 1 bit to 8 bits.
6258 QualType IntegerType = ParamType;
6259 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6260 IntegerType = Enum->getDecl()->getIntegerType();
6261 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6262
6263 Converted = TemplateArgument(Context, Value,
6264 Context.getCanonicalType(ParamType));
6265 return ArgResult;
6266 }
6267
6268 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6269 if (ArgResult.isInvalid())
6270 return ExprError();
6271 Arg = ArgResult.get();
6272
6273 QualType ArgType = Arg->getType();
6274
6275 // C++ [temp.arg.nontype]p1:
6276 // A template-argument for a non-type, non-template
6277 // template-parameter shall be one of:
6278 //
6279 // -- an integral constant-expression of integral or enumeration
6280 // type; or
6281 // -- the name of a non-type template-parameter; or
6282 llvm::APSInt Value;
6283 if (!ArgType->isIntegralOrEnumerationType()) {
6284 Diag(Arg->getLocStart(),
6285 diag::err_template_arg_not_integral_or_enumeral)
6286 << ArgType << Arg->getSourceRange();
6287 Diag(Param->getLocation(), diag::note_template_param_here);
6288 return ExprError();
6289 } else if (!Arg->isValueDependent()) {
6290 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6291 QualType T;
6292
6293 public:
6294 TmplArgICEDiagnoser(QualType T) : T(T) { }
6295
6296 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6297 SourceRange SR) override {
6298 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6299 }
6300 } Diagnoser(ArgType);
6301
6302 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6303 false).get();
6304 if (!Arg)
6305 return ExprError();
6306 }
6307
6308 // From here on out, all we care about is the unqualified form
6309 // of the argument type.
6310 ArgType = ArgType.getUnqualifiedType();
6311
6312 // Try to convert the argument to the parameter's type.
6313 if (Context.hasSameType(ParamType, ArgType)) {
6314 // Okay: no conversion necessary
6315 } else if (ParamType->isBooleanType()) {
6316 // This is an integral-to-boolean conversion.
6317 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6318 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6319 !ParamType->isEnumeralType()) {
6320 // This is an integral promotion or conversion.
6321 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6322 } else {
6323 // We can't perform this conversion.
6324 Diag(Arg->getLocStart(),
6325 diag::err_template_arg_not_convertible)
6326 << Arg->getType() << ParamType << Arg->getSourceRange();
6327 Diag(Param->getLocation(), diag::note_template_param_here);
6328 return ExprError();
6329 }
6330
6331 // Add the value of this argument to the list of converted
6332 // arguments. We use the bitwidth and signedness of the template
6333 // parameter.
6334 if (Arg->isValueDependent()) {
6335 // The argument is value-dependent. Create a new
6336 // TemplateArgument with the converted expression.
6337 Converted = TemplateArgument(Arg);
6338 return Arg;
6339 }
6340
6341 QualType IntegerType = Context.getCanonicalType(ParamType);
6342 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6343 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6344
6345 if (ParamType->isBooleanType()) {
6346 // Value must be zero or one.
6347 Value = Value != 0;
6348 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6349 if (Value.getBitWidth() != AllowedBits)
6350 Value = Value.extOrTrunc(AllowedBits);
6351 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6352 } else {
6353 llvm::APSInt OldValue = Value;
6354
6355 // Coerce the template argument's value to the value it will have
6356 // based on the template parameter's type.
6357 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6358 if (Value.getBitWidth() != AllowedBits)
6359 Value = Value.extOrTrunc(AllowedBits);
6360 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6361
6362 // Complain if an unsigned parameter received a negative value.
6363 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6364 && (OldValue.isSigned() && OldValue.isNegative())) {
6365 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6366 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6367 << Arg->getSourceRange();
6368 Diag(Param->getLocation(), diag::note_template_param_here);
6369 }
6370
6371 // Complain if we overflowed the template parameter's type.
6372 unsigned RequiredBits;
6373 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6374 RequiredBits = OldValue.getActiveBits();
6375 else if (OldValue.isUnsigned())
6376 RequiredBits = OldValue.getActiveBits() + 1;
6377 else
6378 RequiredBits = OldValue.getMinSignedBits();
6379 if (RequiredBits > AllowedBits) {
6380 Diag(Arg->getLocStart(),
6381 diag::warn_template_arg_too_large)
6382 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6383 << Arg->getSourceRange();
6384 Diag(Param->getLocation(), diag::note_template_param_here);
6385 }
6386 }
6387
6388 Converted = TemplateArgument(Context, Value,
6389 ParamType->isEnumeralType()
6390 ? Context.getCanonicalType(ParamType)
6391 : IntegerType);
6392 return Arg;
6393 }
6394
6395 QualType ArgType = Arg->getType();
6396 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6397
6398 // Handle pointer-to-function, reference-to-function, and
6399 // pointer-to-member-function all in (roughly) the same way.
6400 if (// -- For a non-type template-parameter of type pointer to
6401 // function, only the function-to-pointer conversion (4.3) is
6402 // applied. If the template-argument represents a set of
6403 // overloaded functions (or a pointer to such), the matching
6404 // function is selected from the set (13.4).
6405 (ParamType->isPointerType() &&
6406 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6407 // -- For a non-type template-parameter of type reference to
6408 // function, no conversions apply. If the template-argument
6409 // represents a set of overloaded functions, the matching
6410 // function is selected from the set (13.4).
6411 (ParamType->isReferenceType() &&
6412 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6413 // -- For a non-type template-parameter of type pointer to
6414 // member function, no conversions apply. If the
6415 // template-argument represents a set of overloaded member
6416 // functions, the matching member function is selected from
6417 // the set (13.4).
6418 (ParamType->isMemberPointerType() &&
6419 ParamType->getAs<MemberPointerType>()->getPointeeType()
6420 ->isFunctionType())) {
6421
6422 if (Arg->getType() == Context.OverloadTy) {
6423 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6424 true,
6425 FoundResult)) {
6426 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6427 return ExprError();
6428
6429 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6430 ArgType = Arg->getType();
6431 } else
6432 return ExprError();
6433 }
6434
6435 if (!ParamType->isMemberPointerType()) {
6436 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6437 ParamType,
6438 Arg, Converted))
6439 return ExprError();
6440 return Arg;
6441 }
6442
6443 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6444 Converted))
6445 return ExprError();
6446 return Arg;
6447 }
6448
6449 if (ParamType->isPointerType()) {
6450 // -- for a non-type template-parameter of type pointer to
6451 // object, qualification conversions (4.4) and the
6452 // array-to-pointer conversion (4.2) are applied.
6453 // C++0x also allows a value of std::nullptr_t.
6454 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&(static_cast <bool> (ParamType->getPointeeType()->
isIncompleteOrObjectType() && "Only object pointers allowed here"
) ? void (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6455, __extension__ __PRETTY_FUNCTION__))
6455 "Only object pointers allowed here")(static_cast <bool> (ParamType->getPointeeType()->
isIncompleteOrObjectType() && "Only object pointers allowed here"
) ? void (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6455, __extension__ __PRETTY_FUNCTION__))
;
6456
6457 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6458 ParamType,
6459 Arg, Converted))
6460 return ExprError();
6461 return Arg;
6462 }
6463
6464 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6465 // -- For a non-type template-parameter of type reference to
6466 // object, no conversions apply. The type referred to by the
6467 // reference may be more cv-qualified than the (otherwise
6468 // identical) type of the template-argument. The
6469 // template-parameter is bound directly to the
6470 // template-argument, which must be an lvalue.
6471 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&(static_cast <bool> (ParamRefType->getPointeeType()->
isIncompleteOrObjectType() && "Only object references allowed here"
) ? void (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6472, __extension__ __PRETTY_FUNCTION__))
6472 "Only object references allowed here")(static_cast <bool> (ParamRefType->getPointeeType()->
isIncompleteOrObjectType() && "Only object references allowed here"
) ? void (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6472, __extension__ __PRETTY_FUNCTION__))
;
6473
6474 if (Arg->getType() == Context.OverloadTy) {
6475 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6476 ParamRefType->getPointeeType(),
6477 true,
6478 FoundResult)) {
6479 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6480 return ExprError();
6481
6482 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6483 ArgType = Arg->getType();
6484 } else
6485 return ExprError();
6486 }
6487
6488 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6489 ParamType,
6490 Arg, Converted))
6491 return ExprError();
6492 return Arg;
6493 }
6494
6495 // Deal with parameters of type std::nullptr_t.
6496 if (ParamType->isNullPtrType()) {
6497 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6498 Converted = TemplateArgument(Arg);
6499 return Arg;
6500 }
6501
6502 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6503 case NPV_NotNullPointer:
6504 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6505 << Arg->getType() << ParamType;
6506 Diag(Param->getLocation(), diag::note_template_param_here);
6507 return ExprError();
6508
6509 case NPV_Error:
6510 return ExprError();
6511
6512 case NPV_NullPointer:
6513 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6514 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6515 /*isNullPtr*/true);
6516 return Arg;
6517 }
6518 }
6519
6520 // -- For a non-type template-parameter of type pointer to data
6521 // member, qualification conversions (4.4) are applied.
6522 assert(ParamType->isMemberPointerType() && "Only pointers to members remain")(static_cast <bool> (ParamType->isMemberPointerType(
) && "Only pointers to members remain") ? void (0) : __assert_fail
("ParamType->isMemberPointerType() && \"Only pointers to members remain\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6522, __extension__ __PRETTY_FUNCTION__))
;
6523
6524 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6525 Converted))
6526 return ExprError();
6527 return Arg;
6528}
6529
6530static void DiagnoseTemplateParameterListArityMismatch(
6531 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6532 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6533
6534/// \brief Check a template argument against its corresponding
6535/// template template parameter.
6536///
6537/// This routine implements the semantics of C++ [temp.arg.template].
6538/// It returns true if an error occurred, and false otherwise.
6539bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6540 TemplateArgumentLoc &Arg,
6541 unsigned ArgumentPackIndex) {
6542 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6543 TemplateDecl *Template = Name.getAsTemplateDecl();
6544 if (!Template) {
6545 // Any dependent template name is fine.
6546 assert(Name.isDependent() && "Non-dependent template isn't a declaration?")(static_cast <bool> (Name.isDependent() && "Non-dependent template isn't a declaration?"
) ? void (0) : __assert_fail ("Name.isDependent() && \"Non-dependent template isn't a declaration?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6546, __extension__ __PRETTY_FUNCTION__))
;
6547 return false;
6548 }
6549
6550 if (Template->isInvalidDecl())
6551 return true;
6552
6553 // C++0x [temp.arg.template]p1:
6554 // A template-argument for a template template-parameter shall be
6555 // the name of a class template or an alias template, expressed as an
6556 // id-expression. When the template-argument names a class template, only
6557 // primary class templates are considered when matching the
6558 // template template argument with the corresponding parameter;
6559 // partial specializations are not considered even if their
6560 // parameter lists match that of the template template parameter.
6561 //
6562 // Note that we also allow template template parameters here, which
6563 // will happen when we are dealing with, e.g., class template
6564 // partial specializations.
6565 if (!isa<ClassTemplateDecl>(Template) &&
6566 !isa<TemplateTemplateParmDecl>(Template) &&
6567 !isa<TypeAliasTemplateDecl>(Template) &&
6568 !isa<BuiltinTemplateDecl>(Template)) {
6569 assert(isa<FunctionTemplateDecl>(Template) &&(static_cast <bool> (isa<FunctionTemplateDecl>(Template
) && "Only function templates are possible here") ? void
(0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6570, __extension__ __PRETTY_FUNCTION__))
6570 "Only function templates are possible here")(static_cast <bool> (isa<FunctionTemplateDecl>(Template
) && "Only function templates are possible here") ? void
(0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6570, __extension__ __PRETTY_FUNCTION__))
;
6571 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6572 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6573 << Template;
6574 }
6575
6576 TemplateParameterList *Params = Param->getTemplateParameters();
6577 if (Param->isExpandedParameterPack())
6578 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6579
6580 // C++1z [temp.arg.template]p3: (DR 150)
6581 // A template-argument matches a template template-parameter P when P
6582 // is at least as specialized as the template-argument A.
6583 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6584 // Quick check for the common case:
6585 // If P contains a parameter pack, then A [...] matches P if each of A's
6586 // template parameters matches the corresponding template parameter in
6587 // the template-parameter-list of P.
6588 if (TemplateParameterListsAreEqual(
6589 Template->getTemplateParameters(), Params, false,
6590 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6591 return false;
6592
6593 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6594 Arg.getLocation()))
6595 return false;
6596 // FIXME: Produce better diagnostics for deduction failures.
6597 }
6598
6599 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6600 Params,
6601 true,
6602 TPL_TemplateTemplateArgumentMatch,
6603 Arg.getLocation());
6604}
6605
6606/// \brief Given a non-type template argument that refers to a
6607/// declaration and the type of its corresponding non-type template
6608/// parameter, produce an expression that properly refers to that
6609/// declaration.
6610ExprResult
6611Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6612 QualType ParamType,
6613 SourceLocation Loc) {
6614 // C++ [temp.param]p8:
6615 //
6616 // A non-type template-parameter of type "array of T" or
6617 // "function returning T" is adjusted to be of type "pointer to
6618 // T" or "pointer to function returning T", respectively.
6619 if (ParamType->isArrayType())
6620 ParamType = Context.getArrayDecayedType(ParamType);
6621 else if (ParamType->isFunctionType())
6622 ParamType = Context.getPointerType(ParamType);
6623
6624 // For a NULL non-type template argument, return nullptr casted to the
6625 // parameter's type.
6626 if (Arg.getKind() == TemplateArgument::NullPtr) {
6627 return ImpCastExprToType(
6628 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6629 ParamType,
6630 ParamType->getAs<MemberPointerType>()
6631 ? CK_NullToMemberPointer
6632 : CK_NullToPointer);
6633 }
6634 assert(Arg.getKind() == TemplateArgument::Declaration &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Declaration && "Only declaration template arguments permitted here"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6635, __extension__ __PRETTY_FUNCTION__))
6635 "Only declaration template arguments permitted here")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Declaration && "Only declaration template arguments permitted here"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6635, __extension__ __PRETTY_FUNCTION__))
;
6636
6637 ValueDecl *VD = Arg.getAsDecl();
6638
6639 if (VD->getDeclContext()->isRecord() &&
6640 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6641 isa<IndirectFieldDecl>(VD))) {
6642 // If the value is a class member, we might have a pointer-to-member.
6643 // Determine whether the non-type template template parameter is of
6644 // pointer-to-member type. If so, we need to build an appropriate
6645 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6646 // would refer to the member itself.
6647 if (ParamType->isMemberPointerType()) {
6648 QualType ClassType
6649 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6650 NestedNameSpecifier *Qualifier
6651 = NestedNameSpecifier::Create(Context, nullptr, false,
6652 ClassType.getTypePtr());
6653 CXXScopeSpec SS;
6654 SS.MakeTrivial(Context, Qualifier, Loc);
6655
6656 // The actual value-ness of this is unimportant, but for
6657 // internal consistency's sake, references to instance methods
6658 // are r-values.
6659 ExprValueKind VK = VK_LValue;
6660 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6661 VK = VK_RValue;
6662
6663 ExprResult RefExpr = BuildDeclRefExpr(VD,
6664 VD->getType().getNonReferenceType(),
6665 VK,
6666 Loc,
6667 &SS);
6668 if (RefExpr.isInvalid())
6669 return ExprError();
6670
6671 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6672
6673 // We might need to perform a trailing qualification conversion, since
6674 // the element type on the parameter could be more qualified than the
6675 // element type in the expression we constructed.
6676 bool ObjCLifetimeConversion;
6677 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6678 ParamType.getUnqualifiedType(), false,
6679 ObjCLifetimeConversion))
6680 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6681
6682 assert(!RefExpr.isInvalid() &&(static_cast <bool> (!RefExpr.isInvalid() && Context
.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType
.getUnqualifiedType())) ? void (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6684, __extension__ __PRETTY_FUNCTION__))
6683 Context.hasSameType(((Expr*) RefExpr.get())->getType(),(static_cast <bool> (!RefExpr.isInvalid() && Context
.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType
.getUnqualifiedType())) ? void (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6684, __extension__ __PRETTY_FUNCTION__))
6684 ParamType.getUnqualifiedType()))(static_cast <bool> (!RefExpr.isInvalid() && Context
.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType
.getUnqualifiedType())) ? void (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6684, __extension__ __PRETTY_FUNCTION__))
;
6685 return RefExpr;
6686 }
6687 }
6688
6689 QualType T = VD->getType().getNonReferenceType();
6690
6691 if (ParamType->isPointerType()) {
6692 // When the non-type template parameter is a pointer, take the
6693 // address of the declaration.
6694 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6695 if (RefExpr.isInvalid())
6696 return ExprError();
6697
6698 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6699 (T->isFunctionType() || T->isArrayType())) {
6700 // Decay functions and arrays unless we're forming a pointer to array.
6701 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6702 if (RefExpr.isInvalid())
6703 return ExprError();
6704
6705 return RefExpr;
6706 }
6707
6708 // Take the address of everything else
6709 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6710 }
6711
6712 ExprValueKind VK = VK_RValue;
6713
6714 // If the non-type template parameter has reference type, qualify the
6715 // resulting declaration reference with the extra qualifiers on the
6716 // type that the reference refers to.
6717 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6718 VK = VK_LValue;
6719 T = Context.getQualifiedType(T,
6720 TargetRef->getPointeeType().getQualifiers());
6721 } else if (isa<FunctionDecl>(VD)) {
6722 // References to functions are always lvalues.
6723 VK = VK_LValue;
6724 }
6725
6726 return BuildDeclRefExpr(VD, T, VK, Loc);
6727}
6728
6729/// \brief Construct a new expression that refers to the given
6730/// integral template argument with the given source-location
6731/// information.
6732///
6733/// This routine takes care of the mapping from an integral template
6734/// argument (which may have any integral type) to the appropriate
6735/// literal value.
6736ExprResult
6737Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6738 SourceLocation Loc) {
6739 assert(Arg.getKind() == TemplateArgument::Integral &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Integral && "Operation is only valid for integral template arguments"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6740, __extension__ __PRETTY_FUNCTION__))
6740 "Operation is only valid for integral template arguments")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Integral && "Operation is only valid for integral template arguments"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6740, __extension__ __PRETTY_FUNCTION__))
;
6741 QualType OrigT = Arg.getIntegralType();
6742
6743 // If this is an enum type that we're instantiating, we need to use an integer
6744 // type the same size as the enumerator. We don't want to build an
6745 // IntegerLiteral with enum type. The integer type of an enum type can be of
6746 // any integral type with C++11 enum classes, make sure we create the right
6747 // type of literal for it.
6748 QualType T = OrigT;
6749 if (const EnumType *ET = OrigT->getAs<EnumType>())
6750 T = ET->getDecl()->getIntegerType();
6751
6752 Expr *E;
6753 if (T->isAnyCharacterType()) {
6754 // This does not need to handle u8 character literals because those are
6755 // of type char, and so can also be covered by an ASCII character literal.
6756 CharacterLiteral::CharacterKind Kind;
6757 if (T->isWideCharType())
6758 Kind = CharacterLiteral::Wide;
6759 else if (T->isChar16Type())
6760 Kind = CharacterLiteral::UTF16;
6761 else if (T->isChar32Type())
6762 Kind = CharacterLiteral::UTF32;
6763 else
6764 Kind = CharacterLiteral::Ascii;
6765
6766 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6767 Kind, T, Loc);
6768 } else if (T->isBooleanType()) {
6769 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6770 T, Loc);
6771 } else if (T->isNullPtrType()) {
6772 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6773 } else {
6774 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6775 }
6776
6777 if (OrigT->isEnumeralType()) {
6778 // FIXME: This is a hack. We need a better way to handle substituted
6779 // non-type template parameters.
6780 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6781 nullptr,
6782 Context.getTrivialTypeSourceInfo(OrigT, Loc),
6783 Loc, Loc);
6784 }
6785
6786 return E;
6787}
6788
6789/// \brief Match two template parameters within template parameter lists.
6790static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6791 bool Complain,
6792 Sema::TemplateParameterListEqualKind Kind,
6793 SourceLocation TemplateArgLoc) {
6794 // Check the actual kind (type, non-type, template).
6795 if (Old->getKind() != New->getKind()) {
6796 if (Complain) {
6797 unsigned NextDiag = diag::err_template_param_different_kind;
6798 if (TemplateArgLoc.isValid()) {
6799 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6800 NextDiag = diag::note_template_param_different_kind;
6801 }
6802 S.Diag(New->getLocation(), NextDiag)
6803 << (Kind != Sema::TPL_TemplateMatch);
6804 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6805 << (Kind != Sema::TPL_TemplateMatch);
6806 }
6807
6808 return false;
6809 }
6810
6811 // Check that both are parameter packs or neither are parameter packs.
6812 // However, if we are matching a template template argument to a
6813 // template template parameter, the template template parameter can have
6814 // a parameter pack where the template template argument does not.
6815 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6816 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6817 Old->isTemplateParameterPack())) {
6818 if (Complain) {
6819 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6820 if (TemplateArgLoc.isValid()) {
6821 S.Diag(TemplateArgLoc,
6822 diag::err_template_arg_template_params_mismatch);
6823 NextDiag = diag::note_template_parameter_pack_non_pack;
6824 }
6825
6826 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6827 : isa<NonTypeTemplateParmDecl>(New)? 1
6828 : 2;
6829 S.Diag(New->getLocation(), NextDiag)
6830 << ParamKind << New->isParameterPack();
6831 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6832 << ParamKind << Old->isParameterPack();
6833 }
6834
6835 return false;
6836 }
6837
6838 // For non-type template parameters, check the type of the parameter.
6839 if (NonTypeTemplateParmDecl *OldNTTP
6840 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6841 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6842
6843 // If we are matching a template template argument to a template
6844 // template parameter and one of the non-type template parameter types
6845 // is dependent, then we must wait until template instantiation time
6846 // to actually compare the arguments.
6847 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6848 (OldNTTP->getType()->isDependentType() ||
6849 NewNTTP->getType()->isDependentType()))
6850 return true;
6851
6852 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6853 if (Complain) {
6854 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6855 if (TemplateArgLoc.isValid()) {
6856 S.Diag(TemplateArgLoc,
6857 diag::err_template_arg_template_params_mismatch);
6858 NextDiag = diag::note_template_nontype_parm_different_type;
6859 }
6860 S.Diag(NewNTTP->getLocation(), NextDiag)
6861 << NewNTTP->getType()
6862 << (Kind != Sema::TPL_TemplateMatch);
6863 S.Diag(OldNTTP->getLocation(),
6864 diag::note_template_nontype_parm_prev_declaration)
6865 << OldNTTP->getType();
6866 }
6867
6868 return false;
6869 }
6870
6871 return true;
6872 }
6873
6874 // For template template parameters, check the template parameter types.
6875 // The template parameter lists of template template
6876 // parameters must agree.
6877 if (TemplateTemplateParmDecl *OldTTP
6878 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6879 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6880 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6881 OldTTP->getTemplateParameters(),
6882 Complain,
6883 (Kind == Sema::TPL_TemplateMatch
6884 ? Sema::TPL_TemplateTemplateParmMatch
6885 : Kind),
6886 TemplateArgLoc);
6887 }
6888
6889 return true;
6890}
6891
6892/// \brief Diagnose a known arity mismatch when comparing template argument
6893/// lists.
6894static
6895void DiagnoseTemplateParameterListArityMismatch(Sema &S,
6896 TemplateParameterList *New,
6897 TemplateParameterList *Old,
6898 Sema::TemplateParameterListEqualKind Kind,
6899 SourceLocation TemplateArgLoc) {
6900 unsigned NextDiag = diag::err_template_param_list_different_arity;
6901 if (TemplateArgLoc.isValid()) {
6902 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6903 NextDiag = diag::note_template_param_list_different_arity;
6904 }
6905 S.Diag(New->getTemplateLoc(), NextDiag)
6906 << (New->size() > Old->size())
6907 << (Kind != Sema::TPL_TemplateMatch)
6908 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6909 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6910 << (Kind != Sema::TPL_TemplateMatch)
6911 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6912}
6913
6914/// \brief Determine whether the given template parameter lists are
6915/// equivalent.
6916///
6917/// \param New The new template parameter list, typically written in the
6918/// source code as part of a new template declaration.
6919///
6920/// \param Old The old template parameter list, typically found via
6921/// name lookup of the template declared with this template parameter
6922/// list.
6923///
6924/// \param Complain If true, this routine will produce a diagnostic if
6925/// the template parameter lists are not equivalent.
6926///
6927/// \param Kind describes how we are to match the template parameter lists.
6928///
6929/// \param TemplateArgLoc If this source location is valid, then we
6930/// are actually checking the template parameter list of a template
6931/// argument (New) against the template parameter list of its
6932/// corresponding template template parameter (Old). We produce
6933/// slightly different diagnostics in this scenario.
6934///
6935/// \returns True if the template parameter lists are equal, false
6936/// otherwise.
6937bool
6938Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6939 TemplateParameterList *Old,
6940 bool Complain,
6941 TemplateParameterListEqualKind Kind,
6942 SourceLocation TemplateArgLoc) {
6943 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6944 if (Complain)
6945 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6946 TemplateArgLoc);
6947
6948 return false;
6949 }
6950
6951 // C++0x [temp.arg.template]p3:
6952 // A template-argument matches a template template-parameter (call it P)
6953 // when each of the template parameters in the template-parameter-list of
6954 // the template-argument's corresponding class template or alias template
6955 // (call it A) matches the corresponding template parameter in the
6956 // template-parameter-list of P. [...]
6957 TemplateParameterList::iterator NewParm = New->begin();
6958 TemplateParameterList::iterator NewParmEnd = New->end();
6959 for (TemplateParameterList::iterator OldParm = Old->begin(),
6960 OldParmEnd = Old->end();
6961 OldParm != OldParmEnd; ++OldParm) {
6962 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6963 !(*OldParm)->isTemplateParameterPack()) {
6964 if (NewParm == NewParmEnd) {
6965 if (Complain)
6966 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6967 TemplateArgLoc);
6968
6969 return false;
6970 }
6971
6972 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6973 Kind, TemplateArgLoc))
6974 return false;
6975
6976 ++NewParm;
6977 continue;
6978 }
6979
6980 // C++0x [temp.arg.template]p3:
6981 // [...] When P's template- parameter-list contains a template parameter
6982 // pack (14.5.3), the template parameter pack will match zero or more
6983 // template parameters or template parameter packs in the
6984 // template-parameter-list of A with the same type and form as the
6985 // template parameter pack in P (ignoring whether those template
6986 // parameters are template parameter packs).
6987 for (; NewParm != NewParmEnd; ++NewParm) {
6988 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6989 Kind, TemplateArgLoc))
6990 return false;
6991 }
6992 }
6993
6994 // Make sure we exhausted all of the arguments.
6995 if (NewParm != NewParmEnd) {
6996 if (Complain)
6997 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6998 TemplateArgLoc);
6999
7000 return false;
7001 }
7002
7003 return true;
7004}
7005
7006/// \brief Check whether a template can be declared within this scope.
7007///
7008/// If the template declaration is valid in this scope, returns
7009/// false. Otherwise, issues a diagnostic and returns true.
7010bool
7011Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7012 if (!S)
7013 return false;
7014
7015 // Find the nearest enclosing declaration scope.
7016 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7017 (S->getFlags() & Scope::TemplateParamScope) != 0)
7018 S = S->getParent();
7019
7020 // C++ [temp]p4:
7021 // A template [...] shall not have C linkage.
7022 DeclContext *Ctx = S->getEntity();
7023 if (Ctx && Ctx->isExternCContext()) {
7024 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7025 << TemplateParams->getSourceRange();
7026 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7027 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7028 return true;
7029 }
7030 Ctx = Ctx->getRedeclContext();
7031
7032 // C++ [temp]p2:
7033 // A template-declaration can appear only as a namespace scope or
7034 // class scope declaration.
7035 if (Ctx) {
7036 if (Ctx->isFileContext())
7037 return false;
7038 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7039 // C++ [temp.mem]p2:
7040 // A local class shall not have member templates.
7041 if (RD->isLocalClass())
7042 return Diag(TemplateParams->getTemplateLoc(),
7043 diag::err_template_inside_local_class)
7044 << TemplateParams->getSourceRange();
7045 else
7046 return false;
7047 }
7048 }
7049
7050 return Diag(TemplateParams->getTemplateLoc(),
7051 diag::err_template_outside_namespace_or_class_scope)
7052 << TemplateParams->getSourceRange();
7053}
7054
7055/// \brief Determine what kind of template specialization the given declaration
7056/// is.
7057static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7058 if (!D)
7059 return TSK_Undeclared;
7060
7061 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7062 return Record->getTemplateSpecializationKind();
7063 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7064 return Function->getTemplateSpecializationKind();
7065 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7066 return Var->getTemplateSpecializationKind();
7067
7068 return TSK_Undeclared;
7069}
7070
7071/// \brief Check whether a specialization is well-formed in the current
7072/// context.
7073///
7074/// This routine determines whether a template specialization can be declared
7075/// in the current context (C++ [temp.expl.spec]p2).
7076///
7077/// \param S the semantic analysis object for which this check is being
7078/// performed.
7079///
7080/// \param Specialized the entity being specialized or instantiated, which
7081/// may be a kind of template (class template, function template, etc.) or
7082/// a member of a class template (member function, static data member,
7083/// member class).
7084///
7085/// \param PrevDecl the previous declaration of this entity, if any.
7086///
7087/// \param Loc the location of the explicit specialization or instantiation of
7088/// this entity.
7089///
7090/// \param IsPartialSpecialization whether this is a partial specialization of
7091/// a class template.
7092///
7093/// \returns true if there was an error that we cannot recover from, false
7094/// otherwise.
7095static bool CheckTemplateSpecializationScope(Sema &S,
7096 NamedDecl *Specialized,
7097 NamedDecl *PrevDecl,
7098 SourceLocation Loc,
7099 bool IsPartialSpecialization) {
7100 // Keep these "kind" numbers in sync with the %select statements in the
7101 // various diagnostics emitted by this routine.
7102 int EntityKind = 0;
7103 if (isa<ClassTemplateDecl>(Specialized))
7104 EntityKind = IsPartialSpecialization? 1 : 0;
7105 else if (isa<VarTemplateDecl>(Specialized))
7106 EntityKind = IsPartialSpecialization ? 3 : 2;
7107 else if (isa<FunctionTemplateDecl>(Specialized))
7108 EntityKind = 4;
7109 else if (isa<CXXMethodDecl>(Specialized))
7110 EntityKind = 5;
7111 else if (isa<VarDecl>(Specialized))
7112 EntityKind = 6;
7113 else if (isa<RecordDecl>(Specialized))
7114 EntityKind = 7;
7115 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7116 EntityKind = 8;
7117 else {
7118 S.Diag(Loc, diag::err_template_spec_unknown_kind)
7119 << S.getLangOpts().CPlusPlus11;
7120 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7121 return true;
7122 }
7123
7124 // C++ [temp.expl.spec]p2:
7125 // An explicit specialization shall be declared in the namespace
7126 // of which the template is a member, or, for member templates, in
7127 // the namespace of which the enclosing class or enclosing class
7128 // template is a member. An explicit specialization of a member
7129 // function, member class or static data member of a class
7130 // template shall be declared in the namespace of which the class
7131 // template is a member. Such a declaration may also be a
7132 // definition. If the declaration is not a definition, the
7133 // specialization may be defined later in the name- space in which
7134 // the explicit specialization was declared, or in a namespace
7135 // that encloses the one in which the explicit specialization was
7136 // declared.
7137 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7138 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7139 << Specialized;
7140 return true;
7141 }
7142
7143 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
7144 if (S.getLangOpts().MicrosoftExt) {
7145 // Do not warn for class scope explicit specialization during
7146 // instantiation, warning was already emitted during pattern
7147 // semantic analysis.
7148 if (!S.inTemplateInstantiation())
7149 S.Diag(Loc, diag::ext_function_specialization_in_class)
7150 << Specialized;
7151 } else {
7152 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7153 << Specialized;
7154 return true;
7155 }
7156 }
7157
7158 if (S.CurContext->isRecord() &&
7159 !S.CurContext->Equals(Specialized->getDeclContext())) {
7160 // Make sure that we're specializing in the right record context.
7161 // Otherwise, things can go horribly wrong.
7162 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7163 << Specialized;
7164 return true;
7165 }
7166
7167 // C++ [temp.class.spec]p6:
7168 // A class template partial specialization may be declared or redeclared
7169 // in any namespace scope in which its definition may be defined (14.5.1
7170 // and 14.5.2).
7171 DeclContext *SpecializedContext
7172 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
7173 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
7174
7175 // Make sure that this redeclaration (or definition) occurs in an enclosing
7176 // namespace.
7177 // Note that HandleDeclarator() performs this check for explicit
7178 // specializations of function templates, static data members, and member
7179 // functions, so we skip the check here for those kinds of entities.
7180 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
7181 // Should we refactor that check, so that it occurs later?
7182 if (!DC->Encloses(SpecializedContext) &&
7183 !(isa<FunctionTemplateDecl>(Specialized) ||
7184 isa<FunctionDecl>(Specialized) ||
7185 isa<VarTemplateDecl>(Specialized) ||
7186 isa<VarDecl>(Specialized))) {
7187 if (isa<TranslationUnitDecl>(SpecializedContext))
7188 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7189 << EntityKind << Specialized;
7190 else if (isa<NamespaceDecl>(SpecializedContext)) {
7191 int Diag = diag::err_template_spec_redecl_out_of_scope;
7192 if (S.getLangOpts().MicrosoftExt)
7193 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7194 S.Diag(Loc, Diag) << EntityKind << Specialized
7195 << cast<NamedDecl>(SpecializedContext);
7196 } else
7197 llvm_unreachable("unexpected namespace context for specialization")::llvm::llvm_unreachable_internal("unexpected namespace context for specialization"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7197)
;
7198
7199 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7200 } else if ((!PrevDecl ||
7201 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
7202 getTemplateSpecializationKind(PrevDecl) ==
7203 TSK_ImplicitInstantiation)) {
7204 // C++ [temp.exp.spec]p2:
7205 // An explicit specialization shall be declared in the namespace of which
7206 // the template is a member, or, for member templates, in the namespace
7207 // of which the enclosing class or enclosing class template is a member.
7208 // An explicit specialization of a member function, member class or
7209 // static data member of a class template shall be declared in the
7210 // namespace of which the class template is a member.
7211 //
7212 // C++11 [temp.expl.spec]p2:
7213 // An explicit specialization shall be declared in a namespace enclosing
7214 // the specialized template.
7215 // C++11 [temp.explicit]p3:
7216 // An explicit instantiation shall appear in an enclosing namespace of its
7217 // template.
7218 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
7219 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
7220 if (isa<TranslationUnitDecl>(SpecializedContext)) {
7221 assert(!IsCPlusPlus11Extension &&(static_cast <bool> (!IsCPlusPlus11Extension &&
"DC encloses TU but isn't in enclosing namespace set") ? void
(0) : __assert_fail ("!IsCPlusPlus11Extension && \"DC encloses TU but isn't in enclosing namespace set\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7222, __extension__ __PRETTY_FUNCTION__))
7222 "DC encloses TU but isn't in enclosing namespace set")(static_cast <bool> (!IsCPlusPlus11Extension &&
"DC encloses TU but isn't in enclosing namespace set") ? void
(0) : __assert_fail ("!IsCPlusPlus11Extension && \"DC encloses TU but isn't in enclosing namespace set\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7222, __extension__ __PRETTY_FUNCTION__))
;
7223 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
7224 << EntityKind << Specialized;
7225 } else if (isa<NamespaceDecl>(SpecializedContext)) {
7226 int Diag;
7227 if (!IsCPlusPlus11Extension)
7228 Diag = diag::err_template_spec_decl_out_of_scope;
7229 else if (!S.getLangOpts().CPlusPlus11)
7230 Diag = diag::ext_template_spec_decl_out_of_scope;
7231 else
7232 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
7233 S.Diag(Loc, Diag)
7234 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
7235 }
7236
7237 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7238 }
7239 }
7240
7241 return false;
7242}
7243
7244static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7245 if (!E->isTypeDependent())
7246 return SourceLocation();
7247 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7248 Checker.TraverseStmt(E);
7249 if (Checker.MatchLoc.isInvalid())
7250 return E->getSourceRange();
7251 return Checker.MatchLoc;
7252}
7253
7254static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7255 if (!TL.getType()->isDependentType())
7256 return SourceLocation();
7257 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7258 Checker.TraverseTypeLoc(TL);
7259 if (Checker.MatchLoc.isInvalid())
7260 return TL.getSourceRange();
7261 return Checker.MatchLoc;
7262}
7263
7264/// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7265/// that checks non-type template partial specialization arguments.
7266static bool CheckNonTypeTemplatePartialSpecializationArgs(
7267 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7268 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7269 for (unsigned I = 0; I != NumArgs; ++I) {
7270 if (Args[I].getKind() == TemplateArgument::Pack) {
7271 if (CheckNonTypeTemplatePartialSpecializationArgs(
7272 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7273 Args[I].pack_size(), IsDefaultArgument))
7274 return true;
7275
7276 continue;
7277 }
7278
7279 if (Args[I].getKind() != TemplateArgument::Expression)
7280 continue;
7281
7282 Expr *ArgExpr = Args[I].getAsExpr();
7283
7284 // We can have a pack expansion of any of the bullets below.
7285 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7286 ArgExpr = Expansion->getPattern();
7287
7288 // Strip off any implicit casts we added as part of type checking.
7289 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7290 ArgExpr = ICE->getSubExpr();
7291
7292 // C++ [temp.class.spec]p8:
7293 // A non-type argument is non-specialized if it is the name of a
7294 // non-type parameter. All other non-type arguments are
7295 // specialized.
7296 //
7297 // Below, we check the two conditions that only apply to
7298 // specialized non-type arguments, so skip any non-specialized
7299 // arguments.
7300 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7301 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7302 continue;
7303
7304 // C++ [temp.class.spec]p9:
7305 // Within the argument list of a class template partial
7306 // specialization, the following restrictions apply:
7307 // -- A partially specialized non-type argument expression
7308 // shall not involve a template parameter of the partial
7309 // specialization except when the argument expression is a
7310 // simple identifier.
7311 // -- The type of a template parameter corresponding to a
7312 // specialized non-type argument shall not be dependent on a
7313 // parameter of the specialization.
7314 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7315 // We implement a compromise between the original rules and DR1315:
7316 // -- A specialized non-type template argument shall not be
7317 // type-dependent and the corresponding template parameter
7318 // shall have a non-dependent type.
7319 SourceRange ParamUseRange =
7320 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7321 if (ParamUseRange.isValid()) {
7322 if (IsDefaultArgument) {
7323 S.Diag(TemplateNameLoc,
7324 diag::err_dependent_non_type_arg_in_partial_spec);
7325 S.Diag(ParamUseRange.getBegin(),
7326 diag::note_dependent_non_type_default_arg_in_partial_spec)
7327 << ParamUseRange;
7328 } else {
7329 S.Diag(ParamUseRange.getBegin(),
7330 diag::err_dependent_non_type_arg_in_partial_spec)
7331 << ParamUseRange;
7332 }
7333 return true;
7334 }
7335
7336 ParamUseRange = findTemplateParameter(
7337 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7338 if (ParamUseRange.isValid()) {
7339 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7340 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7341 << Param->getType();
7342 S.Diag(Param->getLocation(), diag::note_template_param_here)
7343 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7344 << ParamUseRange;
7345 return true;
7346 }
7347 }
7348
7349 return false;
7350}
7351
7352/// \brief Check the non-type template arguments of a class template
7353/// partial specialization according to C++ [temp.class.spec]p9.
7354///
7355/// \param TemplateNameLoc the location of the template name.
7356/// \param PrimaryTemplate the template parameters of the primary class
7357/// template.
7358/// \param NumExplicit the number of explicitly-specified template arguments.
7359/// \param TemplateArgs the template arguments of the class template
7360/// partial specialization.
7361///
7362/// \returns \c true if there was an error, \c false otherwise.
7363bool Sema::CheckTemplatePartialSpecializationArgs(
7364 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7365 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7366 // We have to be conservative when checking a template in a dependent
7367 // context.
7368 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7369 return false;
7370
7371 TemplateParameterList *TemplateParams =
7372 PrimaryTemplate->getTemplateParameters();
7373 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7374 NonTypeTemplateParmDecl *Param
7375 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7376 if (!Param)
7377 continue;
7378
7379 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7380 Param, &TemplateArgs[I],
7381 1, I >= NumExplicit))
7382 return true;
7383 }
7384
7385 return false;
7386}
7387
7388DeclResult
7389Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7390 TagUseKind TUK,
7391 SourceLocation KWLoc,
7392 SourceLocation ModulePrivateLoc,
7393 TemplateIdAnnotation &TemplateId,
7394 AttributeList *Attr,
7395 MultiTemplateParamsArg
7396 TemplateParameterLists,
7397 SkipBodyInfo *SkipBody) {
7398 assert(TUK != TUK_Reference && "References are not specializations")(static_cast <bool> (TUK != TUK_Reference && "References are not specializations"
) ? void (0) : __assert_fail ("TUK != TUK_Reference && \"References are not specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7398, __extension__ __PRETTY_FUNCTION__))
;
7399
7400 CXXScopeSpec &SS = TemplateId.SS;
7401
7402 // NOTE: KWLoc is the location of the tag keyword. This will instead
7403 // store the location of the outermost template keyword in the declaration.
7404 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7405 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7406 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7407 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7408 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7409
7410 // Find the class template we're specializing
7411 TemplateName Name = TemplateId.Template.get();
7412 ClassTemplateDecl *ClassTemplate
7413 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7414
7415 if (!ClassTemplate) {
7416 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7417 << (Name.getAsTemplateDecl() &&
7418 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7419 return true;
7420 }
7421
7422 bool isMemberSpecialization = false;
7423 bool isPartialSpecialization = false;
7424
7425 // Check the validity of the template headers that introduce this
7426 // template.
7427 // FIXME: We probably shouldn't complain about these headers for
7428 // friend declarations.
7429 bool Invalid = false;
7430 TemplateParameterList *TemplateParams =
7431 MatchTemplateParametersToScopeSpecifier(
7432 KWLoc, TemplateNameLoc, SS, &TemplateId,
7433 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7434 Invalid);
7435 if (Invalid)
7436 return true;
7437
7438 if (TemplateParams && TemplateParams->size() > 0) {
7439 isPartialSpecialization = true;
7440
7441 if (TUK == TUK_Friend) {
7442 Diag(KWLoc, diag::err_partial_specialization_friend)
7443 << SourceRange(LAngleLoc, RAngleLoc);
7444 return true;
7445 }
7446
7447 // C++ [temp.class.spec]p10:
7448 // The template parameter list of a specialization shall not
7449 // contain default template argument values.
7450 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7451 Decl *Param = TemplateParams->getParam(I);
7452 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7453 if (TTP->hasDefaultArgument()) {
7454 Diag(TTP->getDefaultArgumentLoc(),
7455 diag::err_default_arg_in_partial_spec);
7456 TTP->removeDefaultArgument();
7457 }
7458 } else if (NonTypeTemplateParmDecl *NTTP
7459 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7460 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7461 Diag(NTTP->getDefaultArgumentLoc(),
7462 diag::err_default_arg_in_partial_spec)
7463 << DefArg->getSourceRange();
7464 NTTP->removeDefaultArgument();
7465 }
7466 } else {
7467 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7468 if (TTP->hasDefaultArgument()) {
7469 Diag(TTP->getDefaultArgument().getLocation(),
7470 diag::err_default_arg_in_partial_spec)
7471 << TTP->getDefaultArgument().getSourceRange();
7472 TTP->removeDefaultArgument();
7473 }
7474 }
7475 }
7476 } else if (TemplateParams) {
7477 if (TUK == TUK_Friend)
7478 Diag(KWLoc, diag::err_template_spec_friend)
7479 << FixItHint::CreateRemoval(
7480 SourceRange(TemplateParams->getTemplateLoc(),
7481 TemplateParams->getRAngleLoc()))
7482 << SourceRange(LAngleLoc, RAngleLoc);
7483 } else {
7484 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl")(static_cast <bool> (TUK == TUK_Friend && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("TUK == TUK_Friend && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7484, __extension__ __PRETTY_FUNCTION__))
;
7485 }
7486
7487 // Check that the specialization uses the same tag kind as the
7488 // original template.
7489 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7490 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!")(static_cast <bool> (Kind != TTK_Enum && "Invalid enum tag in class template spec!"
) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template spec!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7490, __extension__ __PRETTY_FUNCTION__))
;
7491 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7492 Kind, TUK == TUK_Definition, KWLoc,
7493 ClassTemplate->getIdentifier())) {
7494 Diag(KWLoc, diag::err_use_with_wrong_tag)
7495 << ClassTemplate
7496 << FixItHint::CreateReplacement(KWLoc,
7497 ClassTemplate->getTemplatedDecl()->getKindName());
7498 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7499 diag::note_previous_use);
7500 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7501 }
7502
7503 // Translate the parser's template argument list in our AST format.
7504 TemplateArgumentListInfo TemplateArgs =
7505 makeTemplateArgumentListInfo(*this, TemplateId);
7506
7507 // Check for unexpanded parameter packs in any of the template arguments.
7508 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7509 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7510 UPPC_PartialSpecialization))
7511 return true;
7512
7513 // Check that the template argument list is well-formed for this
7514 // template.
7515 SmallVector<TemplateArgument, 4> Converted;
7516 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7517 TemplateArgs, false, Converted))
7518 return true;
7519
7520 // Find the class template (partial) specialization declaration that
7521 // corresponds to these arguments.
7522 if (isPartialSpecialization) {
7523 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7524 TemplateArgs.size(), Converted))
7525 return true;
7526
7527 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7528 // also do it during instantiation.
7529 bool InstantiationDependent;
7530 if (!Name.isDependent() &&
7531 !TemplateSpecializationType::anyDependentTemplateArguments(
7532 TemplateArgs.arguments(), InstantiationDependent)) {
7533 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7534 << ClassTemplate->getDeclName();
7535 isPartialSpecialization = false;
7536 }
7537 }
7538
7539 void *InsertPos = nullptr;
7540 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7541
7542 if (isPartialSpecialization)
7543 // FIXME: Template parameter list matters, too
7544 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7545 else
7546 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7547
7548 ClassTemplateSpecializationDecl *Specialization = nullptr;
7549
7550 // Check whether we can declare a class template specialization in
7551 // the current scope.
7552 if (TUK != TUK_Friend &&
7553 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7554 TemplateNameLoc,
7555 isPartialSpecialization))
7556 return true;
7557
7558 // The canonical type
7559 QualType CanonType;
7560 if (isPartialSpecialization) {
7561 // Build the canonical type that describes the converted template
7562 // arguments of the class template partial specialization.
7563 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7564 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7565 Converted);
7566
7567 if (Context.hasSameType(CanonType,
7568 ClassTemplate->getInjectedClassNameSpecialization())) {
7569 // C++ [temp.class.spec]p9b3:
7570 //
7571 // -- The argument list of the specialization shall not be identical
7572 // to the implicit argument list of the primary template.
7573 //
7574 // This rule has since been removed, because it's redundant given DR1495,
7575 // but we keep it because it produces better diagnostics and recovery.
7576 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7577 << /*class template*/0 << (TUK == TUK_Definition)
7578 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7579 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7580 ClassTemplate->getIdentifier(),
7581 TemplateNameLoc,
7582 Attr,
7583 TemplateParams,
7584 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7585 /*FriendLoc*/SourceLocation(),
7586 TemplateParameterLists.size() - 1,
7587 TemplateParameterLists.data());
7588 }
7589
7590 // Create a new class template partial specialization declaration node.
7591 ClassTemplatePartialSpecializationDecl *PrevPartial
7592 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7593 ClassTemplatePartialSpecializationDecl *Partial
7594 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7595 ClassTemplate->getDeclContext(),
7596 KWLoc, TemplateNameLoc,
7597 TemplateParams,
7598 ClassTemplate,
7599 Converted,
7600 TemplateArgs,
7601 CanonType,
7602 PrevPartial);
7603 SetNestedNameSpecifier(Partial, SS);
7604 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7605 Partial->setTemplateParameterListsInfo(
7606 Context, TemplateParameterLists.drop_back(1));
7607 }
7608
7609 if (!PrevPartial)
7610 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7611 Specialization = Partial;
7612
7613 // If we are providing an explicit specialization of a member class
7614 // template specialization, make a note of that.
7615 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7616 PrevPartial->setMemberSpecialization();
7617
7618 CheckTemplatePartialSpecialization(Partial);
7619 } else {
7620 // Create a new class template specialization declaration node for
7621 // this explicit specialization or friend declaration.
7622 Specialization
7623 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7624 ClassTemplate->getDeclContext(),
7625 KWLoc, TemplateNameLoc,
7626 ClassTemplate,
7627 Converted,
7628 PrevDecl);
7629 SetNestedNameSpecifier(Specialization, SS);
7630 if (TemplateParameterLists.size() > 0) {
7631 Specialization->setTemplateParameterListsInfo(Context,
7632 TemplateParameterLists);
7633 }
7634
7635 if (!PrevDecl)
7636 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7637
7638 if (CurContext->isDependentContext()) {
7639 // -fms-extensions permits specialization of nested classes without
7640 // fully specializing the outer class(es).
7641 assert(getLangOpts().MicrosoftExt &&(static_cast <bool> (getLangOpts().MicrosoftExt &&
"Only possible with -fms-extensions!") ? void (0) : __assert_fail
("getLangOpts().MicrosoftExt && \"Only possible with -fms-extensions!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7642, __extension__ __PRETTY_FUNCTION__))
7642 "Only possible with -fms-extensions!")(static_cast <bool> (getLangOpts().MicrosoftExt &&
"Only possible with -fms-extensions!") ? void (0) : __assert_fail
("getLangOpts().MicrosoftExt && \"Only possible with -fms-extensions!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7642, __extension__ __PRETTY_FUNCTION__))
;
7643 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7644 CanonType = Context.getTemplateSpecializationType(
7645 CanonTemplate, Converted);
7646 } else {
7647 CanonType = Context.getTypeDeclType(Specialization);
7648 }
7649 }
7650
7651 // C++ [temp.expl.spec]p6:
7652 // If a template, a member template or the member of a class template is
7653 // explicitly specialized then that specialization shall be declared
7654 // before the first use of that specialization that would cause an implicit
7655 // instantiation to take place, in every translation unit in which such a
7656 // use occurs; no diagnostic is required.
7657 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7658 bool Okay = false;
7659 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7660 // Is there any previous explicit specialization declaration?
7661 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7662 Okay = true;
7663 break;
7664 }
7665 }
7666
7667 if (!Okay) {
7668 SourceRange Range(TemplateNameLoc, RAngleLoc);
7669 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7670 << Context.getTypeDeclType(Specialization) << Range;
7671
7672 Diag(PrevDecl->getPointOfInstantiation(),
7673 diag::note_instantiation_required_here)
7674 << (PrevDecl->getTemplateSpecializationKind()
7675 != TSK_ImplicitInstantiation);
7676 return true;
7677 }
7678 }
7679
7680 // If this is not a friend, note that this is an explicit specialization.
7681 if (TUK != TUK_Friend)
7682 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7683
7684 // Check that this isn't a redefinition of this specialization.
7685 if (TUK == TUK_Definition) {
7686 RecordDecl *Def = Specialization->getDefinition();
7687 NamedDecl *Hidden = nullptr;
7688 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7689 SkipBody->ShouldSkip = true;
7690 makeMergedDefinitionVisible(Hidden);
7691 // From here on out, treat this as just a redeclaration.
7692 TUK = TUK_Declaration;
7693 } else if (Def) {
7694 SourceRange Range(TemplateNameLoc, RAngleLoc);
7695 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7696 Diag(Def->getLocation(), diag::note_previous_definition);
7697 Specialization->setInvalidDecl();
7698 return true;
7699 }
7700 }
7701
7702 if (Attr)
7703 ProcessDeclAttributeList(S, Specialization, Attr);
7704
7705 // Add alignment attributes if necessary; these attributes are checked when
7706 // the ASTContext lays out the structure.
7707 if (TUK == TUK_Definition) {
7708 AddAlignmentAttributesForRecord(Specialization);
7709 AddMsStructLayoutForRecord(Specialization);
7710 }
7711
7712 if (ModulePrivateLoc.isValid())
7713 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7714 << (isPartialSpecialization? 1 : 0)
7715 << FixItHint::CreateRemoval(ModulePrivateLoc);
7716
7717 // Build the fully-sugared type for this class template
7718 // specialization as the user wrote in the specialization
7719 // itself. This means that we'll pretty-print the type retrieved
7720 // from the specialization's declaration the way that the user
7721 // actually wrote the specialization, rather than formatting the
7722 // name based on the "canonical" representation used to store the
7723 // template arguments in the specialization.
7724 TypeSourceInfo *WrittenTy
7725 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7726 TemplateArgs, CanonType);
7727 if (TUK != TUK_Friend) {
7728 Specialization->setTypeAsWritten(WrittenTy);
7729 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7730 }
7731
7732 // C++ [temp.expl.spec]p9:
7733 // A template explicit specialization is in the scope of the
7734 // namespace in which the template was defined.
7735 //
7736 // We actually implement this paragraph where we set the semantic
7737 // context (in the creation of the ClassTemplateSpecializationDecl),
7738 // but we also maintain the lexical context where the actual
7739 // definition occurs.
7740 Specialization->setLexicalDeclContext(CurContext);
7741
7742 // We may be starting the definition of this specialization.
7743 if (TUK == TUK_Definition)
7744 Specialization->startDefinition();
7745
7746 if (TUK == TUK_Friend) {
7747 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7748 TemplateNameLoc,
7749 WrittenTy,
7750 /*FIXME:*/KWLoc);
7751 Friend->setAccess(AS_public);
7752 CurContext->addDecl(Friend);
7753 } else {
7754 // Add the specialization into its lexical context, so that it can
7755 // be seen when iterating through the list of declarations in that
7756 // context. However, specializations are not found by name lookup.
7757 CurContext->addDecl(Specialization);
7758 }
7759 return Specialization;
7760}
7761
7762Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7763 MultiTemplateParamsArg TemplateParameterLists,
7764 Declarator &D) {
7765 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7766 ActOnDocumentableDecl(NewDecl);
7767 return NewDecl;
7768}
7769
7770/// \brief Strips various properties off an implicit instantiation
7771/// that has just been explicitly specialized.
7772static void StripImplicitInstantiation(NamedDecl *D) {
7773 D->dropAttr<DLLImportAttr>();
7774 D->dropAttr<DLLExportAttr>();
7775
7776 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7777 FD->setInlineSpecified(false);
7778}
7779
7780/// \brief Compute the diagnostic location for an explicit instantiation
7781// declaration or definition.
7782static SourceLocation DiagLocForExplicitInstantiation(
7783 NamedDecl* D, SourceLocation PointOfInstantiation) {
7784 // Explicit instantiations following a specialization have no effect and
7785 // hence no PointOfInstantiation. In that case, walk decl backwards
7786 // until a valid name loc is found.
7787 SourceLocation PrevDiagLoc = PointOfInstantiation;
7788 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7789 Prev = Prev->getPreviousDecl()) {
7790 PrevDiagLoc = Prev->getLocation();
7791 }
7792 assert(PrevDiagLoc.isValid() &&(static_cast <bool> (PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?"
) ? void (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7793, __extension__ __PRETTY_FUNCTION__))
7793 "Explicit instantiation without point of instantiation?")(static_cast <bool> (PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?"
) ? void (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7793, __extension__ __PRETTY_FUNCTION__))
;
7794 return PrevDiagLoc;
7795}
7796
7797/// \brief Diagnose cases where we have an explicit template specialization
7798/// before/after an explicit template instantiation, producing diagnostics
7799/// for those cases where they are required and determining whether the
7800/// new specialization/instantiation will have any effect.
7801///
7802/// \param NewLoc the location of the new explicit specialization or
7803/// instantiation.
7804///
7805/// \param NewTSK the kind of the new explicit specialization or instantiation.
7806///
7807/// \param PrevDecl the previous declaration of the entity.
7808///
7809/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7810///
7811/// \param PrevPointOfInstantiation if valid, indicates where the previus
7812/// declaration was instantiated (either implicitly or explicitly).
7813///
7814/// \param HasNoEffect will be set to true to indicate that the new
7815/// specialization or instantiation has no effect and should be ignored.
7816///
7817/// \returns true if there was an error that should prevent the introduction of
7818/// the new declaration into the AST, false otherwise.
7819bool
7820Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7821 TemplateSpecializationKind NewTSK,
7822 NamedDecl *PrevDecl,
7823 TemplateSpecializationKind PrevTSK,
7824 SourceLocation PrevPointOfInstantiation,
7825 bool &HasNoEffect) {
7826 HasNoEffect = false;
7827
7828 switch (NewTSK) {
7829 case TSK_Undeclared:
7830 case TSK_ImplicitInstantiation:
7831 assert((static_cast <bool> ((PrevTSK == TSK_Undeclared || PrevTSK
== TSK_ImplicitInstantiation) && "previous declaration must be implicit!"
) ? void (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7833, __extension__ __PRETTY_FUNCTION__))
7832 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&(static_cast <bool> ((PrevTSK == TSK_Undeclared || PrevTSK
== TSK_ImplicitInstantiation) && "previous declaration must be implicit!"
) ? void (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7833, __extension__ __PRETTY_FUNCTION__))
7833 "previous declaration must be implicit!")(static_cast <bool> ((PrevTSK == TSK_Undeclared || PrevTSK
== TSK_ImplicitInstantiation) && "previous declaration must be implicit!"
) ? void (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7833, __extension__ __PRETTY_FUNCTION__))
;
7834 return false;
7835
7836 case TSK_ExplicitSpecialization:
7837 switch (PrevTSK) {
7838 case TSK_Undeclared:
7839 case TSK_ExplicitSpecialization:
7840 // Okay, we're just specializing something that is either already
7841 // explicitly specialized or has merely been mentioned without any
7842 // instantiation.
7843 return false;
7844
7845 case TSK_ImplicitInstantiation:
7846 if (PrevPointOfInstantiation.isInvalid()) {
7847 // The declaration itself has not actually been instantiated, so it is
7848 // still okay to specialize it.
7849 StripImplicitInstantiation(PrevDecl);
7850 return false;
7851 }
7852 // Fall through
7853 LLVM_FALLTHROUGH[[clang::fallthrough]];
7854
7855 case TSK_ExplicitInstantiationDeclaration:
7856 case TSK_ExplicitInstantiationDefinition:
7857 assert((PrevTSK == TSK_ImplicitInstantiation ||(static_cast <bool> ((PrevTSK == TSK_ImplicitInstantiation
|| PrevPointOfInstantiation.isValid()) && "Explicit instantiation without point of instantiation?"
) ? void (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7859, __extension__ __PRETTY_FUNCTION__))
7858 PrevPointOfInstantiation.isValid()) &&(static_cast <bool> ((PrevTSK == TSK_ImplicitInstantiation
|| PrevPointOfInstantiation.isValid()) && "Explicit instantiation without point of instantiation?"
) ? void (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7859, __extension__ __PRETTY_FUNCTION__))
7859 "Explicit instantiation without point of instantiation?")(static_cast <bool> ((PrevTSK == TSK_ImplicitInstantiation
|| PrevPointOfInstantiation.isValid()) && "Explicit instantiation without point of instantiation?"
) ? void (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7859, __extension__ __PRETTY_FUNCTION__))
;
7860
7861 // C++ [temp.expl.spec]p6:
7862 // If a template, a member template or the member of a class template
7863 // is explicitly specialized then that specialization shall be declared
7864 // before the first use of that specialization that would cause an
7865 // implicit instantiation to take place, in every translation unit in
7866 // which such a use occurs; no diagnostic is required.
7867 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7868 // Is there any previous explicit specialization declaration?
7869 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7870 return false;
7871 }
7872
7873 Diag(NewLoc, diag::err_specialization_after_instantiation)
7874 << PrevDecl;
7875 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7876 << (PrevTSK != TSK_ImplicitInstantiation);
7877
7878 return true;
7879 }
7880 llvm_unreachable("The switch over PrevTSK must be exhaustive.")::llvm::llvm_unreachable_internal("The switch over PrevTSK must be exhaustive."
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7880)
;
7881
7882 case TSK_ExplicitInstantiationDeclaration:
7883 switch (PrevTSK) {
7884 case TSK_ExplicitInstantiationDeclaration:
7885 // This explicit instantiation declaration is redundant (that's okay).
7886 HasNoEffect = true;
7887 return false;
7888
7889 case TSK_Undeclared:
7890 case TSK_ImplicitInstantiation:
7891 // We're explicitly instantiating something that may have already been
7892 // implicitly instantiated; that's fine.
7893 return false;
7894
7895 case TSK_ExplicitSpecialization:
7896 // C++0x [temp.explicit]p4:
7897 // For a given set of template parameters, if an explicit instantiation
7898 // of a template appears after a declaration of an explicit
7899 // specialization for that template, the explicit instantiation has no
7900 // effect.
7901 HasNoEffect = true;
7902 return false;
7903
7904 case TSK_ExplicitInstantiationDefinition:
7905 // C++0x [temp.explicit]p10:
7906 // If an entity is the subject of both an explicit instantiation
7907 // declaration and an explicit instantiation definition in the same
7908 // translation unit, the definition shall follow the declaration.
7909 Diag(NewLoc,
7910 diag::err_explicit_instantiation_declaration_after_definition);
7911
7912 // Explicit instantiations following a specialization have no effect and
7913 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7914 // until a valid name loc is found.
7915 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7916 diag::note_explicit_instantiation_definition_here);
7917 HasNoEffect = true;
7918 return false;
7919 }
7920
7921 case TSK_ExplicitInstantiationDefinition:
7922 switch (PrevTSK) {
7923 case TSK_Undeclared:
7924 case TSK_ImplicitInstantiation:
7925 // We're explicitly instantiating something that may have already been
7926 // implicitly instantiated; that's fine.
7927 return false;
7928
7929 case TSK_ExplicitSpecialization:
7930 // C++ DR 259, C++0x [temp.explicit]p4:
7931 // For a given set of template parameters, if an explicit
7932 // instantiation of a template appears after a declaration of
7933 // an explicit specialization for that template, the explicit
7934 // instantiation has no effect.
7935 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7936 << PrevDecl;
7937 Diag(PrevDecl->getLocation(),
7938 diag::note_previous_template_specialization);
7939 HasNoEffect = true;
7940 return false;
7941
7942 case TSK_ExplicitInstantiationDeclaration:
7943 // We're explicity instantiating a definition for something for which we
7944 // were previously asked to suppress instantiations. That's fine.
7945
7946 // C++0x [temp.explicit]p4:
7947 // For a given set of template parameters, if an explicit instantiation
7948 // of a template appears after a declaration of an explicit
7949 // specialization for that template, the explicit instantiation has no
7950 // effect.
7951 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7952 // Is there any previous explicit specialization declaration?
7953 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7954 HasNoEffect = true;
7955 break;
7956 }
7957 }
7958
7959 return false;
7960
7961 case TSK_ExplicitInstantiationDefinition:
7962 // C++0x [temp.spec]p5:
7963 // For a given template and a given set of template-arguments,
7964 // - an explicit instantiation definition shall appear at most once
7965 // in a program,
7966
7967 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7968 Diag(NewLoc, (getLangOpts().MSVCCompat)
7969 ? diag::ext_explicit_instantiation_duplicate
7970 : diag::err_explicit_instantiation_duplicate)
7971 << PrevDecl;
7972 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7973 diag::note_previous_explicit_instantiation);
7974 HasNoEffect = true;
7975 return false;
7976 }
7977 }
7978
7979 llvm_unreachable("Missing specialization/instantiation case?")::llvm::llvm_unreachable_internal("Missing specialization/instantiation case?"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7979)
;
7980}
7981
7982/// \brief Perform semantic analysis for the given dependent function
7983/// template specialization.
7984///
7985/// The only possible way to get a dependent function template specialization
7986/// is with a friend declaration, like so:
7987///
7988/// \code
7989/// template \<class T> void foo(T);
7990/// template \<class T> class A {
7991/// friend void foo<>(T);
7992/// };
7993/// \endcode
7994///
7995/// There really isn't any useful analysis we can do here, so we
7996/// just store the information.
7997bool
7998Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7999 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8000 LookupResult &Previous) {
8001 // Remove anything from Previous that isn't a function template in
8002 // the correct context.
8003 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8004 LookupResult::Filter F = Previous.makeFilter();
8005 while (F.hasNext()) {
8006 NamedDecl *D = F.next()->getUnderlyingDecl();
8007 if (!isa<FunctionTemplateDecl>(D) ||
8008 !FDLookupContext->InEnclosingNamespaceSetOf(
8009 D->getDeclContext()->getRedeclContext()))
8010 F.erase();
8011 }
8012 F.done();
8013
8014 // Should this be diagnosed here?
8015 if (Previous.empty()) return true;
8016
8017 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8018 ExplicitTemplateArgs);
8019 return false;
8020}
8021
8022/// \brief Perform semantic analysis for the given function template
8023/// specialization.
8024///
8025/// This routine performs all of the semantic analysis required for an
8026/// explicit function template specialization. On successful completion,
8027/// the function declaration \p FD will become a function template
8028/// specialization.
8029///
8030/// \param FD the function declaration, which will be updated to become a
8031/// function template specialization.
8032///
8033/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8034/// if any. Note that this may be valid info even when 0 arguments are
8035/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8036/// as it anyway contains info on the angle brackets locations.
8037///
8038/// \param Previous the set of declarations that may be specialized by
8039/// this function specialization.
8040bool Sema::CheckFunctionTemplateSpecialization(
8041 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8042 LookupResult &Previous) {
8043 // The set of function template specializations that could match this
8044 // explicit function template specialization.
8045 UnresolvedSet<8> Candidates;
8046 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8047 /*ForTakingAddress=*/false);
8048
8049 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8050 ConvertedTemplateArgs;
8051
8052 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8053 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8054 I != E; ++I) {
8055 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8056 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8057 // Only consider templates found within the same semantic lookup scope as
8058 // FD.
8059 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8060 Ovl->getDeclContext()->getRedeclContext()))
8061 continue;
8062
8063 // When matching a constexpr member function template specialization
8064 // against the primary template, we don't yet know whether the
8065 // specialization has an implicit 'const' (because we don't know whether
8066 // it will be a static member function until we know which template it
8067 // specializes), so adjust it now assuming it specializes this template.
8068 QualType FT = FD->getType();
8069 if (FD->isConstexpr()) {
8070 CXXMethodDecl *OldMD =
8071 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8072 if (OldMD && OldMD->isConst()) {
8073 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8074 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8075 EPI.TypeQuals |= Qualifiers::Const;
8076 FT = Context.getFunctionType(FPT->getReturnType(),
8077 FPT->getParamTypes(), EPI);
8078 }
8079 }
8080
8081 TemplateArgumentListInfo Args;
8082 if (ExplicitTemplateArgs)
8083 Args = *ExplicitTemplateArgs;
8084
8085 // C++ [temp.expl.spec]p11:
8086 // A trailing template-argument can be left unspecified in the
8087 // template-id naming an explicit function template specialization
8088 // provided it can be deduced from the function argument type.
8089 // Perform template argument deduction to determine whether we may be
8090 // specializing this template.
8091 // FIXME: It is somewhat wasteful to build
8092 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8093 FunctionDecl *Specialization = nullptr;
8094 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8095 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8096 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8097 Info)) {
8098 // Template argument deduction failed; record why it failed, so
8099 // that we can provide nifty diagnostics.
8100 FailedCandidates.addCandidate().set(
8101 I.getPair(), FunTmpl->getTemplatedDecl(),
8102 MakeDeductionFailureInfo(Context, TDK, Info));
8103 (void)TDK;
8104 continue;
8105 }
8106
8107 // Target attributes are part of the cuda function signature, so
8108 // the deduced template's cuda target must match that of the
8109 // specialization. Given that C++ template deduction does not
8110 // take target attributes into account, we reject candidates
8111 // here that have a different target.
8112 if (LangOpts.CUDA &&
8113 IdentifyCUDATarget(Specialization,
8114 /* IgnoreImplicitHDAttributes = */ true) !=
8115 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
8116 FailedCandidates.addCandidate().set(
8117 I.getPair(), FunTmpl->getTemplatedDecl(),
8118 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8119 continue;
8120 }
8121
8122 // Record this candidate.
8123 if (ExplicitTemplateArgs)
8124 ConvertedTemplateArgs[Specialization] = std::move(Args);
8125 Candidates.addDecl(Specialization, I.getAccess());
8126 }
8127 }
8128
8129 // Find the most specialized function template.
8130 UnresolvedSetIterator Result = getMostSpecialized(
8131 Candidates.begin(), Candidates.end(), FailedCandidates,
8132 FD->getLocation(),
8133 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8134 PDiag(diag::err_function_template_spec_ambiguous)
8135 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8136 PDiag(diag::note_function_template_spec_matched));
8137
8138 if (Result == Candidates.end())
8139 return true;
8140
8141 // Ignore access information; it doesn't figure into redeclaration checking.
8142 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8143
8144 FunctionTemplateSpecializationInfo *SpecInfo
8145 = Specialization->getTemplateSpecializationInfo();
8146 assert(SpecInfo && "Function template specialization info missing?")(static_cast <bool> (SpecInfo && "Function template specialization info missing?"
) ? void (0) : __assert_fail ("SpecInfo && \"Function template specialization info missing?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8146, __extension__ __PRETTY_FUNCTION__))
;
8147
8148 // Note: do not overwrite location info if previous template
8149 // specialization kind was explicit.
8150 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8151 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8152 Specialization->setLocation(FD->getLocation());
8153 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8154 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8155 // function can differ from the template declaration with respect to
8156 // the constexpr specifier.
8157 // FIXME: We need an update record for this AST mutation.
8158 // FIXME: What if there are multiple such prior declarations (for instance,
8159 // from different modules)?
8160 Specialization->setConstexpr(FD->isConstexpr());
8161 }
8162
8163 // FIXME: Check if the prior specialization has a point of instantiation.
8164 // If so, we have run afoul of .
8165
8166 // If this is a friend declaration, then we're not really declaring
8167 // an explicit specialization.
8168 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8169
8170 // Check the scope of this explicit specialization.
8171 if (!isFriend &&
8172 CheckTemplateSpecializationScope(*this,
8173 Specialization->getPrimaryTemplate(),
8174 Specialization, FD->getLocation(),
8175 false))
8176 return true;
8177
8178 // C++ [temp.expl.spec]p6:
8179 // If a template, a member template or the member of a class template is
8180 // explicitly specialized then that specialization shall be declared
8181 // before the first use of that specialization that would cause an implicit
8182 // instantiation to take place, in every translation unit in which such a
8183 // use occurs; no diagnostic is required.
8184 bool HasNoEffect = false;
8185 if (!isFriend &&
8186 CheckSpecializationInstantiationRedecl(FD->getLocation(),
8187 TSK_ExplicitSpecialization,
8188 Specialization,
8189 SpecInfo->getTemplateSpecializationKind(),
8190 SpecInfo->getPointOfInstantiation(),
8191 HasNoEffect))
8192 return true;
8193
8194 // Mark the prior declaration as an explicit specialization, so that later
8195 // clients know that this is an explicit specialization.
8196 if (!isFriend) {
8197 // Since explicit specializations do not inherit '=delete' from their
8198 // primary function template - check if the 'specialization' that was
8199 // implicitly generated (during template argument deduction for partial
8200 // ordering) from the most specialized of all the function templates that
8201 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8202 // first check that it was implicitly generated during template argument
8203 // deduction by making sure it wasn't referenced, and then reset the deleted
8204 // flag to not-deleted, so that we can inherit that information from 'FD'.
8205 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8206 !Specialization->getCanonicalDecl()->isReferenced()) {
8207 // FIXME: This assert will not hold in the presence of modules.
8208 assert((static_cast <bool> (Specialization->getCanonicalDecl
() == Specialization && "This must be the only existing declaration of this specialization"
) ? void (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8210, __extension__ __PRETTY_FUNCTION__))
8209 Specialization->getCanonicalDecl() == Specialization &&(static_cast <bool> (Specialization->getCanonicalDecl
() == Specialization && "This must be the only existing declaration of this specialization"
) ? void (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8210, __extension__ __PRETTY_FUNCTION__))
8210 "This must be the only existing declaration of this specialization")(static_cast <bool> (Specialization->getCanonicalDecl
() == Specialization && "This must be the only existing declaration of this specialization"
) ? void (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8210, __extension__ __PRETTY_FUNCTION__))
;
8211 // FIXME: We need an update record for this AST mutation.
8212 Specialization->setDeletedAsWritten(false);
8213 }
8214 // FIXME: We need an update record for this AST mutation.
8215 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8216 MarkUnusedFileScopedDecl(Specialization);
8217 }
8218
8219 // Turn the given function declaration into a function template
8220 // specialization, with the template arguments from the previous
8221 // specialization.
8222 // Take copies of (semantic and syntactic) template argument lists.
8223 const TemplateArgumentList* TemplArgs = new (Context)
8224 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8225 FD->setFunctionTemplateSpecialization(
8226 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8227 SpecInfo->getTemplateSpecializationKind(),
8228 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8229
8230 // A function template specialization inherits the target attributes
8231 // of its template. (We require the attributes explicitly in the
8232 // code to match, but a template may have implicit attributes by
8233 // virtue e.g. of being constexpr, and it passes these implicit
8234 // attributes on to its specializations.)
8235 if (LangOpts.CUDA)
8236 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8237
8238 // The "previous declaration" for this function template specialization is
8239 // the prior function template specialization.
8240 Previous.clear();
8241 Previous.addDecl(Specialization);
8242 return false;
8243}
8244
8245/// \brief Perform semantic analysis for the given non-template member
8246/// specialization.
8247///
8248/// This routine performs all of the semantic analysis required for an
8249/// explicit member function specialization. On successful completion,
8250/// the function declaration \p FD will become a member function
8251/// specialization.
8252///
8253/// \param Member the member declaration, which will be updated to become a
8254/// specialization.
8255///
8256/// \param Previous the set of declarations, one of which may be specialized
8257/// by this function specialization; the set will be modified to contain the
8258/// redeclared member.
8259bool
8260Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8261 assert(!isa<TemplateDecl>(Member) && "Only for non-template members")(static_cast <bool> (!isa<TemplateDecl>(Member) &&
"Only for non-template members") ? void (0) : __assert_fail (
"!isa<TemplateDecl>(Member) && \"Only for non-template members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8261, __extension__ __PRETTY_FUNCTION__))
;
8262
8263 // Try to find the member we are instantiating.
8264 NamedDecl *FoundInstantiation = nullptr;
8265 NamedDecl *Instantiation = nullptr;
8266 NamedDecl *InstantiatedFrom = nullptr;
8267 MemberSpecializationInfo *MSInfo = nullptr;
8268
8269 if (Previous.empty()) {
8270 // Nowhere to look anyway.
8271 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8272 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8273 I != E; ++I) {
8274 NamedDecl *D = (*I)->getUnderlyingDecl();
8275 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8276 QualType Adjusted = Function->getType();
8277 if (!hasExplicitCallingConv(Adjusted))
8278 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8279 if (Context.hasSameType(Adjusted, Method->getType())) {
8280 FoundInstantiation = *I;
8281 Instantiation = Method;
8282 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8283 MSInfo = Method->getMemberSpecializationInfo();
8284 break;
8285 }
8286 }
8287 }
8288 } else if (isa<VarDecl>(Member)) {
8289 VarDecl *PrevVar;
8290 if (Previous.isSingleResult() &&
8291 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8292 if (PrevVar->isStaticDataMember()) {
8293 FoundInstantiation = Previous.getRepresentativeDecl();
8294 Instantiation = PrevVar;
8295 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8296 MSInfo = PrevVar->getMemberSpecializationInfo();
8297 }
8298 } else if (isa<RecordDecl>(Member)) {
8299 CXXRecordDecl *PrevRecord;
8300 if (Previous.isSingleResult() &&
8301 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8302 FoundInstantiation = Previous.getRepresentativeDecl();
8303 Instantiation = PrevRecord;
8304 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8305 MSInfo = PrevRecord->getMemberSpecializationInfo();
8306 }
8307 } else if (isa<EnumDecl>(Member)) {
8308 EnumDecl *PrevEnum;
8309 if (Previous.isSingleResult() &&
8310 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8311 FoundInstantiation = Previous.getRepresentativeDecl();
8312 Instantiation = PrevEnum;
8313 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8314 MSInfo = PrevEnum->getMemberSpecializationInfo();
8315 }
8316 }
8317
8318 if (!Instantiation) {
8319 // There is no previous declaration that matches. Since member
8320 // specializations are always out-of-line, the caller will complain about
8321 // this mismatch later.
8322 return false;
8323 }
8324
8325 // A member specialization in a friend declaration isn't really declaring
8326 // an explicit specialization, just identifying a specific (possibly implicit)
8327 // specialization. Don't change the template specialization kind.
8328 //
8329 // FIXME: Is this really valid? Other compilers reject.
8330 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8331 // Preserve instantiation information.
8332 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8333 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8334 cast<CXXMethodDecl>(InstantiatedFrom),
8335 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8336 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8337 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8338 cast<CXXRecordDecl>(InstantiatedFrom),
8339 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8340 }
8341
8342 Previous.clear();
8343 Previous.addDecl(FoundInstantiation);
8344 return false;
8345 }
8346
8347 // Make sure that this is a specialization of a member.
8348 if (!InstantiatedFrom) {
8349 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8350 << Member;
8351 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8352 return true;
8353 }
8354
8355 // C++ [temp.expl.spec]p6:
8356 // If a template, a member template or the member of a class template is
8357 // explicitly specialized then that specialization shall be declared
8358 // before the first use of that specialization that would cause an implicit
8359 // instantiation to take place, in every translation unit in which such a
8360 // use occurs; no diagnostic is required.
8361 assert(MSInfo && "Member specialization info missing?")(static_cast <bool> (MSInfo && "Member specialization info missing?"
) ? void (0) : __assert_fail ("MSInfo && \"Member specialization info missing?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8361, __extension__ __PRETTY_FUNCTION__))
;
8362
8363 bool HasNoEffect = false;
8364 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8365 TSK_ExplicitSpecialization,
8366 Instantiation,
8367 MSInfo->getTemplateSpecializationKind(),
8368 MSInfo->getPointOfInstantiation(),
8369 HasNoEffect))
8370 return true;
8371
8372 // Check the scope of this explicit specialization.
8373 if (CheckTemplateSpecializationScope(*this,
8374 InstantiatedFrom,
8375 Instantiation, Member->getLocation(),
8376 false))
8377 return true;
8378
8379 // Note that this member specialization is an "instantiation of" the
8380 // corresponding member of the original template.
8381 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8382 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8383 if (InstantiationFunction->getTemplateSpecializationKind() ==
8384 TSK_ImplicitInstantiation) {
8385 // Explicit specializations of member functions of class templates do not
8386 // inherit '=delete' from the member function they are specializing.
8387 if (InstantiationFunction->isDeleted()) {
8388 // FIXME: This assert will not hold in the presence of modules.
8389 assert(InstantiationFunction->getCanonicalDecl() ==(static_cast <bool> (InstantiationFunction->getCanonicalDecl
() == InstantiationFunction) ? void (0) : __assert_fail ("InstantiationFunction->getCanonicalDecl() == InstantiationFunction"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8390, __extension__ __PRETTY_FUNCTION__))
8390 InstantiationFunction)(static_cast <bool> (InstantiationFunction->getCanonicalDecl
() == InstantiationFunction) ? void (0) : __assert_fail ("InstantiationFunction->getCanonicalDecl() == InstantiationFunction"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8390, __extension__ __PRETTY_FUNCTION__))
;
8391 // FIXME: We need an update record for this AST mutation.
8392 InstantiationFunction->setDeletedAsWritten(false);
8393 }
8394 }
8395
8396 MemberFunction->setInstantiationOfMemberFunction(
8397 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8398 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8399 MemberVar->setInstantiationOfStaticDataMember(
8400 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8401 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8402 MemberClass->setInstantiationOfMemberClass(
8403 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8404 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8405 MemberEnum->setInstantiationOfMemberEnum(
8406 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8407 } else {
8408 llvm_unreachable("unknown member specialization kind")::llvm::llvm_unreachable_internal("unknown member specialization kind"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8408)
;
8409 }
8410
8411 // Save the caller the trouble of having to figure out which declaration
8412 // this specialization matches.
8413 Previous.clear();
8414 Previous.addDecl(FoundInstantiation);
8415 return false;
8416}
8417
8418/// Complete the explicit specialization of a member of a class template by
8419/// updating the instantiated member to be marked as an explicit specialization.
8420///
8421/// \param OrigD The member declaration instantiated from the template.
8422/// \param Loc The location of the explicit specialization of the member.
8423template<typename DeclT>
8424static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8425 SourceLocation Loc) {
8426 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8427 return;
8428
8429 // FIXME: Inform AST mutation listeners of this AST mutation.
8430 // FIXME: If there are multiple in-class declarations of the member (from
8431 // multiple modules, or a declaration and later definition of a member type),
8432 // should we update all of them?
8433 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8434 OrigD->setLocation(Loc);
8435}
8436
8437void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8438 LookupResult &Previous) {
8439 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8440 if (Instantiation == Member)
8441 return;
8442
8443 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8444 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8445 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8446 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8447 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8448 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8449 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8450 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8451 else
8452 llvm_unreachable("unknown member specialization kind")::llvm::llvm_unreachable_internal("unknown member specialization kind"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8452)
;
8453}
8454
8455/// \brief Check the scope of an explicit instantiation.
8456///
8457/// \returns true if a serious error occurs, false otherwise.
8458static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8459 SourceLocation InstLoc,
8460 bool WasQualifiedName) {
8461 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8462 DeclContext *CurContext = S.CurContext->getRedeclContext();
8463
8464 if (CurContext->isRecord()) {
8465 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8466 << D;
8467 return true;
8468 }
8469
8470 // C++11 [temp.explicit]p3:
8471 // An explicit instantiation shall appear in an enclosing namespace of its
8472 // template. If the name declared in the explicit instantiation is an
8473 // unqualified name, the explicit instantiation shall appear in the
8474 // namespace where its template is declared or, if that namespace is inline
8475 // (7.3.1), any namespace from its enclosing namespace set.
8476 //
8477 // This is DR275, which we do not retroactively apply to C++98/03.
8478 if (WasQualifiedName) {
8479 if (CurContext->Encloses(OrigContext))
8480 return false;
8481 } else {
8482 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8483 return false;
8484 }
8485
8486 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8487 if (WasQualifiedName)
8488 S.Diag(InstLoc,
8489 S.getLangOpts().CPlusPlus11?
8490 diag::err_explicit_instantiation_out_of_scope :
8491 diag::warn_explicit_instantiation_out_of_scope_0x)
8492 << D << NS;
8493 else
8494 S.Diag(InstLoc,
8495 S.getLangOpts().CPlusPlus11?
8496 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8497 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8498 << D << NS;
8499 } else
8500 S.Diag(InstLoc,
8501 S.getLangOpts().CPlusPlus11?
8502 diag::err_explicit_instantiation_must_be_global :
8503 diag::warn_explicit_instantiation_must_be_global_0x)
8504 << D;
8505 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8506 return false;
8507}
8508
8509/// \brief Determine whether the given scope specifier has a template-id in it.
8510static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8511 if (!SS.isSet())
8512 return false;
8513
8514 // C++11 [temp.explicit]p3:
8515 // If the explicit instantiation is for a member function, a member class
8516 // or a static data member of a class template specialization, the name of
8517 // the class template specialization in the qualified-id for the member
8518 // name shall be a simple-template-id.
8519 //
8520 // C++98 has the same restriction, just worded differently.
8521 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8522 NNS = NNS->getPrefix())
8523 if (const Type *T = NNS->getAsType())
8524 if (isa<TemplateSpecializationType>(T))
8525 return true;
8526
8527 return false;
8528}
8529
8530/// Make a dllexport or dllimport attr on a class template specialization take
8531/// effect.
8532static void dllExportImportClassTemplateSpecialization(
8533 Sema &S, ClassTemplateSpecializationDecl *Def) {
8534 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8535 assert(A && "dllExportImportClassTemplateSpecialization called "(static_cast <bool> (A && "dllExportImportClassTemplateSpecialization called "
"on Def without dllexport or dllimport") ? void (0) : __assert_fail
("A && \"dllExportImportClassTemplateSpecialization called \" \"on Def without dllexport or dllimport\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8536, __extension__ __PRETTY_FUNCTION__))
8536 "on Def without dllexport or dllimport")(static_cast <bool> (A && "dllExportImportClassTemplateSpecialization called "
"on Def without dllexport or dllimport") ? void (0) : __assert_fail
("A && \"dllExportImportClassTemplateSpecialization called \" \"on Def without dllexport or dllimport\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8536, __extension__ __PRETTY_FUNCTION__))
;
8537
8538 // We reject explicit instantiations in class scope, so there should
8539 // never be any delayed exported classes to worry about.
8540 assert(S.DelayedDllExportClasses.empty() &&(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"delayed exports present at explicit instantiation") ? void (
0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"delayed exports present at explicit instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8541, __extension__ __PRETTY_FUNCTION__))
8541 "delayed exports present at explicit instantiation")(static_cast <bool> (S.DelayedDllExportClasses.empty() &&
"delayed exports present at explicit instantiation") ? void (
0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"delayed exports present at explicit instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8541, __extension__ __PRETTY_FUNCTION__))
;
8542 S.checkClassLevelDLLAttribute(Def);
8543
8544 // Propagate attribute to base class templates.
8545 for (auto &B : Def->bases()) {
8546 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8547 B.getType()->getAsCXXRecordDecl()))
8548 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8549 }
8550
8551 S.referenceDLLExportedClassMethods();
8552}
8553
8554// Explicit instantiation of a class template specialization
8555DeclResult
8556Sema::ActOnExplicitInstantiation(Scope *S,
8557 SourceLocation ExternLoc,
8558 SourceLocation TemplateLoc,
8559 unsigned TagSpec,
8560 SourceLocation KWLoc,
8561 const CXXScopeSpec &SS,
8562 TemplateTy TemplateD,
8563 SourceLocation TemplateNameLoc,
8564 SourceLocation LAngleLoc,
8565 ASTTemplateArgsPtr TemplateArgsIn,
8566 SourceLocation RAngleLoc,
8567 AttributeList *Attr) {
8568 // Find the class template we're specializing
8569 TemplateName Name = TemplateD.get();
8570 TemplateDecl *TD = Name.getAsTemplateDecl();
8571 // Check that the specialization uses the same tag kind as the
8572 // original template.
8573 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8574 assert(Kind != TTK_Enum &&(static_cast <bool> (Kind != TTK_Enum && "Invalid enum tag in class template explicit instantiation!"
) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template explicit instantiation!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8575, __extension__ __PRETTY_FUNCTION__))
8575 "Invalid enum tag in class template explicit instantiation!")(static_cast <bool> (Kind != TTK_Enum && "Invalid enum tag in class template explicit instantiation!"
) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template explicit instantiation!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8575, __extension__ __PRETTY_FUNCTION__))
;
8576
8577 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8578
8579 if (!ClassTemplate) {
8580 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8581 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8582 Diag(TD->getLocation(), diag::note_previous_use);
8583 return true;
8584 }
8585
8586 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8587 Kind, /*isDefinition*/false, KWLoc,
8588 ClassTemplate->getIdentifier())) {
8589 Diag(KWLoc, diag::err_use_with_wrong_tag)
8590 << ClassTemplate
8591 << FixItHint::CreateReplacement(KWLoc,
8592 ClassTemplate->getTemplatedDecl()->getKindName());
8593 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8594 diag::note_previous_use);
8595 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8596 }
8597
8598 // C++0x [temp.explicit]p2:
8599 // There are two forms of explicit instantiation: an explicit instantiation
8600 // definition and an explicit instantiation declaration. An explicit
8601 // instantiation declaration begins with the extern keyword. [...]
8602 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8603 ? TSK_ExplicitInstantiationDefinition
8604 : TSK_ExplicitInstantiationDeclaration;
8605
8606 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8607 // Check for dllexport class template instantiation declarations.
8608 for (AttributeList *A = Attr; A; A = A->getNext()) {
8609 if (A->getKind() == AttributeList::AT_DLLExport) {
8610 Diag(ExternLoc,
8611 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8612 Diag(A->getLoc(), diag::note_attribute);
8613 break;
8614 }
8615 }
8616
8617 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8618 Diag(ExternLoc,
8619 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8620 Diag(A->getLocation(), diag::note_attribute);
8621 }
8622 }
8623
8624 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8625 // instantiation declarations for most purposes.
8626 bool DLLImportExplicitInstantiationDef = false;
8627 if (TSK == TSK_ExplicitInstantiationDefinition &&
8628 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8629 // Check for dllimport class template instantiation definitions.
8630 bool DLLImport =
8631 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8632 for (AttributeList *A = Attr; A; A = A->getNext()) {
8633 if (A->getKind() == AttributeList::AT_DLLImport)
8634 DLLImport = true;
8635 if (A->getKind() == AttributeList::AT_DLLExport) {
8636 // dllexport trumps dllimport here.
8637 DLLImport = false;
8638 break;
8639 }
8640 }
8641 if (DLLImport) {
8642 TSK = TSK_ExplicitInstantiationDeclaration;
8643 DLLImportExplicitInstantiationDef = true;
8644 }
8645 }
8646
8647 // Translate the parser's template argument list in our AST format.
8648 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8649 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8650
8651 // Check that the template argument list is well-formed for this
8652 // template.
8653 SmallVector<TemplateArgument, 4> Converted;
8654 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8655 TemplateArgs, false, Converted))
8656 return true;
8657
8658 // Find the class template specialization declaration that
8659 // corresponds to these arguments.
8660 void *InsertPos = nullptr;
8661 ClassTemplateSpecializationDecl *PrevDecl
8662 = ClassTemplate->findSpecialization(Converted, InsertPos);
8663
8664 TemplateSpecializationKind PrevDecl_TSK
8665 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8666
8667 // C++0x [temp.explicit]p2:
8668 // [...] An explicit instantiation shall appear in an enclosing
8669 // namespace of its template. [...]
8670 //
8671 // This is C++ DR 275.
8672 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8673 SS.isSet()))
8674 return true;
8675
8676 ClassTemplateSpecializationDecl *Specialization = nullptr;
8677
8678 bool HasNoEffect = false;
8679 if (PrevDecl) {
8680 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8681 PrevDecl, PrevDecl_TSK,
8682 PrevDecl->getPointOfInstantiation(),
8683 HasNoEffect))
8684 return PrevDecl;
8685
8686 // Even though HasNoEffect == true means that this explicit instantiation
8687 // has no effect on semantics, we go on to put its syntax in the AST.
8688
8689 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8690 PrevDecl_TSK == TSK_Undeclared) {
8691 // Since the only prior class template specialization with these
8692 // arguments was referenced but not declared, reuse that
8693 // declaration node as our own, updating the source location
8694 // for the template name to reflect our new declaration.
8695 // (Other source locations will be updated later.)
8696 Specialization = PrevDecl;
8697 Specialization->setLocation(TemplateNameLoc);
8698 PrevDecl = nullptr;
8699 }
8700
8701 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8702 DLLImportExplicitInstantiationDef) {
8703 // The new specialization might add a dllimport attribute.
8704 HasNoEffect = false;
8705 }
8706 }
8707
8708 if (!Specialization) {
8709 // Create a new class template specialization declaration node for
8710 // this explicit specialization.
8711 Specialization
8712 = ClassTemplateSpecializationDecl::Create(Context, Kind,
8713 ClassTemplate->getDeclContext(),
8714 KWLoc, TemplateNameLoc,
8715 ClassTemplate,
8716 Converted,
8717 PrevDecl);
8718 SetNestedNameSpecifier(Specialization, SS);
8719
8720 if (!HasNoEffect && !PrevDecl) {
8721 // Insert the new specialization.
8722 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8723 }
8724 }
8725
8726 // Build the fully-sugared type for this explicit instantiation as
8727 // the user wrote in the explicit instantiation itself. This means
8728 // that we'll pretty-print the type retrieved from the
8729 // specialization's declaration the way that the user actually wrote
8730 // the explicit instantiation, rather than formatting the name based
8731 // on the "canonical" representation used to store the template
8732 // arguments in the specialization.
8733 TypeSourceInfo *WrittenTy
8734 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8735 TemplateArgs,
8736 Context.getTypeDeclType(Specialization));
8737 Specialization->setTypeAsWritten(WrittenTy);
8738
8739 // Set source locations for keywords.
8740 Specialization->setExternLoc(ExternLoc);
8741 Specialization->setTemplateKeywordLoc(TemplateLoc);
8742 Specialization->setBraceRange(SourceRange());
8743
8744 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8745 if (Attr)
8746 ProcessDeclAttributeList(S, Specialization, Attr);
8747
8748 // Add the explicit instantiation into its lexical context. However,
8749 // since explicit instantiations are never found by name lookup, we
8750 // just put it into the declaration context directly.
8751 Specialization->setLexicalDeclContext(CurContext);
8752 CurContext->addDecl(Specialization);
8753
8754 // Syntax is now OK, so return if it has no other effect on semantics.
8755 if (HasNoEffect) {
8756 // Set the template specialization kind.
8757 Specialization->setTemplateSpecializationKind(TSK);
8758 return Specialization;
8759 }
8760
8761 // C++ [temp.explicit]p3:
8762 // A definition of a class template or class member template
8763 // shall be in scope at the point of the explicit instantiation of
8764 // the class template or class member template.
8765 //
8766 // This check comes when we actually try to perform the
8767 // instantiation.
8768 ClassTemplateSpecializationDecl *Def
8769 = cast_or_null<ClassTemplateSpecializationDecl>(
8770 Specialization->getDefinition());
8771 if (!Def)
8772 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8773 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8774 MarkVTableUsed(TemplateNameLoc, Specialization, true);
8775 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8776 }
8777
8778 // Instantiate the members of this class template specialization.
8779 Def = cast_or_null<ClassTemplateSpecializationDecl>(
8780 Specialization->getDefinition());
8781 if (Def) {
8782 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
8783 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8784 // TSK_ExplicitInstantiationDefinition
8785 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8786 (TSK == TSK_ExplicitInstantiationDefinition ||
8787 DLLImportExplicitInstantiationDef)) {
8788 // FIXME: Need to notify the ASTMutationListener that we did this.
8789 Def->setTemplateSpecializationKind(TSK);
8790
8791 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8792 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8793 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8794 // In the MS ABI, an explicit instantiation definition can add a dll
8795 // attribute to a template with a previous instantiation declaration.
8796 // MinGW doesn't allow this.
8797 auto *A = cast<InheritableAttr>(
8798 getDLLAttr(Specialization)->clone(getASTContext()));
8799 A->setInherited(true);
8800 Def->addAttr(A);
8801 dllExportImportClassTemplateSpecialization(*this, Def);
8802 }
8803 }
8804
8805 // Fix a TSK_ImplicitInstantiation followed by a
8806 // TSK_ExplicitInstantiationDefinition
8807 bool NewlyDLLExported =
8808 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8809 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8810 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8811 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8812 // In the MS ABI, an explicit instantiation definition can add a dll
8813 // attribute to a template with a previous implicit instantiation.
8814 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8815 // avoid potentially strange codegen behavior. For example, if we extend
8816 // this conditional to dllimport, and we have a source file calling a
8817 // method on an implicitly instantiated template class instance and then
8818 // declaring a dllimport explicit instantiation definition for the same
8819 // template class, the codegen for the method call will not respect the
8820 // dllimport, while it will with cl. The Def will already have the DLL
8821 // attribute, since the Def and Specialization will be the same in the
8822 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8823 // attribute to the Specialization; we just need to make it take effect.
8824 assert(Def == Specialization &&(static_cast <bool> (Def == Specialization && "Def and Specialization should match for implicit instantiation"
) ? void (0) : __assert_fail ("Def == Specialization && \"Def and Specialization should match for implicit instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8825, __extension__ __PRETTY_FUNCTION__))
8825 "Def and Specialization should match for implicit instantiation")(static_cast <bool> (Def == Specialization && "Def and Specialization should match for implicit instantiation"
) ? void (0) : __assert_fail ("Def == Specialization && \"Def and Specialization should match for implicit instantiation\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8825, __extension__ __PRETTY_FUNCTION__))
;
8826 dllExportImportClassTemplateSpecialization(*this, Def);
8827 }
8828
8829 // Set the template specialization kind. Make sure it is set before
8830 // instantiating the members which will trigger ASTConsumer callbacks.
8831 Specialization->setTemplateSpecializationKind(TSK);
8832 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8833 } else {
8834
8835 // Set the template specialization kind.
8836 Specialization->setTemplateSpecializationKind(TSK);
8837 }
8838
8839 return Specialization;
8840}
8841
8842// Explicit instantiation of a member class of a class template.
8843DeclResult
8844Sema::ActOnExplicitInstantiation(Scope *S,
8845 SourceLocation ExternLoc,
8846 SourceLocation TemplateLoc,
8847 unsigned TagSpec,
8848 SourceLocation KWLoc,
8849 CXXScopeSpec &SS,
8850 IdentifierInfo *Name,
8851 SourceLocation NameLoc,
8852 AttributeList *Attr) {
8853
8854 bool Owned = false;
8855 bool IsDependent = false;
8856 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8857 KWLoc, SS, Name, NameLoc, Attr, AS_none,
8858 /*ModulePrivateLoc=*/SourceLocation(),
8859 MultiTemplateParamsArg(), Owned, IsDependent,
8860 SourceLocation(), false, TypeResult(),
8861 /*IsTypeSpecifier*/false,
8862 /*IsTemplateParamOrArg*/false);
8863 assert(!IsDependent && "explicit instantiation of dependent name not yet handled")(static_cast <bool> (!IsDependent && "explicit instantiation of dependent name not yet handled"
) ? void (0) : __assert_fail ("!IsDependent && \"explicit instantiation of dependent name not yet handled\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8863, __extension__ __PRETTY_FUNCTION__))
;
8864
8865 if (!TagD)
8866 return true;
8867
8868 TagDecl *Tag = cast<TagDecl>(TagD);
8869 assert(!Tag->isEnum() && "shouldn't see enumerations here")(static_cast <bool> (!Tag->isEnum() && "shouldn't see enumerations here"
) ? void (0) : __assert_fail ("!Tag->isEnum() && \"shouldn't see enumerations here\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8869, __extension__ __PRETTY_FUNCTION__))
;
8870
8871 if (Tag->isInvalidDecl())
8872 return true;
8873
8874 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8875 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8876 if (!Pattern) {
8877 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8878 << Context.getTypeDeclType(Record);
8879 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8880 return true;
8881 }
8882
8883 // C++0x [temp.explicit]p2:
8884 // If the explicit instantiation is for a class or member class, the
8885 // elaborated-type-specifier in the declaration shall include a
8886 // simple-template-id.
8887 //
8888 // C++98 has the same restriction, just worded differently.
8889 if (!ScopeSpecifierHasTemplateId(SS))
8890 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8891 << Record << SS.getRange();
8892
8893 // C++0x [temp.explicit]p2:
8894 // There are two forms of explicit instantiation: an explicit instantiation
8895 // definition and an explicit instantiation declaration. An explicit
8896 // instantiation declaration begins with the extern keyword. [...]
8897 TemplateSpecializationKind TSK
8898 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8899 : TSK_ExplicitInstantiationDeclaration;
8900
8901 // C++0x [temp.explicit]p2:
8902 // [...] An explicit instantiation shall appear in an enclosing
8903 // namespace of its template. [...]
8904 //
8905 // This is C++ DR 275.
8906 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8907
8908 // Verify that it is okay to explicitly instantiate here.
8909 CXXRecordDecl *PrevDecl
8910 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8911 if (!PrevDecl && Record->getDefinition())
8912 PrevDecl = Record;
8913 if (PrevDecl) {
8914 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
8915 bool HasNoEffect = false;
8916 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8916, __extension__ __PRETTY_FUNCTION__))
;
8917 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8918 PrevDecl,
8919 MSInfo->getTemplateSpecializationKind(),
8920 MSInfo->getPointOfInstantiation(),
8921 HasNoEffect))
8922 return true;
8923 if (HasNoEffect)
8924 return TagD;
8925 }
8926
8927 CXXRecordDecl *RecordDef
8928 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8929 if (!RecordDef) {
8930 // C++ [temp.explicit]p3:
8931 // A definition of a member class of a class template shall be in scope
8932 // at the point of an explicit instantiation of the member class.
8933 CXXRecordDecl *Def
8934 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8935 if (!Def) {
8936 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8937 << 0 << Record->getDeclName() << Record->getDeclContext();
8938 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8939 << Pattern;
8940 return true;
8941 } else {
8942 if (InstantiateClass(NameLoc, Record, Def,
8943 getTemplateInstantiationArgs(Record),
8944 TSK))
8945 return true;
8946
8947 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8948 if (!RecordDef)
8949 return true;
8950 }
8951 }
8952
8953 // Instantiate all of the members of the class.
8954 InstantiateClassMembers(NameLoc, RecordDef,
8955 getTemplateInstantiationArgs(Record), TSK);
8956
8957 if (TSK == TSK_ExplicitInstantiationDefinition)
8958 MarkVTableUsed(NameLoc, RecordDef, true);
8959
8960 // FIXME: We don't have any representation for explicit instantiations of
8961 // member classes. Such a representation is not needed for compilation, but it
8962 // should be available for clients that want to see all of the declarations in
8963 // the source code.
8964 return TagD;
8965}
8966
8967DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8968 SourceLocation ExternLoc,
8969 SourceLocation TemplateLoc,
8970 Declarator &D) {
8971 // Explicit instantiations always require a name.
8972 // TODO: check if/when DNInfo should replace Name.
8973 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8974 DeclarationName Name = NameInfo.getName();
8975 if (!Name) {
1
Taking false branch
8976 if (!D.isInvalidType())
8977 Diag(D.getDeclSpec().getLocStart(),
8978 diag::err_explicit_instantiation_requires_name)
8979 << D.getDeclSpec().getSourceRange()
8980 << D.getSourceRange();
8981
8982 return true;
8983 }
8984
8985 // The scope passed in may not be a decl scope. Zip up the scope tree until
8986 // we find one that is.
8987 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2
Assuming the condition is false
4
Loop condition is false. Execution continues on line 8992
8988 (S->getFlags() & Scope::TemplateParamScope) != 0)
3
Assuming the condition is false
8989 S = S->getParent();
8990
8991 // Determine the type of the declaration.
8992 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8993 QualType R = T->getType();
8994 if (R.isNull())
5
Taking false branch
8995 return true;
8996
8997 // C++ [dcl.stc]p1:
8998 // A storage-class-specifier shall not be specified in [...] an explicit
8999 // instantiation (14.7.2) directive.
9000 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6
Assuming the condition is false
7
Taking false branch
9001 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9002 << Name;
9003 return true;
9004 } else if (D.getDeclSpec().getStorageClassSpec()
8
Assuming the condition is false
9
Taking false branch
9005 != DeclSpec::SCS_unspecified) {
9006 // Complain about then remove the storage class specifier.
9007 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9008 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9009
9010 D.getMutableDeclSpec().ClearStorageClassSpecs();
9011 }
9012
9013 // C++0x [temp.explicit]p1:
9014 // [...] An explicit instantiation of a function template shall not use the
9015 // inline or constexpr specifiers.
9016 // Presumably, this also applies to member functions of class templates as
9017 // well.
9018 if (D.getDeclSpec().isInlineSpecified())
10
Taking false branch
9019 Diag(D.getDeclSpec().getInlineSpecLoc(),
9020 getLangOpts().CPlusPlus11 ?
9021 diag::err_explicit_instantiation_inline :
9022 diag::warn_explicit_instantiation_inline_0x)
9023 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9024 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
11
Assuming the condition is false
9025 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9026 // not already specified.
9027 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9028 diag::err_explicit_instantiation_constexpr);
9029
9030 // A deduction guide is not on the list of entities that can be explicitly
9031 // instantiated.
9032 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
12
Assuming the condition is false
13
Taking false branch
9033 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
9034 << /*explicit instantiation*/ 0;
9035 return true;
9036 }
9037
9038 // C++0x [temp.explicit]p2:
9039 // There are two forms of explicit instantiation: an explicit instantiation
9040 // definition and an explicit instantiation declaration. An explicit
9041 // instantiation declaration begins with the extern keyword. [...]
9042 TemplateSpecializationKind TSK
9043 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
14
'?' condition is false
9044 : TSK_ExplicitInstantiationDeclaration;
9045
9046 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9047 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
9048
9049 if (!R->isFunctionType()) {
15
Taking true branch
9050 // C++ [temp.explicit]p1:
9051 // A [...] static data member of a class template can be explicitly
9052 // instantiated from the member definition associated with its class
9053 // template.
9054 // C++1y [temp.explicit]p1:
9055 // A [...] variable [...] template specialization can be explicitly
9056 // instantiated from its template.
9057 if (Previous.isAmbiguous())
16
Assuming the condition is false
17
Taking false branch
9058 return true;
9059
9060 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9061 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9062
9063 if (!PrevTemplate) {
18
Assuming 'PrevTemplate' is non-null
19
Taking false branch
9064 if (!Prev || !Prev->isStaticDataMember()) {
9065 // We expect to see a data data member here.
9066 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9067 << Name;
9068 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9069 P != PEnd; ++P)
9070 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9071 return true;
9072 }
9073
9074 if (!Prev->getInstantiatedFromStaticDataMember()) {
9075 // FIXME: Check for explicit specialization?
9076 Diag(D.getIdentifierLoc(),
9077 diag::err_explicit_instantiation_data_member_not_instantiated)
9078 << Prev;
9079 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9080 // FIXME: Can we provide a note showing where this was declared?
9081 return true;
9082 }
9083 } else {
9084 // Explicitly instantiate a variable template.
9085
9086 // C++1y [dcl.spec.auto]p6:
9087 // ... A program that uses auto or decltype(auto) in a context not
9088 // explicitly allowed in this section is ill-formed.
9089 //
9090 // This includes auto-typed variable template instantiations.
9091 if (R->isUndeducedType()) {
20
Taking false branch
9092 Diag(T->getTypeLoc().getLocStart(),
9093 diag::err_auto_not_allowed_var_inst);
9094 return true;
9095 }
9096
9097 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
21
Assuming the condition is false
22
Taking false branch
9098 // C++1y [temp.explicit]p3:
9099 // If the explicit instantiation is for a variable, the unqualified-id
9100 // in the declaration shall be a template-id.
9101 Diag(D.getIdentifierLoc(),
9102 diag::err_explicit_instantiation_without_template_id)
9103 << PrevTemplate;
9104 Diag(PrevTemplate->getLocation(),
9105 diag::note_explicit_instantiation_here);
9106 return true;
9107 }
9108
9109 // Translate the parser's template argument list into our AST format.
9110 TemplateArgumentListInfo TemplateArgs =
9111 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9112
9113 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
23
Calling 'Sema::CheckVarTemplateId'
9114 D.getIdentifierLoc(), TemplateArgs);
9115 if (Res.isInvalid())
9116 return true;
9117
9118 // Ignore access control bits, we don't need them for redeclaration
9119 // checking.
9120 Prev = cast<VarDecl>(Res.get());
9121 }
9122
9123 // C++0x [temp.explicit]p2:
9124 // If the explicit instantiation is for a member function, a member class
9125 // or a static data member of a class template specialization, the name of
9126 // the class template specialization in the qualified-id for the member
9127 // name shall be a simple-template-id.
9128 //
9129 // C++98 has the same restriction, just worded differently.
9130 //
9131 // This does not apply to variable template specializations, where the
9132 // template-id is in the unqualified-id instead.
9133 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9134 Diag(D.getIdentifierLoc(),
9135 diag::ext_explicit_instantiation_without_qualified_id)
9136 << Prev << D.getCXXScopeSpec().getRange();
9137
9138 // Check the scope of this explicit instantiation.
9139 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
9140
9141 // Verify that it is okay to explicitly instantiate here.
9142 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9143 SourceLocation POI = Prev->getPointOfInstantiation();
9144 bool HasNoEffect = false;
9145 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9146 PrevTSK, POI, HasNoEffect))
9147 return true;
9148
9149 if (!HasNoEffect) {
9150 // Instantiate static data member or variable template.
9151 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9152 if (PrevTemplate) {
9153 // Merge attributes.
9154 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
9155 ProcessDeclAttributeList(S, Prev, Attr);
9156 }
9157 if (TSK == TSK_ExplicitInstantiationDefinition)
9158 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9159 }
9160
9161 // Check the new variable specialization against the parsed input.
9162 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9163 Diag(T->getTypeLoc().getLocStart(),
9164 diag::err_invalid_var_template_spec_type)
9165 << 0 << PrevTemplate << R << Prev->getType();
9166 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9167 << 2 << PrevTemplate->getDeclName();
9168 return true;
9169 }
9170
9171 // FIXME: Create an ExplicitInstantiation node?
9172 return (Decl*) nullptr;
9173 }
9174
9175 // If the declarator is a template-id, translate the parser's template
9176 // argument list into our AST format.
9177 bool HasExplicitTemplateArgs = false;
9178 TemplateArgumentListInfo TemplateArgs;
9179 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9180 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9181 HasExplicitTemplateArgs = true;
9182 }
9183
9184 // C++ [temp.explicit]p1:
9185 // A [...] function [...] can be explicitly instantiated from its template.
9186 // A member function [...] of a class template can be explicitly
9187 // instantiated from the member definition associated with its class
9188 // template.
9189 UnresolvedSet<8> TemplateMatches;
9190 FunctionDecl *NonTemplateMatch = nullptr;
9191 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
9192 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9193 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9194 P != PEnd; ++P) {
9195 NamedDecl *Prev = *P;
9196 if (!HasExplicitTemplateArgs) {
9197 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9198 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9199 /*AdjustExceptionSpec*/true);
9200 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9201 if (Method->getPrimaryTemplate()) {
9202 TemplateMatches.addDecl(Method, P.getAccess());
9203 } else {
9204 // FIXME: Can this assert ever happen? Needs a test.
9205 assert(!NonTemplateMatch && "Multiple NonTemplateMatches")(static_cast <bool> (!NonTemplateMatch && "Multiple NonTemplateMatches"
) ? void (0) : __assert_fail ("!NonTemplateMatch && \"Multiple NonTemplateMatches\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9205, __extension__ __PRETTY_FUNCTION__))
;
9206 NonTemplateMatch = Method;
9207 }
9208 }
9209 }
9210 }
9211
9212 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9213 if (!FunTmpl)
9214 continue;
9215
9216 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9217 FunctionDecl *Specialization = nullptr;
9218 if (TemplateDeductionResult TDK
9219 = DeduceTemplateArguments(FunTmpl,
9220 (HasExplicitTemplateArgs ? &TemplateArgs
9221 : nullptr),
9222 R, Specialization, Info)) {
9223 // Keep track of almost-matches.
9224 FailedCandidates.addCandidate()
9225 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9226 MakeDeductionFailureInfo(Context, TDK, Info));
9227 (void)TDK;
9228 continue;
9229 }
9230
9231 // Target attributes are part of the cuda function signature, so
9232 // the cuda target of the instantiated function must match that of its
9233 // template. Given that C++ template deduction does not take
9234 // target attributes into account, we reject candidates here that
9235 // have a different target.
9236 if (LangOpts.CUDA &&
9237 IdentifyCUDATarget(Specialization,
9238 /* IgnoreImplicitHDAttributes = */ true) !=
9239 IdentifyCUDATarget(Attr)) {
9240 FailedCandidates.addCandidate().set(
9241 P.getPair(), FunTmpl->getTemplatedDecl(),
9242 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9243 continue;
9244 }
9245
9246 TemplateMatches.addDecl(Specialization, P.getAccess());
9247 }
9248
9249 FunctionDecl *Specialization = NonTemplateMatch;
9250 if (!Specialization) {
9251 // Find the most specialized function template specialization.
9252 UnresolvedSetIterator Result = getMostSpecialized(
9253 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9254 D.getIdentifierLoc(),
9255 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9256 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9257 PDiag(diag::note_explicit_instantiation_candidate));
9258
9259 if (Result == TemplateMatches.end())
9260 return true;
9261
9262 // Ignore access control bits, we don't need them for redeclaration checking.
9263 Specialization = cast<FunctionDecl>(*Result);
9264 }
9265
9266 // C++11 [except.spec]p4
9267 // In an explicit instantiation an exception-specification may be specified,
9268 // but is not required.
9269 // If an exception-specification is specified in an explicit instantiation
9270 // directive, it shall be compatible with the exception-specifications of
9271 // other declarations of that function.
9272 if (auto *FPT = R->getAs<FunctionProtoType>())
9273 if (FPT->hasExceptionSpec()) {
9274 unsigned DiagID =
9275 diag::err_mismatched_exception_spec_explicit_instantiation;
9276 if (getLangOpts().MicrosoftExt)
9277 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9278 bool Result = CheckEquivalentExceptionSpec(
9279 PDiag(DiagID) << Specialization->getType(),
9280 PDiag(diag::note_explicit_instantiation_here),
9281 Specialization->getType()->getAs<FunctionProtoType>(),
9282 Specialization->getLocation(), FPT, D.getLocStart());
9283 // In Microsoft mode, mismatching exception specifications just cause a
9284 // warning.
9285 if (!getLangOpts().MicrosoftExt && Result)
9286 return true;
9287 }
9288
9289 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9290 Diag(D.getIdentifierLoc(),
9291 diag::err_explicit_instantiation_member_function_not_instantiated)
9292 << Specialization
9293 << (Specialization->getTemplateSpecializationKind() ==
9294 TSK_ExplicitSpecialization);
9295 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9296 return true;
9297 }
9298
9299 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9300 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9301 PrevDecl = Specialization;
9302
9303 if (PrevDecl) {
9304 bool HasNoEffect = false;
9305 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9306 PrevDecl,
9307 PrevDecl->getTemplateSpecializationKind(),
9308 PrevDecl->getPointOfInstantiation(),
9309 HasNoEffect))
9310 return true;
9311
9312 // FIXME: We may still want to build some representation of this
9313 // explicit specialization.
9314 if (HasNoEffect)
9315 return (Decl*) nullptr;
9316 }
9317
9318 if (Attr)
9319 ProcessDeclAttributeList(S, Specialization, Attr);
9320
9321 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9322 // instantiation declarations.
9323 if (TSK == TSK_ExplicitInstantiationDefinition &&
9324 Specialization->hasAttr<DLLImportAttr>() &&
9325 Context.getTargetInfo().getCXXABI().isMicrosoft())
9326 TSK = TSK_ExplicitInstantiationDeclaration;
9327
9328 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9329
9330 if (Specialization->isDefined()) {
9331 // Let the ASTConsumer know that this function has been explicitly
9332 // instantiated now, and its linkage might have changed.
9333 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9334 } else if (TSK == TSK_ExplicitInstantiationDefinition)
9335 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9336
9337 // C++0x [temp.explicit]p2:
9338 // If the explicit instantiation is for a member function, a member class
9339 // or a static data member of a class template specialization, the name of
9340 // the class template specialization in the qualified-id for the member
9341 // name shall be a simple-template-id.
9342 //
9343 // C++98 has the same restriction, just worded differently.
9344 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9345 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9346 D.getCXXScopeSpec().isSet() &&
9347 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9348 Diag(D.getIdentifierLoc(),
9349 diag::ext_explicit_instantiation_without_qualified_id)
9350 << Specialization << D.getCXXScopeSpec().getRange();
9351
9352 CheckExplicitInstantiationScope(*this,
9353 FunTmpl? (NamedDecl *)FunTmpl
9354 : Specialization->getInstantiatedFromMemberFunction(),
9355 D.getIdentifierLoc(),
9356 D.getCXXScopeSpec().isSet());
9357
9358 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9359 return (Decl*) nullptr;
9360}
9361
9362TypeResult
9363Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9364 const CXXScopeSpec &SS, IdentifierInfo *Name,
9365 SourceLocation TagLoc, SourceLocation NameLoc) {
9366 // This has to hold, because SS is expected to be defined.
9367 assert(Name && "Expected a name in a dependent tag")(static_cast <bool> (Name && "Expected a name in a dependent tag"
) ? void (0) : __assert_fail ("Name && \"Expected a name in a dependent tag\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9367, __extension__ __PRETTY_FUNCTION__))
;
9368
9369 NestedNameSpecifier *NNS = SS.getScopeRep();
9370 if (!NNS)
9371 return true;
9372
9373 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9374
9375 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9376 Diag(NameLoc, diag::err_dependent_tag_decl)
9377 << (TUK == TUK_Definition) << Kind << SS.getRange();
9378 return true;
9379 }
9380
9381 // Create the resulting type.
9382 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9383 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9384
9385 // Create type-source location information for this type.
9386 TypeLocBuilder TLB;
9387 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9388 TL.setElaboratedKeywordLoc(TagLoc);
9389 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9390 TL.setNameLoc(NameLoc);
9391 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9392}
9393
9394TypeResult
9395Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9396 const CXXScopeSpec &SS, const IdentifierInfo &II,
9397 SourceLocation IdLoc) {
9398 if (SS.isInvalid())
9399 return true;
9400
9401 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9402 Diag(TypenameLoc,
9403 getLangOpts().CPlusPlus11 ?
9404 diag::warn_cxx98_compat_typename_outside_of_template :
9405 diag::ext_typename_outside_of_template)
9406 << FixItHint::CreateRemoval(TypenameLoc);
9407
9408 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9409 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9410 TypenameLoc, QualifierLoc, II, IdLoc);
9411 if (T.isNull())
9412 return true;
9413
9414 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9415 if (isa<DependentNameType>(T)) {
9416 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9417 TL.setElaboratedKeywordLoc(TypenameLoc);
9418 TL.setQualifierLoc(QualifierLoc);
9419 TL.setNameLoc(IdLoc);
9420 } else {
9421 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9422 TL.setElaboratedKeywordLoc(TypenameLoc);
9423 TL.setQualifierLoc(QualifierLoc);
9424 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9425 }
9426
9427 return CreateParsedType(T, TSI);
9428}
9429
9430TypeResult
9431Sema::ActOnTypenameType(Scope *S,
9432 SourceLocation TypenameLoc,
9433 const CXXScopeSpec &SS,
9434 SourceLocation TemplateKWLoc,
9435 TemplateTy TemplateIn,
9436 IdentifierInfo *TemplateII,
9437 SourceLocation TemplateIILoc,
9438 SourceLocation LAngleLoc,
9439 ASTTemplateArgsPtr TemplateArgsIn,
9440 SourceLocation RAngleLoc) {
9441 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9442 Diag(TypenameLoc,
9443 getLangOpts().CPlusPlus11 ?
9444 diag::warn_cxx98_compat_typename_outside_of_template :
9445 diag::ext_typename_outside_of_template)
9446 << FixItHint::CreateRemoval(TypenameLoc);
9447
9448 // Strangely, non-type results are not ignored by this lookup, so the
9449 // program is ill-formed if it finds an injected-class-name.
9450 if (TypenameLoc.isValid()) {
9451 auto *LookupRD =
9452 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9453 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9454 Diag(TemplateIILoc,
9455 diag::ext_out_of_line_qualified_id_type_names_constructor)
9456 << TemplateII << 0 /*injected-class-name used as template name*/
9457 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9458 }
9459 }
9460
9461 // Translate the parser's template argument list in our AST format.
9462 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9463 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9464
9465 TemplateName Template = TemplateIn.get();
9466 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9467 // Construct a dependent template specialization type.
9468 assert(DTN && "dependent template has non-dependent name?")(static_cast <bool> (DTN && "dependent template has non-dependent name?"
) ? void (0) : __assert_fail ("DTN && \"dependent template has non-dependent name?\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9468, __extension__ __PRETTY_FUNCTION__))
;
9469 assert(DTN->getQualifier() == SS.getScopeRep())(static_cast <bool> (DTN->getQualifier() == SS.getScopeRep
()) ? void (0) : __assert_fail ("DTN->getQualifier() == SS.getScopeRep()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9469, __extension__ __PRETTY_FUNCTION__))
;
9470 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9471 DTN->getQualifier(),
9472 DTN->getIdentifier(),
9473 TemplateArgs);
9474
9475 // Create source-location information for this type.
9476 TypeLocBuilder Builder;
9477 DependentTemplateSpecializationTypeLoc SpecTL
9478 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9479 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9480 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9481 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9482 SpecTL.setTemplateNameLoc(TemplateIILoc);
9483 SpecTL.setLAngleLoc(LAngleLoc);
9484 SpecTL.setRAngleLoc(RAngleLoc);
9485 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9486 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9487 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9488 }
9489
9490 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9491 if (T.isNull())
9492 return true;
9493
9494 // Provide source-location information for the template specialization type.
9495 TypeLocBuilder Builder;
9496 TemplateSpecializationTypeLoc SpecTL
9497 = Builder.push<TemplateSpecializationTypeLoc>(T);
9498 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9499 SpecTL.setTemplateNameLoc(TemplateIILoc);
9500 SpecTL.setLAngleLoc(LAngleLoc);
9501 SpecTL.setRAngleLoc(RAngleLoc);
9502 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9503 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9504
9505 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9506 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9507 TL.setElaboratedKeywordLoc(TypenameLoc);
9508 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9509
9510 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9511 return CreateParsedType(T, TSI);
9512}
9513
9514
9515/// Determine whether this failed name lookup should be treated as being
9516/// disabled by a usage of std::enable_if.
9517static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9518 SourceRange &CondRange, Expr *&Cond) {
9519 // We must be looking for a ::type...
9520 if (!II.isStr("type"))
9521 return false;
9522
9523 // ... within an explicitly-written template specialization...
9524 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9525 return false;
9526 TypeLoc EnableIfTy = NNS.getTypeLoc();
9527 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9528 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9529 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9530 return false;
9531 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
9532
9533 // ... which names a complete class template declaration...
9534 const TemplateDecl *EnableIfDecl =
9535 EnableIfTST->getTemplateName().getAsTemplateDecl();
9536 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9537 return false;
9538
9539 // ... called "enable_if".
9540 const IdentifierInfo *EnableIfII =
9541 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9542 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9543 return false;
9544
9545 // Assume the first template argument is the condition.
9546 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9547
9548 // Dig out the condition.
9549 Cond = nullptr;
9550 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9551 != TemplateArgument::Expression)
9552 return true;
9553
9554 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9555
9556 // Ignore Boolean literals; they add no value.
9557 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9558 Cond = nullptr;
9559
9560 return true;
9561}
9562
9563/// \brief Build the type that describes a C++ typename specifier,
9564/// e.g., "typename T::type".
9565QualType
9566Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9567 SourceLocation KeywordLoc,
9568 NestedNameSpecifierLoc QualifierLoc,
9569 const IdentifierInfo &II,
9570 SourceLocation IILoc) {
9571 CXXScopeSpec SS;
9572 SS.Adopt(QualifierLoc);
9573
9574 DeclContext *Ctx = computeDeclContext(SS);
9575 if (!Ctx) {
9576 // If the nested-name-specifier is dependent and couldn't be
9577 // resolved to a type, build a typename type.
9578 assert(QualifierLoc.getNestedNameSpecifier()->isDependent())(static_cast <bool> (QualifierLoc.getNestedNameSpecifier
()->isDependent()) ? void (0) : __assert_fail ("QualifierLoc.getNestedNameSpecifier()->isDependent()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9578, __extension__ __PRETTY_FUNCTION__))
;
9579 return Context.getDependentNameType(Keyword,
9580 QualifierLoc.getNestedNameSpecifier(),
9581 &II);
9582 }
9583
9584 // If the nested-name-specifier refers to the current instantiation,
9585 // the "typename" keyword itself is superfluous. In C++03, the
9586 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9587 // allows such extraneous "typename" keywords, and we retroactively
9588 // apply this DR to C++03 code with only a warning. In any case we continue.
9589
9590 if (RequireCompleteDeclContext(SS, Ctx))
9591 return QualType();
9592
9593 DeclarationName Name(&II);
9594 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9595 LookupQualifiedName(Result, Ctx, SS);
9596 unsigned DiagID = 0;
9597 Decl *Referenced = nullptr;
9598 switch (Result.getResultKind()) {
9599 case LookupResult::NotFound: {
9600 // If we're looking up 'type' within a template named 'enable_if', produce
9601 // a more specific diagnostic.
9602 SourceRange CondRange;
9603 Expr *Cond = nullptr;
9604 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9605 // If we have a condition, narrow it down to the specific failed
9606 // condition.
9607 if (Cond) {
9608 Expr *FailedCond;
9609 std::string FailedDescription;
9610 std::tie(FailedCond, FailedDescription) =
9611 findFailedBooleanCondition(Cond, /*AllowTopLevelCond=*/true);
9612
9613 Diag(FailedCond->getExprLoc(),
9614 diag::err_typename_nested_not_found_requirement)
9615 << FailedDescription
9616 << FailedCond->getSourceRange();
9617 return QualType();
9618 }
9619
9620 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9621 << Ctx << CondRange;
9622 return QualType();
9623 }
9624
9625 DiagID = diag::err_typename_nested_not_found;
9626 break;
9627 }
9628
9629 case LookupResult::FoundUnresolvedValue: {
9630 // We found a using declaration that is a value. Most likely, the using
9631 // declaration itself is meant to have the 'typename' keyword.
9632 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9633 IILoc);
9634 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9635 << Name << Ctx << FullRange;
9636 if (UnresolvedUsingValueDecl *Using
9637 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9638 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9639 Diag(Loc, diag::note_using_value_decl_missing_typename)
9640 << FixItHint::CreateInsertion(Loc, "typename ");
9641 }
9642 }
9643 // Fall through to create a dependent typename type, from which we can recover
9644 // better.
9645 LLVM_FALLTHROUGH[[clang::fallthrough]];
9646
9647 case LookupResult::NotFoundInCurrentInstantiation:
9648 // Okay, it's a member of an unknown instantiation.
9649 return Context.getDependentNameType(Keyword,
9650 QualifierLoc.getNestedNameSpecifier(),
9651 &II);
9652
9653 case LookupResult::Found:
9654 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9655 // C++ [class.qual]p2:
9656 // In a lookup in which function names are not ignored and the
9657 // nested-name-specifier nominates a class C, if the name specified
9658 // after the nested-name-specifier, when looked up in C, is the
9659 // injected-class-name of C [...] then the name is instead considered
9660 // to name the constructor of class C.
9661 //
9662 // Unlike in an elaborated-type-specifier, function names are not ignored
9663 // in typename-specifier lookup. However, they are ignored in all the
9664 // contexts where we form a typename type with no keyword (that is, in
9665 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9666 //
9667 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9668 // ignore functions, but that appears to be an oversight.
9669 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9670 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9671 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9672 FoundRD->isInjectedClassName() &&
9673 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9674 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9675 << &II << 1 << 0 /*'typename' keyword used*/;
9676
9677 // We found a type. Build an ElaboratedType, since the
9678 // typename-specifier was just sugar.
9679 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9680 return Context.getElaboratedType(Keyword,
9681 QualifierLoc.getNestedNameSpecifier(),
9682 Context.getTypeDeclType(Type));
9683 }
9684
9685 // C++ [dcl.type.simple]p2:
9686 // A type-specifier of the form
9687 // typename[opt] nested-name-specifier[opt] template-name
9688 // is a placeholder for a deduced class type [...].
9689 if (getLangOpts().CPlusPlus17) {
9690 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9691 return Context.getElaboratedType(
9692 Keyword, QualifierLoc.getNestedNameSpecifier(),
9693 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9694 QualType(), false));
9695 }
9696 }
9697
9698 DiagID = diag::err_typename_nested_not_type;
9699 Referenced = Result.getFoundDecl();
9700 break;
9701
9702 case LookupResult::FoundOverloaded:
9703 DiagID = diag::err_typename_nested_not_type;
9704 Referenced = *Result.begin();
9705 break;
9706
9707 case LookupResult::Ambiguous:
9708 return QualType();
9709 }
9710
9711 // If we get here, it's because name lookup did not find a
9712 // type. Emit an appropriate diagnostic and return an error.
9713 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9714 IILoc);
9715 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9716 if (Referenced)
9717 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9718 << Name;
9719 return QualType();
9720}
9721
9722namespace {
9723 // See Sema::RebuildTypeInCurrentInstantiation
9724 class CurrentInstantiationRebuilder
9725 : public TreeTransform<CurrentInstantiationRebuilder> {
9726 SourceLocation Loc;
9727 DeclarationName Entity;
9728
9729 public:
9730 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
9731
9732 CurrentInstantiationRebuilder(Sema &SemaRef,
9733 SourceLocation Loc,
9734 DeclarationName Entity)
9735 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9736 Loc(Loc), Entity(Entity) { }
9737
9738 /// \brief Determine whether the given type \p T has already been
9739 /// transformed.
9740 ///
9741 /// For the purposes of type reconstruction, a type has already been
9742 /// transformed if it is NULL or if it is not dependent.
9743 bool AlreadyTransformed(QualType T) {
9744 return T.isNull() || !T->isDependentType();
9745 }
9746
9747 /// \brief Returns the location of the entity whose type is being
9748 /// rebuilt.
9749 SourceLocation getBaseLocation() { return Loc; }
9750
9751 /// \brief Returns the name of the entity whose type is being rebuilt.
9752 DeclarationName getBaseEntity() { return Entity; }
9753
9754 /// \brief Sets the "base" location and entity when that
9755 /// information is known based on another transformation.
9756 void setBase(SourceLocation Loc, DeclarationName Entity) {
9757 this->Loc = Loc;
9758 this->Entity = Entity;
9759 }
9760
9761 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9762 // Lambdas never need to be transformed.
9763 return E;
9764 }
9765 };
9766} // end anonymous namespace
9767
9768/// \brief Rebuilds a type within the context of the current instantiation.
9769///
9770/// The type \p T is part of the type of an out-of-line member definition of
9771/// a class template (or class template partial specialization) that was parsed
9772/// and constructed before we entered the scope of the class template (or
9773/// partial specialization thereof). This routine will rebuild that type now
9774/// that we have entered the declarator's scope, which may produce different
9775/// canonical types, e.g.,
9776///
9777/// \code
9778/// template<typename T>
9779/// struct X {
9780/// typedef T* pointer;
9781/// pointer data();
9782/// };
9783///
9784/// template<typename T>
9785/// typename X<T>::pointer X<T>::data() { ... }
9786/// \endcode
9787///
9788/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9789/// since we do not know that we can look into X<T> when we parsed the type.
9790/// This function will rebuild the type, performing the lookup of "pointer"
9791/// in X<T> and returning an ElaboratedType whose canonical type is the same
9792/// as the canonical type of T*, allowing the return types of the out-of-line
9793/// definition and the declaration to match.
9794TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9795 SourceLocation Loc,
9796 DeclarationName Name) {
9797 if (!T || !T->getType()->isDependentType())
9798 return T;
9799
9800 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9801 return Rebuilder.TransformType(T);
9802}
9803
9804ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
9805 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9806 DeclarationName());
9807 return Rebuilder.TransformExpr(E);
9808}
9809
9810bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
9811 if (SS.isInvalid())
9812 return true;
9813
9814 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9815 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9816 DeclarationName());
9817 NestedNameSpecifierLoc Rebuilt
9818 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9819 if (!Rebuilt)
9820 return true;
9821
9822 SS.Adopt(Rebuilt);
9823 return false;
9824}
9825
9826/// \brief Rebuild the template parameters now that we know we're in a current
9827/// instantiation.
9828bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9829 TemplateParameterList *Params) {
9830 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9831 Decl *Param = Params->getParam(I);
9832
9833 // There is nothing to rebuild in a type parameter.
9834 if (isa<TemplateTypeParmDecl>(Param))
9835 continue;
9836
9837 // Rebuild the template parameter list of a template template parameter.
9838 if (TemplateTemplateParmDecl *TTP
9839 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9840 if (RebuildTemplateParamsInCurrentInstantiation(
9841 TTP->getTemplateParameters()))
9842 return true;
9843
9844 continue;
9845 }
9846
9847 // Rebuild the type of a non-type template parameter.
9848 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9849 TypeSourceInfo *NewTSI
9850 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9851 NTTP->getLocation(),
9852 NTTP->getDeclName());
9853 if (!NewTSI)
9854 return true;
9855
9856 if (NewTSI != NTTP->getTypeSourceInfo()) {
9857 NTTP->setTypeSourceInfo(NewTSI);
9858 NTTP->setType(NewTSI->getType());
9859 }
9860 }
9861
9862 return false;
9863}
9864
9865/// \brief Produces a formatted string that describes the binding of
9866/// template parameters to template arguments.
9867std::string
9868Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9869 const TemplateArgumentList &Args) {
9870 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9871}
9872
9873std::string
9874Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9875 const TemplateArgument *Args,
9876 unsigned NumArgs) {
9877 SmallString<128> Str;
9878 llvm::raw_svector_ostream Out(Str);
9879
9880 if (!Params || Params->size() == 0 || NumArgs == 0)
9881 return std::string();
9882
9883 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9884 if (I >= NumArgs)
9885 break;
9886
9887 if (I == 0)
9888 Out << "[with ";
9889 else
9890 Out << ", ";
9891
9892 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9893 Out << Id->getName();
9894 } else {
9895 Out << '$' << I;
9896 }
9897
9898 Out << " = ";
9899 Args[I].print(getPrintingPolicy(), Out);
9900 }
9901
9902 Out << ']';
9903 return Out.str();
9904}
9905
9906void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9907 CachedTokens &Toks) {
9908 if (!FD)
9909 return;
9910
9911 auto LPT = llvm::make_unique<LateParsedTemplate>();
9912
9913 // Take tokens to avoid allocations
9914 LPT->Toks.swap(Toks);
9915 LPT->D = FnD;
9916 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9917
9918 FD->setLateTemplateParsed(true);
9919}
9920
9921void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9922 if (!FD)
9923 return;
9924 FD->setLateTemplateParsed(false);
9925}
9926
9927bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9928 DeclContext *DC = CurContext;
9929
9930 while (DC) {
9931 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9932 const FunctionDecl *FD = RD->isLocalClass();
9933 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9934 } else if (DC->isTranslationUnit() || DC->isNamespace())
9935 return false;
9936
9937 DC = DC->getParent();
9938 }
9939 return false;
9940}
9941
9942namespace {
9943/// \brief Walk the path from which a declaration was instantiated, and check
9944/// that every explicit specialization along that path is visible. This enforces
9945/// C++ [temp.expl.spec]/6:
9946///
9947/// If a template, a member template or a member of a class template is
9948/// explicitly specialized then that specialization shall be declared before
9949/// the first use of that specialization that would cause an implicit
9950/// instantiation to take place, in every translation unit in which such a
9951/// use occurs; no diagnostic is required.
9952///
9953/// and also C++ [temp.class.spec]/1:
9954///
9955/// A partial specialization shall be declared before the first use of a
9956/// class template specialization that would make use of the partial
9957/// specialization as the result of an implicit or explicit instantiation
9958/// in every translation unit in which such a use occurs; no diagnostic is
9959/// required.
9960class ExplicitSpecializationVisibilityChecker {
9961 Sema &S;
9962 SourceLocation Loc;
9963 llvm::SmallVector<Module *, 8> Modules;
9964
9965public:
9966 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9967 : S(S), Loc(Loc) {}
9968
9969 void check(NamedDecl *ND) {
9970 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9971 return checkImpl(FD);
9972 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9973 return checkImpl(RD);
9974 if (auto *VD = dyn_cast<VarDecl>(ND))
9975 return checkImpl(VD);
9976 if (auto *ED = dyn_cast<EnumDecl>(ND))
9977 return checkImpl(ED);
9978 }
9979
9980private:
9981 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9982 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9983 : Sema::MissingImportKind::ExplicitSpecialization;
9984 const bool Recover = true;
9985
9986 // If we got a custom set of modules (because only a subset of the
9987 // declarations are interesting), use them, otherwise let
9988 // diagnoseMissingImport intelligently pick some.
9989 if (Modules.empty())
9990 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9991 else
9992 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9993 }
9994
9995 // Check a specific declaration. There are three problematic cases:
9996 //
9997 // 1) The declaration is an explicit specialization of a template
9998 // specialization.
9999 // 2) The declaration is an explicit specialization of a member of an
10000 // templated class.
10001 // 3) The declaration is an instantiation of a template, and that template
10002 // is an explicit specialization of a member of a templated class.
10003 //
10004 // We don't need to go any deeper than that, as the instantiation of the
10005 // surrounding class / etc is not triggered by whatever triggered this
10006 // instantiation, and thus should be checked elsewhere.
10007 template<typename SpecDecl>
10008 void checkImpl(SpecDecl *Spec) {
10009 bool IsHiddenExplicitSpecialization = false;
10010 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10011 IsHiddenExplicitSpecialization =
10012 Spec->getMemberSpecializationInfo()
10013 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
10014 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
10015 } else {
10016 checkInstantiated(Spec);
10017 }
10018
10019 if (IsHiddenExplicitSpecialization)
10020 diagnose(Spec->getMostRecentDecl(), false);
10021 }
10022
10023 void checkInstantiated(FunctionDecl *FD) {
10024 if (auto *TD = FD->getPrimaryTemplate())
10025 checkTemplate(TD);
10026 }
10027
10028 void checkInstantiated(CXXRecordDecl *RD) {
10029 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10030 if (!SD)
10031 return;
10032
10033 auto From = SD->getSpecializedTemplateOrPartial();
10034 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10035 checkTemplate(TD);
10036 else if (auto *TD =
10037 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10038 if (!S.hasVisibleDeclaration(TD))
10039 diagnose(TD, true);
10040 checkTemplate(TD);
10041 }
10042 }
10043
10044 void checkInstantiated(VarDecl *RD) {
10045 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10046 if (!SD)
10047 return;
10048
10049 auto From = SD->getSpecializedTemplateOrPartial();
10050 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10051 checkTemplate(TD);
10052 else if (auto *TD =
10053 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10054 if (!S.hasVisibleDeclaration(TD))
10055 diagnose(TD, true);
10056 checkTemplate(TD);
10057 }
10058 }
10059
10060 void checkInstantiated(EnumDecl *FD) {}
10061
10062 template<typename TemplDecl>
10063 void checkTemplate(TemplDecl *TD) {
10064 if (TD->isMemberSpecialization()) {
10065 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10066 diagnose(TD->getMostRecentDecl(), false);
10067 }
10068 }
10069};
10070} // end anonymous namespace
10071
10072void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10073 if (!getLangOpts().Modules)
10074 return;
10075
10076 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10077}
10078
10079/// \brief Check whether a template partial specialization that we've discovered
10080/// is hidden, and produce suitable diagnostics if so.
10081void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10082 NamedDecl *Spec) {
10083 llvm::SmallVector<Module *, 8> Modules;
10084 if (!hasVisibleDeclaration(Spec, &Modules))
10085 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10086 MissingImportKind::PartialSpecialization,
10087 /*Recover*/true);
10088}

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h

1//===- DeclTemplate.h - Classes for representing C++ templates --*- C++ -*-===//
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//
10/// \file
11/// \brief Defines the C++ template declaration subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
16#define LLVM_CLANG_AST_DECLTEMPLATE_H
17
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/TemplateBase.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/LLVM.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/Specifiers.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/PointerUnion.h"
32#include "llvm/ADT/iterator.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/TrailingObjects.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <iterator>
41#include <utility>
42
43namespace clang {
44
45enum BuiltinTemplateKind : int;
46class ClassTemplateDecl;
47class ClassTemplatePartialSpecializationDecl;
48class Expr;
49class FunctionTemplateDecl;
50class IdentifierInfo;
51class NonTypeTemplateParmDecl;
52class TemplateDecl;
53class TemplateTemplateParmDecl;
54class TemplateTypeParmDecl;
55class UnresolvedSetImpl;
56class VarTemplateDecl;
57class VarTemplatePartialSpecializationDecl;
58
59/// \brief Stores a template parameter of any kind.
60using TemplateParameter =
61 llvm::PointerUnion3<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
62 TemplateTemplateParmDecl *>;
63
64NamedDecl *getAsNamedDecl(TemplateParameter P);
65
66/// \brief Stores a list of template parameters for a TemplateDecl and its
67/// derived classes.
68class TemplateParameterList final
69 : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
70 Expr *> {
71 /// The location of the 'template' keyword.
72 SourceLocation TemplateLoc;
73
74 /// The locations of the '<' and '>' angle brackets.
75 SourceLocation LAngleLoc, RAngleLoc;
76
77 /// The number of template parameters in this template
78 /// parameter list.
79 unsigned NumParams : 30;
80
81 /// Whether this template parameter list contains an unexpanded parameter
82 /// pack.
83 unsigned ContainsUnexpandedParameterPack : 1;
84
85 /// Whether this template parameter list has an associated requires-clause
86 unsigned HasRequiresClause : 1;
87
88protected:
89 TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
90 ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc,
91 Expr *RequiresClause);
92
93 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
94 return NumParams;
95 }
96
97 size_t numTrailingObjects(OverloadToken<Expr *>) const {
98 return HasRequiresClause;
99 }
100
101public:
102 template <size_t N, bool HasRequiresClause>
103 friend class FixedSizeTemplateParameterListStorage;
104 friend TrailingObjects;
105
106 static TemplateParameterList *Create(const ASTContext &C,
107 SourceLocation TemplateLoc,
108 SourceLocation LAngleLoc,
109 ArrayRef<NamedDecl *> Params,
110 SourceLocation RAngleLoc,
111 Expr *RequiresClause);
112
113 /// \brief Iterates through the template parameters in this list.
114 using iterator = NamedDecl **;
115
116 /// \brief Iterates through the template parameters in this list.
117 using const_iterator = NamedDecl * const *;
118
119 iterator begin() { return getTrailingObjects<NamedDecl *>(); }
120 const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
121 iterator end() { return begin() + NumParams; }
122 const_iterator end() const { return begin() + NumParams; }
123
124 unsigned size() const { return NumParams; }
125
126 ArrayRef<NamedDecl*> asArray() {
127 return llvm::makeArrayRef(begin(), end());
128 }
129 ArrayRef<const NamedDecl*> asArray() const {
130 return llvm::makeArrayRef(begin(), size());
131 }
132
133 NamedDecl* getParam(unsigned Idx) {
134 assert(Idx < size() && "Template parameter index out-of-range")(static_cast <bool> (Idx < size() && "Template parameter index out-of-range"
) ? void (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 134, __extension__ __PRETTY_FUNCTION__))
;
135 return begin()[Idx];
136 }
137 const NamedDecl* getParam(unsigned Idx) const {
138 assert(Idx < size() && "Template parameter index out-of-range")(static_cast <bool> (Idx < size() && "Template parameter index out-of-range"
) ? void (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 138, __extension__ __PRETTY_FUNCTION__))
;
139 return begin()[Idx];
140 }
141
142 /// \brief Returns the minimum number of arguments needed to form a
143 /// template specialization.
144 ///
145 /// This may be fewer than the number of template parameters, if some of
146 /// the parameters have default arguments or if there is a parameter pack.
147 unsigned getMinRequiredArguments() const;
148
149 /// \brief Get the depth of this template parameter list in the set of
150 /// template parameter lists.
151 ///
152 /// The first template parameter list in a declaration will have depth 0,
153 /// the second template parameter list will have depth 1, etc.
154 unsigned getDepth() const;
155
156 /// \brief Determine whether this template parameter list contains an
157 /// unexpanded parameter pack.
158 bool containsUnexpandedParameterPack() const {
159 return ContainsUnexpandedParameterPack;
160 }
161
162 /// \brief The constraint-expression of the associated requires-clause.
163 Expr *getRequiresClause() {
164 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
165 }
166
167 /// \brief The constraint-expression of the associated requires-clause.
168 const Expr *getRequiresClause() const {
169 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
170 }
171
172 SourceLocation getTemplateLoc() const { return TemplateLoc; }
173 SourceLocation getLAngleLoc() const { return LAngleLoc; }
174 SourceLocation getRAngleLoc() const { return RAngleLoc; }
175
176 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
177 return SourceRange(TemplateLoc, RAngleLoc);
178 }
179
180public:
181 // FIXME: workaround for MSVC 2013; remove when no longer needed
182 using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
183};
184
185/// \brief Stores a list of template parameters and the associated
186/// requires-clause (if any) for a TemplateDecl and its derived classes.
187/// Suitable for creating on the stack.
188template <size_t N, bool HasRequiresClause>
189class FixedSizeTemplateParameterListStorage
190 : public TemplateParameterList::FixedSizeStorageOwner {
191 typename TemplateParameterList::FixedSizeStorage<
192 NamedDecl *, Expr *>::with_counts<
193 N, HasRequiresClause ? 1u : 0u
194 >::type storage;
195
196public:
197 FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
198 SourceLocation LAngleLoc,
199 ArrayRef<NamedDecl *> Params,
200 SourceLocation RAngleLoc,
201 Expr *RequiresClause)
202 : FixedSizeStorageOwner(
203 (assert(N == Params.size())(static_cast <bool> (N == Params.size()) ? void (0) : __assert_fail
("N == Params.size()", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 203, __extension__ __PRETTY_FUNCTION__))
,
204 assert(HasRequiresClause == static_cast<bool>(RequiresClause))(static_cast <bool> (HasRequiresClause == static_cast<
bool>(RequiresClause)) ? void (0) : __assert_fail ("HasRequiresClause == static_cast<bool>(RequiresClause)"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 204, __extension__ __PRETTY_FUNCTION__))
,
205 new (static_cast<void *>(&storage)) TemplateParameterList(
206 TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
207};
208
209/// \brief A template argument list.
210class TemplateArgumentList final
211 : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
212 /// \brief The template argument list.
213 const TemplateArgument *Arguments;
214
215 /// \brief The number of template arguments in this template
216 /// argument list.
217 unsigned NumArguments;
218
219 // Constructs an instance with an internal Argument list, containing
220 // a copy of the Args array. (Called by CreateCopy)
221 TemplateArgumentList(ArrayRef<TemplateArgument> Args);
222
223public:
224 friend TrailingObjects;
225
226 TemplateArgumentList(const TemplateArgumentList &) = delete;
227 TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
228
229 /// \brief Type used to indicate that the template argument list itself is a
230 /// stack object. It does not own its template arguments.
231 enum OnStackType { OnStack };
232
233 /// \brief Create a new template argument list that copies the given set of
234 /// template arguments.
235 static TemplateArgumentList *CreateCopy(ASTContext &Context,
236 ArrayRef<TemplateArgument> Args);
237
238 /// \brief Construct a new, temporary template argument list on the stack.
239 ///
240 /// The template argument list does not own the template arguments
241 /// provided.
242 explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
243 : Arguments(Args.data()), NumArguments(Args.size()) {}
244
245 /// \brief Produces a shallow copy of the given template argument list.
246 ///
247 /// This operation assumes that the input argument list outlives it.
248 /// This takes the list as a pointer to avoid looking like a copy
249 /// constructor, since this really really isn't safe to use that
250 /// way.
251 explicit TemplateArgumentList(const TemplateArgumentList *Other)
252 : Arguments(Other->data()), NumArguments(Other->size()) {}
253
254 /// \brief Retrieve the template argument at a given index.
255 const TemplateArgument &get(unsigned Idx) const {
256 assert(Idx < NumArguments && "Invalid template argument index")(static_cast <bool> (Idx < NumArguments && "Invalid template argument index"
) ? void (0) : __assert_fail ("Idx < NumArguments && \"Invalid template argument index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 256, __extension__ __PRETTY_FUNCTION__))
;
257 return data()[Idx];
258 }
259
260 /// \brief Retrieve the template argument at a given index.
261 const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
262
263 /// \brief Produce this as an array ref.
264 ArrayRef<TemplateArgument> asArray() const {
265 return llvm::makeArrayRef(data(), size());
266 }
267
268 /// \brief Retrieve the number of template arguments in this
269 /// template argument list.
270 unsigned size() const { return NumArguments; }
271
272 /// \brief Retrieve a pointer to the template argument list.
273 const TemplateArgument *data() const { return Arguments; }
274};
275
276void *allocateDefaultArgStorageChain(const ASTContext &C);
277
278/// Storage for a default argument. This is conceptually either empty, or an
279/// argument value, or a pointer to a previous declaration that had a default
280/// argument.
281///
282/// However, this is complicated by modules: while we require all the default
283/// arguments for a template to be equivalent, there may be more than one, and
284/// we need to track all the originating parameters to determine if the default
285/// argument is visible.
286template<typename ParmDecl, typename ArgType>
287class DefaultArgStorage {
288 /// Storage for both the value *and* another parameter from which we inherit
289 /// the default argument. This is used when multiple default arguments for a
290 /// parameter are merged together from different modules.
291 struct Chain {
292 ParmDecl *PrevDeclWithDefaultArg;
293 ArgType Value;
294 };
295 static_assert(sizeof(Chain) == sizeof(void *) * 2,
296 "non-pointer argument type?");
297
298 llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
299
300 static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
301 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
302 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl*>())
303 Parm = Prev;
304 assert(!Parm->getDefaultArgStorage()(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
305 .ValueOrInherited.template is<ParmDecl *>() &&(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
306 "should only be one level of indirection")(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
;
307 return Parm;
308 }
309
310public:
311 DefaultArgStorage() : ValueOrInherited(ArgType()) {}
312
313 /// Determine whether there is a default argument for this parameter.
314 bool isSet() const { return !ValueOrInherited.isNull(); }
315
316 /// Determine whether the default argument for this parameter was inherited
317 /// from a previous declaration of the same entity.
318 bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
319
320 /// Get the default argument's value. This does not consider whether the
321 /// default argument is visible.
322 ArgType get() const {
323 const DefaultArgStorage *Storage = this;
324 if (auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl*>())
325 Storage = &Prev->getDefaultArgStorage();
326 if (auto *C = Storage->ValueOrInherited.template dyn_cast<Chain*>())
327 return C->Value;
328 return Storage->ValueOrInherited.template get<ArgType>();
329 }
330
331 /// Get the parameter from which we inherit the default argument, if any.
332 /// This is the parameter on which the default argument was actually written.
333 const ParmDecl *getInheritedFrom() const {
334 if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl*>())
335 return D;
336 if (auto *C = ValueOrInherited.template dyn_cast<Chain*>())
337 return C->PrevDeclWithDefaultArg;
338 return nullptr;
339 }
340
341 /// Set the default argument.
342 void set(ArgType Arg) {
343 assert(!isSet() && "default argument already set")(static_cast <bool> (!isSet() && "default argument already set"
) ? void (0) : __assert_fail ("!isSet() && \"default argument already set\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 343, __extension__ __PRETTY_FUNCTION__))
;
344 ValueOrInherited = Arg;
345 }
346
347 /// Set that the default argument was inherited from another parameter.
348 void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
349 assert(!isInherited() && "default argument already inherited")(static_cast <bool> (!isInherited() && "default argument already inherited"
) ? void (0) : __assert_fail ("!isInherited() && \"default argument already inherited\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 349, __extension__ __PRETTY_FUNCTION__))
;
350 InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
351 if (!isSet())
352 ValueOrInherited = InheritedFrom;
353 else
354 ValueOrInherited = new (allocateDefaultArgStorageChain(C))
355 Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
356 }
357
358 /// Remove the default argument, even if it was inherited.
359 void clear() {
360 ValueOrInherited = ArgType();
361 }
362};
363
364//===----------------------------------------------------------------------===//
365// Kinds of Templates
366//===----------------------------------------------------------------------===//
367
368/// \brief Stores the template parameter list and associated constraints for
369/// \c TemplateDecl objects that track associated constraints.
370class ConstrainedTemplateDeclInfo {
371 friend TemplateDecl;
372
373public:
374 ConstrainedTemplateDeclInfo() = default;
375
376 TemplateParameterList *getTemplateParameters() const {
377 return TemplateParams;
378 }
379
380 Expr *getAssociatedConstraints() const { return AssociatedConstraints; }
381
382protected:
383 void setTemplateParameters(TemplateParameterList *TParams) {
384 TemplateParams = TParams;
385 }
386
387 void setAssociatedConstraints(Expr *AC) { AssociatedConstraints = AC; }
388
389 TemplateParameterList *TemplateParams = nullptr;
390 Expr *AssociatedConstraints = nullptr;
391};
392
393
394/// \brief The base class of all kinds of template declarations (e.g.,
395/// class, function, etc.).
396///
397/// The TemplateDecl class stores the list of template parameters and a
398/// reference to the templated scoped declaration: the underlying AST node.
399class TemplateDecl : public NamedDecl {
400 void anchor() override;
401
402protected:
403 // Construct a template decl with the given name and parameters.
404 // Used when there is no templated element (e.g., for tt-params).
405 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
406 SourceLocation L, DeclarationName Name,
407 TemplateParameterList *Params)
408 : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
409 TemplateParams(CTDI) {
410 this->setTemplateParameters(Params);
411 }
412
413 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
414 TemplateParameterList *Params)
415 : TemplateDecl(nullptr, DK, DC, L, Name, Params) {}
416
417 // Construct a template decl with name, parameters, and templated element.
418 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
419 SourceLocation L, DeclarationName Name,
420 TemplateParameterList *Params, NamedDecl *Decl)
421 : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
422 TemplateParams(CTDI) {
423 this->setTemplateParameters(Params);
424 }
425
426 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
427 TemplateParameterList *Params, NamedDecl *Decl)
428 : TemplateDecl(nullptr, DK, DC, L, Name, Params, Decl) {}
429
430public:
431 /// Get the list of template parameters
432 TemplateParameterList *getTemplateParameters() const {
433 const auto *const CTDI =
434 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
435 return CTDI ? CTDI->getTemplateParameters()
436 : TemplateParams.get<TemplateParameterList *>();
437 }
438
439 /// Get the constraint-expression from the associated requires-clause (if any)
440 const Expr *getRequiresClause() const {
441 const TemplateParameterList *const TP = getTemplateParameters();
442 return TP ? TP->getRequiresClause() : nullptr;
443 }
444
445 Expr *getAssociatedConstraints() const {
446 const TemplateDecl *const C = cast<TemplateDecl>(getCanonicalDecl());
447 const auto *const CTDI =
448 C->TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
449 return CTDI ? CTDI->getAssociatedConstraints() : nullptr;
450 }
451
452 /// Get the underlying, templated declaration.
453 NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
454
455 // Implement isa/cast/dyncast/etc.
456 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
457
458 static bool classofKind(Kind K) {
459 return K >= firstTemplate && K <= lastTemplate;
460 }
461
462 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
463 return SourceRange(getTemplateParameters()->getTemplateLoc(),
464 TemplatedDecl->getSourceRange().getEnd());
465 }
466
467protected:
468 NamedDecl *TemplatedDecl;
469 /// \brief The template parameter list and optional requires-clause
470 /// associated with this declaration; alternatively, a
471 /// \c ConstrainedTemplateDeclInfo if the associated constraints of the
472 /// template are being tracked by this particular declaration.
473 llvm::PointerUnion<TemplateParameterList *,
474 ConstrainedTemplateDeclInfo *>
475 TemplateParams;
476
477 void setTemplateParameters(TemplateParameterList *TParams) {
478 if (auto *const CTDI =
479 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>()) {
480 CTDI->setTemplateParameters(TParams);
481 } else {
482 TemplateParams = TParams;
483 }
484 }
485
486 void setAssociatedConstraints(Expr *AC) {
487 assert(isCanonicalDecl() &&(static_cast <bool> (isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? void (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 488, __extension__ __PRETTY_FUNCTION__))
488 "Attaching associated constraints to non-canonical Decl")(static_cast <bool> (isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? void (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 488, __extension__ __PRETTY_FUNCTION__))
;
489 TemplateParams.get<ConstrainedTemplateDeclInfo *>()
490 ->setAssociatedConstraints(AC);
491 }
492
493public:
494 /// \brief Initialize the underlying templated declaration and
495 /// template parameters.
496 void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
497 assert(!TemplatedDecl && "TemplatedDecl already set!")(static_cast <bool> (!TemplatedDecl && "TemplatedDecl already set!"
) ? void (0) : __assert_fail ("!TemplatedDecl && \"TemplatedDecl already set!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 497, __extension__ __PRETTY_FUNCTION__))
;
498 assert(!TemplateParams && "TemplateParams already set!")(static_cast <bool> (!TemplateParams && "TemplateParams already set!"
) ? void (0) : __assert_fail ("!TemplateParams && \"TemplateParams already set!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 498, __extension__ __PRETTY_FUNCTION__))
;
499 TemplatedDecl = templatedDecl;
500 TemplateParams = templateParams;
501 }
502};
503
504/// \brief Provides information about a function template specialization,
505/// which is a FunctionDecl that has been explicitly specialization or
506/// instantiated from a function template.
507class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
508 FunctionTemplateSpecializationInfo(FunctionDecl *FD,
509 FunctionTemplateDecl *Template,
510 TemplateSpecializationKind TSK,
511 const TemplateArgumentList *TemplateArgs,
512 const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
513 SourceLocation POI)
514 : Function(FD), Template(Template, TSK - 1),
515 TemplateArguments(TemplateArgs),
516 TemplateArgumentsAsWritten(TemplateArgsAsWritten),
517 PointOfInstantiation(POI) {}
518
519public:
520 static FunctionTemplateSpecializationInfo *
521 Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
522 TemplateSpecializationKind TSK,
523 const TemplateArgumentList *TemplateArgs,
524 const TemplateArgumentListInfo *TemplateArgsAsWritten,
525 SourceLocation POI);
526
527 /// \brief The function template specialization that this structure
528 /// describes.
529 FunctionDecl *Function;
530
531 /// \brief The function template from which this function template
532 /// specialization was generated.
533 ///
534 /// The two bits contain the top 4 values of TemplateSpecializationKind.
535 llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
536
537 /// \brief The template arguments used to produce the function template
538 /// specialization from the function template.
539 const TemplateArgumentList *TemplateArguments;
540
541 /// \brief The template arguments as written in the sources, if provided.
542 const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
543
544 /// \brief The point at which this function template specialization was
545 /// first instantiated.
546 SourceLocation PointOfInstantiation;
547
548 /// \brief Retrieve the template from which this function was specialized.
549 FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
550
551 /// \brief Determine what kind of template specialization this is.
552 TemplateSpecializationKind getTemplateSpecializationKind() const {
553 return (TemplateSpecializationKind)(Template.getInt() + 1);
554 }
555
556 bool isExplicitSpecialization() const {
557 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
558 }
559
560 /// \brief True if this declaration is an explicit specialization,
561 /// explicit instantiation declaration, or explicit instantiation
562 /// definition.
563 bool isExplicitInstantiationOrSpecialization() const {
564 return isTemplateExplicitInstantiationOrSpecialization(
565 getTemplateSpecializationKind());
566 }
567
568 /// \brief Set the template specialization kind.
569 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
570 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 571, __extension__ __PRETTY_FUNCTION__))
571 "Cannot encode TSK_Undeclared for a function template specialization")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 571, __extension__ __PRETTY_FUNCTION__))
;
572 Template.setInt(TSK - 1);
573 }
574
575 /// \brief Retrieve the first point of instantiation of this function
576 /// template specialization.
577 ///
578 /// The point of instantiation may be an invalid source location if this
579 /// function has yet to be instantiated.
580 SourceLocation getPointOfInstantiation() const {
581 return PointOfInstantiation;
582 }
583
584 /// \brief Set the (first) point of instantiation of this function template
585 /// specialization.
586 void setPointOfInstantiation(SourceLocation POI) {
587 PointOfInstantiation = POI;
588 }
589
590 void Profile(llvm::FoldingSetNodeID &ID) {
591 Profile(ID, TemplateArguments->asArray(),
592 Function->getASTContext());
593 }
594
595 static void
596 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
597 ASTContext &Context) {
598 ID.AddInteger(TemplateArgs.size());
599 for (const TemplateArgument &TemplateArg : TemplateArgs)
600 TemplateArg.Profile(ID, Context);
601 }
602};
603
604/// \brief Provides information a specialization of a member of a class
605/// template, which may be a member function, static data member,
606/// member class or member enumeration.
607class MemberSpecializationInfo {
608 // The member declaration from which this member was instantiated, and the
609 // manner in which the instantiation occurred (in the lower two bits).
610 llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
611
612 // The point at which this member was first instantiated.
613 SourceLocation PointOfInstantiation;
614
615public:
616 explicit
617 MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
618 SourceLocation POI = SourceLocation())
619 : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
620 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 621, __extension__ __PRETTY_FUNCTION__))
621 "Cannot encode undeclared template specializations for members")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 621, __extension__ __PRETTY_FUNCTION__))
;
622 }
623
624 /// \brief Retrieve the member declaration from which this member was
625 /// instantiated.
626 NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
627
628 /// \brief Determine what kind of template specialization this is.
629 TemplateSpecializationKind getTemplateSpecializationKind() const {
630 return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
631 }
632
633 bool isExplicitSpecialization() const {
634 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
635 }
636
637 /// \brief Set the template specialization kind.
638 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
639 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 640, __extension__ __PRETTY_FUNCTION__))
640 "Cannot encode undeclared template specializations for members")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 640, __extension__ __PRETTY_FUNCTION__))
;
641 MemberAndTSK.setInt(TSK - 1);
642 }
643
644 /// \brief Retrieve the first point of instantiation of this member.
645 /// If the point of instantiation is an invalid location, then this member
646 /// has not yet been instantiated.
647 SourceLocation getPointOfInstantiation() const {
648 return PointOfInstantiation;
649 }
650
651 /// \brief Set the first point of instantiation.
652 void setPointOfInstantiation(SourceLocation POI) {
653 PointOfInstantiation = POI;
654 }
655};
656
657/// \brief Provides information about a dependent function-template
658/// specialization declaration.
659///
660/// Since explicit function template specialization and instantiation
661/// declarations can only appear in namespace scope, and you can only
662/// specialize a member of a fully-specialized class, the only way to
663/// get one of these is in a friend declaration like the following:
664///
665/// \code
666/// template \<class T> void foo(T);
667/// template \<class T> class A {
668/// friend void foo<>(T);
669/// };
670/// \endcode
671class DependentFunctionTemplateSpecializationInfo final
672 : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
673 TemplateArgumentLoc,
674 FunctionTemplateDecl *> {
675 /// The number of potential template candidates.
676 unsigned NumTemplates;
677
678 /// The number of template arguments.
679 unsigned NumArgs;
680
681 /// The locations of the left and right angle brackets.
682 SourceRange AngleLocs;
683
684 size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
685 return NumArgs;
686 }
687 size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
688 return NumTemplates;
689 }
690
691 DependentFunctionTemplateSpecializationInfo(
692 const UnresolvedSetImpl &Templates,
693 const TemplateArgumentListInfo &TemplateArgs);
694
695public:
696 friend TrailingObjects;
697
698 static DependentFunctionTemplateSpecializationInfo *
699 Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
700 const TemplateArgumentListInfo &TemplateArgs);
701
702 /// \brief Returns the number of function templates that this might
703 /// be a specialization of.
704 unsigned getNumTemplates() const { return NumTemplates; }
705
706 /// \brief Returns the i'th template candidate.
707 FunctionTemplateDecl *getTemplate(unsigned I) const {
708 assert(I < getNumTemplates() && "template index out of range")(static_cast <bool> (I < getNumTemplates() &&
"template index out of range") ? void (0) : __assert_fail ("I < getNumTemplates() && \"template index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 708, __extension__ __PRETTY_FUNCTION__))
;
709 return getTrailingObjects<FunctionTemplateDecl *>()[I];
710 }
711
712 /// \brief Returns the explicit template arguments that were given.
713 const TemplateArgumentLoc *getTemplateArgs() const {
714 return getTrailingObjects<TemplateArgumentLoc>();
715 }
716
717 /// \brief Returns the number of explicit template arguments that were given.
718 unsigned getNumTemplateArgs() const { return NumArgs; }
719
720 /// \brief Returns the nth template argument.
721 const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
722 assert(I < getNumTemplateArgs() && "template arg index out of range")(static_cast <bool> (I < getNumTemplateArgs() &&
"template arg index out of range") ? void (0) : __assert_fail
("I < getNumTemplateArgs() && \"template arg index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 722, __extension__ __PRETTY_FUNCTION__))
;
723 return getTemplateArgs()[I];
724 }
725
726 SourceLocation getLAngleLoc() const {
727 return AngleLocs.getBegin();
728 }
729
730 SourceLocation getRAngleLoc() const {
731 return AngleLocs.getEnd();
732 }
733};
734
735/// Declaration of a redeclarable template.
736class RedeclarableTemplateDecl : public TemplateDecl,
737 public Redeclarable<RedeclarableTemplateDecl>
738{
739 using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
740
741 RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
742 return getNextRedeclaration();
743 }
744
745 RedeclarableTemplateDecl *getPreviousDeclImpl() override {
746 return getPreviousDecl();
747 }
748
749 RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
750 return getMostRecentDecl();
751 }
752
753protected:
754 template <typename EntryType> struct SpecEntryTraits {
755 using DeclType = EntryType;
756
757 static DeclType *getDecl(EntryType *D) {
758 return D;
759 }
760
761 static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
762 return D->getTemplateArgs().asArray();
763 }
764 };
765
766 template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
767 typename DeclType = typename SETraits::DeclType>
768 struct SpecIterator
769 : llvm::iterator_adaptor_base<
770 SpecIterator<EntryType, SETraits, DeclType>,
771 typename llvm::FoldingSetVector<EntryType>::iterator,
772 typename std::iterator_traits<typename llvm::FoldingSetVector<
773 EntryType>::iterator>::iterator_category,
774 DeclType *, ptrdiff_t, DeclType *, DeclType *> {
775 SpecIterator() = default;
776 explicit SpecIterator(
777 typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
778 : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
779
780 DeclType *operator*() const {
781 return SETraits::getDecl(&*this->I)->getMostRecentDecl();
782 }
783
784 DeclType *operator->() const { return **this; }
785 };
786
787 template <typename EntryType>
788 static SpecIterator<EntryType>
789 makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
790 return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
791 }
792
793 void loadLazySpecializationsImpl() const;
794
795 template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
796 findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
797 ArrayRef<TemplateArgument> Args, void *&InsertPos);
798
799 template <class Derived, class EntryType>
800 void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
801 EntryType *Entry, void *InsertPos);
802
803 struct CommonBase {
804 CommonBase() : InstantiatedFromMember(nullptr, false) {}
805
806 /// \brief The template from which this was most
807 /// directly instantiated (or null).
808 ///
809 /// The boolean value indicates whether this template
810 /// was explicitly specialized.
811 llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
812 InstantiatedFromMember;
813
814 /// \brief If non-null, points to an array of specializations (including
815 /// partial specializations) known only by their external declaration IDs.
816 ///
817 /// The first value in the array is the number of specializations/partial
818 /// specializations that follow.
819 uint32_t *LazySpecializations = nullptr;
820 };
821
822 /// \brief Pointer to the common data shared by all declarations of this
823 /// template.
824 mutable CommonBase *Common = nullptr;
825
826 /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
827 /// the same template. Calling this routine may implicitly allocate memory
828 /// for the common pointer.
829 CommonBase *getCommonPtr() const;
830
831 virtual CommonBase *newCommon(ASTContext &C) const = 0;
832
833 // Construct a template decl with name, parameters, and templated element.
834 RedeclarableTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK,
835 ASTContext &C, DeclContext *DC, SourceLocation L,
836 DeclarationName Name, TemplateParameterList *Params,
837 NamedDecl *Decl)
838 : TemplateDecl(CTDI, DK, DC, L, Name, Params, Decl), redeclarable_base(C)
839 {}
840
841 RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
842 SourceLocation L, DeclarationName Name,
843 TemplateParameterList *Params, NamedDecl *Decl)
844 : RedeclarableTemplateDecl(nullptr, DK, C, DC, L, Name, Params, Decl) {}
845
846public:
847 friend class ASTDeclReader;
848 friend class ASTDeclWriter;
849 friend class ASTReader;
850 template <class decl_type> friend class RedeclarableTemplate;
851
852 /// \brief Retrieves the canonical declaration of this template.
853 RedeclarableTemplateDecl *getCanonicalDecl() override {
854 return getFirstDecl();
855 }
856 const RedeclarableTemplateDecl *getCanonicalDecl() const {
857 return getFirstDecl();
858 }
859
860 /// \brief Determines whether this template was a specialization of a
861 /// member template.
862 ///
863 /// In the following example, the function template \c X<int>::f and the
864 /// member template \c X<int>::Inner are member specializations.
865 ///
866 /// \code
867 /// template<typename T>
868 /// struct X {
869 /// template<typename U> void f(T, U);
870 /// template<typename U> struct Inner;
871 /// };
872 ///
873 /// template<> template<typename T>
874 /// void X<int>::f(int, T);
875 /// template<> template<typename T>
876 /// struct X<int>::Inner { /* ... */ };
877 /// \endcode
878 bool isMemberSpecialization() const {
879 return getCommonPtr()->InstantiatedFromMember.getInt();
880 }
881
882 /// \brief Note that this member template is a specialization.
883 void setMemberSpecialization() {
884 assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&(static_cast <bool> (getCommonPtr()->InstantiatedFromMember
.getPointer() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 885, __extension__ __PRETTY_FUNCTION__))
885 "Only member templates can be member template specializations")(static_cast <bool> (getCommonPtr()->InstantiatedFromMember
.getPointer() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 885, __extension__ __PRETTY_FUNCTION__))
;
886 getCommonPtr()->InstantiatedFromMember.setInt(true);
887 }
888
889 /// \brief Retrieve the member template from which this template was
890 /// instantiated, or nullptr if this template was not instantiated from a
891 /// member template.
892 ///
893 /// A template is instantiated from a member template when the member
894 /// template itself is part of a class template (or member thereof). For
895 /// example, given
896 ///
897 /// \code
898 /// template<typename T>
899 /// struct X {
900 /// template<typename U> void f(T, U);
901 /// };
902 ///
903 /// void test(X<int> x) {
904 /// x.f(1, 'a');
905 /// };
906 /// \endcode
907 ///
908 /// \c X<int>::f is a FunctionTemplateDecl that describes the function
909 /// template
910 ///
911 /// \code
912 /// template<typename U> void X<int>::f(int, U);
913 /// \endcode
914 ///
915 /// which was itself created during the instantiation of \c X<int>. Calling
916 /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
917 /// retrieve the FunctionTemplateDecl for the original template \c f within
918 /// the class template \c X<T>, i.e.,
919 ///
920 /// \code
921 /// template<typename T>
922 /// template<typename U>
923 /// void X<T>::f(T, U);
924 /// \endcode
925 RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
926 return getCommonPtr()->InstantiatedFromMember.getPointer();
927 }
928
929 void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
930 assert(!getCommonPtr()->InstantiatedFromMember.getPointer())(static_cast <bool> (!getCommonPtr()->InstantiatedFromMember
.getPointer()) ? void (0) : __assert_fail ("!getCommonPtr()->InstantiatedFromMember.getPointer()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 930, __extension__ __PRETTY_FUNCTION__))
;
931 getCommonPtr()->InstantiatedFromMember.setPointer(TD);
932 }
933
934 using redecl_range = redeclarable_base::redecl_range;
935 using redecl_iterator = redeclarable_base::redecl_iterator;
936
937 using redeclarable_base::redecls_begin;
938 using redeclarable_base::redecls_end;
939 using redeclarable_base::redecls;
940 using redeclarable_base::getPreviousDecl;
941 using redeclarable_base::getMostRecentDecl;
942 using redeclarable_base::isFirstDecl;
943
944 // Implement isa/cast/dyncast/etc.
945 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
946
947 static bool classofKind(Kind K) {
948 return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
949 }
950};
951
952template <> struct RedeclarableTemplateDecl::
953SpecEntryTraits<FunctionTemplateSpecializationInfo> {
954 using DeclType = FunctionDecl;
955
956 static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
957 return I->Function;
958 }
959
960 static ArrayRef<TemplateArgument>
961 getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
962 return I->TemplateArguments->asArray();
963 }
964};
965
966/// Declaration of a template function.
967class FunctionTemplateDecl : public RedeclarableTemplateDecl {
968protected:
969 friend class FunctionDecl;
970
971 /// \brief Data that is common to all of the declarations of a given
972 /// function template.
973 struct Common : CommonBase {
974 /// \brief The function template specializations for this function
975 /// template, including explicit specializations and instantiations.
976 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
977
978 /// \brief The set of "injected" template arguments used within this
979 /// function template.
980 ///
981 /// This pointer refers to the template arguments (there are as
982 /// many template arguments as template parameaters) for the function
983 /// template, and is allocated lazily, since most function templates do not
984 /// require the use of this information.
985 TemplateArgument *InjectedArgs = nullptr;
986
987 Common() = default;
988 };
989
990 FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
991 DeclarationName Name, TemplateParameterList *Params,
992 NamedDecl *Decl)
993 : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
994 Decl) {}
995
996 CommonBase *newCommon(ASTContext &C) const override;
997
998 Common *getCommonPtr() const {
999 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1000 }
1001
1002 /// \brief Retrieve the set of function template specializations of this
1003 /// function template.
1004 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
1005 getSpecializations() const;
1006
1007 /// \brief Add a specialization of this function template.
1008 ///
1009 /// \param InsertPos Insert position in the FoldingSetVector, must have been
1010 /// retrieved by an earlier call to findSpecialization().
1011 void addSpecialization(FunctionTemplateSpecializationInfo* Info,
1012 void *InsertPos);
1013
1014public:
1015 friend class ASTDeclReader;
1016 friend class ASTDeclWriter;
1017
1018 /// \brief Load any lazily-loaded specializations from the external source.
1019 void LoadLazySpecializations() const;
1020
1021 /// Get the underlying function declaration of the template.
1022 FunctionDecl *getTemplatedDecl() const {
1023 return static_cast<FunctionDecl *>(TemplatedDecl);
1024 }
1025
1026 /// Returns whether this template declaration defines the primary
1027 /// pattern.
1028 bool isThisDeclarationADefinition() const {
1029 return getTemplatedDecl()->isThisDeclarationADefinition();
1030 }
1031
1032 /// \brief Return the specialization with the provided arguments if it exists,
1033 /// otherwise return the insertion point.
1034 FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
1035 void *&InsertPos);
1036
1037 FunctionTemplateDecl *getCanonicalDecl() override {
1038 return cast<FunctionTemplateDecl>(
1039 RedeclarableTemplateDecl::getCanonicalDecl());
1040 }
1041 const FunctionTemplateDecl *getCanonicalDecl() const {
1042 return cast<FunctionTemplateDecl>(
1043 RedeclarableTemplateDecl::getCanonicalDecl());
1044 }
1045
1046 /// \brief Retrieve the previous declaration of this function template, or
1047 /// nullptr if no such declaration exists.
1048 FunctionTemplateDecl *getPreviousDecl() {
1049 return cast_or_null<FunctionTemplateDecl>(
1050 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1051 }
1052 const FunctionTemplateDecl *getPreviousDecl() const {
1053 return cast_or_null<FunctionTemplateDecl>(
1054 static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1055 }
1056
1057 FunctionTemplateDecl *getMostRecentDecl() {
1058 return cast<FunctionTemplateDecl>(
1059 static_cast<RedeclarableTemplateDecl *>(this)
1060 ->getMostRecentDecl());
1061 }
1062 const FunctionTemplateDecl *getMostRecentDecl() const {
1063 return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
1064 }
1065
1066 FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
1067 return cast_or_null<FunctionTemplateDecl>(
1068 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1069 }
1070
1071 using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
1072 using spec_range = llvm::iterator_range<spec_iterator>;
1073
1074 spec_range specializations() const {
1075 return spec_range(spec_begin(), spec_end());
1076 }
1077
1078 spec_iterator spec_begin() const {
1079 return makeSpecIterator(getSpecializations(), false);
1080 }
1081
1082 spec_iterator spec_end() const {
1083 return makeSpecIterator(getSpecializations(), true);
1084 }
1085
1086 /// \brief Retrieve the "injected" template arguments that correspond to the
1087 /// template parameters of this function template.
1088 ///
1089 /// Although the C++ standard has no notion of the "injected" template
1090 /// arguments for a function template, the notion is convenient when
1091 /// we need to perform substitutions inside the definition of a function
1092 /// template.
1093 ArrayRef<TemplateArgument> getInjectedTemplateArgs();
1094
1095 /// \brief Create a function template node.
1096 static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1097 SourceLocation L,
1098 DeclarationName Name,
1099 TemplateParameterList *Params,
1100 NamedDecl *Decl);
1101
1102 /// \brief Create an empty function template node.
1103 static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1104
1105 // Implement isa/cast/dyncast support
1106 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1107 static bool classofKind(Kind K) { return K == FunctionTemplate; }
1108};
1109
1110//===----------------------------------------------------------------------===//
1111// Kinds of Template Parameters
1112//===----------------------------------------------------------------------===//
1113
1114/// \brief Defines the position of a template parameter within a template
1115/// parameter list.
1116///
1117/// Because template parameter can be listed
1118/// sequentially for out-of-line template members, each template parameter is
1119/// given a Depth - the nesting of template parameter scopes - and a Position -
1120/// the occurrence within the parameter list.
1121/// This class is inheritedly privately by different kinds of template
1122/// parameters and is not part of the Decl hierarchy. Just a facility.
1123class TemplateParmPosition {
1124protected:
1125 // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
1126 // position? Maybe?
1127 unsigned Depth;
1128 unsigned Position;
1129
1130 TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
1131
1132public:
1133 TemplateParmPosition() = delete;
1134
1135 /// Get the nesting depth of the template parameter.
1136 unsigned getDepth() const { return Depth; }
1137 void setDepth(unsigned D) { Depth = D; }
1138
1139 /// Get the position of the template parameter within its parameter list.
1140 unsigned getPosition() const { return Position; }
1141 void setPosition(unsigned P) { Position = P; }
1142
1143 /// Get the index of the template parameter within its parameter list.
1144 unsigned getIndex() const { return Position; }
1145};
1146
1147/// \brief Declaration of a template type parameter.
1148///
1149/// For example, "T" in
1150/// \code
1151/// template<typename T> class vector;
1152/// \endcode
1153class TemplateTypeParmDecl : public TypeDecl {
1154 /// Sema creates these on the stack during auto type deduction.
1155 friend class Sema;
1156
1157 /// \brief Whether this template type parameter was declaration with
1158 /// the 'typename' keyword.
1159 ///
1160 /// If false, it was declared with the 'class' keyword.
1161 bool Typename : 1;
1162
1163 /// \brief The default template argument, if any.
1164 using DefArgStorage =
1165 DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
1166 DefArgStorage DefaultArgument;
1167
1168 TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1169 SourceLocation IdLoc, IdentifierInfo *Id,
1170 bool Typename)
1171 : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename) {}
1172
1173public:
1174 static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
1175 SourceLocation KeyLoc,
1176 SourceLocation NameLoc,
1177 unsigned D, unsigned P,
1178 IdentifierInfo *Id, bool Typename,
1179 bool ParameterPack);
1180 static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1181 unsigned ID);
1182
1183 /// \brief Whether this template type parameter was declared with
1184 /// the 'typename' keyword.
1185 ///
1186 /// If not, it was declared with the 'class' keyword.
1187 bool wasDeclaredWithTypename() const { return Typename; }
1188
1189 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1190
1191 /// \brief Determine whether this template parameter has a default
1192 /// argument.
1193 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1194
1195 /// \brief Retrieve the default argument, if any.
1196 QualType getDefaultArgument() const {
1197 return DefaultArgument.get()->getType();
1198 }
1199
1200 /// \brief Retrieves the default argument's source information, if any.
1201 TypeSourceInfo *getDefaultArgumentInfo() const {
1202 return DefaultArgument.get();
1203 }
1204
1205 /// \brief Retrieves the location of the default argument declaration.
1206 SourceLocation getDefaultArgumentLoc() const;
1207
1208 /// \brief Determines whether the default argument was inherited
1209 /// from a previous declaration of this template.
1210 bool defaultArgumentWasInherited() const {
1211 return DefaultArgument.isInherited();
1212 }
1213
1214 /// \brief Set the default argument for this template parameter.
1215 void setDefaultArgument(TypeSourceInfo *DefArg) {
1216 DefaultArgument.set(DefArg);
1217 }
1218
1219 /// \brief Set that this default argument was inherited from another
1220 /// parameter.
1221 void setInheritedDefaultArgument(const ASTContext &C,
1222 TemplateTypeParmDecl *Prev) {
1223 DefaultArgument.setInherited(C, Prev);
1224 }
1225
1226 /// \brief Removes the default argument of this template parameter.
1227 void removeDefaultArgument() {
1228 DefaultArgument.clear();
1229 }
1230
1231 /// \brief Set whether this template type parameter was declared with
1232 /// the 'typename' or 'class' keyword.
1233 void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1234
1235 /// \brief Retrieve the depth of the template parameter.
1236 unsigned getDepth() const;
1237
1238 /// \brief Retrieve the index of the template parameter.
1239 unsigned getIndex() const;
1240
1241 /// \brief Returns whether this is a parameter pack.
1242 bool isParameterPack() const;
1243
1244 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1245
1246 // Implement isa/cast/dyncast/etc.
1247 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1248 static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1249};
1250
1251/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1252/// e.g., "Size" in
1253/// @code
1254/// template<int Size> class array { };
1255/// @endcode
1256class NonTypeTemplateParmDecl final
1257 : public DeclaratorDecl,
1258 protected TemplateParmPosition,
1259 private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1260 std::pair<QualType, TypeSourceInfo *>> {
1261 friend class ASTDeclReader;
1262 friend TrailingObjects;
1263
1264 /// \brief The default template argument, if any, and whether or not
1265 /// it was inherited.
1266 using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
1267 DefArgStorage DefaultArgument;
1268
1269 // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1270 // down here to save memory.
1271
1272 /// \brief Whether this non-type template parameter is a parameter pack.
1273 bool ParameterPack;
1274
1275 /// \brief Whether this non-type template parameter is an "expanded"
1276 /// parameter pack, meaning that its type is a pack expansion and we
1277 /// already know the set of types that expansion expands to.
1278 bool ExpandedParameterPack = false;
1279
1280 /// \brief The number of types in an expanded parameter pack.
1281 unsigned NumExpandedTypes = 0;
1282
1283 size_t numTrailingObjects(
1284 OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1285 return NumExpandedTypes;
1286 }
1287
1288 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1289 SourceLocation IdLoc, unsigned D, unsigned P,
1290 IdentifierInfo *Id, QualType T,
1291 bool ParameterPack, TypeSourceInfo *TInfo)
1292 : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1293 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1294
1295 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1296 SourceLocation IdLoc, unsigned D, unsigned P,
1297 IdentifierInfo *Id, QualType T,
1298 TypeSourceInfo *TInfo,
1299 ArrayRef<QualType> ExpandedTypes,
1300 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1301
1302public:
1303 static NonTypeTemplateParmDecl *
1304 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1305 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1306 QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1307
1308 static NonTypeTemplateParmDecl *
1309 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1310 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1311 QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
1312 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1313
1314 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1315 unsigned ID);
1316 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1317 unsigned ID,
1318 unsigned NumExpandedTypes);
1319
1320 using TemplateParmPosition::getDepth;
1321 using TemplateParmPosition::setDepth;
1322 using TemplateParmPosition::getPosition;
1323 using TemplateParmPosition::setPosition;
1324 using TemplateParmPosition::getIndex;
1325
1326 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1327
1328 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1329
1330 /// \brief Determine whether this template parameter has a default
1331 /// argument.
1332 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1333
1334 /// \brief Retrieve the default argument, if any.
1335 Expr *getDefaultArgument() const { return DefaultArgument.get(); }
1336
1337 /// \brief Retrieve the location of the default argument, if any.
1338 SourceLocation getDefaultArgumentLoc() const;
1339
1340 /// \brief Determines whether the default argument was inherited
1341 /// from a previous declaration of this template.
1342 bool defaultArgumentWasInherited() const {
1343 return DefaultArgument.isInherited();
1344 }
1345
1346 /// \brief Set the default argument for this template parameter, and
1347 /// whether that default argument was inherited from another
1348 /// declaration.
1349 void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
1350 void setInheritedDefaultArgument(const ASTContext &C,
1351 NonTypeTemplateParmDecl *Parm) {
1352 DefaultArgument.setInherited(C, Parm);
1353 }
1354
1355 /// \brief Removes the default argument of this template parameter.
1356 void removeDefaultArgument() { DefaultArgument.clear(); }
1357
1358 /// \brief Whether this parameter is a non-type template parameter pack.
1359 ///
1360 /// If the parameter is a parameter pack, the type may be a
1361 /// \c PackExpansionType. In the following example, the \c Dims parameter
1362 /// is a parameter pack (whose type is 'unsigned').
1363 ///
1364 /// \code
1365 /// template<typename T, unsigned ...Dims> struct multi_array;
1366 /// \endcode
1367 bool isParameterPack() const { return ParameterPack; }
1368
1369 /// \brief Whether this parameter pack is a pack expansion.
1370 ///
1371 /// A non-type template parameter pack is a pack expansion if its type
1372 /// contains an unexpanded parameter pack. In this case, we will have
1373 /// built a PackExpansionType wrapping the type.
1374 bool isPackExpansion() const {
1375 return ParameterPack && getType()->getAs<PackExpansionType>();
1376 }
1377
1378 /// \brief Whether this parameter is a non-type template parameter pack
1379 /// that has a known list of different types at different positions.
1380 ///
1381 /// A parameter pack is an expanded parameter pack when the original
1382 /// parameter pack's type was itself a pack expansion, and that expansion
1383 /// has already been expanded. For example, given:
1384 ///
1385 /// \code
1386 /// template<typename ...Types>
1387 /// struct X {
1388 /// template<Types ...Values>
1389 /// struct Y { /* ... */ };
1390 /// };
1391 /// \endcode
1392 ///
1393 /// The parameter pack \c Values has a \c PackExpansionType as its type,
1394 /// which expands \c Types. When \c Types is supplied with template arguments
1395 /// by instantiating \c X, the instantiation of \c Values becomes an
1396 /// expanded parameter pack. For example, instantiating
1397 /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1398 /// pack with expansion types \c int and \c unsigned int.
1399 ///
1400 /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1401 /// return the expansion types.
1402 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1403
1404 /// \brief Retrieves the number of expansion types in an expanded parameter
1405 /// pack.
1406 unsigned getNumExpansionTypes() const {
1407 assert(ExpandedParameterPack && "Not an expansion parameter pack")(static_cast <bool> (ExpandedParameterPack && "Not an expansion parameter pack"
) ? void (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1407, __extension__ __PRETTY_FUNCTION__))
;
1408 return NumExpandedTypes;
1409 }
1410
1411 /// \brief Retrieve a particular expansion type within an expanded parameter
1412 /// pack.
1413 QualType getExpansionType(unsigned I) const {
1414 assert(I < NumExpandedTypes && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedTypes &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1414, __extension__ __PRETTY_FUNCTION__))
;
1415 auto TypesAndInfos =
1416 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1417 return TypesAndInfos[I].first;
1418 }
1419
1420 /// \brief Retrieve a particular expansion type source info within an
1421 /// expanded parameter pack.
1422 TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1423 assert(I < NumExpandedTypes && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedTypes &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1423, __extension__ __PRETTY_FUNCTION__))
;
1424 auto TypesAndInfos =
1425 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1426 return TypesAndInfos[I].second;
1427 }
1428
1429 // Implement isa/cast/dyncast/etc.
1430 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1431 static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1432};
1433
1434/// TemplateTemplateParmDecl - Declares a template template parameter,
1435/// e.g., "T" in
1436/// @code
1437/// template <template <typename> class T> class container { };
1438/// @endcode
1439/// A template template parameter is a TemplateDecl because it defines the
1440/// name of a template and the template parameters allowable for substitution.
1441class TemplateTemplateParmDecl final
1442 : public TemplateDecl,
1443 protected TemplateParmPosition,
1444 private llvm::TrailingObjects<TemplateTemplateParmDecl,
1445 TemplateParameterList *> {
1446 /// \brief The default template argument, if any.
1447 using DefArgStorage =
1448 DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
1449 DefArgStorage DefaultArgument;
1450
1451 /// \brief Whether this parameter is a parameter pack.
1452 bool ParameterPack;
1453
1454 /// \brief Whether this template template parameter is an "expanded"
1455 /// parameter pack, meaning that it is a pack expansion and we
1456 /// already know the set of template parameters that expansion expands to.
1457 bool ExpandedParameterPack = false;
1458
1459 /// \brief The number of parameters in an expanded parameter pack.
1460 unsigned NumExpandedParams = 0;
1461
1462 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1463 unsigned D, unsigned P, bool ParameterPack,
1464 IdentifierInfo *Id, TemplateParameterList *Params)
1465 : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1466 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1467
1468 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1469 unsigned D, unsigned P,
1470 IdentifierInfo *Id, TemplateParameterList *Params,
1471 ArrayRef<TemplateParameterList *> Expansions);
1472
1473 void anchor() override;
1474
1475public:
1476 friend class ASTDeclReader;
1477 friend class ASTDeclWriter;
1478 friend TrailingObjects;
1479
1480 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1481 SourceLocation L, unsigned D,
1482 unsigned P, bool ParameterPack,
1483 IdentifierInfo *Id,
1484 TemplateParameterList *Params);
1485 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1486 SourceLocation L, unsigned D,
1487 unsigned P,
1488 IdentifierInfo *Id,
1489 TemplateParameterList *Params,
1490 ArrayRef<TemplateParameterList *> Expansions);
1491
1492 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1493 unsigned ID);
1494 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1495 unsigned ID,
1496 unsigned NumExpansions);
1497
1498 using TemplateParmPosition::getDepth;
1499 using TemplateParmPosition::setDepth;
1500 using TemplateParmPosition::getPosition;
1501 using TemplateParmPosition::setPosition;
1502 using TemplateParmPosition::getIndex;
1503
1504 /// \brief Whether this template template parameter is a template
1505 /// parameter pack.
1506 ///
1507 /// \code
1508 /// template<template <class T> ...MetaFunctions> struct Apply;
1509 /// \endcode
1510 bool isParameterPack() const { return ParameterPack; }
1511
1512 /// \brief Whether this parameter pack is a pack expansion.
1513 ///
1514 /// A template template parameter pack is a pack expansion if its template
1515 /// parameter list contains an unexpanded parameter pack.
1516 bool isPackExpansion() const {
1517 return ParameterPack &&
1518 getTemplateParameters()->containsUnexpandedParameterPack();
1519 }
1520
1521 /// \brief Whether this parameter is a template template parameter pack that
1522 /// has a known list of different template parameter lists at different
1523 /// positions.
1524 ///
1525 /// A parameter pack is an expanded parameter pack when the original parameter
1526 /// pack's template parameter list was itself a pack expansion, and that
1527 /// expansion has already been expanded. For exampe, given:
1528 ///
1529 /// \code
1530 /// template<typename...Types> struct Outer {
1531 /// template<template<Types> class...Templates> struct Inner;
1532 /// };
1533 /// \endcode
1534 ///
1535 /// The parameter pack \c Templates is a pack expansion, which expands the
1536 /// pack \c Types. When \c Types is supplied with template arguments by
1537 /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1538 /// parameter pack.
1539 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1540
1541 /// \brief Retrieves the number of expansion template parameters in
1542 /// an expanded parameter pack.
1543 unsigned getNumExpansionTemplateParameters() const {
1544 assert(ExpandedParameterPack && "Not an expansion parameter pack")(static_cast <bool> (ExpandedParameterPack && "Not an expansion parameter pack"
) ? void (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1544, __extension__ __PRETTY_FUNCTION__))
;
1545 return NumExpandedParams;
1546 }
1547
1548 /// \brief Retrieve a particular expansion type within an expanded parameter
1549 /// pack.
1550 TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1551 assert(I < NumExpandedParams && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedParams &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedParams && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1551, __extension__ __PRETTY_FUNCTION__))
;
1552 return getTrailingObjects<TemplateParameterList *>()[I];
1553 }
1554
1555 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1556
1557 /// \brief Determine whether this template parameter has a default
1558 /// argument.
1559 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1560
1561 /// \brief Retrieve the default argument, if any.
1562 const TemplateArgumentLoc &getDefaultArgument() const {
1563 static const TemplateArgumentLoc None;
1564 return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
1565 }
1566
1567 /// \brief Retrieve the location of the default argument, if any.
1568 SourceLocation getDefaultArgumentLoc() const;
1569
1570 /// \brief Determines whether the default argument was inherited
1571 /// from a previous declaration of this template.
1572 bool defaultArgumentWasInherited() const {
1573 return DefaultArgument.isInherited();
1574 }
1575
1576 /// \brief Set the default argument for this template parameter, and
1577 /// whether that default argument was inherited from another
1578 /// declaration.
1579 void setDefaultArgument(const ASTContext &C,
1580 const TemplateArgumentLoc &DefArg);
1581 void setInheritedDefaultArgument(const ASTContext &C,
1582 TemplateTemplateParmDecl *Prev) {
1583 DefaultArgument.setInherited(C, Prev);
1584 }
1585
1586 /// \brief Removes the default argument of this template parameter.
1587 void removeDefaultArgument() { DefaultArgument.clear(); }
1588
1589 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1590 SourceLocation End = getLocation();
1591 if (hasDefaultArgument() && !defaultArgumentWasInherited())
1592 End = getDefaultArgument().getSourceRange().getEnd();
1593 return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1594 }
1595
1596 // Implement isa/cast/dyncast/etc.
1597 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1598 static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1599};
1600
1601/// \brief Represents the builtin template declaration which is used to
1602/// implement __make_integer_seq and other builtin templates. It serves
1603/// no real purpose beyond existing as a place to hold template parameters.
1604class BuiltinTemplateDecl : public TemplateDecl {
1605 BuiltinTemplateKind BTK;
1606
1607 BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1608 DeclarationName Name, BuiltinTemplateKind BTK);
1609
1610 void anchor() override;
1611
1612public:
1613 // Implement isa/cast/dyncast support
1614 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1615 static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1616
1617 static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1618 DeclarationName Name,
1619 BuiltinTemplateKind BTK) {
1620 return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1621 }
1622
1623 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1624 return SourceRange();
1625 }
1626
1627 BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1628};
1629
1630/// \brief Represents a class template specialization, which refers to
1631/// a class template with a given set of template arguments.
1632///
1633/// Class template specializations represent both explicit
1634/// specialization of class templates, as in the example below, and
1635/// implicit instantiations of class templates.
1636///
1637/// \code
1638/// template<typename T> class array;
1639///
1640/// template<>
1641/// class array<bool> { }; // class template specialization array<bool>
1642/// \endcode
1643class ClassTemplateSpecializationDecl
1644 : public CXXRecordDecl, public llvm::FoldingSetNode {
1645 /// \brief Structure that stores information about a class template
1646 /// specialization that was instantiated from a class template partial
1647 /// specialization.
1648 struct SpecializedPartialSpecialization {
1649 /// \brief The class template partial specialization from which this
1650 /// class template specialization was instantiated.
1651 ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1652
1653 /// \brief The template argument list deduced for the class template
1654 /// partial specialization itself.
1655 const TemplateArgumentList *TemplateArgs;
1656 };
1657
1658 /// \brief The template that this specialization specializes
1659 llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1660 SpecializedTemplate;
1661
1662 /// \brief Further info for explicit template specialization/instantiation.
1663 struct ExplicitSpecializationInfo {
1664 /// \brief The type-as-written.
1665 TypeSourceInfo *TypeAsWritten = nullptr;
1666
1667 /// \brief The location of the extern keyword.
1668 SourceLocation ExternLoc;
1669
1670 /// \brief The location of the template keyword.
1671 SourceLocation TemplateKeywordLoc;
1672
1673 ExplicitSpecializationInfo() = default;
1674 };
1675
1676 /// \brief Further info for explicit template specialization/instantiation.
1677 /// Does not apply to implicit specializations.
1678 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
1679
1680 /// \brief The template arguments used to describe this specialization.
1681 const TemplateArgumentList *TemplateArgs;
1682
1683 /// \brief The point where this template was instantiated (if any)
1684 SourceLocation PointOfInstantiation;
1685
1686 /// \brief The kind of specialization this declaration refers to.
1687 /// Really a value of type TemplateSpecializationKind.
1688 unsigned SpecializationKind : 3;
1689
1690protected:
1691 ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1692 DeclContext *DC, SourceLocation StartLoc,
1693 SourceLocation IdLoc,
1694 ClassTemplateDecl *SpecializedTemplate,
1695 ArrayRef<TemplateArgument> Args,
1696 ClassTemplateSpecializationDecl *PrevDecl);
1697
1698 explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1699
1700public:
1701 friend class ASTDeclReader;
1702 friend class ASTDeclWriter;
1703
1704 static ClassTemplateSpecializationDecl *
1705 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1706 SourceLocation StartLoc, SourceLocation IdLoc,
1707 ClassTemplateDecl *SpecializedTemplate,
1708 ArrayRef<TemplateArgument> Args,
1709 ClassTemplateSpecializationDecl *PrevDecl);
1710 static ClassTemplateSpecializationDecl *
1711 CreateDeserialized(ASTContext &C, unsigned ID);
1712
1713 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1714 bool Qualified) const override;
1715
1716 // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1717 // different "most recent" declaration from this function for the same
1718 // declaration, because we don't override getMostRecentDeclImpl(). But
1719 // it's not clear that we should override that, because the most recent
1720 // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1721 ClassTemplateSpecializationDecl *getMostRecentDecl() {
1722 CXXRecordDecl *Recent = static_cast<CXXRecordDecl *>(
1723 this)->getMostRecentDecl();
1724 while (!isa<ClassTemplateSpecializationDecl>(Recent)) {
1725 // FIXME: Does injected class name need to be in the redeclarations chain?
1726 assert(Recent->isInjectedClassName() && Recent->getPreviousDecl())(static_cast <bool> (Recent->isInjectedClassName() &&
Recent->getPreviousDecl()) ? void (0) : __assert_fail ("Recent->isInjectedClassName() && Recent->getPreviousDecl()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1726, __extension__ __PRETTY_FUNCTION__))
;
1727 Recent = Recent->getPreviousDecl();
1728 }
1729 return cast<ClassTemplateSpecializationDecl>(Recent);
1730 }
1731
1732 /// \brief Retrieve the template that this specialization specializes.
1733 ClassTemplateDecl *getSpecializedTemplate() const;
1734
1735 /// \brief Retrieve the template arguments of the class template
1736 /// specialization.
1737 const TemplateArgumentList &getTemplateArgs() const {
1738 return *TemplateArgs;
1739 }
1740
1741 /// \brief Determine the kind of specialization that this
1742 /// declaration represents.
1743 TemplateSpecializationKind getSpecializationKind() const {
1744 return static_cast<TemplateSpecializationKind>(SpecializationKind);
1745 }
1746
1747 bool isExplicitSpecialization() const {
1748 return getSpecializationKind() == TSK_ExplicitSpecialization;
1749 }
1750
1751 /// \brief True if this declaration is an explicit specialization,
1752 /// explicit instantiation declaration, or explicit instantiation
1753 /// definition.
1754 bool isExplicitInstantiationOrSpecialization() const {
1755 return isTemplateExplicitInstantiationOrSpecialization(
1756 getTemplateSpecializationKind());
1757 }
1758
1759 void setSpecializationKind(TemplateSpecializationKind TSK) {
1760 SpecializationKind = TSK;
1761 }
1762
1763 /// \brief Get the point of instantiation (if any), or null if none.
1764 SourceLocation getPointOfInstantiation() const {
1765 return PointOfInstantiation;
1766 }
1767
1768 void setPointOfInstantiation(SourceLocation Loc) {
1769 assert(Loc.isValid() && "point of instantiation must be valid!")(static_cast <bool> (Loc.isValid() && "point of instantiation must be valid!"
) ? void (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1769, __extension__ __PRETTY_FUNCTION__))
;
1770 PointOfInstantiation = Loc;
1771 }
1772
1773 /// \brief If this class template specialization is an instantiation of
1774 /// a template (rather than an explicit specialization), return the
1775 /// class template or class template partial specialization from which it
1776 /// was instantiated.
1777 llvm::PointerUnion<ClassTemplateDecl *,
1778 ClassTemplatePartialSpecializationDecl *>
1779 getInstantiatedFrom() const {
1780 if (!isTemplateInstantiation(getSpecializationKind()))
1781 return llvm::PointerUnion<ClassTemplateDecl *,
1782 ClassTemplatePartialSpecializationDecl *>();
1783
1784 return getSpecializedTemplateOrPartial();
1785 }
1786
1787 /// \brief Retrieve the class template or class template partial
1788 /// specialization which was specialized by this.
1789 llvm::PointerUnion<ClassTemplateDecl *,
1790 ClassTemplatePartialSpecializationDecl *>
1791 getSpecializedTemplateOrPartial() const {
1792 if (SpecializedPartialSpecialization *PartialSpec
1793 = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1794 return PartialSpec->PartialSpecialization;
1795
1796 return SpecializedTemplate.get<ClassTemplateDecl*>();
1797 }
1798
1799 /// \brief Retrieve the set of template arguments that should be used
1800 /// to instantiate members of the class template or class template partial
1801 /// specialization from which this class template specialization was
1802 /// instantiated.
1803 ///
1804 /// \returns For a class template specialization instantiated from the primary
1805 /// template, this function will return the same template arguments as
1806 /// getTemplateArgs(). For a class template specialization instantiated from
1807 /// a class template partial specialization, this function will return the
1808 /// deduced template arguments for the class template partial specialization
1809 /// itself.
1810 const TemplateArgumentList &getTemplateInstantiationArgs() const {
1811 if (SpecializedPartialSpecialization *PartialSpec
1812 = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1813 return *PartialSpec->TemplateArgs;
1814
1815 return getTemplateArgs();
1816 }
1817
1818 /// \brief Note that this class template specialization is actually an
1819 /// instantiation of the given class template partial specialization whose
1820 /// template arguments have been deduced.
1821 void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1822 const TemplateArgumentList *TemplateArgs) {
1823 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1824, __extension__ __PRETTY_FUNCTION__))
1824 "Already set to a class template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1824, __extension__ __PRETTY_FUNCTION__))
;
1825 SpecializedPartialSpecialization *PS
1826 = new (getASTContext()) SpecializedPartialSpecialization();
1827 PS->PartialSpecialization = PartialSpec;
1828 PS->TemplateArgs = TemplateArgs;
1829 SpecializedTemplate = PS;
1830 }
1831
1832 /// \brief Note that this class template specialization is an instantiation
1833 /// of the given class template.
1834 void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1835 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1836, __extension__ __PRETTY_FUNCTION__))
1836 "Previously set to a class template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 1836, __extension__ __PRETTY_FUNCTION__))
;
1837 SpecializedTemplate = TemplDecl;
1838 }
1839
1840 /// \brief Sets the type of this specialization as it was written by
1841 /// the user. This will be a class template specialization type.
1842 void setTypeAsWritten(TypeSourceInfo *T) {
1843 if (!ExplicitInfo)
1844 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1845 ExplicitInfo->TypeAsWritten = T;
1846 }
1847
1848 /// \brief Gets the type of this specialization as it was written by
1849 /// the user, if it was so written.
1850 TypeSourceInfo *getTypeAsWritten() const {
1851 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
1852 }
1853
1854 /// \brief Gets the location of the extern keyword, if present.
1855 SourceLocation getExternLoc() const {
1856 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1857 }
1858
1859 /// \brief Sets the location of the extern keyword.
1860 void setExternLoc(SourceLocation Loc) {
1861 if (!ExplicitInfo)
1862 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1863 ExplicitInfo->ExternLoc = Loc;
1864 }
1865
1866 /// \brief Sets the location of the template keyword.
1867 void setTemplateKeywordLoc(SourceLocation Loc) {
1868 if (!ExplicitInfo)
1869 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1870 ExplicitInfo->TemplateKeywordLoc = Loc;
1871 }
1872
1873 /// \brief Gets the location of the template keyword, if present.
1874 SourceLocation getTemplateKeywordLoc() const {
1875 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1876 }
1877
1878 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1879
1880 void Profile(llvm::FoldingSetNodeID &ID) const {
1881 Profile(ID, TemplateArgs->asArray(), getASTContext());
1882 }
1883
1884 static void
1885 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
1886 ASTContext &Context) {
1887 ID.AddInteger(TemplateArgs.size());
1888 for (const TemplateArgument &TemplateArg : TemplateArgs)
1889 TemplateArg.Profile(ID, Context);
1890 }
1891
1892 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1893
1894 static bool classofKind(Kind K) {
1895 return K >= firstClassTemplateSpecialization &&
1896 K <= lastClassTemplateSpecialization;
1897 }
1898};
1899
1900class ClassTemplatePartialSpecializationDecl
1901 : public ClassTemplateSpecializationDecl {
1902 /// \brief The list of template parameters
1903 TemplateParameterList* TemplateParams = nullptr;
1904
1905 /// \brief The source info for the template arguments as written.
1906 /// FIXME: redundant with TypeAsWritten?
1907 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
1908
1909 /// \brief The class template partial specialization from which this
1910 /// class template partial specialization was instantiated.
1911 ///
1912 /// The boolean value will be true to indicate that this class template
1913 /// partial specialization was specialized at this level.
1914 llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1915 InstantiatedFromMember;
1916
1917 ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1918 DeclContext *DC,
1919 SourceLocation StartLoc,
1920 SourceLocation IdLoc,
1921 TemplateParameterList *Params,
1922 ClassTemplateDecl *SpecializedTemplate,
1923 ArrayRef<TemplateArgument> Args,
1924 const ASTTemplateArgumentListInfo *ArgsAsWritten,
1925 ClassTemplatePartialSpecializationDecl *PrevDecl);
1926
1927 ClassTemplatePartialSpecializationDecl(ASTContext &C)
1928 : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
1929 InstantiatedFromMember(nullptr, false) {}
1930
1931 void anchor() override;
1932
1933public:
1934 friend class ASTDeclReader;
1935 friend class ASTDeclWriter;
1936
1937 static ClassTemplatePartialSpecializationDecl *
1938 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1939 SourceLocation StartLoc, SourceLocation IdLoc,
1940 TemplateParameterList *Params,
1941 ClassTemplateDecl *SpecializedTemplate,
1942 ArrayRef<TemplateArgument> Args,
1943 const TemplateArgumentListInfo &ArgInfos,
1944 QualType CanonInjectedType,
1945 ClassTemplatePartialSpecializationDecl *PrevDecl);
1946
1947 static ClassTemplatePartialSpecializationDecl *
1948 CreateDeserialized(ASTContext &C, unsigned ID);
1949
1950 ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
1951 return cast<ClassTemplatePartialSpecializationDecl>(
1952 static_cast<ClassTemplateSpecializationDecl *>(
1953 this)->getMostRecentDecl());
1954 }
1955
1956 /// Get the list of template parameters
1957 TemplateParameterList *getTemplateParameters() const {
1958 return TemplateParams;
1959 }
1960
1961 /// Get the template arguments as written.
1962 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
1963 return ArgsAsWritten;
1964 }
1965
1966 /// \brief Retrieve the member class template partial specialization from
1967 /// which this particular class template partial specialization was
1968 /// instantiated.
1969 ///
1970 /// \code
1971 /// template<typename T>
1972 /// struct Outer {
1973 /// template<typename U> struct Inner;
1974 /// template<typename U> struct Inner<U*> { }; // #1
1975 /// };
1976 ///
1977 /// Outer<float>::Inner<int*> ii;
1978 /// \endcode
1979 ///
1980 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1981 /// end up instantiating the partial specialization
1982 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
1983 /// template partial specialization \c Outer<T>::Inner<U*>. Given
1984 /// \c Outer<float>::Inner<U*>, this function would return
1985 /// \c Outer<T>::Inner<U*>.
1986 ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
1987 const ClassTemplatePartialSpecializationDecl *First =
1988 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1989 return First->InstantiatedFromMember.getPointer();
1990 }
1991 ClassTemplatePartialSpecializationDecl *
1992 getInstantiatedFromMemberTemplate() const {
1993 return getInstantiatedFromMember();
1994 }
1995
1996 void setInstantiatedFromMember(
1997 ClassTemplatePartialSpecializationDecl *PartialSpec) {
1998 ClassTemplatePartialSpecializationDecl *First =
1999 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2000 First->InstantiatedFromMember.setPointer(PartialSpec);
2001 }
2002
2003 /// \brief Determines whether this class template partial specialization
2004 /// template was a specialization of a member partial specialization.
2005 ///
2006 /// In the following example, the member template partial specialization
2007 /// \c X<int>::Inner<T*> is a member specialization.
2008 ///
2009 /// \code
2010 /// template<typename T>
2011 /// struct X {
2012 /// template<typename U> struct Inner;
2013 /// template<typename U> struct Inner<U*>;
2014 /// };
2015 ///
2016 /// template<> template<typename T>
2017 /// struct X<int>::Inner<T*> { /* ... */ };
2018 /// \endcode
2019 bool isMemberSpecialization() {
2020 ClassTemplatePartialSpecializationDecl *First =
2021 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2022 return First->InstantiatedFromMember.getInt();
2023 }
2024
2025 /// \brief Note that this member template is a specialization.
2026 void setMemberSpecialization() {
2027 ClassTemplatePartialSpecializationDecl *First =
2028 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2029 assert(First->InstantiatedFromMember.getPointer() &&(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2030, __extension__ __PRETTY_FUNCTION__))
2030 "Only member templates can be member template specializations")(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2030, __extension__ __PRETTY_FUNCTION__))
;
2031 return First->InstantiatedFromMember.setInt(true);
2032 }
2033
2034 /// Retrieves the injected specialization type for this partial
2035 /// specialization. This is not the same as the type-decl-type for
2036 /// this partial specialization, which is an InjectedClassNameType.
2037 QualType getInjectedSpecializationType() const {
2038 assert(getTypeForDecl() && "partial specialization has no type set!")(static_cast <bool> (getTypeForDecl() && "partial specialization has no type set!"
) ? void (0) : __assert_fail ("getTypeForDecl() && \"partial specialization has no type set!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2038, __extension__ __PRETTY_FUNCTION__))
;
2039 return cast<InjectedClassNameType>(getTypeForDecl())
2040 ->getInjectedSpecializationType();
2041 }
2042
2043 // FIXME: Add Profile support!
2044
2045 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2046
2047 static bool classofKind(Kind K) {
2048 return K == ClassTemplatePartialSpecialization;
2049 }
2050};
2051
2052/// Declaration of a class template.
2053class ClassTemplateDecl : public RedeclarableTemplateDecl {
2054protected:
2055 /// \brief Data that is common to all of the declarations of a given
2056 /// class template.
2057 struct Common : CommonBase {
2058 /// \brief The class template specializations for this class
2059 /// template, including explicit specializations and instantiations.
2060 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
2061
2062 /// \brief The class template partial specializations for this class
2063 /// template.
2064 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
2065 PartialSpecializations;
2066
2067 /// \brief The injected-class-name type for this class template.
2068 QualType InjectedClassNameType;
2069
2070 Common() = default;
2071 };
2072
2073 /// \brief Retrieve the set of specializations of this class template.
2074 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
2075 getSpecializations() const;
2076
2077 /// \brief Retrieve the set of partial specializations of this class
2078 /// template.
2079 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
2080 getPartialSpecializations();
2081
2082 ClassTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, ASTContext &C,
2083 DeclContext *DC, SourceLocation L, DeclarationName Name,
2084 TemplateParameterList *Params, NamedDecl *Decl)
2085 : RedeclarableTemplateDecl(CTDI, ClassTemplate, C, DC, L, Name, Params,
2086 Decl) {}
2087
2088 ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2089 DeclarationName Name, TemplateParameterList *Params,
2090 NamedDecl *Decl)
2091 : ClassTemplateDecl(nullptr, C, DC, L, Name, Params, Decl) {}
2092
2093 CommonBase *newCommon(ASTContext &C) const override;
2094
2095 Common *getCommonPtr() const {
2096 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2097 }
2098
2099public:
2100 friend class ASTDeclReader;
2101 friend class ASTDeclWriter;
2102
2103 /// \brief Load any lazily-loaded specializations from the external source.
2104 void LoadLazySpecializations() const;
2105
2106 /// \brief Get the underlying class declarations of the template.
2107 CXXRecordDecl *getTemplatedDecl() const {
2108 return static_cast<CXXRecordDecl *>(TemplatedDecl);
2109 }
2110
2111 /// \brief Returns whether this template declaration defines the primary
2112 /// class pattern.
2113 bool isThisDeclarationADefinition() const {
2114 return getTemplatedDecl()->isThisDeclarationADefinition();
2115 }
2116
2117 // FIXME: remove default argument for AssociatedConstraints
2118 /// \brief Create a class template node.
2119 static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2120 SourceLocation L,
2121 DeclarationName Name,
2122 TemplateParameterList *Params,
2123 NamedDecl *Decl,
2124 Expr *AssociatedConstraints = nullptr);
2125
2126 /// \brief Create an empty class template node.
2127 static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2128
2129 /// \brief Return the specialization with the provided arguments if it exists,
2130 /// otherwise return the insertion point.
2131 ClassTemplateSpecializationDecl *
2132 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2133
2134 /// \brief Insert the specified specialization knowing that it is not already
2135 /// in. InsertPos must be obtained from findSpecialization.
2136 void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2137
2138 ClassTemplateDecl *getCanonicalDecl() override {
2139 return cast<ClassTemplateDecl>(
2140 RedeclarableTemplateDecl::getCanonicalDecl());
2141 }
2142 const ClassTemplateDecl *getCanonicalDecl() const {
2143 return cast<ClassTemplateDecl>(
2144 RedeclarableTemplateDecl::getCanonicalDecl());
2145 }
2146
2147 /// \brief Retrieve the previous declaration of this class template, or
2148 /// nullptr if no such declaration exists.
2149 ClassTemplateDecl *getPreviousDecl() {
2150 return cast_or_null<ClassTemplateDecl>(
2151 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2152 }
2153 const ClassTemplateDecl *getPreviousDecl() const {
2154 return cast_or_null<ClassTemplateDecl>(
2155 static_cast<const RedeclarableTemplateDecl *>(
2156 this)->getPreviousDecl());
2157 }
2158
2159 ClassTemplateDecl *getMostRecentDecl() {
2160 return cast<ClassTemplateDecl>(
2161 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2162 }
2163 const ClassTemplateDecl *getMostRecentDecl() const {
2164 return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2165 }
2166
2167 ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2168 return cast_or_null<ClassTemplateDecl>(
2169 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2170 }
2171
2172 /// \brief Return the partial specialization with the provided arguments if it
2173 /// exists, otherwise return the insertion point.
2174 ClassTemplatePartialSpecializationDecl *
2175 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2176
2177 /// \brief Insert the specified partial specialization knowing that it is not
2178 /// already in. InsertPos must be obtained from findPartialSpecialization.
2179 void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2180 void *InsertPos);
2181
2182 /// \brief Retrieve the partial specializations as an ordered list.
2183 void getPartialSpecializations(
2184 SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
2185
2186 /// \brief Find a class template partial specialization with the given
2187 /// type T.
2188 ///
2189 /// \param T a dependent type that names a specialization of this class
2190 /// template.
2191 ///
2192 /// \returns the class template partial specialization that exactly matches
2193 /// the type \p T, or nullptr if no such partial specialization exists.
2194 ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2195
2196 /// \brief Find a class template partial specialization which was instantiated
2197 /// from the given member partial specialization.
2198 ///
2199 /// \param D a member class template partial specialization.
2200 ///
2201 /// \returns the class template partial specialization which was instantiated
2202 /// from the given member partial specialization, or nullptr if no such
2203 /// partial specialization exists.
2204 ClassTemplatePartialSpecializationDecl *
2205 findPartialSpecInstantiatedFromMember(
2206 ClassTemplatePartialSpecializationDecl *D);
2207
2208 /// \brief Retrieve the template specialization type of the
2209 /// injected-class-name for this class template.
2210 ///
2211 /// The injected-class-name for a class template \c X is \c
2212 /// X<template-args>, where \c template-args is formed from the
2213 /// template arguments that correspond to the template parameters of
2214 /// \c X. For example:
2215 ///
2216 /// \code
2217 /// template<typename T, int N>
2218 /// struct array {
2219 /// typedef array this_type; // "array" is equivalent to "array<T, N>"
2220 /// };
2221 /// \endcode
2222 QualType getInjectedClassNameSpecialization();
2223
2224 using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
2225 using spec_range = llvm::iterator_range<spec_iterator>;
2226
2227 spec_range specializations() const {
2228 return spec_range(spec_begin(), spec_end());
2229 }
2230
2231 spec_iterator spec_begin() const {
2232 return makeSpecIterator(getSpecializations(), false);
2233 }
2234
2235 spec_iterator spec_end() const {
2236 return makeSpecIterator(getSpecializations(), true);
2237 }
2238
2239 // Implement isa/cast/dyncast support
2240 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2241 static bool classofKind(Kind K) { return K == ClassTemplate; }
2242};
2243
2244/// \brief Declaration of a friend template.
2245///
2246/// For example:
2247/// \code
2248/// template \<typename T> class A {
2249/// friend class MyVector<T>; // not a friend template
2250/// template \<typename U> friend class B; // not a friend template
2251/// template \<typename U> friend class Foo<T>::Nested; // friend template
2252/// };
2253/// \endcode
2254///
2255/// \note This class is not currently in use. All of the above
2256/// will yield a FriendDecl, not a FriendTemplateDecl.
2257class FriendTemplateDecl : public Decl {
2258 virtual void anchor();
2259
2260public:
2261 using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
2262
2263private:
2264 // The number of template parameters; always non-zero.
2265 unsigned NumParams = 0;
2266
2267 // The parameter list.
2268 TemplateParameterList **Params = nullptr;
2269
2270 // The declaration that's a friend of this class.
2271 FriendUnion Friend;
2272
2273 // Location of the 'friend' specifier.
2274 SourceLocation FriendLoc;
2275
2276 FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2277 MutableArrayRef<TemplateParameterList *> Params,
2278 FriendUnion Friend, SourceLocation FriendLoc)
2279 : Decl(Decl::FriendTemplate, DC, Loc), NumParams(Params.size()),
2280 Params(Params.data()), Friend(Friend), FriendLoc(FriendLoc) {}
2281
2282 FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
2283
2284public:
2285 friend class ASTDeclReader;
2286
2287 static FriendTemplateDecl *
2288 Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
2289 MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
2290 SourceLocation FriendLoc);
2291
2292 static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2293
2294 /// If this friend declaration names a templated type (or
2295 /// a dependent member type of a templated type), return that
2296 /// type; otherwise return null.
2297 TypeSourceInfo *getFriendType() const {
2298 return Friend.dyn_cast<TypeSourceInfo*>();
2299 }
2300
2301 /// If this friend declaration names a templated function (or
2302 /// a member function of a templated type), return that type;
2303 /// otherwise return null.
2304 NamedDecl *getFriendDecl() const {
2305 return Friend.dyn_cast<NamedDecl*>();
2306 }
2307
2308 /// \brief Retrieves the location of the 'friend' keyword.
2309 SourceLocation getFriendLoc() const {
2310 return FriendLoc;
2311 }
2312
2313 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2314 assert(i <= NumParams)(static_cast <bool> (i <= NumParams) ? void (0) : __assert_fail
("i <= NumParams", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2314, __extension__ __PRETTY_FUNCTION__))
;
2315 return Params[i];
2316 }
2317
2318 unsigned getNumTemplateParameters() const {
2319 return NumParams;
2320 }
2321
2322 // Implement isa/cast/dyncast/etc.
2323 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2324 static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2325};
2326
2327/// \brief Declaration of an alias template.
2328///
2329/// For example:
2330/// \code
2331/// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2332/// \endcode
2333class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2334protected:
2335 using Common = CommonBase;
2336
2337 TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2338 DeclarationName Name, TemplateParameterList *Params,
2339 NamedDecl *Decl)
2340 : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2341 Decl) {}
2342
2343 CommonBase *newCommon(ASTContext &C) const override;
2344
2345 Common *getCommonPtr() {
2346 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2347 }
2348
2349public:
2350 friend class ASTDeclReader;
2351 friend class ASTDeclWriter;
2352
2353 /// Get the underlying function declaration of the template.
2354 TypeAliasDecl *getTemplatedDecl() const {
2355 return static_cast<TypeAliasDecl *>(TemplatedDecl);
2356 }
2357
2358
2359 TypeAliasTemplateDecl *getCanonicalDecl() override {
2360 return cast<TypeAliasTemplateDecl>(
2361 RedeclarableTemplateDecl::getCanonicalDecl());
2362 }
2363 const TypeAliasTemplateDecl *getCanonicalDecl() const {
2364 return cast<TypeAliasTemplateDecl>(
2365 RedeclarableTemplateDecl::getCanonicalDecl());
2366 }
2367
2368 /// \brief Retrieve the previous declaration of this function template, or
2369 /// nullptr if no such declaration exists.
2370 TypeAliasTemplateDecl *getPreviousDecl() {
2371 return cast_or_null<TypeAliasTemplateDecl>(
2372 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2373 }
2374 const TypeAliasTemplateDecl *getPreviousDecl() const {
2375 return cast_or_null<TypeAliasTemplateDecl>(
2376 static_cast<const RedeclarableTemplateDecl *>(
2377 this)->getPreviousDecl());
2378 }
2379
2380 TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2381 return cast_or_null<TypeAliasTemplateDecl>(
2382 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2383 }
2384
2385 /// \brief Create a function template node.
2386 static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2387 SourceLocation L,
2388 DeclarationName Name,
2389 TemplateParameterList *Params,
2390 NamedDecl *Decl);
2391
2392 /// \brief Create an empty alias template node.
2393 static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2394
2395 // Implement isa/cast/dyncast support
2396 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2397 static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2398};
2399
2400/// \brief Declaration of a function specialization at template class scope.
2401///
2402/// This is a non-standard extension needed to support MSVC.
2403///
2404/// For example:
2405/// \code
2406/// template <class T>
2407/// class A {
2408/// template <class U> void foo(U a) { }
2409/// template<> void foo(int a) { }
2410/// }
2411/// \endcode
2412///
2413/// "template<> foo(int a)" will be saved in Specialization as a normal
2414/// CXXMethodDecl. Then during an instantiation of class A, it will be
2415/// transformed into an actual function specialization.
2416class ClassScopeFunctionSpecializationDecl : public Decl {
2417 CXXMethodDecl *Specialization;
2418 bool HasExplicitTemplateArgs;
2419 TemplateArgumentListInfo TemplateArgs;
2420
2421 ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
2422 CXXMethodDecl *FD, bool Args,
2423 TemplateArgumentListInfo TemplArgs)
2424 : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2425 Specialization(FD), HasExplicitTemplateArgs(Args),
2426 TemplateArgs(std::move(TemplArgs)) {}
2427
2428 ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2429 : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2430
2431 virtual void anchor();
2432
2433public:
2434 friend class ASTDeclReader;
2435 friend class ASTDeclWriter;
2436
2437 CXXMethodDecl *getSpecialization() const { return Specialization; }
2438 bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
2439 const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
2440
2441 static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
2442 DeclContext *DC,
2443 SourceLocation Loc,
2444 CXXMethodDecl *FD,
2445 bool HasExplicitTemplateArgs,
2446 TemplateArgumentListInfo TemplateArgs) {
2447 return new (C, DC) ClassScopeFunctionSpecializationDecl(
2448 DC, Loc, FD, HasExplicitTemplateArgs, std::move(TemplateArgs));
2449 }
2450
2451 static ClassScopeFunctionSpecializationDecl *
2452 CreateDeserialized(ASTContext &Context, unsigned ID);
2453
2454 // Implement isa/cast/dyncast/etc.
2455 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2456
2457 static bool classofKind(Kind K) {
2458 return K == Decl::ClassScopeFunctionSpecialization;
2459 }
2460};
2461
2462/// Implementation of inline functions that require the template declarations
2463inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2464 : Function(FTD) {}
2465
2466/// \brief Represents a variable template specialization, which refers to
2467/// a variable template with a given set of template arguments.
2468///
2469/// Variable template specializations represent both explicit
2470/// specializations of variable templates, as in the example below, and
2471/// implicit instantiations of variable templates.
2472///
2473/// \code
2474/// template<typename T> constexpr T pi = T(3.1415926535897932385);
2475///
2476/// template<>
2477/// constexpr float pi<float>; // variable template specialization pi<float>
2478/// \endcode
2479class VarTemplateSpecializationDecl : public VarDecl,
2480 public llvm::FoldingSetNode {
2481
2482 /// \brief Structure that stores information about a variable template
2483 /// specialization that was instantiated from a variable template partial
2484 /// specialization.
2485 struct SpecializedPartialSpecialization {
2486 /// \brief The variable template partial specialization from which this
2487 /// variable template specialization was instantiated.
2488 VarTemplatePartialSpecializationDecl *PartialSpecialization;
2489
2490 /// \brief The template argument list deduced for the variable template
2491 /// partial specialization itself.
2492 const TemplateArgumentList *TemplateArgs;
2493 };
2494
2495 /// \brief The template that this specialization specializes.
2496 llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2497 SpecializedTemplate;
2498
2499 /// \brief Further info for explicit template specialization/instantiation.
2500 struct ExplicitSpecializationInfo {
2501 /// \brief The type-as-written.
2502 TypeSourceInfo *TypeAsWritten = nullptr;
2503
2504 /// \brief The location of the extern keyword.
2505 SourceLocation ExternLoc;
2506
2507 /// \brief The location of the template keyword.
2508 SourceLocation TemplateKeywordLoc;
2509
2510 ExplicitSpecializationInfo() = default;
2511 };
2512
2513 /// \brief Further info for explicit template specialization/instantiation.
2514 /// Does not apply to implicit specializations.
2515 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
2516
2517 /// \brief The template arguments used to describe this specialization.
2518 const TemplateArgumentList *TemplateArgs;
2519 TemplateArgumentListInfo TemplateArgsInfo;
2520
2521 /// \brief The point where this template was instantiated (if any).
2522 SourceLocation PointOfInstantiation;
2523
2524 /// \brief The kind of specialization this declaration refers to.
2525 /// Really a value of type TemplateSpecializationKind.
2526 unsigned SpecializationKind : 3;
2527
2528 /// \brief Whether this declaration is a complete definition of the
2529 /// variable template specialization. We can't otherwise tell apart
2530 /// an instantiated declaration from an instantiated definition with
2531 /// no initializer.
2532 unsigned IsCompleteDefinition : 1;
2533
2534protected:
2535 VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2536 SourceLocation StartLoc, SourceLocation IdLoc,
2537 VarTemplateDecl *SpecializedTemplate,
2538 QualType T, TypeSourceInfo *TInfo,
2539 StorageClass S,
2540 ArrayRef<TemplateArgument> Args);
2541
2542 explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2543
2544public:
2545 friend class ASTDeclReader;
2546 friend class ASTDeclWriter;
2547 friend class VarDecl;
2548
2549 static VarTemplateSpecializationDecl *
2550 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2551 SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2552 TypeSourceInfo *TInfo, StorageClass S,
2553 ArrayRef<TemplateArgument> Args);
2554 static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2555 unsigned ID);
2556
2557 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2558 bool Qualified) const override;
2559
2560 VarTemplateSpecializationDecl *getMostRecentDecl() {
2561 VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2562 return cast<VarTemplateSpecializationDecl>(Recent);
2563 }
2564
2565 /// \brief Retrieve the template that this specialization specializes.
2566 VarTemplateDecl *getSpecializedTemplate() const;
2567
2568 /// \brief Retrieve the template arguments of the variable template
2569 /// specialization.
2570 const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2571
2572 // TODO: Always set this when creating the new specialization?
2573 void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
2574
2575 const TemplateArgumentListInfo &getTemplateArgsInfo() const {
2576 return TemplateArgsInfo;
2577 }
2578
2579 /// \brief Determine the kind of specialization that this
2580 /// declaration represents.
2581 TemplateSpecializationKind getSpecializationKind() const {
2582 return static_cast<TemplateSpecializationKind>(SpecializationKind);
2583 }
2584
2585 bool isExplicitSpecialization() const {
2586 return getSpecializationKind() == TSK_ExplicitSpecialization;
2587 }
2588
2589 /// \brief True if this declaration is an explicit specialization,
2590 /// explicit instantiation declaration, or explicit instantiation
2591 /// definition.
2592 bool isExplicitInstantiationOrSpecialization() const {
2593 return isTemplateExplicitInstantiationOrSpecialization(
2594 getTemplateSpecializationKind());
2595 }
2596
2597 void setSpecializationKind(TemplateSpecializationKind TSK) {
2598 SpecializationKind = TSK;
2599 }
2600
2601 /// \brief Get the point of instantiation (if any), or null if none.
2602 SourceLocation getPointOfInstantiation() const {
2603 return PointOfInstantiation;
2604 }
2605
2606 void setPointOfInstantiation(SourceLocation Loc) {
2607 assert(Loc.isValid() && "point of instantiation must be valid!")(static_cast <bool> (Loc.isValid() && "point of instantiation must be valid!"
) ? void (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2607, __extension__ __PRETTY_FUNCTION__))
;
2608 PointOfInstantiation = Loc;
2609 }
2610
2611 void setCompleteDefinition() { IsCompleteDefinition = true; }
2612
2613 /// \brief If this variable template specialization is an instantiation of
2614 /// a template (rather than an explicit specialization), return the
2615 /// variable template or variable template partial specialization from which
2616 /// it was instantiated.
2617 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2618 getInstantiatedFrom() const {
2619 if (!isTemplateInstantiation(getSpecializationKind()))
2620 return llvm::PointerUnion<VarTemplateDecl *,
2621 VarTemplatePartialSpecializationDecl *>();
2622
2623 return getSpecializedTemplateOrPartial();
2624 }
2625
2626 /// \brief Retrieve the variable template or variable template partial
2627 /// specialization which was specialized by this.
2628 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2629 getSpecializedTemplateOrPartial() const {
2630 if (SpecializedPartialSpecialization *PartialSpec =
2631 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2632 return PartialSpec->PartialSpecialization;
2633
2634 return SpecializedTemplate.get<VarTemplateDecl *>();
2635 }
2636
2637 /// \brief Retrieve the set of template arguments that should be used
2638 /// to instantiate the initializer of the variable template or variable
2639 /// template partial specialization from which this variable template
2640 /// specialization was instantiated.
2641 ///
2642 /// \returns For a variable template specialization instantiated from the
2643 /// primary template, this function will return the same template arguments
2644 /// as getTemplateArgs(). For a variable template specialization instantiated
2645 /// from a variable template partial specialization, this function will the
2646 /// return deduced template arguments for the variable template partial
2647 /// specialization itself.
2648 const TemplateArgumentList &getTemplateInstantiationArgs() const {
2649 if (SpecializedPartialSpecialization *PartialSpec =
2650 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2651 return *PartialSpec->TemplateArgs;
2652
2653 return getTemplateArgs();
2654 }
2655
2656 /// \brief Note that this variable template specialization is actually an
2657 /// instantiation of the given variable template partial specialization whose
2658 /// template arguments have been deduced.
2659 void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2660 const TemplateArgumentList *TemplateArgs) {
2661 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2662, __extension__ __PRETTY_FUNCTION__))
2662 "Already set to a variable template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2662, __extension__ __PRETTY_FUNCTION__))
;
2663 SpecializedPartialSpecialization *PS =
35
'PS' initialized to a null pointer value
2664 new (getASTContext()) SpecializedPartialSpecialization();
2665 PS->PartialSpecialization = PartialSpec;
36
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')
2666 PS->TemplateArgs = TemplateArgs;
2667 SpecializedTemplate = PS;
2668 }
2669
2670 /// \brief Note that this variable template specialization is an instantiation
2671 /// of the given variable template.
2672 void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2673 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2674, __extension__ __PRETTY_FUNCTION__))
2674 "Previously set to a variable template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2674, __extension__ __PRETTY_FUNCTION__))
;
2675 SpecializedTemplate = TemplDecl;
2676 }
2677
2678 /// \brief Sets the type of this specialization as it was written by
2679 /// the user.
2680 void setTypeAsWritten(TypeSourceInfo *T) {
2681 if (!ExplicitInfo)
2682 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2683 ExplicitInfo->TypeAsWritten = T;
2684 }
2685
2686 /// \brief Gets the type of this specialization as it was written by
2687 /// the user, if it was so written.
2688 TypeSourceInfo *getTypeAsWritten() const {
2689 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
2690 }
2691
2692 /// \brief Gets the location of the extern keyword, if present.
2693 SourceLocation getExternLoc() const {
2694 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
2695 }
2696
2697 /// \brief Sets the location of the extern keyword.
2698 void setExternLoc(SourceLocation Loc) {
2699 if (!ExplicitInfo)
2700 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2701 ExplicitInfo->ExternLoc = Loc;
2702 }
2703
2704 /// \brief Sets the location of the template keyword.
2705 void setTemplateKeywordLoc(SourceLocation Loc) {
2706 if (!ExplicitInfo)
2707 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2708 ExplicitInfo->TemplateKeywordLoc = Loc;
2709 }
2710
2711 /// \brief Gets the location of the template keyword, if present.
2712 SourceLocation getTemplateKeywordLoc() const {
2713 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
2714 }
2715
2716 void Profile(llvm::FoldingSetNodeID &ID) const {
2717 Profile(ID, TemplateArgs->asArray(), getASTContext());
2718 }
2719
2720 static void Profile(llvm::FoldingSetNodeID &ID,
2721 ArrayRef<TemplateArgument> TemplateArgs,
2722 ASTContext &Context) {
2723 ID.AddInteger(TemplateArgs.size());
2724 for (const TemplateArgument &TemplateArg : TemplateArgs)
2725 TemplateArg.Profile(ID, Context);
2726 }
2727
2728 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2729
2730 static bool classofKind(Kind K) {
2731 return K >= firstVarTemplateSpecialization &&
2732 K <= lastVarTemplateSpecialization;
2733 }
2734};
2735
2736class VarTemplatePartialSpecializationDecl
2737 : public VarTemplateSpecializationDecl {
2738 /// \brief The list of template parameters
2739 TemplateParameterList *TemplateParams = nullptr;
2740
2741 /// \brief The source info for the template arguments as written.
2742 /// FIXME: redundant with TypeAsWritten?
2743 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2744
2745 /// \brief The variable template partial specialization from which this
2746 /// variable template partial specialization was instantiated.
2747 ///
2748 /// The boolean value will be true to indicate that this variable template
2749 /// partial specialization was specialized at this level.
2750 llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
2751 InstantiatedFromMember;
2752
2753 VarTemplatePartialSpecializationDecl(
2754 ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2755 SourceLocation IdLoc, TemplateParameterList *Params,
2756 VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
2757 StorageClass S, ArrayRef<TemplateArgument> Args,
2758 const ASTTemplateArgumentListInfo *ArgInfos);
2759
2760 VarTemplatePartialSpecializationDecl(ASTContext &Context)
2761 : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization,
2762 Context),
2763 InstantiatedFromMember(nullptr, false) {}
2764
2765 void anchor() override;
2766
2767public:
2768 friend class ASTDeclReader;
2769 friend class ASTDeclWriter;
2770
2771 static VarTemplatePartialSpecializationDecl *
2772 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2773 SourceLocation IdLoc, TemplateParameterList *Params,
2774 VarTemplateDecl *SpecializedTemplate, QualType T,
2775 TypeSourceInfo *TInfo, StorageClass S, ArrayRef<TemplateArgument> Args,
2776 const TemplateArgumentListInfo &ArgInfos);
2777
2778 static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
2779 unsigned ID);
2780
2781 VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
2782 return cast<VarTemplatePartialSpecializationDecl>(
2783 static_cast<VarTemplateSpecializationDecl *>(
2784 this)->getMostRecentDecl());
2785 }
2786
2787 /// Get the list of template parameters
2788 TemplateParameterList *getTemplateParameters() const {
2789 return TemplateParams;
2790 }
2791
2792 /// Get the template arguments as written.
2793 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2794 return ArgsAsWritten;
2795 }
2796
2797 /// \brief Retrieve the member variable template partial specialization from
2798 /// which this particular variable template partial specialization was
2799 /// instantiated.
2800 ///
2801 /// \code
2802 /// template<typename T>
2803 /// struct Outer {
2804 /// template<typename U> U Inner;
2805 /// template<typename U> U* Inner<U*> = (U*)(0); // #1
2806 /// };
2807 ///
2808 /// template int* Outer<float>::Inner<int*>;
2809 /// \endcode
2810 ///
2811 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2812 /// end up instantiating the partial specialization
2813 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
2814 /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
2815 /// \c Outer<float>::Inner<U*>, this function would return
2816 /// \c Outer<T>::Inner<U*>.
2817 VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2818 const VarTemplatePartialSpecializationDecl *First =
2819 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2820 return First->InstantiatedFromMember.getPointer();
2821 }
2822
2823 void
2824 setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
2825 VarTemplatePartialSpecializationDecl *First =
2826 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2827 First->InstantiatedFromMember.setPointer(PartialSpec);
2828 }
2829
2830 /// \brief Determines whether this variable template partial specialization
2831 /// was a specialization of a member partial specialization.
2832 ///
2833 /// In the following example, the member template partial specialization
2834 /// \c X<int>::Inner<T*> is a member specialization.
2835 ///
2836 /// \code
2837 /// template<typename T>
2838 /// struct X {
2839 /// template<typename U> U Inner;
2840 /// template<typename U> U* Inner<U*> = (U*)(0);
2841 /// };
2842 ///
2843 /// template<> template<typename T>
2844 /// U* X<int>::Inner<T*> = (T*)(0) + 1;
2845 /// \endcode
2846 bool isMemberSpecialization() {
2847 VarTemplatePartialSpecializationDecl *First =
2848 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2849 return First->InstantiatedFromMember.getInt();
2850 }
2851
2852 /// \brief Note that this member template is a specialization.
2853 void setMemberSpecialization() {
2854 VarTemplatePartialSpecializationDecl *First =
2855 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2856 assert(First->InstantiatedFromMember.getPointer() &&(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2857, __extension__ __PRETTY_FUNCTION__))
2857 "Only member templates can be member template specializations")(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/AST/DeclTemplate.h"
, 2857, __extension__ __PRETTY_FUNCTION__))
;
2858 return First->InstantiatedFromMember.setInt(true);
2859 }
2860
2861 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2862
2863 static bool classofKind(Kind K) {
2864 return K == VarTemplatePartialSpecialization;
2865 }
2866};
2867
2868/// Declaration of a variable template.
2869class VarTemplateDecl : public RedeclarableTemplateDecl {
2870protected:
2871 /// \brief Data that is common to all of the declarations of a given
2872 /// variable template.
2873 struct Common : CommonBase {
2874 /// \brief The variable template specializations for this variable
2875 /// template, including explicit specializations and instantiations.
2876 llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
2877
2878 /// \brief The variable template partial specializations for this variable
2879 /// template.
2880 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
2881 PartialSpecializations;
2882
2883 Common() = default;
2884 };
2885
2886 /// \brief Retrieve the set of specializations of this variable template.
2887 llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
2888 getSpecializations() const;
2889
2890 /// \brief Retrieve the set of partial specializations of this class
2891 /// template.
2892 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
2893 getPartialSpecializations();
2894
2895 VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2896 DeclarationName Name, TemplateParameterList *Params,
2897 NamedDecl *Decl)
2898 : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
2899
2900 CommonBase *newCommon(ASTContext &C) const override;
2901
2902 Common *getCommonPtr() const {
2903 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2904 }
2905
2906public:
2907 friend class ASTDeclReader;
2908 friend class ASTDeclWriter;
2909
2910 /// \brief Load any lazily-loaded specializations from the external source.
2911 void LoadLazySpecializations() const;
2912
2913 /// \brief Get the underlying variable declarations of the template.
2914 VarDecl *getTemplatedDecl() const {
2915 return static_cast<VarDecl *>(TemplatedDecl);
2916 }
2917
2918 /// \brief Returns whether this template declaration defines the primary
2919 /// variable pattern.
2920 bool isThisDeclarationADefinition() const {
2921 return getTemplatedDecl()->isThisDeclarationADefinition();
2922 }
2923
2924 VarTemplateDecl *getDefinition();
2925
2926 /// \brief Create a variable template node.
2927 static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2928 SourceLocation L, DeclarationName Name,
2929 TemplateParameterList *Params,
2930 VarDecl *Decl);
2931
2932 /// \brief Create an empty variable template node.
2933 static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2934
2935 /// \brief Return the specialization with the provided arguments if it exists,
2936 /// otherwise return the insertion point.
2937 VarTemplateSpecializationDecl *
2938 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2939
2940 /// \brief Insert the specified specialization knowing that it is not already
2941 /// in. InsertPos must be obtained from findSpecialization.
2942 void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
2943
2944 VarTemplateDecl *getCanonicalDecl() override {
2945 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2946 }
2947 const VarTemplateDecl *getCanonicalDecl() const {
2948 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2949 }
2950
2951 /// \brief Retrieve the previous declaration of this variable template, or
2952 /// nullptr if no such declaration exists.
2953 VarTemplateDecl *getPreviousDecl() {
2954 return cast_or_null<VarTemplateDecl>(
2955 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2956 }
2957 const VarTemplateDecl *getPreviousDecl() const {
2958 return cast_or_null<VarTemplateDecl>(
2959 static_cast<const RedeclarableTemplateDecl *>(
2960 this)->getPreviousDecl());
2961 }
2962
2963 VarTemplateDecl *getMostRecentDecl() {
2964 return cast<VarTemplateDecl>(
2965 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2966 }
2967 const VarTemplateDecl *getMostRecentDecl() const {
2968 return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
2969 }
2970
2971 VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
2972 return cast_or_null<VarTemplateDecl>(
2973 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2974 }
2975
2976 /// \brief Return the partial specialization with the provided arguments if it
2977 /// exists, otherwise return the insertion point.
2978 VarTemplatePartialSpecializationDecl *
2979 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2980
2981 /// \brief Insert the specified partial specialization knowing that it is not
2982 /// already in. InsertPos must be obtained from findPartialSpecialization.
2983 void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
2984 void *InsertPos);
2985
2986 /// \brief Retrieve the partial specializations as an ordered list.
2987 void getPartialSpecializations(
2988 SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
2989
2990 /// \brief Find a variable template partial specialization which was
2991 /// instantiated
2992 /// from the given member partial specialization.
2993 ///
2994 /// \param D a member variable template partial specialization.
2995 ///
2996 /// \returns the variable template partial specialization which was
2997 /// instantiated
2998 /// from the given member partial specialization, or nullptr if no such
2999 /// partial specialization exists.
3000 VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
3001 VarTemplatePartialSpecializationDecl *D);
3002
3003 using spec_iterator = SpecIterator<VarTemplateSpecializationDecl>;
3004 using spec_range = llvm::iterator_range<spec_iterator>;
3005
3006 spec_range specializations() const {
3007 return spec_range(spec_begin(), spec_end());
3008 }
3009
3010 spec_iterator spec_begin() const {
3011 return makeSpecIterator(getSpecializations(), false);
3012 }
3013
3014 spec_iterator spec_end() const {
3015 return makeSpecIterator(getSpecializations(), true);
3016 }
3017
3018 // Implement isa/cast/dyncast support
3019 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3020 static bool classofKind(Kind K) { return K == VarTemplate; }
3021};
3022
3023inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
3024 if (auto *PD = P.dyn_cast<TemplateTypeParmDecl*>())
3025 return PD;
3026 if (auto *PD = P.dyn_cast<NonTypeTemplateParmDecl*>())
3027 return PD;
3028 return P.get<TemplateTemplateParmDecl*>();
3029}
3030
3031inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
3032 auto *TD = dyn_cast<TemplateDecl>(D);
3033 return TD && (isa<ClassTemplateDecl>(TD) ||
3034 isa<ClassTemplatePartialSpecializationDecl>(TD) ||
3035 isa<TypeAliasTemplateDecl>(TD) ||
3036 isa<TemplateTemplateParmDecl>(TD))
3037 ? TD
3038 : nullptr;
3039}
3040
3041} // namespace clang
3042
3043#endif // LLVM_CLANG_AST_DECLTEMPLATE_H