Bug Summary

File:tools/clang/lib/Sema/SemaTemplate.cpp
Warning:line 1845, column 33
Access to field 'TypeAsWritten' results in a dereference of a null pointer (loaded from field 'ExplicitInfo')

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~svn326246/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326246/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326246/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326246/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~svn326246/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-02-28-041547-14988-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326246/tools/clang/lib/Sema/SemaTemplate.cpp

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

/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h

1//===- ASTContext.h - Context to hold long-lived AST nodes ------*- 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 clang::ASTContext interface.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
16#define LLVM_CLANG_AST_ASTCONTEXT_H
17
18#include "clang/AST/ASTTypeTraits.h"
19#include "clang/AST/CanonicalType.h"
20#include "clang/AST/CommentCommandTraits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/ExternalASTSource.h"
25#include "clang/AST/NestedNameSpecifier.h"
26#include "clang/AST/PrettyPrinter.h"
27#include "clang/AST/RawCommentList.h"
28#include "clang/AST/TemplateBase.h"
29#include "clang/AST/TemplateName.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/AddressSpaces.h"
32#include "clang/Basic/IdentifierTable.h"
33#include "clang/Basic/LLVM.h"
34#include "clang/Basic/LangOptions.h"
35#include "clang/Basic/Linkage.h"
36#include "clang/Basic/OperatorKinds.h"
37#include "clang/Basic/PartialDiagnostic.h"
38#include "clang/Basic/SanitizerBlacklist.h"
39#include "clang/Basic/SourceLocation.h"
40#include "clang/Basic/Specifiers.h"
41#include "clang/Basic/TargetInfo.h"
42#include "clang/Basic/XRayLists.h"
43#include "llvm/ADT/APSInt.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/FoldingSet.h"
47#include "llvm/ADT/IntrusiveRefCntPtr.h"
48#include "llvm/ADT/MapVector.h"
49#include "llvm/ADT/None.h"
50#include "llvm/ADT/Optional.h"
51#include "llvm/ADT/PointerIntPair.h"
52#include "llvm/ADT/PointerUnion.h"
53#include "llvm/ADT/SmallVector.h"
54#include "llvm/ADT/StringMap.h"
55#include "llvm/ADT/StringRef.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include "llvm/ADT/Triple.h"
58#include "llvm/ADT/iterator_range.h"
59#include "llvm/Support/AlignOf.h"
60#include "llvm/Support/Allocator.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/Compiler.h"
63#include <cassert>
64#include <cstddef>
65#include <cstdint>
66#include <iterator>
67#include <memory>
68#include <string>
69#include <type_traits>
70#include <utility>
71#include <vector>
72
73namespace llvm {
74
75struct fltSemantics;
76
77} // namespace llvm
78
79namespace clang {
80
81class APValue;
82class ASTMutationListener;
83class ASTRecordLayout;
84class AtomicExpr;
85class BlockExpr;
86class BuiltinTemplateDecl;
87class CharUnits;
88class CXXABI;
89class CXXConstructorDecl;
90class CXXMethodDecl;
91class CXXRecordDecl;
92class DiagnosticsEngine;
93class Expr;
94class MangleContext;
95class MangleNumberingContext;
96class MaterializeTemporaryExpr;
97class MemberSpecializationInfo;
98class Module;
99class ObjCCategoryDecl;
100class ObjCCategoryImplDecl;
101class ObjCContainerDecl;
102class ObjCImplDecl;
103class ObjCImplementationDecl;
104class ObjCInterfaceDecl;
105class ObjCIvarDecl;
106class ObjCMethodDecl;
107class ObjCPropertyDecl;
108class ObjCPropertyImplDecl;
109class ObjCProtocolDecl;
110class ObjCTypeParamDecl;
111class Preprocessor;
112class Stmt;
113class StoredDeclsMap;
114class TemplateDecl;
115class TemplateParameterList;
116class TemplateTemplateParmDecl;
117class TemplateTypeParmDecl;
118class UnresolvedSetIterator;
119class UsingShadowDecl;
120class VarTemplateDecl;
121class VTableContextBase;
122
123namespace Builtin {
124
125class Context;
126
127} // namespace Builtin
128
129enum BuiltinTemplateKind : int;
130
131namespace comments {
132
133class FullComment;
134
135} // namespace comments
136
137struct TypeInfo {
138 uint64_t Width = 0;
139 unsigned Align = 0;
140 bool AlignIsRequired : 1;
141
142 TypeInfo() : AlignIsRequired(false) {}
143 TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
144 : Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
145};
146
147/// \brief Holds long-lived AST nodes (such as types and decls) that can be
148/// referred to throughout the semantic analysis of a file.
149class ASTContext : public RefCountedBase<ASTContext> {
150 friend class NestedNameSpecifier;
151
152 mutable SmallVector<Type *, 0> Types;
153 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
154 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
155 mutable llvm::FoldingSet<PointerType> PointerTypes;
156 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
157 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
158 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
159 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
160 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
161 mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
162 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
163 mutable std::vector<VariableArrayType*> VariableArrayTypes;
164 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
165 mutable llvm::FoldingSet<DependentSizedExtVectorType>
166 DependentSizedExtVectorTypes;
167 mutable llvm::FoldingSet<DependentAddressSpaceType>
168 DependentAddressSpaceTypes;
169 mutable llvm::FoldingSet<VectorType> VectorTypes;
170 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
171 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
172 FunctionProtoTypes;
173 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
174 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
175 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
176 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
177 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
178 SubstTemplateTypeParmTypes;
179 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
180 SubstTemplateTypeParmPackTypes;
181 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
182 TemplateSpecializationTypes;
183 mutable llvm::FoldingSet<ParenType> ParenTypes;
184 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
185 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
186 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
187 ASTContext&>
188 DependentTemplateSpecializationTypes;
189 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
190 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
191 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
192 mutable llvm::FoldingSet<DependentUnaryTransformType>
193 DependentUnaryTransformTypes;
194 mutable llvm::FoldingSet<AutoType> AutoTypes;
195 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
196 DeducedTemplateSpecializationTypes;
197 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
198 llvm::FoldingSet<AttributedType> AttributedTypes;
199 mutable llvm::FoldingSet<PipeType> PipeTypes;
200
201 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
202 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
203 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
204 SubstTemplateTemplateParms;
205 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
206 ASTContext&>
207 SubstTemplateTemplateParmPacks;
208
209 /// \brief The set of nested name specifiers.
210 ///
211 /// This set is managed by the NestedNameSpecifier class.
212 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
213 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
214
215 /// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
216 ///
217 /// This is lazily created. This is intentionally not serialized.
218 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
219 ASTRecordLayouts;
220 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
221 ObjCLayouts;
222
223 /// \brief A cache from types to size and alignment information.
224 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
225 mutable TypeInfoMap MemoizedTypeInfo;
226
227 /// \brief A cache mapping from CXXRecordDecls to key functions.
228 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
229
230 /// \brief Mapping from ObjCContainers to their ObjCImplementations.
231 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
232
233 /// \brief Mapping from ObjCMethod to its duplicate declaration in the same
234 /// interface.
235 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
236
237 /// \brief Mapping from __block VarDecls to their copy initialization expr.
238 llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
239
240 /// \brief Mapping from class scope functions specialization to their
241 /// template patterns.
242 llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
243 ClassScopeSpecializationPattern;
244
245 /// \brief Mapping from materialized temporaries with static storage duration
246 /// that appear in constant initializers to their evaluated values. These are
247 /// allocated in a std::map because their address must be stable.
248 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue *>
249 MaterializedTemporaryValues;
250
251 /// \brief Representation of a "canonical" template template parameter that
252 /// is used in canonical template names.
253 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
254 TemplateTemplateParmDecl *Parm;
255
256 public:
257 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
258 : Parm(Parm) {}
259
260 TemplateTemplateParmDecl *getParam() const { return Parm; }
261
262 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
263
264 static void Profile(llvm::FoldingSetNodeID &ID,
265 TemplateTemplateParmDecl *Parm);
266 };
267 mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
268 CanonTemplateTemplateParms;
269
270 TemplateTemplateParmDecl *
271 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
272
273 /// \brief The typedef for the __int128_t type.
274 mutable TypedefDecl *Int128Decl = nullptr;
275
276 /// \brief The typedef for the __uint128_t type.
277 mutable TypedefDecl *UInt128Decl = nullptr;
278
279 /// \brief The typedef for the target specific predefined
280 /// __builtin_va_list type.
281 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
282
283 /// The typedef for the predefined \c __builtin_ms_va_list type.
284 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
285
286 /// \brief The typedef for the predefined \c id type.
287 mutable TypedefDecl *ObjCIdDecl = nullptr;
288
289 /// \brief The typedef for the predefined \c SEL type.
290 mutable TypedefDecl *ObjCSelDecl = nullptr;
291
292 /// \brief The typedef for the predefined \c Class type.
293 mutable TypedefDecl *ObjCClassDecl = nullptr;
294
295 /// \brief The typedef for the predefined \c Protocol class in Objective-C.
296 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
297
298 /// \brief The typedef for the predefined 'BOOL' type.
299 mutable TypedefDecl *BOOLDecl = nullptr;
300
301 // Typedefs which may be provided defining the structure of Objective-C
302 // pseudo-builtins
303 QualType ObjCIdRedefinitionType;
304 QualType ObjCClassRedefinitionType;
305 QualType ObjCSelRedefinitionType;
306
307 /// The identifier 'bool'.
308 mutable IdentifierInfo *BoolName = nullptr;
309
310 /// The identifier 'NSObject'.
311 IdentifierInfo *NSObjectName = nullptr;
312
313 /// The identifier 'NSCopying'.
314 IdentifierInfo *NSCopyingName = nullptr;
315
316 /// The identifier '__make_integer_seq'.
317 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
318
319 /// The identifier '__type_pack_element'.
320 mutable IdentifierInfo *TypePackElementName = nullptr;
321
322 QualType ObjCConstantStringType;
323 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
324 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
325
326 mutable QualType ObjCSuperType;
327
328 QualType ObjCNSStringType;
329
330 /// \brief The typedef declaration for the Objective-C "instancetype" type.
331 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
332
333 /// \brief The type for the C FILE type.
334 TypeDecl *FILEDecl = nullptr;
335
336 /// \brief The type for the C jmp_buf type.
337 TypeDecl *jmp_bufDecl = nullptr;
338
339 /// \brief The type for the C sigjmp_buf type.
340 TypeDecl *sigjmp_bufDecl = nullptr;
341
342 /// \brief The type for the C ucontext_t type.
343 TypeDecl *ucontext_tDecl = nullptr;
344
345 /// \brief Type for the Block descriptor for Blocks CodeGen.
346 ///
347 /// Since this is only used for generation of debug info, it is not
348 /// serialized.
349 mutable RecordDecl *BlockDescriptorType = nullptr;
350
351 /// \brief Type for the Block descriptor for Blocks CodeGen.
352 ///
353 /// Since this is only used for generation of debug info, it is not
354 /// serialized.
355 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
356
357 /// \brief Declaration for the CUDA cudaConfigureCall function.
358 FunctionDecl *cudaConfigureCallDecl = nullptr;
359
360 /// \brief Keeps track of all declaration attributes.
361 ///
362 /// Since so few decls have attrs, we keep them in a hash map instead of
363 /// wasting space in the Decl class.
364 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
365
366 /// \brief A mapping from non-redeclarable declarations in modules that were
367 /// merged with other declarations to the canonical declaration that they were
368 /// merged into.
369 llvm::DenseMap<Decl*, Decl*> MergedDecls;
370
371 /// \brief A mapping from a defining declaration to a list of modules (other
372 /// than the owning module of the declaration) that contain merged
373 /// definitions of that entity.
374 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
375
376 /// \brief Initializers for a module, in order. Each Decl will be either
377 /// something that has a semantic effect on startup (such as a variable with
378 /// a non-constant initializer), or an ImportDecl (which recursively triggers
379 /// initialization of another module).
380 struct PerModuleInitializers {
381 llvm::SmallVector<Decl*, 4> Initializers;
382 llvm::SmallVector<uint32_t, 4> LazyInitializers;
383
384 void resolve(ASTContext &Ctx);
385 };
386 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
387
388 ASTContext &this_() { return *this; }
389
390public:
391 /// \brief A type synonym for the TemplateOrInstantiation mapping.
392 using TemplateOrSpecializationInfo =
393 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
394
395private:
396 friend class ASTDeclReader;
397 friend class ASTReader;
398 friend class ASTWriter;
399 friend class CXXRecordDecl;
400
401 /// \brief A mapping to contain the template or declaration that
402 /// a variable declaration describes or was instantiated from,
403 /// respectively.
404 ///
405 /// For non-templates, this value will be NULL. For variable
406 /// declarations that describe a variable template, this will be a
407 /// pointer to a VarTemplateDecl. For static data members
408 /// of class template specializations, this will be the
409 /// MemberSpecializationInfo referring to the member variable that was
410 /// instantiated or specialized. Thus, the mapping will keep track of
411 /// the static data member templates from which static data members of
412 /// class template specializations were instantiated.
413 ///
414 /// Given the following example:
415 ///
416 /// \code
417 /// template<typename T>
418 /// struct X {
419 /// static T value;
420 /// };
421 ///
422 /// template<typename T>
423 /// T X<T>::value = T(17);
424 ///
425 /// int *x = &X<int>::value;
426 /// \endcode
427 ///
428 /// This mapping will contain an entry that maps from the VarDecl for
429 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
430 /// class template X) and will be marked TSK_ImplicitInstantiation.
431 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
432 TemplateOrInstantiation;
433
434 /// \brief Keeps track of the declaration from which a using declaration was
435 /// created during instantiation.
436 ///
437 /// The source and target declarations are always a UsingDecl, an
438 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
439 ///
440 /// For example:
441 /// \code
442 /// template<typename T>
443 /// struct A {
444 /// void f();
445 /// };
446 ///
447 /// template<typename T>
448 /// struct B : A<T> {
449 /// using A<T>::f;
450 /// };
451 ///
452 /// template struct B<int>;
453 /// \endcode
454 ///
455 /// This mapping will contain an entry that maps from the UsingDecl in
456 /// B<int> to the UnresolvedUsingDecl in B<T>.
457 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
458
459 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
460 InstantiatedFromUsingShadowDecl;
461
462 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
463
464 /// \brief Mapping that stores the methods overridden by a given C++
465 /// member function.
466 ///
467 /// Since most C++ member functions aren't virtual and therefore
468 /// don't override anything, we store the overridden functions in
469 /// this map on the side rather than within the CXXMethodDecl structure.
470 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
471 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
472
473 /// \brief Mapping from each declaration context to its corresponding
474 /// mangling numbering context (used for constructs like lambdas which
475 /// need to be consistently numbered for the mangler).
476 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
477 MangleNumberingContexts;
478
479 /// \brief Side-table of mangling numbers for declarations which rarely
480 /// need them (like static local vars).
481 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
482 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
483
484 /// \brief Mapping that stores parameterIndex values for ParmVarDecls when
485 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
486 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
487 ParameterIndexTable ParamIndices;
488
489 ImportDecl *FirstLocalImport = nullptr;
490 ImportDecl *LastLocalImport = nullptr;
491
492 TranslationUnitDecl *TUDecl;
493 mutable ExternCContextDecl *ExternCContext = nullptr;
494 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
495 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
496
497 /// \brief The associated SourceManager object.
498 SourceManager &SourceMgr;
499
500 /// \brief The language options used to create the AST associated with
501 /// this ASTContext object.
502 LangOptions &LangOpts;
503
504 /// \brief Blacklist object that is used by sanitizers to decide which
505 /// entities should not be instrumented.
506 std::unique_ptr<SanitizerBlacklist> SanitizerBL;
507
508 /// \brief Function filtering mechanism to determine whether a given function
509 /// should be imbued with the XRay "always" or "never" attributes.
510 std::unique_ptr<XRayFunctionFilter> XRayFilter;
511
512 /// \brief The allocator used to create AST objects.
513 ///
514 /// AST objects are never destructed; rather, all memory associated with the
515 /// AST objects will be released when the ASTContext itself is destroyed.
516 mutable llvm::BumpPtrAllocator BumpAlloc;
517
518 /// \brief Allocator for partial diagnostics.
519 PartialDiagnostic::StorageAllocator DiagAllocator;
520
521 /// \brief The current C++ ABI.
522 std::unique_ptr<CXXABI> ABI;
523 CXXABI *createCXXABI(const TargetInfo &T);
524
525 /// \brief The logical -> physical address space map.
526 const LangASMap *AddrSpaceMap = nullptr;
527
528 /// \brief Address space map mangling must be used with language specific
529 /// address spaces (e.g. OpenCL/CUDA)
530 bool AddrSpaceMapMangling;
531
532 const TargetInfo *Target = nullptr;
533 const TargetInfo *AuxTarget = nullptr;
534 clang::PrintingPolicy PrintingPolicy;
535
536public:
537 IdentifierTable &Idents;
538 SelectorTable &Selectors;
539 Builtin::Context &BuiltinInfo;
540 mutable DeclarationNameTable DeclarationNames;
541 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
542 ASTMutationListener *Listener = nullptr;
543
544 /// \brief Contains parents of a node.
545 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
546
547 /// \brief Maps from a node to its parents. This is used for nodes that have
548 /// pointer identity only, which are more common and we can save space by
549 /// only storing a unique pointer to them.
550 using ParentMapPointers =
551 llvm::DenseMap<const void *,
552 llvm::PointerUnion4<const Decl *, const Stmt *,
553 ast_type_traits::DynTypedNode *,
554 ParentVector *>>;
555
556 /// Parent map for nodes without pointer identity. We store a full
557 /// DynTypedNode for all keys.
558 using ParentMapOtherNodes =
559 llvm::DenseMap<ast_type_traits::DynTypedNode,
560 llvm::PointerUnion4<const Decl *, const Stmt *,
561 ast_type_traits::DynTypedNode *,
562 ParentVector *>>;
563
564 /// Container for either a single DynTypedNode or for an ArrayRef to
565 /// DynTypedNode. For use with ParentMap.
566 class DynTypedNodeList {
567 using DynTypedNode = ast_type_traits::DynTypedNode;
568
569 llvm::AlignedCharArrayUnion<ast_type_traits::DynTypedNode,
570 ArrayRef<DynTypedNode>> Storage;
571 bool IsSingleNode;
572
573 public:
574 DynTypedNodeList(const DynTypedNode &N) : IsSingleNode(true) {
575 new (Storage.buffer) DynTypedNode(N);
576 }
577
578 DynTypedNodeList(ArrayRef<DynTypedNode> A) : IsSingleNode(false) {
579 new (Storage.buffer) ArrayRef<DynTypedNode>(A);
580 }
581
582 const ast_type_traits::DynTypedNode *begin() const {
583 if (!IsSingleNode)
584 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
585 ->begin();
586 return reinterpret_cast<const DynTypedNode *>(Storage.buffer);
587 }
588
589 const ast_type_traits::DynTypedNode *end() const {
590 if (!IsSingleNode)
591 return reinterpret_cast<const ArrayRef<DynTypedNode> *>(Storage.buffer)
592 ->end();
593 return reinterpret_cast<const DynTypedNode *>(Storage.buffer) + 1;
594 }
595
596 size_t size() const { return end() - begin(); }
597 bool empty() const { return begin() == end(); }
598
599 const DynTypedNode &operator[](size_t N) const {
600 assert(N < size() && "Out of bounds!")(static_cast <bool> (N < size() && "Out of bounds!"
) ? void (0) : __assert_fail ("N < size() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 600, __extension__ __PRETTY_FUNCTION__))
;
601 return *(begin() + N);
602 }
603 };
604
605 /// \brief Returns the parents of the given node.
606 ///
607 /// Note that this will lazily compute the parents of all nodes
608 /// and store them for later retrieval. Thus, the first call is O(n)
609 /// in the number of AST nodes.
610 ///
611 /// Caveats and FIXMEs:
612 /// Calculating the parent map over all AST nodes will need to load the
613 /// full AST. This can be undesirable in the case where the full AST is
614 /// expensive to create (for example, when using precompiled header
615 /// preambles). Thus, there are good opportunities for optimization here.
616 /// One idea is to walk the given node downwards, looking for references
617 /// to declaration contexts - once a declaration context is found, compute
618 /// the parent map for the declaration context; if that can satisfy the
619 /// request, loading the whole AST can be avoided. Note that this is made
620 /// more complex by statements in templates having multiple parents - those
621 /// problems can be solved by building closure over the templated parts of
622 /// the AST, which also avoids touching large parts of the AST.
623 /// Additionally, we will want to add an interface to already give a hint
624 /// where to search for the parents, for example when looking at a statement
625 /// inside a certain function.
626 ///
627 /// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
628 /// NestedNameSpecifier or NestedNameSpecifierLoc.
629 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node) {
630 return getParents(ast_type_traits::DynTypedNode::create(Node));
631 }
632
633 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node);
634
635 const clang::PrintingPolicy &getPrintingPolicy() const {
636 return PrintingPolicy;
637 }
638
639 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
640 PrintingPolicy = Policy;
641 }
642
643 SourceManager& getSourceManager() { return SourceMgr; }
644 const SourceManager& getSourceManager() const { return SourceMgr; }
645
646 llvm::BumpPtrAllocator &getAllocator() const {
647 return BumpAlloc;
648 }
649
650 void *Allocate(size_t Size, unsigned Align = 8) const {
651 return BumpAlloc.Allocate(Size, Align);
652 }
653 template <typename T> T *Allocate(size_t Num = 1) const {
654 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
655 }
656 void Deallocate(void *Ptr) const {}
657
658 /// Return the total amount of physical memory allocated for representing
659 /// AST nodes and type information.
660 size_t getASTAllocatedMemory() const {
661 return BumpAlloc.getTotalMemory();
662 }
663
664 /// Return the total memory used for various side tables.
665 size_t getSideTableAllocatedMemory() const;
666
667 PartialDiagnostic::StorageAllocator &getDiagAllocator() {
668 return DiagAllocator;
669 }
670
671 const TargetInfo &getTargetInfo() const { return *Target; }
672 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
673
674 /// getIntTypeForBitwidth -
675 /// sets integer QualTy according to specified details:
676 /// bitwidth, signed/unsigned.
677 /// Returns empty type if there is no appropriate target types.
678 QualType getIntTypeForBitwidth(unsigned DestWidth,
679 unsigned Signed) const;
680
681 /// getRealTypeForBitwidth -
682 /// sets floating point QualTy according to specified bitwidth.
683 /// Returns empty type if there is no appropriate target types.
684 QualType getRealTypeForBitwidth(unsigned DestWidth) const;
685
686 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
687
688 const LangOptions& getLangOpts() const { return LangOpts; }
689
690 const SanitizerBlacklist &getSanitizerBlacklist() const {
691 return *SanitizerBL;
692 }
693
694 const XRayFunctionFilter &getXRayFilter() const {
695 return *XRayFilter;
696 }
697
698 DiagnosticsEngine &getDiagnostics() const;
699
700 FullSourceLoc getFullLoc(SourceLocation Loc) const {
701 return FullSourceLoc(Loc,SourceMgr);
702 }
703
704 /// \brief All comments in this translation unit.
705 RawCommentList Comments;
706
707 /// \brief True if comments are already loaded from ExternalASTSource.
708 mutable bool CommentsLoaded = false;
709
710 class RawCommentAndCacheFlags {
711 public:
712 enum Kind {
713 /// We searched for a comment attached to the particular declaration, but
714 /// didn't find any.
715 ///
716 /// getRaw() == 0.
717 NoCommentInDecl = 0,
718
719 /// We have found a comment attached to this particular declaration.
720 ///
721 /// getRaw() != 0.
722 FromDecl,
723
724 /// This declaration does not have an attached comment, and we have
725 /// searched the redeclaration chain.
726 ///
727 /// If getRaw() == 0, the whole redeclaration chain does not have any
728 /// comments.
729 ///
730 /// If getRaw() != 0, it is a comment propagated from other
731 /// redeclaration.
732 FromRedecl
733 };
734
735 Kind getKind() const LLVM_READONLY__attribute__((__pure__)) {
736 return Data.getInt();
737 }
738
739 void setKind(Kind K) {
740 Data.setInt(K);
741 }
742
743 const RawComment *getRaw() const LLVM_READONLY__attribute__((__pure__)) {
744 return Data.getPointer();
745 }
746
747 void setRaw(const RawComment *RC) {
748 Data.setPointer(RC);
749 }
750
751 const Decl *getOriginalDecl() const LLVM_READONLY__attribute__((__pure__)) {
752 return OriginalDecl;
753 }
754
755 void setOriginalDecl(const Decl *Orig) {
756 OriginalDecl = Orig;
757 }
758
759 private:
760 llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
761 const Decl *OriginalDecl;
762 };
763
764 /// \brief Mapping from declarations to comments attached to any
765 /// redeclaration.
766 ///
767 /// Raw comments are owned by Comments list. This mapping is populated
768 /// lazily.
769 mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
770
771 /// \brief Mapping from declarations to parsed comments attached to any
772 /// redeclaration.
773 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
774
775 /// \brief Return the documentation comment attached to a given declaration,
776 /// without looking into cache.
777 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
778
779public:
780 RawCommentList &getRawCommentList() {
781 return Comments;
782 }
783
784 void addComment(const RawComment &RC) {
785 assert(LangOpts.RetainCommentsFromSystemHeaders ||(static_cast <bool> (LangOpts.RetainCommentsFromSystemHeaders
|| !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin(
))) ? void (0) : __assert_fail ("LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 786, __extension__ __PRETTY_FUNCTION__))
786 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()))(static_cast <bool> (LangOpts.RetainCommentsFromSystemHeaders
|| !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin(
))) ? void (0) : __assert_fail ("LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 786, __extension__ __PRETTY_FUNCTION__))
;
787 Comments.addComment(RC, BumpAlloc);
788 }
789
790 /// \brief Return the documentation comment attached to a given declaration.
791 /// Returns nullptr if no comment is attached.
792 ///
793 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
794 /// had the comment, if the comment we found comes from a redeclaration.
795 const RawComment *
796 getRawCommentForAnyRedecl(const Decl *D,
797 const Decl **OriginalDecl = nullptr) const;
798
799 /// Return parsed documentation comment attached to a given declaration.
800 /// Returns nullptr if no comment is attached.
801 ///
802 /// \param PP the Preprocessor used with this TU. Could be nullptr if
803 /// preprocessor is not available.
804 comments::FullComment *getCommentForDecl(const Decl *D,
805 const Preprocessor *PP) const;
806
807 /// Return parsed documentation comment attached to a given declaration.
808 /// Returns nullptr if no comment is attached. Does not look at any
809 /// redeclarations of the declaration.
810 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
811
812 comments::FullComment *cloneFullComment(comments::FullComment *FC,
813 const Decl *D) const;
814
815private:
816 mutable comments::CommandTraits CommentCommandTraits;
817
818 /// \brief Iterator that visits import declarations.
819 class import_iterator {
820 ImportDecl *Import = nullptr;
821
822 public:
823 using value_type = ImportDecl *;
824 using reference = ImportDecl *;
825 using pointer = ImportDecl *;
826 using difference_type = int;
827 using iterator_category = std::forward_iterator_tag;
828
829 import_iterator() = default;
830 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
831
832 reference operator*() const { return Import; }
833 pointer operator->() const { return Import; }
834
835 import_iterator &operator++() {
836 Import = ASTContext::getNextLocalImport(Import);
837 return *this;
838 }
839
840 import_iterator operator++(int) {
841 import_iterator Other(*this);
842 ++(*this);
843 return Other;
844 }
845
846 friend bool operator==(import_iterator X, import_iterator Y) {
847 return X.Import == Y.Import;
848 }
849
850 friend bool operator!=(import_iterator X, import_iterator Y) {
851 return X.Import != Y.Import;
852 }
853 };
854
855public:
856 comments::CommandTraits &getCommentCommandTraits() const {
857 return CommentCommandTraits;
858 }
859
860 /// \brief Retrieve the attributes for the given declaration.
861 AttrVec& getDeclAttrs(const Decl *D);
862
863 /// \brief Erase the attributes corresponding to the given declaration.
864 void eraseDeclAttrs(const Decl *D);
865
866 /// \brief If this variable is an instantiated static data member of a
867 /// class template specialization, returns the templated static data member
868 /// from which it was instantiated.
869 // FIXME: Remove ?
870 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
871 const VarDecl *Var);
872
873 TemplateOrSpecializationInfo
874 getTemplateOrSpecializationInfo(const VarDecl *Var);
875
876 FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
877
878 void setClassScopeSpecializationPattern(FunctionDecl *FD,
879 FunctionDecl *Pattern);
880
881 /// \brief Note that the static data member \p Inst is an instantiation of
882 /// the static data member template \p Tmpl of a class template.
883 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
884 TemplateSpecializationKind TSK,
885 SourceLocation PointOfInstantiation = SourceLocation());
886
887 void setTemplateOrSpecializationInfo(VarDecl *Inst,
888 TemplateOrSpecializationInfo TSI);
889
890 /// \brief If the given using decl \p Inst is an instantiation of a
891 /// (possibly unresolved) using decl from a template instantiation,
892 /// return it.
893 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
894
895 /// \brief Remember that the using decl \p Inst is an instantiation
896 /// of the using decl \p Pattern of a class template.
897 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
898
899 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
900 UsingShadowDecl *Pattern);
901 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
902
903 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
904
905 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
906
907 // Access to the set of methods overridden by the given C++ method.
908 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
909 overridden_cxx_method_iterator
910 overridden_methods_begin(const CXXMethodDecl *Method) const;
911
912 overridden_cxx_method_iterator
913 overridden_methods_end(const CXXMethodDecl *Method) const;
914
915 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
916
917 using overridden_method_range =
918 llvm::iterator_range<overridden_cxx_method_iterator>;
919
920 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
921
922 /// \brief Note that the given C++ \p Method overrides the given \p
923 /// Overridden method.
924 void addOverriddenMethod(const CXXMethodDecl *Method,
925 const CXXMethodDecl *Overridden);
926
927 /// \brief Return C++ or ObjC overridden methods for the given \p Method.
928 ///
929 /// An ObjC method is considered to override any method in the class's
930 /// base classes, its protocols, or its categories' protocols, that has
931 /// the same selector and is of the same kind (class or instance).
932 /// A method in an implementation is not considered as overriding the same
933 /// method in the interface or its categories.
934 void getOverriddenMethods(
935 const NamedDecl *Method,
936 SmallVectorImpl<const NamedDecl *> &Overridden) const;
937
938 /// \brief Notify the AST context that a new import declaration has been
939 /// parsed or implicitly created within this translation unit.
940 void addedLocalImportDecl(ImportDecl *Import);
941
942 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
943 return Import->NextLocalImport;
944 }
945
946 using import_range = llvm::iterator_range<import_iterator>;
947
948 import_range local_imports() const {
949 return import_range(import_iterator(FirstLocalImport), import_iterator());
950 }
951
952 Decl *getPrimaryMergedDecl(Decl *D) {
953 Decl *Result = MergedDecls.lookup(D);
954 return Result ? Result : D;
955 }
956 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
957 MergedDecls[D] = Primary;
958 }
959
960 /// \brief Note that the definition \p ND has been merged into module \p M,
961 /// and should be visible whenever \p M is visible.
962 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
963 bool NotifyListeners = true);
964
965 /// \brief Clean up the merged definition list. Call this if you might have
966 /// added duplicates into the list.
967 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
968
969 /// \brief Get the additional modules in which the definition \p Def has
970 /// been merged.
971 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def) {
972 auto MergedIt = MergedDefModules.find(Def);
973 if (MergedIt == MergedDefModules.end())
974 return None;
975 return MergedIt->second;
976 }
977
978 /// Add a declaration to the list of declarations that are initialized
979 /// for a module. This will typically be a global variable (with internal
980 /// linkage) that runs module initializers, such as the iostream initializer,
981 /// or an ImportDecl nominating another module that has initializers.
982 void addModuleInitializer(Module *M, Decl *Init);
983
984 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
985
986 /// Get the initializations to perform when importing a module, if any.
987 ArrayRef<Decl*> getModuleInitializers(Module *M);
988
989 TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
990
991 ExternCContextDecl *getExternCContextDecl() const;
992 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
993 BuiltinTemplateDecl *getTypePackElementDecl() const;
994
995 // Builtin Types.
996 CanQualType VoidTy;
997 CanQualType BoolTy;
998 CanQualType CharTy;
999 CanQualType WCharTy; // [C++ 3.9.1p5].
1000 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1001 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1002 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1003 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1004 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1005 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1006 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1007 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
1008 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1009 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1010 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
1011 CanQualType Float128ComplexTy;
1012 CanQualType VoidPtrTy, NullPtrTy;
1013 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
1014 CanQualType BuiltinFnTy;
1015 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1016 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1017 CanQualType ObjCBuiltinBoolTy;
1018#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1019 CanQualType SingletonId;
1020#include "clang/Basic/OpenCLImageTypes.def"
1021 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1022 CanQualType OCLQueueTy, OCLReserveIDTy;
1023 CanQualType OMPArraySectionTy;
1024
1025 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1026 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1027 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1028
1029 // Decl used to help define __builtin_va_list for some targets.
1030 // The decl is built when constructing 'BuiltinVaListDecl'.
1031 mutable Decl *VaListTagDecl;
1032
1033 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1034 SelectorTable &sels, Builtin::Context &builtins);
1035 ASTContext(const ASTContext &) = delete;
1036 ASTContext &operator=(const ASTContext &) = delete;
1037 ~ASTContext();
1038
1039 /// \brief Attach an external AST source to the AST context.
1040 ///
1041 /// The external AST source provides the ability to load parts of
1042 /// the abstract syntax tree as needed from some external storage,
1043 /// e.g., a precompiled header.
1044 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1045
1046 /// \brief Retrieve a pointer to the external AST source associated
1047 /// with this AST context, if any.
1048 ExternalASTSource *getExternalSource() const {
1049 return ExternalSource.get();
1050 }
1051
1052 /// \brief Attach an AST mutation listener to the AST context.
1053 ///
1054 /// The AST mutation listener provides the ability to track modifications to
1055 /// the abstract syntax tree entities committed after they were initially
1056 /// created.
1057 void setASTMutationListener(ASTMutationListener *Listener) {
1058 this->Listener = Listener;
1059 }
1060
1061 /// \brief Retrieve a pointer to the AST mutation listener associated
1062 /// with this AST context, if any.
1063 ASTMutationListener *getASTMutationListener() const { return Listener; }
1064
1065 void PrintStats() const;
1066 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1067
1068 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1069 const IdentifierInfo *II) const;
1070
1071 /// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl
1072 /// declaration.
1073 RecordDecl *buildImplicitRecord(StringRef Name,
1074 RecordDecl::TagKind TK = TTK_Struct) const;
1075
1076 /// \brief Create a new implicit TU-level typedef declaration.
1077 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1078
1079 /// \brief Retrieve the declaration for the 128-bit signed integer type.
1080 TypedefDecl *getInt128Decl() const;
1081
1082 /// \brief Retrieve the declaration for the 128-bit unsigned integer type.
1083 TypedefDecl *getUInt128Decl() const;
1084
1085 //===--------------------------------------------------------------------===//
1086 // Type Constructors
1087 //===--------------------------------------------------------------------===//
1088
1089private:
1090 /// \brief Return a type with extended qualifiers.
1091 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1092
1093 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1094
1095 QualType getPipeType(QualType T, bool ReadOnly) const;
1096
1097public:
1098 /// \brief Return the uniqued reference to the type for an address space
1099 /// qualified type with the specified type and address space.
1100 ///
1101 /// The resulting type has a union of the qualifiers from T and the address
1102 /// space. If T already has an address space specifier, it is silently
1103 /// replaced.
1104 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1105
1106 /// \brief Remove any existing address space on the type and returns the type
1107 /// with qualifiers intact (or that's the idea anyway)
1108 ///
1109 /// The return type should be T with all prior qualifiers minus the address
1110 /// space.
1111 QualType removeAddrSpaceQualType(QualType T) const;
1112
1113 /// \brief Apply Objective-C protocol qualifiers to the given type.
1114 /// \param allowOnPointerType specifies if we can apply protocol
1115 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1116 /// contructing the canonical type of a Objective-C type parameter.
1117 QualType applyObjCProtocolQualifiers(QualType type,
1118 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1119 bool allowOnPointerType = false) const;
1120
1121 /// \brief Return the uniqued reference to the type for an Objective-C
1122 /// gc-qualified type.
1123 ///
1124 /// The retulting type has a union of the qualifiers from T and the gc
1125 /// attribute.
1126 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1127
1128 /// \brief Return the uniqued reference to the type for a \c restrict
1129 /// qualified type.
1130 ///
1131 /// The resulting type has a union of the qualifiers from \p T and
1132 /// \c restrict.
1133 QualType getRestrictType(QualType T) const {
1134 return T.withFastQualifiers(Qualifiers::Restrict);
1135 }
1136
1137 /// \brief Return the uniqued reference to the type for a \c volatile
1138 /// qualified type.
1139 ///
1140 /// The resulting type has a union of the qualifiers from \p T and
1141 /// \c volatile.
1142 QualType getVolatileType(QualType T) const {
1143 return T.withFastQualifiers(Qualifiers::Volatile);
1144 }
1145
1146 /// \brief Return the uniqued reference to the type for a \c const
1147 /// qualified type.
1148 ///
1149 /// The resulting type has a union of the qualifiers from \p T and \c const.
1150 ///
1151 /// It can be reasonably expected that this will always be equivalent to
1152 /// calling T.withConst().
1153 QualType getConstType(QualType T) const { return T.withConst(); }
1154
1155 /// \brief Change the ExtInfo on a function type.
1156 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1157 FunctionType::ExtInfo EInfo);
1158
1159 /// Adjust the given function result type.
1160 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1161
1162 /// \brief Change the result type of a function type once it is deduced.
1163 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1164
1165 /// Get a function type and produce the equivalent function type with the
1166 /// specified exception specification. Type sugar that can be present on a
1167 /// declaration of a function with an exception specification is permitted
1168 /// and preserved. Other type sugar (for instance, typedefs) is not.
1169 QualType getFunctionTypeWithExceptionSpec(
1170 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1171
1172 /// \brief Determine whether two function types are the same, ignoring
1173 /// exception specifications in cases where they're part of the type.
1174 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1175
1176 /// \brief Change the exception specification on a function once it is
1177 /// delay-parsed, instantiated, or computed.
1178 void adjustExceptionSpec(FunctionDecl *FD,
1179 const FunctionProtoType::ExceptionSpecInfo &ESI,
1180 bool AsWritten = false);
1181
1182 /// Determine whether a type is a class that should be detructed in the
1183 /// callee function.
1184 bool isParamDestroyedInCallee(QualType T) const;
1185
1186 /// \brief Return the uniqued reference to the type for a complex
1187 /// number with the specified element type.
1188 QualType getComplexType(QualType T) const;
1189 CanQualType getComplexType(CanQualType T) const {
1190 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1191 }
1192
1193 /// \brief Return the uniqued reference to the type for a pointer to
1194 /// the specified type.
1195 QualType getPointerType(QualType T) const;
1196 CanQualType getPointerType(CanQualType T) const {
1197 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1198 }
1199
1200 /// \brief Return the uniqued reference to a type adjusted from the original
1201 /// type to a new type.
1202 QualType getAdjustedType(QualType Orig, QualType New) const;
1203 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1204 return CanQualType::CreateUnsafe(
1205 getAdjustedType((QualType)Orig, (QualType)New));
1206 }
1207
1208 /// \brief Return the uniqued reference to the decayed version of the given
1209 /// type. Can only be called on array and function types which decay to
1210 /// pointer types.
1211 QualType getDecayedType(QualType T) const;
1212 CanQualType getDecayedType(CanQualType T) const {
1213 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1214 }
1215
1216 /// \brief Return the uniqued reference to the atomic type for the specified
1217 /// type.
1218 QualType getAtomicType(QualType T) const;
1219
1220 /// \brief Return the uniqued reference to the type for a block of the
1221 /// specified type.
1222 QualType getBlockPointerType(QualType T) const;
1223
1224 /// Gets the struct used to keep track of the descriptor for pointer to
1225 /// blocks.
1226 QualType getBlockDescriptorType() const;
1227
1228 /// \brief Return a read_only pipe type for the specified type.
1229 QualType getReadPipeType(QualType T) const;
1230
1231 /// \brief Return a write_only pipe type for the specified type.
1232 QualType getWritePipeType(QualType T) const;
1233
1234 /// Gets the struct used to keep track of the extended descriptor for
1235 /// pointer to blocks.
1236 QualType getBlockDescriptorExtendedType() const;
1237
1238 /// Map an AST Type to an OpenCLTypeKind enum value.
1239 TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1240
1241 /// Get address space for OpenCL type.
1242 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1243
1244 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1245 cudaConfigureCallDecl = FD;
1246 }
1247
1248 FunctionDecl *getcudaConfigureCallDecl() {
1249 return cudaConfigureCallDecl;
1250 }
1251
1252 /// Returns true iff we need copy/dispose helpers for the given type.
1253 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1254
1255 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
1256 /// to false in this case. If HasByrefExtendedLayout returns true, byref variable
1257 /// has extended lifetime.
1258 bool getByrefLifetime(QualType Ty,
1259 Qualifiers::ObjCLifetime &Lifetime,
1260 bool &HasByrefExtendedLayout) const;
1261
1262 /// \brief Return the uniqued reference to the type for an lvalue reference
1263 /// to the specified type.
1264 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1265 const;
1266
1267 /// \brief Return the uniqued reference to the type for an rvalue reference
1268 /// to the specified type.
1269 QualType getRValueReferenceType(QualType T) const;
1270
1271 /// \brief Return the uniqued reference to the type for a member pointer to
1272 /// the specified type in the specified class.
1273 ///
1274 /// The class \p Cls is a \c Type because it could be a dependent name.
1275 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1276
1277 /// \brief Return a non-unique reference to the type for a variable array of
1278 /// the specified element type.
1279 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1280 ArrayType::ArraySizeModifier ASM,
1281 unsigned IndexTypeQuals,
1282 SourceRange Brackets) const;
1283
1284 /// \brief Return a non-unique reference to the type for a dependently-sized
1285 /// array of the specified element type.
1286 ///
1287 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1288 /// point.
1289 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1290 ArrayType::ArraySizeModifier ASM,
1291 unsigned IndexTypeQuals,
1292 SourceRange Brackets) const;
1293
1294 /// \brief Return a unique reference to the type for an incomplete array of
1295 /// the specified element type.
1296 QualType getIncompleteArrayType(QualType EltTy,
1297 ArrayType::ArraySizeModifier ASM,
1298 unsigned IndexTypeQuals) const;
1299
1300 /// \brief Return the unique reference to the type for a constant array of
1301 /// the specified element type.
1302 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1303 ArrayType::ArraySizeModifier ASM,
1304 unsigned IndexTypeQuals) const;
1305
1306 /// \brief Returns a vla type where known sizes are replaced with [*].
1307 QualType getVariableArrayDecayedType(QualType Ty) const;
1308
1309 /// \brief Return the unique reference to a vector type of the specified
1310 /// element type and size.
1311 ///
1312 /// \pre \p VectorType must be a built-in type.
1313 QualType getVectorType(QualType VectorType, unsigned NumElts,
1314 VectorType::VectorKind VecKind) const;
1315
1316 /// \brief Return the unique reference to an extended vector type
1317 /// of the specified element type and size.
1318 ///
1319 /// \pre \p VectorType must be a built-in type.
1320 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1321
1322 /// \pre Return a non-unique reference to the type for a dependently-sized
1323 /// vector of the specified element type.
1324 ///
1325 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1326 /// point.
1327 QualType getDependentSizedExtVectorType(QualType VectorType,
1328 Expr *SizeExpr,
1329 SourceLocation AttrLoc) const;
1330
1331 QualType getDependentAddressSpaceType(QualType PointeeType,
1332 Expr *AddrSpaceExpr,
1333 SourceLocation AttrLoc) const;
1334
1335 /// \brief Return a K&R style C function type like 'int()'.
1336 QualType getFunctionNoProtoType(QualType ResultTy,
1337 const FunctionType::ExtInfo &Info) const;
1338
1339 QualType getFunctionNoProtoType(QualType ResultTy) const {
1340 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1341 }
1342
1343 /// \brief Return a normal function type with a typed argument list.
1344 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1345 const FunctionProtoType::ExtProtoInfo &EPI) const {
1346 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1347 }
1348
1349private:
1350 /// \brief Return a normal function type with a typed argument list.
1351 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1352 const FunctionProtoType::ExtProtoInfo &EPI,
1353 bool OnlyWantCanonical) const;
1354
1355public:
1356 /// \brief Return the unique reference to the type for the specified type
1357 /// declaration.
1358 QualType getTypeDeclType(const TypeDecl *Decl,
1359 const TypeDecl *PrevDecl = nullptr) const {
1360 assert(Decl && "Passed null for Decl param")(static_cast <bool> (Decl && "Passed null for Decl param"
) ? void (0) : __assert_fail ("Decl && \"Passed null for Decl param\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 1360, __extension__ __PRETTY_FUNCTION__))
;
29
Within the expansion of the macro 'assert':
a
Assuming 'Decl' is non-null
1361 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
30
Assuming the condition is false
31
Taking false branch
1362
1363 if (PrevDecl) {
32
Taking false branch
1364 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl")(static_cast <bool> (PrevDecl->TypeForDecl &&
"previous decl has no TypeForDecl") ? void (0) : __assert_fail
("PrevDecl->TypeForDecl && \"previous decl has no TypeForDecl\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 1364, __extension__ __PRETTY_FUNCTION__))
;
1365 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1366 return QualType(PrevDecl->TypeForDecl, 0);
1367 }
1368
1369 return getTypeDeclTypeSlow(Decl);
1370 }
1371
1372 /// \brief Return the unique reference to the type for the specified
1373 /// typedef-name decl.
1374 QualType getTypedefType(const TypedefNameDecl *Decl,
1375 QualType Canon = QualType()) const;
1376
1377 QualType getRecordType(const RecordDecl *Decl) const;
1378
1379 QualType getEnumType(const EnumDecl *Decl) const;
1380
1381 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1382
1383 QualType getAttributedType(AttributedType::Kind attrKind,
1384 QualType modifiedType,
1385 QualType equivalentType);
1386
1387 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1388 QualType Replacement) const;
1389 QualType getSubstTemplateTypeParmPackType(
1390 const TemplateTypeParmType *Replaced,
1391 const TemplateArgument &ArgPack);
1392
1393 QualType
1394 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1395 bool ParameterPack,
1396 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1397
1398 QualType getTemplateSpecializationType(TemplateName T,
1399 ArrayRef<TemplateArgument> Args,
1400 QualType Canon = QualType()) const;
1401
1402 QualType
1403 getCanonicalTemplateSpecializationType(TemplateName T,
1404 ArrayRef<TemplateArgument> Args) const;
1405
1406 QualType getTemplateSpecializationType(TemplateName T,
1407 const TemplateArgumentListInfo &Args,
1408 QualType Canon = QualType()) const;
1409
1410 TypeSourceInfo *
1411 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1412 const TemplateArgumentListInfo &Args,
1413 QualType Canon = QualType()) const;
1414
1415 QualType getParenType(QualType NamedType) const;
1416
1417 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1418 NestedNameSpecifier *NNS,
1419 QualType NamedType) const;
1420 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1421 NestedNameSpecifier *NNS,
1422 const IdentifierInfo *Name,
1423 QualType Canon = QualType()) const;
1424
1425 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1426 NestedNameSpecifier *NNS,
1427 const IdentifierInfo *Name,
1428 const TemplateArgumentListInfo &Args) const;
1429 QualType getDependentTemplateSpecializationType(
1430 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1431 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1432
1433 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1434
1435 /// Get a template argument list with one argument per template parameter
1436 /// in a template parameter list, such as for the injected class name of
1437 /// a class template.
1438 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1439 SmallVectorImpl<TemplateArgument> &Args);
1440
1441 QualType getPackExpansionType(QualType Pattern,
1442 Optional<unsigned> NumExpansions);
1443
1444 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1445 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1446
1447 /// Legacy interface: cannot provide type arguments or __kindof.
1448 QualType getObjCObjectType(QualType Base,
1449 ObjCProtocolDecl * const *Protocols,
1450 unsigned NumProtocols) const;
1451
1452 QualType getObjCObjectType(QualType Base,
1453 ArrayRef<QualType> typeArgs,
1454 ArrayRef<ObjCProtocolDecl *> protocols,
1455 bool isKindOf) const;
1456
1457 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1458 ArrayRef<ObjCProtocolDecl *> protocols,
1459 QualType Canonical = QualType()) const;
1460
1461 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1462
1463 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1464 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1465 /// of protocols.
1466 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1467 ObjCInterfaceDecl *IDecl);
1468
1469 /// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
1470 QualType getObjCObjectPointerType(QualType OIT) const;
1471
1472 /// \brief GCC extension.
1473 QualType getTypeOfExprType(Expr *e) const;
1474 QualType getTypeOfType(QualType t) const;
1475
1476 /// \brief C++11 decltype.
1477 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1478
1479 /// \brief Unary type transforms
1480 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1481 UnaryTransformType::UTTKind UKind) const;
1482
1483 /// \brief C++11 deduced auto type.
1484 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1485 bool IsDependent) const;
1486
1487 /// \brief C++11 deduction pattern for 'auto' type.
1488 QualType getAutoDeductType() const;
1489
1490 /// \brief C++11 deduction pattern for 'auto &&' type.
1491 QualType getAutoRRefDeductType() const;
1492
1493 /// \brief C++17 deduced class template specialization type.
1494 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1495 QualType DeducedType,
1496 bool IsDependent) const;
1497
1498 /// \brief Return the unique reference to the type for the specified TagDecl
1499 /// (struct/union/class/enum) decl.
1500 QualType getTagDeclType(const TagDecl *Decl) const;
1501
1502 /// \brief Return the unique type for "size_t" (C99 7.17), defined in
1503 /// <stddef.h>.
1504 ///
1505 /// The sizeof operator requires this (C99 6.5.3.4p4).
1506 CanQualType getSizeType() const;
1507
1508 /// \brief Return the unique signed counterpart of
1509 /// the integer type corresponding to size_t.
1510 CanQualType getSignedSizeType() const;
1511
1512 /// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1513 /// <stdint.h>.
1514 CanQualType getIntMaxType() const;
1515
1516 /// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1517 /// <stdint.h>.
1518 CanQualType getUIntMaxType() const;
1519
1520 /// \brief Return the unique wchar_t type available in C++ (and available as
1521 /// __wchar_t as a Microsoft extension).
1522 QualType getWCharType() const { return WCharTy; }
1523
1524 /// \brief Return the type of wide characters. In C++, this returns the
1525 /// unique wchar_t type. In C99, this returns a type compatible with the type
1526 /// defined in <stddef.h> as defined by the target.
1527 QualType getWideCharType() const { return WideCharTy; }
1528
1529 /// \brief Return the type of "signed wchar_t".
1530 ///
1531 /// Used when in C++, as a GCC extension.
1532 QualType getSignedWCharType() const;
1533
1534 /// \brief Return the type of "unsigned wchar_t".
1535 ///
1536 /// Used when in C++, as a GCC extension.
1537 QualType getUnsignedWCharType() const;
1538
1539 /// \brief In C99, this returns a type compatible with the type
1540 /// defined in <stddef.h> as defined by the target.
1541 QualType getWIntType() const { return WIntTy; }
1542
1543 /// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
1544 /// as defined by the target.
1545 QualType getIntPtrType() const;
1546
1547 /// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1548 /// as defined by the target.
1549 QualType getUIntPtrType() const;
1550
1551 /// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1552 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1553 QualType getPointerDiffType() const;
1554
1555 /// \brief Return the unique unsigned counterpart of "ptrdiff_t"
1556 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1557 /// in the definition of %tu format specifier.
1558 QualType getUnsignedPointerDiffType() const;
1559
1560 /// \brief Return the unique type for "pid_t" defined in
1561 /// <sys/types.h>. We need this to compute the correct type for vfork().
1562 QualType getProcessIDType() const;
1563
1564 /// \brief Return the C structure type used to represent constant CFStrings.
1565 QualType getCFConstantStringType() const;
1566
1567 /// \brief Returns the C struct type for objc_super
1568 QualType getObjCSuperType() const;
1569 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1570
1571 /// Get the structure type used to representation CFStrings, or NULL
1572 /// if it hasn't yet been built.
1573 QualType getRawCFConstantStringType() const {
1574 if (CFConstantStringTypeDecl)
1575 return getTypedefType(CFConstantStringTypeDecl);
1576 return QualType();
1577 }
1578 void setCFConstantStringType(QualType T);
1579 TypedefDecl *getCFConstantStringDecl() const;
1580 RecordDecl *getCFConstantStringTagDecl() const;
1581
1582 // This setter/getter represents the ObjC type for an NSConstantString.
1583 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1584 QualType getObjCConstantStringInterface() const {
1585 return ObjCConstantStringType;
1586 }
1587
1588 QualType getObjCNSStringType() const {
1589 return ObjCNSStringType;
1590 }
1591
1592 void setObjCNSStringType(QualType T) {
1593 ObjCNSStringType = T;
1594 }
1595
1596 /// \brief Retrieve the type that \c id has been defined to, which may be
1597 /// different from the built-in \c id if \c id has been typedef'd.
1598 QualType getObjCIdRedefinitionType() const {
1599 if (ObjCIdRedefinitionType.isNull())
1600 return getObjCIdType();
1601 return ObjCIdRedefinitionType;
1602 }
1603
1604 /// \brief Set the user-written type that redefines \c id.
1605 void setObjCIdRedefinitionType(QualType RedefType) {
1606 ObjCIdRedefinitionType = RedefType;
1607 }
1608
1609 /// \brief Retrieve the type that \c Class has been defined to, which may be
1610 /// different from the built-in \c Class if \c Class has been typedef'd.
1611 QualType getObjCClassRedefinitionType() const {
1612 if (ObjCClassRedefinitionType.isNull())
1613 return getObjCClassType();
1614 return ObjCClassRedefinitionType;
1615 }
1616
1617 /// \brief Set the user-written type that redefines 'SEL'.
1618 void setObjCClassRedefinitionType(QualType RedefType) {
1619 ObjCClassRedefinitionType = RedefType;
1620 }
1621
1622 /// \brief Retrieve the type that 'SEL' has been defined to, which may be
1623 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1624 QualType getObjCSelRedefinitionType() const {
1625 if (ObjCSelRedefinitionType.isNull())
1626 return getObjCSelType();
1627 return ObjCSelRedefinitionType;
1628 }
1629
1630 /// \brief Set the user-written type that redefines 'SEL'.
1631 void setObjCSelRedefinitionType(QualType RedefType) {
1632 ObjCSelRedefinitionType = RedefType;
1633 }
1634
1635 /// Retrieve the identifier 'NSObject'.
1636 IdentifierInfo *getNSObjectName() {
1637 if (!NSObjectName) {
1638 NSObjectName = &Idents.get("NSObject");
1639 }
1640
1641 return NSObjectName;
1642 }
1643
1644 /// Retrieve the identifier 'NSCopying'.
1645 IdentifierInfo *getNSCopyingName() {
1646 if (!NSCopyingName) {
1647 NSCopyingName = &Idents.get("NSCopying");
1648 }
1649
1650 return NSCopyingName;
1651 }
1652
1653 CanQualType getNSUIntegerType() const {
1654 assert(Target && "Expected target to be initialized")(static_cast <bool> (Target && "Expected target to be initialized"
) ? void (0) : __assert_fail ("Target && \"Expected target to be initialized\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 1654, __extension__ __PRETTY_FUNCTION__))
;
1655 const llvm::Triple &T = Target->getTriple();
1656 // Windows is LLP64 rather than LP64
1657 if (T.isOSWindows() && T.isArch64Bit())
1658 return UnsignedLongLongTy;
1659 return UnsignedLongTy;
1660 }
1661
1662 CanQualType getNSIntegerType() const {
1663 assert(Target && "Expected target to be initialized")(static_cast <bool> (Target && "Expected target to be initialized"
) ? void (0) : __assert_fail ("Target && \"Expected target to be initialized\""
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 1663, __extension__ __PRETTY_FUNCTION__))
;
1664 const llvm::Triple &T = Target->getTriple();
1665 // Windows is LLP64 rather than LP64
1666 if (T.isOSWindows() && T.isArch64Bit())
1667 return LongLongTy;
1668 return LongTy;
1669 }
1670
1671 /// Retrieve the identifier 'bool'.
1672 IdentifierInfo *getBoolName() const {
1673 if (!BoolName)
1674 BoolName = &Idents.get("bool");
1675 return BoolName;
1676 }
1677
1678 IdentifierInfo *getMakeIntegerSeqName() const {
1679 if (!MakeIntegerSeqName)
1680 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1681 return MakeIntegerSeqName;
1682 }
1683
1684 IdentifierInfo *getTypePackElementName() const {
1685 if (!TypePackElementName)
1686 TypePackElementName = &Idents.get("__type_pack_element");
1687 return TypePackElementName;
1688 }
1689
1690 /// \brief Retrieve the Objective-C "instancetype" type, if already known;
1691 /// otherwise, returns a NULL type;
1692 QualType getObjCInstanceType() {
1693 return getTypeDeclType(getObjCInstanceTypeDecl());
1694 }
1695
1696 /// \brief Retrieve the typedef declaration corresponding to the Objective-C
1697 /// "instancetype" type.
1698 TypedefDecl *getObjCInstanceTypeDecl();
1699
1700 /// \brief Set the type for the C FILE type.
1701 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1702
1703 /// \brief Retrieve the C FILE type.
1704 QualType getFILEType() const {
1705 if (FILEDecl)
1706 return getTypeDeclType(FILEDecl);
1707 return QualType();
1708 }
1709
1710 /// \brief Set the type for the C jmp_buf type.
1711 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1712 this->jmp_bufDecl = jmp_bufDecl;
1713 }
1714
1715 /// \brief Retrieve the C jmp_buf type.
1716 QualType getjmp_bufType() const {
1717 if (jmp_bufDecl)
1718 return getTypeDeclType(jmp_bufDecl);
1719 return QualType();
1720 }
1721
1722 /// \brief Set the type for the C sigjmp_buf type.
1723 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1724 this->sigjmp_bufDecl = sigjmp_bufDecl;
1725 }
1726
1727 /// \brief Retrieve the C sigjmp_buf type.
1728 QualType getsigjmp_bufType() const {
1729 if (sigjmp_bufDecl)
1730 return getTypeDeclType(sigjmp_bufDecl);
1731 return QualType();
1732 }
1733
1734 /// \brief Set the type for the C ucontext_t type.
1735 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1736 this->ucontext_tDecl = ucontext_tDecl;
1737 }
1738
1739 /// \brief Retrieve the C ucontext_t type.
1740 QualType getucontext_tType() const {
1741 if (ucontext_tDecl)
1742 return getTypeDeclType(ucontext_tDecl);
1743 return QualType();
1744 }
1745
1746 /// \brief The result type of logical operations, '<', '>', '!=', etc.
1747 QualType getLogicalOperationType() const {
1748 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1749 }
1750
1751 /// \brief Emit the Objective-CC type encoding for the given type \p T into
1752 /// \p S.
1753 ///
1754 /// If \p Field is specified then record field names are also encoded.
1755 void getObjCEncodingForType(QualType T, std::string &S,
1756 const FieldDecl *Field=nullptr,
1757 QualType *NotEncodedT=nullptr) const;
1758
1759 /// \brief Emit the Objective-C property type encoding for the given
1760 /// type \p T into \p S.
1761 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1762
1763 void getLegacyIntegralTypeEncoding(QualType &t) const;
1764
1765 /// \brief Put the string version of the type qualifiers \p QT into \p S.
1766 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1767 std::string &S) const;
1768
1769 /// \brief Emit the encoded type for the function \p Decl into \p S.
1770 ///
1771 /// This is in the same format as Objective-C method encodings.
1772 ///
1773 /// \returns true if an error occurred (e.g., because one of the parameter
1774 /// types is incomplete), false otherwise.
1775 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1776
1777 /// \brief Emit the encoded type for the method declaration \p Decl into
1778 /// \p S.
1779 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1780 bool Extended = false) const;
1781
1782 /// \brief Return the encoded type for this block declaration.
1783 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1784
1785 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1786 /// this method declaration. If non-NULL, Container must be either
1787 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1788 /// only be NULL when getting encodings for protocol properties.
1789 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1790 const Decl *Container) const;
1791
1792 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1793 ObjCProtocolDecl *rProto) const;
1794
1795 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1796 const ObjCPropertyDecl *PD,
1797 const Decl *Container) const;
1798
1799 /// \brief Return the size of type \p T for Objective-C encoding purpose,
1800 /// in characters.
1801 CharUnits getObjCEncodingTypeSize(QualType T) const;
1802
1803 /// \brief Retrieve the typedef corresponding to the predefined \c id type
1804 /// in Objective-C.
1805 TypedefDecl *getObjCIdDecl() const;
1806
1807 /// \brief Represents the Objective-CC \c id type.
1808 ///
1809 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1810 /// pointer type, a pointer to a struct.
1811 QualType getObjCIdType() const {
1812 return getTypeDeclType(getObjCIdDecl());
1813 }
1814
1815 /// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
1816 /// in Objective-C.
1817 TypedefDecl *getObjCSelDecl() const;
1818
1819 /// \brief Retrieve the type that corresponds to the predefined Objective-C
1820 /// 'SEL' type.
1821 QualType getObjCSelType() const {
1822 return getTypeDeclType(getObjCSelDecl());
1823 }
1824
1825 /// \brief Retrieve the typedef declaration corresponding to the predefined
1826 /// Objective-C 'Class' type.
1827 TypedefDecl *getObjCClassDecl() const;
1828
1829 /// \brief Represents the Objective-C \c Class type.
1830 ///
1831 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
1832 /// pointer type, a pointer to a struct.
1833 QualType getObjCClassType() const {
1834 return getTypeDeclType(getObjCClassDecl());
1835 }
1836
1837 /// \brief Retrieve the Objective-C class declaration corresponding to
1838 /// the predefined \c Protocol class.
1839 ObjCInterfaceDecl *getObjCProtocolDecl() const;
1840
1841 /// \brief Retrieve declaration of 'BOOL' typedef
1842 TypedefDecl *getBOOLDecl() const {
1843 return BOOLDecl;
1844 }
1845
1846 /// \brief Save declaration of 'BOOL' typedef
1847 void setBOOLDecl(TypedefDecl *TD) {
1848 BOOLDecl = TD;
1849 }
1850
1851 /// \brief type of 'BOOL' type.
1852 QualType getBOOLType() const {
1853 return getTypeDeclType(getBOOLDecl());
1854 }
1855
1856 /// \brief Retrieve the type of the Objective-C \c Protocol class.
1857 QualType getObjCProtoType() const {
1858 return getObjCInterfaceType(getObjCProtocolDecl());
1859 }
1860
1861 /// \brief Retrieve the C type declaration corresponding to the predefined
1862 /// \c __builtin_va_list type.
1863 TypedefDecl *getBuiltinVaListDecl() const;
1864
1865 /// \brief Retrieve the type of the \c __builtin_va_list type.
1866 QualType getBuiltinVaListType() const {
1867 return getTypeDeclType(getBuiltinVaListDecl());
1868 }
1869
1870 /// \brief Retrieve the C type declaration corresponding to the predefined
1871 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
1872 /// for some targets.
1873 Decl *getVaListTagDecl() const;
1874
1875 /// Retrieve the C type declaration corresponding to the predefined
1876 /// \c __builtin_ms_va_list type.
1877 TypedefDecl *getBuiltinMSVaListDecl() const;
1878
1879 /// Retrieve the type of the \c __builtin_ms_va_list type.
1880 QualType getBuiltinMSVaListType() const {
1881 return getTypeDeclType(getBuiltinMSVaListDecl());
1882 }
1883
1884 /// \brief Return a type with additional \c const, \c volatile, or
1885 /// \c restrict qualifiers.
1886 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
1887 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
1888 }
1889
1890 /// \brief Un-split a SplitQualType.
1891 QualType getQualifiedType(SplitQualType split) const {
1892 return getQualifiedType(split.Ty, split.Quals);
1893 }
1894
1895 /// \brief Return a type with additional qualifiers.
1896 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
1897 if (!Qs.hasNonFastQualifiers())
1898 return T.withFastQualifiers(Qs.getFastQualifiers());
1899 QualifierCollector Qc(Qs);
1900 const Type *Ptr = Qc.strip(T);
1901 return getExtQualType(Ptr, Qc);
1902 }
1903
1904 /// \brief Return a type with additional qualifiers.
1905 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
1906 if (!Qs.hasNonFastQualifiers())
1907 return QualType(T, Qs.getFastQualifiers());
1908 return getExtQualType(T, Qs);
1909 }
1910
1911 /// \brief Return a type with the given lifetime qualifier.
1912 ///
1913 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
1914 QualType getLifetimeQualifiedType(QualType type,
1915 Qualifiers::ObjCLifetime lifetime) {
1916 assert(type.getObjCLifetime() == Qualifiers::OCL_None)(static_cast <bool> (type.getObjCLifetime() == Qualifiers
::OCL_None) ? void (0) : __assert_fail ("type.getObjCLifetime() == Qualifiers::OCL_None"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 1916, __extension__ __PRETTY_FUNCTION__))
;
1917 assert(lifetime != Qualifiers::OCL_None)(static_cast <bool> (lifetime != Qualifiers::OCL_None) ?
void (0) : __assert_fail ("lifetime != Qualifiers::OCL_None"
, "/build/llvm-toolchain-snapshot-7~svn326246/tools/clang/include/clang/AST/ASTContext.h"
, 1917, __extension__ __PRETTY_FUNCTION__))
;
1918
1919 Qualifiers qs;
1920 qs.addObjCLifetime(lifetime);
1921 return getQualifiedType(type, qs);
1922 }
1923
1924 /// getUnqualifiedObjCPointerType - Returns version of
1925 /// Objective-C pointer type with lifetime qualifier removed.
1926 QualType getUnqualifiedObjCPointerType(QualType type) const {
1927 if (!type.getTypePtr()->isObjCObjectPointerType() ||
1928 !type.getQualifiers().hasObjCLifetime())
1929 return type;
1930 Qualifiers Qs = type.getQualifiers();
1931 Qs.removeObjCLifetime();
1932 return getQualifiedType(type.getUnqualifiedType(), Qs);
1933 }
1934
1935 DeclarationNameInfo getNameForTemplate(TemplateName Name,
1936 SourceLocation NameLoc) const;
1937
1938 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
1939 UnresolvedSetIterator End) const;
1940
1941 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
1942 bool TemplateKeyword,
1943 TemplateDecl *Template) const;
1944
1945 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1946 const IdentifierInfo *Name) const;
1947 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
1948 OverloadedOperatorKind Operator) const;
1949 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
1950 TemplateName replacement) const;
1951 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
1952 const TemplateArgument &ArgPack) const;
1953
1954 enum GetBuiltinTypeError {
1955 /// No error
1956 GE_None,
1957
1958 /// Missing a type from <stdio.h>
1959 GE_Missing_stdio,
1960
1961 /// Missing a type from <setjmp.h>
1962 GE_Missing_setjmp,
1963
1964 /// Missing a type from <ucontext.h>
1965 GE_Missing_ucontext
1966 };
1967
1968 /// \brief Return the type for the specified builtin.
1969 ///
1970 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
1971 /// arguments to the builtin that are required to be integer constant
1972 /// expressions.
1973 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
1974 unsigned *IntegerConstantArgs = nullptr) const;
1975
1976private:
1977 CanQualType getFromTargetType(unsigned Type) const;
1978 TypeInfo getTypeInfoImpl(const Type *T) const;
1979
1980 //===--------------------------------------------------------------------===//
1981 // Type Predicates.
1982 //===--------------------------------------------------------------------===//
1983
1984public:
1985 /// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
1986 /// collection attributes.
1987 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
1988
1989 /// \brief Return true if the given vector types are of the same unqualified
1990 /// type or if they are equivalent to the same GCC vector type.
1991 ///
1992 /// \note This ignores whether they are target-specific (AltiVec or Neon)
1993 /// types.
1994 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
1995
1996 /// \brief Return true if this is an \c NSObject object with its \c NSObject
1997 /// attribute set.
1998 static bool isObjCNSObjectType(QualType Ty) {
1999 return Ty->isObjCNSObjectType();
2000 }
2001
2002 //===--------------------------------------------------------------------===//
2003 // Type Sizing and Analysis
2004 //===--------------------------------------------------------------------===//
2005
2006 /// \brief Return the APFloat 'semantics' for the specified scalar floating
2007 /// point type.
2008 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2009
2010 /// \brief Get the size and alignment of the specified complete type in bits.
2011 TypeInfo getTypeInfo(const Type *T) const;
2012 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2013
2014 /// \brief Get default simd alignment of the specified complete type in bits.
2015 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2016
2017 /// \brief Return the size of the specified (complete) type \p T, in bits.
2018 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2019 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2020
2021 /// \brief Return the size of the character type, in bits.
2022 uint64_t getCharWidth() const {
2023 return getTypeSize(CharTy);
2024 }
2025
2026 /// \brief Convert a size in bits to a size in characters.
2027 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2028
2029 /// \brief Convert a size in characters to a size in bits.
2030 int64_t toBits(CharUnits CharSize) const;
2031
2032 /// \brief Return the size of the specified (complete) type \p T, in
2033 /// characters.
2034 CharUnits getTypeSizeInChars(QualType T) const;
2035 CharUnits getTypeSizeInChars(const Type *T) const;
2036
2037 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
2038 /// bits.
2039 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2040 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2041
2042 /// \brief Return the ABI-specified alignment of a type, in bits, or 0 if
2043 /// the type is incomplete and we cannot determine the alignment (for
2044 /// example, from alignment attributes).
2045 unsigned getTypeAlignIfKnown(QualType T) const;
2046
2047 /// \brief Return the ABI-specified alignment of a (complete) type \p T, in
2048 /// characters.
2049 CharUnits getTypeAlignInChars(QualType T) const;
2050 CharUnits getTypeAlignInChars(const Type *T) const;
2051
2052 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2053 // type is a record, its data size is returned.
2054 std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
2055
2056 std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
2057 std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
2058
2059 /// \brief Determine if the alignment the type has was required using an
2060 /// alignment attribute.
2061 bool isAlignmentRequired(const Type *T) const;
2062 bool isAlignmentRequired(QualType T) const;
2063
2064 /// \brief Return the "preferred" alignment of the specified type \p T for
2065 /// the current target, in bits.
2066 ///
2067 /// This can be different than the ABI alignment in cases where it is
2068 /// beneficial for performance to overalign a data type.
2069 unsigned getPreferredTypeAlign(const Type *T) const;
2070
2071 /// \brief Return the default alignment for __attribute__((aligned)) on
2072 /// this target, to be used if no alignment value is specified.
2073 unsigned getTargetDefaultAlignForAttributeAligned() const;
2074
2075 /// \brief Return the alignment in bits that should be given to a
2076 /// global variable with type \p T.
2077 unsigned getAlignOfGlobalVar(QualType T) const;
2078
2079 /// \brief Return the alignment in characters that should be given to a
2080 /// global variable with type \p T.
2081 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2082
2083 /// \brief Return a conservative estimate of the alignment of the specified
2084 /// decl \p D.
2085 ///
2086 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2087 /// alignment.
2088 ///
2089 /// If \p ForAlignof, references are treated like their underlying type
2090 /// and large arrays don't get any special treatment. If not \p ForAlignof
2091 /// it computes the value expected by CodeGen: references are treated like
2092 /// pointers and large arrays get extra alignment.
2093 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2094
2095 /// \brief Get or compute information about the layout of the specified
2096 /// record (struct/union/class) \p D, which indicates its size and field
2097 /// position information.
2098 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2099
2100 /// \brief Get or compute information about the layout of the specified
2101 /// Objective-C interface.
2102 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2103 const;
2104
2105 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2106 bool Simple = false) const;
2107
2108 /// \brief Get or compute information about the layout of the specified
2109 /// Objective-C implementation.
2110 ///
2111 /// This may differ from the interface if synthesized ivars are present.
2112 const ASTRecordLayout &
2113 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2114
2115 /// \brief Get our current best idea for the key function of the
2116 /// given record decl, or nullptr if there isn't one.
2117 ///
2118 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2119 /// ...the first non-pure virtual function that is not inline at the
2120 /// point of class definition.
2121 ///
2122 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2123 /// virtual functions that are defined 'inline', which means that
2124 /// the result of this computation can change.
2125 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2126
2127 /// \brief Observe that the given method cannot be a key function.
2128 /// Checks the key-function cache for the method's class and clears it
2129 /// if matches the given declaration.
2130 ///
2131 /// This is used in ABIs where out-of-line definitions marked
2132 /// inline are not considered to be key functions.
2133 ///
2134 /// \param method should be the declaration from the class definition
2135 void setNonKeyFunction(const CXXMethodDecl *method);
2136
2137 /// Loading virtual member pointers using the virtual inheritance model
2138 /// always results in an adjustment using the vbtable even if the index is
2139 /// zero.
2140 ///
2141 /// This is usually OK because the first slot in the vbtable points
2142 /// backwards to the top of the MDC. However, the MDC might be reusing a
2143 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2144 /// points to the start of the nv-base which introduced the vbptr and *not*
2145 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2146 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2147
2148 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2149 uint64_t getFieldOffset(const ValueDecl *FD) const;
2150
2151 /// Get the offset of an ObjCIvarDecl in bits.
2152 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2153 const ObjCImplementationDecl *ID,
2154 const ObjCIvarDecl *Ivar) const;
2155
2156 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2157
2158 VTableContextBase *getVTableContext();
2159
2160 MangleContext *createMangleContext();
2161
2162 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2163 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2164
2165 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2166 void CollectInheritedProtocols(const Decl *CDecl,
2167 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2168
2169 /// \brief Return true if the specified type has unique object representations
2170 /// according to (C++17 [meta.unary.prop]p9)
2171 bool hasUniqueObjectRepresentations(QualType Ty) const;
2172
2173 //===--------------------------------------------------------------------===//
2174 // Type Operators
2175 //===--------------------------------------------------------------------===//
2176
2177 /// \brief Return the canonical (structural) type corresponding to the
2178 /// specified potentially non-canonical type \p T.
2179 ///
2180 /// The non-canonical version of a type may have many "decorated" versions of
2181 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2182 /// returned type is guaranteed to be free of any of these, allowing two
2183 /// canonical types to be compared for exact equality with a simple pointer
2184 /// comparison.
2185 CanQualType getCanonicalType(QualType T) const {
2186 return CanQualType::CreateUnsafe(T.getCanonicalType());
2187 }
2188
2189 const Type *getCanonicalType(const Type *T) const {
2190 return T->getCanonicalTypeInternal().getTypePtr();
2191 }
2192
2193 /// \brief Return the canonical parameter type corresponding to the specific
2194 /// potentially non-canonical one.
2195 ///
2196 /// Qualifiers are stripped off, functions are turned into function
2197 /// pointers, and arrays decay one level into pointers.
2198 CanQualType getCanonicalParamType(QualType T) const;
2199
2200 /// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
2201 bool hasSameType(QualType T1, QualType T2) const {
2202 return getCanonicalType(T1) == getCanonicalType(T2);
2203 }
2204 bool hasSameType(const Type *T1, const Type *T2) const {
2205 return getCanonicalType(T1) == getCanonicalType(T2);
2206 }
2207
2208 /// \brief Return this type as a completely-unqualified array type,
2209 /// capturing the qualifiers in \p Quals.
2210 ///
2211 /// This will remove the minimal amount of sugaring from the types, similar
2212 /// to the behavior of QualType::getUnqualifiedType().
2213 ///
2214 /// \param T is the qualified type, which may be an ArrayType
2215 ///
2216 /// \param Quals will receive the full set of qualifiers that were
2217 /// applied to the array.
2218 ///
2219 /// \returns if this is an array type, the completely unqualified array type
2220 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2221 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2222
2223 /// \brief Determine whether the given types are equivalent after
2224 /// cvr-qualifiers have been removed.
2225 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2226 return getCanonicalType(T1).getTypePtr() ==
2227 getCanonicalType(T2).getTypePtr();
2228 }
2229
2230 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2231 bool IsParam) const {
2232 auto SubTnullability = SubT->getNullability(*this);
2233 auto SuperTnullability = SuperT->getNullability(*this);
2234 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2235 // Neither has nullability; return true
2236 if (!SubTnullability)
2237 return true;
2238 // Both have nullability qualifier.
2239 if (*SubTnullability == *SuperTnullability ||
2240 *SubTnullability == NullabilityKind::Unspecified ||
2241 *SuperTnullability == NullabilityKind::Unspecified)
2242 return true;
2243
2244 if (IsParam) {
2245 // Ok for the superclass method parameter to be "nonnull" and the subclass
2246 // method parameter to be "nullable"
2247 return (*SuperTnullability == NullabilityKind::NonNull &&
2248 *SubTnullability == NullabilityKind::Nullable);
2249 }
2250 else {
2251 // For the return type, it's okay for the superclass method to specify
2252 // "nullable" and the subclass method specify "nonnull"
2253 return (*SuperTnullability == NullabilityKind::Nullable &&
2254 *SubTnullability == NullabilityKind::NonNull);
2255 }
2256 }
2257 return true;
2258 }
2259
2260 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2261 const ObjCMethodDecl *MethodImp);
2262
2263 bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
2264
2265 /// \brief Retrieves the "canonical" nested name specifier for a
2266 /// given nested name specifier.
2267 ///
2268 /// The canonical nested name specifier is a nested name specifier
2269 /// that uniquely identifies a type or namespace within the type
2270 /// system. For example, given:
2271 ///
2272 /// \code
2273 /// namespace N {
2274 /// struct S {
2275 /// template<typename T> struct X { typename T* type; };
2276 /// };
2277 /// }
2278 ///
2279 /// template<typename T> struct Y {
2280 /// typename N::S::X<T>::type member;
2281 /// };
2282 /// \endcode
2283 ///
2284 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2285 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2286 /// by declarations in the type system and the canonical type for
2287 /// the template type parameter 'T' is template-param-0-0.
2288 NestedNameSpecifier *
2289 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2290
2291 /// \brief Retrieves the default calling convention for the current target.
2292 CallingConv getDefaultCallingConvention(bool IsVariadic,
2293 bool IsCXXMethod) const;
2294
2295 /// \brief Retrieves the "canonical" template name that refers to a
2296 /// given template.
2297 ///
2298 /// The canonical template name is the simplest expression that can
2299 /// be used to refer to a given template. For most templates, this
2300 /// expression is just the template declaration itself. For example,
2301 /// the template std::vector can be referred to via a variety of
2302 /// names---std::vector, \::std::vector, vector (if vector is in
2303 /// scope), etc.---but all of these names map down to the same
2304 /// TemplateDecl, which is used to form the canonical template name.
2305 ///
2306 /// Dependent template names are more interesting. Here, the
2307 /// template name could be something like T::template apply or
2308 /// std::allocator<T>::template rebind, where the nested name
2309 /// specifier itself is dependent. In this case, the canonical
2310 /// template name uses the shortest form of the dependent
2311 /// nested-name-specifier, which itself contains all canonical
2312 /// types, values, and templates.
2313 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2314
2315 /// \brief Determine whether the given template names refer to the same
2316 /// template.
2317 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2318
2319 /// \brief Retrieve the "canonical" template argument.
2320 ///
2321 /// The canonical template argument is the simplest template argument
2322 /// (which may be a type, value, expression, or declaration) that
2323 /// expresses the value of the argument.
2324 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2325 const;
2326
2327 /// Type Query functions. If the type is an instance of the specified class,
2328 /// return the Type pointer for the underlying maximally pretty type. This
2329 /// is a member of ASTContext because this may need to do some amount of
2330 /// canonicalization, e.g. to move type qualifiers into the element type.
2331 const ArrayType *getAsArrayType(QualType T) const;
2332 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2333 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2334 }
2335 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2336 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2337 }
2338 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2339 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2340 }
2341 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2342 const {
2343 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2344 }
2345
2346 /// \brief Return the innermost element type of an array type.
2347 ///
2348 /// For example, will return "int" for int[m][n]
2349 QualType getBaseElementType(const ArrayType *VAT) const;
2350
2351 /// \brief Return the innermost element type of a type (which needn't
2352 /// actually be an array type).
2353 QualType getBaseElementType(QualType QT) const;
2354
2355 /// \brief Return number of constant array elements.
2356 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2357
2358 /// \brief Perform adjustment on the parameter type of a function.
2359 ///
2360 /// This routine adjusts the given parameter type @p T to the actual
2361 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2362 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2363 QualType getAdjustedParameterType(QualType T) const;
2364
2365 /// \brief Retrieve the parameter type as adjusted for use in the signature
2366 /// of a function, decaying array and function types and removing top-level
2367 /// cv-qualifiers.
2368 QualType getSignatureParameterType(QualType T) const;
2369
2370 QualType getExceptionObjectType(QualType T) const;
2371
2372 /// \brief Return the properly qualified result of decaying the specified
2373 /// array type to a pointer.
2374 ///
2375 /// This operation is non-trivial when handling typedefs etc. The canonical
2376 /// type of \p T must be an array type, this returns a pointer to a properly
2377 /// qualified element of the array.
2378 ///
2379 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2380 QualType getArrayDecayedType(QualType T) const;
2381
2382 /// \brief Return the type that \p PromotableType will promote to: C99
2383 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2384 QualType getPromotedIntegerType(QualType PromotableType) const;
2385
2386 /// \brief Recurses in pointer/array types until it finds an Objective-C
2387 /// retainable type and returns its ownership.
2388 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2389
2390 /// \brief Whether this is a promotable bitfield reference according
2391 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2392 ///
2393 /// \returns the type this bit-field will promote to, or NULL if no
2394 /// promotion occurs.
2395 QualType isPromotableBitField(Expr *E) const;
2396
2397 /// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
2398 ///
2399 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2400 /// \p LHS < \p RHS, return -1.
2401 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2402
2403 /// \brief Compare the rank of the two specified floating point types,
2404 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2405 ///
2406 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2407 /// \p LHS < \p RHS, return -1.
2408 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2409
2410 /// \brief Return a real floating point or a complex type (based on
2411 /// \p typeDomain/\p typeSize).
2412 ///
2413 /// \param typeDomain a real floating point or complex type.
2414 /// \param typeSize a real floating point or complex type.
2415 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2416 QualType typeDomain) const;
2417
2418 unsigned getTargetAddressSpace(QualType T) const {
2419 return getTargetAddressSpace(T.getQualifiers());
2420 }
2421
2422 unsigned getTargetAddressSpace(Qualifiers Q) const {
2423 return getTargetAddressSpace(Q.getAddressSpace());
2424 }
2425
2426 unsigned getTargetAddressSpace(LangAS AS) const;
2427
2428 /// Get target-dependent integer value for null pointer which is used for
2429 /// constant folding.
2430 uint64_t getTargetNullPointerValue(QualType QT) const;
2431
2432 bool addressSpaceMapManglingFor(LangAS AS) const {
2433 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2434 }
2435
2436private:
2437 // Helper for integer ordering
2438 unsigned getIntegerRank(const Type *T) const;
2439
2440public:
2441 //===--------------------------------------------------------------------===//
2442 // Type Compatibility Predicates
2443 //===--------------------------------------------------------------------===//
2444
2445 /// Compatibility predicates used to check assignment expressions.
2446 bool typesAreCompatible(QualType T1, QualType T2,
2447 bool CompareUnqualified = false); // C99 6.2.7p1
2448
2449 bool propertyTypesAreCompatible(QualType, QualType);
2450 bool typesAreBlockPointerCompatible(QualType, QualType);
2451
2452 bool isObjCIdType(QualType T) const {
2453 return T == getObjCIdType();
2454 }
2455
2456 bool isObjCClassType(QualType T) const {
2457 return T == getObjCClassType();
2458 }
2459
2460 bool isObjCSelType(QualType T) const {
2461 return T == getObjCSelType();
2462 }
2463
2464 bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
2465 bool ForCompare);
2466
2467 bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
2468
2469 // Check the safety of assignment from LHS to RHS
2470 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2471 const ObjCObjectPointerType *RHSOPT);
2472 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2473 const ObjCObjectType *RHS);
2474 bool canAssignObjCInterfacesInBlockPointer(
2475 const ObjCObjectPointerType *LHSOPT,
2476 const ObjCObjectPointerType *RHSOPT,
2477 bool BlockReturnType);
2478 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2479 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2480 const ObjCObjectPointerType *RHSOPT);
2481 bool canBindObjCObjectType(QualType To, QualType From);
2482
2483 // Functions for calculating composite types
2484 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2485 bool Unqualified = false, bool BlockReturnType = false);
2486 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2487 bool Unqualified = false);
2488 QualType mergeFunctionParameterTypes(QualType, QualType,
2489 bool OfBlockPointer = false,
2490 bool Unqualified = false);
2491 QualType mergeTransparentUnionType(QualType, QualType,
2492 bool OfBlockPointer=false,
2493 bool Unqualified = false);
2494
2495 QualType mergeObjCGCQualifiers(QualType, QualType);
2496
2497 /// This function merges the ExtParameterInfo lists of two functions. It
2498 /// returns true if the lists are compatible. The merged list is returned in
2499 /// NewParamInfos.
2500 ///
2501 /// \param FirstFnType The type of the first function.
2502 ///
2503 /// \param SecondFnType The type of the second function.
2504 ///
2505 /// \param CanUseFirst This flag is set to true if the first function's
2506 /// ExtParameterInfo list can be used as the composite list of
2507 /// ExtParameterInfo.
2508 ///
2509 /// \param CanUseSecond This flag is set to true if the second function's
2510 /// ExtParameterInfo list can be used as the composite list of
2511 /// ExtParameterInfo.
2512 ///
2513 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2514 /// empty if none of the flags are set.
2515 ///
2516 bool mergeExtParameterInfo(
2517 const FunctionProtoType *FirstFnType,
2518 const FunctionProtoType *SecondFnType,
2519 bool &CanUseFirst, bool &CanUseSecond,
2520 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2521
2522 void ResetObjCLayout(const ObjCContainerDecl *CD);
2523
2524 //===--------------------------------------------------------------------===//
2525 // Integer Predicates
2526 //===--------------------------------------------------------------------===//
2527
2528 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2529 // of bits in an integer type excluding any padding bits.
2530 unsigned getIntWidth(QualType T) const;
2531
2532 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2533 // unsigned integer type. This method takes a signed type, and returns the
2534 // corresponding unsigned integer type.
2535 QualType getCorrespondingUnsignedType(QualType T) const;
2536
2537 //===--------------------------------------------------------------------===//
2538 // Integer Values
2539 //===--------------------------------------------------------------------===//
2540
2541 /// \brief Make an APSInt of the appropriate width and signedness for the
2542 /// given \p Value and integer \p Type.
2543 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2544 // If Type is a signed integer type larger than 64 bits, we need to be sure
2545 // to sign extend Res appropriately.
2546 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2547 Res = Value;
2548 unsigned Width = getIntWidth(Type);
2549 if (Width != Res.getBitWidth())
2550 return Res.extOrTrunc(Width);
2551 return Res;
2552 }
2553
2554 bool isSentinelNullExpr(const Expr *E);
2555
2556 /// \brief Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2557 /// none exists.
2558 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2559
2560 /// \brief Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2561 /// none exists.
2562 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2563
2564 /// \brief Return true if there is at least one \@implementation in the TU.
2565 bool AnyObjCImplementation() {
2566 return !ObjCImpls.empty();
2567 }
2568
2569 /// \brief Set the implementation of ObjCInterfaceDecl.
2570 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2571 ObjCImplementationDecl *ImplD);
2572
2573 /// \brief Set the implementation of ObjCCategoryDecl.
2574 void setObjCImplementation(ObjCCategoryDecl *CatD,
2575 ObjCCategoryImplDecl *ImplD);
2576
2577 /// \brief Get the duplicate declaration of a ObjCMethod in the same
2578 /// interface, or null if none exists.
2579 const ObjCMethodDecl *
2580 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2581
2582 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2583 const ObjCMethodDecl *Redecl);
2584
2585 /// \brief Returns the Objective-C interface that \p ND belongs to if it is
2586 /// an Objective-C method/property/ivar etc. that is part of an interface,
2587 /// otherwise returns null.
2588 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2589
2590 /// \brief Set the copy inialization expression of a block var decl.
2591 void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
2592
2593 /// \brief Get the copy initialization expression of the VarDecl \p VD, or
2594 /// nullptr if none exists.
2595 Expr *getBlockVarCopyInits(const VarDecl* VD);
2596
2597 /// \brief Allocate an uninitialized TypeSourceInfo.
2598 ///
2599 /// The caller should initialize the memory held by TypeSourceInfo using
2600 /// the TypeLoc wrappers.
2601 ///
2602 /// \param T the type that will be the basis for type source info. This type
2603 /// should refer to how the declarator was written in source code, not to
2604 /// what type semantic analysis resolved the declarator to.
2605 ///
2606 /// \param Size the size of the type info to create, or 0 if the size
2607 /// should be calculated based on the type.
2608 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2609
2610 /// \brief Allocate a TypeSourceInfo where all locations have been
2611 /// initialized to a given location, which defaults to the empty
2612 /// location.
2613 TypeSourceInfo *
2614 getTrivialTypeSourceInfo(QualType T,
2615 SourceLocation Loc = SourceLocation()) const;
2616
2617 /// \brief Add a deallocation callback that will be invoked when the
2618 /// ASTContext is destroyed.
2619 ///
2620 /// \param Callback A callback function that will be invoked on destruction.
2621 ///
2622 /// \param Data Pointer data that will be provided to the callback function
2623 /// when it is called.
2624 void AddDeallocation(void (*Callback)(void*), void *Data);
2625
2626 /// If T isn't trivially destructible, calls AddDeallocation to register it
2627 /// for destruction.
2628 template <typename T>
2629 void addDestruction(T *Ptr) {
2630 if (!std::is_trivially_destructible<T>::value) {
2631 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2632 AddDeallocation(DestroyPtr, Ptr);
2633 }
2634 }
2635
2636 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2637 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2638
2639 /// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
2640 /// lazily, only when used; this is only relevant for function or file scoped
2641 /// var definitions.
2642 ///
2643 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2644 /// it is not used.
2645 bool DeclMustBeEmitted(const Decl *D);
2646
2647 /// \brief Visits all versions of a multiversioned function with the passed
2648 /// predicate.
2649 void forEachMultiversionedFunctionVersion(
2650 const FunctionDecl *FD,
2651 llvm::function_ref<void(const FunctionDecl *)> Pred) const;
2652
2653 const CXXConstructorDecl *
2654 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2655
2656 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2657 CXXConstructorDecl *CD);
2658
2659 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2660
2661 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2662
2663 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2664
2665 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2666
2667 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2668 unsigned getManglingNumber(const NamedDecl *ND) const;
2669
2670 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2671 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2672
2673 /// \brief Retrieve the context for computing mangling numbers in the given
2674 /// DeclContext.
2675 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2676
2677 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2678
2679 /// \brief Used by ParmVarDecl to store on the side the
2680 /// index of the parameter when it exceeds the size of the normal bitfield.
2681 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2682
2683 /// \brief Used by ParmVarDecl to retrieve on the side the
2684 /// index of the parameter when it exceeds the size of the normal bitfield.
2685 unsigned getParameterIndex(const ParmVarDecl *D) const;
2686
2687 /// \brief Get the storage for the constant value of a materialized temporary
2688 /// of static storage duration.
2689 APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
2690 bool MayCreate);
2691
2692 //===--------------------------------------------------------------------===//
2693 // Statistics
2694 //===--------------------------------------------------------------------===//
2695
2696 /// \brief The number of implicitly-declared default constructors.
2697 static unsigned NumImplicitDefaultConstructors;
2698
2699 /// \brief The number of implicitly-declared default constructors for
2700 /// which declarations were built.
2701 static unsigned NumImplicitDefaultConstructorsDeclared;
2702
2703 /// \brief The number of implicitly-declared copy constructors.
2704 static unsigned NumImplicitCopyConstructors;
2705
2706 /// \brief The number of implicitly-declared copy constructors for
2707 /// which declarations were built.
2708 static unsigned NumImplicitCopyConstructorsDeclared;
2709
2710 /// \brief The number of implicitly-declared move constructors.
2711 static unsigned NumImplicitMoveConstructors;
2712
2713 /// \brief The number of implicitly-declared move constructors for
2714 /// which declarations were built.
2715 static unsigned NumImplicitMoveConstructorsDeclared;
2716
2717 /// \brief The number of implicitly-declared copy assignment operators.
2718 static unsigned NumImplicitCopyAssignmentOperators;
2719
2720 /// \brief The number of implicitly-declared copy assignment operators for
2721 /// which declarations were built.
2722 static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
2723
2724 /// \brief The number of implicitly-declared move assignment operators.
2725 static unsigned NumImplicitMoveAssignmentOperators;
2726
2727 /// \brief The number of implicitly-declared move assignment operators for
2728 /// which declarations were built.
2729 static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
2730
2731 /// \brief The number of implicitly-declared destructors.
2732 static unsigned NumImplicitDestructors;
2733
2734 /// \brief The number of implicitly-declared destructors for which
2735 /// declarations were built.
2736 static unsigned NumImplicitDestructorsDeclared;
2737
2738public:
2739 /// \brief Initialize built-in types.
2740 ///
2741 /// This routine may only be invoked once for a given ASTContext object.
2742 /// It is normally invoked after ASTContext construction.
2743 ///
2744 /// \param Target The target
2745 void InitBuiltinTypes(const TargetInfo &Target,
2746 const TargetInfo *AuxTarget = nullptr);
2747
2748private:
2749 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
2750
2751 // Return the Objective-C type encoding for a given type.
2752 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
2753 bool ExpandPointedToStructures,
2754 bool ExpandStructures,
2755 const FieldDecl *Field,
2756 bool OutermostType = false,
2757 bool EncodingProperty = false,
2758 bool StructField = false,
2759 bool EncodeBlockParameters = false,
2760 bool EncodeClassNames = false,
2761 bool EncodePointerToObjCTypedef = false,
2762 QualType *NotEncodedT=nullptr) const;
2763
2764 // Adds the encoding of the structure's members.
2765 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
2766 const FieldDecl *Field,
2767 bool includeVBases = true,
2768 QualType *NotEncodedT=nullptr) const;
2769
2770public:
2771 // Adds the encoding of a method parameter or return type.
2772 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
2773 QualType T, std::string& S,
2774 bool Extended) const;
2775
2776 /// \brief Returns true if this is an inline-initialized static data member
2777 /// which is treated as a definition for MSVC compatibility.
2778 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
2779
2780 enum class InlineVariableDefinitionKind {
2781 /// Not an inline variable.
2782 None,
2783
2784 /// Weak definition of inline variable.
2785 Weak,
2786
2787 /// Weak for now, might become strong later in this TU.
2788 WeakUnknown,
2789
2790 /// Strong definition.
2791 Strong
2792 };
2793
2794 /// \brief Determine whether a definition of this inline variable should
2795 /// be treated as a weak or strong definition. For compatibility with
2796 /// C++14 and before, for a constexpr static data member, if there is an
2797 /// out-of-line declaration of the member, we may promote it from weak to
2798 /// strong.
2799 InlineVariableDefinitionKind
2800 getInlineVariableDefinitionKind(const VarDecl *VD) const;
2801
2802private:
2803 friend class DeclarationNameTable;
2804 friend class DeclContext;
2805
2806 const ASTRecordLayout &
2807 getObjCLayout(const ObjCInterfaceDecl *D,
2808 const ObjCImplementationDecl *Impl) const;
2809
2810 /// \brief A set of deallocations that should be performed when the
2811 /// ASTContext is destroyed.
2812 // FIXME: We really should have a better mechanism in the ASTContext to
2813 // manage running destructors for types which do variable sized allocation
2814 // within the AST. In some places we thread the AST bump pointer allocator
2815 // into the datastructures which avoids this mess during deallocation but is
2816 // wasteful of memory, and here we require a lot of error prone book keeping
2817 // in order to track and run destructors while we're tearing things down.
2818 using DeallocationFunctionsAndArguments =
2819 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
2820 DeallocationFunctionsAndArguments Deallocations;
2821
2822 // FIXME: This currently contains the set of StoredDeclMaps used
2823 // by DeclContext objects. This probably should not be in ASTContext,
2824 // but we include it here so that ASTContext can quickly deallocate them.
2825 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
2826
2827 std::unique_ptr<ParentMapPointers> PointerParents;
2828 std::unique_ptr<ParentMapOtherNodes> OtherParents;
2829
2830 std::unique_ptr<VTableContextBase> VTContext;
2831
2832 void ReleaseDeclContextMaps();
2833 void ReleaseParentMapEntries();
2834
2835public:
2836 enum PragmaSectionFlag : unsigned {
2837 PSF_None = 0,
2838 PSF_Read = 0x1,
2839 PSF_Write = 0x2,
2840 PSF_Execute = 0x4,
2841 PSF_Implicit = 0x8,
2842 PSF_Invalid = 0x80000000U,
2843 };
2844
2845 struct SectionInfo {
2846 DeclaratorDecl *Decl;
2847 SourceLocation PragmaSectionLocation;
2848 int SectionFlags;
2849
2850 SectionInfo() = default;
2851 SectionInfo(DeclaratorDecl *Decl,
2852 SourceLocation PragmaSectionLocation,
2853 int SectionFlags)
2854 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
2855 SectionFlags(SectionFlags) {}
2856 };
2857
2858 llvm::StringMap<SectionInfo> SectionInfos;
2859};
2860
2861/// \brief Utility function for constructing a nullary selector.
2862inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
2863 IdentifierInfo* II = &Ctx.Idents.get(name);
2864 return Ctx.Selectors.getSelector(0, &II);
2865}
2866
2867/// \brief Utility function for constructing an unary selector.
2868inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
2869 IdentifierInfo* II = &Ctx.Idents.get(name);
2870 return Ctx.Selectors.getSelector(1, &II);
2871}
2872
2873} // namespace clang
2874
2875// operator new and delete aren't allowed inside namespaces.
2876
2877/// @brief Placement new for using the ASTContext's allocator.
2878///
2879/// This placement form of operator new uses the ASTContext's allocator for
2880/// obtaining memory.
2881///
2882/// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
2883/// here need to also be made there.
2884///
2885/// We intentionally avoid using a nothrow specification here so that the calls
2886/// to this operator will not perform a null check on the result -- the
2887/// underlying allocator never returns null pointers.
2888///
2889/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2890/// @code
2891/// // Default alignment (8)
2892/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
2893/// // Specific alignment
2894/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
2895/// @endcode
2896/// Memory allocated through this placement new operator does not need to be
2897/// explicitly freed, as ASTContext will free all of this memory when it gets
2898/// destroyed. Please note that you cannot use delete on the pointer.
2899///
2900/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2901/// @param C The ASTContext that provides the allocator.
2902/// @param Alignment The alignment of the allocated memory (if the underlying
2903/// allocator supports it).
2904/// @return The allocated memory. Could be nullptr.
2905inline void *operator new(size_t Bytes, const clang::ASTContext &C,
2906 size_t Alignment) {
2907 return C.Allocate(Bytes, Alignment);
2908}
2909
2910/// @brief Placement delete companion to the new above.
2911///
2912/// This operator is just a companion to the new above. There is no way of
2913/// invoking it directly; see the new operator for more details. This operator
2914/// is called implicitly by the compiler if a placement new expression using
2915/// the ASTContext throws in the object constructor.
2916inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
2917 C.Deallocate(Ptr);
2918}
2919
2920/// This placement form of operator new[] uses the ASTContext's allocator for
2921/// obtaining memory.
2922///
2923/// We intentionally avoid using a nothrow specification here so that the calls
2924/// to this operator will not perform a null check on the result -- the
2925/// underlying allocator never returns null pointers.
2926///
2927/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
2928/// @code
2929/// // Default alignment (8)
2930/// char *data = new (Context) char[10];
2931/// // Specific alignment
2932/// char *data = new (Context, 4) char[10];
2933/// @endcode
2934/// Memory allocated through this placement new[] operator does not need to be
2935/// explicitly freed, as ASTContext will free all of this memory when it gets
2936/// destroyed. Please note that you cannot use delete on the pointer.
2937///
2938/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
2939/// @param C The ASTContext that provides the allocator.
2940/// @param Alignment The alignment of the allocated memory (if the underlying
2941/// allocator supports it).
2942/// @return The allocated memory. Could be nullptr.
2943inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
2944 size_t Alignment = 8) {
2945 return C.Allocate(Bytes, Alignment);
2946}
2947
2948/// @brief Placement delete[] companion to the new[] above.
2949///
2950/// This operator is just a companion to the new[] above. There is no way of
2951/// invoking it directly; see the new[] operator for more details. This operator
2952/// is called implicitly by the compiler if a placement new[] expression using
2953/// the ASTContext throws in the object constructor.
2954inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
2955 C.Deallocate(Ptr);
2956}
2957
2958/// \brief Create the representation of a LazyGenerationalUpdatePtr.
2959template <typename Owner, typename T,
2960 void (clang::ExternalASTSource::*Update)(Owner)>
2961typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
2962 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
2963 const clang::ASTContext &Ctx, T Value) {
2964 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
2965 // include ASTContext.h. We explicitly instantiate it for all relevant types
2966 // in ASTContext.cpp.
2967 if (auto *Source = Ctx.getExternalSource())
2968 return new (Ctx) LazyData(Source, Value);
2969 return Value;
2970}
2971
2972#endif // LLVM_CLANG_AST_ASTCONTEXT_H

/build/llvm-toolchain-snapshot-7~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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)
43
Assuming the condition is true
44
Taking true branch
1844 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
45
Null pointer value stored to field 'ExplicitInfo'
1845 ExplicitInfo->TypeAsWritten = T;
46
Access to field 'TypeAsWritten' results in a dereference of a null pointer (loaded from field 'ExplicitInfo')
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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/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~svn326246/tools/clang/include/clang/AST/DeclTemplate.h"
, 2662, __extension__ __PRETTY_FUNCTION__))
;
2663 SpecializedPartialSpecialization *PS =
2664 new (getASTContext()) SpecializedPartialSpecialization();
2665 PS->PartialSpecialization = PartialSpec;
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~svn326246/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~svn326246/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~svn326246/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~svn326246/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