Bug Summary

File:tools/clang/lib/Sema/SemaTemplate.cpp
Warning:line 5877, column 8
Called C++ object pointer is null

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-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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp

1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
12#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/DeclFriend.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/RecursiveASTVisitor.h"
19#include "clang/AST/TypeVisitor.h"
20#include "clang/Basic/Builtins.h"
21#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/Stack.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/// [temp.constr.decl]p2: A template's associated constraints are
50/// defined as a single constraint-expression derived from the introduced
51/// constraint-expressions [ ... ].
52///
53/// \param Params The template parameter list and optional requires-clause.
54///
55/// \param FD The underlying templated function declaration for a function
56/// template.
57static Expr *formAssociatedConstraints(TemplateParameterList *Params,
58 FunctionDecl *FD);
59}
60
61static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
62 FunctionDecl *FD) {
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.")((!FD && "Cannot collect constraints from function declaration yet."
) ? static_cast<void> (0) : __assert_fail ("!FD && \"Cannot collect constraints from function declaration yet.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 64, __PRETTY_FUNCTION__))
;
65 return Params->getRequiresClause();
66}
67
68/// 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.
71///
72/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
73/// is true. In all other cases it will return a TemplateDecl (or null).
74NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
75 bool AllowFunctionTemplates,
76 bool AllowDependent) {
77 D = D->getUnderlyingDecl();
78
79 if (isa<TemplateDecl>(D)) {
80 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
81 return nullptr;
82
83 return D;
84 }
85
86 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
87 // C++ [temp.local]p1:
88 // Like normal (non-template) classes, class templates have an
89 // injected-class-name (Clause 9). The injected-class-name
90 // can be used with or without a template-argument-list. When
91 // it is used without a template-argument-list, it is
92 // equivalent to the injected-class-name followed by the
93 // template-parameters of the class template enclosed in
94 // <>. When it is used with a template-argument-list, it
95 // refers to the specified class template specialization,
96 // which could be the current specialization or another
97 // specialization.
98 if (Record->isInjectedClassName()) {
99 Record = cast<CXXRecordDecl>(Record->getDeclContext());
100 if (Record->getDescribedClassTemplate())
101 return Record->getDescribedClassTemplate();
102
103 if (ClassTemplateSpecializationDecl *Spec
104 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
105 return Spec->getSpecializedTemplate();
106 }
107
108 return nullptr;
109 }
110
111 // 'using Dependent::foo;' can resolve to a template name.
112 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
113 // injected-class-name).
114 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
115 return D;
116
117 return nullptr;
118}
119
120void Sema::FilterAcceptableTemplateNames(LookupResult &R,
121 bool AllowFunctionTemplates,
122 bool AllowDependent) {
123 LookupResult::Filter filter = R.makeFilter();
124 while (filter.hasNext()) {
125 NamedDecl *Orig = filter.next();
126 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
127 filter.erase();
128 }
129 filter.done();
130}
131
132bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
133 bool AllowFunctionTemplates,
134 bool AllowDependent,
135 bool AllowNonTemplateFunctions) {
136 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
137 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
138 return true;
139 if (AllowNonTemplateFunctions &&
140 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
141 return true;
142 }
143
144 return false;
145}
146
147TemplateNameKind Sema::isTemplateName(Scope *S,
148 CXXScopeSpec &SS,
149 bool hasTemplateKeyword,
150 const UnqualifiedId &Name,
151 ParsedType ObjectTypePtr,
152 bool EnteringContext,
153 TemplateTy &TemplateResult,
154 bool &MemberOfUnknownSpecialization) {
155 assert(getLangOpts().CPlusPlus && "No template names in C!")((getLangOpts().CPlusPlus && "No template names in C!"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 155, __PRETTY_FUNCTION__))
;
156
157 DeclarationName TName;
158 MemberOfUnknownSpecialization = false;
159
160 switch (Name.getKind()) {
161 case UnqualifiedIdKind::IK_Identifier:
162 TName = DeclarationName(Name.Identifier);
163 break;
164
165 case UnqualifiedIdKind::IK_OperatorFunctionId:
166 TName = Context.DeclarationNames.getCXXOperatorName(
167 Name.OperatorFunctionId.Operator);
168 break;
169
170 case UnqualifiedIdKind::IK_LiteralOperatorId:
171 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
172 break;
173
174 default:
175 return TNK_Non_template;
176 }
177
178 QualType ObjectType = ObjectTypePtr.get();
179
180 AssumedTemplateKind AssumedTemplate;
181 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
182 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
183 MemberOfUnknownSpecialization, SourceLocation(),
184 &AssumedTemplate))
185 return TNK_Non_template;
186
187 if (AssumedTemplate != AssumedTemplateKind::None) {
188 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
189 // Let the parser know whether we found nothing or found functions; if we
190 // found nothing, we want to more carefully check whether this is actually
191 // a function template name versus some other kind of undeclared identifier.
192 return AssumedTemplate == AssumedTemplateKind::FoundNothing
193 ? TNK_Undeclared_template
194 : TNK_Function_template;
195 }
196
197 if (R.empty())
198 return TNK_Non_template;
199
200 NamedDecl *D = nullptr;
201 if (R.isAmbiguous()) {
202 // If we got an ambiguity involving a non-function template, treat this
203 // as a template name, and pick an arbitrary template for error recovery.
204 bool AnyFunctionTemplates = false;
205 for (NamedDecl *FoundD : R) {
206 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
207 if (isa<FunctionTemplateDecl>(FoundTemplate))
208 AnyFunctionTemplates = true;
209 else {
210 D = FoundTemplate;
211 break;
212 }
213 }
214 }
215
216 // If we didn't find any templates at all, this isn't a template name.
217 // Leave the ambiguity for a later lookup to diagnose.
218 if (!D && !AnyFunctionTemplates) {
219 R.suppressDiagnostics();
220 return TNK_Non_template;
221 }
222
223 // If the only templates were function templates, filter out the rest.
224 // We'll diagnose the ambiguity later.
225 if (!D)
226 FilterAcceptableTemplateNames(R);
227 }
228
229 // At this point, we have either picked a single template name declaration D
230 // or we have a non-empty set of results R containing either one template name
231 // declaration or a set of function templates.
232
233 TemplateName Template;
234 TemplateNameKind TemplateKind;
235
236 unsigned ResultCount = R.end() - R.begin();
237 if (!D && ResultCount > 1) {
238 // We assume that we'll preserve the qualifier from a function
239 // template name in other ways.
240 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
241 TemplateKind = TNK_Function_template;
242
243 // We'll do this lookup again later.
244 R.suppressDiagnostics();
245 } else {
246 if (!D) {
247 D = getAsTemplateNameDecl(*R.begin());
248 assert(D && "unambiguous result is not a template name")((D && "unambiguous result is not a template name") ?
static_cast<void> (0) : __assert_fail ("D && \"unambiguous result is not a template name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 248, __PRETTY_FUNCTION__))
;
249 }
250
251 if (isa<UnresolvedUsingValueDecl>(D)) {
252 // We don't yet know whether this is a template-name or not.
253 MemberOfUnknownSpecialization = true;
254 return TNK_Non_template;
255 }
256
257 TemplateDecl *TD = cast<TemplateDecl>(D);
258
259 if (SS.isSet() && !SS.isInvalid()) {
260 NestedNameSpecifier *Qualifier = SS.getScopeRep();
261 Template = Context.getQualifiedTemplateName(Qualifier,
262 hasTemplateKeyword, TD);
263 } else {
264 Template = TemplateName(TD);
265 }
266
267 if (isa<FunctionTemplateDecl>(TD)) {
268 TemplateKind = TNK_Function_template;
269
270 // We'll do this lookup again later.
271 R.suppressDiagnostics();
272 } else {
273 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 275, __PRETTY_FUNCTION__))
274 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 275, __PRETTY_FUNCTION__))
275 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD))((isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl
>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl
>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl
>(TD)) ? static_cast<void> (0) : __assert_fail ("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 275, __PRETTY_FUNCTION__))
;
276 TemplateKind =
277 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
278 isa<ConceptDecl>(TD) ? TNK_Concept_template :
279 TNK_Type_template;
280 }
281 }
282
283 TemplateResult = TemplateTy::make(Template);
284 return TemplateKind;
285}
286
287bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
288 SourceLocation NameLoc,
289 ParsedTemplateTy *Template) {
290 CXXScopeSpec SS;
291 bool MemberOfUnknownSpecialization = false;
292
293 // We could use redeclaration lookup here, but we don't need to: the
294 // syntactic form of a deduction guide is enough to identify it even
295 // if we can't look up the template name at all.
296 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
297 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
298 /*EnteringContext*/ false,
299 MemberOfUnknownSpecialization))
300 return false;
301
302 if (R.empty()) return false;
303 if (R.isAmbiguous()) {
304 // FIXME: Diagnose an ambiguity if we find at least one template.
305 R.suppressDiagnostics();
306 return false;
307 }
308
309 // We only treat template-names that name type templates as valid deduction
310 // guide names.
311 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
312 if (!TD || !getAsTypeTemplateDecl(TD))
313 return false;
314
315 if (Template)
316 *Template = TemplateTy::make(TemplateName(TD));
317 return true;
318}
319
320bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
321 SourceLocation IILoc,
322 Scope *S,
323 const CXXScopeSpec *SS,
324 TemplateTy &SuggestedTemplate,
325 TemplateNameKind &SuggestedKind) {
326 // We can't recover unless there's a dependent scope specifier preceding the
327 // template name.
328 // FIXME: Typo correction?
329 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
330 computeDeclContext(*SS))
331 return false;
332
333 // The code is missing a 'template' keyword prior to the dependent template
334 // name.
335 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
336 Diag(IILoc, diag::err_template_kw_missing)
337 << Qualifier << II.getName()
338 << FixItHint::CreateInsertion(IILoc, "template ");
339 SuggestedTemplate
340 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
341 SuggestedKind = TNK_Dependent_template_name;
342 return true;
343}
344
345bool Sema::LookupTemplateName(LookupResult &Found,
346 Scope *S, CXXScopeSpec &SS,
347 QualType ObjectType,
348 bool EnteringContext,
349 bool &MemberOfUnknownSpecialization,
350 SourceLocation TemplateKWLoc,
351 AssumedTemplateKind *ATK) {
352 if (ATK)
353 *ATK = AssumedTemplateKind::None;
354
355 Found.setTemplateNameLookup(true);
356
357 // Determine where to perform name lookup
358 MemberOfUnknownSpecialization = false;
359 DeclContext *LookupCtx = nullptr;
360 bool IsDependent = false;
361 if (!ObjectType.isNull()) {
362 // This nested-name-specifier occurs in a member access expression, e.g.,
363 // x->B::f, and we are looking into the type of the object.
364 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist")((!SS.isSet() && "ObjectType and scope specifier cannot coexist"
) ? static_cast<void> (0) : __assert_fail ("!SS.isSet() && \"ObjectType and scope specifier cannot coexist\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 364, __PRETTY_FUNCTION__))
;
365 LookupCtx = computeDeclContext(ObjectType);
366 IsDependent = !LookupCtx && ObjectType->isDependentType();
367 assert((IsDependent || !ObjectType->isIncompleteType() ||(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 369, __PRETTY_FUNCTION__))
368 ObjectType->castAs<TagType>()->isBeingDefined()) &&(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 369, __PRETTY_FUNCTION__))
369 "Caller should have completed object type")(((IsDependent || !ObjectType->isIncompleteType() || ObjectType
->castAs<TagType>()->isBeingDefined()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 369, __PRETTY_FUNCTION__))
;
370
371 // Template names cannot appear inside an Objective-C class or object type
372 // or a vector type.
373 //
374 // FIXME: This is wrong. For example:
375 //
376 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
377 // Vec<int> vi;
378 // vi.Vec<int>::~Vec<int>();
379 //
380 // ... should be accepted but we will not treat 'Vec' as a template name
381 // here. The right thing to do would be to check if the name is a valid
382 // vector component name, and look up a template name if not. And similarly
383 // for lookups into Objective-C class and object types, where the same
384 // problem can arise.
385 if (ObjectType->isObjCObjectOrInterfaceType() ||
386 ObjectType->isVectorType()) {
387 Found.clear();
388 return false;
389 }
390 } else if (SS.isSet()) {
391 // This nested-name-specifier occurs after another nested-name-specifier,
392 // so long into the context associated with the prior nested-name-specifier.
393 LookupCtx = computeDeclContext(SS, EnteringContext);
394 IsDependent = !LookupCtx;
395
396 // The declaration context must be complete.
397 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
398 return true;
399 }
400
401 bool ObjectTypeSearchedInScope = false;
402 bool AllowFunctionTemplatesInLookup = true;
403 if (LookupCtx) {
404 // Perform "qualified" name lookup into the declaration context we
405 // computed, which is either the type of the base of a member access
406 // expression or the declaration context associated with a prior
407 // nested-name-specifier.
408 LookupQualifiedName(Found, LookupCtx);
409
410 // FIXME: The C++ standard does not clearly specify what happens in the
411 // case where the object type is dependent, and implementations vary. In
412 // Clang, we treat a name after a . or -> as a template-name if lookup
413 // finds a non-dependent member or member of the current instantiation that
414 // is a type template, or finds no such members and lookup in the context
415 // of the postfix-expression finds a type template. In the latter case, the
416 // name is nonetheless dependent, and we may resolve it to a member of an
417 // unknown specialization when we come to instantiate the template.
418 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
419 }
420
421 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
422 // C++ [basic.lookup.classref]p1:
423 // In a class member access expression (5.2.5), if the . or -> token is
424 // immediately followed by an identifier followed by a <, the
425 // identifier must be looked up to determine whether the < is the
426 // beginning of a template argument list (14.2) or a less-than operator.
427 // The identifier is first looked up in the class of the object
428 // expression. If the identifier is not found, it is then looked up in
429 // the context of the entire postfix-expression and shall name a class
430 // template.
431 if (S)
432 LookupName(Found, S);
433
434 if (!ObjectType.isNull()) {
435 // FIXME: We should filter out all non-type templates here, particularly
436 // variable templates and concepts. But the exclusion of alias templates
437 // and template template parameters is a wording defect.
438 AllowFunctionTemplatesInLookup = false;
439 ObjectTypeSearchedInScope = true;
440 }
441
442 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
443 }
444
445 if (Found.isAmbiguous())
446 return false;
447
448 if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
449 // C++2a [temp.names]p2:
450 // A name is also considered to refer to a template if it is an
451 // unqualified-id followed by a < and name lookup finds either one or more
452 // functions or finds nothing.
453 //
454 // To keep our behavior consistent, we apply the "finds nothing" part in
455 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
456 // successfully form a call to an undeclared template-id.
457 bool AllFunctions =
458 getLangOpts().CPlusPlus2a &&
459 std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
460 return isa<FunctionDecl>(ND->getUnderlyingDecl());
461 });
462 if (AllFunctions || (Found.empty() && !IsDependent)) {
463 // If lookup found any functions, or if this is a name that can only be
464 // used for a function, then strongly assume this is a function
465 // template-id.
466 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
467 ? AssumedTemplateKind::FoundNothing
468 : AssumedTemplateKind::FoundFunctions;
469 Found.clear();
470 return false;
471 }
472 }
473
474 if (Found.empty() && !IsDependent) {
475 // If we did not find any names, attempt to correct any typos.
476 DeclarationName Name = Found.getLookupName();
477 Found.clear();
478 // Simple filter callback that, for keywords, only accepts the C++ *_cast
479 DefaultFilterCCC FilterCCC{};
480 FilterCCC.WantTypeSpecifiers = false;
481 FilterCCC.WantExpressionKeywords = false;
482 FilterCCC.WantRemainingKeywords = false;
483 FilterCCC.WantCXXNamedCasts = true;
484 if (TypoCorrection Corrected =
485 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
486 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
487 if (auto *ND = Corrected.getFoundDecl())
488 Found.addDecl(ND);
489 FilterAcceptableTemplateNames(Found);
490 if (Found.isAmbiguous()) {
491 Found.clear();
492 } else if (!Found.empty()) {
493 Found.setLookupName(Corrected.getCorrection());
494 if (LookupCtx) {
495 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
496 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
497 Name.getAsString() == CorrectedStr;
498 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
499 << Name << LookupCtx << DroppedSpecifier
500 << SS.getRange());
501 } else {
502 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
503 }
504 }
505 }
506 }
507
508 NamedDecl *ExampleLookupResult =
509 Found.empty() ? nullptr : Found.getRepresentativeDecl();
510 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
511 if (Found.empty()) {
512 if (IsDependent) {
513 MemberOfUnknownSpecialization = true;
514 return false;
515 }
516
517 // If a 'template' keyword was used, a lookup that finds only non-template
518 // names is an error.
519 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
520 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
521 << Found.getLookupName() << SS.getRange();
522 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
523 diag::note_template_kw_refers_to_non_template)
524 << Found.getLookupName();
525 return true;
526 }
527
528 return false;
529 }
530
531 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
532 !getLangOpts().CPlusPlus11) {
533 // C++03 [basic.lookup.classref]p1:
534 // [...] If the lookup in the class of the object expression finds a
535 // template, the name is also looked up in the context of the entire
536 // postfix-expression and [...]
537 //
538 // Note: C++11 does not perform this second lookup.
539 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
540 LookupOrdinaryName);
541 FoundOuter.setTemplateNameLookup(true);
542 LookupName(FoundOuter, S);
543 // FIXME: We silently accept an ambiguous lookup here, in violation of
544 // [basic.lookup]/1.
545 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
546
547 NamedDecl *OuterTemplate;
548 if (FoundOuter.empty()) {
549 // - if the name is not found, the name found in the class of the
550 // object expression is used, otherwise
551 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
552 !(OuterTemplate =
553 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
554 // - if the name is found in the context of the entire
555 // postfix-expression and does not name a class template, the name
556 // found in the class of the object expression is used, otherwise
557 FoundOuter.clear();
558 } else if (!Found.isSuppressingDiagnostics()) {
559 // - if the name found is a class template, it must refer to the same
560 // entity as the one found in the class of the object expression,
561 // otherwise the program is ill-formed.
562 if (!Found.isSingleResult() ||
563 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
564 OuterTemplate->getCanonicalDecl()) {
565 Diag(Found.getNameLoc(),
566 diag::ext_nested_name_member_ref_lookup_ambiguous)
567 << Found.getLookupName()
568 << ObjectType;
569 Diag(Found.getRepresentativeDecl()->getLocation(),
570 diag::note_ambig_member_ref_object_type)
571 << ObjectType;
572 Diag(FoundOuter.getFoundDecl()->getLocation(),
573 diag::note_ambig_member_ref_scope);
574
575 // Recover by taking the template that we found in the object
576 // expression's type.
577 }
578 }
579 }
580
581 return false;
582}
583
584void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
585 SourceLocation Less,
586 SourceLocation Greater) {
587 if (TemplateName.isInvalid())
588 return;
589
590 DeclarationNameInfo NameInfo;
591 CXXScopeSpec SS;
592 LookupNameKind LookupKind;
593
594 DeclContext *LookupCtx = nullptr;
595 NamedDecl *Found = nullptr;
596 bool MissingTemplateKeyword = false;
597
598 // Figure out what name we looked up.
599 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
600 NameInfo = DRE->getNameInfo();
601 SS.Adopt(DRE->getQualifierLoc());
602 LookupKind = LookupOrdinaryName;
603 Found = DRE->getFoundDecl();
604 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
605 NameInfo = ME->getMemberNameInfo();
606 SS.Adopt(ME->getQualifierLoc());
607 LookupKind = LookupMemberName;
608 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
609 Found = ME->getMemberDecl();
610 } else if (auto *DSDRE =
611 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
612 NameInfo = DSDRE->getNameInfo();
613 SS.Adopt(DSDRE->getQualifierLoc());
614 MissingTemplateKeyword = true;
615 } else if (auto *DSME =
616 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
617 NameInfo = DSME->getMemberNameInfo();
618 SS.Adopt(DSME->getQualifierLoc());
619 MissingTemplateKeyword = true;
620 } else {
621 llvm_unreachable("unexpected kind of potential template name")::llvm::llvm_unreachable_internal("unexpected kind of potential template name"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 621)
;
622 }
623
624 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
625 // was missing.
626 if (MissingTemplateKeyword) {
627 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
628 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
629 return;
630 }
631
632 // Try to correct the name by looking for templates and C++ named casts.
633 struct TemplateCandidateFilter : CorrectionCandidateCallback {
634 Sema &S;
635 TemplateCandidateFilter(Sema &S) : S(S) {
636 WantTypeSpecifiers = false;
637 WantExpressionKeywords = false;
638 WantRemainingKeywords = false;
639 WantCXXNamedCasts = true;
640 };
641 bool ValidateCandidate(const TypoCorrection &Candidate) override {
642 if (auto *ND = Candidate.getCorrectionDecl())
643 return S.getAsTemplateNameDecl(ND);
644 return Candidate.isKeyword();
645 }
646
647 std::unique_ptr<CorrectionCandidateCallback> clone() override {
648 return std::make_unique<TemplateCandidateFilter>(*this);
649 }
650 };
651
652 DeclarationName Name = NameInfo.getName();
653 TemplateCandidateFilter CCC(*this);
654 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
655 CTK_ErrorRecovery, LookupCtx)) {
656 auto *ND = Corrected.getFoundDecl();
657 if (ND)
658 ND = getAsTemplateNameDecl(ND);
659 if (ND || Corrected.isKeyword()) {
660 if (LookupCtx) {
661 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
662 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
663 Name.getAsString() == CorrectedStr;
664 diagnoseTypo(Corrected,
665 PDiag(diag::err_non_template_in_member_template_id_suggest)
666 << Name << LookupCtx << DroppedSpecifier
667 << SS.getRange(), false);
668 } else {
669 diagnoseTypo(Corrected,
670 PDiag(diag::err_non_template_in_template_id_suggest)
671 << Name, false);
672 }
673 if (Found)
674 Diag(Found->getLocation(),
675 diag::note_non_template_in_template_id_found);
676 return;
677 }
678 }
679
680 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
681 << Name << SourceRange(Less, Greater);
682 if (Found)
683 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
684}
685
686/// ActOnDependentIdExpression - Handle a dependent id-expression that
687/// was just parsed. This is only possible with an explicit scope
688/// specifier naming a dependent type.
689ExprResult
690Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
691 SourceLocation TemplateKWLoc,
692 const DeclarationNameInfo &NameInfo,
693 bool isAddressOfOperand,
694 const TemplateArgumentListInfo *TemplateArgs) {
695 DeclContext *DC = getFunctionLevelDeclContext();
696
697 // C++11 [expr.prim.general]p12:
698 // An id-expression that denotes a non-static data member or non-static
699 // member function of a class can only be used:
700 // (...)
701 // - if that id-expression denotes a non-static data member and it
702 // appears in an unevaluated operand.
703 //
704 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
705 // CXXDependentScopeMemberExpr. The former can instantiate to either
706 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
707 // always a MemberExpr.
708 bool MightBeCxx11UnevalField =
709 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
710
711 // Check if the nested name specifier is an enum type.
712 bool IsEnum = false;
713 if (NestedNameSpecifier *NNS = SS.getScopeRep())
714 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
715
716 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
717 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
718 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
719
720 // Since the 'this' expression is synthesized, we don't need to
721 // perform the double-lookup check.
722 NamedDecl *FirstQualifierInScope = nullptr;
723
724 return CXXDependentScopeMemberExpr::Create(
725 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
726 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
727 FirstQualifierInScope, NameInfo, TemplateArgs);
728 }
729
730 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
731}
732
733ExprResult
734Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
735 SourceLocation TemplateKWLoc,
736 const DeclarationNameInfo &NameInfo,
737 const TemplateArgumentListInfo *TemplateArgs) {
738 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
739 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
740 if (!QualifierLoc)
741 return ExprError();
742
743 return DependentScopeDeclRefExpr::Create(
744 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
745}
746
747
748/// Determine whether we would be unable to instantiate this template (because
749/// it either has no definition, or is in the process of being instantiated).
750bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
751 NamedDecl *Instantiation,
752 bool InstantiatedFromMember,
753 const NamedDecl *Pattern,
754 const NamedDecl *PatternDef,
755 TemplateSpecializationKind TSK,
756 bool Complain /*= true*/) {
757 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||((isa<TagDecl>(Instantiation) || isa<FunctionDecl>
(Instantiation) || isa<VarDecl>(Instantiation)) ? static_cast
<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 758, __PRETTY_FUNCTION__))
758 isa<VarDecl>(Instantiation))((isa<TagDecl>(Instantiation) || isa<FunctionDecl>
(Instantiation) || isa<VarDecl>(Instantiation)) ? static_cast
<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 758, __PRETTY_FUNCTION__))
;
759
760 bool IsEntityBeingDefined = false;
761 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
762 IsEntityBeingDefined = TD->isBeingDefined();
763
764 if (PatternDef && !IsEntityBeingDefined) {
765 NamedDecl *SuggestedDef = nullptr;
766 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
767 /*OnlyNeedComplete*/false)) {
768 // If we're allowed to diagnose this and recover, do so.
769 bool Recover = Complain && !isSFINAEContext();
770 if (Complain)
771 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
772 Sema::MissingImportKind::Definition, Recover);
773 return !Recover;
774 }
775 return false;
776 }
777
778 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
779 return true;
780
781 llvm::Optional<unsigned> Note;
782 QualType InstantiationTy;
783 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
784 InstantiationTy = Context.getTypeDeclType(TD);
785 if (PatternDef) {
786 Diag(PointOfInstantiation,
787 diag::err_template_instantiate_within_definition)
788 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
789 << InstantiationTy;
790 // Not much point in noting the template declaration here, since
791 // we're lexically inside it.
792 Instantiation->setInvalidDecl();
793 } else if (InstantiatedFromMember) {
794 if (isa<FunctionDecl>(Instantiation)) {
795 Diag(PointOfInstantiation,
796 diag::err_explicit_instantiation_undefined_member)
797 << /*member function*/ 1 << Instantiation->getDeclName()
798 << Instantiation->getDeclContext();
799 Note = diag::note_explicit_instantiation_here;
800 } else {
801 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!")((isa<TagDecl>(Instantiation) && "Must be a TagDecl!"
) ? static_cast<void> (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 801, __PRETTY_FUNCTION__))
;
802 Diag(PointOfInstantiation,
803 diag::err_implicit_instantiate_member_undefined)
804 << InstantiationTy;
805 Note = diag::note_member_declared_at;
806 }
807 } else {
808 if (isa<FunctionDecl>(Instantiation)) {
809 Diag(PointOfInstantiation,
810 diag::err_explicit_instantiation_undefined_func_template)
811 << Pattern;
812 Note = diag::note_explicit_instantiation_here;
813 } else if (isa<TagDecl>(Instantiation)) {
814 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
815 << (TSK != TSK_ImplicitInstantiation)
816 << InstantiationTy;
817 Note = diag::note_template_decl_here;
818 } else {
819 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!")((isa<VarDecl>(Instantiation) && "Must be a VarDecl!"
) ? static_cast<void> (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 819, __PRETTY_FUNCTION__))
;
820 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
821 Diag(PointOfInstantiation,
822 diag::err_explicit_instantiation_undefined_var_template)
823 << Instantiation;
824 Instantiation->setInvalidDecl();
825 } else
826 Diag(PointOfInstantiation,
827 diag::err_explicit_instantiation_undefined_member)
828 << /*static data member*/ 2 << Instantiation->getDeclName()
829 << Instantiation->getDeclContext();
830 Note = diag::note_explicit_instantiation_here;
831 }
832 }
833 if (Note) // Diagnostics were emitted.
834 Diag(Pattern->getLocation(), Note.getValue());
835
836 // In general, Instantiation isn't marked invalid to get more than one
837 // error for multiple undefined instantiations. But the code that does
838 // explicit declaration -> explicit definition conversion can't handle
839 // invalid declarations, so mark as invalid in that case.
840 if (TSK == TSK_ExplicitInstantiationDeclaration)
841 Instantiation->setInvalidDecl();
842 return true;
843}
844
845/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
846/// that the template parameter 'PrevDecl' is being shadowed by a new
847/// declaration at location Loc. Returns true to indicate that this is
848/// an error, and false otherwise.
849void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
850 assert(PrevDecl->isTemplateParameter() && "Not a template parameter")((PrevDecl->isTemplateParameter() && "Not a template parameter"
) ? static_cast<void> (0) : __assert_fail ("PrevDecl->isTemplateParameter() && \"Not a template parameter\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 850, __PRETTY_FUNCTION__))
;
851
852 // C++ [temp.local]p4:
853 // A template-parameter shall not be redeclared within its
854 // scope (including nested scopes).
855 //
856 // Make this a warning when MSVC compatibility is requested.
857 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
858 : diag::err_template_param_shadow;
859 Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
860 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
861}
862
863/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
864/// the parameter D to reference the templated declaration and return a pointer
865/// to the template declaration. Otherwise, do nothing to D and return null.
866TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
867 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
868 D = Temp->getTemplatedDecl();
869 return Temp;
870 }
871 return nullptr;
872}
873
874ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
875 SourceLocation EllipsisLoc) const {
876 assert(Kind == Template &&((Kind == Template && "Only template template arguments can be pack expansions here"
) ? static_cast<void> (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 877, __PRETTY_FUNCTION__))
877 "Only template template arguments can be pack expansions here")((Kind == Template && "Only template template arguments can be pack expansions here"
) ? static_cast<void> (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 877, __PRETTY_FUNCTION__))
;
878 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&((getAsTemplate().get().containsUnexpandedParameterPack() &&
"Template template argument pack expansion without packs") ?
static_cast<void> (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 879, __PRETTY_FUNCTION__))
879 "Template template argument pack expansion without packs")((getAsTemplate().get().containsUnexpandedParameterPack() &&
"Template template argument pack expansion without packs") ?
static_cast<void> (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 879, __PRETTY_FUNCTION__))
;
880 ParsedTemplateArgument Result(*this);
881 Result.EllipsisLoc = EllipsisLoc;
882 return Result;
883}
884
885static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
886 const ParsedTemplateArgument &Arg) {
887
888 switch (Arg.getKind()) {
889 case ParsedTemplateArgument::Type: {
890 TypeSourceInfo *DI;
891 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
892 if (!DI)
893 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
894 return TemplateArgumentLoc(TemplateArgument(T), DI);
895 }
896
897 case ParsedTemplateArgument::NonType: {
898 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
899 return TemplateArgumentLoc(TemplateArgument(E), E);
900 }
901
902 case ParsedTemplateArgument::Template: {
903 TemplateName Template = Arg.getAsTemplate().get();
904 TemplateArgument TArg;
905 if (Arg.getEllipsisLoc().isValid())
906 TArg = TemplateArgument(Template, Optional<unsigned int>());
907 else
908 TArg = Template;
909 return TemplateArgumentLoc(TArg,
910 Arg.getScopeSpec().getWithLocInContext(
911 SemaRef.Context),
912 Arg.getLocation(),
913 Arg.getEllipsisLoc());
914 }
915 }
916
917 llvm_unreachable("Unhandled parsed template argument")::llvm::llvm_unreachable_internal("Unhandled parsed template argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 917)
;
918}
919
920/// Translates template arguments as provided by the parser
921/// into template arguments used by semantic analysis.
922void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
923 TemplateArgumentListInfo &TemplateArgs) {
924 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
925 TemplateArgs.addArgument(translateTemplateArgument(*this,
926 TemplateArgsIn[I]));
927}
928
929static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
930 SourceLocation Loc,
931 IdentifierInfo *Name) {
932 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
933 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
934 if (PrevDecl && PrevDecl->isTemplateParameter())
935 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
936}
937
938/// Convert a parsed type into a parsed template argument. This is mostly
939/// trivial, except that we may have parsed a C++17 deduced class template
940/// specialization type, in which case we should form a template template
941/// argument instead of a type template argument.
942ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
943 TypeSourceInfo *TInfo;
944 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
945 if (T.isNull())
946 return ParsedTemplateArgument();
947 assert(TInfo && "template argument with no location")((TInfo && "template argument with no location") ? static_cast
<void> (0) : __assert_fail ("TInfo && \"template argument with no location\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 947, __PRETTY_FUNCTION__))
;
948
949 // If we might have formed a deduced template specialization type, convert
950 // it to a template template argument.
951 if (getLangOpts().CPlusPlus17) {
952 TypeLoc TL = TInfo->getTypeLoc();
953 SourceLocation EllipsisLoc;
954 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
955 EllipsisLoc = PET.getEllipsisLoc();
956 TL = PET.getPatternLoc();
957 }
958
959 CXXScopeSpec SS;
960 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
961 SS.Adopt(ET.getQualifierLoc());
962 TL = ET.getNamedTypeLoc();
963 }
964
965 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
966 TemplateName Name = DTST.getTypePtr()->getTemplateName();
967 if (SS.isSet())
968 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
969 /*HasTemplateKeyword*/ false,
970 Name.getAsTemplateDecl());
971 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
972 DTST.getTemplateNameLoc());
973 if (EllipsisLoc.isValid())
974 Result = Result.getTemplatePackExpansion(EllipsisLoc);
975 return Result;
976 }
977 }
978
979 // This is a normal type template argument. Note, if the type template
980 // argument is an injected-class-name for a template, it has a dual nature
981 // and can be used as either a type or a template. We handle that in
982 // convertTypeTemplateArgumentToTemplate.
983 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
984 ParsedType.get().getAsOpaquePtr(),
985 TInfo->getTypeLoc().getBeginLoc());
986}
987
988/// ActOnTypeParameter - Called when a C++ template type parameter
989/// (e.g., "typename T") has been parsed. Typename specifies whether
990/// the keyword "typename" was used to declare the type parameter
991/// (otherwise, "class" was used), and KeyLoc is the location of the
992/// "class" or "typename" keyword. ParamName is the name of the
993/// parameter (NULL indicates an unnamed template parameter) and
994/// ParamNameLoc is the location of the parameter name (if any).
995/// If the type parameter has a default argument, it will be added
996/// later via ActOnTypeParameterDefault.
997NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
998 SourceLocation EllipsisLoc,
999 SourceLocation KeyLoc,
1000 IdentifierInfo *ParamName,
1001 SourceLocation ParamNameLoc,
1002 unsigned Depth, unsigned Position,
1003 SourceLocation EqualLoc,
1004 ParsedType DefaultArg) {
1005 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1006, __PRETTY_FUNCTION__))
1006 "Template type parameter not in template parameter scope!")((S->isTemplateParamScope() && "Template type parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1006, __PRETTY_FUNCTION__))
;
1007
1008 bool IsParameterPack = EllipsisLoc.isValid();
1009 TemplateTypeParmDecl *Param = TemplateTypeParmDecl::Create(
1010 Context, Context.getTranslationUnitDecl(), KeyLoc, ParamNameLoc, Depth,
1011 Position, ParamName, Typename, IsParameterPack);
1012 Param->setAccess(AS_public);
1013
1014 if (Param->isParameterPack())
1015 if (auto *LSI = getEnclosingLambda())
1016 LSI->LocalPacks.push_back(Param);
1017
1018 if (ParamName) {
1019 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1020
1021 // Add the template parameter into the current scope.
1022 S->AddDecl(Param);
1023 IdResolver.AddDecl(Param);
1024 }
1025
1026 // C++0x [temp.param]p9:
1027 // A default template-argument may be specified for any kind of
1028 // template-parameter that is not a template parameter pack.
1029 if (DefaultArg && IsParameterPack) {
1030 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1031 DefaultArg = nullptr;
1032 }
1033
1034 // Handle the default argument, if provided.
1035 if (DefaultArg) {
1036 TypeSourceInfo *DefaultTInfo;
1037 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1038
1039 assert(DefaultTInfo && "expected source information for type")((DefaultTInfo && "expected source information for type"
) ? static_cast<void> (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1039, __PRETTY_FUNCTION__))
;
1040
1041 // Check for unexpanded parameter packs.
1042 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1043 UPPC_DefaultArgument))
1044 return Param;
1045
1046 // Check the template argument itself.
1047 if (CheckTemplateArgument(Param, DefaultTInfo)) {
1048 Param->setInvalidDecl();
1049 return Param;
1050 }
1051
1052 Param->setDefaultArgument(DefaultTInfo);
1053 }
1054
1055 return Param;
1056}
1057
1058/// Check that the type of a non-type template parameter is
1059/// well-formed.
1060///
1061/// \returns the (possibly-promoted) parameter type if valid;
1062/// otherwise, produces a diagnostic and returns a NULL type.
1063QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1064 SourceLocation Loc) {
1065 if (TSI->getType()->isUndeducedType()) {
1066 // C++17 [temp.dep.expr]p3:
1067 // An id-expression is type-dependent if it contains
1068 // - an identifier associated by name lookup with a non-type
1069 // template-parameter declared with a type that contains a
1070 // placeholder type (7.1.7.4),
1071 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1072 }
1073
1074 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1075}
1076
1077QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1078 SourceLocation Loc) {
1079 // We don't allow variably-modified types as the type of non-type template
1080 // parameters.
1081 if (T->isVariablyModifiedType()) {
1082 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1083 << T;
1084 return QualType();
1085 }
1086
1087 // C++ [temp.param]p4:
1088 //
1089 // A non-type template-parameter shall have one of the following
1090 // (optionally cv-qualified) types:
1091 //
1092 // -- integral or enumeration type,
1093 if (T->isIntegralOrEnumerationType() ||
1094 // -- pointer to object or pointer to function,
1095 T->isPointerType() ||
1096 // -- reference to object or reference to function,
1097 T->isReferenceType() ||
1098 // -- pointer to member,
1099 T->isMemberPointerType() ||
1100 // -- std::nullptr_t.
1101 T->isNullPtrType() ||
1102 // If T is a dependent type, we can't do the check now, so we
1103 // assume that it is well-formed.
1104 T->isDependentType() ||
1105 // Allow use of auto in template parameter declarations.
1106 T->isUndeducedType()) {
1107 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1108 // are ignored when determining its type.
1109 return T.getUnqualifiedType();
1110 }
1111
1112 // C++ [temp.param]p8:
1113 //
1114 // A non-type template-parameter of type "array of T" or
1115 // "function returning T" is adjusted to be of type "pointer to
1116 // T" or "pointer to function returning T", respectively.
1117 else if (T->isArrayType() || T->isFunctionType())
1118 return Context.getDecayedType(T);
1119
1120 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1121 << T;
1122
1123 return QualType();
1124}
1125
1126NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1127 unsigned Depth,
1128 unsigned Position,
1129 SourceLocation EqualLoc,
1130 Expr *Default) {
1131 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1132
1133 // Check that we have valid decl-specifiers specified.
1134 auto CheckValidDeclSpecifiers = [this, &D] {
1135 // C++ [temp.param]
1136 // p1
1137 // template-parameter:
1138 // ...
1139 // parameter-declaration
1140 // p2
1141 // ... A storage class shall not be specified in a template-parameter
1142 // declaration.
1143 // [dcl.typedef]p1:
1144 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1145 // of a parameter-declaration
1146 const DeclSpec &DS = D.getDeclSpec();
1147 auto EmitDiag = [this](SourceLocation Loc) {
1148 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1149 << FixItHint::CreateRemoval(Loc);
1150 };
1151 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1152 EmitDiag(DS.getStorageClassSpecLoc());
1153
1154 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1155 EmitDiag(DS.getThreadStorageClassSpecLoc());
1156
1157 // [dcl.inline]p1:
1158 // The inline specifier can be applied only to the declaration or
1159 // definition of a variable or function.
1160
1161 if (DS.isInlineSpecified())
1162 EmitDiag(DS.getInlineSpecLoc());
1163
1164 // [dcl.constexpr]p1:
1165 // The constexpr specifier shall be applied only to the definition of a
1166 // variable or variable template or the declaration of a function or
1167 // function template.
1168
1169 if (DS.hasConstexprSpecifier())
1170 EmitDiag(DS.getConstexprSpecLoc());
1171
1172 // [dcl.fct.spec]p1:
1173 // Function-specifiers can be used only in function declarations.
1174
1175 if (DS.isVirtualSpecified())
1176 EmitDiag(DS.getVirtualSpecLoc());
1177
1178 if (DS.hasExplicitSpecifier())
1179 EmitDiag(DS.getExplicitSpecLoc());
1180
1181 if (DS.isNoreturnSpecified())
1182 EmitDiag(DS.getNoreturnSpecLoc());
1183 };
1184
1185 CheckValidDeclSpecifiers();
1186
1187 if (TInfo->getType()->isUndeducedType()) {
1188 Diag(D.getIdentifierLoc(),
1189 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1190 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1191 }
1192
1193 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1194, __PRETTY_FUNCTION__))
1194 "Non-type template parameter not in template parameter scope!")((S->isTemplateParamScope() && "Non-type template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1194, __PRETTY_FUNCTION__))
;
1195 bool Invalid = false;
1196
1197 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1198 if (T.isNull()) {
1199 T = Context.IntTy; // Recover with an 'int' type.
1200 Invalid = true;
1201 }
1202
1203 CheckFunctionOrTemplateParamDeclarator(S, D);
1204
1205 IdentifierInfo *ParamName = D.getIdentifier();
1206 bool IsParameterPack = D.hasEllipsis();
1207 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1208 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1209 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1210 TInfo);
1211 Param->setAccess(AS_public);
1212
1213 if (Invalid)
1214 Param->setInvalidDecl();
1215
1216 if (Param->isParameterPack())
1217 if (auto *LSI = getEnclosingLambda())
1218 LSI->LocalPacks.push_back(Param);
1219
1220 if (ParamName) {
1221 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1222 ParamName);
1223
1224 // Add the template parameter into the current scope.
1225 S->AddDecl(Param);
1226 IdResolver.AddDecl(Param);
1227 }
1228
1229 // C++0x [temp.param]p9:
1230 // A default template-argument may be specified for any kind of
1231 // template-parameter that is not a template parameter pack.
1232 if (Default && IsParameterPack) {
1233 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1234 Default = nullptr;
1235 }
1236
1237 // Check the well-formedness of the default template argument, if provided.
1238 if (Default) {
1239 // Check for unexpanded parameter packs.
1240 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1241 return Param;
1242
1243 TemplateArgument Converted;
1244 ExprResult DefaultRes =
1245 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1246 if (DefaultRes.isInvalid()) {
1247 Param->setInvalidDecl();
1248 return Param;
1249 }
1250 Default = DefaultRes.get();
1251
1252 Param->setDefaultArgument(Default);
1253 }
1254
1255 return Param;
1256}
1257
1258/// ActOnTemplateTemplateParameter - Called when a C++ template template
1259/// parameter (e.g. T in template <template \<typename> class T> class array)
1260/// has been parsed. S is the current scope.
1261NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1262 SourceLocation TmpLoc,
1263 TemplateParameterList *Params,
1264 SourceLocation EllipsisLoc,
1265 IdentifierInfo *Name,
1266 SourceLocation NameLoc,
1267 unsigned Depth,
1268 unsigned Position,
1269 SourceLocation EqualLoc,
1270 ParsedTemplateArgument Default) {
1271 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1272, __PRETTY_FUNCTION__))
1272 "Template template parameter not in template parameter scope!")((S->isTemplateParamScope() && "Template template parameter not in template parameter scope!"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1272, __PRETTY_FUNCTION__))
;
1273
1274 // Construct the parameter object.
1275 bool IsParameterPack = EllipsisLoc.isValid();
1276 TemplateTemplateParmDecl *Param =
1277 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1278 NameLoc.isInvalid()? TmpLoc : NameLoc,
1279 Depth, Position, IsParameterPack,
1280 Name, Params);
1281 Param->setAccess(AS_public);
1282
1283 if (Param->isParameterPack())
1284 if (auto *LSI = getEnclosingLambda())
1285 LSI->LocalPacks.push_back(Param);
1286
1287 // If the template template parameter has a name, then link the identifier
1288 // into the scope and lookup mechanisms.
1289 if (Name) {
1290 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1291
1292 S->AddDecl(Param);
1293 IdResolver.AddDecl(Param);
1294 }
1295
1296 if (Params->size() == 0) {
1297 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1298 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1299 Param->setInvalidDecl();
1300 }
1301
1302 // C++0x [temp.param]p9:
1303 // A default template-argument may be specified for any kind of
1304 // template-parameter that is not a template parameter pack.
1305 if (IsParameterPack && !Default.isInvalid()) {
1306 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1307 Default = ParsedTemplateArgument();
1308 }
1309
1310 if (!Default.isInvalid()) {
1311 // Check only that we have a template template argument. We don't want to
1312 // try to check well-formedness now, because our template template parameter
1313 // might have dependent types in its template parameters, which we wouldn't
1314 // be able to match now.
1315 //
1316 // If none of the template template parameter's template arguments mention
1317 // other template parameters, we could actually perform more checking here.
1318 // However, it isn't worth doing.
1319 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1320 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1321 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1322 << DefaultArg.getSourceRange();
1323 return Param;
1324 }
1325
1326 // Check for unexpanded parameter packs.
1327 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1328 DefaultArg.getArgument().getAsTemplate(),
1329 UPPC_DefaultArgument))
1330 return Param;
1331
1332 Param->setDefaultArgument(Context, DefaultArg);
1333 }
1334
1335 return Param;
1336}
1337
1338/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1339/// constrained by RequiresClause, that contains the template parameters in
1340/// Params.
1341TemplateParameterList *
1342Sema::ActOnTemplateParameterList(unsigned Depth,
1343 SourceLocation ExportLoc,
1344 SourceLocation TemplateLoc,
1345 SourceLocation LAngleLoc,
1346 ArrayRef<NamedDecl *> Params,
1347 SourceLocation RAngleLoc,
1348 Expr *RequiresClause) {
1349 if (ExportLoc.isValid())
1350 Diag(ExportLoc, diag::warn_template_export_unsupported);
1351
1352 return TemplateParameterList::Create(
1353 Context, TemplateLoc, LAngleLoc,
1354 llvm::makeArrayRef(Params.data(), Params.size()),
1355 RAngleLoc, RequiresClause);
1356}
1357
1358static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1359 const CXXScopeSpec &SS) {
1360 if (SS.isSet())
1361 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1362}
1363
1364DeclResult Sema::CheckClassTemplate(
1365 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1366 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1367 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1368 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1369 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1370 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1371 assert(TemplateParams && TemplateParams->size() > 0 &&((TemplateParams && TemplateParams->size() > 0 &&
"No template parameters") ? static_cast<void> (0) : __assert_fail
("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1372, __PRETTY_FUNCTION__))
1372 "No template parameters")((TemplateParams && TemplateParams->size() > 0 &&
"No template parameters") ? static_cast<void> (0) : __assert_fail
("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1372, __PRETTY_FUNCTION__))
;
1373 assert(TUK != TUK_Reference && "Can only declare or define class templates")((TUK != TUK_Reference && "Can only declare or define class templates"
) ? static_cast<void> (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1373, __PRETTY_FUNCTION__))
;
1374 bool Invalid = false;
1375
1376 // Check that we can declare a template here.
1377 if (CheckTemplateDeclScope(S, TemplateParams))
1378 return true;
1379
1380 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1381 assert(Kind != TTK_Enum && "can't build template of enumerated type")((Kind != TTK_Enum && "can't build template of enumerated type"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1381, __PRETTY_FUNCTION__))
;
1382
1383 // There is no such thing as an unnamed class template.
1384 if (!Name) {
1385 Diag(KWLoc, diag::err_template_unnamed_class);
1386 return true;
1387 }
1388
1389 // Find any previous declaration with this name. For a friend with no
1390 // scope explicitly specified, we only look for tag declarations (per
1391 // C++11 [basic.lookup.elab]p2).
1392 DeclContext *SemanticContext;
1393 LookupResult Previous(*this, Name, NameLoc,
1394 (SS.isEmpty() && TUK == TUK_Friend)
1395 ? LookupTagName : LookupOrdinaryName,
1396 forRedeclarationInCurContext());
1397 if (SS.isNotEmpty() && !SS.isInvalid()) {
1398 SemanticContext = computeDeclContext(SS, true);
1399 if (!SemanticContext) {
1400 // FIXME: Horrible, horrible hack! We can't currently represent this
1401 // in the AST, and historically we have just ignored such friend
1402 // class templates, so don't complain here.
1403 Diag(NameLoc, TUK == TUK_Friend
1404 ? diag::warn_template_qualified_friend_ignored
1405 : diag::err_template_qualified_declarator_no_match)
1406 << SS.getScopeRep() << SS.getRange();
1407 return TUK != TUK_Friend;
1408 }
1409
1410 if (RequireCompleteDeclContext(SS, SemanticContext))
1411 return true;
1412
1413 // If we're adding a template to a dependent context, we may need to
1414 // rebuilding some of the types used within the template parameter list,
1415 // now that we know what the current instantiation is.
1416 if (SemanticContext->isDependentContext()) {
1417 ContextRAII SavedContext(*this, SemanticContext);
1418 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1419 Invalid = true;
1420 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1421 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1422
1423 LookupQualifiedName(Previous, SemanticContext);
1424 } else {
1425 SemanticContext = CurContext;
1426
1427 // C++14 [class.mem]p14:
1428 // If T is the name of a class, then each of the following shall have a
1429 // name different from T:
1430 // -- every member template of class T
1431 if (TUK != TUK_Friend &&
1432 DiagnoseClassNameShadow(SemanticContext,
1433 DeclarationNameInfo(Name, NameLoc)))
1434 return true;
1435
1436 LookupName(Previous, S);
1437 }
1438
1439 if (Previous.isAmbiguous())
1440 return true;
1441
1442 NamedDecl *PrevDecl = nullptr;
1443 if (Previous.begin() != Previous.end())
1444 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1445
1446 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1447 // Maybe we will complain about the shadowed template parameter.
1448 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1449 // Just pretend that we didn't see the previous declaration.
1450 PrevDecl = nullptr;
1451 }
1452
1453 // If there is a previous declaration with the same name, check
1454 // whether this is a valid redeclaration.
1455 ClassTemplateDecl *PrevClassTemplate =
1456 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1457
1458 // We may have found the injected-class-name of a class template,
1459 // class template partial specialization, or class template specialization.
1460 // In these cases, grab the template that is being defined or specialized.
1461 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1462 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1463 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1464 PrevClassTemplate
1465 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1466 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1467 PrevClassTemplate
1468 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1469 ->getSpecializedTemplate();
1470 }
1471 }
1472
1473 if (TUK == TUK_Friend) {
1474 // C++ [namespace.memdef]p3:
1475 // [...] When looking for a prior declaration of a class or a function
1476 // declared as a friend, and when the name of the friend class or
1477 // function is neither a qualified name nor a template-id, scopes outside
1478 // the innermost enclosing namespace scope are not considered.
1479 if (!SS.isSet()) {
1480 DeclContext *OutermostContext = CurContext;
1481 while (!OutermostContext->isFileContext())
1482 OutermostContext = OutermostContext->getLookupParent();
1483
1484 if (PrevDecl &&
1485 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1486 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1487 SemanticContext = PrevDecl->getDeclContext();
1488 } else {
1489 // Declarations in outer scopes don't matter. However, the outermost
1490 // context we computed is the semantic context for our new
1491 // declaration.
1492 PrevDecl = PrevClassTemplate = nullptr;
1493 SemanticContext = OutermostContext;
1494
1495 // Check that the chosen semantic context doesn't already contain a
1496 // declaration of this name as a non-tag type.
1497 Previous.clear(LookupOrdinaryName);
1498 DeclContext *LookupContext = SemanticContext;
1499 while (LookupContext->isTransparentContext())
1500 LookupContext = LookupContext->getLookupParent();
1501 LookupQualifiedName(Previous, LookupContext);
1502
1503 if (Previous.isAmbiguous())
1504 return true;
1505
1506 if (Previous.begin() != Previous.end())
1507 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1508 }
1509 }
1510 } else if (PrevDecl &&
1511 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1512 S, SS.isValid()))
1513 PrevDecl = PrevClassTemplate = nullptr;
1514
1515 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1516 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1517 if (SS.isEmpty() &&
1518 !(PrevClassTemplate &&
1519 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1520 SemanticContext->getRedeclContext()))) {
1521 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1522 Diag(Shadow->getTargetDecl()->getLocation(),
1523 diag::note_using_decl_target);
1524 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1525 // Recover by ignoring the old declaration.
1526 PrevDecl = PrevClassTemplate = nullptr;
1527 }
1528 }
1529
1530 // TODO Memory management; associated constraints are not always stored.
1531 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1532
1533 if (PrevClassTemplate) {
1534 // Ensure that the template parameter lists are compatible. Skip this check
1535 // for a friend in a dependent context: the template parameter list itself
1536 // could be dependent.
1537 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1538 !TemplateParameterListsAreEqual(TemplateParams,
1539 PrevClassTemplate->getTemplateParameters(),
1540 /*Complain=*/true,
1541 TPL_TemplateMatch))
1542 return true;
1543
1544 // Check for matching associated constraints on redeclarations.
1545 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1546 const bool RedeclACMismatch = [&] {
1547 if (!(CurAC || PrevAC))
1548 return false; // Nothing to check; no mismatch.
1549 if (CurAC && PrevAC) {
1550 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1551 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1552 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1553 if (CurACInfo == PrevACInfo)
1554 return false; // All good; no mismatch.
1555 }
1556 return true;
1557 }();
1558
1559 if (RedeclACMismatch) {
1560 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc,
1561 diag::err_template_different_associated_constraints);
1562 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(),
1563 diag::note_template_prev_declaration)
1564 << /*declaration*/ 0;
1565 return true;
1566 }
1567
1568 // C++ [temp.class]p4:
1569 // In a redeclaration, partial specialization, explicit
1570 // specialization or explicit instantiation of a class template,
1571 // the class-key shall agree in kind with the original class
1572 // template declaration (7.1.5.3).
1573 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1574 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1575 TUK == TUK_Definition, KWLoc, Name)) {
1576 Diag(KWLoc, diag::err_use_with_wrong_tag)
1577 << Name
1578 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1579 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1580 Kind = PrevRecordDecl->getTagKind();
1581 }
1582
1583 // Check for redefinition of this class template.
1584 if (TUK == TUK_Definition) {
1585 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1586 // If we have a prior definition that is not visible, treat this as
1587 // simply making that previous definition visible.
1588 NamedDecl *Hidden = nullptr;
1589 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1590 SkipBody->ShouldSkip = true;
1591 SkipBody->Previous = Def;
1592 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1593 assert(Tmpl && "original definition of a class template is not a "((Tmpl && "original definition of a class template is not a "
"class template?") ? static_cast<void> (0) : __assert_fail
("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1594, __PRETTY_FUNCTION__))
1594 "class template?")((Tmpl && "original definition of a class template is not a "
"class template?") ? static_cast<void> (0) : __assert_fail
("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1594, __PRETTY_FUNCTION__))
;
1595 makeMergedDefinitionVisible(Hidden);
1596 makeMergedDefinitionVisible(Tmpl);
1597 } else {
1598 Diag(NameLoc, diag::err_redefinition) << Name;
1599 Diag(Def->getLocation(), diag::note_previous_definition);
1600 // FIXME: Would it make sense to try to "forget" the previous
1601 // definition, as part of error recovery?
1602 return true;
1603 }
1604 }
1605 }
1606 } else if (PrevDecl) {
1607 // C++ [temp]p5:
1608 // A class template shall not have the same name as any other
1609 // template, class, function, object, enumeration, enumerator,
1610 // namespace, or type in the same scope (3.3), except as specified
1611 // in (14.5.4).
1612 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1613 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1614 return true;
1615 }
1616
1617 // Check the template parameter list of this declaration, possibly
1618 // merging in the template parameter list from the previous class
1619 // template declaration. Skip this check for a friend in a dependent
1620 // context, because the template parameter list might be dependent.
1621 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1622 CheckTemplateParameterList(
1623 TemplateParams,
1624 PrevClassTemplate
1625 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1626 : nullptr,
1627 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1628 SemanticContext->isDependentContext())
1629 ? TPC_ClassTemplateMember
1630 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1631 SkipBody))
1632 Invalid = true;
1633
1634 if (SS.isSet()) {
1635 // If the name of the template was qualified, we must be defining the
1636 // template out-of-line.
1637 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1638 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1639 : diag::err_member_decl_does_not_match)
1640 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1641 Invalid = true;
1642 }
1643 }
1644
1645 // If this is a templated friend in a dependent context we should not put it
1646 // on the redecl chain. In some cases, the templated friend can be the most
1647 // recent declaration tricking the template instantiator to make substitutions
1648 // there.
1649 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1650 bool ShouldAddRedecl
1651 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1652
1653 CXXRecordDecl *NewClass =
1654 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1655 PrevClassTemplate && ShouldAddRedecl ?
1656 PrevClassTemplate->getTemplatedDecl() : nullptr,
1657 /*DelayTypeCreation=*/true);
1658 SetNestedNameSpecifier(*this, NewClass, SS);
1659 if (NumOuterTemplateParamLists > 0)
1660 NewClass->setTemplateParameterListsInfo(
1661 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1662 NumOuterTemplateParamLists));
1663
1664 // Add alignment attributes if necessary; these attributes are checked when
1665 // the ASTContext lays out the structure.
1666 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
1667 AddAlignmentAttributesForRecord(NewClass);
1668 AddMsStructLayoutForRecord(NewClass);
1669 }
1670
1671 // Attach the associated constraints when the declaration will not be part of
1672 // a decl chain.
1673 Expr *const ACtoAttach =
1674 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1675
1676 ClassTemplateDecl *NewTemplate
1677 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1678 DeclarationName(Name), TemplateParams,
1679 NewClass, ACtoAttach);
1680
1681 if (ShouldAddRedecl)
1682 NewTemplate->setPreviousDecl(PrevClassTemplate);
1683
1684 NewClass->setDescribedClassTemplate(NewTemplate);
1685
1686 if (ModulePrivateLoc.isValid())
1687 NewTemplate->setModulePrivate();
1688
1689 // Build the type for the class template declaration now.
1690 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1691 T = Context.getInjectedClassNameType(NewClass, T);
1692 assert(T->isDependentType() && "Class template type is not dependent?")((T->isDependentType() && "Class template type is not dependent?"
) ? static_cast<void> (0) : __assert_fail ("T->isDependentType() && \"Class template type is not dependent?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1692, __PRETTY_FUNCTION__))
;
1693 (void)T;
1694
1695 // If we are providing an explicit specialization of a member that is a
1696 // class template, make a note of that.
1697 if (PrevClassTemplate &&
1698 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1699 PrevClassTemplate->setMemberSpecialization();
1700
1701 // Set the access specifier.
1702 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1703 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1704
1705 // Set the lexical context of these templates
1706 NewClass->setLexicalDeclContext(CurContext);
1707 NewTemplate->setLexicalDeclContext(CurContext);
1708
1709 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
1710 NewClass->startDefinition();
1711
1712 ProcessDeclAttributeList(S, NewClass, Attr);
1713
1714 if (PrevClassTemplate)
1715 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1716
1717 AddPushedVisibilityAttribute(NewClass);
1718 inferGslOwnerPointerAttribute(NewClass);
1719
1720 if (TUK != TUK_Friend) {
1721 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1722 Scope *Outer = S;
1723 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1724 Outer = Outer->getParent();
1725 PushOnScopeChains(NewTemplate, Outer);
1726 } else {
1727 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1728 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1729 NewClass->setAccess(PrevClassTemplate->getAccess());
1730 }
1731
1732 NewTemplate->setObjectOfFriendDecl();
1733
1734 // Friend templates are visible in fairly strange ways.
1735 if (!CurContext->isDependentContext()) {
1736 DeclContext *DC = SemanticContext->getRedeclContext();
1737 DC->makeDeclVisibleInContext(NewTemplate);
1738 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1739 PushOnScopeChains(NewTemplate, EnclosingScope,
1740 /* AddToContext = */ false);
1741 }
1742
1743 FriendDecl *Friend = FriendDecl::Create(
1744 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1745 Friend->setAccess(AS_public);
1746 CurContext->addDecl(Friend);
1747 }
1748
1749 if (PrevClassTemplate)
1750 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1751
1752 if (Invalid) {
1753 NewTemplate->setInvalidDecl();
1754 NewClass->setInvalidDecl();
1755 }
1756
1757 ActOnDocumentableDecl(NewTemplate);
1758
1759 if (SkipBody && SkipBody->ShouldSkip)
1760 return SkipBody->Previous;
1761
1762 return NewTemplate;
1763}
1764
1765namespace {
1766/// Tree transform to "extract" a transformed type from a class template's
1767/// constructor to a deduction guide.
1768class ExtractTypeForDeductionGuide
1769 : public TreeTransform<ExtractTypeForDeductionGuide> {
1770public:
1771 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1772 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1773
1774 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1775
1776 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1777 return TransformType(
1778 TLB,
1779 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1780 }
1781};
1782
1783/// Transform to convert portions of a constructor declaration into the
1784/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1785struct ConvertConstructorToDeductionGuideTransform {
1786 ConvertConstructorToDeductionGuideTransform(Sema &S,
1787 ClassTemplateDecl *Template)
1788 : SemaRef(S), Template(Template) {}
1789
1790 Sema &SemaRef;
1791 ClassTemplateDecl *Template;
1792
1793 DeclContext *DC = Template->getDeclContext();
1794 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1795 DeclarationName DeductionGuideName =
1796 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1797
1798 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1799
1800 // Index adjustment to apply to convert depth-1 template parameters into
1801 // depth-0 template parameters.
1802 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1803
1804 /// Transform a constructor declaration into a deduction guide.
1805 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1806 CXXConstructorDecl *CD) {
1807 SmallVector<TemplateArgument, 16> SubstArgs;
1808
1809 LocalInstantiationScope Scope(SemaRef);
1810
1811 // C++ [over.match.class.deduct]p1:
1812 // -- For each constructor of the class template designated by the
1813 // template-name, a function template with the following properties:
1814
1815 // -- The template parameters are the template parameters of the class
1816 // template followed by the template parameters (including default
1817 // template arguments) of the constructor, if any.
1818 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1819 if (FTD) {
1820 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1821 SmallVector<NamedDecl *, 16> AllParams;
1822 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1823 AllParams.insert(AllParams.begin(),
1824 TemplateParams->begin(), TemplateParams->end());
1825 SubstArgs.reserve(InnerParams->size());
1826
1827 // Later template parameters could refer to earlier ones, so build up
1828 // a list of substituted template arguments as we go.
1829 for (NamedDecl *Param : *InnerParams) {
1830 MultiLevelTemplateArgumentList Args;
1831 Args.addOuterTemplateArguments(SubstArgs);
1832 Args.addOuterRetainedLevel();
1833 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1834 if (!NewParam)
1835 return nullptr;
1836 AllParams.push_back(NewParam);
1837 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1838 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1839 }
1840 TemplateParams = TemplateParameterList::Create(
1841 SemaRef.Context, InnerParams->getTemplateLoc(),
1842 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1843 /*FIXME: RequiresClause*/ nullptr);
1844 }
1845
1846 // If we built a new template-parameter-list, track that we need to
1847 // substitute references to the old parameters into references to the
1848 // new ones.
1849 MultiLevelTemplateArgumentList Args;
1850 if (FTD) {
1851 Args.addOuterTemplateArguments(SubstArgs);
1852 Args.addOuterRetainedLevel();
1853 }
1854
1855 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1856 .getAsAdjusted<FunctionProtoTypeLoc>();
1857 assert(FPTL && "no prototype for constructor declaration")((FPTL && "no prototype for constructor declaration")
? static_cast<void> (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1857, __PRETTY_FUNCTION__))
;
1858
1859 // Transform the type of the function, adjusting the return type and
1860 // replacing references to the old parameters with references to the
1861 // new ones.
1862 TypeLocBuilder TLB;
1863 SmallVector<ParmVarDecl*, 8> Params;
1864 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1865 if (NewType.isNull())
1866 return nullptr;
1867 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1868
1869 return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1870 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
1871 CD->getEndLoc());
1872 }
1873
1874 /// Build a deduction guide with the specified parameter types.
1875 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1876 SourceLocation Loc = Template->getLocation();
1877
1878 // Build the requested type.
1879 FunctionProtoType::ExtProtoInfo EPI;
1880 EPI.HasTrailingReturn = true;
1881 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1882 DeductionGuideName, EPI);
1883 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1884
1885 FunctionProtoTypeLoc FPTL =
1886 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1887
1888 // Build the parameters, needed during deduction / substitution.
1889 SmallVector<ParmVarDecl*, 4> Params;
1890 for (auto T : ParamTypes) {
1891 ParmVarDecl *NewParam = ParmVarDecl::Create(
1892 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1893 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1894 NewParam->setScopeInfo(0, Params.size());
1895 FPTL.setParam(Params.size(), NewParam);
1896 Params.push_back(NewParam);
1897 }
1898
1899 return buildDeductionGuide(Template->getTemplateParameters(),
1900 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
1901 }
1902
1903private:
1904 /// Transform a constructor template parameter into a deduction guide template
1905 /// parameter, rebuilding any internal references to earlier parameters and
1906 /// renumbering as we go.
1907 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1908 MultiLevelTemplateArgumentList &Args) {
1909 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1910 // TemplateTypeParmDecl's index cannot be changed after creation, so
1911 // substitute it directly.
1912 auto *NewTTP = TemplateTypeParmDecl::Create(
1913 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1914 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
1915 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1916 TTP->isParameterPack());
1917 if (TTP->hasDefaultArgument()) {
1918 TypeSourceInfo *InstantiatedDefaultArg =
1919 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1920 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1921 if (InstantiatedDefaultArg)
1922 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1923 }
1924 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1925 NewTTP);
1926 return NewTTP;
1927 }
1928
1929 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1930 return transformTemplateParameterImpl(TTP, Args);
1931
1932 return transformTemplateParameterImpl(
1933 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1934 }
1935 template<typename TemplateParmDecl>
1936 TemplateParmDecl *
1937 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1938 MultiLevelTemplateArgumentList &Args) {
1939 // Ask the template instantiator to do the heavy lifting for us, then adjust
1940 // the index of the parameter once it's done.
1941 auto *NewParam =
1942 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1943 assert(NewParam->getDepth() == 0 && "unexpected template param depth")((NewParam->getDepth() == 0 && "unexpected template param depth"
) ? static_cast<void> (0) : __assert_fail ("NewParam->getDepth() == 0 && \"unexpected template param depth\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 1943, __PRETTY_FUNCTION__))
;
1944 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1945 return NewParam;
1946 }
1947
1948 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1949 FunctionProtoTypeLoc TL,
1950 SmallVectorImpl<ParmVarDecl*> &Params,
1951 MultiLevelTemplateArgumentList &Args) {
1952 SmallVector<QualType, 4> ParamTypes;
1953 const FunctionProtoType *T = TL.getTypePtr();
1954
1955 // -- The types of the function parameters are those of the constructor.
1956 for (auto *OldParam : TL.getParams()) {
1957 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1958 if (!NewParam)
1959 return QualType();
1960 ParamTypes.push_back(NewParam->getType());
1961 Params.push_back(NewParam);
1962 }
1963
1964 // -- The return type is the class template specialization designated by
1965 // the template-name and template arguments corresponding to the
1966 // template parameters obtained from the class template.
1967 //
1968 // We use the injected-class-name type of the primary template instead.
1969 // This has the convenient property that it is different from any type that
1970 // the user can write in a deduction-guide (because they cannot enter the
1971 // context of the template), so implicit deduction guides can never collide
1972 // with explicit ones.
1973 QualType ReturnType = DeducedType;
1974 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1975
1976 // Resolving a wording defect, we also inherit the variadicness of the
1977 // constructor.
1978 FunctionProtoType::ExtProtoInfo EPI;
1979 EPI.Variadic = T->isVariadic();
1980 EPI.HasTrailingReturn = true;
1981
1982 QualType Result = SemaRef.BuildFunctionType(
1983 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
1984 if (Result.isNull())
1985 return QualType();
1986
1987 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1988 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1989 NewTL.setLParenLoc(TL.getLParenLoc());
1990 NewTL.setRParenLoc(TL.getRParenLoc());
1991 NewTL.setExceptionSpecRange(SourceRange());
1992 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1993 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1994 NewTL.setParam(I, Params[I]);
1995
1996 return Result;
1997 }
1998
1999 ParmVarDecl *
2000 transformFunctionTypeParam(ParmVarDecl *OldParam,
2001 MultiLevelTemplateArgumentList &Args) {
2002 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2003 TypeSourceInfo *NewDI;
2004 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2005 // Expand out the one and only element in each inner pack.
2006 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2007 NewDI =
2008 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2009 OldParam->getLocation(), OldParam->getDeclName());
2010 if (!NewDI) return nullptr;
2011 NewDI =
2012 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2013 PackTL.getTypePtr()->getNumExpansions());
2014 } else
2015 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2016 OldParam->getDeclName());
2017 if (!NewDI)
2018 return nullptr;
2019
2020 // Extract the type. This (for instance) replaces references to typedef
2021 // members of the current instantiations with the definitions of those
2022 // typedefs, avoiding triggering instantiation of the deduced type during
2023 // deduction.
2024 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
2025
2026 // Resolving a wording defect, we also inherit default arguments from the
2027 // constructor.
2028 ExprResult NewDefArg;
2029 if (OldParam->hasDefaultArg()) {
2030 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
2031 if (NewDefArg.isInvalid())
2032 return nullptr;
2033 }
2034
2035 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2036 OldParam->getInnerLocStart(),
2037 OldParam->getLocation(),
2038 OldParam->getIdentifier(),
2039 NewDI->getType(),
2040 NewDI,
2041 OldParam->getStorageClass(),
2042 NewDefArg.get());
2043 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2044 OldParam->getFunctionScopeIndex());
2045 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2046 return NewParam;
2047 }
2048
2049 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
2050 ExplicitSpecifier ES, TypeSourceInfo *TInfo,
2051 SourceLocation LocStart, SourceLocation Loc,
2052 SourceLocation LocEnd) {
2053 DeclarationNameInfo Name(DeductionGuideName, Loc);
2054 ArrayRef<ParmVarDecl *> Params =
2055 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2056
2057 // Build the implicit deduction guide template.
2058 auto *Guide =
2059 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2060 TInfo->getType(), TInfo, LocEnd);
2061 Guide->setImplicit();
2062 Guide->setParams(Params);
2063
2064 for (auto *Param : Params)
2065 Param->setDeclContext(Guide);
2066
2067 auto *GuideTemplate = FunctionTemplateDecl::Create(
2068 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2069 GuideTemplate->setImplicit();
2070 Guide->setDescribedFunctionTemplate(GuideTemplate);
2071
2072 if (isa<CXXRecordDecl>(DC)) {
2073 Guide->setAccess(AS_public);
2074 GuideTemplate->setAccess(AS_public);
2075 }
2076
2077 DC->addDecl(GuideTemplate);
2078 return GuideTemplate;
2079 }
2080};
2081}
2082
2083void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2084 SourceLocation Loc) {
2085 if (CXXRecordDecl *DefRecord =
2086 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2087 TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2088 Template = DescribedTemplate ? DescribedTemplate : Template;
2089 }
2090
2091 DeclContext *DC = Template->getDeclContext();
2092 if (DC->isDependentContext())
2093 return;
2094
2095 ConvertConstructorToDeductionGuideTransform Transform(
2096 *this, cast<ClassTemplateDecl>(Template));
2097 if (!isCompleteType(Loc, Transform.DeducedType))
2098 return;
2099
2100 // Check whether we've already declared deduction guides for this template.
2101 // FIXME: Consider storing a flag on the template to indicate this.
2102 auto Existing = DC->lookup(Transform.DeductionGuideName);
2103 for (auto *D : Existing)
2104 if (D->isImplicit())
2105 return;
2106
2107 // In case we were expanding a pack when we attempted to declare deduction
2108 // guides, turn off pack expansion for everything we're about to do.
2109 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2110 // Create a template instantiation record to track the "instantiation" of
2111 // constructors into deduction guides.
2112 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2113 // this substitution process actually fail?
2114 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2115 if (BuildingDeductionGuides.isInvalid())
2116 return;
2117
2118 // Convert declared constructors into deduction guide templates.
2119 // FIXME: Skip constructors for which deduction must necessarily fail (those
2120 // for which some class template parameter without a default argument never
2121 // appears in a deduced context).
2122 bool AddedAny = false;
2123 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2124 D = D->getUnderlyingDecl();
2125 if (D->isInvalidDecl() || D->isImplicit())
2126 continue;
2127 D = cast<NamedDecl>(D->getCanonicalDecl());
2128
2129 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2130 auto *CD =
2131 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2132 // Class-scope explicit specializations (MS extension) do not result in
2133 // deduction guides.
2134 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2135 continue;
2136
2137 Transform.transformConstructor(FTD, CD);
2138 AddedAny = true;
2139 }
2140
2141 // C++17 [over.match.class.deduct]
2142 // -- If C is not defined or does not declare any constructors, an
2143 // additional function template derived as above from a hypothetical
2144 // constructor C().
2145 if (!AddedAny)
2146 Transform.buildSimpleDeductionGuide(None);
2147
2148 // -- An additional function template derived as above from a hypothetical
2149 // constructor C(C), called the copy deduction candidate.
2150 cast<CXXDeductionGuideDecl>(
2151 cast<FunctionTemplateDecl>(
2152 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2153 ->getTemplatedDecl())
2154 ->setIsCopyDeductionCandidate();
2155}
2156
2157/// Diagnose the presence of a default template argument on a
2158/// template parameter, which is ill-formed in certain contexts.
2159///
2160/// \returns true if the default template argument should be dropped.
2161static bool DiagnoseDefaultTemplateArgument(Sema &S,
2162 Sema::TemplateParamListContext TPC,
2163 SourceLocation ParamLoc,
2164 SourceRange DefArgRange) {
2165 switch (TPC) {
2166 case Sema::TPC_ClassTemplate:
2167 case Sema::TPC_VarTemplate:
2168 case Sema::TPC_TypeAliasTemplate:
2169 return false;
2170
2171 case Sema::TPC_FunctionTemplate:
2172 case Sema::TPC_FriendFunctionTemplateDefinition:
2173 // C++ [temp.param]p9:
2174 // A default template-argument shall not be specified in a
2175 // function template declaration or a function template
2176 // definition [...]
2177 // If a friend function template declaration specifies a default
2178 // template-argument, that declaration shall be a definition and shall be
2179 // the only declaration of the function template in the translation unit.
2180 // (C++98/03 doesn't have this wording; see DR226).
2181 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2182 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2183 : diag::ext_template_parameter_default_in_function_template)
2184 << DefArgRange;
2185 return false;
2186
2187 case Sema::TPC_ClassTemplateMember:
2188 // C++0x [temp.param]p9:
2189 // A default template-argument shall not be specified in the
2190 // template-parameter-lists of the definition of a member of a
2191 // class template that appears outside of the member's class.
2192 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2193 << DefArgRange;
2194 return true;
2195
2196 case Sema::TPC_FriendClassTemplate:
2197 case Sema::TPC_FriendFunctionTemplate:
2198 // C++ [temp.param]p9:
2199 // A default template-argument shall not be specified in a
2200 // friend template declaration.
2201 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2202 << DefArgRange;
2203 return true;
2204
2205 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2206 // for friend function templates if there is only a single
2207 // declaration (and it is a definition). Strange!
2208 }
2209
2210 llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2210)
;
2211}
2212
2213/// Check for unexpanded parameter packs within the template parameters
2214/// of a template template parameter, recursively.
2215static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2216 TemplateTemplateParmDecl *TTP) {
2217 // A template template parameter which is a parameter pack is also a pack
2218 // expansion.
2219 if (TTP->isParameterPack())
2220 return false;
2221
2222 TemplateParameterList *Params = TTP->getTemplateParameters();
2223 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2224 NamedDecl *P = Params->getParam(I);
2225 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2226 if (!NTTP->isParameterPack() &&
2227 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2228 NTTP->getTypeSourceInfo(),
2229 Sema::UPPC_NonTypeTemplateParameterType))
2230 return true;
2231
2232 continue;
2233 }
2234
2235 if (TemplateTemplateParmDecl *InnerTTP
2236 = dyn_cast<TemplateTemplateParmDecl>(P))
2237 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2238 return true;
2239 }
2240
2241 return false;
2242}
2243
2244/// Checks the validity of a template parameter list, possibly
2245/// considering the template parameter list from a previous
2246/// declaration.
2247///
2248/// If an "old" template parameter list is provided, it must be
2249/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2250/// template parameter list.
2251///
2252/// \param NewParams Template parameter list for a new template
2253/// declaration. This template parameter list will be updated with any
2254/// default arguments that are carried through from the previous
2255/// template parameter list.
2256///
2257/// \param OldParams If provided, template parameter list from a
2258/// previous declaration of the same template. Default template
2259/// arguments will be merged from the old template parameter list to
2260/// the new template parameter list.
2261///
2262/// \param TPC Describes the context in which we are checking the given
2263/// template parameter list.
2264///
2265/// \param SkipBody If we might have already made a prior merged definition
2266/// of this template visible, the corresponding body-skipping information.
2267/// Default argument redefinition is not an error when skipping such a body,
2268/// because (under the ODR) we can assume the default arguments are the same
2269/// as the prior merged definition.
2270///
2271/// \returns true if an error occurred, false otherwise.
2272bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2273 TemplateParameterList *OldParams,
2274 TemplateParamListContext TPC,
2275 SkipBodyInfo *SkipBody) {
2276 bool Invalid = false;
2277
2278 // C++ [temp.param]p10:
2279 // The set of default template-arguments available for use with a
2280 // template declaration or definition is obtained by merging the
2281 // default arguments from the definition (if in scope) and all
2282 // declarations in scope in the same way default function
2283 // arguments are (8.3.6).
2284 bool SawDefaultArgument = false;
2285 SourceLocation PreviousDefaultArgLoc;
2286
2287 // Dummy initialization to avoid warnings.
2288 TemplateParameterList::iterator OldParam = NewParams->end();
2289 if (OldParams)
2290 OldParam = OldParams->begin();
2291
2292 bool RemoveDefaultArguments = false;
2293 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2294 NewParamEnd = NewParams->end();
2295 NewParam != NewParamEnd; ++NewParam) {
2296 // Variables used to diagnose redundant default arguments
2297 bool RedundantDefaultArg = false;
2298 SourceLocation OldDefaultLoc;
2299 SourceLocation NewDefaultLoc;
2300
2301 // Variable used to diagnose missing default arguments
2302 bool MissingDefaultArg = false;
2303
2304 // Variable used to diagnose non-final parameter packs
2305 bool SawParameterPack = false;
2306
2307 if (TemplateTypeParmDecl *NewTypeParm
2308 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2309 // Check the presence of a default argument here.
2310 if (NewTypeParm->hasDefaultArgument() &&
2311 DiagnoseDefaultTemplateArgument(*this, TPC,
2312 NewTypeParm->getLocation(),
2313 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2314 .getSourceRange()))
2315 NewTypeParm->removeDefaultArgument();
2316
2317 // Merge default arguments for template type parameters.
2318 TemplateTypeParmDecl *OldTypeParm
2319 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2320 if (NewTypeParm->isParameterPack()) {
2321 assert(!NewTypeParm->hasDefaultArgument() &&((!NewTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2322, __PRETTY_FUNCTION__))
2322 "Parameter packs can't have a default argument!")((!NewTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2322, __PRETTY_FUNCTION__))
;
2323 SawParameterPack = true;
2324 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2325 NewTypeParm->hasDefaultArgument() &&
2326 (!SkipBody || !SkipBody->ShouldSkip)) {
2327 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2328 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2329 SawDefaultArgument = true;
2330 RedundantDefaultArg = true;
2331 PreviousDefaultArgLoc = NewDefaultLoc;
2332 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2333 // Merge the default argument from the old declaration to the
2334 // new declaration.
2335 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2336 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2337 } else if (NewTypeParm->hasDefaultArgument()) {
2338 SawDefaultArgument = true;
2339 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2340 } else if (SawDefaultArgument)
2341 MissingDefaultArg = true;
2342 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2343 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2344 // Check for unexpanded parameter packs.
2345 if (!NewNonTypeParm->isParameterPack() &&
2346 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2347 NewNonTypeParm->getTypeSourceInfo(),
2348 UPPC_NonTypeTemplateParameterType)) {
2349 Invalid = true;
2350 continue;
2351 }
2352
2353 // Check the presence of a default argument here.
2354 if (NewNonTypeParm->hasDefaultArgument() &&
2355 DiagnoseDefaultTemplateArgument(*this, TPC,
2356 NewNonTypeParm->getLocation(),
2357 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2358 NewNonTypeParm->removeDefaultArgument();
2359 }
2360
2361 // Merge default arguments for non-type template parameters
2362 NonTypeTemplateParmDecl *OldNonTypeParm
2363 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2364 if (NewNonTypeParm->isParameterPack()) {
2365 assert(!NewNonTypeParm->hasDefaultArgument() &&((!NewNonTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2366, __PRETTY_FUNCTION__))
2366 "Parameter packs can't have a default argument!")((!NewNonTypeParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2366, __PRETTY_FUNCTION__))
;
2367 if (!NewNonTypeParm->isPackExpansion())
2368 SawParameterPack = true;
2369 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2370 NewNonTypeParm->hasDefaultArgument() &&
2371 (!SkipBody || !SkipBody->ShouldSkip)) {
2372 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2373 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2374 SawDefaultArgument = true;
2375 RedundantDefaultArg = true;
2376 PreviousDefaultArgLoc = NewDefaultLoc;
2377 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2378 // Merge the default argument from the old declaration to the
2379 // new declaration.
2380 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2381 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2382 } else if (NewNonTypeParm->hasDefaultArgument()) {
2383 SawDefaultArgument = true;
2384 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2385 } else if (SawDefaultArgument)
2386 MissingDefaultArg = true;
2387 } else {
2388 TemplateTemplateParmDecl *NewTemplateParm
2389 = cast<TemplateTemplateParmDecl>(*NewParam);
2390
2391 // Check for unexpanded parameter packs, recursively.
2392 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2393 Invalid = true;
2394 continue;
2395 }
2396
2397 // Check the presence of a default argument here.
2398 if (NewTemplateParm->hasDefaultArgument() &&
2399 DiagnoseDefaultTemplateArgument(*this, TPC,
2400 NewTemplateParm->getLocation(),
2401 NewTemplateParm->getDefaultArgument().getSourceRange()))
2402 NewTemplateParm->removeDefaultArgument();
2403
2404 // Merge default arguments for template template parameters
2405 TemplateTemplateParmDecl *OldTemplateParm
2406 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2407 if (NewTemplateParm->isParameterPack()) {
2408 assert(!NewTemplateParm->hasDefaultArgument() &&((!NewTemplateParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2409, __PRETTY_FUNCTION__))
2409 "Parameter packs can't have a default argument!")((!NewTemplateParm->hasDefaultArgument() && "Parameter packs can't have a default argument!"
) ? static_cast<void> (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 2409, __PRETTY_FUNCTION__))
;
2410 if (!NewTemplateParm->isPackExpansion())
2411 SawParameterPack = true;
2412 } else if (OldTemplateParm &&
2413 hasVisibleDefaultArgument(OldTemplateParm) &&
2414 NewTemplateParm->hasDefaultArgument() &&
2415 (!SkipBody || !SkipBody->ShouldSkip)) {
2416 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2417 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2418 SawDefaultArgument = true;
2419 RedundantDefaultArg = true;
2420 PreviousDefaultArgLoc = NewDefaultLoc;
2421 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2422 // Merge the default argument from the old declaration to the
2423 // new declaration.
2424 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2425 PreviousDefaultArgLoc
2426 = OldTemplateParm->getDefaultArgument().getLocation();
2427 } else if (NewTemplateParm->hasDefaultArgument()) {
2428 SawDefaultArgument = true;
2429 PreviousDefaultArgLoc
2430 = NewTemplateParm->getDefaultArgument().getLocation();
2431 } else if (SawDefaultArgument)
2432 MissingDefaultArg = true;
2433 }
2434
2435 // C++11 [temp.param]p11:
2436 // If a template parameter of a primary class template or alias template
2437 // is a template parameter pack, it shall be the last template parameter.
2438 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2439 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2440 TPC == TPC_TypeAliasTemplate)) {
2441 Diag((*NewParam)->getLocation(),
2442 diag::err_template_param_pack_must_be_last_template_parameter);
2443 Invalid = true;
2444 }
2445
2446 if (RedundantDefaultArg) {
2447 // C++ [temp.param]p12:
2448 // A template-parameter shall not be given default arguments
2449 // by two different declarations in the same scope.
2450 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2451 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2452 Invalid = true;
2453 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2454 // C++ [temp.param]p11:
2455 // If a template-parameter of a class template has a default
2456 // template-argument, each subsequent template-parameter shall either
2457 // have a default template-argument supplied or be a template parameter
2458 // pack.
2459 Diag((*NewParam)->getLocation(),
2460 diag::err_template_param_default_arg_missing);
2461 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2462 Invalid = true;
2463 RemoveDefaultArguments = true;
2464 }
2465
2466 // If we have an old template parameter list that we're merging
2467 // in, move on to the next parameter.
2468 if (OldParams)
2469 ++OldParam;
2470 }
2471
2472 // We were missing some default arguments at the end of the list, so remove
2473 // all of the default arguments.
2474 if (RemoveDefaultArguments) {
2475 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2476 NewParamEnd = NewParams->end();
2477 NewParam != NewParamEnd; ++NewParam) {
2478 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2479 TTP->removeDefaultArgument();
2480 else if (NonTypeTemplateParmDecl *NTTP
2481 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2482 NTTP->removeDefaultArgument();
2483 else
2484 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2485 }
2486 }
2487
2488 return Invalid;
2489}
2490
2491namespace {
2492
2493/// A class which looks for a use of a certain level of template
2494/// parameter.
2495struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2496 typedef RecursiveASTVisitor<DependencyChecker> super;
2497
2498 unsigned Depth;
2499
2500 // Whether we're looking for a use of a template parameter that makes the
2501 // overall construct type-dependent / a dependent type. This is strictly
2502 // best-effort for now; we may fail to match at all for a dependent type
2503 // in some cases if this is set.
2504 bool IgnoreNonTypeDependent;
2505
2506 bool Match;
2507 SourceLocation MatchLoc;
2508
2509 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2510 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2511 Match(false) {}
2512
2513 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2514 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2515 NamedDecl *ND = Params->getParam(0);
2516 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2517 Depth = PD->getDepth();
2518 } else if (NonTypeTemplateParmDecl *PD =
2519 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2520 Depth = PD->getDepth();
2521 } else {
2522 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2523 }
2524 }
2525
2526 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2527 if (ParmDepth >= Depth) {
2528 Match = true;
2529 MatchLoc = Loc;
2530 return true;
2531 }
2532 return false;
2533 }
2534
2535 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2536 // Prune out non-type-dependent expressions if requested. This can
2537 // sometimes result in us failing to find a template parameter reference
2538 // (if a value-dependent expression creates a dependent type), but this
2539 // mode is best-effort only.
2540 if (auto *E = dyn_cast_or_null<Expr>(S))
2541 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2542 return true;
2543 return super::TraverseStmt(S, Q);
2544 }
2545
2546 bool TraverseTypeLoc(TypeLoc TL) {
2547 if (IgnoreNonTypeDependent && !TL.isNull() &&
2548 !TL.getType()->isDependentType())
2549 return true;
2550 return super::TraverseTypeLoc(TL);
2551 }
2552
2553 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2554 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2555 }
2556
2557 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2558 // For a best-effort search, keep looking until we find a location.
2559 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2560 }
2561
2562 bool TraverseTemplateName(TemplateName N) {
2563 if (TemplateTemplateParmDecl *PD =
2564 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2565 if (Matches(PD->getDepth()))
2566 return false;
2567 return super::TraverseTemplateName(N);
2568 }
2569
2570 bool VisitDeclRefExpr(DeclRefExpr *E) {
2571 if (NonTypeTemplateParmDecl *PD =
2572 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2573 if (Matches(PD->getDepth(), E->getExprLoc()))
2574 return false;
2575 return super::VisitDeclRefExpr(E);
2576 }
2577
2578 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2579 return TraverseType(T->getReplacementType());
2580 }
2581
2582 bool
2583 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2584 return TraverseTemplateArgument(T->getArgumentPack());
2585 }
2586
2587 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2588 return TraverseType(T->getInjectedSpecializationType());
2589 }
2590};
2591} // end anonymous namespace
2592
2593/// Determines whether a given type depends on the given parameter
2594/// list.
2595static bool
2596DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2597 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2598 Checker.TraverseType(T);
2599 return Checker.Match;
2600}
2601
2602// Find the source range corresponding to the named type in the given
2603// nested-name-specifier, if any.
2604static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2605 QualType T,
2606 const CXXScopeSpec &SS) {
2607 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2608 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2609 if (const Type *CurType = NNS->getAsType()) {
2610 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2611 return NNSLoc.getTypeLoc().getSourceRange();
2612 } else
2613 break;
2614
2615 NNSLoc = NNSLoc.getPrefix();
2616 }
2617
2618 return SourceRange();
2619}
2620
2621/// Match the given template parameter lists to the given scope
2622/// specifier, returning the template parameter list that applies to the
2623/// name.
2624///
2625/// \param DeclStartLoc the start of the declaration that has a scope
2626/// specifier or a template parameter list.
2627///
2628/// \param DeclLoc The location of the declaration itself.
2629///
2630/// \param SS the scope specifier that will be matched to the given template
2631/// parameter lists. This scope specifier precedes a qualified name that is
2632/// being declared.
2633///
2634/// \param TemplateId The template-id following the scope specifier, if there
2635/// is one. Used to check for a missing 'template<>'.
2636///
2637/// \param ParamLists the template parameter lists, from the outermost to the
2638/// innermost template parameter lists.
2639///
2640/// \param IsFriend Whether to apply the slightly different rules for
2641/// matching template parameters to scope specifiers in friend
2642/// declarations.
2643///
2644/// \param IsMemberSpecialization will be set true if the scope specifier
2645/// denotes a fully-specialized type, and therefore this is a declaration of
2646/// a member specialization.
2647///
2648/// \returns the template parameter list, if any, that corresponds to the
2649/// name that is preceded by the scope specifier @p SS. This template
2650/// parameter list may have template parameters (if we're declaring a
2651/// template) or may have no template parameters (if we're declaring a
2652/// template specialization), or may be NULL (if what we're declaring isn't
2653/// itself a template).
2654TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2655 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2656 TemplateIdAnnotation *TemplateId,
2657 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2658 bool &IsMemberSpecialization, bool &Invalid) {
2659 IsMemberSpecialization = false;
2660 Invalid = false;
2661
2662 // The sequence of nested types to which we will match up the template
2663 // parameter lists. We first build this list by starting with the type named
2664 // by the nested-name-specifier and walking out until we run out of types.
2665 SmallVector<QualType, 4> NestedTypes;
2666 QualType T;
2667 if (SS.getScopeRep()) {
2668 if (CXXRecordDecl *Record
2669 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2670 T = Context.getTypeDeclType(Record);
2671 else
2672 T = QualType(SS.getScopeRep()->getAsType(), 0);
2673 }
2674
2675 // If we found an explicit specialization that prevents us from needing
2676 // 'template<>' headers, this will be set to the location of that
2677 // explicit specialization.
2678 SourceLocation ExplicitSpecLoc;
2679
2680 while (!T.isNull()) {
2681 NestedTypes.push_back(T);
2682
2683 // Retrieve the parent of a record type.
2684 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2685 // If this type is an explicit specialization, we're done.
2686 if (ClassTemplateSpecializationDecl *Spec
2687 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2688 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2689 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2690 ExplicitSpecLoc = Spec->getLocation();
2691 break;
2692 }
2693 } else if (Record->getTemplateSpecializationKind()
2694 == TSK_ExplicitSpecialization) {
2695 ExplicitSpecLoc = Record->getLocation();
2696 break;
2697 }
2698
2699 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2700 T = Context.getTypeDeclType(Parent);
2701 else
2702 T = QualType();
2703 continue;
2704 }
2705
2706 if (const TemplateSpecializationType *TST
2707 = T->getAs<TemplateSpecializationType>()) {
2708 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2709 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2710 T = Context.getTypeDeclType(Parent);
2711 else
2712 T = QualType();
2713 continue;
2714 }
2715 }
2716
2717 // Look one step prior in a dependent template specialization type.
2718 if (const DependentTemplateSpecializationType *DependentTST
2719 = T->getAs<DependentTemplateSpecializationType>()) {
2720 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2721 T = QualType(NNS->getAsType(), 0);
2722 else
2723 T = QualType();
2724 continue;
2725 }
2726
2727 // Look one step prior in a dependent name type.
2728 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2729 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2730 T = QualType(NNS->getAsType(), 0);
2731 else
2732 T = QualType();
2733 continue;
2734 }
2735
2736 // Retrieve the parent of an enumeration type.
2737 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2738 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2739 // check here.
2740 EnumDecl *Enum = EnumT->getDecl();
2741
2742 // Get to the parent type.
2743 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2744 T = Context.getTypeDeclType(Parent);
2745 else
2746 T = QualType();
2747 continue;
2748 }
2749
2750 T = QualType();
2751 }
2752 // Reverse the nested types list, since we want to traverse from the outermost
2753 // to the innermost while checking template-parameter-lists.
2754 std::reverse(NestedTypes.begin(), NestedTypes.end());
2755
2756 // C++0x [temp.expl.spec]p17:
2757 // A member or a member template may be nested within many
2758 // enclosing class templates. In an explicit specialization for
2759 // such a member, the member declaration shall be preceded by a
2760 // template<> for each enclosing class template that is
2761 // explicitly specialized.
2762 bool SawNonEmptyTemplateParameterList = false;
2763
2764 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2765 if (SawNonEmptyTemplateParameterList) {
2766 Diag(DeclLoc, diag::err_specialize_member_of_template)
2767 << !Recovery << Range;
2768 Invalid = true;
2769 IsMemberSpecialization = false;
2770 return true;
2771 }
2772
2773 return false;
2774 };
2775
2776 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2777 // Check that we can have an explicit specialization here.
2778 if (CheckExplicitSpecialization(Range, true))
2779 return true;
2780
2781 // We don't have a template header, but we should.
2782 SourceLocation ExpectedTemplateLoc;
2783 if (!ParamLists.empty())
2784 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2785 else
2786 ExpectedTemplateLoc = DeclStartLoc;
2787
2788 Diag(DeclLoc, diag::err_template_spec_needs_header)
2789 << Range
2790 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2791 return false;
2792 };
2793
2794 unsigned ParamIdx = 0;
2795 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2796 ++TypeIdx) {
2797 T = NestedTypes[TypeIdx];
2798
2799 // Whether we expect a 'template<>' header.
2800 bool NeedEmptyTemplateHeader = false;
2801
2802 // Whether we expect a template header with parameters.
2803 bool NeedNonemptyTemplateHeader = false;
2804
2805 // For a dependent type, the set of template parameters that we
2806 // expect to see.
2807 TemplateParameterList *ExpectedTemplateParams = nullptr;
2808
2809 // C++0x [temp.expl.spec]p15:
2810 // A member or a member template may be nested within many enclosing
2811 // class templates. In an explicit specialization for such a member, the
2812 // member declaration shall be preceded by a template<> for each
2813 // enclosing class template that is explicitly specialized.
2814 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2815 if (ClassTemplatePartialSpecializationDecl *Partial
2816 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2817 ExpectedTemplateParams = Partial->getTemplateParameters();
2818 NeedNonemptyTemplateHeader = true;
2819 } else if (Record->isDependentType()) {
2820 if (Record->getDescribedClassTemplate()) {
2821 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2822 ->getTemplateParameters();
2823 NeedNonemptyTemplateHeader = true;
2824 }
2825 } else if (ClassTemplateSpecializationDecl *Spec
2826 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2827 // C++0x [temp.expl.spec]p4:
2828 // Members of an explicitly specialized class template are defined
2829 // in the same manner as members of normal classes, and not using
2830 // the template<> syntax.
2831 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2832 NeedEmptyTemplateHeader = true;
2833 else
2834 continue;
2835 } else if (Record->getTemplateSpecializationKind()) {
2836 if (Record->getTemplateSpecializationKind()
2837 != TSK_ExplicitSpecialization &&
2838 TypeIdx == NumTypes - 1)
2839 IsMemberSpecialization = true;
2840
2841 continue;
2842 }
2843 } else if (const TemplateSpecializationType *TST
2844 = T->getAs<TemplateSpecializationType>()) {
2845 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2846 ExpectedTemplateParams = Template->getTemplateParameters();
2847 NeedNonemptyTemplateHeader = true;
2848 }
2849 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2850 // FIXME: We actually could/should check the template arguments here
2851 // against the corresponding template parameter list.
2852 NeedNonemptyTemplateHeader = false;
2853 }
2854
2855 // C++ [temp.expl.spec]p16:
2856 // In an explicit specialization declaration for a member of a class
2857 // template or a member template that ap- pears in namespace scope, the
2858 // member template and some of its enclosing class templates may remain
2859 // unspecialized, except that the declaration shall not explicitly
2860 // specialize a class member template if its en- closing class templates
2861 // are not explicitly specialized as well.
2862 if (ParamIdx < ParamLists.size()) {
2863 if (ParamLists[ParamIdx]->size() == 0) {
2864 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2865 false))
2866 return nullptr;
2867 } else
2868 SawNonEmptyTemplateParameterList = true;
2869 }
2870
2871 if (NeedEmptyTemplateHeader) {
2872 // If we're on the last of the types, and we need a 'template<>' header
2873 // here, then it's a member specialization.
2874 if (TypeIdx == NumTypes - 1)
2875 IsMemberSpecialization = true;
2876
2877 if (ParamIdx < ParamLists.size()) {
2878 if (ParamLists[ParamIdx]->size() > 0) {
2879 // The header has template parameters when it shouldn't. Complain.
2880 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2881 diag::err_template_param_list_matches_nontemplate)
2882 << T
2883 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2884 ParamLists[ParamIdx]->getRAngleLoc())
2885 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2886 Invalid = true;
2887 return nullptr;
2888 }
2889
2890 // Consume this template header.
2891 ++ParamIdx;
2892 continue;
2893 }
2894
2895 if (!IsFriend)
2896 if (DiagnoseMissingExplicitSpecialization(
2897 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2898 return nullptr;
2899
2900 continue;
2901 }
2902
2903 if (NeedNonemptyTemplateHeader) {
2904 // In friend declarations we can have template-ids which don't
2905 // depend on the corresponding template parameter lists. But
2906 // assume that empty parameter lists are supposed to match this
2907 // template-id.
2908 if (IsFriend && T->isDependentType()) {
2909 if (ParamIdx < ParamLists.size() &&
2910 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2911 ExpectedTemplateParams = nullptr;
2912 else
2913 continue;
2914 }
2915
2916 if (ParamIdx < ParamLists.size()) {
2917 // Check the template parameter list, if we can.
2918 if (ExpectedTemplateParams &&
2919 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2920 ExpectedTemplateParams,
2921 true, TPL_TemplateMatch))
2922 Invalid = true;
2923
2924 if (!Invalid &&
2925 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2926 TPC_ClassTemplateMember))
2927 Invalid = true;
2928
2929 ++ParamIdx;
2930 continue;
2931 }
2932
2933 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2934 << T
2935 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2936 Invalid = true;
2937 continue;
2938 }
2939 }
2940
2941 // If there were at least as many template-ids as there were template
2942 // parameter lists, then there are no template parameter lists remaining for
2943 // the declaration itself.
2944 if (ParamIdx >= ParamLists.size()) {
2945 if (TemplateId && !IsFriend) {
2946 // We don't have a template header for the declaration itself, but we
2947 // should.
2948 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2949 TemplateId->RAngleLoc));
2950
2951 // Fabricate an empty template parameter list for the invented header.
2952 return TemplateParameterList::Create(Context, SourceLocation(),
2953 SourceLocation(), None,
2954 SourceLocation(), nullptr);
2955 }
2956
2957 return nullptr;
2958 }
2959
2960 // If there were too many template parameter lists, complain about that now.
2961 if (ParamIdx < ParamLists.size() - 1) {
2962 bool HasAnyExplicitSpecHeader = false;
2963 bool AllExplicitSpecHeaders = true;
2964 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2965 if (ParamLists[I]->size() == 0)
2966 HasAnyExplicitSpecHeader = true;
2967 else
2968 AllExplicitSpecHeaders = false;
2969 }
2970
2971 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2972 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2973 : diag::err_template_spec_extra_headers)
2974 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2975 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2976
2977 // If there was a specialization somewhere, such that 'template<>' is
2978 // not required, and there were any 'template<>' headers, note where the
2979 // specialization occurred.
2980 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2981 Diag(ExplicitSpecLoc,
2982 diag::note_explicit_template_spec_does_not_need_header)
2983 << NestedTypes.back();
2984
2985 // We have a template parameter list with no corresponding scope, which
2986 // means that the resulting template declaration can't be instantiated
2987 // properly (we'll end up with dependent nodes when we shouldn't).
2988 if (!AllExplicitSpecHeaders)
2989 Invalid = true;
2990 }
2991
2992 // C++ [temp.expl.spec]p16:
2993 // In an explicit specialization declaration for a member of a class
2994 // template or a member template that ap- pears in namespace scope, the
2995 // member template and some of its enclosing class templates may remain
2996 // unspecialized, except that the declaration shall not explicitly
2997 // specialize a class member template if its en- closing class templates
2998 // are not explicitly specialized as well.
2999 if (ParamLists.back()->size() == 0 &&
3000 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3001 false))
3002 return nullptr;
3003
3004 // Return the last template parameter list, which corresponds to the
3005 // entity being declared.
3006 return ParamLists.back();
3007}
3008
3009void Sema::NoteAllFoundTemplates(TemplateName Name) {
3010 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3011 Diag(Template->getLocation(), diag::note_template_declared_here)
3012 << (isa<FunctionTemplateDecl>(Template)
3013 ? 0
3014 : isa<ClassTemplateDecl>(Template)
3015 ? 1
3016 : isa<VarTemplateDecl>(Template)
3017 ? 2
3018 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3019 << Template->getDeclName();
3020 return;
3021 }
3022
3023 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3024 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3025 IEnd = OST->end();
3026 I != IEnd; ++I)
3027 Diag((*I)->getLocation(), diag::note_template_declared_here)
3028 << 0 << (*I)->getDeclName();
3029
3030 return;
3031 }
3032}
3033
3034static QualType
3035checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3036 const SmallVectorImpl<TemplateArgument> &Converted,
3037 SourceLocation TemplateLoc,
3038 TemplateArgumentListInfo &TemplateArgs) {
3039 ASTContext &Context = SemaRef.getASTContext();
3040 switch (BTD->getBuiltinTemplateKind()) {
3041 case BTK__make_integer_seq: {
3042 // Specializations of __make_integer_seq<S, T, N> are treated like
3043 // S<T, 0, ..., N-1>.
3044
3045 // C++14 [inteseq.intseq]p1:
3046 // T shall be an integer type.
3047 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3048 SemaRef.Diag(TemplateArgs[1].getLocation(),
3049 diag::err_integer_sequence_integral_element_type);
3050 return QualType();
3051 }
3052
3053 // C++14 [inteseq.make]p1:
3054 // If N is negative the program is ill-formed.
3055 TemplateArgument NumArgsArg = Converted[2];
3056 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3057 if (NumArgs < 0) {
3058 SemaRef.Diag(TemplateArgs[2].getLocation(),
3059 diag::err_integer_sequence_negative_length);
3060 return QualType();
3061 }
3062
3063 QualType ArgTy = NumArgsArg.getIntegralType();
3064 TemplateArgumentListInfo SyntheticTemplateArgs;
3065 // The type argument gets reused as the first template argument in the
3066 // synthetic template argument list.
3067 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3068 // Expand N into 0 ... N-1.
3069 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3070 I < NumArgs; ++I) {
3071 TemplateArgument TA(Context, I, ArgTy);
3072 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3073 TA, ArgTy, TemplateArgs[2].getLocation()));
3074 }
3075 // The first template argument will be reused as the template decl that
3076 // our synthetic template arguments will be applied to.
3077 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3078 TemplateLoc, SyntheticTemplateArgs);
3079 }
3080
3081 case BTK__type_pack_element:
3082 // Specializations of
3083 // __type_pack_element<Index, T_1, ..., T_N>
3084 // are treated like T_Index.
3085 assert(Converted.size() == 2 &&((Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? static_cast<void> (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3086, __PRETTY_FUNCTION__))
3086 "__type_pack_element should be given an index and a parameter pack")((Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? static_cast<void> (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3086, __PRETTY_FUNCTION__))
;
3087
3088 // If the Index is out of bounds, the program is ill-formed.
3089 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3090 llvm::APSInt Index = IndexArg.getAsIntegral();
3091 assert(Index >= 0 && "the index used with __type_pack_element should be of "((Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? static_cast
<void> (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3092, __PRETTY_FUNCTION__))
3092 "type std::size_t, and hence be non-negative")((Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? static_cast
<void> (0) : __assert_fail ("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3092, __PRETTY_FUNCTION__))
;
3093 if (Index >= Ts.pack_size()) {
3094 SemaRef.Diag(TemplateArgs[0].getLocation(),
3095 diag::err_type_pack_element_out_of_bounds);
3096 return QualType();
3097 }
3098
3099 // We simply return the type at index `Index`.
3100 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3101 return Nth->getAsType();
3102 }
3103 llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3103)
;
3104}
3105
3106/// Determine whether this alias template is "enable_if_t".
3107static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3108 return AliasTemplate->getName().equals("enable_if_t");
3109}
3110
3111/// Collect all of the separable terms in the given condition, which
3112/// might be a conjunction.
3113///
3114/// FIXME: The right answer is to convert the logical expression into
3115/// disjunctive normal form, so we can find the first failed term
3116/// within each possible clause.
3117static void collectConjunctionTerms(Expr *Clause,
3118 SmallVectorImpl<Expr *> &Terms) {
3119 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3120 if (BinOp->getOpcode() == BO_LAnd) {
3121 collectConjunctionTerms(BinOp->getLHS(), Terms);
3122 collectConjunctionTerms(BinOp->getRHS(), Terms);
3123 }
3124
3125 return;
3126 }
3127
3128 Terms.push_back(Clause);
3129}
3130
3131// The ranges-v3 library uses an odd pattern of a top-level "||" with
3132// a left-hand side that is value-dependent but never true. Identify
3133// the idiom and ignore that term.
3134static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3135 // Top-level '||'.
3136 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3137 if (!BinOp) return Cond;
3138
3139 if (BinOp->getOpcode() != BO_LOr) return Cond;
3140
3141 // With an inner '==' that has a literal on the right-hand side.
3142 Expr *LHS = BinOp->getLHS();
3143 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3144 if (!InnerBinOp) return Cond;
3145
3146 if (InnerBinOp->getOpcode() != BO_EQ ||
3147 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3148 return Cond;
3149
3150 // If the inner binary operation came from a macro expansion named
3151 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3152 // of the '||', which is the real, user-provided condition.
3153 SourceLocation Loc = InnerBinOp->getExprLoc();
3154 if (!Loc.isMacroID()) return Cond;
3155
3156 StringRef MacroName = PP.getImmediateMacroName(Loc);
3157 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3158 return BinOp->getRHS();
3159
3160 return Cond;
3161}
3162
3163namespace {
3164
3165// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3166// within failing boolean expression, such as substituting template parameters
3167// for actual types.
3168class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3169public:
3170 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3171 : Policy(P) {}
3172
3173 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3174 const auto *DR = dyn_cast<DeclRefExpr>(E);
3175 if (DR && DR->getQualifier()) {
3176 // If this is a qualified name, expand the template arguments in nested
3177 // qualifiers.
3178 DR->getQualifier()->print(OS, Policy, true);
3179 // Then print the decl itself.
3180 const ValueDecl *VD = DR->getDecl();
3181 OS << VD->getName();
3182 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3183 // This is a template variable, print the expanded template arguments.
3184 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3185 }
3186 return true;
3187 }
3188 return false;
3189 }
3190
3191private:
3192 const PrintingPolicy Policy;
3193};
3194
3195} // end anonymous namespace
3196
3197std::pair<Expr *, std::string>
3198Sema::findFailedBooleanCondition(Expr *Cond) {
3199 Cond = lookThroughRangesV3Condition(PP, Cond);
3200
3201 // Separate out all of the terms in a conjunction.
3202 SmallVector<Expr *, 4> Terms;
3203 collectConjunctionTerms(Cond, Terms);
3204
3205 // Determine which term failed.
3206 Expr *FailedCond = nullptr;
3207 for (Expr *Term : Terms) {
3208 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3209
3210 // Literals are uninteresting.
3211 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3212 isa<IntegerLiteral>(TermAsWritten))
3213 continue;
3214
3215 // The initialization of the parameter from the argument is
3216 // a constant-evaluated context.
3217 EnterExpressionEvaluationContext ConstantEvaluated(
3218 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3219
3220 bool Succeeded;
3221 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3222 !Succeeded) {
3223 FailedCond = TermAsWritten;
3224 break;
3225 }
3226 }
3227 if (!FailedCond)
3228 FailedCond = Cond->IgnoreParenImpCasts();
3229
3230 std::string Description;
3231 {
3232 llvm::raw_string_ostream Out(Description);
3233 PrintingPolicy Policy = getPrintingPolicy();
3234 Policy.PrintCanonicalTypes = true;
3235 FailedBooleanConditionPrinterHelper Helper(Policy);
3236 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3237 }
3238 return { FailedCond, Description };
3239}
3240
3241QualType Sema::CheckTemplateIdType(TemplateName Name,
3242 SourceLocation TemplateLoc,
3243 TemplateArgumentListInfo &TemplateArgs) {
3244 DependentTemplateName *DTN
3245 = Name.getUnderlying().getAsDependentTemplateName();
3246 if (DTN && DTN->isIdentifier())
3247 // When building a template-id where the template-name is dependent,
3248 // assume the template is a type template. Either our assumption is
3249 // correct, or the code is ill-formed and will be diagnosed when the
3250 // dependent name is substituted.
3251 return Context.getDependentTemplateSpecializationType(ETK_None,
3252 DTN->getQualifier(),
3253 DTN->getIdentifier(),
3254 TemplateArgs);
3255
3256 TemplateDecl *Template = Name.getAsTemplateDecl();
3257 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3258 isa<VarTemplateDecl>(Template) ||
3259 isa<ConceptDecl>(Template)) {
3260 // We might have a substituted template template parameter pack. If so,
3261 // build a template specialization type for it.
3262 if (Name.getAsSubstTemplateTemplateParmPack())
3263 return Context.getTemplateSpecializationType(Name, TemplateArgs);
3264
3265 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3266 << Name;
3267 NoteAllFoundTemplates(Name);
3268 return QualType();
3269 }
3270
3271 // Check that the template argument list is well-formed for this
3272 // template.
3273 SmallVector<TemplateArgument, 4> Converted;
3274 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3275 false, Converted))
3276 return QualType();
3277
3278 QualType CanonType;
3279
3280 bool InstantiationDependent = false;
3281 if (TypeAliasTemplateDecl *AliasTemplate =
3282 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3283 // Find the canonical type for this type alias template specialization.
3284 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3285 if (Pattern->isInvalidDecl())
3286 return QualType();
3287
3288 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3289 Converted);
3290
3291 // Only substitute for the innermost template argument list.
3292 MultiLevelTemplateArgumentList TemplateArgLists;
3293 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3294 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3295 for (unsigned I = 0; I < Depth; ++I)
3296 TemplateArgLists.addOuterTemplateArguments(None);
3297
3298 LocalInstantiationScope Scope(*this);
3299 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3300 if (Inst.isInvalid())
3301 return QualType();
3302
3303 CanonType = SubstType(Pattern->getUnderlyingType(),
3304 TemplateArgLists, AliasTemplate->getLocation(),
3305 AliasTemplate->getDeclName());
3306 if (CanonType.isNull()) {
3307 // If this was enable_if and we failed to find the nested type
3308 // within enable_if in a SFINAE context, dig out the specific
3309 // enable_if condition that failed and present that instead.
3310 if (isEnableIfAliasTemplate(AliasTemplate)) {
3311 if (auto DeductionInfo = isSFINAEContext()) {
3312 if (*DeductionInfo &&
3313 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3314 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3315 diag::err_typename_nested_not_found_enable_if &&
3316 TemplateArgs[0].getArgument().getKind()
3317 == TemplateArgument::Expression) {
3318 Expr *FailedCond;
3319 std::string FailedDescription;
3320 std::tie(FailedCond, FailedDescription) =
3321 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3322
3323 // Remove the old SFINAE diagnostic.
3324 PartialDiagnosticAt OldDiag =
3325 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3326 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3327
3328 // Add a new SFINAE diagnostic specifying which condition
3329 // failed.
3330 (*DeductionInfo)->addSFINAEDiagnostic(
3331 OldDiag.first,
3332 PDiag(diag::err_typename_nested_not_found_requirement)
3333 << FailedDescription
3334 << FailedCond->getSourceRange());
3335 }
3336 }
3337 }
3338
3339 return QualType();
3340 }
3341 } else if (Name.isDependent() ||
3342 TemplateSpecializationType::anyDependentTemplateArguments(
3343 TemplateArgs, InstantiationDependent)) {
3344 // This class template specialization is a dependent
3345 // type. Therefore, its canonical type is another class template
3346 // specialization type that contains all of the converted
3347 // arguments in canonical form. This ensures that, e.g., A<T> and
3348 // A<T, T> have identical types when A is declared as:
3349 //
3350 // template<typename T, typename U = T> struct A;
3351 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3352
3353 // This might work out to be a current instantiation, in which
3354 // case the canonical type needs to be the InjectedClassNameType.
3355 //
3356 // TODO: in theory this could be a simple hashtable lookup; most
3357 // changes to CurContext don't change the set of current
3358 // instantiations.
3359 if (isa<ClassTemplateDecl>(Template)) {
3360 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3361 // If we get out to a namespace, we're done.
3362 if (Ctx->isFileContext()) break;
3363
3364 // If this isn't a record, keep looking.
3365 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3366 if (!Record) continue;
3367
3368 // Look for one of the two cases with InjectedClassNameTypes
3369 // and check whether it's the same template.
3370 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3371 !Record->getDescribedClassTemplate())
3372 continue;
3373
3374 // Fetch the injected class name type and check whether its
3375 // injected type is equal to the type we just built.
3376 QualType ICNT = Context.getTypeDeclType(Record);
3377 QualType Injected = cast<InjectedClassNameType>(ICNT)
3378 ->getInjectedSpecializationType();
3379
3380 if (CanonType != Injected->getCanonicalTypeInternal())
3381 continue;
3382
3383 // If so, the canonical type of this TST is the injected
3384 // class name type of the record we just found.
3385 assert(ICNT.isCanonical())((ICNT.isCanonical()) ? static_cast<void> (0) : __assert_fail
("ICNT.isCanonical()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3385, __PRETTY_FUNCTION__))
;
3386 CanonType = ICNT;
3387 break;
3388 }
3389 }
3390 } else if (ClassTemplateDecl *ClassTemplate
3391 = dyn_cast<ClassTemplateDecl>(Template)) {
3392 // Find the class template specialization declaration that
3393 // corresponds to these arguments.
3394 void *InsertPos = nullptr;
3395 ClassTemplateSpecializationDecl *Decl
3396 = ClassTemplate->findSpecialization(Converted, InsertPos);
3397 if (!Decl) {
3398 // This is the first time we have referenced this class template
3399 // specialization. Create the canonical declaration and add it to
3400 // the set of specializations.
3401 Decl = ClassTemplateSpecializationDecl::Create(
3402 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3403 ClassTemplate->getDeclContext(),
3404 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3405 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3406 ClassTemplate->AddSpecialization(Decl, InsertPos);
3407 if (ClassTemplate->isOutOfLine())
3408 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3409 }
3410
3411 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3412 MultiLevelTemplateArgumentList TemplateArgLists;
3413 TemplateArgLists.addOuterTemplateArguments(Converted);
3414 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3415 Decl);
3416 }
3417
3418 // Diagnose uses of this specialization.
3419 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3420
3421 CanonType = Context.getTypeDeclType(Decl);
3422 assert(isa<RecordType>(CanonType) &&((isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3423, __PRETTY_FUNCTION__))
3423 "type of non-dependent specialization is not a RecordType")((isa<RecordType>(CanonType) && "type of non-dependent specialization is not a RecordType"
) ? static_cast<void> (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3423, __PRETTY_FUNCTION__))
;
3424 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3425 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3426 TemplateArgs);
3427 }
3428
3429 // Build the fully-sugared type for this class template
3430 // specialization, which refers back to the class template
3431 // specialization we created or found.
3432 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3433}
3434
3435void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3436 TemplateNameKind &TNK,
3437 SourceLocation NameLoc,
3438 IdentifierInfo *&II) {
3439 assert(TNK == TNK_Undeclared_template && "not an undeclared template name")((TNK == TNK_Undeclared_template && "not an undeclared template name"
) ? static_cast<void> (0) : __assert_fail ("TNK == TNK_Undeclared_template && \"not an undeclared template name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3439, __PRETTY_FUNCTION__))
;
3440
3441 TemplateName Name = ParsedName.get();
3442 auto *ATN = Name.getAsAssumedTemplateName();
3443 assert(ATN && "not an assumed template name")((ATN && "not an assumed template name") ? static_cast
<void> (0) : __assert_fail ("ATN && \"not an assumed template name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3443, __PRETTY_FUNCTION__))
;
3444 II = ATN->getDeclName().getAsIdentifierInfo();
3445
3446 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3447 // Resolved to a type template name.
3448 ParsedName = TemplateTy::make(Name);
3449 TNK = TNK_Type_template;
3450 }
3451}
3452
3453bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3454 SourceLocation NameLoc,
3455 bool Diagnose) {
3456 // We assumed this undeclared identifier to be an (ADL-only) function
3457 // template name, but it was used in a context where a type was required.
3458 // Try to typo-correct it now.
3459 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3460 assert(ATN && "not an assumed template name")((ATN && "not an assumed template name") ? static_cast
<void> (0) : __assert_fail ("ATN && \"not an assumed template name\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3460, __PRETTY_FUNCTION__))
;
3461
3462 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3463 struct CandidateCallback : CorrectionCandidateCallback {
3464 bool ValidateCandidate(const TypoCorrection &TC) override {
3465 return TC.getCorrectionDecl() &&
3466 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3467 }
3468 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3469 return std::make_unique<CandidateCallback>(*this);
3470 }
3471 } FilterCCC;
3472
3473 TypoCorrection Corrected =
3474 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3475 FilterCCC, CTK_ErrorRecovery);
3476 if (Corrected && Corrected.getFoundDecl()) {
3477 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3478 << ATN->getDeclName());
3479 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3480 return false;
3481 }
3482
3483 if (Diagnose)
3484 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3485 return true;
3486}
3487
3488TypeResult Sema::ActOnTemplateIdType(
3489 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3490 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3491 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3492 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3493 bool IsCtorOrDtorName, bool IsClassName) {
3494 if (SS.isInvalid())
3495 return true;
3496
3497 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3498 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3499
3500 // C++ [temp.res]p3:
3501 // A qualified-id that refers to a type and in which the
3502 // nested-name-specifier depends on a template-parameter (14.6.2)
3503 // shall be prefixed by the keyword typename to indicate that the
3504 // qualified-id denotes a type, forming an
3505 // elaborated-type-specifier (7.1.5.3).
3506 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3507 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3508 << SS.getScopeRep() << TemplateII->getName();
3509 // Recover as if 'typename' were specified.
3510 // FIXME: This is not quite correct recovery as we don't transform SS
3511 // into the corresponding dependent form (and we don't diagnose missing
3512 // 'template' keywords within SS as a result).
3513 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3514 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3515 TemplateArgsIn, RAngleLoc);
3516 }
3517
3518 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3519 // it's not actually allowed to be used as a type in most cases. Because
3520 // we annotate it before we know whether it's valid, we have to check for
3521 // this case here.
3522 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3523 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3524 Diag(TemplateIILoc,
3525 TemplateKWLoc.isInvalid()
3526 ? diag::err_out_of_line_qualified_id_type_names_constructor
3527 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3528 << TemplateII << 0 /*injected-class-name used as template name*/
3529 << 1 /*if any keyword was present, it was 'template'*/;
3530 }
3531 }
3532
3533 TemplateName Template = TemplateD.get();
3534 if (Template.getAsAssumedTemplateName() &&
3535 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3536 return true;
3537
3538 // Translate the parser's template argument list in our AST format.
3539 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3540 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3541
3542 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3543 QualType T
3544 = Context.getDependentTemplateSpecializationType(ETK_None,
3545 DTN->getQualifier(),
3546 DTN->getIdentifier(),
3547 TemplateArgs);
3548 // Build type-source information.
3549 TypeLocBuilder TLB;
3550 DependentTemplateSpecializationTypeLoc SpecTL
3551 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3552 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3553 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3554 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3555 SpecTL.setTemplateNameLoc(TemplateIILoc);
3556 SpecTL.setLAngleLoc(LAngleLoc);
3557 SpecTL.setRAngleLoc(RAngleLoc);
3558 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3559 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3560 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3561 }
3562
3563 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3564 if (Result.isNull())
3565 return true;
3566
3567 // Build type-source information.
3568 TypeLocBuilder TLB;
3569 TemplateSpecializationTypeLoc SpecTL
3570 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3571 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3572 SpecTL.setTemplateNameLoc(TemplateIILoc);
3573 SpecTL.setLAngleLoc(LAngleLoc);
3574 SpecTL.setRAngleLoc(RAngleLoc);
3575 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3576 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3577
3578 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3579 // constructor or destructor name (in such a case, the scope specifier
3580 // will be attached to the enclosing Decl or Expr node).
3581 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3582 // Create an elaborated-type-specifier containing the nested-name-specifier.
3583 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3584 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3585 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3586 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3587 }
3588
3589 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3590}
3591
3592TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3593 TypeSpecifierType TagSpec,
3594 SourceLocation TagLoc,
3595 CXXScopeSpec &SS,
3596 SourceLocation TemplateKWLoc,
3597 TemplateTy TemplateD,
3598 SourceLocation TemplateLoc,
3599 SourceLocation LAngleLoc,
3600 ASTTemplateArgsPtr TemplateArgsIn,
3601 SourceLocation RAngleLoc) {
3602 TemplateName Template = TemplateD.get();
3603
3604 // Translate the parser's template argument list in our AST format.
3605 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3606 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3607
3608 // Determine the tag kind
3609 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3610 ElaboratedTypeKeyword Keyword
3611 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3612
3613 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3614 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3615 DTN->getQualifier(),
3616 DTN->getIdentifier(),
3617 TemplateArgs);
3618
3619 // Build type-source information.
3620 TypeLocBuilder TLB;
3621 DependentTemplateSpecializationTypeLoc SpecTL
3622 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3623 SpecTL.setElaboratedKeywordLoc(TagLoc);
3624 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3625 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3626 SpecTL.setTemplateNameLoc(TemplateLoc);
3627 SpecTL.setLAngleLoc(LAngleLoc);
3628 SpecTL.setRAngleLoc(RAngleLoc);
3629 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3630 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3631 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3632 }
3633
3634 if (TypeAliasTemplateDecl *TAT =
3635 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3636 // C++0x [dcl.type.elab]p2:
3637 // If the identifier resolves to a typedef-name or the simple-template-id
3638 // resolves to an alias template specialization, the
3639 // elaborated-type-specifier is ill-formed.
3640 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3641 << TAT << NTK_TypeAliasTemplate << TagKind;
3642 Diag(TAT->getLocation(), diag::note_declared_at);
3643 }
3644
3645 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3646 if (Result.isNull())
3647 return TypeResult(true);
3648
3649 // Check the tag kind
3650 if (const RecordType *RT = Result->getAs<RecordType>()) {
3651 RecordDecl *D = RT->getDecl();
3652
3653 IdentifierInfo *Id = D->getIdentifier();
3654 assert(Id && "templated class must have an identifier")((Id && "templated class must have an identifier") ? static_cast
<void> (0) : __assert_fail ("Id && \"templated class must have an identifier\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3654, __PRETTY_FUNCTION__))
;
3655
3656 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3657 TagLoc, Id)) {
3658 Diag(TagLoc, diag::err_use_with_wrong_tag)
3659 << Result
3660 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3661 Diag(D->getLocation(), diag::note_previous_use);
3662 }
3663 }
3664
3665 // Provide source-location information for the template specialization.
3666 TypeLocBuilder TLB;
3667 TemplateSpecializationTypeLoc SpecTL
3668 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3669 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3670 SpecTL.setTemplateNameLoc(TemplateLoc);
3671 SpecTL.setLAngleLoc(LAngleLoc);
3672 SpecTL.setRAngleLoc(RAngleLoc);
3673 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3674 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3675
3676 // Construct an elaborated type containing the nested-name-specifier (if any)
3677 // and tag keyword.
3678 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3679 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3680 ElabTL.setElaboratedKeywordLoc(TagLoc);
3681 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3682 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3683}
3684
3685static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3686 NamedDecl *PrevDecl,
3687 SourceLocation Loc,
3688 bool IsPartialSpecialization);
3689
3690static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3691
3692static bool isTemplateArgumentTemplateParameter(
3693 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3694 switch (Arg.getKind()) {
3695 case TemplateArgument::Null:
3696 case TemplateArgument::NullPtr:
3697 case TemplateArgument::Integral:
3698 case TemplateArgument::Declaration:
3699 case TemplateArgument::Pack:
3700 case TemplateArgument::TemplateExpansion:
3701 return false;
3702
3703 case TemplateArgument::Type: {
3704 QualType Type = Arg.getAsType();
3705 const TemplateTypeParmType *TPT =
3706 Arg.getAsType()->getAs<TemplateTypeParmType>();
3707 return TPT && !Type.hasQualifiers() &&
3708 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3709 }
3710
3711 case TemplateArgument::Expression: {
3712 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3713 if (!DRE || !DRE->getDecl())
3714 return false;
3715 const NonTypeTemplateParmDecl *NTTP =
3716 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3717 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3718 }
3719
3720 case TemplateArgument::Template:
3721 const TemplateTemplateParmDecl *TTP =
3722 dyn_cast_or_null<TemplateTemplateParmDecl>(
3723 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3724 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3725 }
3726 llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3726)
;
3727}
3728
3729static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3730 ArrayRef<TemplateArgument> Args) {
3731 if (Params->size() != Args.size())
3732 return false;
3733
3734 unsigned Depth = Params->getDepth();
3735
3736 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3737 TemplateArgument Arg = Args[I];
3738
3739 // If the parameter is a pack expansion, the argument must be a pack
3740 // whose only element is a pack expansion.
3741 if (Params->getParam(I)->isParameterPack()) {
3742 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3743 !Arg.pack_begin()->isPackExpansion())
3744 return false;
3745 Arg = Arg.pack_begin()->getPackExpansionPattern();
3746 }
3747
3748 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3749 return false;
3750 }
3751
3752 return true;
3753}
3754
3755/// Convert the parser's template argument list representation into our form.
3756static TemplateArgumentListInfo
3757makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3758 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3759 TemplateId.RAngleLoc);
3760 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3761 TemplateId.NumArgs);
3762 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3763 return TemplateArgs;
3764}
3765
3766template<typename PartialSpecDecl>
3767static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3768 if (Partial->getDeclContext()->isDependentContext())
3769 return;
3770
3771 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3772 // for non-substitution-failure issues?
3773 TemplateDeductionInfo Info(Partial->getLocation());
3774 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3775 return;
3776
3777 auto *Template = Partial->getSpecializedTemplate();
3778 S.Diag(Partial->getLocation(),
3779 diag::ext_partial_spec_not_more_specialized_than_primary)
3780 << isa<VarTemplateDecl>(Template);
3781
3782 if (Info.hasSFINAEDiagnostic()) {
3783 PartialDiagnosticAt Diag = {SourceLocation(),
3784 PartialDiagnostic::NullDiagnostic()};
3785 Info.takeSFINAEDiagnostic(Diag);
3786 SmallString<128> SFINAEArgString;
3787 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3788 S.Diag(Diag.first,
3789 diag::note_partial_spec_not_more_specialized_than_primary)
3790 << SFINAEArgString;
3791 }
3792
3793 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3794}
3795
3796static void
3797noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3798 const llvm::SmallBitVector &DeducibleParams) {
3799 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3800 if (!DeducibleParams[I]) {
3801 NamedDecl *Param = TemplateParams->getParam(I);
3802 if (Param->getDeclName())
3803 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3804 << Param->getDeclName();
3805 else
3806 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3807 << "(anonymous)";
3808 }
3809 }
3810}
3811
3812
3813template<typename PartialSpecDecl>
3814static void checkTemplatePartialSpecialization(Sema &S,
3815 PartialSpecDecl *Partial) {
3816 // C++1z [temp.class.spec]p8: (DR1495)
3817 // - The specialization shall be more specialized than the primary
3818 // template (14.5.5.2).
3819 checkMoreSpecializedThanPrimary(S, Partial);
3820
3821 // C++ [temp.class.spec]p8: (DR1315)
3822 // - Each template-parameter shall appear at least once in the
3823 // template-id outside a non-deduced context.
3824 // C++1z [temp.class.spec.match]p3 (P0127R2)
3825 // If the template arguments of a partial specialization cannot be
3826 // deduced because of the structure of its template-parameter-list
3827 // and the template-id, the program is ill-formed.
3828 auto *TemplateParams = Partial->getTemplateParameters();
3829 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3830 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3831 TemplateParams->getDepth(), DeducibleParams);
3832
3833 if (!DeducibleParams.all()) {
3834 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3835 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3836 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3837 << (NumNonDeducible > 1)
3838 << SourceRange(Partial->getLocation(),
3839 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3840 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3841 }
3842}
3843
3844void Sema::CheckTemplatePartialSpecialization(
3845 ClassTemplatePartialSpecializationDecl *Partial) {
3846 checkTemplatePartialSpecialization(*this, Partial);
3847}
3848
3849void Sema::CheckTemplatePartialSpecialization(
3850 VarTemplatePartialSpecializationDecl *Partial) {
3851 checkTemplatePartialSpecialization(*this, Partial);
3852}
3853
3854void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3855 // C++1z [temp.param]p11:
3856 // A template parameter of a deduction guide template that does not have a
3857 // default-argument shall be deducible from the parameter-type-list of the
3858 // deduction guide template.
3859 auto *TemplateParams = TD->getTemplateParameters();
3860 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3861 MarkDeducedTemplateParameters(TD, DeducibleParams);
3862 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3863 // A parameter pack is deducible (to an empty pack).
3864 auto *Param = TemplateParams->getParam(I);
3865 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3866 DeducibleParams[I] = true;
3867 }
3868
3869 if (!DeducibleParams.all()) {
3870 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3871 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3872 << (NumNonDeducible > 1);
3873 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3874 }
3875}
3876
3877DeclResult Sema::ActOnVarTemplateSpecialization(
3878 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3879 TemplateParameterList *TemplateParams, StorageClass SC,
3880 bool IsPartialSpecialization) {
3881 // D must be variable template id.
3882 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&((D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
"Variable template specialization is declared with a template it."
) ? static_cast<void> (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3883, __PRETTY_FUNCTION__))
3883 "Variable template specialization is declared with a template it.")((D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
"Variable template specialization is declared with a template it."
) ? static_cast<void> (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template it.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 3883, __PRETTY_FUNCTION__))
;
3884
3885 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3886 TemplateArgumentListInfo TemplateArgs =
3887 makeTemplateArgumentListInfo(*this, *TemplateId);
3888 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3889 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3890 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3891
3892 TemplateName Name = TemplateId->Template.get();
3893
3894 // The template-id must name a variable template.
3895 VarTemplateDecl *VarTemplate =
3896 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3897 if (!VarTemplate) {
3898 NamedDecl *FnTemplate;
3899 if (auto *OTS = Name.getAsOverloadedTemplate())
3900 FnTemplate = *OTS->begin();
3901 else
3902 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3903 if (FnTemplate)
3904 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3905 << FnTemplate->getDeclName();
3906 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3907 << IsPartialSpecialization;
3908 }
3909
3910 // Check for unexpanded parameter packs in any of the template arguments.
3911 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3912 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3913 UPPC_PartialSpecialization))
3914 return true;
3915
3916 // Check that the template argument list is well-formed for this
3917 // template.
3918 SmallVector<TemplateArgument, 4> Converted;
3919 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3920 false, Converted))
3921 return true;
3922
3923 // Find the variable template (partial) specialization declaration that
3924 // corresponds to these arguments.
3925 if (IsPartialSpecialization) {
3926 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3927 TemplateArgs.size(), Converted))
3928 return true;
3929
3930 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3931 // also do them during instantiation.
3932 bool InstantiationDependent;
3933 if (!Name.isDependent() &&
3934 !TemplateSpecializationType::anyDependentTemplateArguments(
3935 TemplateArgs.arguments(),
3936 InstantiationDependent)) {
3937 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3938 << VarTemplate->getDeclName();
3939 IsPartialSpecialization = false;
3940 }
3941
3942 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3943 Converted)) {
3944 // C++ [temp.class.spec]p9b3:
3945 //
3946 // -- The argument list of the specialization shall not be identical
3947 // to the implicit argument list of the primary template.
3948 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3949 << /*variable template*/ 1
3950 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3951 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3952 // FIXME: Recover from this by treating the declaration as a redeclaration
3953 // of the primary template.
3954 return true;
3955 }
3956 }
3957
3958 void *InsertPos = nullptr;
3959 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3960
3961 if (IsPartialSpecialization)
3962 // FIXME: Template parameter list matters too
3963 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3964 else
3965 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3966
3967 VarTemplateSpecializationDecl *Specialization = nullptr;
3968
3969 // Check whether we can declare a variable template specialization in
3970 // the current scope.
3971 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3972 TemplateNameLoc,
3973 IsPartialSpecialization))
3974 return true;
3975
3976 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3977 // Since the only prior variable template specialization with these
3978 // arguments was referenced but not declared, reuse that
3979 // declaration node as our own, updating its source location and
3980 // the list of outer template parameters to reflect our new declaration.
3981 Specialization = PrevDecl;
3982 Specialization->setLocation(TemplateNameLoc);
3983 PrevDecl = nullptr;
3984 } else if (IsPartialSpecialization) {
3985 // Create a new class template partial specialization declaration node.
3986 VarTemplatePartialSpecializationDecl *PrevPartial =
3987 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3988 VarTemplatePartialSpecializationDecl *Partial =
3989 VarTemplatePartialSpecializationDecl::Create(
3990 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3991 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3992 Converted, TemplateArgs);
3993
3994 if (!PrevPartial)
3995 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3996 Specialization = Partial;
3997
3998 // If we are providing an explicit specialization of a member variable
3999 // template specialization, make a note of that.
4000 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4001 PrevPartial->setMemberSpecialization();
4002
4003 CheckTemplatePartialSpecialization(Partial);
4004 } else {
4005 // Create a new class template specialization declaration node for
4006 // this explicit specialization or friend declaration.
4007 Specialization = VarTemplateSpecializationDecl::Create(
4008 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4009 VarTemplate, DI->getType(), DI, SC, Converted);
4010 Specialization->setTemplateArgsInfo(TemplateArgs);
4011
4012 if (!PrevDecl)
4013 VarTemplate->AddSpecialization(Specialization, InsertPos);
4014 }
4015
4016 // C++ [temp.expl.spec]p6:
4017 // If a template, a member template or the member of a class template is
4018 // explicitly specialized then that specialization shall be declared
4019 // before the first use of that specialization that would cause an implicit
4020 // instantiation to take place, in every translation unit in which such a
4021 // use occurs; no diagnostic is required.
4022 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4023 bool Okay = false;
4024 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4025 // Is there any previous explicit specialization declaration?
4026 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4027 Okay = true;
4028 break;
4029 }
4030 }
4031
4032 if (!Okay) {
4033 SourceRange Range(TemplateNameLoc, RAngleLoc);
4034 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4035 << Name << Range;
4036
4037 Diag(PrevDecl->getPointOfInstantiation(),
4038 diag::note_instantiation_required_here)
4039 << (PrevDecl->getTemplateSpecializationKind() !=
4040 TSK_ImplicitInstantiation);
4041 return true;
4042 }
4043 }
4044
4045 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4046 Specialization->setLexicalDeclContext(CurContext);
4047
4048 // Add the specialization into its lexical context, so that it can
4049 // be seen when iterating through the list of declarations in that
4050 // context. However, specializations are not found by name lookup.
4051 CurContext->addDecl(Specialization);
4052
4053 // Note that this is an explicit specialization.
4054 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4055
4056 if (PrevDecl) {
4057 // Check that this isn't a redefinition of this specialization,
4058 // merging with previous declarations.
4059 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4060 forRedeclarationInCurContext());
4061 PrevSpec.addDecl(PrevDecl);
4062 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4063 } else if (Specialization->isStaticDataMember() &&
4064 Specialization->isOutOfLine()) {
4065 Specialization->setAccess(VarTemplate->getAccess());
4066 }
4067
4068 return Specialization;
4069}
4070
4071namespace {
4072/// A partial specialization whose template arguments have matched
4073/// a given template-id.
4074struct PartialSpecMatchResult {
4075 VarTemplatePartialSpecializationDecl *Partial;
4076 TemplateArgumentList *Args;
4077};
4078} // end anonymous namespace
4079
4080DeclResult
4081Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4082 SourceLocation TemplateNameLoc,
4083 const TemplateArgumentListInfo &TemplateArgs) {
4084 assert(Template && "A variable template id without template?")((Template && "A variable template id without template?"
) ? static_cast<void> (0) : __assert_fail ("Template && \"A variable template id without template?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4084, __PRETTY_FUNCTION__))
;
4085
4086 // Check that the template argument list is well-formed for this template.
4087 SmallVector<TemplateArgument, 4> Converted;
4088 if (CheckTemplateArgumentList(
4089 Template, TemplateNameLoc,
4090 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4091 Converted))
4092 return true;
4093
4094 // Find the variable template specialization declaration that
4095 // corresponds to these arguments.
4096 void *InsertPos = nullptr;
4097 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4098 Converted, InsertPos)) {
4099 checkSpecializationVisibility(TemplateNameLoc, Spec);
4100 // If we already have a variable template specialization, return it.
4101 return Spec;
4102 }
4103
4104 // This is the first time we have referenced this variable template
4105 // specialization. Create the canonical declaration and add it to
4106 // the set of specializations, based on the closest partial specialization
4107 // that it represents. That is,
4108 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4109 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4110 Converted);
4111 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4112 bool AmbiguousPartialSpec = false;
4113 typedef PartialSpecMatchResult MatchResult;
4114 SmallVector<MatchResult, 4> Matched;
4115 SourceLocation PointOfInstantiation = TemplateNameLoc;
4116 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4117 /*ForTakingAddress=*/false);
4118
4119 // 1. Attempt to find the closest partial specialization that this
4120 // specializes, if any.
4121 // If any of the template arguments is dependent, then this is probably
4122 // a placeholder for an incomplete declarative context; which must be
4123 // complete by instantiation time. Thus, do not search through the partial
4124 // specializations yet.
4125 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4126 // Perhaps better after unification of DeduceTemplateArguments() and
4127 // getMoreSpecializedPartialSpecialization().
4128 bool InstantiationDependent = false;
4129 if (!TemplateSpecializationType::anyDependentTemplateArguments(
4130 TemplateArgs, InstantiationDependent)) {
4131
4132 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4133 Template->getPartialSpecializations(PartialSpecs);
4134
4135 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4136 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4137 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4138
4139 if (TemplateDeductionResult Result =
4140 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4141 // Store the failed-deduction information for use in diagnostics, later.
4142 // TODO: Actually use the failed-deduction info?
4143 FailedCandidates.addCandidate().set(
4144 DeclAccessPair::make(Template, AS_public), Partial,
4145 MakeDeductionFailureInfo(Context, Result, Info));
4146 (void)Result;
4147 } else {
4148 Matched.push_back(PartialSpecMatchResult());
4149 Matched.back().Partial = Partial;
4150 Matched.back().Args = Info.take();
4151 }
4152 }
4153
4154 if (Matched.size() >= 1) {
4155 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4156 if (Matched.size() == 1) {
4157 // -- If exactly one matching specialization is found, the
4158 // instantiation is generated from that specialization.
4159 // We don't need to do anything for this.
4160 } else {
4161 // -- If more than one matching specialization is found, the
4162 // partial order rules (14.5.4.2) are used to determine
4163 // whether one of the specializations is more specialized
4164 // than the others. If none of the specializations is more
4165 // specialized than all of the other matching
4166 // specializations, then the use of the variable template is
4167 // ambiguous and the program is ill-formed.
4168 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4169 PEnd = Matched.end();
4170 P != PEnd; ++P) {
4171 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4172 PointOfInstantiation) ==
4173 P->Partial)
4174 Best = P;
4175 }
4176
4177 // Determine if the best partial specialization is more specialized than
4178 // the others.
4179 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4180 PEnd = Matched.end();
4181 P != PEnd; ++P) {
4182 if (P != Best && getMoreSpecializedPartialSpecialization(
4183 P->Partial, Best->Partial,
4184 PointOfInstantiation) != Best->Partial) {
4185 AmbiguousPartialSpec = true;
4186 break;
4187 }
4188 }
4189 }
4190
4191 // Instantiate using the best variable template partial specialization.
4192 InstantiationPattern = Best->Partial;
4193 InstantiationArgs = Best->Args;
4194 } else {
4195 // -- If no match is found, the instantiation is generated
4196 // from the primary template.
4197 // InstantiationPattern = Template->getTemplatedDecl();
4198 }
4199 }
4200
4201 // 2. Create the canonical declaration.
4202 // Note that we do not instantiate a definition until we see an odr-use
4203 // in DoMarkVarDeclReferenced().
4204 // FIXME: LateAttrs et al.?
4205 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4206 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4207 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4208 if (!Decl)
4209 return true;
4210
4211 if (AmbiguousPartialSpec) {
4212 // Partial ordering did not produce a clear winner. Complain.
4213 Decl->setInvalidDecl();
4214 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4215 << Decl;
4216
4217 // Print the matching partial specializations.
4218 for (MatchResult P : Matched)
4219 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4220 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4221 *P.Args);
4222 return true;
4223 }
4224
4225 if (VarTemplatePartialSpecializationDecl *D =
4226 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4227 Decl->setInstantiationOf(D, InstantiationArgs);
4228
4229 checkSpecializationVisibility(TemplateNameLoc, Decl);
4230
4231 assert(Decl && "No variable template specialization?")((Decl && "No variable template specialization?") ? static_cast
<void> (0) : __assert_fail ("Decl && \"No variable template specialization?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4231, __PRETTY_FUNCTION__))
;
4232 return Decl;
4233}
4234
4235ExprResult
4236Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4237 const DeclarationNameInfo &NameInfo,
4238 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4239 const TemplateArgumentListInfo *TemplateArgs) {
4240
4241 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4242 *TemplateArgs);
4243 if (Decl.isInvalid())
4244 return ExprError();
4245
4246 VarDecl *Var = cast<VarDecl>(Decl.get());
4247 if (!Var->getTemplateSpecializationKind())
4248 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4249 NameInfo.getLoc());
4250
4251 // Build an ordinary singleton decl ref.
4252 return BuildDeclarationNameExpr(SS, NameInfo, Var,
4253 /*FoundD=*/nullptr, TemplateArgs);
4254}
4255
4256void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4257 SourceLocation Loc) {
4258 Diag(Loc, diag::err_template_missing_args)
4259 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4260 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4261 Diag(TD->getLocation(), diag::note_template_decl_here)
4262 << TD->getTemplateParameters()->getSourceRange();
4263 }
4264}
4265
4266ExprResult
4267Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4268 const DeclarationNameInfo &NameInfo,
4269 ConceptDecl *Template,
4270 SourceLocation TemplateLoc,
4271 const TemplateArgumentListInfo *TemplateArgs) {
4272 // TODO: Do concept specialization here.
4273 Diag(NameInfo.getBeginLoc(), diag::err_concept_not_implemented) <<
4274 "concept specialization";
4275 return ExprError();
4276}
4277
4278ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4279 SourceLocation TemplateKWLoc,
4280 LookupResult &R,
4281 bool RequiresADL,
4282 const TemplateArgumentListInfo *TemplateArgs) {
4283 // FIXME: Can we do any checking at this point? I guess we could check the
4284 // template arguments that we have against the template name, if the template
4285 // name refers to a single template. That's not a terribly common case,
4286 // though.
4287 // foo<int> could identify a single function unambiguously
4288 // This approach does NOT work, since f<int>(1);
4289 // gets resolved prior to resorting to overload resolution
4290 // i.e., template<class T> void f(double);
4291 // vs template<class T, class U> void f(U);
4292
4293 // These should be filtered out by our callers.
4294 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")((!R.isAmbiguous() && "ambiguous lookup when building templateid"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4294, __PRETTY_FUNCTION__))
;
4295
4296 // Non-function templates require a template argument list.
4297 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4298 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4299 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4300 return ExprError();
4301 }
4302 }
4303
4304 auto AnyDependentArguments = [&]() -> bool {
4305 bool InstantiationDependent;
4306 return TemplateArgs &&
4307 TemplateSpecializationType::anyDependentTemplateArguments(
4308 *TemplateArgs, InstantiationDependent);
4309 };
4310
4311 // In C++1y, check variable template ids.
4312 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
4313 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4314 R.getAsSingle<VarTemplateDecl>(),
4315 TemplateKWLoc, TemplateArgs);
4316 }
4317
4318 if (R.getAsSingle<ConceptDecl>() && !AnyDependentArguments()) {
4319 return CheckConceptTemplateId(SS, R.getLookupNameInfo(),
4320 R.getAsSingle<ConceptDecl>(),
4321 TemplateKWLoc, TemplateArgs);
4322 }
4323
4324 // We don't want lookup warnings at this point.
4325 R.suppressDiagnostics();
4326
4327 UnresolvedLookupExpr *ULE
4328 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4329 SS.getWithLocInContext(Context),
4330 TemplateKWLoc,
4331 R.getLookupNameInfo(),
4332 RequiresADL, TemplateArgs,
4333 R.begin(), R.end());
4334
4335 return ULE;
4336}
4337
4338// We actually only call this from template instantiation.
4339ExprResult
4340Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4341 SourceLocation TemplateKWLoc,
4342 const DeclarationNameInfo &NameInfo,
4343 const TemplateArgumentListInfo *TemplateArgs) {
4344
4345 assert(TemplateArgs || TemplateKWLoc.isValid())((TemplateArgs || TemplateKWLoc.isValid()) ? static_cast<void
> (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4345, __PRETTY_FUNCTION__))
;
4346 DeclContext *DC;
4347 if (!(DC = computeDeclContext(SS, false)) ||
4348 DC->isDependentContext() ||
4349 RequireCompleteDeclContext(SS, DC))
4350 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4351
4352 bool MemberOfUnknownSpecialization;
4353 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4354 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4355 /*Entering*/false, MemberOfUnknownSpecialization,
4356 TemplateKWLoc))
4357 return ExprError();
4358
4359 if (R.isAmbiguous())
4360 return ExprError();
4361
4362 if (R.empty()) {
4363 Diag(NameInfo.getLoc(), diag::err_no_member)
4364 << NameInfo.getName() << DC << SS.getRange();
4365 return ExprError();
4366 }
4367
4368 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4369 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4370 << SS.getScopeRep()
4371 << NameInfo.getName().getAsString() << SS.getRange();
4372 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4373 return ExprError();
4374 }
4375
4376 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4377}
4378
4379/// Form a dependent template name.
4380///
4381/// This action forms a dependent template name given the template
4382/// name and its (presumably dependent) scope specifier. For
4383/// example, given "MetaFun::template apply", the scope specifier \p
4384/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4385/// of the "template" keyword, and "apply" is the \p Name.
4386TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4387 CXXScopeSpec &SS,
4388 SourceLocation TemplateKWLoc,
4389 const UnqualifiedId &Name,
4390 ParsedType ObjectType,
4391 bool EnteringContext,
4392 TemplateTy &Result,
4393 bool AllowInjectedClassName) {
4394 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4395 Diag(TemplateKWLoc,
4396 getLangOpts().CPlusPlus11 ?
4397 diag::warn_cxx98_compat_template_outside_of_template :
4398 diag::ext_template_outside_of_template)
4399 << FixItHint::CreateRemoval(TemplateKWLoc);
4400
4401 DeclContext *LookupCtx = nullptr;
4402 if (SS.isSet())
4403 LookupCtx = computeDeclContext(SS, EnteringContext);
4404 if (!LookupCtx && ObjectType)
4405 LookupCtx = computeDeclContext(ObjectType.get());
4406 if (LookupCtx) {
4407 // C++0x [temp.names]p5:
4408 // If a name prefixed by the keyword template is not the name of
4409 // a template, the program is ill-formed. [Note: the keyword
4410 // template may not be applied to non-template members of class
4411 // templates. -end note ] [ Note: as is the case with the
4412 // typename prefix, the template prefix is allowed in cases
4413 // where it is not strictly necessary; i.e., when the
4414 // nested-name-specifier or the expression on the left of the ->
4415 // or . is not dependent on a template-parameter, or the use
4416 // does not appear in the scope of a template. -end note]
4417 //
4418 // Note: C++03 was more strict here, because it banned the use of
4419 // the "template" keyword prior to a template-name that was not a
4420 // dependent name. C++ DR468 relaxed this requirement (the
4421 // "template" keyword is now permitted). We follow the C++0x
4422 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4423 bool MemberOfUnknownSpecialization;
4424 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4425 ObjectType, EnteringContext, Result,
4426 MemberOfUnknownSpecialization);
4427 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
4428 // This is a dependent template. Handle it below.
4429 } else if (TNK == TNK_Non_template) {
4430 // Do the lookup again to determine if this is a "nothing found" case or
4431 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4432 // need to do this.
4433 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4434 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4435 LookupOrdinaryName);
4436 bool MOUS;
4437 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4438 MOUS, TemplateKWLoc) && !R.isAmbiguous())
4439 Diag(Name.getBeginLoc(), diag::err_no_member)
4440 << DNI.getName() << LookupCtx << SS.getRange();
4441 return TNK_Non_template;
4442 } else {
4443 // We found something; return it.
4444 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4445 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4446 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4447 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4448 // C++14 [class.qual]p2:
4449 // In a lookup in which function names are not ignored and the
4450 // nested-name-specifier nominates a class C, if the name specified
4451 // [...] is the injected-class-name of C, [...] the name is instead
4452 // considered to name the constructor
4453 //
4454 // We don't get here if naming the constructor would be valid, so we
4455 // just reject immediately and recover by treating the
4456 // injected-class-name as naming the template.
4457 Diag(Name.getBeginLoc(),
4458 diag::ext_out_of_line_qualified_id_type_names_constructor)
4459 << Name.Identifier
4460 << 0 /*injected-class-name used as template name*/
4461 << 1 /*'template' keyword was used*/;
4462 }
4463 return TNK;
4464 }
4465 }
4466
4467 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4468
4469 switch (Name.getKind()) {
4470 case UnqualifiedIdKind::IK_Identifier:
4471 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4472 Name.Identifier));
4473 return TNK_Dependent_template_name;
4474
4475 case UnqualifiedIdKind::IK_OperatorFunctionId:
4476 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4477 Name.OperatorFunctionId.Operator));
4478 return TNK_Function_template;
4479
4480 case UnqualifiedIdKind::IK_LiteralOperatorId:
4481 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-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4481)
;
4482
4483 default:
4484 break;
4485 }
4486
4487 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4488 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4489 << TemplateKWLoc;
4490 return TNK_Non_template;
4491}
4492
4493bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4494 TemplateArgumentLoc &AL,
4495 SmallVectorImpl<TemplateArgument> &Converted) {
4496 const TemplateArgument &Arg = AL.getArgument();
4497 QualType ArgType;
4498 TypeSourceInfo *TSI = nullptr;
4499
4500 // Check template type parameter.
4501 switch(Arg.getKind()) {
4502 case TemplateArgument::Type:
4503 // C++ [temp.arg.type]p1:
4504 // A template-argument for a template-parameter which is a
4505 // type shall be a type-id.
4506 ArgType = Arg.getAsType();
4507 TSI = AL.getTypeSourceInfo();
4508 break;
4509 case TemplateArgument::Template:
4510 case TemplateArgument::TemplateExpansion: {
4511 // We have a template type parameter but the template argument
4512 // is a template without any arguments.
4513 SourceRange SR = AL.getSourceRange();
4514 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4515 diagnoseMissingTemplateArguments(Name, SR.getEnd());
4516 return true;
4517 }
4518 case TemplateArgument::Expression: {
4519 // We have a template type parameter but the template argument is an
4520 // expression; see if maybe it is missing the "typename" keyword.
4521 CXXScopeSpec SS;
4522 DeclarationNameInfo NameInfo;
4523
4524 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4525 SS.Adopt(ArgExpr->getQualifierLoc());
4526 NameInfo = ArgExpr->getNameInfo();
4527 } else if (DependentScopeDeclRefExpr *ArgExpr =
4528 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4529 SS.Adopt(ArgExpr->getQualifierLoc());
4530 NameInfo = ArgExpr->getNameInfo();
4531 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4532 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4533 if (ArgExpr->isImplicitAccess()) {
4534 SS.Adopt(ArgExpr->getQualifierLoc());
4535 NameInfo = ArgExpr->getMemberNameInfo();
4536 }
4537 }
4538
4539 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4540 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4541 LookupParsedName(Result, CurScope, &SS);
4542
4543 if (Result.getAsSingle<TypeDecl>() ||
4544 Result.getResultKind() ==
4545 LookupResult::NotFoundInCurrentInstantiation) {
4546 // Suggest that the user add 'typename' before the NNS.
4547 SourceLocation Loc = AL.getSourceRange().getBegin();
4548 Diag(Loc, getLangOpts().MSVCCompat
4549 ? diag::ext_ms_template_type_arg_missing_typename
4550 : diag::err_template_arg_must_be_type_suggest)
4551 << FixItHint::CreateInsertion(Loc, "typename ");
4552 Diag(Param->getLocation(), diag::note_template_param_here);
4553
4554 // Recover by synthesizing a type using the location information that we
4555 // already have.
4556 ArgType =
4557 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4558 TypeLocBuilder TLB;
4559 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4560 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4561 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4562 TL.setNameLoc(NameInfo.getLoc());
4563 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4564
4565 // Overwrite our input TemplateArgumentLoc so that we can recover
4566 // properly.
4567 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4568 TemplateArgumentLocInfo(TSI));
4569
4570 break;
4571 }
4572 }
4573 // fallthrough
4574 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4575 }
4576 default: {
4577 // We have a template type parameter but the template argument
4578 // is not a type.
4579 SourceRange SR = AL.getSourceRange();
4580 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4581 Diag(Param->getLocation(), diag::note_template_param_here);
4582
4583 return true;
4584 }
4585 }
4586
4587 if (CheckTemplateArgument(Param, TSI))
4588 return true;
4589
4590 // Add the converted template type argument.
4591 ArgType = Context.getCanonicalType(ArgType);
4592
4593 // Objective-C ARC:
4594 // If an explicitly-specified template argument type is a lifetime type
4595 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4596 if (getLangOpts().ObjCAutoRefCount &&
4597 ArgType->isObjCLifetimeType() &&
4598 !ArgType.getObjCLifetime()) {
4599 Qualifiers Qs;
4600 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4601 ArgType = Context.getQualifiedType(ArgType, Qs);
4602 }
4603
4604 Converted.push_back(TemplateArgument(ArgType));
4605 return false;
4606}
4607
4608/// Substitute template arguments into the default template argument for
4609/// the given template type parameter.
4610///
4611/// \param SemaRef the semantic analysis object for which we are performing
4612/// the substitution.
4613///
4614/// \param Template the template that we are synthesizing template arguments
4615/// for.
4616///
4617/// \param TemplateLoc the location of the template name that started the
4618/// template-id we are checking.
4619///
4620/// \param RAngleLoc the location of the right angle bracket ('>') that
4621/// terminates the template-id.
4622///
4623/// \param Param the template template parameter whose default we are
4624/// substituting into.
4625///
4626/// \param Converted the list of template arguments provided for template
4627/// parameters that precede \p Param in the template parameter list.
4628/// \returns the substituted template argument, or NULL if an error occurred.
4629static TypeSourceInfo *
4630SubstDefaultTemplateArgument(Sema &SemaRef,
4631 TemplateDecl *Template,
4632 SourceLocation TemplateLoc,
4633 SourceLocation RAngleLoc,
4634 TemplateTypeParmDecl *Param,
4635 SmallVectorImpl<TemplateArgument> &Converted) {
4636 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4637
4638 // If the argument type is dependent, instantiate it now based
4639 // on the previously-computed template arguments.
4640 if (ArgType->getType()->isInstantiationDependentType()) {
4641 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4642 Param, Template, Converted,
4643 SourceRange(TemplateLoc, RAngleLoc));
4644 if (Inst.isInvalid())
4645 return nullptr;
4646
4647 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4648
4649 // Only substitute for the innermost template argument list.
4650 MultiLevelTemplateArgumentList TemplateArgLists;
4651 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4652 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4653 TemplateArgLists.addOuterTemplateArguments(None);
4654
4655 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4656 ArgType =
4657 SemaRef.SubstType(ArgType, TemplateArgLists,
4658 Param->getDefaultArgumentLoc(), Param->getDeclName());
4659 }
4660
4661 return ArgType;
4662}
4663
4664/// Substitute template arguments into the default template argument for
4665/// the given non-type template parameter.
4666///
4667/// \param SemaRef the semantic analysis object for which we are performing
4668/// the substitution.
4669///
4670/// \param Template the template that we are synthesizing template arguments
4671/// for.
4672///
4673/// \param TemplateLoc the location of the template name that started the
4674/// template-id we are checking.
4675///
4676/// \param RAngleLoc the location of the right angle bracket ('>') that
4677/// terminates the template-id.
4678///
4679/// \param Param the non-type template parameter whose default we are
4680/// substituting into.
4681///
4682/// \param Converted the list of template arguments provided for template
4683/// parameters that precede \p Param in the template parameter list.
4684///
4685/// \returns the substituted template argument, or NULL if an error occurred.
4686static ExprResult
4687SubstDefaultTemplateArgument(Sema &SemaRef,
4688 TemplateDecl *Template,
4689 SourceLocation TemplateLoc,
4690 SourceLocation RAngleLoc,
4691 NonTypeTemplateParmDecl *Param,
4692 SmallVectorImpl<TemplateArgument> &Converted) {
4693 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4694 Param, Template, Converted,
4695 SourceRange(TemplateLoc, RAngleLoc));
4696 if (Inst.isInvalid())
4697 return ExprError();
4698
4699 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4700
4701 // Only substitute for the innermost template argument list.
4702 MultiLevelTemplateArgumentList TemplateArgLists;
4703 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4704 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4705 TemplateArgLists.addOuterTemplateArguments(None);
4706
4707 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4708 EnterExpressionEvaluationContext ConstantEvaluated(
4709 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4710 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4711}
4712
4713/// Substitute template arguments into the default template argument for
4714/// the given template template parameter.
4715///
4716/// \param SemaRef the semantic analysis object for which we are performing
4717/// the substitution.
4718///
4719/// \param Template the template that we are synthesizing template arguments
4720/// for.
4721///
4722/// \param TemplateLoc the location of the template name that started the
4723/// template-id we are checking.
4724///
4725/// \param RAngleLoc the location of the right angle bracket ('>') that
4726/// terminates the template-id.
4727///
4728/// \param Param the template template parameter whose default we are
4729/// substituting into.
4730///
4731/// \param Converted the list of template arguments provided for template
4732/// parameters that precede \p Param in the template parameter list.
4733///
4734/// \param QualifierLoc Will be set to the nested-name-specifier (with
4735/// source-location information) that precedes the template name.
4736///
4737/// \returns the substituted template argument, or NULL if an error occurred.
4738static TemplateName
4739SubstDefaultTemplateArgument(Sema &SemaRef,
4740 TemplateDecl *Template,
4741 SourceLocation TemplateLoc,
4742 SourceLocation RAngleLoc,
4743 TemplateTemplateParmDecl *Param,
4744 SmallVectorImpl<TemplateArgument> &Converted,
4745 NestedNameSpecifierLoc &QualifierLoc) {
4746 Sema::InstantiatingTemplate Inst(
4747 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4748 SourceRange(TemplateLoc, RAngleLoc));
4749 if (Inst.isInvalid())
4750 return TemplateName();
4751
4752 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4753
4754 // Only substitute for the innermost template argument list.
4755 MultiLevelTemplateArgumentList TemplateArgLists;
4756 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4757 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4758 TemplateArgLists.addOuterTemplateArguments(None);
4759
4760 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4761 // Substitute into the nested-name-specifier first,
4762 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4763 if (QualifierLoc) {
4764 QualifierLoc =
4765 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4766 if (!QualifierLoc)
4767 return TemplateName();
4768 }
4769
4770 return SemaRef.SubstTemplateName(
4771 QualifierLoc,
4772 Param->getDefaultArgument().getArgument().getAsTemplate(),
4773 Param->getDefaultArgument().getTemplateNameLoc(),
4774 TemplateArgLists);
4775}
4776
4777/// If the given template parameter has a default template
4778/// argument, substitute into that default template argument and
4779/// return the corresponding template argument.
4780TemplateArgumentLoc
4781Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4782 SourceLocation TemplateLoc,
4783 SourceLocation RAngleLoc,
4784 Decl *Param,
4785 SmallVectorImpl<TemplateArgument>
4786 &Converted,
4787 bool &HasDefaultArg) {
4788 HasDefaultArg = false;
4789
4790 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4791 if (!hasVisibleDefaultArgument(TypeParm))
4792 return TemplateArgumentLoc();
4793
4794 HasDefaultArg = true;
4795 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4796 TemplateLoc,
4797 RAngleLoc,
4798 TypeParm,
4799 Converted);
4800 if (DI)
4801 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4802
4803 return TemplateArgumentLoc();
4804 }
4805
4806 if (NonTypeTemplateParmDecl *NonTypeParm
4807 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4808 if (!hasVisibleDefaultArgument(NonTypeParm))
4809 return TemplateArgumentLoc();
4810
4811 HasDefaultArg = true;
4812 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4813 TemplateLoc,
4814 RAngleLoc,
4815 NonTypeParm,
4816 Converted);
4817 if (Arg.isInvalid())
4818 return TemplateArgumentLoc();
4819
4820 Expr *ArgE = Arg.getAs<Expr>();
4821 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4822 }
4823
4824 TemplateTemplateParmDecl *TempTempParm
4825 = cast<TemplateTemplateParmDecl>(Param);
4826 if (!hasVisibleDefaultArgument(TempTempParm))
4827 return TemplateArgumentLoc();
4828
4829 HasDefaultArg = true;
4830 NestedNameSpecifierLoc QualifierLoc;
4831 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4832 TemplateLoc,
4833 RAngleLoc,
4834 TempTempParm,
4835 Converted,
4836 QualifierLoc);
4837 if (TName.isNull())
4838 return TemplateArgumentLoc();
4839
4840 return TemplateArgumentLoc(TemplateArgument(TName),
4841 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4842 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4843}
4844
4845/// Convert a template-argument that we parsed as a type into a template, if
4846/// possible. C++ permits injected-class-names to perform dual service as
4847/// template template arguments and as template type arguments.
4848static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4849 // Extract and step over any surrounding nested-name-specifier.
4850 NestedNameSpecifierLoc QualLoc;
4851 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4852 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4853 return TemplateArgumentLoc();
4854
4855 QualLoc = ETLoc.getQualifierLoc();
4856 TLoc = ETLoc.getNamedTypeLoc();
4857 }
4858
4859 // If this type was written as an injected-class-name, it can be used as a
4860 // template template argument.
4861 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4862 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4863 QualLoc, InjLoc.getNameLoc());
4864
4865 // If this type was written as an injected-class-name, it may have been
4866 // converted to a RecordType during instantiation. If the RecordType is
4867 // *not* wrapped in a TemplateSpecializationType and denotes a class
4868 // template specialization, it must have come from an injected-class-name.
4869 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4870 if (auto *CTSD =
4871 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4872 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4873 QualLoc, RecLoc.getNameLoc());
4874
4875 return TemplateArgumentLoc();
4876}
4877
4878/// Check that the given template argument corresponds to the given
4879/// template parameter.
4880///
4881/// \param Param The template parameter against which the argument will be
4882/// checked.
4883///
4884/// \param Arg The template argument, which may be updated due to conversions.
4885///
4886/// \param Template The template in which the template argument resides.
4887///
4888/// \param TemplateLoc The location of the template name for the template
4889/// whose argument list we're matching.
4890///
4891/// \param RAngleLoc The location of the right angle bracket ('>') that closes
4892/// the template argument list.
4893///
4894/// \param ArgumentPackIndex The index into the argument pack where this
4895/// argument will be placed. Only valid if the parameter is a parameter pack.
4896///
4897/// \param Converted The checked, converted argument will be added to the
4898/// end of this small vector.
4899///
4900/// \param CTAK Describes how we arrived at this particular template argument:
4901/// explicitly written, deduced, etc.
4902///
4903/// \returns true on error, false otherwise.
4904bool Sema::CheckTemplateArgument(NamedDecl *Param,
4905 TemplateArgumentLoc &Arg,
4906 NamedDecl *Template,
4907 SourceLocation TemplateLoc,
4908 SourceLocation RAngleLoc,
4909 unsigned ArgumentPackIndex,
4910 SmallVectorImpl<TemplateArgument> &Converted,
4911 CheckTemplateArgumentKind CTAK) {
4912 // Check template type parameters.
4913 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4914 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4915
4916 // Check non-type template parameters.
4917 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4918 // Do substitution on the type of the non-type template parameter
4919 // with the template arguments we've seen thus far. But if the
4920 // template has a dependent context then we cannot substitute yet.
4921 QualType NTTPType = NTTP->getType();
4922 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4923 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4924
4925 // FIXME: Do we need to substitute into parameters here if they're
4926 // instantiation-dependent but not dependent?
4927 if (NTTPType->isDependentType() &&
4928 !isa<TemplateTemplateParmDecl>(Template) &&
4929 !Template->getDeclContext()->isDependentContext()) {
4930 // Do substitution on the type of the non-type template parameter.
4931 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4932 NTTP, Converted,
4933 SourceRange(TemplateLoc, RAngleLoc));
4934 if (Inst.isInvalid())
4935 return true;
4936
4937 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4938 Converted);
4939
4940 // If the parameter is a pack expansion, expand this slice of the pack.
4941 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
4942 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
4943 ArgumentPackIndex);
4944 NTTPType = SubstType(PET->getPattern(),
4945 MultiLevelTemplateArgumentList(TemplateArgs),
4946 NTTP->getLocation(),
4947 NTTP->getDeclName());
4948 } else {
4949 NTTPType = SubstType(NTTPType,
4950 MultiLevelTemplateArgumentList(TemplateArgs),
4951 NTTP->getLocation(),
4952 NTTP->getDeclName());
4953 }
4954
4955 // If that worked, check the non-type template parameter type
4956 // for validity.
4957 if (!NTTPType.isNull())
4958 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4959 NTTP->getLocation());
4960 if (NTTPType.isNull())
4961 return true;
4962 }
4963
4964 switch (Arg.getArgument().getKind()) {
4965 case TemplateArgument::Null:
4966 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-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 4966)
;
4967
4968 case TemplateArgument::Expression: {
4969 TemplateArgument Result;
4970 unsigned CurSFINAEErrors = NumSFINAEErrors;
4971 ExprResult Res =
4972 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4973 Result, CTAK);
4974 if (Res.isInvalid())
4975 return true;
4976 // If the current template argument causes an error, give up now.
4977 if (CurSFINAEErrors < NumSFINAEErrors)
4978 return true;
4979
4980 // If the resulting expression is new, then use it in place of the
4981 // old expression in the template argument.
4982 if (Res.get() != Arg.getArgument().getAsExpr()) {
4983 TemplateArgument TA(Res.get());
4984 Arg = TemplateArgumentLoc(TA, Res.get());
4985 }
4986
4987 Converted.push_back(Result);
4988 break;
4989 }
4990
4991 case TemplateArgument::Declaration:
4992 case TemplateArgument::Integral:
4993 case TemplateArgument::NullPtr:
4994 // We've already checked this template argument, so just copy
4995 // it to the list of converted arguments.
4996 Converted.push_back(Arg.getArgument());
4997 break;
4998
4999 case TemplateArgument::Template:
5000 case TemplateArgument::TemplateExpansion:
5001 // We were given a template template argument. It may not be ill-formed;
5002 // see below.
5003 if (DependentTemplateName *DTN
5004 = Arg.getArgument().getAsTemplateOrTemplatePattern()
5005 .getAsDependentTemplateName()) {
5006 // We have a template argument such as \c T::template X, which we
5007 // parsed as a template template argument. However, since we now
5008 // know that we need a non-type template argument, convert this
5009 // template name into an expression.
5010
5011 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5012 Arg.getTemplateNameLoc());
5013
5014 CXXScopeSpec SS;
5015 SS.Adopt(Arg.getTemplateQualifierLoc());
5016 // FIXME: the template-template arg was a DependentTemplateName,
5017 // so it was provided with a template keyword. However, its source
5018 // location is not stored in the template argument structure.
5019 SourceLocation TemplateKWLoc;
5020 ExprResult E = DependentScopeDeclRefExpr::Create(
5021 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5022 nullptr);
5023
5024 // If we parsed the template argument as a pack expansion, create a
5025 // pack expansion expression.
5026 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5027 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5028 if (E.isInvalid())
5029 return true;
5030 }
5031
5032 TemplateArgument Result;
5033 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
5034 if (E.isInvalid())
5035 return true;
5036
5037 Converted.push_back(Result);
5038 break;
5039 }
5040
5041 // We have a template argument that actually does refer to a class
5042 // template, alias template, or template template parameter, and
5043 // therefore cannot be a non-type template argument.
5044 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5045 << Arg.getSourceRange();
5046
5047 Diag(Param->getLocation(), diag::note_template_param_here);
5048 return true;
5049
5050 case TemplateArgument::Type: {
5051 // We have a non-type template parameter but the template
5052 // argument is a type.
5053
5054 // C++ [temp.arg]p2:
5055 // In a template-argument, an ambiguity between a type-id and
5056 // an expression is resolved to a type-id, regardless of the
5057 // form of the corresponding template-parameter.
5058 //
5059 // We warn specifically about this case, since it can be rather
5060 // confusing for users.
5061 QualType T = Arg.getArgument().getAsType();
5062 SourceRange SR = Arg.getSourceRange();
5063 if (T->isFunctionType())
5064 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5065 else
5066 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5067 Diag(Param->getLocation(), diag::note_template_param_here);
5068 return true;
5069 }
5070
5071 case TemplateArgument::Pack:
5072 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5072)
;
5073 }
5074
5075 return false;
5076 }
5077
5078
5079 // Check template template parameters.
5080 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5081
5082 TemplateParameterList *Params = TempParm->getTemplateParameters();
5083 if (TempParm->isExpandedParameterPack())
5084 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5085
5086 // Substitute into the template parameter list of the template
5087 // template parameter, since previously-supplied template arguments
5088 // may appear within the template template parameter.
5089 //
5090 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5091 {
5092 // Set up a template instantiation context.
5093 LocalInstantiationScope Scope(*this);
5094 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5095 TempParm, Converted,
5096 SourceRange(TemplateLoc, RAngleLoc));
5097 if (Inst.isInvalid())
5098 return true;
5099
5100 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5101 Params = SubstTemplateParams(Params, CurContext,
5102 MultiLevelTemplateArgumentList(TemplateArgs));
5103 if (!Params)
5104 return true;
5105 }
5106
5107 // C++1z [temp.local]p1: (DR1004)
5108 // When [the injected-class-name] is used [...] as a template-argument for
5109 // a template template-parameter [...] it refers to the class template
5110 // itself.
5111 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5112 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5113 Arg.getTypeSourceInfo()->getTypeLoc());
5114 if (!ConvertedArg.getArgument().isNull())
5115 Arg = ConvertedArg;
5116 }
5117
5118 switch (Arg.getArgument().getKind()) {
5119 case TemplateArgument::Null:
5120 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-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5120)
;
5121
5122 case TemplateArgument::Template:
5123 case TemplateArgument::TemplateExpansion:
5124 if (CheckTemplateTemplateArgument(Params, Arg))
5125 return true;
5126
5127 Converted.push_back(Arg.getArgument());
5128 break;
5129
5130 case TemplateArgument::Expression:
5131 case TemplateArgument::Type:
5132 // We have a template template parameter but the template
5133 // argument does not refer to a template.
5134 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5135 << getLangOpts().CPlusPlus11;
5136 return true;
5137
5138 case TemplateArgument::Declaration:
5139 llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5139)
;
5140 case TemplateArgument::Integral:
5141 llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5141)
;
5142 case TemplateArgument::NullPtr:
5143 llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5143)
;
5144
5145 case TemplateArgument::Pack:
5146 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5146)
;
5147 }
5148
5149 return false;
5150}
5151
5152/// Check whether the template parameter is a pack expansion, and if so,
5153/// determine the number of parameters produced by that expansion. For instance:
5154///
5155/// \code
5156/// template<typename ...Ts> struct A {
5157/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5158/// };
5159/// \endcode
5160///
5161/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5162/// is not a pack expansion, so returns an empty Optional.
5163static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
5164 if (NonTypeTemplateParmDecl *NTTP
5165 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5166 if (NTTP->isExpandedParameterPack())
5167 return NTTP->getNumExpansionTypes();
5168 }
5169
5170 if (TemplateTemplateParmDecl *TTP
5171 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5172 if (TTP->isExpandedParameterPack())
5173 return TTP->getNumExpansionTemplateParameters();
5174 }
5175
5176 return None;
5177}
5178
5179/// Diagnose a missing template argument.
5180template<typename TemplateParmDecl>
5181static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5182 TemplateDecl *TD,
5183 const TemplateParmDecl *D,
5184 TemplateArgumentListInfo &Args) {
5185 // Dig out the most recent declaration of the template parameter; there may be
5186 // declarations of the template that are more recent than TD.
5187 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5188 ->getTemplateParameters()
5189 ->getParam(D->getIndex()));
5190
5191 // If there's a default argument that's not visible, diagnose that we're
5192 // missing a module import.
5193 llvm::SmallVector<Module*, 8> Modules;
5194 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5195 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5196 D->getDefaultArgumentLoc(), Modules,
5197 Sema::MissingImportKind::DefaultArgument,
5198 /*Recover*/true);
5199 return true;
5200 }
5201
5202 // FIXME: If there's a more recent default argument that *is* visible,
5203 // diagnose that it was declared too late.
5204
5205 TemplateParameterList *Params = TD->getTemplateParameters();
5206
5207 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5208 << /*not enough args*/0
5209 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5210 << TD;
5211 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5212 << Params->getSourceRange();
5213 return true;
5214}
5215
5216/// Check that the given template argument list is well-formed
5217/// for specializing the given template.
5218bool Sema::CheckTemplateArgumentList(
5219 TemplateDecl *Template, SourceLocation TemplateLoc,
5220 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5221 SmallVectorImpl<TemplateArgument> &Converted,
5222 bool UpdateArgsWithConversions) {
5223 // Make a copy of the template arguments for processing. Only make the
5224 // changes at the end when successful in matching the arguments to the
5225 // template.
5226 TemplateArgumentListInfo NewArgs = TemplateArgs;
5227
5228 // Make sure we get the template parameter list from the most
5229 // recentdeclaration, since that is the only one that has is guaranteed to
5230 // have all the default template argument information.
5231 TemplateParameterList *Params =
5232 cast<TemplateDecl>(Template->getMostRecentDecl())
5233 ->getTemplateParameters();
5234
5235 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5236
5237 // C++ [temp.arg]p1:
5238 // [...] The type and form of each template-argument specified in
5239 // a template-id shall match the type and form specified for the
5240 // corresponding parameter declared by the template in its
5241 // template-parameter-list.
5242 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5243 SmallVector<TemplateArgument, 2> ArgumentPack;
5244 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5245 LocalInstantiationScope InstScope(*this, true);
5246 for (TemplateParameterList::iterator Param = Params->begin(),
5247 ParamEnd = Params->end();
5248 Param != ParamEnd; /* increment in loop */) {
5249 // If we have an expanded parameter pack, make sure we don't have too
5250 // many arguments.
5251 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5252 if (*Expansions == ArgumentPack.size()) {
5253 // We're done with this parameter pack. Pack up its arguments and add
5254 // them to the list.
5255 Converted.push_back(
5256 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5257 ArgumentPack.clear();
5258
5259 // This argument is assigned to the next parameter.
5260 ++Param;
5261 continue;
5262 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5263 // Not enough arguments for this parameter pack.
5264 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5265 << /*not enough args*/0
5266 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5267 << Template;
5268 Diag(Template->getLocation(), diag::note_template_decl_here)
5269 << Params->getSourceRange();
5270 return true;
5271 }
5272 }
5273
5274 if (ArgIdx < NumArgs) {
5275 // Check the template argument we were given.
5276 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5277 TemplateLoc, RAngleLoc,
5278 ArgumentPack.size(), Converted))
5279 return true;
5280
5281 bool PackExpansionIntoNonPack =
5282 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5283 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5284 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
5285 // Core issue 1430: we have a pack expansion as an argument to an
5286 // alias template, and it's not part of a parameter pack. This
5287 // can't be canonicalized, so reject it now.
5288 Diag(NewArgs[ArgIdx].getLocation(),
5289 diag::err_alias_template_expansion_into_fixed_list)
5290 << NewArgs[ArgIdx].getSourceRange();
5291 Diag((*Param)->getLocation(), diag::note_template_param_here);
5292 return true;
5293 }
5294
5295 // We're now done with this argument.
5296 ++ArgIdx;
5297
5298 if ((*Param)->isTemplateParameterPack()) {
5299 // The template parameter was a template parameter pack, so take the
5300 // deduced argument and place it on the argument pack. Note that we
5301 // stay on the same template parameter so that we can deduce more
5302 // arguments.
5303 ArgumentPack.push_back(Converted.pop_back_val());
5304 } else {
5305 // Move to the next template parameter.
5306 ++Param;
5307 }
5308
5309 // If we just saw a pack expansion into a non-pack, then directly convert
5310 // the remaining arguments, because we don't know what parameters they'll
5311 // match up with.
5312 if (PackExpansionIntoNonPack) {
5313 if (!ArgumentPack.empty()) {
5314 // If we were part way through filling in an expanded parameter pack,
5315 // fall back to just producing individual arguments.
5316 Converted.insert(Converted.end(),
5317 ArgumentPack.begin(), ArgumentPack.end());
5318 ArgumentPack.clear();
5319 }
5320
5321 while (ArgIdx < NumArgs) {
5322 Converted.push_back(NewArgs[ArgIdx].getArgument());
5323 ++ArgIdx;
5324 }
5325
5326 return false;
5327 }
5328
5329 continue;
5330 }
5331
5332 // If we're checking a partial template argument list, we're done.
5333 if (PartialTemplateArgs) {
5334 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5335 Converted.push_back(
5336 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5337
5338 return false;
5339 }
5340
5341 // If we have a template parameter pack with no more corresponding
5342 // arguments, just break out now and we'll fill in the argument pack below.
5343 if ((*Param)->isTemplateParameterPack()) {
5344 assert(!getExpandedPackSize(*Param) &&((!getExpandedPackSize(*Param) && "Should have dealt with this already"
) ? static_cast<void> (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5345, __PRETTY_FUNCTION__))
5345 "Should have dealt with this already")((!getExpandedPackSize(*Param) && "Should have dealt with this already"
) ? static_cast<void> (0) : __assert_fail ("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5345, __PRETTY_FUNCTION__))
;
5346
5347 // A non-expanded parameter pack before the end of the parameter list
5348 // only occurs for an ill-formed template parameter list, unless we've
5349 // got a partial argument list for a function template, so just bail out.
5350 if (Param + 1 != ParamEnd)
5351 return true;
5352
5353 Converted.push_back(
5354 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5355 ArgumentPack.clear();
5356
5357 ++Param;
5358 continue;
5359 }
5360
5361 // Check whether we have a default argument.
5362 TemplateArgumentLoc Arg;
5363
5364 // Retrieve the default template argument from the template
5365 // parameter. For each kind of template parameter, we substitute the
5366 // template arguments provided thus far and any "outer" template arguments
5367 // (when the template parameter was part of a nested template) into
5368 // the default argument.
5369 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5370 if (!hasVisibleDefaultArgument(TTP))
5371 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5372 NewArgs);
5373
5374 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5375 Template,
5376 TemplateLoc,
5377 RAngleLoc,
5378 TTP,
5379 Converted);
5380 if (!ArgType)
5381 return true;
5382
5383 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5384 ArgType);
5385 } else if (NonTypeTemplateParmDecl *NTTP
5386 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5387 if (!hasVisibleDefaultArgument(NTTP))
5388 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5389 NewArgs);
5390
5391 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5392 TemplateLoc,
5393 RAngleLoc,
5394 NTTP,
5395 Converted);
5396 if (E.isInvalid())
5397 return true;
5398
5399 Expr *Ex = E.getAs<Expr>();
5400 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5401 } else {
5402 TemplateTemplateParmDecl *TempParm
5403 = cast<TemplateTemplateParmDecl>(*Param);
5404
5405 if (!hasVisibleDefaultArgument(TempParm))
5406 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5407 NewArgs);
5408
5409 NestedNameSpecifierLoc QualifierLoc;
5410 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5411 TemplateLoc,
5412 RAngleLoc,
5413 TempParm,
5414 Converted,
5415 QualifierLoc);
5416 if (Name.isNull())
5417 return true;
5418
5419 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5420 TempParm->getDefaultArgument().getTemplateNameLoc());
5421 }
5422
5423 // Introduce an instantiation record that describes where we are using
5424 // the default template argument. We're not actually instantiating a
5425 // template here, we just create this object to put a note into the
5426 // context stack.
5427 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5428 SourceRange(TemplateLoc, RAngleLoc));
5429 if (Inst.isInvalid())
5430 return true;
5431
5432 // Check the default template argument.
5433 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5434 RAngleLoc, 0, Converted))
5435 return true;
5436
5437 // Core issue 150 (assumed resolution): if this is a template template
5438 // parameter, keep track of the default template arguments from the
5439 // template definition.
5440 if (isTemplateTemplateParameter)
5441 NewArgs.addArgument(Arg);
5442
5443 // Move to the next template parameter and argument.
5444 ++Param;
5445 ++ArgIdx;
5446 }
5447
5448 // If we're performing a partial argument substitution, allow any trailing
5449 // pack expansions; they might be empty. This can happen even if
5450 // PartialTemplateArgs is false (the list of arguments is complete but
5451 // still dependent).
5452 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5453 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5454 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5455 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5456 }
5457
5458 // If we have any leftover arguments, then there were too many arguments.
5459 // Complain and fail.
5460 if (ArgIdx < NumArgs) {
5461 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5462 << /*too many args*/1
5463 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5464 << Template
5465 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5466 Diag(Template->getLocation(), diag::note_template_decl_here)
5467 << Params->getSourceRange();
5468 return true;
5469 }
5470
5471 // No problems found with the new argument list, propagate changes back
5472 // to caller.
5473 if (UpdateArgsWithConversions)
5474 TemplateArgs = std::move(NewArgs);
5475
5476 return false;
5477}
5478
5479namespace {
5480 class UnnamedLocalNoLinkageFinder
5481 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5482 {
5483 Sema &S;
5484 SourceRange SR;
5485
5486 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5487
5488 public:
5489 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5490
5491 bool Visit(QualType T) {
5492 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5493 }
5494
5495#define TYPE(Class, Parent) \
5496 bool Visit##Class##Type(const Class##Type *);
5497#define ABSTRACT_TYPE(Class, Parent) \
5498 bool Visit##Class##Type(const Class##Type *) { return false; }
5499#define NON_CANONICAL_TYPE(Class, Parent) \
5500 bool Visit##Class##Type(const Class##Type *) { return false; }
5501#include "clang/AST/TypeNodes.inc"
5502
5503 bool VisitTagDecl(const TagDecl *Tag);
5504 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5505 };
5506} // end anonymous namespace
5507
5508bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5509 return false;
5510}
5511
5512bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5513 return Visit(T->getElementType());
5514}
5515
5516bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5517 return Visit(T->getPointeeType());
5518}
5519
5520bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5521 const BlockPointerType* T) {
5522 return Visit(T->getPointeeType());
5523}
5524
5525bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5526 const LValueReferenceType* T) {
5527 return Visit(T->getPointeeType());
5528}
5529
5530bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5531 const RValueReferenceType* T) {
5532 return Visit(T->getPointeeType());
5533}
5534
5535bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5536 const MemberPointerType* T) {
5537 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5538}
5539
5540bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5541 const ConstantArrayType* T) {
5542 return Visit(T->getElementType());
5543}
5544
5545bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5546 const IncompleteArrayType* T) {
5547 return Visit(T->getElementType());
5548}
5549
5550bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5551 const VariableArrayType* T) {
5552 return Visit(T->getElementType());
5553}
5554
5555bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5556 const DependentSizedArrayType* T) {
5557 return Visit(T->getElementType());
5558}
5559
5560bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5561 const DependentSizedExtVectorType* T) {
5562 return Visit(T->getElementType());
5563}
5564
5565bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5566 const DependentAddressSpaceType *T) {
5567 return Visit(T->getPointeeType());
5568}
5569
5570bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5571 return Visit(T->getElementType());
5572}
5573
5574bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5575 const DependentVectorType *T) {
5576 return Visit(T->getElementType());
5577}
5578
5579bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5580 return Visit(T->getElementType());
5581}
5582
5583bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5584 const FunctionProtoType* T) {
5585 for (const auto &A : T->param_types()) {
5586 if (Visit(A))
5587 return true;
5588 }
5589
5590 return Visit(T->getReturnType());
5591}
5592
5593bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5594 const FunctionNoProtoType* T) {
5595 return Visit(T->getReturnType());
5596}
5597
5598bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5599 const UnresolvedUsingType*) {
5600 return false;
5601}
5602
5603bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5604 return false;
5605}
5606
5607bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5608 return Visit(T->getUnderlyingType());
5609}
5610
5611bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5612 return false;
5613}
5614
5615bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5616 const UnaryTransformType*) {
5617 return false;
5618}
5619
5620bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5621 return Visit(T->getDeducedType());
5622}
5623
5624bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5625 const DeducedTemplateSpecializationType *T) {
5626 return Visit(T->getDeducedType());
5627}
5628
5629bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5630 return VisitTagDecl(T->getDecl());
5631}
5632
5633bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5634 return VisitTagDecl(T->getDecl());
5635}
5636
5637bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5638 const TemplateTypeParmType*) {
5639 return false;
5640}
5641
5642bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5643 const SubstTemplateTypeParmPackType *) {
5644 return false;
5645}
5646
5647bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5648 const TemplateSpecializationType*) {
5649 return false;
5650}
5651
5652bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5653 const InjectedClassNameType* T) {
5654 return VisitTagDecl(T->getDecl());
5655}
5656
5657bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5658 const DependentNameType* T) {
5659 return VisitNestedNameSpecifier(T->getQualifier());
5660}
5661
5662bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5663 const DependentTemplateSpecializationType* T) {
5664 return VisitNestedNameSpecifier(T->getQualifier());
5665}
5666
5667bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5668 const PackExpansionType* T) {
5669 return Visit(T->getPattern());
5670}
5671
5672bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5673 return false;
5674}
5675
5676bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5677 const ObjCInterfaceType *) {
5678 return false;
5679}
5680
5681bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5682 const ObjCObjectPointerType *) {
5683 return false;
5684}
5685
5686bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5687 return Visit(T->getValueType());
5688}
5689
5690bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5691 return false;
5692}
5693
5694bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5695 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5696 S.Diag(SR.getBegin(),
5697 S.getLangOpts().CPlusPlus11 ?
5698 diag::warn_cxx98_compat_template_arg_local_type :
5699 diag::ext_template_arg_local_type)
5700 << S.Context.getTypeDeclType(Tag) << SR;
5701 return true;
5702 }
5703
5704 if (!Tag->hasNameForLinkage()) {
5705 S.Diag(SR.getBegin(),
5706 S.getLangOpts().CPlusPlus11 ?
5707 diag::warn_cxx98_compat_template_arg_unnamed_type :
5708 diag::ext_template_arg_unnamed_type) << SR;
5709 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5710 return true;
5711 }
5712
5713 return false;
5714}
5715
5716bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5717 NestedNameSpecifier *NNS) {
5718 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5719 return true;
5720
5721 switch (NNS->getKind()) {
5722 case NestedNameSpecifier::Identifier:
5723 case NestedNameSpecifier::Namespace:
5724 case NestedNameSpecifier::NamespaceAlias:
5725 case NestedNameSpecifier::Global:
5726 case NestedNameSpecifier::Super:
5727 return false;
5728
5729 case NestedNameSpecifier::TypeSpec:
5730 case NestedNameSpecifier::TypeSpecWithTemplate:
5731 return Visit(QualType(NNS->getAsType(), 0));
5732 }
5733 llvm_unreachable("Invalid NestedNameSpecifier::Kind!")::llvm::llvm_unreachable_internal("Invalid NestedNameSpecifier::Kind!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5733)
;
5734}
5735
5736/// Check a template argument against its corresponding
5737/// template type parameter.
5738///
5739/// This routine implements the semantics of C++ [temp.arg.type]. It
5740/// returns true if an error occurred, and false otherwise.
5741bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5742 TypeSourceInfo *ArgInfo) {
5743 assert(ArgInfo && "invalid TypeSourceInfo")((ArgInfo && "invalid TypeSourceInfo") ? static_cast<
void> (0) : __assert_fail ("ArgInfo && \"invalid TypeSourceInfo\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5743, __PRETTY_FUNCTION__))
;
5744 QualType Arg = ArgInfo->getType();
5745 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5746
5747 if (Arg->isVariablyModifiedType()) {
5748 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5749 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5750 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5751 }
5752
5753 // C++03 [temp.arg.type]p2:
5754 // A local type, a type with no linkage, an unnamed type or a type
5755 // compounded from any of these types shall not be used as a
5756 // template-argument for a template type-parameter.
5757 //
5758 // C++11 allows these, and even in C++03 we allow them as an extension with
5759 // a warning.
5760 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5761 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5762 (void)Finder.Visit(Context.getCanonicalType(Arg));
5763 }
5764
5765 return false;
5766}
5767
5768enum NullPointerValueKind {
5769 NPV_NotNullPointer,
5770 NPV_NullPointer,
5771 NPV_Error
5772};
5773
5774/// Determine whether the given template argument is a null pointer
5775/// value of the appropriate type.
5776static NullPointerValueKind
5777isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5778 QualType ParamType, Expr *Arg,
5779 Decl *Entity = nullptr) {
5780 if (Arg->isValueDependent() || Arg->isTypeDependent())
5781 return NPV_NotNullPointer;
5782
5783 // dllimport'd entities aren't constant but are available inside of template
5784 // arguments.
5785 if (Entity && Entity->hasAttr<DLLImportAttr>())
5786 return NPV_NotNullPointer;
5787
5788 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5789 llvm_unreachable(::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5790)
5790 "Incomplete parameter type in isNullPointerValueTemplateArgument!")::llvm::llvm_unreachable_internal("Incomplete parameter type in isNullPointerValueTemplateArgument!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5790)
;
5791
5792 if (!S.getLangOpts().CPlusPlus11)
5793 return NPV_NotNullPointer;
5794
5795 // Determine whether we have a constant expression.
5796 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5797 if (ArgRV.isInvalid())
5798 return NPV_Error;
5799 Arg = ArgRV.get();
5800
5801 Expr::EvalResult EvalResult;
5802 SmallVector<PartialDiagnosticAt, 8> Notes;
5803 EvalResult.Diag = &Notes;
5804 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5805 EvalResult.HasSideEffects) {
5806 SourceLocation DiagLoc = Arg->getExprLoc();
5807
5808 // If our only note is the usual "invalid subexpression" note, just point
5809 // the caret at its location rather than producing an essentially
5810 // redundant note.
5811 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5812 diag::note_invalid_subexpr_in_const_expr) {
5813 DiagLoc = Notes[0].first;
5814 Notes.clear();
5815 }
5816
5817 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5818 << Arg->getType() << Arg->getSourceRange();
5819 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5820 S.Diag(Notes[I].first, Notes[I].second);
5821
5822 S.Diag(Param->getLocation(), diag::note_template_param_here);
5823 return NPV_Error;
5824 }
5825
5826 // C++11 [temp.arg.nontype]p1:
5827 // - an address constant expression of type std::nullptr_t
5828 if (Arg->getType()->isNullPtrType())
5829 return NPV_NullPointer;
5830
5831 // - a constant expression that evaluates to a null pointer value (4.10); or
5832 // - a constant expression that evaluates to a null member pointer value
5833 // (4.11); or
5834 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5835 (EvalResult.Val.isMemberPointer() &&
5836 !EvalResult.Val.getMemberPointerDecl())) {
5837 // If our expression has an appropriate type, we've succeeded.
5838 bool ObjCLifetimeConversion;
5839 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5840 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5841 ObjCLifetimeConversion))
5842 return NPV_NullPointer;
5843
5844 // The types didn't match, but we know we got a null pointer; complain,
5845 // then recover as if the types were correct.
5846 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5847 << Arg->getType() << ParamType << Arg->getSourceRange();
5848 S.Diag(Param->getLocation(), diag::note_template_param_here);
5849 return NPV_NullPointer;
5850 }
5851
5852 // If we don't have a null pointer value, but we do have a NULL pointer
5853 // constant, suggest a cast to the appropriate type.
5854 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5855 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5856 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5857 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
5858 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
5859 ")");
5860 S.Diag(Param->getLocation(), diag::note_template_param_here);
5861 return NPV_NullPointer;
5862 }
5863
5864 // FIXME: If we ever want to support general, address-constant expressions
5865 // as non-type template arguments, we should return the ExprResult here to
5866 // be interpreted by the caller.
5867 return NPV_NotNullPointer;
5868}
5869
5870/// Checks whether the given template argument is compatible with its
5871/// template parameter.
5872static bool CheckTemplateArgumentIsCompatibleWithParameter(
5873 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5874 Expr *Arg, QualType ArgType) {
5875 bool ObjCLifetimeConversion;
5876 if (ParamType->isPointerType() &&
19
Calling 'Type::isPointerType'
22
Returning from 'Type::isPointerType'
5877 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
23
Assuming the object is not a 'PointerType'
24
Called C++ object pointer is null
5878 S.IsQualificationConversion(ArgType, ParamType, false,
5879 ObjCLifetimeConversion)) {
5880 // For pointer-to-object types, qualification conversions are
5881 // permitted.
5882 } else {
5883 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5884 if (!ParamRef->getPointeeType()->isFunctionType()) {
5885 // C++ [temp.arg.nontype]p5b3:
5886 // For a non-type template-parameter of type reference to
5887 // object, no conversions apply. The type referred to by the
5888 // reference may be more cv-qualified than the (otherwise
5889 // identical) type of the template- argument. The
5890 // template-parameter is bound directly to the
5891 // template-argument, which shall be an lvalue.
5892
5893 // FIXME: Other qualifiers?
5894 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5895 unsigned ArgQuals = ArgType.getCVRQualifiers();
5896
5897 if ((ParamQuals | ArgQuals) != ParamQuals) {
5898 S.Diag(Arg->getBeginLoc(),
5899 diag::err_template_arg_ref_bind_ignores_quals)
5900 << ParamType << Arg->getType() << Arg->getSourceRange();
5901 S.Diag(Param->getLocation(), diag::note_template_param_here);
5902 return true;
5903 }
5904 }
5905 }
5906
5907 // At this point, the template argument refers to an object or
5908 // function with external linkage. We now need to check whether the
5909 // argument and parameter types are compatible.
5910 if (!S.Context.hasSameUnqualifiedType(ArgType,
5911 ParamType.getNonReferenceType())) {
5912 // We can't perform this conversion or binding.
5913 if (ParamType->isReferenceType())
5914 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
5915 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5916 else
5917 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
5918 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5919 S.Diag(Param->getLocation(), diag::note_template_param_here);
5920 return true;
5921 }
5922 }
5923
5924 return false;
5925}
5926
5927/// Checks whether the given template argument is the address
5928/// of an object or function according to C++ [temp.arg.nontype]p1.
5929static bool
5930CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5931 NonTypeTemplateParmDecl *Param,
5932 QualType ParamType,
5933 Expr *ArgIn,
5934 TemplateArgument &Converted) {
5935 bool Invalid = false;
5936 Expr *Arg = ArgIn;
5937 QualType ArgType = Arg->getType();
5938
5939 bool AddressTaken = false;
5940 SourceLocation AddrOpLoc;
5941 if (S.getLangOpts().MicrosoftExt) {
1
Assuming field 'MicrosoftExt' is 0
2
Taking false branch
5942 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5943 // dereference and address-of operators.
5944 Arg = Arg->IgnoreParenCasts();
5945
5946 bool ExtWarnMSTemplateArg = false;
5947 UnaryOperatorKind FirstOpKind;
5948 SourceLocation FirstOpLoc;
5949 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5950 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5951 if (UnOpKind == UO_Deref)
5952 ExtWarnMSTemplateArg = true;
5953 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5954 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5955 if (!AddrOpLoc.isValid()) {
5956 FirstOpKind = UnOpKind;
5957 FirstOpLoc = UnOp->getOperatorLoc();
5958 }
5959 } else
5960 break;
5961 }
5962 if (FirstOpLoc.isValid()) {
5963 if (ExtWarnMSTemplateArg)
5964 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
5965 << ArgIn->getSourceRange();
5966
5967 if (FirstOpKind == UO_AddrOf)
5968 AddressTaken = true;
5969 else if (Arg->getType()->isPointerType()) {
5970 // We cannot let pointers get dereferenced here, that is obviously not a
5971 // constant expression.
5972 assert(FirstOpKind == UO_Deref)((FirstOpKind == UO_Deref) ? static_cast<void> (0) : __assert_fail
("FirstOpKind == UO_Deref", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 5972, __PRETTY_FUNCTION__))
;
5973 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
5974 << Arg->getSourceRange();
5975 }
5976 }
5977 } else {
5978 // See through any implicit casts we added to fix the type.
5979 Arg = Arg->IgnoreImpCasts();
5980
5981 // C++ [temp.arg.nontype]p1:
5982 //
5983 // A template-argument for a non-type, non-template
5984 // template-parameter shall be one of: [...]
5985 //
5986 // -- the address of an object or function with external
5987 // linkage, including function templates and function
5988 // template-ids but excluding non-static class members,
5989 // expressed as & id-expression where the & is optional if
5990 // the name refers to a function or array, or if the
5991 // corresponding template-parameter is a reference; or
5992
5993 // In C++98/03 mode, give an extension warning on any extra parentheses.
5994 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5995 bool ExtraParens = false;
5996 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3
Assuming 'Arg' is not a 'ParenExpr'
4
Loop condition is false. Execution continues on line 6010
5997 if (!Invalid && !ExtraParens) {
5998 S.Diag(Arg->getBeginLoc(),
5999 S.getLangOpts().CPlusPlus11
6000 ? diag::warn_cxx98_compat_template_arg_extra_parens
6001 : diag::ext_template_arg_extra_parens)
6002 << Arg->getSourceRange();
6003 ExtraParens = true;
6004 }
6005
6006 Arg = Parens->getSubExpr();
6007 }
6008
6009 while (SubstNonTypeTemplateParmExpr *subst =
6
Loop condition is false. Execution continues on line 6013
6010 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5
Assuming 'Arg' is not a 'SubstNonTypeTemplateParmExpr'
6011 Arg = subst->getReplacement()->IgnoreImpCasts();
6012
6013 if (UnaryOperator *UnOp
7.1
'UnOp' is null
7.1
'UnOp' is null
= dyn_cast<UnaryOperator>(Arg)) {
7
Assuming 'Arg' is not a 'UnaryOperator'
8
Taking false branch
6014 if (UnOp->getOpcode() == UO_AddrOf) {
6015 Arg = UnOp->getSubExpr();
6016 AddressTaken = true;
6017 AddrOpLoc = UnOp->getOperatorLoc();
6018 }
6019 }
6020
6021 while (SubstNonTypeTemplateParmExpr *subst =
10
Loop condition is false. Execution continues on line 6026
6022 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
9
'Arg' is not a 'SubstNonTypeTemplateParmExpr'
6023 Arg = subst->getReplacement()->IgnoreImpCasts();
6024 }
6025
6026 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
11
Assuming 'Arg' is not a 'DeclRefExpr'
6027 ValueDecl *Entity = DRE
11.1
'DRE' is null
11.1
'DRE' is null
? DRE->getDecl() : nullptr;
12
'?' condition is false
6028
6029 // If our parameter has pointer type, check for a null template value.
6030 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
13
Taking false branch
6031 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6032 Entity)) {
6033 case NPV_NullPointer:
6034 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6035 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6036 /*isNullPtr=*/true);
6037 return false;
6038
6039 case NPV_Error:
6040 return true;
6041
6042 case NPV_NotNullPointer:
6043 break;
6044 }
6045 }
6046
6047 // Stop checking the precise nature of the argument if it is value dependent,
6048 // it should be checked when instantiated.
6049 if (Arg->isValueDependent()) {
14
Assuming the condition is false
15
Taking false branch
6050 Converted = TemplateArgument(ArgIn);
6051 return false;
6052 }
6053
6054 if (isa<CXXUuidofExpr>(Arg)) {
16
Assuming 'Arg' is a 'CXXUuidofExpr'
17
Taking true branch
6055 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
18
Calling 'CheckTemplateArgumentIsCompatibleWithParameter'
6056 ArgIn, Arg, ArgType))
6057 return true;
6058
6059 Converted = TemplateArgument(ArgIn);
6060 return false;
6061 }
6062
6063 if (!DRE) {
6064 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6065 << Arg->getSourceRange();
6066 S.Diag(Param->getLocation(), diag::note_template_param_here);
6067 return true;
6068 }
6069
6070 // Cannot refer to non-static data members
6071 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6072 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6073 << Entity << Arg->getSourceRange();
6074 S.Diag(Param->getLocation(), diag::note_template_param_here);
6075 return true;
6076 }
6077
6078 // Cannot refer to non-static member functions
6079 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6080 if (!Method->isStatic()) {
6081 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6082 << Method << Arg->getSourceRange();
6083 S.Diag(Param->getLocation(), diag::note_template_param_here);
6084 return true;
6085 }
6086 }
6087
6088 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6089 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6090
6091 // A non-type template argument must refer to an object or function.
6092 if (!Func && !Var) {
6093 // We found something, but we don't know specifically what it is.
6094 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6095 << Arg->getSourceRange();
6096 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6097 return true;
6098 }
6099
6100 // Address / reference template args must have external linkage in C++98.
6101 if (Entity->getFormalLinkage() == InternalLinkage) {
6102 S.Diag(Arg->getBeginLoc(),
6103 S.getLangOpts().CPlusPlus11
6104 ? diag::warn_cxx98_compat_template_arg_object_internal
6105 : diag::ext_template_arg_object_internal)
6106 << !Func << Entity << Arg->getSourceRange();
6107 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6108 << !Func;
6109 } else if (!Entity->hasLinkage()) {
6110 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6111 << !Func << Entity << Arg->getSourceRange();
6112 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6113 << !Func;
6114 return true;
6115 }
6116
6117 if (Func) {
6118 // If the template parameter has pointer type, the function decays.
6119 if (ParamType->isPointerType() && !AddressTaken)
6120 ArgType = S.Context.getPointerType(Func->getType());
6121 else if (AddressTaken && ParamType->isReferenceType()) {
6122 // If we originally had an address-of operator, but the
6123 // parameter has reference type, complain and (if things look
6124 // like they will work) drop the address-of operator.
6125 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6126 ParamType.getNonReferenceType())) {
6127 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6128 << ParamType;
6129 S.Diag(Param->getLocation(), diag::note_template_param_here);
6130 return true;
6131 }
6132
6133 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6134 << ParamType
6135 << FixItHint::CreateRemoval(AddrOpLoc);
6136 S.Diag(Param->getLocation(), diag::note_template_param_here);
6137
6138 ArgType = Func->getType();
6139 }
6140 } else {
6141 // A value of reference type is not an object.
6142 if (Var->getType()->isReferenceType()) {
6143 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6144 << Var->getType() << Arg->getSourceRange();
6145 S.Diag(Param->getLocation(), diag::note_template_param_here);
6146 return true;
6147 }
6148
6149 // A template argument must have static storage duration.
6150 if (Var->getTLSKind()) {
6151 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6152 << Arg->getSourceRange();
6153 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6154 return true;
6155 }
6156
6157 // If the template parameter has pointer type, we must have taken
6158 // the address of this object.
6159 if (ParamType->isReferenceType()) {
6160 if (AddressTaken) {
6161 // If we originally had an address-of operator, but the
6162 // parameter has reference type, complain and (if things look
6163 // like they will work) drop the address-of operator.
6164 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6165 ParamType.getNonReferenceType())) {
6166 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6167 << ParamType;
6168 S.Diag(Param->getLocation(), diag::note_template_param_here);
6169 return true;
6170 }
6171
6172 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6173 << ParamType
6174 << FixItHint::CreateRemoval(AddrOpLoc);
6175 S.Diag(Param->getLocation(), diag::note_template_param_here);
6176
6177 ArgType = Var->getType();
6178 }
6179 } else if (!AddressTaken && ParamType->isPointerType()) {
6180 if (Var->getType()->isArrayType()) {
6181 // Array-to-pointer decay.
6182 ArgType = S.Context.getArrayDecayedType(Var->getType());
6183 } else {
6184 // If the template parameter has pointer type but the address of
6185 // this object was not taken, complain and (possibly) recover by
6186 // taking the address of the entity.
6187 ArgType = S.Context.getPointerType(Var->getType());
6188 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6189 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6190 << ParamType;
6191 S.Diag(Param->getLocation(), diag::note_template_param_here);
6192 return true;
6193 }
6194
6195 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6196 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6197
6198 S.Diag(Param->getLocation(), diag::note_template_param_here);
6199 }
6200 }
6201 }
6202
6203 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6204 Arg, ArgType))
6205 return true;
6206
6207 // Create the template argument.
6208 Converted =
6209 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
6210 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6211 return false;
6212}
6213
6214/// Checks whether the given template argument is a pointer to
6215/// member constant according to C++ [temp.arg.nontype]p1.
6216static bool CheckTemplateArgumentPointerToMember(Sema &S,
6217 NonTypeTemplateParmDecl *Param,
6218 QualType ParamType,
6219 Expr *&ResultArg,
6220 TemplateArgument &Converted) {
6221 bool Invalid = false;
6222
6223 Expr *Arg = ResultArg;
6224 bool ObjCLifetimeConversion;
6225
6226 // C++ [temp.arg.nontype]p1:
6227 //
6228 // A template-argument for a non-type, non-template
6229 // template-parameter shall be one of: [...]
6230 //
6231 // -- a pointer to member expressed as described in 5.3.1.
6232 DeclRefExpr *DRE = nullptr;
6233
6234 // In C++98/03 mode, give an extension warning on any extra parentheses.
6235 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6236 bool ExtraParens = false;
6237 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6238 if (!Invalid && !ExtraParens) {
6239 S.Diag(Arg->getBeginLoc(),
6240 S.getLangOpts().CPlusPlus11
6241 ? diag::warn_cxx98_compat_template_arg_extra_parens
6242 : diag::ext_template_arg_extra_parens)
6243 << Arg->getSourceRange();
6244 ExtraParens = true;
6245 }
6246
6247 Arg = Parens->getSubExpr();
6248 }
6249
6250 while (SubstNonTypeTemplateParmExpr *subst =
6251 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6252 Arg = subst->getReplacement()->IgnoreImpCasts();
6253
6254 // A pointer-to-member constant written &Class::member.
6255 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6256 if (UnOp->getOpcode() == UO_AddrOf) {
6257 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6258 if (DRE && !DRE->getQualifier())
6259 DRE = nullptr;
6260 }
6261 }
6262 // A constant of pointer-to-member type.
6263 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6264 ValueDecl *VD = DRE->getDecl();
6265 if (VD->getType()->isMemberPointerType()) {
6266 if (isa<NonTypeTemplateParmDecl>(VD)) {
6267 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6268 Converted = TemplateArgument(Arg);
6269 } else {
6270 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6271 Converted = TemplateArgument(VD, ParamType);
6272 }
6273 return Invalid;
6274 }
6275 }
6276
6277 DRE = nullptr;
6278 }
6279
6280 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6281
6282 // Check for a null pointer value.
6283 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6284 Entity)) {
6285 case NPV_Error:
6286 return true;
6287 case NPV_NullPointer:
6288 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6289 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6290 /*isNullPtr*/true);
6291 return false;
6292 case NPV_NotNullPointer:
6293 break;
6294 }
6295
6296 if (S.IsQualificationConversion(ResultArg->getType(),
6297 ParamType.getNonReferenceType(), false,
6298 ObjCLifetimeConversion)) {
6299 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6300 ResultArg->getValueKind())
6301 .get();
6302 } else if (!S.Context.hasSameUnqualifiedType(
6303 ResultArg->getType(), ParamType.getNonReferenceType())) {
6304 // We can't perform this conversion.
6305 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6306 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6307 S.Diag(Param->getLocation(), diag::note_template_param_here);
6308 return true;
6309 }
6310
6311 if (!DRE)
6312 return S.Diag(Arg->getBeginLoc(),
6313 diag::err_template_arg_not_pointer_to_member_form)
6314 << Arg->getSourceRange();
6315
6316 if (isa<FieldDecl>(DRE->getDecl()) ||
6317 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6318 isa<CXXMethodDecl>(DRE->getDecl())) {
6319 assert((isa<FieldDecl>(DRE->getDecl()) ||(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6322, __PRETTY_FUNCTION__))
6320 isa<IndirectFieldDecl>(DRE->getDecl()) ||(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6322, __PRETTY_FUNCTION__))
6321 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6322, __PRETTY_FUNCTION__))
6322 "Only non-static member pointers can make it here")(((isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl
>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->
getDecl())->isStatic()) && "Only non-static member pointers can make it here"
) ? static_cast<void> (0) : __assert_fail ("(isa<FieldDecl>(DRE->getDecl()) || isa<IndirectFieldDecl>(DRE->getDecl()) || !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && \"Only non-static member pointers can make it here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6322, __PRETTY_FUNCTION__))
;
6323
6324 // Okay: this is the address of a non-static member, and therefore
6325 // a member pointer constant.
6326 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6327 Converted = TemplateArgument(Arg);
6328 } else {
6329 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
6330 Converted = TemplateArgument(D, ParamType);
6331 }
6332 return Invalid;
6333 }
6334
6335 // We found something else, but we don't know specifically what it is.
6336 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6337 << Arg->getSourceRange();
6338 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6339 return true;
6340}
6341
6342/// Check a template argument against its corresponding
6343/// non-type template parameter.
6344///
6345/// This routine implements the semantics of C++ [temp.arg.nontype].
6346/// If an error occurred, it returns ExprError(); otherwise, it
6347/// returns the converted template argument. \p ParamType is the
6348/// type of the non-type template parameter after it has been instantiated.
6349ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6350 QualType ParamType, Expr *Arg,
6351 TemplateArgument &Converted,
6352 CheckTemplateArgumentKind CTAK) {
6353 SourceLocation StartLoc = Arg->getBeginLoc();
6354
6355 // If the parameter type somehow involves auto, deduce the type now.
6356 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
6357 // During template argument deduction, we allow 'decltype(auto)' to
6358 // match an arbitrary dependent argument.
6359 // FIXME: The language rules don't say what happens in this case.
6360 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6361 // expression is merely instantiation-dependent; is this enough?
6362 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6363 auto *AT = dyn_cast<AutoType>(ParamType);
6364 if (AT && AT->isDecltypeAuto()) {
6365 Converted = TemplateArgument(Arg);
6366 return Arg;
6367 }
6368 }
6369
6370 // When checking a deduced template argument, deduce from its type even if
6371 // the type is dependent, in order to check the types of non-type template
6372 // arguments line up properly in partial ordering.
6373 Optional<unsigned> Depth = Param->getDepth() + 1;
6374 Expr *DeductionArg = Arg;
6375 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6376 DeductionArg = PE->getPattern();
6377 if (DeduceAutoType(
6378 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6379 DeductionArg, ParamType, Depth) == DAR_Failed) {
6380 Diag(Arg->getExprLoc(),
6381 diag::err_non_type_template_parm_type_deduction_failure)
6382 << Param->getDeclName() << Param->getType() << Arg->getType()
6383 << Arg->getSourceRange();
6384 Diag(Param->getLocation(), diag::note_template_param_here);
6385 return ExprError();
6386 }
6387 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6388 // an error. The error message normally references the parameter
6389 // declaration, but here we'll pass the argument location because that's
6390 // where the parameter type is deduced.
6391 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6392 if (ParamType.isNull()) {
6393 Diag(Param->getLocation(), diag::note_template_param_here);
6394 return ExprError();
6395 }
6396 }
6397
6398 // We should have already dropped all cv-qualifiers by now.
6399 assert(!ParamType.hasQualifiers() &&((!ParamType.hasQualifiers() && "non-type template parameter type cannot be qualified"
) ? static_cast<void> (0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6400, __PRETTY_FUNCTION__))
6400 "non-type template parameter type cannot be qualified")((!ParamType.hasQualifiers() && "non-type template parameter type cannot be qualified"
) ? static_cast<void> (0) : __assert_fail ("!ParamType.hasQualifiers() && \"non-type template parameter type cannot be qualified\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6400, __PRETTY_FUNCTION__))
;
6401
6402 if (CTAK == CTAK_Deduced &&
6403 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6404 Arg->getType())) {
6405 // FIXME: If either type is dependent, we skip the check. This isn't
6406 // correct, since during deduction we're supposed to have replaced each
6407 // template parameter with some unique (non-dependent) placeholder.
6408 // FIXME: If the argument type contains 'auto', we carry on and fail the
6409 // type check in order to force specific types to be more specialized than
6410 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6411 // work.
6412 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6413 !Arg->getType()->getContainedAutoType()) {
6414 Converted = TemplateArgument(Arg);
6415 return Arg;
6416 }
6417 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6418 // we should actually be checking the type of the template argument in P,
6419 // not the type of the template argument deduced from A, against the
6420 // template parameter type.
6421 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6422 << Arg->getType()
6423 << ParamType.getUnqualifiedType();
6424 Diag(Param->getLocation(), diag::note_template_param_here);
6425 return ExprError();
6426 }
6427
6428 // If either the parameter has a dependent type or the argument is
6429 // type-dependent, there's nothing we can check now. The argument only
6430 // contains an unexpanded pack during partial ordering, and there's
6431 // nothing more we can check in that case.
6432 if (ParamType->isDependentType() || Arg->isTypeDependent() ||
6433 Arg->containsUnexpandedParameterPack()) {
6434 // Force the argument to the type of the parameter to maintain invariants.
6435 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6436 if (PE)
6437 Arg = PE->getPattern();
6438 ExprResult E = ImpCastExprToType(
6439 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6440 ParamType->isLValueReferenceType() ? VK_LValue :
6441 ParamType->isRValueReferenceType() ? VK_XValue : VK_RValue);
6442 if (E.isInvalid())
6443 return ExprError();
6444 if (PE) {
6445 // Recreate a pack expansion if we unwrapped one.
6446 E = new (Context)
6447 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6448 PE->getNumExpansions());
6449 }
6450 Converted = TemplateArgument(E.get());
6451 return E;
6452 }
6453
6454 // The initialization of the parameter from the argument is
6455 // a constant-evaluated context.
6456 EnterExpressionEvaluationContext ConstantEvaluated(
6457 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6458
6459 if (getLangOpts().CPlusPlus17) {
6460 // C++17 [temp.arg.nontype]p1:
6461 // A template-argument for a non-type template parameter shall be
6462 // a converted constant expression of the type of the template-parameter.
6463 APValue Value;
6464 ExprResult ArgResult = CheckConvertedConstantExpression(
6465 Arg, ParamType, Value, CCEK_TemplateArg);
6466 if (ArgResult.isInvalid())
6467 return ExprError();
6468
6469 // For a value-dependent argument, CheckConvertedConstantExpression is
6470 // permitted (and expected) to be unable to determine a value.
6471 if (ArgResult.get()->isValueDependent()) {
6472 Converted = TemplateArgument(ArgResult.get());
6473 return ArgResult;
6474 }
6475
6476 QualType CanonParamType = Context.getCanonicalType(ParamType);
6477
6478 // Convert the APValue to a TemplateArgument.
6479 switch (Value.getKind()) {
6480 case APValue::None:
6481 assert(ParamType->isNullPtrType())((ParamType->isNullPtrType()) ? static_cast<void> (0
) : __assert_fail ("ParamType->isNullPtrType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6481, __PRETTY_FUNCTION__))
;
6482 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6483 break;
6484 case APValue::Indeterminate:
6485 llvm_unreachable("result of constant evaluation should be initialized")::llvm::llvm_unreachable_internal("result of constant evaluation should be initialized"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6485)
;
6486 break;
6487 case APValue::Int:
6488 assert(ParamType->isIntegralOrEnumerationType())((ParamType->isIntegralOrEnumerationType()) ? static_cast<
void> (0) : __assert_fail ("ParamType->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6488, __PRETTY_FUNCTION__))
;
6489 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6490 break;
6491 case APValue::MemberPointer: {
6492 assert(ParamType->isMemberPointerType())((ParamType->isMemberPointerType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isMemberPointerType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6492, __PRETTY_FUNCTION__))
;
6493
6494 // FIXME: We need TemplateArgument representation and mangling for these.
6495 if (!Value.getMemberPointerPath().empty()) {
6496 Diag(Arg->getBeginLoc(),
6497 diag::err_template_arg_member_ptr_base_derived_not_supported)
6498 << Value.getMemberPointerDecl() << ParamType
6499 << Arg->getSourceRange();
6500 return ExprError();
6501 }
6502
6503 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6504 Converted = VD ? TemplateArgument(VD, CanonParamType)
6505 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6506 break;
6507 }
6508 case APValue::LValue: {
6509 // For a non-type template-parameter of pointer or reference type,
6510 // the value of the constant expression shall not refer to
6511 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||((ParamType->isPointerType() || ParamType->isReferenceType
() || ParamType->isNullPtrType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6512, __PRETTY_FUNCTION__))
6512 ParamType->isNullPtrType())((ParamType->isPointerType() || ParamType->isReferenceType
() || ParamType->isNullPtrType()) ? static_cast<void>
(0) : __assert_fail ("ParamType->isPointerType() || ParamType->isReferenceType() || ParamType->isNullPtrType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6512, __PRETTY_FUNCTION__))
;
6513 // -- a temporary object
6514 // -- a string literal
6515 // -- the result of a typeid expression, or
6516 // -- a predefined __func__ variable
6517 APValue::LValueBase Base = Value.getLValueBase();
6518 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6519 if (Base && !VD) {
6520 auto *E = Base.dyn_cast<const Expr *>();
6521 if (E && isa<CXXUuidofExpr>(E)) {
6522 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
6523 break;
6524 }
6525 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6526 << Arg->getSourceRange();
6527 return ExprError();
6528 }
6529 // -- a subobject
6530 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6531 VD && VD->getType()->isArrayType() &&
6532 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6533 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6534 // Per defect report (no number yet):
6535 // ... other than a pointer to the first element of a complete array
6536 // object.
6537 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6538 Value.isLValueOnePastTheEnd()) {
6539 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6540 << Value.getAsString(Context, ParamType);
6541 return ExprError();
6542 }
6543 assert((VD || !ParamType->isReferenceType()) &&(((VD || !ParamType->isReferenceType()) && "null reference should not be a constant expression"
) ? static_cast<void> (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6544, __PRETTY_FUNCTION__))
6544 "null reference should not be a constant expression")(((VD || !ParamType->isReferenceType()) && "null reference should not be a constant expression"
) ? static_cast<void> (0) : __assert_fail ("(VD || !ParamType->isReferenceType()) && \"null reference should not be a constant expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6544, __PRETTY_FUNCTION__))
;
6545 assert((!VD || !ParamType->isNullPtrType()) &&(((!VD || !ParamType->isNullPtrType()) && "non-null value of type nullptr_t?"
) ? static_cast<void> (0) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6546, __PRETTY_FUNCTION__))
6546 "non-null value of type nullptr_t?")(((!VD || !ParamType->isNullPtrType()) && "non-null value of type nullptr_t?"
) ? static_cast<void> (0) : __assert_fail ("(!VD || !ParamType->isNullPtrType()) && \"non-null value of type nullptr_t?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6546, __PRETTY_FUNCTION__))
;
6547 Converted = VD ? TemplateArgument(VD, CanonParamType)
6548 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6549 break;
6550 }
6551 case APValue::AddrLabelDiff:
6552 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6553 case APValue::FixedPoint:
6554 case APValue::Float:
6555 case APValue::ComplexInt:
6556 case APValue::ComplexFloat:
6557 case APValue::Vector:
6558 case APValue::Array:
6559 case APValue::Struct:
6560 case APValue::Union:
6561 llvm_unreachable("invalid kind for template argument")::llvm::llvm_unreachable_internal("invalid kind for template argument"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6561)
;
6562 }
6563
6564 return ArgResult.get();
6565 }
6566
6567 // C++ [temp.arg.nontype]p5:
6568 // The following conversions are performed on each expression used
6569 // as a non-type template-argument. If a non-type
6570 // template-argument cannot be converted to the type of the
6571 // corresponding template-parameter then the program is
6572 // ill-formed.
6573 if (ParamType->isIntegralOrEnumerationType()) {
6574 // C++11:
6575 // -- for a non-type template-parameter of integral or
6576 // enumeration type, conversions permitted in a converted
6577 // constant expression are applied.
6578 //
6579 // C++98:
6580 // -- for a non-type template-parameter of integral or
6581 // enumeration type, integral promotions (4.5) and integral
6582 // conversions (4.7) are applied.
6583
6584 if (getLangOpts().CPlusPlus11) {
6585 // C++ [temp.arg.nontype]p1:
6586 // A template-argument for a non-type, non-template template-parameter
6587 // shall be one of:
6588 //
6589 // -- for a non-type template-parameter of integral or enumeration
6590 // type, a converted constant expression of the type of the
6591 // template-parameter; or
6592 llvm::APSInt Value;
6593 ExprResult ArgResult =
6594 CheckConvertedConstantExpression(Arg, ParamType, Value,
6595 CCEK_TemplateArg);
6596 if (ArgResult.isInvalid())
6597 return ExprError();
6598
6599 // We can't check arbitrary value-dependent arguments.
6600 if (ArgResult.get()->isValueDependent()) {
6601 Converted = TemplateArgument(ArgResult.get());
6602 return ArgResult;
6603 }
6604
6605 // Widen the argument value to sizeof(parameter type). This is almost
6606 // always a no-op, except when the parameter type is bool. In
6607 // that case, this may extend the argument from 1 bit to 8 bits.
6608 QualType IntegerType = ParamType;
6609 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6610 IntegerType = Enum->getDecl()->getIntegerType();
6611 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6612
6613 Converted = TemplateArgument(Context, Value,
6614 Context.getCanonicalType(ParamType));
6615 return ArgResult;
6616 }
6617
6618 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6619 if (ArgResult.isInvalid())
6620 return ExprError();
6621 Arg = ArgResult.get();
6622
6623 QualType ArgType = Arg->getType();
6624
6625 // C++ [temp.arg.nontype]p1:
6626 // A template-argument for a non-type, non-template
6627 // template-parameter shall be one of:
6628 //
6629 // -- an integral constant-expression of integral or enumeration
6630 // type; or
6631 // -- the name of a non-type template-parameter; or
6632 llvm::APSInt Value;
6633 if (!ArgType->isIntegralOrEnumerationType()) {
6634 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6635 << ArgType << Arg->getSourceRange();
6636 Diag(Param->getLocation(), diag::note_template_param_here);
6637 return ExprError();
6638 } else if (!Arg->isValueDependent()) {
6639 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6640 QualType T;
6641
6642 public:
6643 TmplArgICEDiagnoser(QualType T) : T(T) { }
6644
6645 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6646 SourceRange SR) override {
6647 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6648 }
6649 } Diagnoser(ArgType);
6650
6651 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6652 false).get();
6653 if (!Arg)
6654 return ExprError();
6655 }
6656
6657 // From here on out, all we care about is the unqualified form
6658 // of the argument type.
6659 ArgType = ArgType.getUnqualifiedType();
6660
6661 // Try to convert the argument to the parameter's type.
6662 if (Context.hasSameType(ParamType, ArgType)) {
6663 // Okay: no conversion necessary
6664 } else if (ParamType->isBooleanType()) {
6665 // This is an integral-to-boolean conversion.
6666 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6667 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6668 !ParamType->isEnumeralType()) {
6669 // This is an integral promotion or conversion.
6670 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6671 } else {
6672 // We can't perform this conversion.
6673 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6674 << Arg->getType() << ParamType << Arg->getSourceRange();
6675 Diag(Param->getLocation(), diag::note_template_param_here);
6676 return ExprError();
6677 }
6678
6679 // Add the value of this argument to the list of converted
6680 // arguments. We use the bitwidth and signedness of the template
6681 // parameter.
6682 if (Arg->isValueDependent()) {
6683 // The argument is value-dependent. Create a new
6684 // TemplateArgument with the converted expression.
6685 Converted = TemplateArgument(Arg);
6686 return Arg;
6687 }
6688
6689 QualType IntegerType = Context.getCanonicalType(ParamType);
6690 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6691 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6692
6693 if (ParamType->isBooleanType()) {
6694 // Value must be zero or one.
6695 Value = Value != 0;
6696 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6697 if (Value.getBitWidth() != AllowedBits)
6698 Value = Value.extOrTrunc(AllowedBits);
6699 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6700 } else {
6701 llvm::APSInt OldValue = Value;
6702
6703 // Coerce the template argument's value to the value it will have
6704 // based on the template parameter's type.
6705 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6706 if (Value.getBitWidth() != AllowedBits)
6707 Value = Value.extOrTrunc(AllowedBits);
6708 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6709
6710 // Complain if an unsigned parameter received a negative value.
6711 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6712 && (OldValue.isSigned() && OldValue.isNegative())) {
6713 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6714 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6715 << Arg->getSourceRange();
6716 Diag(Param->getLocation(), diag::note_template_param_here);
6717 }
6718
6719 // Complain if we overflowed the template parameter's type.
6720 unsigned RequiredBits;
6721 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6722 RequiredBits = OldValue.getActiveBits();
6723 else if (OldValue.isUnsigned())
6724 RequiredBits = OldValue.getActiveBits() + 1;
6725 else
6726 RequiredBits = OldValue.getMinSignedBits();
6727 if (RequiredBits > AllowedBits) {
6728 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6729 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6730 << Arg->getSourceRange();
6731 Diag(Param->getLocation(), diag::note_template_param_here);
6732 }
6733 }
6734
6735 Converted = TemplateArgument(Context, Value,
6736 ParamType->isEnumeralType()
6737 ? Context.getCanonicalType(ParamType)
6738 : IntegerType);
6739 return Arg;
6740 }
6741
6742 QualType ArgType = Arg->getType();
6743 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6744
6745 // Handle pointer-to-function, reference-to-function, and
6746 // pointer-to-member-function all in (roughly) the same way.
6747 if (// -- For a non-type template-parameter of type pointer to
6748 // function, only the function-to-pointer conversion (4.3) is
6749 // applied. If the template-argument represents a set of
6750 // overloaded functions (or a pointer to such), the matching
6751 // function is selected from the set (13.4).
6752 (ParamType->isPointerType() &&
6753 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6754 // -- For a non-type template-parameter of type reference to
6755 // function, no conversions apply. If the template-argument
6756 // represents a set of overloaded functions, the matching
6757 // function is selected from the set (13.4).
6758 (ParamType->isReferenceType() &&
6759 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6760 // -- For a non-type template-parameter of type pointer to
6761 // member function, no conversions apply. If the
6762 // template-argument represents a set of overloaded member
6763 // functions, the matching member function is selected from
6764 // the set (13.4).
6765 (ParamType->isMemberPointerType() &&
6766 ParamType->getAs<MemberPointerType>()->getPointeeType()
6767 ->isFunctionType())) {
6768
6769 if (Arg->getType() == Context.OverloadTy) {
6770 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6771 true,
6772 FoundResult)) {
6773 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6774 return ExprError();
6775
6776 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6777 ArgType = Arg->getType();
6778 } else
6779 return ExprError();
6780 }
6781
6782 if (!ParamType->isMemberPointerType()) {
6783 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6784 ParamType,
6785 Arg, Converted))
6786 return ExprError();
6787 return Arg;
6788 }
6789
6790 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6791 Converted))
6792 return ExprError();
6793 return Arg;
6794 }
6795
6796 if (ParamType->isPointerType()) {
6797 // -- for a non-type template-parameter of type pointer to
6798 // object, qualification conversions (4.4) and the
6799 // array-to-pointer conversion (4.2) are applied.
6800 // C++0x also allows a value of std::nullptr_t.
6801 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&((ParamType->getPointeeType()->isIncompleteOrObjectType
() && "Only object pointers allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6802, __PRETTY_FUNCTION__))
6802 "Only object pointers allowed here")((ParamType->getPointeeType()->isIncompleteOrObjectType
() && "Only object pointers allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamType->getPointeeType()->isIncompleteOrObjectType() && \"Only object pointers allowed here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6802, __PRETTY_FUNCTION__))
;
6803
6804 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6805 ParamType,
6806 Arg, Converted))
6807 return ExprError();
6808 return Arg;
6809 }
6810
6811 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6812 // -- For a non-type template-parameter of type reference to
6813 // object, no conversions apply. The type referred to by the
6814 // reference may be more cv-qualified than the (otherwise
6815 // identical) type of the template-argument. The
6816 // template-parameter is bound directly to the
6817 // template-argument, which must be an lvalue.
6818 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&((ParamRefType->getPointeeType()->isIncompleteOrObjectType
() && "Only object references allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6819, __PRETTY_FUNCTION__))
6819 "Only object references allowed here")((ParamRefType->getPointeeType()->isIncompleteOrObjectType
() && "Only object references allowed here") ? static_cast
<void> (0) : __assert_fail ("ParamRefType->getPointeeType()->isIncompleteOrObjectType() && \"Only object references allowed here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6819, __PRETTY_FUNCTION__))
;
6820
6821 if (Arg->getType() == Context.OverloadTy) {
6822 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6823 ParamRefType->getPointeeType(),
6824 true,
6825 FoundResult)) {
6826 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6827 return ExprError();
6828
6829 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6830 ArgType = Arg->getType();
6831 } else
6832 return ExprError();
6833 }
6834
6835 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6836 ParamType,
6837 Arg, Converted))
6838 return ExprError();
6839 return Arg;
6840 }
6841
6842 // Deal with parameters of type std::nullptr_t.
6843 if (ParamType->isNullPtrType()) {
6844 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6845 Converted = TemplateArgument(Arg);
6846 return Arg;
6847 }
6848
6849 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6850 case NPV_NotNullPointer:
6851 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6852 << Arg->getType() << ParamType;
6853 Diag(Param->getLocation(), diag::note_template_param_here);
6854 return ExprError();
6855
6856 case NPV_Error:
6857 return ExprError();
6858
6859 case NPV_NullPointer:
6860 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6861 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6862 /*isNullPtr*/true);
6863 return Arg;
6864 }
6865 }
6866
6867 // -- For a non-type template-parameter of type pointer to data
6868 // member, qualification conversions (4.4) are applied.
6869 assert(ParamType->isMemberPointerType() && "Only pointers to members remain")((ParamType->isMemberPointerType() && "Only pointers to members remain"
) ? static_cast<void> (0) : __assert_fail ("ParamType->isMemberPointerType() && \"Only pointers to members remain\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6869, __PRETTY_FUNCTION__))
;
6870
6871 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6872 Converted))
6873 return ExprError();
6874 return Arg;
6875}
6876
6877static void DiagnoseTemplateParameterListArityMismatch(
6878 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6879 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6880
6881/// Check a template argument against its corresponding
6882/// template template parameter.
6883///
6884/// This routine implements the semantics of C++ [temp.arg.template].
6885/// It returns true if an error occurred, and false otherwise.
6886bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6887 TemplateArgumentLoc &Arg) {
6888 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6889 TemplateDecl *Template = Name.getAsTemplateDecl();
6890 if (!Template) {
6891 // Any dependent template name is fine.
6892 assert(Name.isDependent() && "Non-dependent template isn't a declaration?")((Name.isDependent() && "Non-dependent template isn't a declaration?"
) ? static_cast<void> (0) : __assert_fail ("Name.isDependent() && \"Non-dependent template isn't a declaration?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6892, __PRETTY_FUNCTION__))
;
6893 return false;
6894 }
6895
6896 if (Template->isInvalidDecl())
6897 return true;
6898
6899 // C++0x [temp.arg.template]p1:
6900 // A template-argument for a template template-parameter shall be
6901 // the name of a class template or an alias template, expressed as an
6902 // id-expression. When the template-argument names a class template, only
6903 // primary class templates are considered when matching the
6904 // template template argument with the corresponding parameter;
6905 // partial specializations are not considered even if their
6906 // parameter lists match that of the template template parameter.
6907 //
6908 // Note that we also allow template template parameters here, which
6909 // will happen when we are dealing with, e.g., class template
6910 // partial specializations.
6911 if (!isa<ClassTemplateDecl>(Template) &&
6912 !isa<TemplateTemplateParmDecl>(Template) &&
6913 !isa<TypeAliasTemplateDecl>(Template) &&
6914 !isa<BuiltinTemplateDecl>(Template)) {
6915 assert(isa<FunctionTemplateDecl>(Template) &&((isa<FunctionTemplateDecl>(Template) && "Only function templates are possible here"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6916, __PRETTY_FUNCTION__))
6916 "Only function templates are possible here")((isa<FunctionTemplateDecl>(Template) && "Only function templates are possible here"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionTemplateDecl>(Template) && \"Only function templates are possible here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6916, __PRETTY_FUNCTION__))
;
6917 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6918 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6919 << Template;
6920 }
6921
6922 // C++1z [temp.arg.template]p3: (DR 150)
6923 // A template-argument matches a template template-parameter P when P
6924 // is at least as specialized as the template-argument A.
6925 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6926 // Quick check for the common case:
6927 // If P contains a parameter pack, then A [...] matches P if each of A's
6928 // template parameters matches the corresponding template parameter in
6929 // the template-parameter-list of P.
6930 if (TemplateParameterListsAreEqual(
6931 Template->getTemplateParameters(), Params, false,
6932 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6933 return false;
6934
6935 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6936 Arg.getLocation()))
6937 return false;
6938 // FIXME: Produce better diagnostics for deduction failures.
6939 }
6940
6941 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6942 Params,
6943 true,
6944 TPL_TemplateTemplateArgumentMatch,
6945 Arg.getLocation());
6946}
6947
6948/// Given a non-type template argument that refers to a
6949/// declaration and the type of its corresponding non-type template
6950/// parameter, produce an expression that properly refers to that
6951/// declaration.
6952ExprResult
6953Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6954 QualType ParamType,
6955 SourceLocation Loc) {
6956 // C++ [temp.param]p8:
6957 //
6958 // A non-type template-parameter of type "array of T" or
6959 // "function returning T" is adjusted to be of type "pointer to
6960 // T" or "pointer to function returning T", respectively.
6961 if (ParamType->isArrayType())
6962 ParamType = Context.getArrayDecayedType(ParamType);
6963 else if (ParamType->isFunctionType())
6964 ParamType = Context.getPointerType(ParamType);
6965
6966 // For a NULL non-type template argument, return nullptr casted to the
6967 // parameter's type.
6968 if (Arg.getKind() == TemplateArgument::NullPtr) {
6969 return ImpCastExprToType(
6970 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6971 ParamType,
6972 ParamType->getAs<MemberPointerType>()
6973 ? CK_NullToMemberPointer
6974 : CK_NullToPointer);
6975 }
6976 assert(Arg.getKind() == TemplateArgument::Declaration &&((Arg.getKind() == TemplateArgument::Declaration && "Only declaration template arguments permitted here"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6977, __PRETTY_FUNCTION__))
6977 "Only declaration template arguments permitted here")((Arg.getKind() == TemplateArgument::Declaration && "Only declaration template arguments permitted here"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Declaration && \"Only declaration template arguments permitted here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 6977, __PRETTY_FUNCTION__))
;
6978
6979 ValueDecl *VD = Arg.getAsDecl();
6980
6981 if (VD->getDeclContext()->isRecord() &&
6982 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6983 isa<IndirectFieldDecl>(VD))) {
6984 // If the value is a class member, we might have a pointer-to-member.
6985 // Determine whether the non-type template template parameter is of
6986 // pointer-to-member type. If so, we need to build an appropriate
6987 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6988 // would refer to the member itself.
6989 if (ParamType->isMemberPointerType()) {
6990 QualType ClassType
6991 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6992 NestedNameSpecifier *Qualifier
6993 = NestedNameSpecifier::Create(Context, nullptr, false,
6994 ClassType.getTypePtr());
6995 CXXScopeSpec SS;
6996 SS.MakeTrivial(Context, Qualifier, Loc);
6997
6998 // The actual value-ness of this is unimportant, but for
6999 // internal consistency's sake, references to instance methods
7000 // are r-values.
7001 ExprValueKind VK = VK_LValue;
7002 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
7003 VK = VK_RValue;
7004
7005 ExprResult RefExpr = BuildDeclRefExpr(VD,
7006 VD->getType().getNonReferenceType(),
7007 VK,
7008 Loc,
7009 &SS);
7010 if (RefExpr.isInvalid())
7011 return ExprError();
7012
7013 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7014
7015 // We might need to perform a trailing qualification conversion, since
7016 // the element type on the parameter could be more qualified than the
7017 // element type in the expression we constructed.
7018 bool ObjCLifetimeConversion;
7019 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
7020 ParamType.getUnqualifiedType(), false,
7021 ObjCLifetimeConversion))
7022 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
7023
7024 assert(!RefExpr.isInvalid() &&((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7026, __PRETTY_FUNCTION__))
7025 Context.hasSameType(((Expr*) RefExpr.get())->getType(),((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7026, __PRETTY_FUNCTION__))
7026 ParamType.getUnqualifiedType()))((!RefExpr.isInvalid() && Context.hasSameType(((Expr*
) RefExpr.get())->getType(), ParamType.getUnqualifiedType(
))) ? static_cast<void> (0) : __assert_fail ("!RefExpr.isInvalid() && Context.hasSameType(((Expr*) RefExpr.get())->getType(), ParamType.getUnqualifiedType())"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7026, __PRETTY_FUNCTION__))
;
7027 return RefExpr;
7028 }
7029 }
7030
7031 QualType T = VD->getType().getNonReferenceType();
7032
7033 if (ParamType->isPointerType()) {
7034 // When the non-type template parameter is a pointer, take the
7035 // address of the declaration.
7036 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
7037 if (RefExpr.isInvalid())
7038 return ExprError();
7039
7040 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
7041 (T->isFunctionType() || T->isArrayType())) {
7042 // Decay functions and arrays unless we're forming a pointer to array.
7043 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7044 if (RefExpr.isInvalid())
7045 return ExprError();
7046
7047 return RefExpr;
7048 }
7049
7050 // Take the address of everything else
7051 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7052 }
7053
7054 ExprValueKind VK = VK_RValue;
7055
7056 // If the non-type template parameter has reference type, qualify the
7057 // resulting declaration reference with the extra qualifiers on the
7058 // type that the reference refers to.
7059 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
7060 VK = VK_LValue;
7061 T = Context.getQualifiedType(T,
7062 TargetRef->getPointeeType().getQualifiers());
7063 } else if (isa<FunctionDecl>(VD)) {
7064 // References to functions are always lvalues.
7065 VK = VK_LValue;
7066 }
7067
7068 return BuildDeclRefExpr(VD, T, VK, Loc);
7069}
7070
7071/// Construct a new expression that refers to the given
7072/// integral template argument with the given source-location
7073/// information.
7074///
7075/// This routine takes care of the mapping from an integral template
7076/// argument (which may have any integral type) to the appropriate
7077/// literal value.
7078ExprResult
7079Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7080 SourceLocation Loc) {
7081 assert(Arg.getKind() == TemplateArgument::Integral &&((Arg.getKind() == TemplateArgument::Integral && "Operation is only valid for integral template arguments"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7082, __PRETTY_FUNCTION__))
7082 "Operation is only valid for integral template arguments")((Arg.getKind() == TemplateArgument::Integral && "Operation is only valid for integral template arguments"
) ? static_cast<void> (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Integral && \"Operation is only valid for integral template arguments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7082, __PRETTY_FUNCTION__))
;
7083 QualType OrigT = Arg.getIntegralType();
7084
7085 // If this is an enum type that we're instantiating, we need to use an integer
7086 // type the same size as the enumerator. We don't want to build an
7087 // IntegerLiteral with enum type. The integer type of an enum type can be of
7088 // any integral type with C++11 enum classes, make sure we create the right
7089 // type of literal for it.
7090 QualType T = OrigT;
7091 if (const EnumType *ET = OrigT->getAs<EnumType>())
7092 T = ET->getDecl()->getIntegerType();
7093
7094 Expr *E;
7095 if (T->isAnyCharacterType()) {
7096 CharacterLiteral::CharacterKind Kind;
7097 if (T->isWideCharType())
7098 Kind = CharacterLiteral::Wide;
7099 else if (T->isChar8Type() && getLangOpts().Char8)
7100 Kind = CharacterLiteral::UTF8;
7101 else if (T->isChar16Type())
7102 Kind = CharacterLiteral::UTF16;
7103 else if (T->isChar32Type())
7104 Kind = CharacterLiteral::UTF32;
7105 else
7106 Kind = CharacterLiteral::Ascii;
7107
7108 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7109 Kind, T, Loc);
7110 } else if (T->isBooleanType()) {
7111 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7112 T, Loc);
7113 } else if (T->isNullPtrType()) {
7114 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7115 } else {
7116 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
7117 }
7118
7119 if (OrigT->isEnumeralType()) {
7120 // FIXME: This is a hack. We need a better way to handle substituted
7121 // non-type template parameters.
7122 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7123 nullptr,
7124 Context.getTrivialTypeSourceInfo(OrigT, Loc),
7125 Loc, Loc);
7126 }
7127
7128 return E;
7129}
7130
7131/// Match two template parameters within template parameter lists.
7132static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7133 bool Complain,
7134 Sema::TemplateParameterListEqualKind Kind,
7135 SourceLocation TemplateArgLoc) {
7136 // Check the actual kind (type, non-type, template).
7137 if (Old->getKind() != New->getKind()) {
7138 if (Complain) {
7139 unsigned NextDiag = diag::err_template_param_different_kind;
7140 if (TemplateArgLoc.isValid()) {
7141 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7142 NextDiag = diag::note_template_param_different_kind;
7143 }
7144 S.Diag(New->getLocation(), NextDiag)
7145 << (Kind != Sema::TPL_TemplateMatch);
7146 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7147 << (Kind != Sema::TPL_TemplateMatch);
7148 }
7149
7150 return false;
7151 }
7152
7153 // Check that both are parameter packs or neither are parameter packs.
7154 // However, if we are matching a template template argument to a
7155 // template template parameter, the template template parameter can have
7156 // a parameter pack where the template template argument does not.
7157 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7158 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7159 Old->isTemplateParameterPack())) {
7160 if (Complain) {
7161 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7162 if (TemplateArgLoc.isValid()) {
7163 S.Diag(TemplateArgLoc,
7164 diag::err_template_arg_template_params_mismatch);
7165 NextDiag = diag::note_template_parameter_pack_non_pack;
7166 }
7167
7168 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7169 : isa<NonTypeTemplateParmDecl>(New)? 1
7170 : 2;
7171 S.Diag(New->getLocation(), NextDiag)
7172 << ParamKind << New->isParameterPack();
7173 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7174 << ParamKind << Old->isParameterPack();
7175 }
7176
7177 return false;
7178 }
7179
7180 // For non-type template parameters, check the type of the parameter.
7181 if (NonTypeTemplateParmDecl *OldNTTP
7182 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7183 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7184
7185 // If we are matching a template template argument to a template
7186 // template parameter and one of the non-type template parameter types
7187 // is dependent, then we must wait until template instantiation time
7188 // to actually compare the arguments.
7189 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7190 (OldNTTP->getType()->isDependentType() ||
7191 NewNTTP->getType()->isDependentType()))
7192 return true;
7193
7194 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7195 if (Complain) {
7196 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7197 if (TemplateArgLoc.isValid()) {
7198 S.Diag(TemplateArgLoc,
7199 diag::err_template_arg_template_params_mismatch);
7200 NextDiag = diag::note_template_nontype_parm_different_type;
7201 }
7202 S.Diag(NewNTTP->getLocation(), NextDiag)
7203 << NewNTTP->getType()
7204 << (Kind != Sema::TPL_TemplateMatch);
7205 S.Diag(OldNTTP->getLocation(),
7206 diag::note_template_nontype_parm_prev_declaration)
7207 << OldNTTP->getType();
7208 }
7209
7210 return false;
7211 }
7212
7213 return true;
7214 }
7215
7216 // For template template parameters, check the template parameter types.
7217 // The template parameter lists of template template
7218 // parameters must agree.
7219 if (TemplateTemplateParmDecl *OldTTP
7220 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
7221 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7222 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7223 OldTTP->getTemplateParameters(),
7224 Complain,
7225 (Kind == Sema::TPL_TemplateMatch
7226 ? Sema::TPL_TemplateTemplateParmMatch
7227 : Kind),
7228 TemplateArgLoc);
7229 }
7230
7231 return true;
7232}
7233
7234/// Diagnose a known arity mismatch when comparing template argument
7235/// lists.
7236static
7237void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7238 TemplateParameterList *New,
7239 TemplateParameterList *Old,
7240 Sema::TemplateParameterListEqualKind Kind,
7241 SourceLocation TemplateArgLoc) {
7242 unsigned NextDiag = diag::err_template_param_list_different_arity;
7243 if (TemplateArgLoc.isValid()) {
7244 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7245 NextDiag = diag::note_template_param_list_different_arity;
7246 }
7247 S.Diag(New->getTemplateLoc(), NextDiag)
7248 << (New->size() > Old->size())
7249 << (Kind != Sema::TPL_TemplateMatch)
7250 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7251 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7252 << (Kind != Sema::TPL_TemplateMatch)
7253 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7254}
7255
7256/// Determine whether the given template parameter lists are
7257/// equivalent.
7258///
7259/// \param New The new template parameter list, typically written in the
7260/// source code as part of a new template declaration.
7261///
7262/// \param Old The old template parameter list, typically found via
7263/// name lookup of the template declared with this template parameter
7264/// list.
7265///
7266/// \param Complain If true, this routine will produce a diagnostic if
7267/// the template parameter lists are not equivalent.
7268///
7269/// \param Kind describes how we are to match the template parameter lists.
7270///
7271/// \param TemplateArgLoc If this source location is valid, then we
7272/// are actually checking the template parameter list of a template
7273/// argument (New) against the template parameter list of its
7274/// corresponding template template parameter (Old). We produce
7275/// slightly different diagnostics in this scenario.
7276///
7277/// \returns True if the template parameter lists are equal, false
7278/// otherwise.
7279bool
7280Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7281 TemplateParameterList *Old,
7282 bool Complain,
7283 TemplateParameterListEqualKind Kind,
7284 SourceLocation TemplateArgLoc) {
7285 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7286 if (Complain)
7287 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7288 TemplateArgLoc);
7289
7290 return false;
7291 }
7292
7293 // C++0x [temp.arg.template]p3:
7294 // A template-argument matches a template template-parameter (call it P)
7295 // when each of the template parameters in the template-parameter-list of
7296 // the template-argument's corresponding class template or alias template
7297 // (call it A) matches the corresponding template parameter in the
7298 // template-parameter-list of P. [...]
7299 TemplateParameterList::iterator NewParm = New->begin();
7300 TemplateParameterList::iterator NewParmEnd = New->end();
7301 for (TemplateParameterList::iterator OldParm = Old->begin(),
7302 OldParmEnd = Old->end();
7303 OldParm != OldParmEnd; ++OldParm) {
7304 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7305 !(*OldParm)->isTemplateParameterPack()) {
7306 if (NewParm == NewParmEnd) {
7307 if (Complain)
7308 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7309 TemplateArgLoc);
7310
7311 return false;
7312 }
7313
7314 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7315 Kind, TemplateArgLoc))
7316 return false;
7317
7318 ++NewParm;
7319 continue;
7320 }
7321
7322 // C++0x [temp.arg.template]p3:
7323 // [...] When P's template- parameter-list contains a template parameter
7324 // pack (14.5.3), the template parameter pack will match zero or more
7325 // template parameters or template parameter packs in the
7326 // template-parameter-list of A with the same type and form as the
7327 // template parameter pack in P (ignoring whether those template
7328 // parameters are template parameter packs).
7329 for (; NewParm != NewParmEnd; ++NewParm) {
7330 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7331 Kind, TemplateArgLoc))
7332 return false;
7333 }
7334 }
7335
7336 // Make sure we exhausted all of the arguments.
7337 if (NewParm != NewParmEnd) {
7338 if (Complain)
7339 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7340 TemplateArgLoc);
7341
7342 return false;
7343 }
7344
7345 return true;
7346}
7347
7348/// Check whether a template can be declared within this scope.
7349///
7350/// If the template declaration is valid in this scope, returns
7351/// false. Otherwise, issues a diagnostic and returns true.
7352bool
7353Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7354 if (!S)
7355 return false;
7356
7357 // Find the nearest enclosing declaration scope.
7358 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7359 (S->getFlags() & Scope::TemplateParamScope) != 0)
7360 S = S->getParent();
7361
7362 // C++ [temp]p4:
7363 // A template [...] shall not have C linkage.
7364 DeclContext *Ctx = S->getEntity();
7365 if (Ctx && Ctx->isExternCContext()) {
7366 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7367 << TemplateParams->getSourceRange();
7368 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7369 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7370 return true;
7371 }
7372 Ctx = Ctx->getRedeclContext();
7373
7374 // C++ [temp]p2:
7375 // A template-declaration can appear only as a namespace scope or
7376 // class scope declaration.
7377 if (Ctx) {
7378 if (Ctx->isFileContext())
7379 return false;
7380 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7381 // C++ [temp.mem]p2:
7382 // A local class shall not have member templates.
7383 if (RD->isLocalClass())
7384 return Diag(TemplateParams->getTemplateLoc(),
7385 diag::err_template_inside_local_class)
7386 << TemplateParams->getSourceRange();
7387 else
7388 return false;
7389 }
7390 }
7391
7392 return Diag(TemplateParams->getTemplateLoc(),
7393 diag::err_template_outside_namespace_or_class_scope)
7394 << TemplateParams->getSourceRange();
7395}
7396
7397/// Determine what kind of template specialization the given declaration
7398/// is.
7399static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7400 if (!D)
7401 return TSK_Undeclared;
7402
7403 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7404 return Record->getTemplateSpecializationKind();
7405 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7406 return Function->getTemplateSpecializationKind();
7407 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7408 return Var->getTemplateSpecializationKind();
7409
7410 return TSK_Undeclared;
7411}
7412
7413/// Check whether a specialization is well-formed in the current
7414/// context.
7415///
7416/// This routine determines whether a template specialization can be declared
7417/// in the current context (C++ [temp.expl.spec]p2).
7418///
7419/// \param S the semantic analysis object for which this check is being
7420/// performed.
7421///
7422/// \param Specialized the entity being specialized or instantiated, which
7423/// may be a kind of template (class template, function template, etc.) or
7424/// a member of a class template (member function, static data member,
7425/// member class).
7426///
7427/// \param PrevDecl the previous declaration of this entity, if any.
7428///
7429/// \param Loc the location of the explicit specialization or instantiation of
7430/// this entity.
7431///
7432/// \param IsPartialSpecialization whether this is a partial specialization of
7433/// a class template.
7434///
7435/// \returns true if there was an error that we cannot recover from, false
7436/// otherwise.
7437static bool CheckTemplateSpecializationScope(Sema &S,
7438 NamedDecl *Specialized,
7439 NamedDecl *PrevDecl,
7440 SourceLocation Loc,
7441 bool IsPartialSpecialization) {
7442 // Keep these "kind" numbers in sync with the %select statements in the
7443 // various diagnostics emitted by this routine.
7444 int EntityKind = 0;
7445 if (isa<ClassTemplateDecl>(Specialized))
7446 EntityKind = IsPartialSpecialization? 1 : 0;
7447 else if (isa<VarTemplateDecl>(Specialized))
7448 EntityKind = IsPartialSpecialization ? 3 : 2;
7449 else if (isa<FunctionTemplateDecl>(Specialized))
7450 EntityKind = 4;
7451 else if (isa<CXXMethodDecl>(Specialized))
7452 EntityKind = 5;
7453 else if (isa<VarDecl>(Specialized))
7454 EntityKind = 6;
7455 else if (isa<RecordDecl>(Specialized))
7456 EntityKind = 7;
7457 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7458 EntityKind = 8;
7459 else {
7460 S.Diag(Loc, diag::err_template_spec_unknown_kind)
7461 << S.getLangOpts().CPlusPlus11;
7462 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7463 return true;
7464 }
7465
7466 // C++ [temp.expl.spec]p2:
7467 // An explicit specialization may be declared in any scope in which
7468 // the corresponding primary template may be defined.
7469 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7470 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7471 << Specialized;
7472 return true;
7473 }
7474
7475 // C++ [temp.class.spec]p6:
7476 // A class template partial specialization may be declared in any
7477 // scope in which the primary template may be defined.
7478 DeclContext *SpecializedContext =
7479 Specialized->getDeclContext()->getRedeclContext();
7480 DeclContext *DC = S.CurContext->getRedeclContext();
7481
7482 // Make sure that this redeclaration (or definition) occurs in the same
7483 // scope or an enclosing namespace.
7484 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7485 : DC->Equals(SpecializedContext))) {
7486 if (isa<TranslationUnitDecl>(SpecializedContext))
7487 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7488 << EntityKind << Specialized;
7489 else {
7490 auto *ND = cast<NamedDecl>(SpecializedContext);
7491 int Diag = diag::err_template_spec_redecl_out_of_scope;
7492 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7493 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7494 S.Diag(Loc, Diag) << EntityKind << Specialized
7495 << ND << isa<CXXRecordDecl>(ND);
7496 }
7497
7498 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7499
7500 // Don't allow specializing in the wrong class during error recovery.
7501 // Otherwise, things can go horribly wrong.
7502 if (DC->isRecord())
7503 return true;
7504 }
7505
7506 return false;
7507}
7508
7509static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7510 if (!E->isTypeDependent())
7511 return SourceLocation();
7512 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7513 Checker.TraverseStmt(E);
7514 if (Checker.MatchLoc.isInvalid())
7515 return E->getSourceRange();
7516 return Checker.MatchLoc;
7517}
7518
7519static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7520 if (!TL.getType()->isDependentType())
7521 return SourceLocation();
7522 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7523 Checker.TraverseTypeLoc(TL);
7524 if (Checker.MatchLoc.isInvalid())
7525 return TL.getSourceRange();
7526 return Checker.MatchLoc;
7527}
7528
7529/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7530/// that checks non-type template partial specialization arguments.
7531static bool CheckNonTypeTemplatePartialSpecializationArgs(
7532 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7533 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7534 for (unsigned I = 0; I != NumArgs; ++I) {
7535 if (Args[I].getKind() == TemplateArgument::Pack) {
7536 if (CheckNonTypeTemplatePartialSpecializationArgs(
7537 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7538 Args[I].pack_size(), IsDefaultArgument))
7539 return true;
7540
7541 continue;
7542 }
7543
7544 if (Args[I].getKind() != TemplateArgument::Expression)
7545 continue;
7546
7547 Expr *ArgExpr = Args[I].getAsExpr();
7548
7549 // We can have a pack expansion of any of the bullets below.
7550 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7551 ArgExpr = Expansion->getPattern();
7552
7553 // Strip off any implicit casts we added as part of type checking.
7554 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7555 ArgExpr = ICE->getSubExpr();
7556
7557 // C++ [temp.class.spec]p8:
7558 // A non-type argument is non-specialized if it is the name of a
7559 // non-type parameter. All other non-type arguments are
7560 // specialized.
7561 //
7562 // Below, we check the two conditions that only apply to
7563 // specialized non-type arguments, so skip any non-specialized
7564 // arguments.
7565 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7566 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7567 continue;
7568
7569 // C++ [temp.class.spec]p9:
7570 // Within the argument list of a class template partial
7571 // specialization, the following restrictions apply:
7572 // -- A partially specialized non-type argument expression
7573 // shall not involve a template parameter of the partial
7574 // specialization except when the argument expression is a
7575 // simple identifier.
7576 // -- The type of a template parameter corresponding to a
7577 // specialized non-type argument shall not be dependent on a
7578 // parameter of the specialization.
7579 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7580 // We implement a compromise between the original rules and DR1315:
7581 // -- A specialized non-type template argument shall not be
7582 // type-dependent and the corresponding template parameter
7583 // shall have a non-dependent type.
7584 SourceRange ParamUseRange =
7585 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7586 if (ParamUseRange.isValid()) {
7587 if (IsDefaultArgument) {
7588 S.Diag(TemplateNameLoc,
7589 diag::err_dependent_non_type_arg_in_partial_spec);
7590 S.Diag(ParamUseRange.getBegin(),
7591 diag::note_dependent_non_type_default_arg_in_partial_spec)
7592 << ParamUseRange;
7593 } else {
7594 S.Diag(ParamUseRange.getBegin(),
7595 diag::err_dependent_non_type_arg_in_partial_spec)
7596 << ParamUseRange;
7597 }
7598 return true;
7599 }
7600
7601 ParamUseRange = findTemplateParameter(
7602 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7603 if (ParamUseRange.isValid()) {
7604 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
7605 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7606 << Param->getType();
7607 S.Diag(Param->getLocation(), diag::note_template_param_here)
7608 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7609 << ParamUseRange;
7610 return true;
7611 }
7612 }
7613
7614 return false;
7615}
7616
7617/// Check the non-type template arguments of a class template
7618/// partial specialization according to C++ [temp.class.spec]p9.
7619///
7620/// \param TemplateNameLoc the location of the template name.
7621/// \param PrimaryTemplate the template parameters of the primary class
7622/// template.
7623/// \param NumExplicit the number of explicitly-specified template arguments.
7624/// \param TemplateArgs the template arguments of the class template
7625/// partial specialization.
7626///
7627/// \returns \c true if there was an error, \c false otherwise.
7628bool Sema::CheckTemplatePartialSpecializationArgs(
7629 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7630 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7631 // We have to be conservative when checking a template in a dependent
7632 // context.
7633 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7634 return false;
7635
7636 TemplateParameterList *TemplateParams =
7637 PrimaryTemplate->getTemplateParameters();
7638 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7639 NonTypeTemplateParmDecl *Param
7640 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7641 if (!Param)
7642 continue;
7643
7644 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7645 Param, &TemplateArgs[I],
7646 1, I >= NumExplicit))
7647 return true;
7648 }
7649
7650 return false;
7651}
7652
7653DeclResult Sema::ActOnClassTemplateSpecialization(
7654 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7655 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7656 const ParsedAttributesView &Attr,
7657 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
7658 assert(TUK != TUK_Reference && "References are not specializations")((TUK != TUK_Reference && "References are not specializations"
) ? static_cast<void> (0) : __assert_fail ("TUK != TUK_Reference && \"References are not specializations\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7658, __PRETTY_FUNCTION__))
;
7659
7660 CXXScopeSpec &SS = TemplateId.SS;
7661
7662 // NOTE: KWLoc is the location of the tag keyword. This will instead
7663 // store the location of the outermost template keyword in the declaration.
7664 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7665 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7666 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7667 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7668 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7669
7670 // Find the class template we're specializing
7671 TemplateName Name = TemplateId.Template.get();
7672 ClassTemplateDecl *ClassTemplate
7673 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7674
7675 if (!ClassTemplate) {
7676 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7677 << (Name.getAsTemplateDecl() &&
7678 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7679 return true;
7680 }
7681
7682 bool isMemberSpecialization = false;
7683 bool isPartialSpecialization = false;
7684
7685 // Check the validity of the template headers that introduce this
7686 // template.
7687 // FIXME: We probably shouldn't complain about these headers for
7688 // friend declarations.
7689 bool Invalid = false;
7690 TemplateParameterList *TemplateParams =
7691 MatchTemplateParametersToScopeSpecifier(
7692 KWLoc, TemplateNameLoc, SS, &TemplateId,
7693 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7694 Invalid);
7695 if (Invalid)
7696 return true;
7697
7698 if (TemplateParams && TemplateParams->size() > 0) {
7699 isPartialSpecialization = true;
7700
7701 if (TUK == TUK_Friend) {
7702 Diag(KWLoc, diag::err_partial_specialization_friend)
7703 << SourceRange(LAngleLoc, RAngleLoc);
7704 return true;
7705 }
7706
7707 // C++ [temp.class.spec]p10:
7708 // The template parameter list of a specialization shall not
7709 // contain default template argument values.
7710 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7711 Decl *Param = TemplateParams->getParam(I);
7712 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7713 if (TTP->hasDefaultArgument()) {
7714 Diag(TTP->getDefaultArgumentLoc(),
7715 diag::err_default_arg_in_partial_spec);
7716 TTP->removeDefaultArgument();
7717 }
7718 } else if (NonTypeTemplateParmDecl *NTTP
7719 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7720 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7721 Diag(NTTP->getDefaultArgumentLoc(),
7722 diag::err_default_arg_in_partial_spec)
7723 << DefArg->getSourceRange();
7724 NTTP->removeDefaultArgument();
7725 }
7726 } else {
7727 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7728 if (TTP->hasDefaultArgument()) {
7729 Diag(TTP->getDefaultArgument().getLocation(),
7730 diag::err_default_arg_in_partial_spec)
7731 << TTP->getDefaultArgument().getSourceRange();
7732 TTP->removeDefaultArgument();
7733 }
7734 }
7735 }
7736 } else if (TemplateParams) {
7737 if (TUK == TUK_Friend)
7738 Diag(KWLoc, diag::err_template_spec_friend)
7739 << FixItHint::CreateRemoval(
7740 SourceRange(TemplateParams->getTemplateLoc(),
7741 TemplateParams->getRAngleLoc()))
7742 << SourceRange(LAngleLoc, RAngleLoc);
7743 } else {
7744 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl")((TUK == TUK_Friend && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7744, __PRETTY_FUNCTION__))
;
7745 }
7746
7747 // Check that the specialization uses the same tag kind as the
7748 // original template.
7749 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7750 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!")((Kind != TTK_Enum && "Invalid enum tag in class template spec!"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template spec!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 7750, __PRETTY_FUNCTION__))
;
7751 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7752 Kind, TUK == TUK_Definition, KWLoc,
7753 ClassTemplate->getIdentifier())) {
7754 Diag(KWLoc, diag::err_use_with_wrong_tag)
7755 << ClassTemplate
7756 << FixItHint::CreateReplacement(KWLoc,
7757 ClassTemplate->getTemplatedDecl()->getKindName());
7758 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7759 diag::note_previous_use);
7760 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7761 }
7762
7763 // Translate the parser's template argument list in our AST format.
7764 TemplateArgumentListInfo TemplateArgs =
7765 makeTemplateArgumentListInfo(*this, TemplateId);
7766
7767 // Check for unexpanded parameter packs in any of the template arguments.
7768 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7769 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7770 UPPC_PartialSpecialization))
7771 return true;
7772
7773 // Check that the template argument list is well-formed for this
7774 // template.
7775 SmallVector<TemplateArgument, 4> Converted;
7776 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7777 TemplateArgs, false, Converted))
7778 return true;
7779
7780 // Find the class template (partial) specialization declaration that
7781 // corresponds to these arguments.
7782 if (isPartialSpecialization) {
7783 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7784 TemplateArgs.size(), Converted))
7785 return true;
7786
7787 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7788 // also do it during instantiation.
7789 bool InstantiationDependent;
7790 if (!Name.isDependent() &&
7791 !TemplateSpecializationType::anyDependentTemplateArguments(
7792 TemplateArgs.arguments(), InstantiationDependent)) {
7793 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7794 << ClassTemplate->getDeclName();
7795 isPartialSpecialization = false;
7796 }
7797 }
7798
7799 void *InsertPos = nullptr;
7800 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7801
7802 if (isPartialSpecialization)
7803 // FIXME: Template parameter list matters, too
7804 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7805 else
7806 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7807
7808 ClassTemplateSpecializationDecl *Specialization = nullptr;
7809
7810 // Check whether we can declare a class template specialization in
7811 // the current scope.
7812 if (TUK != TUK_Friend &&
7813 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7814 TemplateNameLoc,
7815 isPartialSpecialization))
7816 return true;
7817
7818 // The canonical type
7819 QualType CanonType;
7820 if (isPartialSpecialization) {
7821 // Build the canonical type that describes the converted template
7822 // arguments of the class template partial specialization.
7823 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7824 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7825 Converted);
7826
7827 if (Context.hasSameType(CanonType,
7828 ClassTemplate->getInjectedClassNameSpecialization())) {
7829 // C++ [temp.class.spec]p9b3:
7830 //
7831 // -- The argument list of the specialization shall not be identical
7832 // to the implicit argument list of the primary template.
7833 //
7834 // This rule has since been removed, because it's redundant given DR1495,
7835 // but we keep it because it produces better diagnostics and recovery.
7836 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7837 << /*class template*/0 << (TUK == TUK_Definition)
7838 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7839 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7840 ClassTemplate->getIdentifier(),
7841 TemplateNameLoc,
7842 Attr,
7843 TemplateParams,
7844 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7845 /*FriendLoc*/SourceLocation(),
7846 TemplateParameterLists.size() - 1,
7847 TemplateParameterLists.data());
7848 }
7849
7850 // Create a new class template partial specialization declaration node.
7851 ClassTemplatePartialSpecializationDecl *PrevPartial
7852 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7853 ClassTemplatePartialSpecializationDecl *Partial
7854 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7855 ClassTemplate->getDeclContext(),
7856 KWLoc, TemplateNameLoc,
7857 TemplateParams,
7858 ClassTemplate,
7859 Converted,
7860 TemplateArgs,
7861 CanonType,
7862 PrevPartial);
7863 SetNestedNameSpecifier(*this, Partial, SS);
7864 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7865 Partial->setTemplateParameterListsInfo(
7866 Context, TemplateParameterLists.drop_back(1));
7867 }
7868
7869 if (!PrevPartial)
7870 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7871 Specialization = Partial;
7872
7873 // If we are providing an explicit specialization of a member class
7874 // template specialization, make a note of that.
7875 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7876 PrevPartial->setMemberSpecialization();
7877
7878 CheckTemplatePartialSpecialization(Partial);
7879 } else {
7880 // Create a new class template specialization declaration node for
7881 // this explicit specialization or friend declaration.
7882 Specialization
7883 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7884 ClassTemplate->getDeclContext(),
7885 KWLoc, TemplateNameLoc,
7886 ClassTemplate,
7887 Converted,
7888 PrevDecl);
7889 SetNestedNameSpecifier(*this, Specialization, SS);
7890 if (TemplateParameterLists.size() > 0) {
7891 Specialization->setTemplateParameterListsInfo(Context,
7892 TemplateParameterLists);
7893 }
7894
7895 if (!PrevDecl)
7896 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7897
7898 if (CurContext->isDependentContext()) {
7899 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7900 CanonType = Context.getTemplateSpecializationType(
7901 CanonTemplate, Converted);
7902 } else {
7903 CanonType = Context.getTypeDeclType(Specialization);
7904 }
7905 }
7906
7907 // C++ [temp.expl.spec]p6:
7908 // If a template, a member template or the member of a class template is
7909 // explicitly specialized then that specialization shall be declared
7910 // before the first use of that specialization that would cause an implicit
7911 // instantiation to take place, in every translation unit in which such a
7912 // use occurs; no diagnostic is required.
7913 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7914 bool Okay = false;
7915 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7916 // Is there any previous explicit specialization declaration?
7917 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7918 Okay = true;
7919 break;
7920 }
7921 }
7922
7923 if (!Okay) {
7924 SourceRange Range(TemplateNameLoc, RAngleLoc);
7925 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7926 << Context.getTypeDeclType(Specialization) << Range;
7927
7928 Diag(PrevDecl->getPointOfInstantiation(),
7929 diag::note_instantiation_required_here)
7930 << (PrevDecl->getTemplateSpecializationKind()
7931 != TSK_ImplicitInstantiation);
7932 return true;
7933 }
7934 }
7935
7936 // If this is not a friend, note that this is an explicit specialization.
7937 if (TUK != TUK_Friend)
7938 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7939
7940 // Check that this isn't a redefinition of this specialization.
7941 if (TUK == TUK_Definition) {
7942 RecordDecl *Def = Specialization->getDefinition();
7943 NamedDecl *Hidden = nullptr;
7944 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7945 SkipBody->ShouldSkip = true;
7946 SkipBody->Previous = Def;
7947 makeMergedDefinitionVisible(Hidden);
7948 } else if (Def) {
7949 SourceRange Range(TemplateNameLoc, RAngleLoc);
7950 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7951 Diag(Def->getLocation(), diag::note_previous_definition);
7952 Specialization->setInvalidDecl();
7953 return true;
7954 }
7955 }
7956
7957 ProcessDeclAttributeList(S, Specialization, Attr);
7958
7959 // Add alignment attributes if necessary; these attributes are checked when
7960 // the ASTContext lays out the structure.
7961 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
7962 AddAlignmentAttributesForRecord(Specialization);
7963 AddMsStructLayoutForRecord(Specialization);
7964 }
7965
7966 if (ModulePrivateLoc.isValid())
7967 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7968 << (isPartialSpecialization? 1 : 0)
7969 << FixItHint::CreateRemoval(ModulePrivateLoc);
7970
7971 // Build the fully-sugared type for this class template
7972 // specialization as the user wrote in the specialization
7973 // itself. This means that we'll pretty-print the type retrieved
7974 // from the specialization's declaration the way that the user
7975 // actually wrote the specialization, rather than formatting the
7976 // name based on the "canonical" representation used to store the
7977 // template arguments in the specialization.
7978 TypeSourceInfo *WrittenTy
7979 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7980 TemplateArgs, CanonType);
7981 if (TUK != TUK_Friend) {
7982 Specialization->setTypeAsWritten(WrittenTy);
7983 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7984 }
7985
7986 // C++ [temp.expl.spec]p9:
7987 // A template explicit specialization is in the scope of the
7988 // namespace in which the template was defined.
7989 //
7990 // We actually implement this paragraph where we set the semantic
7991 // context (in the creation of the ClassTemplateSpecializationDecl),
7992 // but we also maintain the lexical context where the actual
7993 // definition occurs.
7994 Specialization->setLexicalDeclContext(CurContext);
7995
7996 // We may be starting the definition of this specialization.
7997 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
7998 Specialization->startDefinition();
7999
8000 if (TUK == TUK_Friend) {
8001 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8002 TemplateNameLoc,
8003 WrittenTy,
8004 /*FIXME:*/KWLoc);
8005 Friend->setAccess(AS_public);
8006 CurContext->addDecl(Friend);
8007 } else {
8008 // Add the specialization into its lexical context, so that it can
8009 // be seen when iterating through the list of declarations in that
8010 // context. However, specializations are not found by name lookup.
8011 CurContext->addDecl(Specialization);
8012 }
8013
8014 if (SkipBody && SkipBody->ShouldSkip)
8015 return SkipBody->Previous;
8016
8017 return Specialization;
8018}
8019
8020Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8021 MultiTemplateParamsArg TemplateParameterLists,
8022 Declarator &D) {
8023 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8024 ActOnDocumentableDecl(NewDecl);
8025 return NewDecl;
8026}
8027
8028Decl *Sema::ActOnConceptDefinition(Scope *S,
8029 MultiTemplateParamsArg TemplateParameterLists,
8030 IdentifierInfo *Name, SourceLocation NameLoc,
8031 Expr *ConstraintExpr) {
8032 DeclContext *DC = CurContext;
8033
8034 if (!DC->getRedeclContext()->isFileContext()) {
8035 Diag(NameLoc,
8036 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8037 return nullptr;
8038 }
8039
8040 if (TemplateParameterLists.size() > 1) {
8041 Diag(NameLoc, diag::err_concept_extra_headers);
8042 return nullptr;
8043 }
8044
8045 if (TemplateParameterLists.front()->size() == 0) {
8046 Diag(NameLoc, diag::err_concept_no_parameters);
8047 return nullptr;
8048 }
8049
8050 ConceptDecl *NewDecl = ConceptDecl::Create(Context, DC, NameLoc, Name,
8051 TemplateParameterLists.front(),
8052 ConstraintExpr);
8053
8054 if (!ConstraintExpr->isTypeDependent() &&
8055 ConstraintExpr->getType() != Context.BoolTy) {
8056 // C++2a [temp.constr.atomic]p3:
8057 // E shall be a constant expression of type bool.
8058 // TODO: Do this check for individual atomic constraints
8059 // and not the constraint expression. Probably should do it in
8060 // ParseConstraintExpression.
8061 Diag(ConstraintExpr->getSourceRange().getBegin(),
8062 diag::err_concept_initialized_with_non_bool_type)
8063 << ConstraintExpr->getType();
8064 NewDecl->setInvalidDecl();
8065 }
8066
8067 if (NewDecl->getAssociatedConstraints()) {
8068 // C++2a [temp.concept]p4:
8069 // A concept shall not have associated constraints.
8070 // TODO: Make a test once we have actual associated constraints.
8071 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8072 NewDecl->setInvalidDecl();
8073 }
8074
8075 // Check for conflicting previous declaration.
8076 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8077 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8078 ForVisibleRedeclaration);
8079 LookupName(Previous, S);
8080
8081 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8082 /*AllowInlineNamespace*/false);
8083 if (!Previous.empty()) {
8084 auto *Old = Previous.getRepresentativeDecl();
8085 Diag(NameLoc, isa<ConceptDecl>(Old) ? diag::err_redefinition :
8086 diag::err_redefinition_different_kind) << NewDecl->getDeclName();
8087 Diag(Old->getLocation(), diag::note_previous_definition);
8088 }
8089
8090 ActOnDocumentableDecl(NewDecl);
8091 PushOnScopeChains(NewDecl, S);
8092 return NewDecl;
8093}
8094
8095/// \brief Strips various properties off an implicit instantiation
8096/// that has just been explicitly specialized.
8097static void StripImplicitInstantiation(NamedDecl *D) {
8098 D->dropAttr<DLLImportAttr>();
8099 D->dropAttr<DLLExportAttr>();
8100
8101 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8102 FD->setInlineSpecified(false);
8103}
8104
8105/// Compute the diagnostic location for an explicit instantiation
8106// declaration or definition.
8107static SourceLocation DiagLocForExplicitInstantiation(
8108 NamedDecl* D, SourceLocation PointOfInstantiation) {
8109 // Explicit instantiations following a specialization have no effect and
8110 // hence no PointOfInstantiation. In that case, walk decl backwards
8111 // until a valid name loc is found.
8112 SourceLocation PrevDiagLoc = PointOfInstantiation;
8113 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8114 Prev = Prev->getPreviousDecl()) {
8115 PrevDiagLoc = Prev->getLocation();
8116 }
8117 assert(PrevDiagLoc.isValid() &&((PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8118, __PRETTY_FUNCTION__))
8118 "Explicit instantiation without point of instantiation?")((PrevDiagLoc.isValid() && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("PrevDiagLoc.isValid() && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8118, __PRETTY_FUNCTION__))
;
8119 return PrevDiagLoc;
8120}
8121
8122/// Diagnose cases where we have an explicit template specialization
8123/// before/after an explicit template instantiation, producing diagnostics
8124/// for those cases where they are required and determining whether the
8125/// new specialization/instantiation will have any effect.
8126///
8127/// \param NewLoc the location of the new explicit specialization or
8128/// instantiation.
8129///
8130/// \param NewTSK the kind of the new explicit specialization or instantiation.
8131///
8132/// \param PrevDecl the previous declaration of the entity.
8133///
8134/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
8135///
8136/// \param PrevPointOfInstantiation if valid, indicates where the previus
8137/// declaration was instantiated (either implicitly or explicitly).
8138///
8139/// \param HasNoEffect will be set to true to indicate that the new
8140/// specialization or instantiation has no effect and should be ignored.
8141///
8142/// \returns true if there was an error that should prevent the introduction of
8143/// the new declaration into the AST, false otherwise.
8144bool
8145Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8146 TemplateSpecializationKind NewTSK,
8147 NamedDecl *PrevDecl,
8148 TemplateSpecializationKind PrevTSK,
8149 SourceLocation PrevPointOfInstantiation,
8150 bool &HasNoEffect) {
8151 HasNoEffect = false;
8152
8153 switch (NewTSK) {
8154 case TSK_Undeclared:
8155 case TSK_ImplicitInstantiation:
8156 assert((((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8158, __PRETTY_FUNCTION__))
8157 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&(((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8158, __PRETTY_FUNCTION__))
8158 "previous declaration must be implicit!")(((PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation
) && "previous declaration must be implicit!") ? static_cast
<void> (0) : __assert_fail ("(PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && \"previous declaration must be implicit!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8158, __PRETTY_FUNCTION__))
;
8159 return false;
8160
8161 case TSK_ExplicitSpecialization:
8162 switch (PrevTSK) {
8163 case TSK_Undeclared:
8164 case TSK_ExplicitSpecialization:
8165 // Okay, we're just specializing something that is either already
8166 // explicitly specialized or has merely been mentioned without any
8167 // instantiation.
8168 return false;
8169
8170 case TSK_ImplicitInstantiation:
8171 if (PrevPointOfInstantiation.isInvalid()) {
8172 // The declaration itself has not actually been instantiated, so it is
8173 // still okay to specialize it.
8174 StripImplicitInstantiation(PrevDecl);
8175 return false;
8176 }
8177 // Fall through
8178 LLVM_FALLTHROUGH[[gnu::fallthrough]];
8179
8180 case TSK_ExplicitInstantiationDeclaration:
8181 case TSK_ExplicitInstantiationDefinition:
8182 assert((PrevTSK == TSK_ImplicitInstantiation ||(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8184, __PRETTY_FUNCTION__))
8183 PrevPointOfInstantiation.isValid()) &&(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8184, __PRETTY_FUNCTION__))
8184 "Explicit instantiation without point of instantiation?")(((PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation
.isValid()) && "Explicit instantiation without point of instantiation?"
) ? static_cast<void> (0) : __assert_fail ("(PrevTSK == TSK_ImplicitInstantiation || PrevPointOfInstantiation.isValid()) && \"Explicit instantiation without point of instantiation?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8184, __PRETTY_FUNCTION__))
;
8185
8186 // C++ [temp.expl.spec]p6:
8187 // If a template, a member template or the member of a class template
8188 // is explicitly specialized then that specialization shall be declared
8189 // before the first use of that specialization that would cause an
8190 // implicit instantiation to take place, in every translation unit in
8191 // which such a use occurs; no diagnostic is required.
8192 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8193 // Is there any previous explicit specialization declaration?
8194 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8195 return false;
8196 }
8197
8198 Diag(NewLoc, diag::err_specialization_after_instantiation)
8199 << PrevDecl;
8200 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8201 << (PrevTSK != TSK_ImplicitInstantiation);
8202
8203 return true;
8204 }
8205 llvm_unreachable("The switch over PrevTSK must be exhaustive.")::llvm::llvm_unreachable_internal("The switch over PrevTSK must be exhaustive."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8205)
;
8206
8207 case TSK_ExplicitInstantiationDeclaration:
8208 switch (PrevTSK) {
8209 case TSK_ExplicitInstantiationDeclaration:
8210 // This explicit instantiation declaration is redundant (that's okay).
8211 HasNoEffect = true;
8212 return false;
8213
8214 case TSK_Undeclared:
8215 case TSK_ImplicitInstantiation:
8216 // We're explicitly instantiating something that may have already been
8217 // implicitly instantiated; that's fine.
8218 return false;
8219
8220 case TSK_ExplicitSpecialization:
8221 // C++0x [temp.explicit]p4:
8222 // For a given set of template parameters, if an explicit instantiation
8223 // of a template appears after a declaration of an explicit
8224 // specialization for that template, the explicit instantiation has no
8225 // effect.
8226 HasNoEffect = true;
8227 return false;
8228
8229 case TSK_ExplicitInstantiationDefinition:
8230 // C++0x [temp.explicit]p10:
8231 // If an entity is the subject of both an explicit instantiation
8232 // declaration and an explicit instantiation definition in the same
8233 // translation unit, the definition shall follow the declaration.
8234 Diag(NewLoc,
8235 diag::err_explicit_instantiation_declaration_after_definition);
8236
8237 // Explicit instantiations following a specialization have no effect and
8238 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8239 // until a valid name loc is found.
8240 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8241 diag::note_explicit_instantiation_definition_here);
8242 HasNoEffect = true;
8243 return false;
8244 }
8245 llvm_unreachable("Unexpected TemplateSpecializationKind!")::llvm::llvm_unreachable_internal("Unexpected TemplateSpecializationKind!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8245)
;
8246
8247 case TSK_ExplicitInstantiationDefinition:
8248 switch (PrevTSK) {
8249 case TSK_Undeclared:
8250 case TSK_ImplicitInstantiation:
8251 // We're explicitly instantiating something that may have already been
8252 // implicitly instantiated; that's fine.
8253 return false;
8254
8255 case TSK_ExplicitSpecialization:
8256 // C++ DR 259, C++0x [temp.explicit]p4:
8257 // For a given set of template parameters, if an explicit
8258 // instantiation of a template appears after a declaration of
8259 // an explicit specialization for that template, the explicit
8260 // instantiation has no effect.
8261 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8262 << PrevDecl;
8263 Diag(PrevDecl->getLocation(),
8264 diag::note_previous_template_specialization);
8265 HasNoEffect = true;
8266 return false;
8267
8268 case TSK_ExplicitInstantiationDeclaration:
8269 // We're explicitly instantiating a definition for something for which we
8270 // were previously asked to suppress instantiations. That's fine.
8271
8272 // C++0x [temp.explicit]p4:
8273 // For a given set of template parameters, if an explicit instantiation
8274 // of a template appears after a declaration of an explicit
8275 // specialization for that template, the explicit instantiation has no
8276 // effect.
8277 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8278 // Is there any previous explicit specialization declaration?
8279 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8280 HasNoEffect = true;
8281 break;
8282 }
8283 }
8284
8285 return false;
8286
8287 case TSK_ExplicitInstantiationDefinition:
8288 // C++0x [temp.spec]p5:
8289 // For a given template and a given set of template-arguments,
8290 // - an explicit instantiation definition shall appear at most once
8291 // in a program,
8292
8293 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8294 Diag(NewLoc, (getLangOpts().MSVCCompat)
8295 ? diag::ext_explicit_instantiation_duplicate
8296 : diag::err_explicit_instantiation_duplicate)
8297 << PrevDecl;
8298 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8299 diag::note_previous_explicit_instantiation);
8300 HasNoEffect = true;
8301 return false;
8302 }
8303 }
8304
8305 llvm_unreachable("Missing specialization/instantiation case?")::llvm::llvm_unreachable_internal("Missing specialization/instantiation case?"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8305)
;
8306}
8307
8308/// Perform semantic analysis for the given dependent function
8309/// template specialization.
8310///
8311/// The only possible way to get a dependent function template specialization
8312/// is with a friend declaration, like so:
8313///
8314/// \code
8315/// template \<class T> void foo(T);
8316/// template \<class T> class A {
8317/// friend void foo<>(T);
8318/// };
8319/// \endcode
8320///
8321/// There really isn't any useful analysis we can do here, so we
8322/// just store the information.
8323bool
8324Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8325 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8326 LookupResult &Previous) {
8327 // Remove anything from Previous that isn't a function template in
8328 // the correct context.
8329 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8330 LookupResult::Filter F = Previous.makeFilter();
8331 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8332 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8333 while (F.hasNext()) {
8334 NamedDecl *D = F.next()->getUnderlyingDecl();
8335 if (!isa<FunctionTemplateDecl>(D)) {
8336 F.erase();
8337 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8338 continue;
8339 }
8340
8341 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8342 D->getDeclContext()->getRedeclContext())) {
8343 F.erase();
8344 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8345 continue;
8346 }
8347 }
8348 F.done();
8349
8350 if (Previous.empty()) {
8351 Diag(FD->getLocation(),
8352 diag::err_dependent_function_template_spec_no_match);
8353 for (auto &P : DiscardedCandidates)
8354 Diag(P.second->getLocation(),
8355 diag::note_dependent_function_template_spec_discard_reason)
8356 << P.first;
8357 return true;
8358 }
8359
8360 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8361 ExplicitTemplateArgs);
8362 return false;
8363}
8364
8365/// Perform semantic analysis for the given function template
8366/// specialization.
8367///
8368/// This routine performs all of the semantic analysis required for an
8369/// explicit function template specialization. On successful completion,
8370/// the function declaration \p FD will become a function template
8371/// specialization.
8372///
8373/// \param FD the function declaration, which will be updated to become a
8374/// function template specialization.
8375///
8376/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8377/// if any. Note that this may be valid info even when 0 arguments are
8378/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8379/// as it anyway contains info on the angle brackets locations.
8380///
8381/// \param Previous the set of declarations that may be specialized by
8382/// this function specialization.
8383///
8384/// \param QualifiedFriend whether this is a lookup for a qualified friend
8385/// declaration with no explicit template argument list that might be
8386/// befriending a function template specialization.
8387bool Sema::CheckFunctionTemplateSpecialization(
8388 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8389 LookupResult &Previous, bool QualifiedFriend) {
8390 // The set of function template specializations that could match this
8391 // explicit function template specialization.
8392 UnresolvedSet<8> Candidates;
8393 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8394 /*ForTakingAddress=*/false);
8395
8396 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8397 ConvertedTemplateArgs;
8398
8399 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8400 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8401 I != E; ++I) {
8402 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8403 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8404 // Only consider templates found within the same semantic lookup scope as
8405 // FD.
8406 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8407 Ovl->getDeclContext()->getRedeclContext()))
8408 continue;
8409
8410 // When matching a constexpr member function template specialization
8411 // against the primary template, we don't yet know whether the
8412 // specialization has an implicit 'const' (because we don't know whether
8413 // it will be a static member function until we know which template it
8414 // specializes), so adjust it now assuming it specializes this template.
8415 QualType FT = FD->getType();
8416 if (FD->isConstexpr()) {
8417 CXXMethodDecl *OldMD =
8418 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8419 if (OldMD && OldMD->isConst()) {
8420 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8421 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8422 EPI.TypeQuals.addConst();
8423 FT = Context.getFunctionType(FPT->getReturnType(),
8424 FPT->getParamTypes(), EPI);
8425 }
8426 }
8427
8428 TemplateArgumentListInfo Args;
8429 if (ExplicitTemplateArgs)
8430 Args = *ExplicitTemplateArgs;
8431
8432 // C++ [temp.expl.spec]p11:
8433 // A trailing template-argument can be left unspecified in the
8434 // template-id naming an explicit function template specialization
8435 // provided it can be deduced from the function argument type.
8436 // Perform template argument deduction to determine whether we may be
8437 // specializing this template.
8438 // FIXME: It is somewhat wasteful to build
8439 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8440 FunctionDecl *Specialization = nullptr;
8441 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8442 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8443 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8444 Info)) {
8445 // Template argument deduction failed; record why it failed, so
8446 // that we can provide nifty diagnostics.
8447 FailedCandidates.addCandidate().set(
8448 I.getPair(), FunTmpl->getTemplatedDecl(),
8449 MakeDeductionFailureInfo(Context, TDK, Info));
8450 (void)TDK;
8451 continue;
8452 }
8453
8454 // Target attributes are part of the cuda function signature, so
8455 // the deduced template's cuda target must match that of the
8456 // specialization. Given that C++ template deduction does not
8457 // take target attributes into account, we reject candidates
8458 // here that have a different target.
8459 if (LangOpts.CUDA &&
8460 IdentifyCUDATarget(Specialization,
8461 /* IgnoreImplicitHDAttr = */ true) !=
8462 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
8463 FailedCandidates.addCandidate().set(
8464 I.getPair(), FunTmpl->getTemplatedDecl(),
8465 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8466 continue;
8467 }
8468
8469 // Record this candidate.
8470 if (ExplicitTemplateArgs)
8471 ConvertedTemplateArgs[Specialization] = std::move(Args);
8472 Candidates.addDecl(Specialization, I.getAccess());
8473 }
8474 }
8475
8476 // For a qualified friend declaration (with no explicit marker to indicate
8477 // that a template specialization was intended), note all (template and
8478 // non-template) candidates.
8479 if (QualifiedFriend && Candidates.empty()) {
8480 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8481 << FD->getDeclName() << FDLookupContext;
8482 // FIXME: We should form a single candidate list and diagnose all
8483 // candidates at once, to get proper sorting and limiting.
8484 for (auto *OldND : Previous) {
8485 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8486 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false);
8487 }
8488 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8489 return true;
8490 }
8491
8492 // Find the most specialized function template.
8493 UnresolvedSetIterator Result = getMostSpecialized(
8494 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
8495 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8496 PDiag(diag::err_function_template_spec_ambiguous)
8497 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8498 PDiag(diag::note_function_template_spec_matched));
8499
8500 if (Result == Candidates.end())
8501 return true;
8502
8503 // Ignore access information; it doesn't figure into redeclaration checking.
8504 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8505
8506 FunctionTemplateSpecializationInfo *SpecInfo
8507 = Specialization->getTemplateSpecializationInfo();
8508 assert(SpecInfo && "Function template specialization info missing?")((SpecInfo && "Function template specialization info missing?"
) ? static_cast<void> (0) : __assert_fail ("SpecInfo && \"Function template specialization info missing?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8508, __PRETTY_FUNCTION__))
;
8509
8510 // Note: do not overwrite location info if previous template
8511 // specialization kind was explicit.
8512 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8513 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8514 Specialization->setLocation(FD->getLocation());
8515 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8516 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8517 // function can differ from the template declaration with respect to
8518 // the constexpr specifier.
8519 // FIXME: We need an update record for this AST mutation.
8520 // FIXME: What if there are multiple such prior declarations (for instance,
8521 // from different modules)?
8522 Specialization->setConstexprKind(FD->getConstexprKind());
8523 }
8524
8525 // FIXME: Check if the prior specialization has a point of instantiation.
8526 // If so, we have run afoul of .
8527
8528 // If this is a friend declaration, then we're not really declaring
8529 // an explicit specialization.
8530 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8531
8532 // Check the scope of this explicit specialization.
8533 if (!isFriend &&
8534 CheckTemplateSpecializationScope(*this,
8535 Specialization->getPrimaryTemplate(),
8536 Specialization, FD->getLocation(),
8537 false))
8538 return true;
8539
8540 // C++ [temp.expl.spec]p6:
8541 // If a template, a member template or the member of a class template is
8542 // explicitly specialized then that specialization shall be declared
8543 // before the first use of that specialization that would cause an implicit
8544 // instantiation to take place, in every translation unit in which such a
8545 // use occurs; no diagnostic is required.
8546 bool HasNoEffect = false;
8547 if (!isFriend &&
8548 CheckSpecializationInstantiationRedecl(FD->getLocation(),
8549 TSK_ExplicitSpecialization,
8550 Specialization,
8551 SpecInfo->getTemplateSpecializationKind(),
8552 SpecInfo->getPointOfInstantiation(),
8553 HasNoEffect))
8554 return true;
8555
8556 // Mark the prior declaration as an explicit specialization, so that later
8557 // clients know that this is an explicit specialization.
8558 if (!isFriend) {
8559 // Since explicit specializations do not inherit '=delete' from their
8560 // primary function template - check if the 'specialization' that was
8561 // implicitly generated (during template argument deduction for partial
8562 // ordering) from the most specialized of all the function templates that
8563 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8564 // first check that it was implicitly generated during template argument
8565 // deduction by making sure it wasn't referenced, and then reset the deleted
8566 // flag to not-deleted, so that we can inherit that information from 'FD'.
8567 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8568 !Specialization->getCanonicalDecl()->isReferenced()) {
8569 // FIXME: This assert will not hold in the presence of modules.
8570 assert(((Specialization->getCanonicalDecl() == Specialization &&
"This must be the only existing declaration of this specialization"
) ? static_cast<void> (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8572, __PRETTY_FUNCTION__))
8571 Specialization->getCanonicalDecl() == Specialization &&((Specialization->getCanonicalDecl() == Specialization &&
"This must be the only existing declaration of this specialization"
) ? static_cast<void> (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8572, __PRETTY_FUNCTION__))
8572 "This must be the only existing declaration of this specialization")((Specialization->getCanonicalDecl() == Specialization &&
"This must be the only existing declaration of this specialization"
) ? static_cast<void> (0) : __assert_fail ("Specialization->getCanonicalDecl() == Specialization && \"This must be the only existing declaration of this specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8572, __PRETTY_FUNCTION__))
;
8573 // FIXME: We need an update record for this AST mutation.
8574 Specialization->setDeletedAsWritten(false);
8575 }
8576 // FIXME: We need an update record for this AST mutation.
8577 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8578 MarkUnusedFileScopedDecl(Specialization);
8579 }
8580
8581 // Turn the given function declaration into a function template
8582 // specialization, with the template arguments from the previous
8583 // specialization.
8584 // Take copies of (semantic and syntactic) template argument lists.
8585 const TemplateArgumentList* TemplArgs = new (Context)
8586 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8587 FD->setFunctionTemplateSpecialization(
8588 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8589 SpecInfo->getTemplateSpecializationKind(),
8590 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8591
8592 // A function template specialization inherits the target attributes
8593 // of its template. (We require the attributes explicitly in the
8594 // code to match, but a template may have implicit attributes by
8595 // virtue e.g. of being constexpr, and it passes these implicit
8596 // attributes on to its specializations.)
8597 if (LangOpts.CUDA)
8598 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8599
8600 // The "previous declaration" for this function template specialization is
8601 // the prior function template specialization.
8602 Previous.clear();
8603 Previous.addDecl(Specialization);
8604 return false;
8605}
8606
8607/// Perform semantic analysis for the given non-template member
8608/// specialization.
8609///
8610/// This routine performs all of the semantic analysis required for an
8611/// explicit member function specialization. On successful completion,
8612/// the function declaration \p FD will become a member function
8613/// specialization.
8614///
8615/// \param Member the member declaration, which will be updated to become a
8616/// specialization.
8617///
8618/// \param Previous the set of declarations, one of which may be specialized
8619/// by this function specialization; the set will be modified to contain the
8620/// redeclared member.
8621bool
8622Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8623 assert(!isa<TemplateDecl>(Member) && "Only for non-template members")((!isa<TemplateDecl>(Member) && "Only for non-template members"
) ? static_cast<void> (0) : __assert_fail ("!isa<TemplateDecl>(Member) && \"Only for non-template members\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8623, __PRETTY_FUNCTION__))
;
8624
8625 // Try to find the member we are instantiating.
8626 NamedDecl *FoundInstantiation = nullptr;
8627 NamedDecl *Instantiation = nullptr;
8628 NamedDecl *InstantiatedFrom = nullptr;
8629 MemberSpecializationInfo *MSInfo = nullptr;
8630
8631 if (Previous.empty()) {
8632 // Nowhere to look anyway.
8633 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8634 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8635 I != E; ++I) {
8636 NamedDecl *D = (*I)->getUnderlyingDecl();
8637 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8638 QualType Adjusted = Function->getType();
8639 if (!hasExplicitCallingConv(Adjusted))
8640 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8641 // This doesn't handle deduced return types, but both function
8642 // declarations should be undeduced at this point.
8643 if (Context.hasSameType(Adjusted, Method->getType())) {
8644 FoundInstantiation = *I;
8645 Instantiation = Method;
8646 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8647 MSInfo = Method->getMemberSpecializationInfo();
8648 break;
8649 }
8650 }
8651 }
8652 } else if (isa<VarDecl>(Member)) {
8653 VarDecl *PrevVar;
8654 if (Previous.isSingleResult() &&
8655 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8656 if (PrevVar->isStaticDataMember()) {
8657 FoundInstantiation = Previous.getRepresentativeDecl();
8658 Instantiation = PrevVar;
8659 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8660 MSInfo = PrevVar->getMemberSpecializationInfo();
8661 }
8662 } else if (isa<RecordDecl>(Member)) {
8663 CXXRecordDecl *PrevRecord;
8664 if (Previous.isSingleResult() &&
8665 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8666 FoundInstantiation = Previous.getRepresentativeDecl();
8667 Instantiation = PrevRecord;
8668 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8669 MSInfo = PrevRecord->getMemberSpecializationInfo();
8670 }
8671 } else if (isa<EnumDecl>(Member)) {
8672 EnumDecl *PrevEnum;
8673 if (Previous.isSingleResult() &&
8674 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8675 FoundInstantiation = Previous.getRepresentativeDecl();
8676 Instantiation = PrevEnum;
8677 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8678 MSInfo = PrevEnum->getMemberSpecializationInfo();
8679 }
8680 }
8681
8682 if (!Instantiation) {
8683 // There is no previous declaration that matches. Since member
8684 // specializations are always out-of-line, the caller will complain about
8685 // this mismatch later.
8686 return false;
8687 }
8688
8689 // A member specialization in a friend declaration isn't really declaring
8690 // an explicit specialization, just identifying a specific (possibly implicit)
8691 // specialization. Don't change the template specialization kind.
8692 //
8693 // FIXME: Is this really valid? Other compilers reject.
8694 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8695 // Preserve instantiation information.
8696 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8697 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8698 cast<CXXMethodDecl>(InstantiatedFrom),
8699 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8700 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8701 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8702 cast<CXXRecordDecl>(InstantiatedFrom),
8703 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8704 }
8705
8706 Previous.clear();
8707 Previous.addDecl(FoundInstantiation);
8708 return false;
8709 }
8710
8711 // Make sure that this is a specialization of a member.
8712 if (!InstantiatedFrom) {
8713 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8714 << Member;
8715 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8716 return true;
8717 }
8718
8719 // C++ [temp.expl.spec]p6:
8720 // If a template, a member template or the member of a class template is
8721 // explicitly specialized then that specialization shall be declared
8722 // before the first use of that specialization that would cause an implicit
8723 // instantiation to take place, in every translation unit in which such a
8724 // use occurs; no diagnostic is required.
8725 assert(MSInfo && "Member specialization info missing?")((MSInfo && "Member specialization info missing?") ? static_cast
<void> (0) : __assert_fail ("MSInfo && \"Member specialization info missing?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8725, __PRETTY_FUNCTION__))
;
8726
8727 bool HasNoEffect = false;
8728 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8729 TSK_ExplicitSpecialization,
8730 Instantiation,
8731 MSInfo->getTemplateSpecializationKind(),
8732 MSInfo->getPointOfInstantiation(),
8733 HasNoEffect))
8734 return true;
8735
8736 // Check the scope of this explicit specialization.
8737 if (CheckTemplateSpecializationScope(*this,
8738 InstantiatedFrom,
8739 Instantiation, Member->getLocation(),
8740 false))
8741 return true;
8742
8743 // Note that this member specialization is an "instantiation of" the
8744 // corresponding member of the original template.
8745 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8746 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8747 if (InstantiationFunction->getTemplateSpecializationKind() ==
8748 TSK_ImplicitInstantiation) {
8749 // Explicit specializations of member functions of class templates do not
8750 // inherit '=delete' from the member function they are specializing.
8751 if (InstantiationFunction->isDeleted()) {
8752 // FIXME: This assert will not hold in the presence of modules.
8753 assert(InstantiationFunction->getCanonicalDecl() ==((InstantiationFunction->getCanonicalDecl() == InstantiationFunction
) ? static_cast<void> (0) : __assert_fail ("InstantiationFunction->getCanonicalDecl() == InstantiationFunction"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8754, __PRETTY_FUNCTION__))
8754 InstantiationFunction)((InstantiationFunction->getCanonicalDecl() == InstantiationFunction
) ? static_cast<void> (0) : __assert_fail ("InstantiationFunction->getCanonicalDecl() == InstantiationFunction"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8754, __PRETTY_FUNCTION__))
;
8755 // FIXME: We need an update record for this AST mutation.
8756 InstantiationFunction->setDeletedAsWritten(false);
8757 }
8758 }
8759
8760 MemberFunction->setInstantiationOfMemberFunction(
8761 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8762 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8763 MemberVar->setInstantiationOfStaticDataMember(
8764 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8765 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8766 MemberClass->setInstantiationOfMemberClass(
8767 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8768 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8769 MemberEnum->setInstantiationOfMemberEnum(
8770 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8771 } else {
8772 llvm_unreachable("unknown member specialization kind")::llvm::llvm_unreachable_internal("unknown member specialization kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8772)
;
8773 }
8774
8775 // Save the caller the trouble of having to figure out which declaration
8776 // this specialization matches.
8777 Previous.clear();
8778 Previous.addDecl(FoundInstantiation);
8779 return false;
8780}
8781
8782/// Complete the explicit specialization of a member of a class template by
8783/// updating the instantiated member to be marked as an explicit specialization.
8784///
8785/// \param OrigD The member declaration instantiated from the template.
8786/// \param Loc The location of the explicit specialization of the member.
8787template<typename DeclT>
8788static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8789 SourceLocation Loc) {
8790 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8791 return;
8792
8793 // FIXME: Inform AST mutation listeners of this AST mutation.
8794 // FIXME: If there are multiple in-class declarations of the member (from
8795 // multiple modules, or a declaration and later definition of a member type),
8796 // should we update all of them?
8797 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8798 OrigD->setLocation(Loc);
8799}
8800
8801void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8802 LookupResult &Previous) {
8803 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8804 if (Instantiation == Member)
8805 return;
8806
8807 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8808 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8809 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8810 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8811 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8812 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8813 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8814 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8815 else
8816 llvm_unreachable("unknown member specialization kind")::llvm::llvm_unreachable_internal("unknown member specialization kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8816)
;
8817}
8818
8819/// Check the scope of an explicit instantiation.
8820///
8821/// \returns true if a serious error occurs, false otherwise.
8822static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8823 SourceLocation InstLoc,
8824 bool WasQualifiedName) {
8825 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8826 DeclContext *CurContext = S.CurContext->getRedeclContext();
8827
8828 if (CurContext->isRecord()) {
8829 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8830 << D;
8831 return true;
8832 }
8833
8834 // C++11 [temp.explicit]p3:
8835 // An explicit instantiation shall appear in an enclosing namespace of its
8836 // template. If the name declared in the explicit instantiation is an
8837 // unqualified name, the explicit instantiation shall appear in the
8838 // namespace where its template is declared or, if that namespace is inline
8839 // (7.3.1), any namespace from its enclosing namespace set.
8840 //
8841 // This is DR275, which we do not retroactively apply to C++98/03.
8842 if (WasQualifiedName) {
8843 if (CurContext->Encloses(OrigContext))
8844 return false;
8845 } else {
8846 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8847 return false;
8848 }
8849
8850 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8851 if (WasQualifiedName)
8852 S.Diag(InstLoc,
8853 S.getLangOpts().CPlusPlus11?
8854 diag::err_explicit_instantiation_out_of_scope :
8855 diag::warn_explicit_instantiation_out_of_scope_0x)
8856 << D << NS;
8857 else
8858 S.Diag(InstLoc,
8859 S.getLangOpts().CPlusPlus11?
8860 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8861 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8862 << D << NS;
8863 } else
8864 S.Diag(InstLoc,
8865 S.getLangOpts().CPlusPlus11?
8866 diag::err_explicit_instantiation_must_be_global :
8867 diag::warn_explicit_instantiation_must_be_global_0x)
8868 << D;
8869 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8870 return false;
8871}
8872
8873/// Common checks for whether an explicit instantiation of \p D is valid.
8874static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
8875 SourceLocation InstLoc,
8876 bool WasQualifiedName,
8877 TemplateSpecializationKind TSK) {
8878 // C++ [temp.explicit]p13:
8879 // An explicit instantiation declaration shall not name a specialization of
8880 // a template with internal linkage.
8881 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8882 D->getFormalLinkage() == InternalLinkage) {
8883 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
8884 return true;
8885 }
8886
8887 // C++11 [temp.explicit]p3: [DR 275]
8888 // An explicit instantiation shall appear in an enclosing namespace of its
8889 // template.
8890 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
8891 return true;
8892
8893 return false;
8894}
8895
8896/// Determine whether the given scope specifier has a template-id in it.
8897static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8898 if (!SS.isSet())
8899 return false;
8900
8901 // C++11 [temp.explicit]p3:
8902 // If the explicit instantiation is for a member function, a member class
8903 // or a static data member of a class template specialization, the name of
8904 // the class template specialization in the qualified-id for the member
8905 // name shall be a simple-template-id.
8906 //
8907 // C++98 has the same restriction, just worded differently.
8908 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8909 NNS = NNS->getPrefix())
8910 if (const Type *T = NNS->getAsType())
8911 if (isa<TemplateSpecializationType>(T))
8912 return true;
8913
8914 return false;
8915}
8916
8917/// Make a dllexport or dllimport attr on a class template specialization take
8918/// effect.
8919static void dllExportImportClassTemplateSpecialization(
8920 Sema &S, ClassTemplateSpecializationDecl *Def) {
8921 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8922 assert(A && "dllExportImportClassTemplateSpecialization called "((A && "dllExportImportClassTemplateSpecialization called "
"on Def without dllexport or dllimport") ? static_cast<void
> (0) : __assert_fail ("A && \"dllExportImportClassTemplateSpecialization called \" \"on Def without dllexport or dllimport\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8923, __PRETTY_FUNCTION__))
8923 "on Def without dllexport or dllimport")((A && "dllExportImportClassTemplateSpecialization called "
"on Def without dllexport or dllimport") ? static_cast<void
> (0) : __assert_fail ("A && \"dllExportImportClassTemplateSpecialization called \" \"on Def without dllexport or dllimport\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8923, __PRETTY_FUNCTION__))
;
8924
8925 // We reject explicit instantiations in class scope, so there should
8926 // never be any delayed exported classes to worry about.
8927 assert(S.DelayedDllExportClasses.empty() &&((S.DelayedDllExportClasses.empty() && "delayed exports present at explicit instantiation"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"delayed exports present at explicit instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8928, __PRETTY_FUNCTION__))
8928 "delayed exports present at explicit instantiation")((S.DelayedDllExportClasses.empty() && "delayed exports present at explicit instantiation"
) ? static_cast<void> (0) : __assert_fail ("S.DelayedDllExportClasses.empty() && \"delayed exports present at explicit instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8928, __PRETTY_FUNCTION__))
;
8929 S.checkClassLevelDLLAttribute(Def);
8930
8931 // Propagate attribute to base class templates.
8932 for (auto &B : Def->bases()) {
8933 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8934 B.getType()->getAsCXXRecordDecl()))
8935 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
8936 }
8937
8938 S.referenceDLLExportedClassMethods();
8939}
8940
8941// Explicit instantiation of a class template specialization
8942DeclResult Sema::ActOnExplicitInstantiation(
8943 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8944 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8945 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8946 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8947 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
8948 // Find the class template we're specializing
8949 TemplateName Name = TemplateD.get();
8950 TemplateDecl *TD = Name.getAsTemplateDecl();
8951 // Check that the specialization uses the same tag kind as the
8952 // original template.
8953 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8954 assert(Kind != TTK_Enum &&((Kind != TTK_Enum && "Invalid enum tag in class template explicit instantiation!"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template explicit instantiation!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8955, __PRETTY_FUNCTION__))
8955 "Invalid enum tag in class template explicit instantiation!")((Kind != TTK_Enum && "Invalid enum tag in class template explicit instantiation!"
) ? static_cast<void> (0) : __assert_fail ("Kind != TTK_Enum && \"Invalid enum tag in class template explicit instantiation!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 8955, __PRETTY_FUNCTION__))
;
8956
8957 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8958
8959 if (!ClassTemplate) {
8960 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8961 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8962 Diag(TD->getLocation(), diag::note_previous_use);
8963 return true;
8964 }
8965
8966 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8967 Kind, /*isDefinition*/false, KWLoc,
8968 ClassTemplate->getIdentifier())) {
8969 Diag(KWLoc, diag::err_use_with_wrong_tag)
8970 << ClassTemplate
8971 << FixItHint::CreateReplacement(KWLoc,
8972 ClassTemplate->getTemplatedDecl()->getKindName());
8973 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8974 diag::note_previous_use);
8975 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8976 }
8977
8978 // C++0x [temp.explicit]p2:
8979 // There are two forms of explicit instantiation: an explicit instantiation
8980 // definition and an explicit instantiation declaration. An explicit
8981 // instantiation declaration begins with the extern keyword. [...]
8982 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8983 ? TSK_ExplicitInstantiationDefinition
8984 : TSK_ExplicitInstantiationDeclaration;
8985
8986 if (TSK == TSK_ExplicitInstantiationDeclaration &&
8987 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
8988 // Check for dllexport class template instantiation declarations,
8989 // except for MinGW mode.
8990 for (const ParsedAttr &AL : Attr) {
8991 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8992 Diag(ExternLoc,
8993 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8994 Diag(AL.getLoc(), diag::note_attribute);
8995 break;
8996 }
8997 }
8998
8999 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9000 Diag(ExternLoc,
9001 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9002 Diag(A->getLocation(), diag::note_attribute);
9003 }
9004 }
9005
9006 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9007 // instantiation declarations for most purposes.
9008 bool DLLImportExplicitInstantiationDef = false;
9009 if (TSK == TSK_ExplicitInstantiationDefinition &&
9010 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9011 // Check for dllimport class template instantiation definitions.
9012 bool DLLImport =
9013 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9014 for (const ParsedAttr &AL : Attr) {
9015 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9016 DLLImport = true;
9017 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9018 // dllexport trumps dllimport here.
9019 DLLImport = false;
9020 break;
9021 }
9022 }
9023 if (DLLImport) {
9024 TSK = TSK_ExplicitInstantiationDeclaration;
9025 DLLImportExplicitInstantiationDef = true;
9026 }
9027 }
9028
9029 // Translate the parser's template argument list in our AST format.
9030 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9031 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9032
9033 // Check that the template argument list is well-formed for this
9034 // template.
9035 SmallVector<TemplateArgument, 4> Converted;
9036 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
9037 TemplateArgs, false, Converted))
9038 return true;
9039
9040 // Find the class template specialization declaration that
9041 // corresponds to these arguments.
9042 void *InsertPos = nullptr;
9043 ClassTemplateSpecializationDecl *PrevDecl
9044 = ClassTemplate->findSpecialization(Converted, InsertPos);
9045
9046 TemplateSpecializationKind PrevDecl_TSK
9047 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9048
9049 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9050 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9051 // Check for dllexport class template instantiation definitions in MinGW
9052 // mode, if a previous declaration of the instantiation was seen.
9053 for (const ParsedAttr &AL : Attr) {
9054 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9055 Diag(AL.getLoc(),
9056 diag::warn_attribute_dllexport_explicit_instantiation_def);
9057 break;
9058 }
9059 }
9060 }
9061
9062 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9063 SS.isSet(), TSK))
9064 return true;
9065
9066 ClassTemplateSpecializationDecl *Specialization = nullptr;
9067
9068 bool HasNoEffect = false;
9069 if (PrevDecl) {
9070 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9071 PrevDecl, PrevDecl_TSK,
9072 PrevDecl->getPointOfInstantiation(),
9073 HasNoEffect))
9074 return PrevDecl;
9075
9076 // Even though HasNoEffect == true means that this explicit instantiation
9077 // has no effect on semantics, we go on to put its syntax in the AST.
9078
9079 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9080 PrevDecl_TSK == TSK_Undeclared) {
9081 // Since the only prior class template specialization with these
9082 // arguments was referenced but not declared, reuse that
9083 // declaration node as our own, updating the source location
9084 // for the template name to reflect our new declaration.
9085 // (Other source locations will be updated later.)
9086 Specialization = PrevDecl;
9087 Specialization->setLocation(TemplateNameLoc);
9088 PrevDecl = nullptr;
9089 }
9090
9091 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9092 DLLImportExplicitInstantiationDef) {
9093 // The new specialization might add a dllimport attribute.
9094 HasNoEffect = false;
9095 }
9096 }
9097
9098 if (!Specialization) {
9099 // Create a new class template specialization declaration node for
9100 // this explicit specialization.
9101 Specialization
9102 = ClassTemplateSpecializationDecl::Create(Context, Kind,
9103 ClassTemplate->getDeclContext(),
9104 KWLoc, TemplateNameLoc,
9105 ClassTemplate,
9106 Converted,
9107 PrevDecl);
9108 SetNestedNameSpecifier(*this, Specialization, SS);
9109
9110 if (!HasNoEffect && !PrevDecl) {
9111 // Insert the new specialization.
9112 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9113 }
9114 }
9115
9116 // Build the fully-sugared type for this explicit instantiation as
9117 // the user wrote in the explicit instantiation itself. This means
9118 // that we'll pretty-print the type retrieved from the
9119 // specialization's declaration the way that the user actually wrote
9120 // the explicit instantiation, rather than formatting the name based
9121 // on the "canonical" representation used to store the template
9122 // arguments in the specialization.
9123 TypeSourceInfo *WrittenTy
9124 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9125 TemplateArgs,
9126 Context.getTypeDeclType(Specialization));
9127 Specialization->setTypeAsWritten(WrittenTy);
9128
9129 // Set source locations for keywords.
9130 Specialization->setExternLoc(ExternLoc);
9131 Specialization->setTemplateKeywordLoc(TemplateLoc);
9132 Specialization->setBraceRange(SourceRange());
9133
9134 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9135 ProcessDeclAttributeList(S, Specialization, Attr);
9136
9137 // Add the explicit instantiation into its lexical context. However,
9138 // since explicit instantiations are never found by name lookup, we
9139 // just put it into the declaration context directly.
9140 Specialization->setLexicalDeclContext(CurContext);
9141 CurContext->addDecl(Specialization);
9142
9143 // Syntax is now OK, so return if it has no other effect on semantics.
9144 if (HasNoEffect) {
9145 // Set the template specialization kind.
9146 Specialization->setTemplateSpecializationKind(TSK);
9147 return Specialization;
9148 }
9149
9150 // C++ [temp.explicit]p3:
9151 // A definition of a class template or class member template
9152 // shall be in scope at the point of the explicit instantiation of
9153 // the class template or class member template.
9154 //
9155 // This check comes when we actually try to perform the
9156 // instantiation.
9157 ClassTemplateSpecializationDecl *Def
9158 = cast_or_null<ClassTemplateSpecializationDecl>(
9159 Specialization->getDefinition());
9160 if (!Def)
9161 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9162 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9163 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9164 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9165 }
9166
9167 // Instantiate the members of this class template specialization.
9168 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9169 Specialization->getDefinition());
9170 if (Def) {
9171 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
9172 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9173 // TSK_ExplicitInstantiationDefinition
9174 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9175 (TSK == TSK_ExplicitInstantiationDefinition ||
9176 DLLImportExplicitInstantiationDef)) {
9177 // FIXME: Need to notify the ASTMutationListener that we did this.
9178 Def->setTemplateSpecializationKind(TSK);
9179
9180 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9181 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9182 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9183 // In the MS ABI, an explicit instantiation definition can add a dll
9184 // attribute to a template with a previous instantiation declaration.
9185 // MinGW doesn't allow this.
9186 auto *A = cast<InheritableAttr>(
9187 getDLLAttr(Specialization)->clone(getASTContext()));
9188 A->setInherited(true);
9189 Def->addAttr(A);
9190 dllExportImportClassTemplateSpecialization(*this, Def);
9191 }
9192 }
9193
9194 // Fix a TSK_ImplicitInstantiation followed by a
9195 // TSK_ExplicitInstantiationDefinition
9196 bool NewlyDLLExported =
9197 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9198 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9199 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9200 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9201 // In the MS ABI, an explicit instantiation definition can add a dll
9202 // attribute to a template with a previous implicit instantiation.
9203 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9204 // avoid potentially strange codegen behavior. For example, if we extend
9205 // this conditional to dllimport, and we have a source file calling a
9206 // method on an implicitly instantiated template class instance and then
9207 // declaring a dllimport explicit instantiation definition for the same
9208 // template class, the codegen for the method call will not respect the
9209 // dllimport, while it will with cl. The Def will already have the DLL
9210 // attribute, since the Def and Specialization will be the same in the
9211 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9212 // attribute to the Specialization; we just need to make it take effect.
9213 assert(Def == Specialization &&((Def == Specialization && "Def and Specialization should match for implicit instantiation"
) ? static_cast<void> (0) : __assert_fail ("Def == Specialization && \"Def and Specialization should match for implicit instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9214, __PRETTY_FUNCTION__))
9214 "Def and Specialization should match for implicit instantiation")((Def == Specialization && "Def and Specialization should match for implicit instantiation"
) ? static_cast<void> (0) : __assert_fail ("Def == Specialization && \"Def and Specialization should match for implicit instantiation\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9214, __PRETTY_FUNCTION__))
;
9215 dllExportImportClassTemplateSpecialization(*this, Def);
9216 }
9217
9218 // In MinGW mode, export the template instantiation if the declaration
9219 // was marked dllexport.
9220 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9221 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9222 PrevDecl->hasAttr<DLLExportAttr>()) {
9223 dllExportImportClassTemplateSpecialization(*this, Def);
9224 }
9225
9226 // Set the template specialization kind. Make sure it is set before
9227 // instantiating the members which will trigger ASTConsumer callbacks.
9228 Specialization->setTemplateSpecializationKind(TSK);
9229 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9230 } else {
9231
9232 // Set the template specialization kind.
9233 Specialization->setTemplateSpecializationKind(TSK);
9234 }
9235
9236 return Specialization;
9237}
9238
9239// Explicit instantiation of a member class of a class template.
9240DeclResult
9241Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9242 SourceLocation TemplateLoc, unsigned TagSpec,
9243 SourceLocation KWLoc, CXXScopeSpec &SS,
9244 IdentifierInfo *Name, SourceLocation NameLoc,
9245 const ParsedAttributesView &Attr) {
9246
9247 bool Owned = false;
9248 bool IsDependent = false;
9249 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
9250 KWLoc, SS, Name, NameLoc, Attr, AS_none,
9251 /*ModulePrivateLoc=*/SourceLocation(),
9252 MultiTemplateParamsArg(), Owned, IsDependent,
9253 SourceLocation(), false, TypeResult(),
9254 /*IsTypeSpecifier*/false,
9255 /*IsTemplateParamOrArg*/false);
9256 assert(!IsDependent && "explicit instantiation of dependent name not yet handled")((!IsDependent && "explicit instantiation of dependent name not yet handled"
) ? static_cast<void> (0) : __assert_fail ("!IsDependent && \"explicit instantiation of dependent name not yet handled\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9256, __PRETTY_FUNCTION__))
;
9257
9258 if (!TagD)
9259 return true;
9260
9261 TagDecl *Tag = cast<TagDecl>(TagD);
9262 assert(!Tag->isEnum() && "shouldn't see enumerations here")((!Tag->isEnum() && "shouldn't see enumerations here"
) ? static_cast<void> (0) : __assert_fail ("!Tag->isEnum() && \"shouldn't see enumerations here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9262, __PRETTY_FUNCTION__))
;
9263
9264 if (Tag->isInvalidDecl())
9265 return true;
9266
9267 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9268 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9269 if (!Pattern) {
9270 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9271 << Context.getTypeDeclType(Record);
9272 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9273 return true;
9274 }
9275
9276 // C++0x [temp.explicit]p2:
9277 // If the explicit instantiation is for a class or member class, the
9278 // elaborated-type-specifier in the declaration shall include a
9279 // simple-template-id.
9280 //
9281 // C++98 has the same restriction, just worded differently.
9282 if (!ScopeSpecifierHasTemplateId(SS))
9283 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
9284 << Record << SS.getRange();
9285
9286 // C++0x [temp.explicit]p2:
9287 // There are two forms of explicit instantiation: an explicit instantiation
9288 // definition and an explicit instantiation declaration. An explicit
9289 // instantiation declaration begins with the extern keyword. [...]
9290 TemplateSpecializationKind TSK
9291 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9292 : TSK_ExplicitInstantiationDeclaration;
9293
9294 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
9295
9296 // Verify that it is okay to explicitly instantiate here.
9297 CXXRecordDecl *PrevDecl
9298 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
9299 if (!PrevDecl && Record->getDefinition())
9300 PrevDecl = Record;
9301 if (PrevDecl) {
9302 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
9303 bool HasNoEffect = false;
9304 assert(MSInfo && "No member specialization information?")((MSInfo && "No member specialization information?") ?
static_cast<void> (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9304, __PRETTY_FUNCTION__))
;
9305 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
9306 PrevDecl,
9307 MSInfo->getTemplateSpecializationKind(),
9308 MSInfo->getPointOfInstantiation(),
9309 HasNoEffect))
9310 return true;
9311 if (HasNoEffect)
9312 return TagD;
9313 }
9314
9315 CXXRecordDecl *RecordDef
9316 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9317 if (!RecordDef) {
9318 // C++ [temp.explicit]p3:
9319 // A definition of a member class of a class template shall be in scope
9320 // at the point of an explicit instantiation of the member class.
9321 CXXRecordDecl *Def
9322 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
9323 if (!Def) {
9324 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9325 << 0 << Record->getDeclName() << Record->getDeclContext();
9326 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9327 << Pattern;
9328 return true;
9329 } else {
9330 if (InstantiateClass(NameLoc, Record, Def,
9331 getTemplateInstantiationArgs(Record),
9332 TSK))
9333 return true;
9334
9335 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9336 if (!RecordDef)
9337 return true;
9338 }
9339 }
9340
9341 // Instantiate all of the members of the class.
9342 InstantiateClassMembers(NameLoc, RecordDef,
9343 getTemplateInstantiationArgs(Record), TSK);
9344
9345 if (TSK == TSK_ExplicitInstantiationDefinition)
9346 MarkVTableUsed(NameLoc, RecordDef, true);
9347
9348 // FIXME: We don't have any representation for explicit instantiations of
9349 // member classes. Such a representation is not needed for compilation, but it
9350 // should be available for clients that want to see all of the declarations in
9351 // the source code.
9352 return TagD;
9353}
9354
9355DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9356 SourceLocation ExternLoc,
9357 SourceLocation TemplateLoc,
9358 Declarator &D) {
9359 // Explicit instantiations always require a name.
9360 // TODO: check if/when DNInfo should replace Name.
9361 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9362 DeclarationName Name = NameInfo.getName();
9363 if (!Name) {
9364 if (!D.isInvalidType())
9365 Diag(D.getDeclSpec().getBeginLoc(),
9366 diag::err_explicit_instantiation_requires_name)
9367 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9368
9369 return true;
9370 }
9371
9372 // The scope passed in may not be a decl scope. Zip up the scope tree until
9373 // we find one that is.
9374 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9375 (S->getFlags() & Scope::TemplateParamScope) != 0)
9376 S = S->getParent();
9377
9378 // Determine the type of the declaration.
9379 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9380 QualType R = T->getType();
9381 if (R.isNull())
9382 return true;
9383
9384 // C++ [dcl.stc]p1:
9385 // A storage-class-specifier shall not be specified in [...] an explicit
9386 // instantiation (14.7.2) directive.
9387 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9388 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9389 << Name;
9390 return true;
9391 } else if (D.getDeclSpec().getStorageClassSpec()
9392 != DeclSpec::SCS_unspecified) {
9393 // Complain about then remove the storage class specifier.
9394 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9395 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9396
9397 D.getMutableDeclSpec().ClearStorageClassSpecs();
9398 }
9399
9400 // C++0x [temp.explicit]p1:
9401 // [...] An explicit instantiation of a function template shall not use the
9402 // inline or constexpr specifiers.
9403 // Presumably, this also applies to member functions of class templates as
9404 // well.
9405 if (D.getDeclSpec().isInlineSpecified())
9406 Diag(D.getDeclSpec().getInlineSpecLoc(),
9407 getLangOpts().CPlusPlus11 ?
9408 diag::err_explicit_instantiation_inline :
9409 diag::warn_explicit_instantiation_inline_0x)
9410 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9411 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
9412 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9413 // not already specified.
9414 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9415 diag::err_explicit_instantiation_constexpr);
9416
9417 // A deduction guide is not on the list of entities that can be explicitly
9418 // instantiated.
9419 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9420 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9421 << /*explicit instantiation*/ 0;
9422 return true;
9423 }
9424
9425 // C++0x [temp.explicit]p2:
9426 // There are two forms of explicit instantiation: an explicit instantiation
9427 // definition and an explicit instantiation declaration. An explicit
9428 // instantiation declaration begins with the extern keyword. [...]
9429 TemplateSpecializationKind TSK
9430 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9431 : TSK_ExplicitInstantiationDeclaration;
9432
9433 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9434 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
9435
9436 if (!R->isFunctionType()) {
9437 // C++ [temp.explicit]p1:
9438 // A [...] static data member of a class template can be explicitly
9439 // instantiated from the member definition associated with its class
9440 // template.
9441 // C++1y [temp.explicit]p1:
9442 // A [...] variable [...] template specialization can be explicitly
9443 // instantiated from its template.
9444 if (Previous.isAmbiguous())
9445 return true;
9446
9447 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9448 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9449
9450 if (!PrevTemplate) {
9451 if (!Prev || !Prev->isStaticDataMember()) {
9452 // We expect to see a static data member here.
9453 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9454 << Name;
9455 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9456 P != PEnd; ++P)
9457 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9458 return true;
9459 }
9460
9461 if (!Prev->getInstantiatedFromStaticDataMember()) {
9462 // FIXME: Check for explicit specialization?
9463 Diag(D.getIdentifierLoc(),
9464 diag::err_explicit_instantiation_data_member_not_instantiated)
9465 << Prev;
9466 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9467 // FIXME: Can we provide a note showing where this was declared?
9468 return true;
9469 }
9470 } else {
9471 // Explicitly instantiate a variable template.
9472
9473 // C++1y [dcl.spec.auto]p6:
9474 // ... A program that uses auto or decltype(auto) in a context not
9475 // explicitly allowed in this section is ill-formed.
9476 //
9477 // This includes auto-typed variable template instantiations.
9478 if (R->isUndeducedType()) {
9479 Diag(T->getTypeLoc().getBeginLoc(),
9480 diag::err_auto_not_allowed_var_inst);
9481 return true;
9482 }
9483
9484 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9485 // C++1y [temp.explicit]p3:
9486 // If the explicit instantiation is for a variable, the unqualified-id
9487 // in the declaration shall be a template-id.
9488 Diag(D.getIdentifierLoc(),
9489 diag::err_explicit_instantiation_without_template_id)
9490 << PrevTemplate;
9491 Diag(PrevTemplate->getLocation(),
9492 diag::note_explicit_instantiation_here);
9493 return true;
9494 }
9495
9496 // Translate the parser's template argument list into our AST format.
9497 TemplateArgumentListInfo TemplateArgs =
9498 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9499
9500 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9501 D.getIdentifierLoc(), TemplateArgs);
9502 if (Res.isInvalid())
9503 return true;
9504
9505 // Ignore access control bits, we don't need them for redeclaration
9506 // checking.
9507 Prev = cast<VarDecl>(Res.get());
9508 }
9509
9510 // C++0x [temp.explicit]p2:
9511 // If the explicit instantiation is for a member function, a member class
9512 // or a static data member of a class template specialization, the name of
9513 // the class template specialization in the qualified-id for the member
9514 // name shall be a simple-template-id.
9515 //
9516 // C++98 has the same restriction, just worded differently.
9517 //
9518 // This does not apply to variable template specializations, where the
9519 // template-id is in the unqualified-id instead.
9520 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9521 Diag(D.getIdentifierLoc(),
9522 diag::ext_explicit_instantiation_without_qualified_id)
9523 << Prev << D.getCXXScopeSpec().getRange();
9524
9525 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
9526
9527 // Verify that it is okay to explicitly instantiate here.
9528 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9529 SourceLocation POI = Prev->getPointOfInstantiation();
9530 bool HasNoEffect = false;
9531 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9532 PrevTSK, POI, HasNoEffect))
9533 return true;
9534
9535 if (!HasNoEffect) {
9536 // Instantiate static data member or variable template.
9537 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9538 // Merge attributes.
9539 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
9540 if (TSK == TSK_ExplicitInstantiationDefinition)
9541 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9542 }
9543
9544 // Check the new variable specialization against the parsed input.
9545 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9546 Diag(T->getTypeLoc().getBeginLoc(),
9547 diag::err_invalid_var_template_spec_type)
9548 << 0 << PrevTemplate << R << Prev->getType();
9549 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9550 << 2 << PrevTemplate->getDeclName();
9551 return true;
9552 }
9553
9554 // FIXME: Create an ExplicitInstantiation node?
9555 return (Decl*) nullptr;
9556 }
9557
9558 // If the declarator is a template-id, translate the parser's template
9559 // argument list into our AST format.
9560 bool HasExplicitTemplateArgs = false;
9561 TemplateArgumentListInfo TemplateArgs;
9562 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9563 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9564 HasExplicitTemplateArgs = true;
9565 }
9566
9567 // C++ [temp.explicit]p1:
9568 // A [...] function [...] can be explicitly instantiated from its template.
9569 // A member function [...] of a class template can be explicitly
9570 // instantiated from the member definition associated with its class
9571 // template.
9572 UnresolvedSet<8> TemplateMatches;
9573 FunctionDecl *NonTemplateMatch = nullptr;
9574 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9575 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9576 P != PEnd; ++P) {
9577 NamedDecl *Prev = *P;
9578 if (!HasExplicitTemplateArgs) {
9579 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9580 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9581 /*AdjustExceptionSpec*/true);
9582 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9583 if (Method->getPrimaryTemplate()) {
9584 TemplateMatches.addDecl(Method, P.getAccess());
9585 } else {
9586 // FIXME: Can this assert ever happen? Needs a test.
9587 assert(!NonTemplateMatch && "Multiple NonTemplateMatches")((!NonTemplateMatch && "Multiple NonTemplateMatches")
? static_cast<void> (0) : __assert_fail ("!NonTemplateMatch && \"Multiple NonTemplateMatches\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9587, __PRETTY_FUNCTION__))
;
9588 NonTemplateMatch = Method;
9589 }
9590 }
9591 }
9592 }
9593
9594 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9595 if (!FunTmpl)
9596 continue;
9597
9598 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9599 FunctionDecl *Specialization = nullptr;
9600 if (TemplateDeductionResult TDK
9601 = DeduceTemplateArguments(FunTmpl,
9602 (HasExplicitTemplateArgs ? &TemplateArgs
9603 : nullptr),
9604 R, Specialization, Info)) {
9605 // Keep track of almost-matches.
9606 FailedCandidates.addCandidate()
9607 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9608 MakeDeductionFailureInfo(Context, TDK, Info));
9609 (void)TDK;
9610 continue;
9611 }
9612
9613 // Target attributes are part of the cuda function signature, so
9614 // the cuda target of the instantiated function must match that of its
9615 // template. Given that C++ template deduction does not take
9616 // target attributes into account, we reject candidates here that
9617 // have a different target.
9618 if (LangOpts.CUDA &&
9619 IdentifyCUDATarget(Specialization,
9620 /* IgnoreImplicitHDAttr = */ true) !=
9621 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
9622 FailedCandidates.addCandidate().set(
9623 P.getPair(), FunTmpl->getTemplatedDecl(),
9624 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9625 continue;
9626 }
9627
9628 TemplateMatches.addDecl(Specialization, P.getAccess());
9629 }
9630
9631 FunctionDecl *Specialization = NonTemplateMatch;
9632 if (!Specialization) {
9633 // Find the most specialized function template specialization.
9634 UnresolvedSetIterator Result = getMostSpecialized(
9635 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9636 D.getIdentifierLoc(),
9637 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9638 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9639 PDiag(diag::note_explicit_instantiation_candidate));
9640
9641 if (Result == TemplateMatches.end())
9642 return true;
9643
9644 // Ignore access control bits, we don't need them for redeclaration checking.
9645 Specialization = cast<FunctionDecl>(*Result);
9646 }
9647
9648 // C++11 [except.spec]p4
9649 // In an explicit instantiation an exception-specification may be specified,
9650 // but is not required.
9651 // If an exception-specification is specified in an explicit instantiation
9652 // directive, it shall be compatible with the exception-specifications of
9653 // other declarations of that function.
9654 if (auto *FPT = R->getAs<FunctionProtoType>())
9655 if (FPT->hasExceptionSpec()) {
9656 unsigned DiagID =
9657 diag::err_mismatched_exception_spec_explicit_instantiation;
9658 if (getLangOpts().MicrosoftExt)
9659 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9660 bool Result = CheckEquivalentExceptionSpec(
9661 PDiag(DiagID) << Specialization->getType(),
9662 PDiag(diag::note_explicit_instantiation_here),
9663 Specialization->getType()->getAs<FunctionProtoType>(),
9664 Specialization->getLocation(), FPT, D.getBeginLoc());
9665 // In Microsoft mode, mismatching exception specifications just cause a
9666 // warning.
9667 if (!getLangOpts().MicrosoftExt && Result)
9668 return true;
9669 }
9670
9671 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9672 Diag(D.getIdentifierLoc(),
9673 diag::err_explicit_instantiation_member_function_not_instantiated)
9674 << Specialization
9675 << (Specialization->getTemplateSpecializationKind() ==
9676 TSK_ExplicitSpecialization);
9677 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9678 return true;
9679 }
9680
9681 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9682 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9683 PrevDecl = Specialization;
9684
9685 if (PrevDecl) {
9686 bool HasNoEffect = false;
9687 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9688 PrevDecl,
9689 PrevDecl->getTemplateSpecializationKind(),
9690 PrevDecl->getPointOfInstantiation(),
9691 HasNoEffect))
9692 return true;
9693
9694 // FIXME: We may still want to build some representation of this
9695 // explicit specialization.
9696 if (HasNoEffect)
9697 return (Decl*) nullptr;
9698 }
9699
9700 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9701 // functions
9702 // valarray<size_t>::valarray(size_t) and
9703 // valarray<size_t>::~valarray()
9704 // that it declared to have internal linkage with the internal_linkage
9705 // attribute. Ignore the explicit instantiation declaration in this case.
9706 if (Specialization->hasAttr<InternalLinkageAttr>() &&
9707 TSK == TSK_ExplicitInstantiationDeclaration) {
9708 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9709 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9710 RD->isInStdNamespace())
9711 return (Decl*) nullptr;
9712 }
9713
9714 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
9715
9716 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9717 // instantiation declarations.
9718 if (TSK == TSK_ExplicitInstantiationDefinition &&
9719 Specialization->hasAttr<DLLImportAttr>() &&
9720 Context.getTargetInfo().getCXXABI().isMicrosoft())
9721 TSK = TSK_ExplicitInstantiationDeclaration;
9722
9723 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9724
9725 if (Specialization->isDefined()) {
9726 // Let the ASTConsumer know that this function has been explicitly
9727 // instantiated now, and its linkage might have changed.
9728 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9729 } else if (TSK == TSK_ExplicitInstantiationDefinition)
9730 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9731
9732 // C++0x [temp.explicit]p2:
9733 // If the explicit instantiation is for a member function, a member class
9734 // or a static data member of a class template specialization, the name of
9735 // the class template specialization in the qualified-id for the member
9736 // name shall be a simple-template-id.
9737 //
9738 // C++98 has the same restriction, just worded differently.
9739 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9740 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9741 D.getCXXScopeSpec().isSet() &&
9742 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9743 Diag(D.getIdentifierLoc(),
9744 diag::ext_explicit_instantiation_without_qualified_id)
9745 << Specialization << D.getCXXScopeSpec().getRange();
9746
9747 CheckExplicitInstantiation(
9748 *this,
9749 FunTmpl ? (NamedDecl *)FunTmpl
9750 : Specialization->getInstantiatedFromMemberFunction(),
9751 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
9752
9753 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9754 return (Decl*) nullptr;
9755}
9756
9757TypeResult
9758Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9759 const CXXScopeSpec &SS, IdentifierInfo *Name,
9760 SourceLocation TagLoc, SourceLocation NameLoc) {
9761 // This has to hold, because SS is expected to be defined.
9762 assert(Name && "Expected a name in a dependent tag")((Name && "Expected a name in a dependent tag") ? static_cast
<void> (0) : __assert_fail ("Name && \"Expected a name in a dependent tag\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9762, __PRETTY_FUNCTION__))
;
9763
9764 NestedNameSpecifier *NNS = SS.getScopeRep();
9765 if (!NNS)
9766 return true;
9767
9768 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9769
9770 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9771 Diag(NameLoc, diag::err_dependent_tag_decl)
9772 << (TUK == TUK_Definition) << Kind << SS.getRange();
9773 return true;
9774 }
9775
9776 // Create the resulting type.
9777 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9778 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9779
9780 // Create type-source location information for this type.
9781 TypeLocBuilder TLB;
9782 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9783 TL.setElaboratedKeywordLoc(TagLoc);
9784 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9785 TL.setNameLoc(NameLoc);
9786 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9787}
9788
9789TypeResult
9790Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9791 const CXXScopeSpec &SS, const IdentifierInfo &II,
9792 SourceLocation IdLoc) {
9793 if (SS.isInvalid())
9794 return true;
9795
9796 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9797 Diag(TypenameLoc,
9798 getLangOpts().CPlusPlus11 ?
9799 diag::warn_cxx98_compat_typename_outside_of_template :
9800 diag::ext_typename_outside_of_template)
9801 << FixItHint::CreateRemoval(TypenameLoc);
9802
9803 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9804 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9805 TypenameLoc, QualifierLoc, II, IdLoc);
9806 if (T.isNull())
9807 return true;
9808
9809 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9810 if (isa<DependentNameType>(T)) {
9811 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9812 TL.setElaboratedKeywordLoc(TypenameLoc);
9813 TL.setQualifierLoc(QualifierLoc);
9814 TL.setNameLoc(IdLoc);
9815 } else {
9816 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9817 TL.setElaboratedKeywordLoc(TypenameLoc);
9818 TL.setQualifierLoc(QualifierLoc);
9819 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9820 }
9821
9822 return CreateParsedType(T, TSI);
9823}
9824
9825TypeResult
9826Sema::ActOnTypenameType(Scope *S,
9827 SourceLocation TypenameLoc,
9828 const CXXScopeSpec &SS,
9829 SourceLocation TemplateKWLoc,
9830 TemplateTy TemplateIn,
9831 IdentifierInfo *TemplateII,
9832 SourceLocation TemplateIILoc,
9833 SourceLocation LAngleLoc,
9834 ASTTemplateArgsPtr TemplateArgsIn,
9835 SourceLocation RAngleLoc) {
9836 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9837 Diag(TypenameLoc,
9838 getLangOpts().CPlusPlus11 ?
9839 diag::warn_cxx98_compat_typename_outside_of_template :
9840 diag::ext_typename_outside_of_template)
9841 << FixItHint::CreateRemoval(TypenameLoc);
9842
9843 // Strangely, non-type results are not ignored by this lookup, so the
9844 // program is ill-formed if it finds an injected-class-name.
9845 if (TypenameLoc.isValid()) {
9846 auto *LookupRD =
9847 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9848 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9849 Diag(TemplateIILoc,
9850 diag::ext_out_of_line_qualified_id_type_names_constructor)
9851 << TemplateII << 0 /*injected-class-name used as template name*/
9852 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9853 }
9854 }
9855
9856 // Translate the parser's template argument list in our AST format.
9857 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9858 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9859
9860 TemplateName Template = TemplateIn.get();
9861 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9862 // Construct a dependent template specialization type.
9863 assert(DTN && "dependent template has non-dependent name?")((DTN && "dependent template has non-dependent name?"
) ? static_cast<void> (0) : __assert_fail ("DTN && \"dependent template has non-dependent name?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9863, __PRETTY_FUNCTION__))
;
9864 assert(DTN->getQualifier() == SS.getScopeRep())((DTN->getQualifier() == SS.getScopeRep()) ? static_cast<
void> (0) : __assert_fail ("DTN->getQualifier() == SS.getScopeRep()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9864, __PRETTY_FUNCTION__))
;
9865 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9866 DTN->getQualifier(),
9867 DTN->getIdentifier(),
9868 TemplateArgs);
9869
9870 // Create source-location information for this type.
9871 TypeLocBuilder Builder;
9872 DependentTemplateSpecializationTypeLoc SpecTL
9873 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9874 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9875 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9876 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9877 SpecTL.setTemplateNameLoc(TemplateIILoc);
9878 SpecTL.setLAngleLoc(LAngleLoc);
9879 SpecTL.setRAngleLoc(RAngleLoc);
9880 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9881 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9882 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9883 }
9884
9885 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9886 if (T.isNull())
9887 return true;
9888
9889 // Provide source-location information for the template specialization type.
9890 TypeLocBuilder Builder;
9891 TemplateSpecializationTypeLoc SpecTL
9892 = Builder.push<TemplateSpecializationTypeLoc>(T);
9893 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9894 SpecTL.setTemplateNameLoc(TemplateIILoc);
9895 SpecTL.setLAngleLoc(LAngleLoc);
9896 SpecTL.setRAngleLoc(RAngleLoc);
9897 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9898 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9899
9900 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9901 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9902 TL.setElaboratedKeywordLoc(TypenameLoc);
9903 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9904
9905 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9906 return CreateParsedType(T, TSI);
9907}
9908
9909
9910/// Determine whether this failed name lookup should be treated as being
9911/// disabled by a usage of std::enable_if.
9912static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9913 SourceRange &CondRange, Expr *&Cond) {
9914 // We must be looking for a ::type...
9915 if (!II.isStr("type"))
9916 return false;
9917
9918 // ... within an explicitly-written template specialization...
9919 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9920 return false;
9921 TypeLoc EnableIfTy = NNS.getTypeLoc();
9922 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9923 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9924 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9925 return false;
9926 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
9927
9928 // ... which names a complete class template declaration...
9929 const TemplateDecl *EnableIfDecl =
9930 EnableIfTST->getTemplateName().getAsTemplateDecl();
9931 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9932 return false;
9933
9934 // ... called "enable_if".
9935 const IdentifierInfo *EnableIfII =
9936 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9937 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9938 return false;
9939
9940 // Assume the first template argument is the condition.
9941 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9942
9943 // Dig out the condition.
9944 Cond = nullptr;
9945 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9946 != TemplateArgument::Expression)
9947 return true;
9948
9949 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9950
9951 // Ignore Boolean literals; they add no value.
9952 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9953 Cond = nullptr;
9954
9955 return true;
9956}
9957
9958/// Build the type that describes a C++ typename specifier,
9959/// e.g., "typename T::type".
9960QualType
9961Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9962 SourceLocation KeywordLoc,
9963 NestedNameSpecifierLoc QualifierLoc,
9964 const IdentifierInfo &II,
9965 SourceLocation IILoc) {
9966 CXXScopeSpec SS;
9967 SS.Adopt(QualifierLoc);
9968
9969 DeclContext *Ctx = computeDeclContext(SS);
9970 if (!Ctx) {
9971 // If the nested-name-specifier is dependent and couldn't be
9972 // resolved to a type, build a typename type.
9973 assert(QualifierLoc.getNestedNameSpecifier()->isDependent())((QualifierLoc.getNestedNameSpecifier()->isDependent()) ? static_cast
<void> (0) : __assert_fail ("QualifierLoc.getNestedNameSpecifier()->isDependent()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaTemplate.cpp"
, 9973, __PRETTY_FUNCTION__))
;
9974 return Context.getDependentNameType(Keyword,
9975 QualifierLoc.getNestedNameSpecifier(),
9976 &II);
9977 }
9978
9979 // If the nested-name-specifier refers to the current instantiation,
9980 // the "typename" keyword itself is superfluous. In C++03, the
9981 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9982 // allows such extraneous "typename" keywords, and we retroactively
9983 // apply this DR to C++03 code with only a warning. In any case we continue.
9984
9985 if (RequireCompleteDeclContext(SS, Ctx))
9986 return QualType();
9987
9988 DeclarationName Name(&II);
9989 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9990 LookupQualifiedName(Result, Ctx, SS);
9991 unsigned DiagID = 0;
9992 Decl *Referenced = nullptr;
9993 switch (Result.getResultKind()) {
9994 case LookupResult::NotFound: {
9995 // If we're looking up 'type' within a template named 'enable_if', produce
9996 // a more specific diagnostic.
9997 SourceRange CondRange;
9998 Expr *Cond = nullptr;
9999 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10000 // If we have a condition, narrow it down to the specific failed
10001 // condition.
10002 if (Cond) {
10003 Expr *FailedCond;
10004 std::string FailedDescription;
10005 std::tie(FailedCond, FailedDescription) =
10006 findFailedBooleanCondition(Cond);
10007
10008 Diag(FailedCond->getExprLoc(),
10009 diag::err_typename_nested_not_found_requirement)
10010 << FailedDescription
10011 << FailedCond->getSourceRange();
10012 return QualType();
10013 }
10014
10015 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
10016 << Ctx << CondRange;
10017 return QualType();
10018 }
10019
10020 DiagID = diag::err_typename_nested_not_found;
10021 break;
10022 }
10023
10024 case LookupResult::FoundUnresolvedValue: {
10025 // We found a using declaration that is a value. Most likely, the using
10026 // declaration itself is meant to have the 'typename' keyword.
10027 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10028 IILoc);
10029 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10030 << Name << Ctx << FullRange;
10031 if (UnresolvedUsingValueDecl *Using
10032 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10033 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10034 Diag(Loc, diag::note_using_value_decl_missing_typename)
10035 << FixItHint::CreateInsertion(Loc, "typename ");
10036 }
10037 }
10038 // Fall through to create a dependent typename type, from which we can recover
10039 // better.
10040 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10041
10042 case LookupResult::NotFoundInCurrentInstantiation:
10043 // Okay, it's a member of an unknown instantiation.
10044 return Context.getDependentNameType(Keyword,
10045 QualifierLoc.getNestedNameSpecifier(),
10046 &II);
10047
10048 case LookupResult::Found:
10049 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10050 // C++ [class.qual]p2:
10051 // In a lookup in which function names are not ignored and the
10052 // nested-name-specifier nominates a class C, if the name specified
10053 // after the nested-name-specifier, when looked up in C, is the
10054 // injected-class-name of C [...] then the name is instead considered
10055 // to name the constructor of class C.
10056 //
10057 // Unlike in an elaborated-type-specifier, function names are not ignored
10058 // in typename-specifier lookup. However, they are ignored in all the
10059 // contexts where we form a typename type with no keyword (that is, in
10060 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10061 //
10062 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10063 // ignore functions, but that appears to be an oversight.
10064 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10065 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10066 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
10067 FoundRD->isInjectedClassName() &&
10068 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10069 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10070 << &II << 1 << 0 /*'typename' keyword used*/;
10071
10072 // We found a type. Build an ElaboratedType, since the
10073 // typename-specifier was just sugar.
10074 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10075 return Context.getElaboratedType(Keyword,
10076 QualifierLoc.getNestedNameSpecifier(),
10077 Context.getTypeDeclType(Type));
10078 }
10079
10080 // C++ [dcl.type.simple]p2:
10081 // A type-specifier of the form
10082 // typename[opt] nested-name-specifier[opt] template-name
10083 // is a placeholder for a deduced class type [...].
10084 if (getLangOpts().CPlusPlus17) {
10085 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10086 return Context.getElaboratedType(
10087 Keyword, QualifierLoc.getNestedNameSpecifier(),
10088 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10089 QualType(), false));
10090 }
10091 }
10092
10093 DiagID = diag::err_typename_nested_not_type;
10094 Referenced = Result.getFoundDecl();
10095 break;
10096
10097 case LookupResult::FoundOverloaded:
10098 DiagID = diag::err_typename_nested_not_type;
10099 Referenced = *Result.begin();
10100 break;
10101
10102 case LookupResult::Ambiguous:
10103 return QualType();
10104 }
10105
10106 // If we get here, it's because name lookup did not find a
10107 // type. Emit an appropriate diagnostic and return an error.
10108 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10109 IILoc);
10110 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10111 if (Referenced)
10112 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
10113 << Name;
10114 return QualType();
10115}
10116
10117namespace {
10118 // See Sema::RebuildTypeInCurrentInstantiation
10119 class CurrentInstantiationRebuilder
10120 : public TreeTransform<CurrentInstantiationRebuilder> {
10121 SourceLocation Loc;
10122 DeclarationName Entity;
10123
10124 public:
10125 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
10126
10127 CurrentInstantiationRebuilder(Sema &SemaRef,
10128 SourceLocation Loc,
10129 DeclarationName Entity)
10130 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10131 Loc(Loc), Entity(Entity) { }
10132
10133 /// Determine whether the given type \p T has already been
10134 /// transformed.
10135 ///
10136 /// For the purposes of type reconstruction, a type has already been
10137 /// transformed if it is NULL or if it is not dependent.
10138 bool AlreadyTransformed(QualType T) {
10139 return T.isNull() || !T->isDependentType();
10140 }
10141
10142 /// Returns the location of the entity whose type is being
10143 /// rebuilt.
10144 SourceLocation getBaseLocation() { return Loc; }
10145
10146 /// Returns the name of the entity whose type is being rebuilt.
10147 DeclarationName getBaseEntity() { return Entity; }
10148
10149 /// Sets the "base" location and entity when that
10150 /// information is known based on another transformation.
10151 void setBase(SourceLocation Loc, DeclarationName Entity) {
10152 this->Loc = Loc;
10153 this->Entity = Entity;
10154 }
10155
10156 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10157 // Lambdas never need to be transformed.
10158 return E;
10159 }
10160 };
10161} // end anonymous namespace
10162
10163/// Rebuilds a type within the context of the current instantiation.
10164///
10165/// The type \p T is part of the type of an out-of-line member definition of
10166/// a class template (or class template partial specialization) that was parsed
10167/// and constructed before we entered the scope of the class template (or
10168/// partial specialization thereof). This routine will rebuild that type now
10169/// that we have entered the declarator's scope, which may produce different
10170/// canonical types, e.g.,
10171///
10172/// \code
10173/// template<typename T>
10174/// struct X {
10175/// typedef T* pointer;
10176/// pointer data();
10177/// };
10178///
10179/// template<typename T>
10180/// typename X<T>::pointer X<T>::data() { ... }
10181/// \endcode
10182///
10183/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
10184/// since we do not know that we can look into X<T> when we parsed the type.
10185/// This function will rebuild the type, performing the lookup of "pointer"
10186/// in X<T> and returning an ElaboratedType whose canonical type is the same
10187/// as the canonical type of T*, allowing the return types of the out-of-line
10188/// definition and the declaration to match.
10189TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10190 SourceLocation Loc,
10191 DeclarationName Name) {
10192 if (!T || !T->getType()->isDependentType())
10193 return T;
10194
10195 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10196 return Rebuilder.TransformType(T);
10197}
10198
10199ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
10200 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10201 DeclarationName());
10202 return Rebuilder.TransformExpr(E);
10203}
10204
10205bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
10206 if (SS.isInvalid())
10207 return true;
10208
10209 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10210 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10211 DeclarationName());
10212 NestedNameSpecifierLoc Rebuilt
10213 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
10214 if (!Rebuilt)
10215 return true;
10216
10217 SS.Adopt(Rebuilt);
10218 return false;
10219}
10220
10221/// Rebuild the template parameters now that we know we're in a current
10222/// instantiation.
10223bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10224 TemplateParameterList *Params) {
10225 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10226 Decl *Param = Params->getParam(I);
10227
10228 // There is nothing to rebuild in a type parameter.
10229 if (isa<TemplateTypeParmDecl>(Param))
10230 continue;
10231
10232 // Rebuild the template parameter list of a template template parameter.
10233 if (TemplateTemplateParmDecl *TTP
10234 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10235 if (RebuildTemplateParamsInCurrentInstantiation(
10236 TTP->getTemplateParameters()))
10237 return true;
10238
10239 continue;
10240 }
10241
10242 // Rebuild the type of a non-type template parameter.
10243 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
10244 TypeSourceInfo *NewTSI
10245 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10246 NTTP->getLocation(),
10247 NTTP->getDeclName());
10248 if (!NewTSI)
10249 return true;
10250
10251 if (NewTSI->getType()->isUndeducedType()) {
10252 // C++17 [temp.dep.expr]p3:
10253 // An id-expression is type-dependent if it contains
10254 // - an identifier associated by name lookup with a non-type
10255 // template-parameter declared with a type that contains a
10256 // placeholder type (7.1.7.4),
10257 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10258 }
10259
10260 if (NewTSI != NTTP->getTypeSourceInfo()) {
10261 NTTP->setTypeSourceInfo(NewTSI);
10262 NTTP->setType(NewTSI->getType());
10263 }
10264 }
10265
10266 return false;
10267}
10268
10269/// Produces a formatted string that describes the binding of
10270/// template parameters to template arguments.
10271std::string
10272Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10273 const TemplateArgumentList &Args) {
10274 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
10275}
10276
10277std::string
10278Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10279 const TemplateArgument *Args,
10280 unsigned NumArgs) {
10281 SmallString<128> Str;
10282 llvm::raw_svector_ostream Out(Str);
10283
10284 if (!Params || Params->size() == 0 || NumArgs == 0)
10285 return std::string();
10286
10287 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10288 if (I >= NumArgs)
10289 break;
10290
10291 if (I == 0)
10292 Out << "[with ";
10293 else
10294 Out << ", ";
10295
10296 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
10297 Out << Id->getName();
10298 } else {
10299 Out << '$' << I;
10300 }
10301
10302 Out << " = ";
10303 Args[I].print(getPrintingPolicy(), Out);
10304 }
10305
10306 Out << ']';
10307 return Out.str();
10308}
10309
10310void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10311 CachedTokens &Toks) {
10312 if (!FD)
10313 return;
10314
10315 auto LPT = std::make_unique<LateParsedTemplate>();
10316
10317 // Take tokens to avoid allocations
10318 LPT->Toks.swap(Toks);
10319 LPT->D = FnD;
10320 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
10321
10322 FD->setLateTemplateParsed(true);
10323}
10324
10325void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10326 if (!FD)
10327 return;
10328 FD->setLateTemplateParsed(false);
10329}
10330
10331bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10332 DeclContext *DC = CurContext;
10333
10334 while (DC) {
10335 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10336 const FunctionDecl *FD = RD->isLocalClass();
10337 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10338 } else if (DC->isTranslationUnit() || DC->isNamespace())
10339 return false;
10340
10341 DC = DC->getParent();
10342 }
10343 return false;
10344}
10345
10346namespace {
10347/// Walk the path from which a declaration was instantiated, and check
10348/// that every explicit specialization along that path is visible. This enforces
10349/// C++ [temp.expl.spec]/6:
10350///
10351/// If a template, a member template or a member of a class template is
10352/// explicitly specialized then that specialization shall be declared before
10353/// the first use of that specialization that would cause an implicit
10354/// instantiation to take place, in every translation unit in which such a
10355/// use occurs; no diagnostic is required.
10356///
10357/// and also C++ [temp.class.spec]/1:
10358///
10359/// A partial specialization shall be declared before the first use of a
10360/// class template specialization that would make use of the partial
10361/// specialization as the result of an implicit or explicit instantiation
10362/// in every translation unit in which such a use occurs; no diagnostic is
10363/// required.
10364class ExplicitSpecializationVisibilityChecker {
10365 Sema &S;
10366 SourceLocation Loc;
10367 llvm::SmallVector<Module *, 8> Modules;
10368
10369public:
10370 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10371 : S(S), Loc(Loc) {}
10372
10373 void check(NamedDecl *ND) {
10374 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10375 return checkImpl(FD);
10376 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10377 return checkImpl(RD);
10378 if (auto *VD = dyn_cast<VarDecl>(ND))
10379 return checkImpl(VD);
10380 if (auto *ED = dyn_cast<EnumDecl>(ND))
10381 return checkImpl(ED);
10382 }
10383
10384private:
10385 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10386 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10387 : Sema::MissingImportKind::ExplicitSpecialization;
10388 const bool Recover = true;
10389
10390 // If we got a custom set of modules (because only a subset of the
10391 // declarations are interesting), use them, otherwise let
10392 // diagnoseMissingImport intelligently pick some.
10393 if (Modules.empty())
10394 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10395 else
10396 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10397 }
10398
10399 // Check a specific declaration. There are three problematic cases:
10400 //
10401 // 1) The declaration is an explicit specialization of a template
10402 // specialization.
10403 // 2) The declaration is an explicit specialization of a member of an
10404 // templated class.
10405 // 3) The declaration is an instantiation of a template, and that template
10406 // is an explicit specialization of a member of a templated class.
10407 //
10408 // We don't need to go any deeper than that, as the instantiation of the
10409 // surrounding class / etc is not triggered by whatever triggered this
10410 // instantiation, and thus should be checked elsewhere.
10411 template<typename SpecDecl>
10412 void checkImpl(SpecDecl *Spec) {
10413 bool IsHiddenExplicitSpecialization = false;
10414 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10415 IsHiddenExplicitSpecialization =
10416 Spec->getMemberSpecializationInfo()
10417 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
10418 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
10419 } else {
10420 checkInstantiated(Spec);
10421 }
10422
10423 if (IsHiddenExplicitSpecialization)
10424 diagnose(Spec->getMostRecentDecl(), false);
10425 }
10426
10427 void checkInstantiated(FunctionDecl *FD) {
10428 if (auto *TD = FD->getPrimaryTemplate())
10429 checkTemplate(TD);
10430 }
10431
10432 void checkInstantiated(CXXRecordDecl *RD) {
10433 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10434 if (!SD)
10435 return;
10436
10437 auto From = SD->getSpecializedTemplateOrPartial();
10438 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10439 checkTemplate(TD);
10440 else if (auto *TD =
10441 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10442 if (!S.hasVisibleDeclaration(TD))
10443 diagnose(TD, true);
10444 checkTemplate(TD);
10445 }
10446 }
10447
10448 void checkInstantiated(VarDecl *RD) {
10449 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10450 if (!SD)
10451 return;
10452
10453 auto From = SD->getSpecializedTemplateOrPartial();
10454 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10455 checkTemplate(TD);
10456 else if (auto *TD =
10457 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10458 if (!S.hasVisibleDeclaration(TD))
10459 diagnose(TD, true);
10460 checkTemplate(TD);
10461 }
10462 }
10463
10464 void checkInstantiated(EnumDecl *FD) {}
10465
10466 template<typename TemplDecl>
10467 void checkTemplate(TemplDecl *TD) {
10468 if (TD->isMemberSpecialization()) {
10469 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10470 diagnose(TD->getMostRecentDecl(), false);
10471 }
10472 }
10473};
10474} // end anonymous namespace
10475
10476void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10477 if (!getLangOpts().Modules)
10478 return;
10479
10480 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10481}
10482
10483/// Check whether a template partial specialization that we've discovered
10484/// is hidden, and produce suitable diagnostics if so.
10485void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10486 NamedDecl *Spec) {
10487 llvm::SmallVector<Module *, 8> Modules;
10488 if (!hasVisibleDeclaration(Spec, &Modules))
10489 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10490 MissingImportKind::PartialSpecialization,
10491 /*Recover*/true);
10492}

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69} // namespace clang
70
71namespace llvm {
72
73 template <typename T>
74 struct PointerLikeTypeTraits;
75 template<>
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
81 }
82
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 };
85
86 template<>
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
92 }
93
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 };
96
97} // namespace llvm
98
99namespace clang {
100
101class ASTContext;
102template <typename> class CanQual;
103class CXXRecordDecl;
104class DeclContext;
105class EnumDecl;
106class Expr;
107class ExtQualsTypeCommonBase;
108class FunctionDecl;
109class IdentifierInfo;
110class NamedDecl;
111class ObjCInterfaceDecl;
112class ObjCProtocolDecl;
113class ObjCTypeParamDecl;
114struct PrintingPolicy;
115class RecordDecl;
116class Stmt;
117class TagDecl;
118class TemplateArgument;
119class TemplateArgumentListInfo;
120class TemplateArgumentLoc;
121class TemplateTypeParmDecl;
122class TypedefNameDecl;
123class UnresolvedUsingTypenameDecl;
124
125using CanQualType = CanQual<Type>;
126
127// Provide forward declarations for all of the *Type classes.
128#define TYPE(Class, Base) class Class##Type;
129#include "clang/AST/TypeNodes.inc"
130
131/// The collection of all-type qualifiers we support.
132/// Clang supports five independent qualifiers:
133/// * C99: const, volatile, and restrict
134/// * MS: __unaligned
135/// * Embedded C (TR18037): address spaces
136/// * Objective C: the GC attributes (none, weak, or strong)
137class Qualifiers {
138public:
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140 Const = 0x1,
141 Restrict = 0x2,
142 Volatile = 0x4,
143 CVRMask = Const | Volatile | Restrict
144 };
145
146 enum GC {
147 GCNone = 0,
148 Weak,
149 Strong
150 };
151
152 enum ObjCLifetime {
153 /// There is no lifetime qualification on this type.
154 OCL_None,
155
156 /// This object can be modified without requiring retains or
157 /// releases.
158 OCL_ExplicitNone,
159
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
164 /// live.
165 OCL_Strong,
166
167 /// Reading or writing from this object requires a barrier call.
168 OCL_Weak,
169
170 /// Assigning into this object requires a lifetime extension.
171 OCL_Autoreleasing
172 };
173
174 enum {
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
178
179 /// The width of the "fast" qualifier mask.
180 FastWidth = 3,
181
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
184 };
185
186 /// Returns the common set of qualifiers while removing them from
187 /// the given sets.
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191 Qualifiers Q;
192 Q.Mask = L.Mask & R.Mask;
193 L.Mask &= ~Q.Mask;
194 R.Mask &= ~Q.Mask;
195 return Q;
196 }
197
198 Qualifiers Q;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
203
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
208 }
209
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
214 }
215
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
220 }
221 return Q;
222 }
223
224 static Qualifiers fromFastMask(unsigned Mask) {
225 Qualifiers Qs;
226 Qs.addFastQualifiers(Mask);
227 return Qs;
228 }
229
230 static Qualifiers fromCVRMask(unsigned CVR) {
231 Qualifiers Qs;
232 Qs.addCVRQualifiers(CVR);
233 return Qs;
234 }
235
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
237 Qualifiers Qs;
238 Qs.addCVRUQualifiers(CVRU);
239 return Qs;
240 }
241
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
244 Qualifiers Qs;
245 Qs.Mask = opaque;
246 return Qs;
247 }
248
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
251 return Mask;
252 }
253
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
258
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
263
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
268
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 274, __PRETTY_FUNCTION__))
;
275 Mask = (Mask & ~CVRMask) | mask;
276 }
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 278, __PRETTY_FUNCTION__))
;
279 Mask &= ~mask;
280 }
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
283 }
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask |= mask;
287 }
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 289, __PRETTY_FUNCTION__))
;
290 Mask |= mask;
291 }
292
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296 }
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
299
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304 }
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
307 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 307, __PRETTY_FUNCTION__))
;
308 setObjCGCAttr(type);
309 }
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
313 return qs;
314 }
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
318 return qs;
319 }
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
323 return qs;
324 }
325
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 }
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 }
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
335 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 335, __PRETTY_FUNCTION__))
;
336 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 336, __PRETTY_FUNCTION__))
;
337 Mask |= (type << LifetimeShift);
338 }
339
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
344 }
345
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350 }
351
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 }
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
358 }
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 365, __PRETTY_FUNCTION__))
;
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
371 return 0;
372 }
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 374, __PRETTY_FUNCTION__))
;
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
377 }
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 380, __PRETTY_FUNCTION__))
;
381 setAddressSpace(space);
382 }
383
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 389, __PRETTY_FUNCTION__))
;
390 Mask = (Mask & ~FastMask) | mask;
391 }
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 393, __PRETTY_FUNCTION__))
;
394 Mask &= ~mask;
395 }
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
398 }
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask |= mask;
402 }
403
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
410 return Quals;
411 }
412
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
416
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
420 // bit-or it in.
421 if (!(Q.Mask & ~CVRMask))
422 Mask |= Q.Mask;
423 else {
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
431 }
432 }
433
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
439 Mask &= ~Q.Mask;
440 else {
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 removeObjCGCAttr();
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
448 }
449 }
450
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
455 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
;
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
459 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
;
460 Mask |= qs.Mask;
461 }
462
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
466 /// CL1.1 or CL1.2:
467 /// every address space is a superset of itself.
468 /// CL2.0 adds:
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
472 return A == B ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
476 }
477
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482 }
483
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
490 // be changed.
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
499 }
500
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503 ///
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
510 return true;
511
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513 return false;
514
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 return true;
517
518 return hasConst();
519 }
520
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
524
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527
528 explicit operator bool() const { return hasQualifiers(); }
529
530 Qualifiers &operator+=(Qualifiers R) {
531 addQualifiers(R);
532 return *this;
533 }
534
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
538 L += R;
539 return L;
540 }
541
542 Qualifiers &operator-=(Qualifiers R) {
543 removeQualifiers(R);
544 return *this;
545 }
546
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
549 L -= R;
550 return L;
551 }
552
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
555
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
559
560 void Profile(llvm::FoldingSetNodeID &ID) const {
561 ID.AddInteger(Mask);
562 }
563
564private:
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
567 uint32_t Mask = 0;
568
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
578};
579
580/// A std::pair-like structure for storing a qualified type split
581/// into its local qualifiers and its locally-unqualified type.
582struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
585
586 /// The local qualifiers.
587 Qualifiers Quals;
588
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
593
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
597 }
598
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
601 }
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
604 }
605};
606
607/// The kind of type we are substituting Objective-C type arguments into.
608///
609/// The kind of substitution affects the replacement of type parameters when
610/// no concrete type information is provided, e.g., when dealing with an
611/// unspecialized type.
612enum class ObjCSubstitutionContext {
613 /// An ordinary type.
614 Ordinary,
615
616 /// The result type of a method or function.
617 Result,
618
619 /// The parameter type of a method or function.
620 Parameter,
621
622 /// The type of a property.
623 Property,
624
625 /// The superclass of a type.
626 Superclass,
627};
628
629/// A (possibly-)qualified type.
630///
631/// For efficiency, we don't store CV-qualified types as nodes on their
632/// own: instead each reference to a type stores the qualifiers. This
633/// greatly reduces the number of nodes we need to allocate for types (for
634/// example we only need one for 'int', 'const int', 'volatile int',
635/// 'const volatile int', etc).
636///
637/// As an added efficiency bonus, instead of making this a pair, we
638/// just store the two bits we care about in the low bits of the
639/// pointer. To handle the packing/unpacking, we make QualType be a
640/// simple wrapper class that acts like a smart pointer. A third bit
641/// indicates whether there are extended qualifiers present, in which
642/// case the pointer points to a special structure.
643class QualType {
644 friend class QualifierCollector;
645
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
649
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
652 }
653
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
656 }
657
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 659, __PRETTY_FUNCTION__))
;
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663 }
664
665public:
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672
673 /// Retrieves a pointer to the underlying (unqualified) type.
674 ///
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
678
679 const Type *getTypePtrOrNull() const;
680
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
683
684 /// Divides a QualType into its unqualified type and a set of local
685 /// qualifiers.
686 SplitQualType split() const;
687
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689
690 static QualType getFromOpaquePtr(const void *Ptr) {
691 QualType T;
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693 return T;
694 }
695
696 const Type &operator*() const {
697 return *getTypePtr();
698 }
699
700 const Type *operator->() const {
701 return getTypePtr();
702 }
703
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
706
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
710 }
711
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
717 }
718
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
721
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
727 }
728
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
737 }
738
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
741
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747 }
748
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754 /// instance.
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
757 }
758
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
761 /// other sugar.
762 Qualifiers getLocalQualifiers() const;
763
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
766
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
772 }
773
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
777
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
780 }
781
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
784
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
788
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
794
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
797
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
800
801
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
804
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
807
808 // Don't promise in the API that anything besides 'const' can be
809 // easily added.
810
811 /// Add the `const` type qualifier to this QualType.
812 void addConst() {
813 addFastQualifiers(Qualifiers::Const);
814 }
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
817 }
818
819 /// Add the `volatile` type qualifier to this QualType.
820 void addVolatile() {
821 addFastQualifiers(Qualifiers::Volatile);
822 }
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
825 }
826
827 /// Add the `restrict` qualifier to this QualType.
828 void addRestrict() {
829 addFastQualifiers(Qualifiers::Restrict);
830 }
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
833 }
834
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
837 }
838
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
841 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
;
842 Value.setInt(Value.getInt() | TQs);
843 }
844
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
849
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 852, __PRETTY_FUNCTION__))
;
853 Value.setInt(Value.getInt() & ~Mask);
854 }
855
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
859 QualType T = *this;
860 T.addFastQualifiers(TQs);
861 return T;
862 }
863
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868 }
869
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
872 QualType T = *this;
873 T.removeLocalFastQualifiers();
874 return T;
875 }
876
877 QualType getCanonicalType() const;
878
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
886 ///
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
889 ///
890 /// \code
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
894 /// \endcode
895 ///
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898 ///
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
903
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
906 ///
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
909 ///
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
914
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
918
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
922
923 QualType getNonReferenceType() const;
924
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
927 ///
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
934
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940 /// concrete.
941 ///
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
945 }
946
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
949 }
950
951 /// Return the specified type with one level of "sugar" removed from
952 /// the type.
953 ///
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
958 }
959
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
965 return *this;
966 }
967
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
971 }
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
974 }
975 friend bool operator<(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value < RHS.Value;
977 }
978
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
982 }
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
985
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
988
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const;
992
993 static void print(SplitQualType split, raw_ostream &OS,
994 const PrintingPolicy &policy, const Twine &PlaceHolder,
995 unsigned Indentation = 0) {
996 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997 }
998
999 static void print(const Type *ty, Qualifiers qs,
1000 raw_ostream &OS, const PrintingPolicy &policy,
1001 const Twine &PlaceHolder,
1002 unsigned Indentation = 0);
1003
1004 void getAsStringInternal(std::string &Str,
1005 const PrintingPolicy &Policy) const;
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Check if this is or contains a C union that is non-trivial to
1165 /// default-initialize, which is a union that has a member that is non-trivial
1166 /// to default-initialize. If this returns true,
1167 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1168 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1169
1170 /// Check if this is or contains a C union that is non-trivial to destruct,
1171 /// which is a union that has a member that is non-trivial to destruct. If
1172 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1173 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1174
1175 /// Check if this is or contains a C union that is non-trivial to copy, which
1176 /// is a union that has a member that is non-trivial to copy. If this returns
1177 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1178 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1179
1180 /// Determine whether expressions of the given type are forbidden
1181 /// from being lvalues in C.
1182 ///
1183 /// The expression types that are forbidden to be lvalues are:
1184 /// - 'void', but not qualified void
1185 /// - function types
1186 ///
1187 /// The exact rule here is C99 6.3.2.1:
1188 /// An lvalue is an expression with an object type or an incomplete
1189 /// type other than void.
1190 bool isCForbiddenLValueType() const;
1191
1192 /// Substitute type arguments for the Objective-C type parameters used in the
1193 /// subject type.
1194 ///
1195 /// \param ctx ASTContext in which the type exists.
1196 ///
1197 /// \param typeArgs The type arguments that will be substituted for the
1198 /// Objective-C type parameters in the subject type, which are generally
1199 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1200 /// parameters will be replaced with their bounds or id/Class, as appropriate
1201 /// for the context.
1202 ///
1203 /// \param context The context in which the subject type was written.
1204 ///
1205 /// \returns the resulting type.
1206 QualType substObjCTypeArgs(ASTContext &ctx,
1207 ArrayRef<QualType> typeArgs,
1208 ObjCSubstitutionContext context) const;
1209
1210 /// Substitute type arguments from an object type for the Objective-C type
1211 /// parameters used in the subject type.
1212 ///
1213 /// This operation combines the computation of type arguments for
1214 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1215 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1216 /// callers that need to perform a single substitution in isolation.
1217 ///
1218 /// \param objectType The type of the object whose member type we're
1219 /// substituting into. For example, this might be the receiver of a message
1220 /// or the base of a property access.
1221 ///
1222 /// \param dc The declaration context from which the subject type was
1223 /// retrieved, which indicates (for example) which type parameters should
1224 /// be substituted.
1225 ///
1226 /// \param context The context in which the subject type was written.
1227 ///
1228 /// \returns the subject type after replacing all of the Objective-C type
1229 /// parameters with their corresponding arguments.
1230 QualType substObjCMemberType(QualType objectType,
1231 const DeclContext *dc,
1232 ObjCSubstitutionContext context) const;
1233
1234 /// Strip Objective-C "__kindof" types from the given type.
1235 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1236
1237 /// Remove all qualifiers including _Atomic.
1238 QualType getAtomicUnqualifiedType() const;
1239
1240private:
1241 // These methods are implemented in a separate translation unit;
1242 // "static"-ize them to avoid creating temporary QualTypes in the
1243 // caller.
1244 static bool isConstant(QualType T, const ASTContext& Ctx);
1245 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1246 static SplitQualType getSplitDesugaredType(QualType T);
1247 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1248 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1249 const ASTContext &C);
1250 static QualType IgnoreParens(QualType T);
1251 static DestructionKind isDestructedTypeImpl(QualType type);
1252
1253 /// Check if \param RD is or contains a non-trivial C union.
1254 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1255 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1256 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1257};
1258
1259} // namespace clang
1260
1261namespace llvm {
1262
1263/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1264/// to a specific Type class.
1265template<> struct simplify_type< ::clang::QualType> {
1266 using SimpleType = const ::clang::Type *;
1267
1268 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1269 return Val.getTypePtr();
1270 }
1271};
1272
1273// Teach SmallPtrSet that QualType is "basically a pointer".
1274template<>
1275struct PointerLikeTypeTraits<clang::QualType> {
1276 static inline void *getAsVoidPointer(clang::QualType P) {
1277 return P.getAsOpaquePtr();
1278 }
1279
1280 static inline clang::QualType getFromVoidPointer(void *P) {
1281 return clang::QualType::getFromOpaquePtr(P);
1282 }
1283
1284 // Various qualifiers go in low bits.
1285 enum { NumLowBitsAvailable = 0 };
1286};
1287
1288} // namespace llvm
1289
1290namespace clang {
1291
1292/// Base class that is common to both the \c ExtQuals and \c Type
1293/// classes, which allows \c QualType to access the common fields between the
1294/// two.
1295class ExtQualsTypeCommonBase {
1296 friend class ExtQuals;
1297 friend class QualType;
1298 friend class Type;
1299
1300 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1301 /// a self-referential pointer (for \c Type).
1302 ///
1303 /// This pointer allows an efficient mapping from a QualType to its
1304 /// underlying type pointer.
1305 const Type *const BaseType;
1306
1307 /// The canonical type of this type. A QualType.
1308 QualType CanonicalType;
1309
1310 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1311 : BaseType(baseType), CanonicalType(canon) {}
1312};
1313
1314/// We can encode up to four bits in the low bits of a
1315/// type pointer, but there are many more type qualifiers that we want
1316/// to be able to apply to an arbitrary type. Therefore we have this
1317/// struct, intended to be heap-allocated and used by QualType to
1318/// store qualifiers.
1319///
1320/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1321/// in three low bits on the QualType pointer; a fourth bit records whether
1322/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1323/// Objective-C GC attributes) are much more rare.
1324class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1325 // NOTE: changing the fast qualifiers should be straightforward as
1326 // long as you don't make 'const' non-fast.
1327 // 1. Qualifiers:
1328 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1329 // Fast qualifiers must occupy the low-order bits.
1330 // b) Update Qualifiers::FastWidth and FastMask.
1331 // 2. QualType:
1332 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1333 // b) Update remove{Volatile,Restrict}, defined near the end of
1334 // this header.
1335 // 3. ASTContext:
1336 // a) Update get{Volatile,Restrict}Type.
1337
1338 /// The immutable set of qualifiers applied by this node. Always contains
1339 /// extended qualifiers.
1340 Qualifiers Quals;
1341
1342 ExtQuals *this_() { return this; }
1343
1344public:
1345 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1346 : ExtQualsTypeCommonBase(baseType,
1347 canon.isNull() ? QualType(this_(), 0) : canon),
1348 Quals(quals) {
1349 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
1350 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
;
1351 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
1352 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 }
1354
1355 Qualifiers getQualifiers() const { return Quals; }
1356
1357 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1358 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1359
1360 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1361 Qualifiers::ObjCLifetime getObjCLifetime() const {
1362 return Quals.getObjCLifetime();
1363 }
1364
1365 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1366 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1367
1368 const Type *getBaseType() const { return BaseType; }
1369
1370public:
1371 void Profile(llvm::FoldingSetNodeID &ID) const {
1372 Profile(ID, getBaseType(), Quals);
1373 }
1374
1375 static void Profile(llvm::FoldingSetNodeID &ID,
1376 const Type *BaseType,
1377 Qualifiers Quals) {
1378 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 ID.AddPointer(BaseType);
1380 Quals.Profile(ID);
1381 }
1382};
1383
1384/// The kind of C++11 ref-qualifier associated with a function type.
1385/// This determines whether a member function's "this" object can be an
1386/// lvalue, rvalue, or neither.
1387enum RefQualifierKind {
1388 /// No ref-qualifier was provided.
1389 RQ_None = 0,
1390
1391 /// An lvalue ref-qualifier was provided (\c &).
1392 RQ_LValue,
1393
1394 /// An rvalue ref-qualifier was provided (\c &&).
1395 RQ_RValue
1396};
1397
1398/// Which keyword(s) were used to create an AutoType.
1399enum class AutoTypeKeyword {
1400 /// auto
1401 Auto,
1402
1403 /// decltype(auto)
1404 DecltypeAuto,
1405
1406 /// __auto_type (GNU extension)
1407 GNUAutoType
1408};
1409
1410/// The base class of the type hierarchy.
1411///
1412/// A central concept with types is that each type always has a canonical
1413/// type. A canonical type is the type with any typedef names stripped out
1414/// of it or the types it references. For example, consider:
1415///
1416/// typedef int foo;
1417/// typedef foo* bar;
1418/// 'int *' 'foo *' 'bar'
1419///
1420/// There will be a Type object created for 'int'. Since int is canonical, its
1421/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1422/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1423/// there is a PointerType that represents 'int*', which, like 'int', is
1424/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1425/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1426/// is also 'int*'.
1427///
1428/// Non-canonical types are useful for emitting diagnostics, without losing
1429/// information about typedefs being used. Canonical types are useful for type
1430/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1431/// about whether something has a particular form (e.g. is a function type),
1432/// because they implicitly, recursively, strip all typedefs out of a type.
1433///
1434/// Types, once created, are immutable.
1435///
1436class alignas(8) Type : public ExtQualsTypeCommonBase {
1437public:
1438 enum TypeClass {
1439#define TYPE(Class, Base) Class,
1440#define LAST_TYPE(Class) TypeLast = Class
1441#define ABSTRACT_TYPE(Class, Base)
1442#include "clang/AST/TypeNodes.inc"
1443 };
1444
1445private:
1446 /// Bitfields required by the Type class.
1447 class TypeBitfields {
1448 friend class Type;
1449 template <class T> friend class TypePropertyCache;
1450
1451 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1452 unsigned TC : 8;
1453
1454 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1455 unsigned Dependent : 1;
1456
1457 /// Whether this type somehow involves a template parameter, even
1458 /// if the resolution of the type does not depend on a template parameter.
1459 unsigned InstantiationDependent : 1;
1460
1461 /// Whether this type is a variably-modified type (C99 6.7.5).
1462 unsigned VariablyModified : 1;
1463
1464 /// Whether this type contains an unexpanded parameter pack
1465 /// (for C++11 variadic templates).
1466 unsigned ContainsUnexpandedParameterPack : 1;
1467
1468 /// True if the cache (i.e. the bitfields here starting with
1469 /// 'Cache') is valid.
1470 mutable unsigned CacheValid : 1;
1471
1472 /// Linkage of this type.
1473 mutable unsigned CachedLinkage : 3;
1474
1475 /// Whether this type involves and local or unnamed types.
1476 mutable unsigned CachedLocalOrUnnamed : 1;
1477
1478 /// Whether this type comes from an AST file.
1479 mutable unsigned FromAST : 1;
1480
1481 bool isCacheValid() const {
1482 return CacheValid;
1483 }
1484
1485 Linkage getLinkage() const {
1486 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1486, __PRETTY_FUNCTION__))
;
1487 return static_cast<Linkage>(CachedLinkage);
1488 }
1489
1490 bool hasLocalOrUnnamedType() const {
1491 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1491, __PRETTY_FUNCTION__))
;
1492 return CachedLocalOrUnnamed;
1493 }
1494 };
1495 enum { NumTypeBits = 18 };
1496
1497protected:
1498 // These classes allow subclasses to somewhat cleanly pack bitfields
1499 // into Type.
1500
1501 class ArrayTypeBitfields {
1502 friend class ArrayType;
1503
1504 unsigned : NumTypeBits;
1505
1506 /// CVR qualifiers from declarations like
1507 /// 'int X[static restrict 4]'. For function parameters only.
1508 unsigned IndexTypeQuals : 3;
1509
1510 /// Storage class qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 /// Actually an ArrayType::ArraySizeModifier.
1513 unsigned SizeModifier : 3;
1514 };
1515
1516 class BuiltinTypeBitfields {
1517 friend class BuiltinType;
1518
1519 unsigned : NumTypeBits;
1520
1521 /// The kind (BuiltinType::Kind) of builtin type this is.
1522 unsigned Kind : 8;
1523 };
1524
1525 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1526 /// Only common bits are stored here. Additional uncommon bits are stored
1527 /// in a trailing object after FunctionProtoType.
1528 class FunctionTypeBitfields {
1529 friend class FunctionProtoType;
1530 friend class FunctionType;
1531
1532 unsigned : NumTypeBits;
1533
1534 /// Extra information which affects how the function is called, like
1535 /// regparm and the calling convention.
1536 unsigned ExtInfo : 12;
1537
1538 /// The ref-qualifier associated with a \c FunctionProtoType.
1539 ///
1540 /// This is a value of type \c RefQualifierKind.
1541 unsigned RefQualifier : 2;
1542
1543 /// Used only by FunctionProtoType, put here to pack with the
1544 /// other bitfields.
1545 /// The qualifiers are part of FunctionProtoType because...
1546 ///
1547 /// C++ 8.3.5p4: The return type, the parameter type list and the
1548 /// cv-qualifier-seq, [...], are part of the function type.
1549 unsigned FastTypeQuals : Qualifiers::FastWidth;
1550 /// Whether this function has extended Qualifiers.
1551 unsigned HasExtQuals : 1;
1552
1553 /// The number of parameters this function has, not counting '...'.
1554 /// According to [implimits] 8 bits should be enough here but this is
1555 /// somewhat easy to exceed with metaprogramming and so we would like to
1556 /// keep NumParams as wide as reasonably possible.
1557 unsigned NumParams : 16;
1558
1559 /// The type of exception specification this function has.
1560 unsigned ExceptionSpecType : 4;
1561
1562 /// Whether this function has extended parameter information.
1563 unsigned HasExtParameterInfos : 1;
1564
1565 /// Whether the function is variadic.
1566 unsigned Variadic : 1;
1567
1568 /// Whether this function has a trailing return type.
1569 unsigned HasTrailingReturn : 1;
1570 };
1571
1572 class ObjCObjectTypeBitfields {
1573 friend class ObjCObjectType;
1574
1575 unsigned : NumTypeBits;
1576
1577 /// The number of type arguments stored directly on this object type.
1578 unsigned NumTypeArgs : 7;
1579
1580 /// The number of protocols stored directly on this object type.
1581 unsigned NumProtocols : 6;
1582
1583 /// Whether this is a "kindof" type.
1584 unsigned IsKindOf : 1;
1585 };
1586
1587 class ReferenceTypeBitfields {
1588 friend class ReferenceType;
1589
1590 unsigned : NumTypeBits;
1591
1592 /// True if the type was originally spelled with an lvalue sigil.
1593 /// This is never true of rvalue references but can also be false
1594 /// on lvalue references because of C++0x [dcl.typedef]p9,
1595 /// as follows:
1596 ///
1597 /// typedef int &ref; // lvalue, spelled lvalue
1598 /// typedef int &&rvref; // rvalue
1599 /// ref &a; // lvalue, inner ref, spelled lvalue
1600 /// ref &&a; // lvalue, inner ref
1601 /// rvref &a; // lvalue, inner ref, spelled lvalue
1602 /// rvref &&a; // rvalue, inner ref
1603 unsigned SpelledAsLValue : 1;
1604
1605 /// True if the inner type is a reference type. This only happens
1606 /// in non-canonical forms.
1607 unsigned InnerRef : 1;
1608 };
1609
1610 class TypeWithKeywordBitfields {
1611 friend class TypeWithKeyword;
1612
1613 unsigned : NumTypeBits;
1614
1615 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1616 unsigned Keyword : 8;
1617 };
1618
1619 enum { NumTypeWithKeywordBits = 8 };
1620
1621 class ElaboratedTypeBitfields {
1622 friend class ElaboratedType;
1623
1624 unsigned : NumTypeBits;
1625 unsigned : NumTypeWithKeywordBits;
1626
1627 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1628 unsigned HasOwnedTagDecl : 1;
1629 };
1630
1631 class VectorTypeBitfields {
1632 friend class VectorType;
1633 friend class DependentVectorType;
1634
1635 unsigned : NumTypeBits;
1636
1637 /// The kind of vector, either a generic vector type or some
1638 /// target-specific vector type such as for AltiVec or Neon.
1639 unsigned VecKind : 3;
1640
1641 /// The number of elements in the vector.
1642 unsigned NumElements : 29 - NumTypeBits;
1643
1644 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1645 };
1646
1647 class AttributedTypeBitfields {
1648 friend class AttributedType;
1649
1650 unsigned : NumTypeBits;
1651
1652 /// An AttributedType::Kind
1653 unsigned AttrKind : 32 - NumTypeBits;
1654 };
1655
1656 class AutoTypeBitfields {
1657 friend class AutoType;
1658
1659 unsigned : NumTypeBits;
1660
1661 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1662 /// or '__auto_type'? AutoTypeKeyword value.
1663 unsigned Keyword : 2;
1664 };
1665
1666 class SubstTemplateTypeParmPackTypeBitfields {
1667 friend class SubstTemplateTypeParmPackType;
1668
1669 unsigned : NumTypeBits;
1670
1671 /// The number of template arguments in \c Arguments, which is
1672 /// expected to be able to hold at least 1024 according to [implimits].
1673 /// However as this limit is somewhat easy to hit with template
1674 /// metaprogramming we'd prefer to keep it as large as possible.
1675 /// At the moment it has been left as a non-bitfield since this type
1676 /// safely fits in 64 bits as an unsigned, so there is no reason to
1677 /// introduce the performance impact of a bitfield.
1678 unsigned NumArgs;
1679 };
1680
1681 class TemplateSpecializationTypeBitfields {
1682 friend class TemplateSpecializationType;
1683
1684 unsigned : NumTypeBits;
1685
1686 /// Whether this template specialization type is a substituted type alias.
1687 unsigned TypeAlias : 1;
1688
1689 /// The number of template arguments named in this class template
1690 /// specialization, which is expected to be able to hold at least 1024
1691 /// according to [implimits]. However, as this limit is somewhat easy to
1692 /// hit with template metaprogramming we'd prefer to keep it as large
1693 /// as possible. At the moment it has been left as a non-bitfield since
1694 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1695 /// to introduce the performance impact of a bitfield.
1696 unsigned NumArgs;
1697 };
1698
1699 class DependentTemplateSpecializationTypeBitfields {
1700 friend class DependentTemplateSpecializationType;
1701
1702 unsigned : NumTypeBits;
1703 unsigned : NumTypeWithKeywordBits;
1704
1705 /// The number of template arguments named in this class template
1706 /// specialization, which is expected to be able to hold at least 1024
1707 /// according to [implimits]. However, as this limit is somewhat easy to
1708 /// hit with template metaprogramming we'd prefer to keep it as large
1709 /// as possible. At the moment it has been left as a non-bitfield since
1710 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1711 /// to introduce the performance impact of a bitfield.
1712 unsigned NumArgs;
1713 };
1714
1715 class PackExpansionTypeBitfields {
1716 friend class PackExpansionType;
1717
1718 unsigned : NumTypeBits;
1719
1720 /// The number of expansions that this pack expansion will
1721 /// generate when substituted (+1), which is expected to be able to
1722 /// hold at least 1024 according to [implimits]. However, as this limit
1723 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1724 /// keep it as large as possible. At the moment it has been left as a
1725 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1726 /// there is no reason to introduce the performance impact of a bitfield.
1727 ///
1728 /// This field will only have a non-zero value when some of the parameter
1729 /// packs that occur within the pattern have been substituted but others
1730 /// have not.
1731 unsigned NumExpansions;
1732 };
1733
1734 union {
1735 TypeBitfields TypeBits;
1736 ArrayTypeBitfields ArrayTypeBits;
1737 AttributedTypeBitfields AttributedTypeBits;
1738 AutoTypeBitfields AutoTypeBits;
1739 BuiltinTypeBitfields BuiltinTypeBits;
1740 FunctionTypeBitfields FunctionTypeBits;
1741 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1742 ReferenceTypeBitfields ReferenceTypeBits;
1743 TypeWithKeywordBitfields TypeWithKeywordBits;
1744 ElaboratedTypeBitfields ElaboratedTypeBits;
1745 VectorTypeBitfields VectorTypeBits;
1746 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1747 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1748 DependentTemplateSpecializationTypeBitfields
1749 DependentTemplateSpecializationTypeBits;
1750 PackExpansionTypeBitfields PackExpansionTypeBits;
1751
1752 static_assert(sizeof(TypeBitfields) <= 8,
1753 "TypeBitfields is larger than 8 bytes!");
1754 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1755 "ArrayTypeBitfields is larger than 8 bytes!");
1756 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1757 "AttributedTypeBitfields is larger than 8 bytes!");
1758 static_assert(sizeof(AutoTypeBitfields) <= 8,
1759 "AutoTypeBitfields is larger than 8 bytes!");
1760 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1761 "BuiltinTypeBitfields is larger than 8 bytes!");
1762 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1763 "FunctionTypeBitfields is larger than 8 bytes!");
1764 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1765 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1767 "ReferenceTypeBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1769 "TypeWithKeywordBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1771 "ElaboratedTypeBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(VectorTypeBitfields) <= 8,
1773 "VectorTypeBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1775 "SubstTemplateTypeParmPackTypeBitfields is larger"
1776 " than 8 bytes!");
1777 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1778 "TemplateSpecializationTypeBitfields is larger"
1779 " than 8 bytes!");
1780 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1781 "DependentTemplateSpecializationTypeBitfields is larger"
1782 " than 8 bytes!");
1783 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1784 "PackExpansionTypeBitfields is larger than 8 bytes");
1785 };
1786
1787private:
1788 template <class T> friend class TypePropertyCache;
1789
1790 /// Set whether this type comes from an AST file.
1791 void setFromAST(bool V = true) const {
1792 TypeBits.FromAST = V;
1793 }
1794
1795protected:
1796 friend class ASTContext;
1797
1798 Type(TypeClass tc, QualType canon, bool Dependent,
1799 bool InstantiationDependent, bool VariablyModified,
1800 bool ContainsUnexpandedParameterPack)
1801 : ExtQualsTypeCommonBase(this,
1802 canon.isNull() ? QualType(this_(), 0) : canon) {
1803 TypeBits.TC = tc;
1804 TypeBits.Dependent = Dependent;
1805 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1806 TypeBits.VariablyModified = VariablyModified;
1807 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1808 TypeBits.CacheValid = false;
1809 TypeBits.CachedLocalOrUnnamed = false;
1810 TypeBits.CachedLinkage = NoLinkage;
1811 TypeBits.FromAST = false;
1812 }
1813
1814 // silence VC++ warning C4355: 'this' : used in base member initializer list
1815 Type *this_() { return this; }
1816
1817 void setDependent(bool D = true) {
1818 TypeBits.Dependent = D;
1819 if (D)
1820 TypeBits.InstantiationDependent = true;
1821 }
1822
1823 void setInstantiationDependent(bool D = true) {
1824 TypeBits.InstantiationDependent = D; }
1825
1826 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1827
1828 void setContainsUnexpandedParameterPack(bool PP = true) {
1829 TypeBits.ContainsUnexpandedParameterPack = PP;
1830 }
1831
1832public:
1833 friend class ASTReader;
1834 friend class ASTWriter;
1835
1836 Type(const Type &) = delete;
1837 Type(Type &&) = delete;
1838 Type &operator=(const Type &) = delete;
1839 Type &operator=(Type &&) = delete;
1840
1841 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1842
1843 /// Whether this type comes from an AST file.
1844 bool isFromAST() const { return TypeBits.FromAST; }
1845
1846 /// Whether this type is or contains an unexpanded parameter
1847 /// pack, used to support C++0x variadic templates.
1848 ///
1849 /// A type that contains a parameter pack shall be expanded by the
1850 /// ellipsis operator at some point. For example, the typedef in the
1851 /// following example contains an unexpanded parameter pack 'T':
1852 ///
1853 /// \code
1854 /// template<typename ...T>
1855 /// struct X {
1856 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1857 /// };
1858 /// \endcode
1859 ///
1860 /// Note that this routine does not specify which
1861 bool containsUnexpandedParameterPack() const {
1862 return TypeBits.ContainsUnexpandedParameterPack;
1863 }
1864
1865 /// Determines if this type would be canonical if it had no further
1866 /// qualification.
1867 bool isCanonicalUnqualified() const {
1868 return CanonicalType == QualType(this, 0);
1869 }
1870
1871 /// Pull a single level of sugar off of this locally-unqualified type.
1872 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1873 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1874 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1875
1876 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1877 /// object types, function types, and incomplete types.
1878
1879 /// Return true if this is an incomplete type.
1880 /// A type that can describe objects, but which lacks information needed to
1881 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1882 /// routine will need to determine if the size is actually required.
1883 ///
1884 /// Def If non-null, and the type refers to some kind of declaration
1885 /// that can be completed (such as a C struct, C++ class, or Objective-C
1886 /// class), will be set to the declaration.
1887 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1888
1889 /// Return true if this is an incomplete or object
1890 /// type, in other words, not a function type.
1891 bool isIncompleteOrObjectType() const {
1892 return !isFunctionType();
1893 }
1894
1895 /// Determine whether this type is an object type.
1896 bool isObjectType() const {
1897 // C++ [basic.types]p8:
1898 // An object type is a (possibly cv-qualified) type that is not a
1899 // function type, not a reference type, and not a void type.
1900 return !isReferenceType() && !isFunctionType() && !isVoidType();
1901 }
1902
1903 /// Return true if this is a literal type
1904 /// (C++11 [basic.types]p10)
1905 bool isLiteralType(const ASTContext &Ctx) const;
1906
1907 /// Test if this type is a standard-layout type.
1908 /// (C++0x [basic.type]p9)
1909 bool isStandardLayoutType() const;
1910
1911 /// Helper methods to distinguish type categories. All type predicates
1912 /// operate on the canonical type, ignoring typedefs and qualifiers.
1913
1914 /// Returns true if the type is a builtin type.
1915 bool isBuiltinType() const;
1916
1917 /// Test for a particular builtin type.
1918 bool isSpecificBuiltinType(unsigned K) const;
1919
1920 /// Test for a type which does not represent an actual type-system type but
1921 /// is instead used as a placeholder for various convenient purposes within
1922 /// Clang. All such types are BuiltinTypes.
1923 bool isPlaceholderType() const;
1924 const BuiltinType *getAsPlaceholderType() const;
1925
1926 /// Test for a specific placeholder type.
1927 bool isSpecificPlaceholderType(unsigned K) const;
1928
1929 /// Test for a placeholder type other than Overload; see
1930 /// BuiltinType::isNonOverloadPlaceholderType.
1931 bool isNonOverloadPlaceholderType() const;
1932
1933 /// isIntegerType() does *not* include complex integers (a GCC extension).
1934 /// isComplexIntegerType() can be used to test for complex integers.
1935 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1936 bool isEnumeralType() const;
1937
1938 /// Determine whether this type is a scoped enumeration type.
1939 bool isScopedEnumeralType() const;
1940 bool isBooleanType() const;
1941 bool isCharType() const;
1942 bool isWideCharType() const;
1943 bool isChar8Type() const;
1944 bool isChar16Type() const;
1945 bool isChar32Type() const;
1946 bool isAnyCharacterType() const;
1947 bool isIntegralType(const ASTContext &Ctx) const;
1948
1949 /// Determine whether this type is an integral or enumeration type.
1950 bool isIntegralOrEnumerationType() const;
1951
1952 /// Determine whether this type is an integral or unscoped enumeration type.
1953 bool isIntegralOrUnscopedEnumerationType() const;
1954
1955 /// Floating point categories.
1956 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1957 /// isComplexType() does *not* include complex integers (a GCC extension).
1958 /// isComplexIntegerType() can be used to test for complex integers.
1959 bool isComplexType() const; // C99 6.2.5p11 (complex)
1960 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1961 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1962 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1963 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1964 bool isFloat128Type() const;
1965 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1966 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1967 bool isVoidType() const; // C99 6.2.5p19
1968 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1969 bool isAggregateType() const;
1970 bool isFundamentalType() const;
1971 bool isCompoundType() const;
1972
1973 // Type Predicates: Check to see if this type is structurally the specified
1974 // type, ignoring typedefs and qualifiers.
1975 bool isFunctionType() const;
1976 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1977 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1978 bool isPointerType() const;
1979 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1980 bool isBlockPointerType() const;
1981 bool isVoidPointerType() const;
1982 bool isReferenceType() const;
1983 bool isLValueReferenceType() const;
1984 bool isRValueReferenceType() const;
1985 bool isFunctionPointerType() const;
1986 bool isFunctionReferenceType() const;
1987 bool isMemberPointerType() const;
1988 bool isMemberFunctionPointerType() const;
1989 bool isMemberDataPointerType() const;
1990 bool isArrayType() const;
1991 bool isConstantArrayType() const;
1992 bool isIncompleteArrayType() const;
1993 bool isVariableArrayType() const;
1994 bool isDependentSizedArrayType() const;
1995 bool isRecordType() const;
1996 bool isClassType() const;
1997 bool isStructureType() const;
1998 bool isObjCBoxableRecordType() const;
1999 bool isInterfaceType() const;
2000 bool isStructureOrClassType() const;
2001 bool isUnionType() const;
2002 bool isComplexIntegerType() const; // GCC _Complex integer type.
2003 bool isVectorType() const; // GCC vector type.
2004 bool isExtVectorType() const; // Extended vector type.
2005 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2006 bool isObjCObjectPointerType() const; // pointer to ObjC object
2007 bool isObjCRetainableType() const; // ObjC object or block pointer
2008 bool isObjCLifetimeType() const; // (array of)* retainable type
2009 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2010 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2011 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2012 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2013 // for the common case.
2014 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2015 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2016 bool isObjCQualifiedIdType() const; // id<foo>
2017 bool isObjCQualifiedClassType() const; // Class<foo>
2018 bool isObjCObjectOrInterfaceType() const;
2019 bool isObjCIdType() const; // id
2020 bool isDecltypeType() const;
2021 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2022 /// qualifier?
2023 ///
2024 /// This approximates the answer to the following question: if this
2025 /// translation unit were compiled in ARC, would this type be qualified
2026 /// with __unsafe_unretained?
2027 bool isObjCInertUnsafeUnretainedType() const {
2028 return hasAttr(attr::ObjCInertUnsafeUnretained);
2029 }
2030
2031 /// Whether the type is Objective-C 'id' or a __kindof type of an
2032 /// object type, e.g., __kindof NSView * or __kindof id
2033 /// <NSCopying>.
2034 ///
2035 /// \param bound Will be set to the bound on non-id subtype types,
2036 /// which will be (possibly specialized) Objective-C class type, or
2037 /// null for 'id.
2038 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2039 const ObjCObjectType *&bound) const;
2040
2041 bool isObjCClassType() const; // Class
2042
2043 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2044 /// Class type, e.g., __kindof Class <NSCopying>.
2045 ///
2046 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2047 /// here because Objective-C's type system cannot express "a class
2048 /// object for a subclass of NSFoo".
2049 bool isObjCClassOrClassKindOfType() const;
2050
2051 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2052 bool isObjCSelType() const; // Class
2053 bool isObjCBuiltinType() const; // 'id' or 'Class'
2054 bool isObjCARCBridgableType() const;
2055 bool isCARCBridgableType() const;
2056 bool isTemplateTypeParmType() const; // C++ template type parameter
2057 bool isNullPtrType() const; // C++11 std::nullptr_t
2058 bool isNothrowT() const; // C++ std::nothrow_t
2059 bool isAlignValT() const; // C++17 std::align_val_t
2060 bool isStdByteType() const; // C++17 std::byte
2061 bool isAtomicType() const; // C11 _Atomic()
2062
2063#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2064 bool is##Id##Type() const;
2065#include "clang/Basic/OpenCLImageTypes.def"
2066
2067 bool isImageType() const; // Any OpenCL image type
2068
2069 bool isSamplerT() const; // OpenCL sampler_t
2070 bool isEventT() const; // OpenCL event_t
2071 bool isClkEventT() const; // OpenCL clk_event_t
2072 bool isQueueT() const; // OpenCL queue_t
2073 bool isReserveIDT() const; // OpenCL reserve_id_t
2074
2075#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2076 bool is##Id##Type() const;
2077#include "clang/Basic/OpenCLExtensionTypes.def"
2078 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2079 bool isOCLIntelSubgroupAVCType() const;
2080 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2081
2082 bool isPipeType() const; // OpenCL pipe type
2083 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2084
2085 /// Determines if this type, which must satisfy
2086 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2087 /// than implicitly __strong.
2088 bool isObjCARCImplicitlyUnretainedType() const;
2089
2090 /// Return the implicit lifetime for this type, which must not be dependent.
2091 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2092
2093 enum ScalarTypeKind {
2094 STK_CPointer,
2095 STK_BlockPointer,
2096 STK_ObjCObjectPointer,
2097 STK_MemberPointer,
2098 STK_Bool,
2099 STK_Integral,
2100 STK_Floating,
2101 STK_IntegralComplex,
2102 STK_FloatingComplex,
2103 STK_FixedPoint
2104 };
2105
2106 /// Given that this is a scalar type, classify it.
2107 ScalarTypeKind getScalarTypeKind() const;
2108
2109 /// Whether this type is a dependent type, meaning that its definition
2110 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2111 bool isDependentType() const { return TypeBits.Dependent; }
2112
2113 /// Determine whether this type is an instantiation-dependent type,
2114 /// meaning that the type involves a template parameter (even if the
2115 /// definition does not actually depend on the type substituted for that
2116 /// template parameter).
2117 bool isInstantiationDependentType() const {
2118 return TypeBits.InstantiationDependent;
2119 }
2120
2121 /// Determine whether this type is an undeduced type, meaning that
2122 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2123 /// deduced.
2124 bool isUndeducedType() const;
2125
2126 /// Whether this type is a variably-modified type (C99 6.7.5).
2127 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2128
2129 /// Whether this type involves a variable-length array type
2130 /// with a definite size.
2131 bool hasSizedVLAType() const;
2132
2133 /// Whether this type is or contains a local or unnamed type.
2134 bool hasUnnamedOrLocalType() const;
2135
2136 bool isOverloadableType() const;
2137
2138 /// Determine wither this type is a C++ elaborated-type-specifier.
2139 bool isElaboratedTypeSpecifier() const;
2140
2141 bool canDecayToPointerType() const;
2142
2143 /// Whether this type is represented natively as a pointer. This includes
2144 /// pointers, references, block pointers, and Objective-C interface,
2145 /// qualified id, and qualified interface types, as well as nullptr_t.
2146 bool hasPointerRepresentation() const;
2147
2148 /// Whether this type can represent an objective pointer type for the
2149 /// purpose of GC'ability
2150 bool hasObjCPointerRepresentation() const;
2151
2152 /// Determine whether this type has an integer representation
2153 /// of some sort, e.g., it is an integer type or a vector.
2154 bool hasIntegerRepresentation() const;
2155
2156 /// Determine whether this type has an signed integer representation
2157 /// of some sort, e.g., it is an signed integer type or a vector.
2158 bool hasSignedIntegerRepresentation() const;
2159
2160 /// Determine whether this type has an unsigned integer representation
2161 /// of some sort, e.g., it is an unsigned integer type or a vector.
2162 bool hasUnsignedIntegerRepresentation() const;
2163
2164 /// Determine whether this type has a floating-point representation
2165 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2166 bool hasFloatingRepresentation() const;
2167
2168 // Type Checking Functions: Check to see if this type is structurally the
2169 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2170 // the best type we can.
2171 const RecordType *getAsStructureType() const;
2172 /// NOTE: getAs*ArrayType are methods on ASTContext.
2173 const RecordType *getAsUnionType() const;
2174 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2175 const ObjCObjectType *getAsObjCInterfaceType() const;
2176
2177 // The following is a convenience method that returns an ObjCObjectPointerType
2178 // for object declared using an interface.
2179 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2180 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2181 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2182 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2183
2184 /// Retrieves the CXXRecordDecl that this type refers to, either
2185 /// because the type is a RecordType or because it is the injected-class-name
2186 /// type of a class template or class template partial specialization.
2187 CXXRecordDecl *getAsCXXRecordDecl() const;
2188
2189 /// Retrieves the RecordDecl this type refers to.
2190 RecordDecl *getAsRecordDecl() const;
2191
2192 /// Retrieves the TagDecl that this type refers to, either
2193 /// because the type is a TagType or because it is the injected-class-name
2194 /// type of a class template or class template partial specialization.
2195 TagDecl *getAsTagDecl() const;
2196
2197 /// If this is a pointer or reference to a RecordType, return the
2198 /// CXXRecordDecl that the type refers to.
2199 ///
2200 /// If this is not a pointer or reference, or the type being pointed to does
2201 /// not refer to a CXXRecordDecl, returns NULL.
2202 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2203
2204 /// Get the DeducedType whose type will be deduced for a variable with
2205 /// an initializer of this type. This looks through declarators like pointer
2206 /// types, but not through decltype or typedefs.
2207 DeducedType *getContainedDeducedType() const;
2208
2209 /// Get the AutoType whose type will be deduced for a variable with
2210 /// an initializer of this type. This looks through declarators like pointer
2211 /// types, but not through decltype or typedefs.
2212 AutoType *getContainedAutoType() const {
2213 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2214 }
2215
2216 /// Determine whether this type was written with a leading 'auto'
2217 /// corresponding to a trailing return type (possibly for a nested
2218 /// function type within a pointer to function type or similar).
2219 bool hasAutoForTrailingReturnType() const;
2220
2221 /// Member-template getAs<specific type>'. Look through sugar for
2222 /// an instance of \<specific type>. This scheme will eventually
2223 /// replace the specific getAsXXXX methods above.
2224 ///
2225 /// There are some specializations of this member template listed
2226 /// immediately following this class.
2227 template <typename T> const T *getAs() const;
2228
2229 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2230 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2231 /// This is used when you need to walk over sugar nodes that represent some
2232 /// kind of type adjustment from a type that was written as a \<specific type>
2233 /// to another type that is still canonically a \<specific type>.
2234 template <typename T> const T *getAsAdjusted() const;
2235
2236 /// A variant of getAs<> for array types which silently discards
2237 /// qualifiers from the outermost type.
2238 const ArrayType *getAsArrayTypeUnsafe() const;
2239
2240 /// Member-template castAs<specific type>. Look through sugar for
2241 /// the underlying instance of \<specific type>.
2242 ///
2243 /// This method has the same relationship to getAs<T> as cast<T> has
2244 /// to dyn_cast<T>; which is to say, the underlying type *must*
2245 /// have the intended type, and this method will never return null.
2246 template <typename T> const T *castAs() const;
2247
2248 /// A variant of castAs<> for array type which silently discards
2249 /// qualifiers from the outermost type.
2250 const ArrayType *castAsArrayTypeUnsafe() const;
2251
2252 /// Determine whether this type had the specified attribute applied to it
2253 /// (looking through top-level type sugar).
2254 bool hasAttr(attr::Kind AK) const;
2255
2256 /// Get the base element type of this type, potentially discarding type
2257 /// qualifiers. This should never be used when type qualifiers
2258 /// are meaningful.
2259 const Type *getBaseElementTypeUnsafe() const;
2260
2261 /// If this is an array type, return the element type of the array,
2262 /// potentially with type qualifiers missing.
2263 /// This should never be used when type qualifiers are meaningful.
2264 const Type *getArrayElementTypeNoTypeQual() const;
2265
2266 /// If this is a pointer type, return the pointee type.
2267 /// If this is an array type, return the array element type.
2268 /// This should never be used when type qualifiers are meaningful.
2269 const Type *getPointeeOrArrayElementType() const;
2270
2271 /// If this is a pointer, ObjC object pointer, or block
2272 /// pointer, this returns the respective pointee.
2273 QualType getPointeeType() const;
2274
2275 /// Return the specified type with any "sugar" removed from the type,
2276 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2277 const Type *getUnqualifiedDesugaredType() const;
2278
2279 /// More type predicates useful for type checking/promotion
2280 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2281
2282 /// Return true if this is an integer type that is
2283 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2284 /// or an enum decl which has a signed representation.
2285 bool isSignedIntegerType() const;
2286
2287 /// Return true if this is an integer type that is
2288 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2289 /// or an enum decl which has an unsigned representation.
2290 bool isUnsignedIntegerType() const;
2291
2292 /// Determines whether this is an integer type that is signed or an
2293 /// enumeration types whose underlying type is a signed integer type.
2294 bool isSignedIntegerOrEnumerationType() const;
2295
2296 /// Determines whether this is an integer type that is unsigned or an
2297 /// enumeration types whose underlying type is a unsigned integer type.
2298 bool isUnsignedIntegerOrEnumerationType() const;
2299
2300 /// Return true if this is a fixed point type according to
2301 /// ISO/IEC JTC1 SC22 WG14 N1169.
2302 bool isFixedPointType() const;
2303
2304 /// Return true if this is a fixed point or integer type.
2305 bool isFixedPointOrIntegerType() const;
2306
2307 /// Return true if this is a saturated fixed point type according to
2308 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2309 bool isSaturatedFixedPointType() const;
2310
2311 /// Return true if this is a saturated fixed point type according to
2312 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2313 bool isUnsaturatedFixedPointType() const;
2314
2315 /// Return true if this is a fixed point type that is signed according
2316 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2317 bool isSignedFixedPointType() const;
2318
2319 /// Return true if this is a fixed point type that is unsigned according
2320 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2321 bool isUnsignedFixedPointType() const;
2322
2323 /// Return true if this is not a variable sized type,
2324 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2325 /// incomplete types.
2326 bool isConstantSizeType() const;
2327
2328 /// Returns true if this type can be represented by some
2329 /// set of type specifiers.
2330 bool isSpecifierType() const;
2331
2332 /// Determine the linkage of this type.
2333 Linkage getLinkage() const;
2334
2335 /// Determine the visibility of this type.
2336 Visibility getVisibility() const {
2337 return getLinkageAndVisibility().getVisibility();
2338 }
2339
2340 /// Return true if the visibility was explicitly set is the code.
2341 bool isVisibilityExplicit() const {
2342 return getLinkageAndVisibility().isVisibilityExplicit();
2343 }
2344
2345 /// Determine the linkage and visibility of this type.
2346 LinkageInfo getLinkageAndVisibility() const;
2347
2348 /// True if the computed linkage is valid. Used for consistency
2349 /// checking. Should always return true.
2350 bool isLinkageValid() const;
2351
2352 /// Determine the nullability of the given type.
2353 ///
2354 /// Note that nullability is only captured as sugar within the type
2355 /// system, not as part of the canonical type, so nullability will
2356 /// be lost by canonicalization and desugaring.
2357 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2358
2359 /// Determine whether the given type can have a nullability
2360 /// specifier applied to it, i.e., if it is any kind of pointer type.
2361 ///
2362 /// \param ResultIfUnknown The value to return if we don't yet know whether
2363 /// this type can have nullability because it is dependent.
2364 bool canHaveNullability(bool ResultIfUnknown = true) const;
2365
2366 /// Retrieve the set of substitutions required when accessing a member
2367 /// of the Objective-C receiver type that is declared in the given context.
2368 ///
2369 /// \c *this is the type of the object we're operating on, e.g., the
2370 /// receiver for a message send or the base of a property access, and is
2371 /// expected to be of some object or object pointer type.
2372 ///
2373 /// \param dc The declaration context for which we are building up a
2374 /// substitution mapping, which should be an Objective-C class, extension,
2375 /// category, or method within.
2376 ///
2377 /// \returns an array of type arguments that can be substituted for
2378 /// the type parameters of the given declaration context in any type described
2379 /// within that context, or an empty optional to indicate that no
2380 /// substitution is required.
2381 Optional<ArrayRef<QualType>>
2382 getObjCSubstitutions(const DeclContext *dc) const;
2383
2384 /// Determines if this is an ObjC interface type that may accept type
2385 /// parameters.
2386 bool acceptsObjCTypeParams() const;
2387
2388 const char *getTypeClassName() const;
2389
2390 QualType getCanonicalTypeInternal() const {
2391 return CanonicalType;
2392 }
2393
2394 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2395 void dump() const;
2396 void dump(llvm::raw_ostream &OS) const;
2397};
2398
2399/// This will check for a TypedefType by removing any existing sugar
2400/// until it reaches a TypedefType or a non-sugared type.
2401template <> const TypedefType *Type::getAs() const;
2402
2403/// This will check for a TemplateSpecializationType by removing any
2404/// existing sugar until it reaches a TemplateSpecializationType or a
2405/// non-sugared type.
2406template <> const TemplateSpecializationType *Type::getAs() const;
2407
2408/// This will check for an AttributedType by removing any existing sugar
2409/// until it reaches an AttributedType or a non-sugared type.
2410template <> const AttributedType *Type::getAs() const;
2411
2412// We can do canonical leaf types faster, because we don't have to
2413// worry about preserving child type decoration.
2414#define TYPE(Class, Base)
2415#define LEAF_TYPE(Class) \
2416template <> inline const Class##Type *Type::getAs() const { \
2417 return dyn_cast<Class##Type>(CanonicalType); \
2418} \
2419template <> inline const Class##Type *Type::castAs() const { \
2420 return cast<Class##Type>(CanonicalType); \
2421}
2422#include "clang/AST/TypeNodes.inc"
2423
2424/// This class is used for builtin types like 'int'. Builtin
2425/// types are always canonical and have a literal name field.
2426class BuiltinType : public Type {
2427public:
2428 enum Kind {
2429// OpenCL image types
2430#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2431#include "clang/Basic/OpenCLImageTypes.def"
2432// OpenCL extension types
2433#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2434#include "clang/Basic/OpenCLExtensionTypes.def"
2435// SVE Types
2436#define SVE_TYPE(Name, Id, SingletonId) Id,
2437#include "clang/Basic/AArch64SVEACLETypes.def"
2438// All other builtin types
2439#define BUILTIN_TYPE(Id, SingletonId) Id,
2440#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2441#include "clang/AST/BuiltinTypes.def"
2442 };
2443
2444private:
2445 friend class ASTContext; // ASTContext creates these.
2446
2447 BuiltinType(Kind K)
2448 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2449 /*InstantiationDependent=*/(K == Dependent),
2450 /*VariablyModified=*/false,
2451 /*Unexpanded parameter pack=*/false) {
2452 BuiltinTypeBits.Kind = K;
2453 }
2454
2455public:
2456 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2457 StringRef getName(const PrintingPolicy &Policy) const;
2458
2459 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2460 // The StringRef is null-terminated.
2461 StringRef str = getName(Policy);
2462 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 2462, __PRETTY_FUNCTION__))
;
2463 return str.data();
2464 }
2465
2466 bool isSugared() const { return false; }
2467 QualType desugar() const { return QualType(this, 0); }
2468
2469 bool isInteger() const {
2470 return getKind() >= Bool && getKind() <= Int128;
2471 }
2472
2473 bool isSignedInteger() const {
2474 return getKind() >= Char_S && getKind() <= Int128;
2475 }
2476
2477 bool isUnsignedInteger() const {
2478 return getKind() >= Bool && getKind() <= UInt128;
2479 }
2480
2481 bool isFloatingPoint() const {
2482 return getKind() >= Half && getKind() <= Float128;
2483 }
2484
2485 /// Determines whether the given kind corresponds to a placeholder type.
2486 static bool isPlaceholderTypeKind(Kind K) {
2487 return K >= Overload;
2488 }
2489
2490 /// Determines whether this type is a placeholder type, i.e. a type
2491 /// which cannot appear in arbitrary positions in a fully-formed
2492 /// expression.
2493 bool isPlaceholderType() const {
2494 return isPlaceholderTypeKind(getKind());
2495 }
2496
2497 /// Determines whether this type is a placeholder type other than
2498 /// Overload. Most placeholder types require only syntactic
2499 /// information about their context in order to be resolved (e.g.
2500 /// whether it is a call expression), which means they can (and
2501 /// should) be resolved in an earlier "phase" of analysis.
2502 /// Overload expressions sometimes pick up further information
2503 /// from their context, like whether the context expects a
2504 /// specific function-pointer type, and so frequently need
2505 /// special treatment.
2506 bool isNonOverloadPlaceholderType() const {
2507 return getKind() > Overload;
2508 }
2509
2510 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2511};
2512
2513/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2514/// types (_Complex float etc) as well as the GCC integer complex extensions.
2515class ComplexType : public Type, public llvm::FoldingSetNode {
2516 friend class ASTContext; // ASTContext creates these.
2517
2518 QualType ElementType;
2519
2520 ComplexType(QualType Element, QualType CanonicalPtr)
2521 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2522 Element->isInstantiationDependentType(),
2523 Element->isVariablyModifiedType(),
2524 Element->containsUnexpandedParameterPack()),
2525 ElementType(Element) {}
2526
2527public:
2528 QualType getElementType() const { return ElementType; }
2529
2530 bool isSugared() const { return false; }
2531 QualType desugar() const { return QualType(this, 0); }
2532
2533 void Profile(llvm::FoldingSetNodeID &ID) {
2534 Profile(ID, getElementType());
2535 }
2536
2537 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2538 ID.AddPointer(Element.getAsOpaquePtr());
2539 }
2540
2541 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2542};
2543
2544/// Sugar for parentheses used when specifying types.
2545class ParenType : public Type, public llvm::FoldingSetNode {
2546 friend class ASTContext; // ASTContext creates these.
2547
2548 QualType Inner;
2549
2550 ParenType(QualType InnerType, QualType CanonType)
2551 : Type(Paren, CanonType, InnerType->isDependentType(),
2552 InnerType->isInstantiationDependentType(),
2553 InnerType->isVariablyModifiedType(),
2554 InnerType->containsUnexpandedParameterPack()),
2555 Inner(InnerType) {}
2556
2557public:
2558 QualType getInnerType() const { return Inner; }
2559
2560 bool isSugared() const { return true; }
2561 QualType desugar() const { return getInnerType(); }
2562
2563 void Profile(llvm::FoldingSetNodeID &ID) {
2564 Profile(ID, getInnerType());
2565 }
2566
2567 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2568 Inner.Profile(ID);
2569 }
2570
2571 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2572};
2573
2574/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2575class PointerType : public Type, public llvm::FoldingSetNode {
2576 friend class ASTContext; // ASTContext creates these.
2577
2578 QualType PointeeType;
2579
2580 PointerType(QualType Pointee, QualType CanonicalPtr)
2581 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2582 Pointee->isInstantiationDependentType(),
2583 Pointee->isVariablyModifiedType(),
2584 Pointee->containsUnexpandedParameterPack()),
2585 PointeeType(Pointee) {}
2586
2587public:
2588 QualType getPointeeType() const { return PointeeType; }
2589
2590 /// Returns true if address spaces of pointers overlap.
2591 /// OpenCL v2.0 defines conversion rules for pointers to different
2592 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2593 /// address spaces.
2594 /// CL1.1 or CL1.2:
2595 /// address spaces overlap iff they are they same.
2596 /// CL2.0 adds:
2597 /// __generic overlaps with any address space except for __constant.
2598 bool isAddressSpaceOverlapping(const PointerType &other) const {
2599 Qualifiers thisQuals = PointeeType.getQualifiers();
2600 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2601 // Address spaces overlap if at least one of them is a superset of another
2602 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2603 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2604 }
2605
2606 bool isSugared() const { return false; }
2607 QualType desugar() const { return QualType(this, 0); }
2608
2609 void Profile(llvm::FoldingSetNodeID &ID) {
2610 Profile(ID, getPointeeType());
2611 }
2612
2613 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2614 ID.AddPointer(Pointee.getAsOpaquePtr());
2615 }
2616
2617 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2618};
2619
2620/// Represents a type which was implicitly adjusted by the semantic
2621/// engine for arbitrary reasons. For example, array and function types can
2622/// decay, and function types can have their calling conventions adjusted.
2623class AdjustedType : public Type, public llvm::FoldingSetNode {
2624 QualType OriginalTy;
2625 QualType AdjustedTy;
2626
2627protected:
2628 friend class ASTContext; // ASTContext creates these.
2629
2630 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2631 QualType CanonicalPtr)
2632 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2633 OriginalTy->isInstantiationDependentType(),
2634 OriginalTy->isVariablyModifiedType(),
2635 OriginalTy->containsUnexpandedParameterPack()),
2636 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2637
2638public:
2639 QualType getOriginalType() const { return OriginalTy; }
2640 QualType getAdjustedType() const { return AdjustedTy; }
2641
2642 bool isSugared() const { return true; }
2643 QualType desugar() const { return AdjustedTy; }
2644
2645 void Profile(llvm::FoldingSetNodeID &ID) {
2646 Profile(ID, OriginalTy, AdjustedTy);
2647 }
2648
2649 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2650 ID.AddPointer(Orig.getAsOpaquePtr());
2651 ID.AddPointer(New.getAsOpaquePtr());
2652 }
2653
2654 static bool classof(const Type *T) {
2655 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2656 }
2657};
2658
2659/// Represents a pointer type decayed from an array or function type.
2660class DecayedType : public AdjustedType {
2661 friend class ASTContext; // ASTContext creates these.
2662
2663 inline
2664 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2665
2666public:
2667 QualType getDecayedType() const { return getAdjustedType(); }
2668
2669 inline QualType getPointeeType() const;
2670
2671 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2672};
2673
2674/// Pointer to a block type.
2675/// This type is to represent types syntactically represented as
2676/// "void (^)(int)", etc. Pointee is required to always be a function type.
2677class BlockPointerType : public Type, public llvm::FoldingSetNode {
2678 friend class ASTContext; // ASTContext creates these.
2679
2680 // Block is some kind of pointer type
2681 QualType PointeeType;
2682
2683 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2684 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2685 Pointee->isInstantiationDependentType(),
2686 Pointee->isVariablyModifiedType(),
2687 Pointee->containsUnexpandedParameterPack()),
2688 PointeeType(Pointee) {}
2689
2690public:
2691 // Get the pointee type. Pointee is required to always be a function type.
2692 QualType getPointeeType() const { return PointeeType; }
2693
2694 bool isSugared() const { return false; }
2695 QualType desugar() const { return QualType(this, 0); }
2696
2697 void Profile(llvm::FoldingSetNodeID &ID) {
2698 Profile(ID, getPointeeType());
2699 }
2700
2701 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2702 ID.AddPointer(Pointee.getAsOpaquePtr());
2703 }
2704
2705 static bool classof(const Type *T) {
2706 return T->getTypeClass() == BlockPointer;
2707 }
2708};
2709
2710/// Base for LValueReferenceType and RValueReferenceType
2711class ReferenceType : public Type, public llvm::FoldingSetNode {
2712 QualType PointeeType;
2713
2714protected:
2715 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2716 bool SpelledAsLValue)
2717 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2718 Referencee->isInstantiationDependentType(),
2719 Referencee->isVariablyModifiedType(),
2720 Referencee->containsUnexpandedParameterPack()),
2721 PointeeType(Referencee) {
2722 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2723 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2724 }
2725
2726public:
2727 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2728 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2729
2730 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2731
2732 QualType getPointeeType() const {
2733 // FIXME: this might strip inner qualifiers; okay?
2734 const ReferenceType *T = this;
2735 while (T->isInnerRef())
2736 T = T->PointeeType->castAs<ReferenceType>();
2737 return T->PointeeType;
2738 }
2739
2740 void Profile(llvm::FoldingSetNodeID &ID) {
2741 Profile(ID, PointeeType, isSpelledAsLValue());
2742 }
2743
2744 static void Profile(llvm::FoldingSetNodeID &ID,
2745 QualType Referencee,
2746 bool SpelledAsLValue) {
2747 ID.AddPointer(Referencee.getAsOpaquePtr());
2748 ID.AddBoolean(SpelledAsLValue);
2749 }
2750
2751 static bool classof(const Type *T) {
2752 return T->getTypeClass() == LValueReference ||
2753 T->getTypeClass() == RValueReference;
2754 }
2755};
2756
2757/// An lvalue reference type, per C++11 [dcl.ref].
2758class LValueReferenceType : public ReferenceType {
2759 friend class ASTContext; // ASTContext creates these
2760
2761 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2762 bool SpelledAsLValue)
2763 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2764 SpelledAsLValue) {}
2765
2766public:
2767 bool isSugared() const { return false; }
2768 QualType desugar() const { return QualType(this, 0); }
2769
2770 static bool classof(const Type *T) {
2771 return T->getTypeClass() == LValueReference;
2772 }
2773};
2774
2775/// An rvalue reference type, per C++11 [dcl.ref].
2776class RValueReferenceType : public ReferenceType {
2777 friend class ASTContext; // ASTContext creates these
2778
2779 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2780 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2781
2782public:
2783 bool isSugared() const { return false; }
2784 QualType desugar() const { return QualType(this, 0); }
2785
2786 static bool classof(const Type *T) {
2787 return T->getTypeClass() == RValueReference;
2788 }
2789};
2790
2791/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2792///
2793/// This includes both pointers to data members and pointer to member functions.
2794class MemberPointerType : public Type, public llvm::FoldingSetNode {
2795 friend class ASTContext; // ASTContext creates these.
2796
2797 QualType PointeeType;
2798
2799 /// The class of which the pointee is a member. Must ultimately be a
2800 /// RecordType, but could be a typedef or a template parameter too.
2801 const Type *Class;
2802
2803 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2804 : Type(MemberPointer, CanonicalPtr,
2805 Cls->isDependentType() || Pointee->isDependentType(),
2806 (Cls->isInstantiationDependentType() ||
2807 Pointee->isInstantiationDependentType()),
2808 Pointee->isVariablyModifiedType(),
2809 (Cls->containsUnexpandedParameterPack() ||
2810 Pointee->containsUnexpandedParameterPack())),
2811 PointeeType(Pointee), Class(Cls) {}
2812
2813public:
2814 QualType getPointeeType() const { return PointeeType; }
2815
2816 /// Returns true if the member type (i.e. the pointee type) is a
2817 /// function type rather than a data-member type.
2818 bool isMemberFunctionPointer() const {
2819 return PointeeType->isFunctionProtoType();
2820 }
2821
2822 /// Returns true if the member type (i.e. the pointee type) is a
2823 /// data type rather than a function type.
2824 bool isMemberDataPointer() const {
2825 return !PointeeType->isFunctionProtoType();
2826 }
2827
2828 const Type *getClass() const { return Class; }
2829 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2830
2831 bool isSugared() const { return false; }
2832 QualType desugar() const { return QualType(this, 0); }
2833
2834 void Profile(llvm::FoldingSetNodeID &ID) {
2835 Profile(ID, getPointeeType(), getClass());
2836 }
2837
2838 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2839 const Type *Class) {
2840 ID.AddPointer(Pointee.getAsOpaquePtr());
2841 ID.AddPointer(Class);
2842 }
2843
2844 static bool classof(const Type *T) {
2845 return T->getTypeClass() == MemberPointer;
2846 }
2847};
2848
2849/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2850class ArrayType : public Type, public llvm::FoldingSetNode {
2851public:
2852 /// Capture whether this is a normal array (e.g. int X[4])
2853 /// an array with a static size (e.g. int X[static 4]), or an array
2854 /// with a star size (e.g. int X[*]).
2855 /// 'static' is only allowed on function parameters.
2856 enum ArraySizeModifier {
2857 Normal, Static, Star
2858 };
2859
2860private:
2861 /// The element type of the array.
2862 QualType ElementType;
2863
2864protected:
2865 friend class ASTContext; // ASTContext creates these.
2866
2867 // C++ [temp.dep.type]p1:
2868 // A type is dependent if it is...
2869 // - an array type constructed from any dependent type or whose
2870 // size is specified by a constant expression that is
2871 // value-dependent,
2872 ArrayType(TypeClass tc, QualType et, QualType can,
2873 ArraySizeModifier sm, unsigned tq,
2874 bool ContainsUnexpandedParameterPack)
2875 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2876 et->isInstantiationDependentType() || tc == DependentSizedArray,
2877 (tc == VariableArray || et->isVariablyModifiedType()),
2878 ContainsUnexpandedParameterPack),
2879 ElementType(et) {
2880 ArrayTypeBits.IndexTypeQuals = tq;
2881 ArrayTypeBits.SizeModifier = sm;
2882 }
2883
2884public:
2885 QualType getElementType() const { return ElementType; }
2886
2887 ArraySizeModifier getSizeModifier() const {
2888 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2889 }
2890
2891 Qualifiers getIndexTypeQualifiers() const {
2892 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2893 }
2894
2895 unsigned getIndexTypeCVRQualifiers() const {
2896 return ArrayTypeBits.IndexTypeQuals;
2897 }
2898
2899 static bool classof(const Type *T) {
2900 return T->getTypeClass() == ConstantArray ||
2901 T->getTypeClass() == VariableArray ||
2902 T->getTypeClass() == IncompleteArray ||
2903 T->getTypeClass() == DependentSizedArray;
2904 }
2905};
2906
2907/// Represents the canonical version of C arrays with a specified constant size.
2908/// For example, the canonical type for 'int A[4 + 4*100]' is a
2909/// ConstantArrayType where the element type is 'int' and the size is 404.
2910class ConstantArrayType : public ArrayType {
2911 llvm::APInt Size; // Allows us to unique the type.
2912
2913 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2914 ArraySizeModifier sm, unsigned tq)
2915 : ArrayType(ConstantArray, et, can, sm, tq,
2916 et->containsUnexpandedParameterPack()),
2917 Size(size) {}
2918
2919protected:
2920 friend class ASTContext; // ASTContext creates these.
2921
2922 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2923 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2924 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2925 Size(size) {}
2926
2927public:
2928 const llvm::APInt &getSize() const { return Size; }
2929 bool isSugared() const { return false; }
2930 QualType desugar() const { return QualType(this, 0); }
2931
2932 /// Determine the number of bits required to address a member of
2933 // an array with the given element type and number of elements.
2934 static unsigned getNumAddressingBits(const ASTContext &Context,
2935 QualType ElementType,
2936 const llvm::APInt &NumElements);
2937
2938 /// Determine the maximum number of active bits that an array's size
2939 /// can require, which limits the maximum size of the array.
2940 static unsigned getMaxSizeBits(const ASTContext &Context);
2941
2942 void Profile(llvm::FoldingSetNodeID &ID) {
2943 Profile(ID, getElementType(), getSize(),
2944 getSizeModifier(), getIndexTypeCVRQualifiers());
2945 }
2946
2947 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2948 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2949 unsigned TypeQuals) {
2950 ID.AddPointer(ET.getAsOpaquePtr());
2951 ID.AddInteger(ArraySize.getZExtValue());
2952 ID.AddInteger(SizeMod);
2953 ID.AddInteger(TypeQuals);
2954 }
2955
2956 static bool classof(const Type *T) {
2957 return T->getTypeClass() == ConstantArray;
2958 }
2959};
2960
2961/// Represents a C array with an unspecified size. For example 'int A[]' has
2962/// an IncompleteArrayType where the element type is 'int' and the size is
2963/// unspecified.
2964class IncompleteArrayType : public ArrayType {
2965 friend class ASTContext; // ASTContext creates these.
2966
2967 IncompleteArrayType(QualType et, QualType can,
2968 ArraySizeModifier sm, unsigned tq)
2969 : ArrayType(IncompleteArray, et, can, sm, tq,
2970 et->containsUnexpandedParameterPack()) {}
2971
2972public:
2973 friend class StmtIteratorBase;
2974
2975 bool isSugared() const { return false; }
2976 QualType desugar() const { return QualType(this, 0); }
2977
2978 static bool classof(const Type *T) {
2979 return T->getTypeClass() == IncompleteArray;
2980 }
2981
2982 void Profile(llvm::FoldingSetNodeID &ID) {
2983 Profile(ID, getElementType(), getSizeModifier(),
2984 getIndexTypeCVRQualifiers());
2985 }
2986
2987 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2988 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2989 ID.AddPointer(ET.getAsOpaquePtr());
2990 ID.AddInteger(SizeMod);
2991 ID.AddInteger(TypeQuals);
2992 }
2993};
2994
2995/// Represents a C array with a specified size that is not an
2996/// integer-constant-expression. For example, 'int s[x+foo()]'.
2997/// Since the size expression is an arbitrary expression, we store it as such.
2998///
2999/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3000/// should not be: two lexically equivalent variable array types could mean
3001/// different things, for example, these variables do not have the same type
3002/// dynamically:
3003///
3004/// void foo(int x) {
3005/// int Y[x];
3006/// ++x;
3007/// int Z[x];
3008/// }
3009class VariableArrayType : public ArrayType {
3010 friend class ASTContext; // ASTContext creates these.
3011
3012 /// An assignment-expression. VLA's are only permitted within
3013 /// a function block.
3014 Stmt *SizeExpr;
3015
3016 /// The range spanned by the left and right array brackets.
3017 SourceRange Brackets;
3018
3019 VariableArrayType(QualType et, QualType can, Expr *e,
3020 ArraySizeModifier sm, unsigned tq,
3021 SourceRange brackets)
3022 : ArrayType(VariableArray, et, can, sm, tq,
3023 et->containsUnexpandedParameterPack()),
3024 SizeExpr((Stmt*) e), Brackets(brackets) {}
3025
3026public:
3027 friend class StmtIteratorBase;
3028
3029 Expr *getSizeExpr() const {
3030 // We use C-style casts instead of cast<> here because we do not wish
3031 // to have a dependency of Type.h on Stmt.h/Expr.h.
3032 return (Expr*) SizeExpr;
3033 }
3034
3035 SourceRange getBracketsRange() const { return Brackets; }
3036 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3037 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3038
3039 bool isSugared() const { return false; }
3040 QualType desugar() const { return QualType(this, 0); }
3041
3042 static bool classof(const Type *T) {
3043 return T->getTypeClass() == VariableArray;
3044 }
3045
3046 void Profile(llvm::FoldingSetNodeID &ID) {
3047 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3047)
;
3048 }
3049};
3050
3051/// Represents an array type in C++ whose size is a value-dependent expression.
3052///
3053/// For example:
3054/// \code
3055/// template<typename T, int Size>
3056/// class array {
3057/// T data[Size];
3058/// };
3059/// \endcode
3060///
3061/// For these types, we won't actually know what the array bound is
3062/// until template instantiation occurs, at which point this will
3063/// become either a ConstantArrayType or a VariableArrayType.
3064class DependentSizedArrayType : public ArrayType {
3065 friend class ASTContext; // ASTContext creates these.
3066
3067 const ASTContext &Context;
3068
3069 /// An assignment expression that will instantiate to the
3070 /// size of the array.
3071 ///
3072 /// The expression itself might be null, in which case the array
3073 /// type will have its size deduced from an initializer.
3074 Stmt *SizeExpr;
3075
3076 /// The range spanned by the left and right array brackets.
3077 SourceRange Brackets;
3078
3079 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3080 Expr *e, ArraySizeModifier sm, unsigned tq,
3081 SourceRange brackets);
3082
3083public:
3084 friend class StmtIteratorBase;
3085
3086 Expr *getSizeExpr() const {
3087 // We use C-style casts instead of cast<> here because we do not wish
3088 // to have a dependency of Type.h on Stmt.h/Expr.h.
3089 return (Expr*) SizeExpr;
3090 }
3091
3092 SourceRange getBracketsRange() const { return Brackets; }
3093 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3094 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3095
3096 bool isSugared() const { return false; }
3097 QualType desugar() const { return QualType(this, 0); }
3098
3099 static bool classof(const Type *T) {
3100 return T->getTypeClass() == DependentSizedArray;
3101 }
3102
3103 void Profile(llvm::FoldingSetNodeID &ID) {
3104 Profile(ID, Context, getElementType(),
3105 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3106 }
3107
3108 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3109 QualType ET, ArraySizeModifier SizeMod,
3110 unsigned TypeQuals, Expr *E);
3111};
3112
3113/// Represents an extended address space qualifier where the input address space
3114/// value is dependent. Non-dependent address spaces are not represented with a
3115/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3116///
3117/// For example:
3118/// \code
3119/// template<typename T, int AddrSpace>
3120/// class AddressSpace {
3121/// typedef T __attribute__((address_space(AddrSpace))) type;
3122/// }
3123/// \endcode
3124class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3125 friend class ASTContext;
3126
3127 const ASTContext &Context;
3128 Expr *AddrSpaceExpr;
3129 QualType PointeeType;
3130 SourceLocation loc;
3131
3132 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3133 QualType can, Expr *AddrSpaceExpr,
3134 SourceLocation loc);
3135
3136public:
3137 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3138 QualType getPointeeType() const { return PointeeType; }
3139 SourceLocation getAttributeLoc() const { return loc; }
3140
3141 bool isSugared() const { return false; }
3142 QualType desugar() const { return QualType(this, 0); }
3143
3144 static bool classof(const Type *T) {
3145 return T->getTypeClass() == DependentAddressSpace;
3146 }
3147
3148 void Profile(llvm::FoldingSetNodeID &ID) {
3149 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3150 }
3151
3152 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3153 QualType PointeeType, Expr *AddrSpaceExpr);
3154};
3155
3156/// Represents an extended vector type where either the type or size is
3157/// dependent.
3158///
3159/// For example:
3160/// \code
3161/// template<typename T, int Size>
3162/// class vector {
3163/// typedef T __attribute__((ext_vector_type(Size))) type;
3164/// }
3165/// \endcode
3166class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3167 friend class ASTContext;
3168
3169 const ASTContext &Context;
3170 Expr *SizeExpr;
3171
3172 /// The element type of the array.
3173 QualType ElementType;
3174
3175 SourceLocation loc;
3176
3177 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3178 QualType can, Expr *SizeExpr, SourceLocation loc);
3179
3180public:
3181 Expr *getSizeExpr() const { return SizeExpr; }
3182 QualType getElementType() const { return ElementType; }
3183 SourceLocation getAttributeLoc() const { return loc; }
3184
3185 bool isSugared() const { return false; }
3186 QualType desugar() const { return QualType(this, 0); }
3187
3188 static bool classof(const Type *T) {
3189 return T->getTypeClass() == DependentSizedExtVector;
3190 }
3191
3192 void Profile(llvm::FoldingSetNodeID &ID) {
3193 Profile(ID, Context, getElementType(), getSizeExpr());
3194 }
3195
3196 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3197 QualType ElementType, Expr *SizeExpr);
3198};
3199
3200
3201/// Represents a GCC generic vector type. This type is created using
3202/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3203/// bytes; or from an Altivec __vector or vector declaration.
3204/// Since the constructor takes the number of vector elements, the
3205/// client is responsible for converting the size into the number of elements.
3206class VectorType : public Type, public llvm::FoldingSetNode {
3207public:
3208 enum VectorKind {
3209 /// not a target-specific vector type
3210 GenericVector,
3211
3212 /// is AltiVec vector
3213 AltiVecVector,
3214
3215 /// is AltiVec 'vector Pixel'
3216 AltiVecPixel,
3217
3218 /// is AltiVec 'vector bool ...'
3219 AltiVecBool,
3220
3221 /// is ARM Neon vector
3222 NeonVector,
3223
3224 /// is ARM Neon polynomial vector
3225 NeonPolyVector
3226 };
3227
3228protected:
3229 friend class ASTContext; // ASTContext creates these.
3230
3231 /// The element type of the vector.
3232 QualType ElementType;
3233
3234 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3235 VectorKind vecKind);
3236
3237 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3238 QualType canonType, VectorKind vecKind);
3239
3240public:
3241 QualType getElementType() const { return ElementType; }
3242 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3243
3244 static bool isVectorSizeTooLarge(unsigned NumElements) {
3245 return NumElements > VectorTypeBitfields::MaxNumElements;
3246 }
3247
3248 bool isSugared() const { return false; }
3249 QualType desugar() const { return QualType(this, 0); }
3250
3251 VectorKind getVectorKind() const {
3252 return VectorKind(VectorTypeBits.VecKind);
3253 }
3254
3255 void Profile(llvm::FoldingSetNodeID &ID) {
3256 Profile(ID, getElementType(), getNumElements(),
3257 getTypeClass(), getVectorKind());
3258 }
3259
3260 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3261 unsigned NumElements, TypeClass TypeClass,
3262 VectorKind VecKind) {
3263 ID.AddPointer(ElementType.getAsOpaquePtr());
3264 ID.AddInteger(NumElements);
3265 ID.AddInteger(TypeClass);
3266 ID.AddInteger(VecKind);
3267 }
3268
3269 static bool classof(const Type *T) {
3270 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3271 }
3272};
3273
3274/// Represents a vector type where either the type or size is dependent.
3275////
3276/// For example:
3277/// \code
3278/// template<typename T, int Size>
3279/// class vector {
3280/// typedef T __attribute__((vector_size(Size))) type;
3281/// }
3282/// \endcode
3283class DependentVectorType : public Type, public llvm::FoldingSetNode {
3284 friend class ASTContext;
3285
3286 const ASTContext &Context;
3287 QualType ElementType;
3288 Expr *SizeExpr;
3289 SourceLocation Loc;
3290
3291 DependentVectorType(const ASTContext &Context, QualType ElementType,
3292 QualType CanonType, Expr *SizeExpr,
3293 SourceLocation Loc, VectorType::VectorKind vecKind);
3294
3295public:
3296 Expr *getSizeExpr() const { return SizeExpr; }
3297 QualType getElementType() const { return ElementType; }
3298 SourceLocation getAttributeLoc() const { return Loc; }
3299 VectorType::VectorKind getVectorKind() const {
3300 return VectorType::VectorKind(VectorTypeBits.VecKind);
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 static bool classof(const Type *T) {
3307 return T->getTypeClass() == DependentVector;
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3312 }
3313
3314 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3315 QualType ElementType, const Expr *SizeExpr,
3316 VectorType::VectorKind VecKind);
3317};
3318
3319/// ExtVectorType - Extended vector type. This type is created using
3320/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3321/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3322/// class enables syntactic extensions, like Vector Components for accessing
3323/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3324/// Shading Language).
3325class ExtVectorType : public VectorType {
3326 friend class ASTContext; // ASTContext creates these.
3327
3328 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3329 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3330
3331public:
3332 static int getPointAccessorIdx(char c) {
3333 switch (c) {
3334 default: return -1;
3335 case 'x': case 'r': return 0;
3336 case 'y': case 'g': return 1;
3337 case 'z': case 'b': return 2;
3338 case 'w': case 'a': return 3;
3339 }
3340 }
3341
3342 static int getNumericAccessorIdx(char c) {
3343 switch (c) {
3344 default: return -1;
3345 case '0': return 0;
3346 case '1': return 1;
3347 case '2': return 2;
3348 case '3': return 3;
3349 case '4': return 4;
3350 case '5': return 5;
3351 case '6': return 6;
3352 case '7': return 7;
3353 case '8': return 8;
3354 case '9': return 9;
3355 case 'A':
3356 case 'a': return 10;
3357 case 'B':
3358 case 'b': return 11;
3359 case 'C':
3360 case 'c': return 12;
3361 case 'D':
3362 case 'd': return 13;
3363 case 'E':
3364 case 'e': return 14;
3365 case 'F':
3366 case 'f': return 15;
3367 }
3368 }
3369
3370 static int getAccessorIdx(char c, bool isNumericAccessor) {
3371 if (isNumericAccessor)
3372 return getNumericAccessorIdx(c);
3373 else
3374 return getPointAccessorIdx(c);
3375 }
3376
3377 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3378 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3379 return unsigned(idx-1) < getNumElements();
3380 return false;
3381 }
3382
3383 bool isSugared() const { return false; }
3384 QualType desugar() const { return QualType(this, 0); }
3385
3386 static bool classof(const Type *T) {
3387 return T->getTypeClass() == ExtVector;
3388 }
3389};
3390
3391/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3392/// class of FunctionNoProtoType and FunctionProtoType.
3393class FunctionType : public Type {
3394 // The type returned by the function.
3395 QualType ResultType;
3396
3397public:
3398 /// Interesting information about a specific parameter that can't simply
3399 /// be reflected in parameter's type. This is only used by FunctionProtoType
3400 /// but is in FunctionType to make this class available during the
3401 /// specification of the bases of FunctionProtoType.
3402 ///
3403 /// It makes sense to model language features this way when there's some
3404 /// sort of parameter-specific override (such as an attribute) that
3405 /// affects how the function is called. For example, the ARC ns_consumed
3406 /// attribute changes whether a parameter is passed at +0 (the default)
3407 /// or +1 (ns_consumed). This must be reflected in the function type,
3408 /// but isn't really a change to the parameter type.
3409 ///
3410 /// One serious disadvantage of modelling language features this way is
3411 /// that they generally do not work with language features that attempt
3412 /// to destructure types. For example, template argument deduction will
3413 /// not be able to match a parameter declared as
3414 /// T (*)(U)
3415 /// against an argument of type
3416 /// void (*)(__attribute__((ns_consumed)) id)
3417 /// because the substitution of T=void, U=id into the former will
3418 /// not produce the latter.
3419 class ExtParameterInfo {
3420 enum {
3421 ABIMask = 0x0F,
3422 IsConsumed = 0x10,
3423 HasPassObjSize = 0x20,
3424 IsNoEscape = 0x40,
3425 };
3426 unsigned char Data = 0;
3427
3428 public:
3429 ExtParameterInfo() = default;
3430
3431 /// Return the ABI treatment of this parameter.
3432 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3433 ExtParameterInfo withABI(ParameterABI kind) const {
3434 ExtParameterInfo copy = *this;
3435 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3436 return copy;
3437 }
3438
3439 /// Is this parameter considered "consumed" by Objective-C ARC?
3440 /// Consumed parameters must have retainable object type.
3441 bool isConsumed() const { return (Data & IsConsumed); }
3442 ExtParameterInfo withIsConsumed(bool consumed) const {
3443 ExtParameterInfo copy = *this;
3444 if (consumed)
3445 copy.Data |= IsConsumed;
3446 else
3447 copy.Data &= ~IsConsumed;
3448 return copy;
3449 }
3450
3451 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3452 ExtParameterInfo withHasPassObjectSize() const {
3453 ExtParameterInfo Copy = *this;
3454 Copy.Data |= HasPassObjSize;
3455 return Copy;
3456 }
3457
3458 bool isNoEscape() const { return Data & IsNoEscape; }
3459 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3460 ExtParameterInfo Copy = *this;
3461 if (NoEscape)
3462 Copy.Data |= IsNoEscape;
3463 else
3464 Copy.Data &= ~IsNoEscape;
3465 return Copy;
3466 }
3467
3468 unsigned char getOpaqueValue() const { return Data; }
3469 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3470 ExtParameterInfo result;
3471 result.Data = data;
3472 return result;
3473 }
3474
3475 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3476 return lhs.Data == rhs.Data;
3477 }
3478
3479 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3480 return lhs.Data != rhs.Data;
3481 }
3482 };
3483
3484 /// A class which abstracts out some details necessary for
3485 /// making a call.
3486 ///
3487 /// It is not actually used directly for storing this information in
3488 /// a FunctionType, although FunctionType does currently use the
3489 /// same bit-pattern.
3490 ///
3491 // If you add a field (say Foo), other than the obvious places (both,
3492 // constructors, compile failures), what you need to update is
3493 // * Operator==
3494 // * getFoo
3495 // * withFoo
3496 // * functionType. Add Foo, getFoo.
3497 // * ASTContext::getFooType
3498 // * ASTContext::mergeFunctionTypes
3499 // * FunctionNoProtoType::Profile
3500 // * FunctionProtoType::Profile
3501 // * TypePrinter::PrintFunctionProto
3502 // * AST read and write
3503 // * Codegen
3504 class ExtInfo {
3505 friend class FunctionType;
3506
3507 // Feel free to rearrange or add bits, but if you go over 12,
3508 // you'll need to adjust both the Bits field below and
3509 // Type::FunctionTypeBitfields.
3510
3511 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3512 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3513 //
3514 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3515 enum { CallConvMask = 0x1F };
3516 enum { NoReturnMask = 0x20 };
3517 enum { ProducesResultMask = 0x40 };
3518 enum { NoCallerSavedRegsMask = 0x80 };
3519 enum { NoCfCheckMask = 0x800 };
3520 enum {
3521 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3522 NoCallerSavedRegsMask | NoCfCheckMask),
3523 RegParmOffset = 8
3524 }; // Assumed to be the last field
3525 uint16_t Bits = CC_C;
3526
3527 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3528
3529 public:
3530 // Constructor with no defaults. Use this when you know that you
3531 // have all the elements (when reading an AST file for example).
3532 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3533 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3534 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3534, __PRETTY_FUNCTION__))
;
3535 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3536 (producesResult ? ProducesResultMask : 0) |
3537 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3538 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3539 (NoCfCheck ? NoCfCheckMask : 0);
3540 }
3541
3542 // Constructor with all defaults. Use when for example creating a
3543 // function known to use defaults.
3544 ExtInfo() = default;
3545
3546 // Constructor with just the calling convention, which is an important part
3547 // of the canonical type.
3548 ExtInfo(CallingConv CC) : Bits(CC) {}
3549
3550 bool getNoReturn() const { return Bits & NoReturnMask; }
3551 bool getProducesResult() const { return Bits & ProducesResultMask; }
3552 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3553 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3554 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3555
3556 unsigned getRegParm() const {
3557 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3558 if (RegParm > 0)
3559 --RegParm;
3560 return RegParm;
3561 }
3562
3563 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3564
3565 bool operator==(ExtInfo Other) const {
3566 return Bits == Other.Bits;
3567 }
3568 bool operator!=(ExtInfo Other) const {
3569 return Bits != Other.Bits;
3570 }
3571
3572 // Note that we don't have setters. That is by design, use
3573 // the following with methods instead of mutating these objects.
3574
3575 ExtInfo withNoReturn(bool noReturn) const {
3576 if (noReturn)
3577 return ExtInfo(Bits | NoReturnMask);
3578 else
3579 return ExtInfo(Bits & ~NoReturnMask);
3580 }
3581
3582 ExtInfo withProducesResult(bool producesResult) const {
3583 if (producesResult)
3584 return ExtInfo(Bits | ProducesResultMask);
3585 else
3586 return ExtInfo(Bits & ~ProducesResultMask);
3587 }
3588
3589 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3590 if (noCallerSavedRegs)
3591 return ExtInfo(Bits | NoCallerSavedRegsMask);
3592 else
3593 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3594 }
3595
3596 ExtInfo withNoCfCheck(bool noCfCheck) const {
3597 if (noCfCheck)
3598 return ExtInfo(Bits | NoCfCheckMask);
3599 else
3600 return ExtInfo(Bits & ~NoCfCheckMask);
3601 }
3602
3603 ExtInfo withRegParm(unsigned RegParm) const {
3604 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3604, __PRETTY_FUNCTION__))
;
3605 return ExtInfo((Bits & ~RegParmMask) |
3606 ((RegParm + 1) << RegParmOffset));
3607 }
3608
3609 ExtInfo withCallingConv(CallingConv cc) const {
3610 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3611 }
3612
3613 void Profile(llvm::FoldingSetNodeID &ID) const {
3614 ID.AddInteger(Bits);
3615 }
3616 };
3617
3618 /// A simple holder for a QualType representing a type in an
3619 /// exception specification. Unfortunately needed by FunctionProtoType
3620 /// because TrailingObjects cannot handle repeated types.
3621 struct ExceptionType { QualType Type; };
3622
3623 /// A simple holder for various uncommon bits which do not fit in
3624 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3625 /// alignment of subsequent objects in TrailingObjects. You must update
3626 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3627 struct alignas(void *) FunctionTypeExtraBitfields {
3628 /// The number of types in the exception specification.
3629 /// A whole unsigned is not needed here and according to
3630 /// [implimits] 8 bits would be enough here.
3631 unsigned NumExceptionType;
3632 };
3633
3634protected:
3635 FunctionType(TypeClass tc, QualType res,
3636 QualType Canonical, bool Dependent,
3637 bool InstantiationDependent,
3638 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3639 ExtInfo Info)
3640 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3641 ContainsUnexpandedParameterPack),
3642 ResultType(res) {
3643 FunctionTypeBits.ExtInfo = Info.Bits;
3644 }
3645
3646 Qualifiers getFastTypeQuals() const {
3647 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3648 }
3649
3650public:
3651 QualType getReturnType() const { return ResultType; }
3652
3653 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3654 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3655
3656 /// Determine whether this function type includes the GNU noreturn
3657 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3658 /// type.
3659 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3660
3661 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3662 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3663
3664 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3665 "Const, volatile and restrict are assumed to be a subset of "
3666 "the fast qualifiers.");
3667
3668 bool isConst() const { return getFastTypeQuals().hasConst(); }
3669 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3670 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3671
3672 /// Determine the type of an expression that calls a function of
3673 /// this type.
3674 QualType getCallResultType(const ASTContext &Context) const {
3675 return getReturnType().getNonLValueExprType(Context);
3676 }
3677
3678 static StringRef getNameForCallConv(CallingConv CC);
3679
3680 static bool classof(const Type *T) {
3681 return T->getTypeClass() == FunctionNoProto ||
3682 T->getTypeClass() == FunctionProto;
3683 }
3684};
3685
3686/// Represents a K&R-style 'int foo()' function, which has
3687/// no information available about its arguments.
3688class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3689 friend class ASTContext; // ASTContext creates these.
3690
3691 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3692 : FunctionType(FunctionNoProto, Result, Canonical,
3693 /*Dependent=*/false, /*InstantiationDependent=*/false,
3694 Result->isVariablyModifiedType(),
3695 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3696
3697public:
3698 // No additional state past what FunctionType provides.
3699
3700 bool isSugared() const { return false; }
3701 QualType desugar() const { return QualType(this, 0); }
3702
3703 void Profile(llvm::FoldingSetNodeID &ID) {
3704 Profile(ID, getReturnType(), getExtInfo());
3705 }
3706
3707 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3708 ExtInfo Info) {
3709 Info.Profile(ID);
3710 ID.AddPointer(ResultType.getAsOpaquePtr());
3711 }
3712
3713 static bool classof(const Type *T) {
3714 return T->getTypeClass() == FunctionNoProto;
3715 }
3716};
3717
3718/// Represents a prototype with parameter type info, e.g.
3719/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3720/// parameters, not as having a single void parameter. Such a type can have
3721/// an exception specification, but this specification is not part of the
3722/// canonical type. FunctionProtoType has several trailing objects, some of
3723/// which optional. For more information about the trailing objects see
3724/// the first comment inside FunctionProtoType.
3725class FunctionProtoType final
3726 : public FunctionType,
3727 public llvm::FoldingSetNode,
3728 private llvm::TrailingObjects<
3729 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3730 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3731 FunctionType::ExtParameterInfo, Qualifiers> {
3732 friend class ASTContext; // ASTContext creates these.
3733 friend TrailingObjects;
3734
3735 // FunctionProtoType is followed by several trailing objects, some of
3736 // which optional. They are in order:
3737 //
3738 // * An array of getNumParams() QualType holding the parameter types.
3739 // Always present. Note that for the vast majority of FunctionProtoType,
3740 // these will be the only trailing objects.
3741 //
3742 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3743 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3744 // a single FunctionTypeExtraBitfields. Present if and only if
3745 // hasExtraBitfields() is true.
3746 //
3747 // * Optionally exactly one of:
3748 // * an array of getNumExceptions() ExceptionType,
3749 // * a single Expr *,
3750 // * a pair of FunctionDecl *,
3751 // * a single FunctionDecl *
3752 // used to store information about the various types of exception
3753 // specification. See getExceptionSpecSize for the details.
3754 //
3755 // * Optionally an array of getNumParams() ExtParameterInfo holding
3756 // an ExtParameterInfo for each of the parameters. Present if and
3757 // only if hasExtParameterInfos() is true.
3758 //
3759 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3760 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3761 // if hasExtQualifiers() is true.
3762 //
3763 // The optional FunctionTypeExtraBitfields has to be before the data
3764 // related to the exception specification since it contains the number
3765 // of exception types.
3766 //
3767 // We put the ExtParameterInfos last. If all were equal, it would make
3768 // more sense to put these before the exception specification, because
3769 // it's much easier to skip past them compared to the elaborate switch
3770 // required to skip the exception specification. However, all is not
3771 // equal; ExtParameterInfos are used to model very uncommon features,
3772 // and it's better not to burden the more common paths.
3773
3774public:
3775 /// Holds information about the various types of exception specification.
3776 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3777 /// used to group together the various bits of information about the
3778 /// exception specification.
3779 struct ExceptionSpecInfo {
3780 /// The kind of exception specification this is.
3781 ExceptionSpecificationType Type = EST_None;
3782
3783 /// Explicitly-specified list of exception types.
3784 ArrayRef<QualType> Exceptions;
3785
3786 /// Noexcept expression, if this is a computed noexcept specification.
3787 Expr *NoexceptExpr = nullptr;
3788
3789 /// The function whose exception specification this is, for
3790 /// EST_Unevaluated and EST_Uninstantiated.
3791 FunctionDecl *SourceDecl = nullptr;
3792
3793 /// The function template whose exception specification this is instantiated
3794 /// from, for EST_Uninstantiated.
3795 FunctionDecl *SourceTemplate = nullptr;
3796
3797 ExceptionSpecInfo() = default;
3798
3799 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3800 };
3801
3802 /// Extra information about a function prototype. ExtProtoInfo is not
3803 /// stored as such in FunctionProtoType but is used to group together
3804 /// the various bits of extra information about a function prototype.
3805 struct ExtProtoInfo {
3806 FunctionType::ExtInfo ExtInfo;
3807 bool Variadic : 1;
3808 bool HasTrailingReturn : 1;
3809 Qualifiers TypeQuals;
3810 RefQualifierKind RefQualifier = RQ_None;
3811 ExceptionSpecInfo ExceptionSpec;
3812 const ExtParameterInfo *ExtParameterInfos = nullptr;
3813
3814 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3815
3816 ExtProtoInfo(CallingConv CC)
3817 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3818
3819 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3820 ExtProtoInfo Result(*this);
3821 Result.ExceptionSpec = ESI;
3822 return Result;
3823 }
3824 };
3825
3826private:
3827 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3828 return getNumParams();
3829 }
3830
3831 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3832 return hasExtraBitfields();
3833 }
3834
3835 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3836 return getExceptionSpecSize().NumExceptionType;
3837 }
3838
3839 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3840 return getExceptionSpecSize().NumExprPtr;
3841 }
3842
3843 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3844 return getExceptionSpecSize().NumFunctionDeclPtr;
3845 }
3846
3847 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3848 return hasExtParameterInfos() ? getNumParams() : 0;
3849 }
3850
3851 /// Determine whether there are any argument types that
3852 /// contain an unexpanded parameter pack.
3853 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3854 unsigned numArgs) {
3855 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3856 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3857 return true;
3858
3859 return false;
3860 }
3861
3862 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3863 QualType canonical, const ExtProtoInfo &epi);
3864
3865 /// This struct is returned by getExceptionSpecSize and is used to
3866 /// translate an ExceptionSpecificationType to the number and kind
3867 /// of trailing objects related to the exception specification.
3868 struct ExceptionSpecSizeHolder {
3869 unsigned NumExceptionType;
3870 unsigned NumExprPtr;
3871 unsigned NumFunctionDeclPtr;
3872 };
3873
3874 /// Return the number and kind of trailing objects
3875 /// related to the exception specification.
3876 static ExceptionSpecSizeHolder
3877 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3878 switch (EST) {
3879 case EST_None:
3880 case EST_DynamicNone:
3881 case EST_MSAny:
3882 case EST_BasicNoexcept:
3883 case EST_Unparsed:
3884 case EST_NoThrow:
3885 return {0, 0, 0};
3886
3887 case EST_Dynamic:
3888 return {NumExceptions, 0, 0};
3889
3890 case EST_DependentNoexcept:
3891 case EST_NoexceptFalse:
3892 case EST_NoexceptTrue:
3893 return {0, 1, 0};
3894
3895 case EST_Uninstantiated:
3896 return {0, 0, 2};
3897
3898 case EST_Unevaluated:
3899 return {0, 0, 1};
3900 }
3901 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3901)
;
3902 }
3903
3904 /// Return the number and kind of trailing objects
3905 /// related to the exception specification.
3906 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3907 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3908 }
3909
3910 /// Whether the trailing FunctionTypeExtraBitfields is present.
3911 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3912 // If the exception spec type is EST_Dynamic then we have > 0 exception
3913 // types and the exact number is stored in FunctionTypeExtraBitfields.
3914 return EST == EST_Dynamic;
3915 }
3916
3917 /// Whether the trailing FunctionTypeExtraBitfields is present.
3918 bool hasExtraBitfields() const {
3919 return hasExtraBitfields(getExceptionSpecType());
3920 }
3921
3922 bool hasExtQualifiers() const {
3923 return FunctionTypeBits.HasExtQuals;
3924 }
3925
3926public:
3927 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3928
3929 QualType getParamType(unsigned i) const {
3930 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3930, __PRETTY_FUNCTION__))
;
3931 return param_type_begin()[i];
3932 }
3933
3934 ArrayRef<QualType> getParamTypes() const {
3935 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3936 }
3937
3938 ExtProtoInfo getExtProtoInfo() const {
3939 ExtProtoInfo EPI;
3940 EPI.ExtInfo = getExtInfo();
3941 EPI.Variadic = isVariadic();
3942 EPI.HasTrailingReturn = hasTrailingReturn();
3943 EPI.ExceptionSpec.Type = getExceptionSpecType();
3944 EPI.TypeQuals = getMethodQuals();
3945 EPI.RefQualifier = getRefQualifier();
3946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3947 EPI.ExceptionSpec.Exceptions = exceptions();
3948 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3949 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3951 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3952 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3954 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3955 }
3956 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3957 return EPI;
3958 }
3959
3960 /// Get the kind of exception specification on this function.
3961 ExceptionSpecificationType getExceptionSpecType() const {
3962 return static_cast<ExceptionSpecificationType>(
3963 FunctionTypeBits.ExceptionSpecType);
3964 }
3965
3966 /// Return whether this function has any kind of exception spec.
3967 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3968
3969 /// Return whether this function has a dynamic (throw) exception spec.
3970 bool hasDynamicExceptionSpec() const {
3971 return isDynamicExceptionSpec(getExceptionSpecType());
3972 }
3973
3974 /// Return whether this function has a noexcept exception spec.
3975 bool hasNoexceptExceptionSpec() const {
3976 return isNoexceptExceptionSpec(getExceptionSpecType());
3977 }
3978
3979 /// Return whether this function has a dependent exception spec.
3980 bool hasDependentExceptionSpec() const;
3981
3982 /// Return whether this function has an instantiation-dependent exception
3983 /// spec.
3984 bool hasInstantiationDependentExceptionSpec() const;
3985
3986 /// Return the number of types in the exception specification.
3987 unsigned getNumExceptions() const {
3988 return getExceptionSpecType() == EST_Dynamic
3989 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3990 ->NumExceptionType
3991 : 0;
3992 }
3993
3994 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3995 QualType getExceptionType(unsigned i) const {
3996 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3996, __PRETTY_FUNCTION__))
;
3997 return exception_begin()[i];
3998 }
3999
4000 /// Return the expression inside noexcept(expression), or a null pointer
4001 /// if there is none (because the exception spec is not of this form).
4002 Expr *getNoexceptExpr() const {
4003 if (!isComputedNoexcept(getExceptionSpecType()))
4004 return nullptr;
4005 return *getTrailingObjects<Expr *>();
4006 }
4007
4008 /// If this function type has an exception specification which hasn't
4009 /// been determined yet (either because it has not been evaluated or because
4010 /// it has not been instantiated), this is the function whose exception
4011 /// specification is represented by this type.
4012 FunctionDecl *getExceptionSpecDecl() const {
4013 if (getExceptionSpecType() != EST_Uninstantiated &&
4014 getExceptionSpecType() != EST_Unevaluated)
4015 return nullptr;
4016 return getTrailingObjects<FunctionDecl *>()[0];
4017 }
4018
4019 /// If this function type has an uninstantiated exception
4020 /// specification, this is the function whose exception specification
4021 /// should be instantiated to find the exception specification for
4022 /// this type.
4023 FunctionDecl *getExceptionSpecTemplate() const {
4024 if (getExceptionSpecType() != EST_Uninstantiated)
4025 return nullptr;
4026 return getTrailingObjects<FunctionDecl *>()[1];
4027 }
4028
4029 /// Determine whether this function type has a non-throwing exception
4030 /// specification.
4031 CanThrowResult canThrow() const;
4032
4033 /// Determine whether this function type has a non-throwing exception
4034 /// specification. If this depends on template arguments, returns
4035 /// \c ResultIfDependent.
4036 bool isNothrow(bool ResultIfDependent = false) const {
4037 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4038 }
4039
4040 /// Whether this function prototype is variadic.
4041 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4042
4043 /// Determines whether this function prototype contains a
4044 /// parameter pack at the end.
4045 ///
4046 /// A function template whose last parameter is a parameter pack can be
4047 /// called with an arbitrary number of arguments, much like a variadic
4048 /// function.
4049 bool isTemplateVariadic() const;
4050
4051 /// Whether this function prototype has a trailing return type.
4052 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4053
4054 Qualifiers getMethodQuals() const {
4055 if (hasExtQualifiers())
4056 return *getTrailingObjects<Qualifiers>();
4057 else
4058 return getFastTypeQuals();
4059 }
4060
4061 /// Retrieve the ref-qualifier associated with this function type.
4062 RefQualifierKind getRefQualifier() const {
4063 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4064 }
4065
4066 using param_type_iterator = const QualType *;
4067 using param_type_range = llvm::iterator_range<param_type_iterator>;
4068
4069 param_type_range param_types() const {
4070 return param_type_range(param_type_begin(), param_type_end());
4071 }
4072
4073 param_type_iterator param_type_begin() const {
4074 return getTrailingObjects<QualType>();
4075 }
4076
4077 param_type_iterator param_type_end() const {
4078 return param_type_begin() + getNumParams();
4079 }
4080
4081 using exception_iterator = const QualType *;
4082
4083 ArrayRef<QualType> exceptions() const {
4084 return llvm::makeArrayRef(exception_begin(), exception_end());
4085 }
4086
4087 exception_iterator exception_begin() const {
4088 return reinterpret_cast<exception_iterator>(
4089 getTrailingObjects<ExceptionType>());
4090 }
4091
4092 exception_iterator exception_end() const {
4093 return exception_begin() + getNumExceptions();
4094 }
4095
4096 /// Is there any interesting extra information for any of the parameters
4097 /// of this function type?
4098 bool hasExtParameterInfos() const {
4099 return FunctionTypeBits.HasExtParameterInfos;
4100 }
4101
4102 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4103 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4103, __PRETTY_FUNCTION__))
;
4104 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4105 getNumParams());
4106 }
4107
4108 /// Return a pointer to the beginning of the array of extra parameter
4109 /// information, if present, or else null if none of the parameters
4110 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4111 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4112 if (!hasExtParameterInfos())
4113 return nullptr;
4114 return getTrailingObjects<ExtParameterInfo>();
4115 }
4116
4117 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4118 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4118, __PRETTY_FUNCTION__))
;
4119 if (hasExtParameterInfos())
4120 return getTrailingObjects<ExtParameterInfo>()[I];
4121 return ExtParameterInfo();
4122 }
4123
4124 ParameterABI getParameterABI(unsigned I) const {
4125 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4125, __PRETTY_FUNCTION__))
;
4126 if (hasExtParameterInfos())
4127 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4128 return ParameterABI::Ordinary;
4129 }
4130
4131 bool isParamConsumed(unsigned I) const {
4132 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4132, __PRETTY_FUNCTION__))
;
4133 if (hasExtParameterInfos())
4134 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4135 return false;
4136 }
4137
4138 bool isSugared() const { return false; }
4139 QualType desugar() const { return QualType(this, 0); }
4140
4141 void printExceptionSpecification(raw_ostream &OS,
4142 const PrintingPolicy &Policy) const;
4143
4144 static bool classof(const Type *T) {
4145 return T->getTypeClass() == FunctionProto;
4146 }
4147
4148 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4149 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4150 param_type_iterator ArgTys, unsigned NumArgs,
4151 const ExtProtoInfo &EPI, const ASTContext &Context,
4152 bool Canonical);
4153};
4154
4155/// Represents the dependent type named by a dependently-scoped
4156/// typename using declaration, e.g.
4157/// using typename Base<T>::foo;
4158///
4159/// Template instantiation turns these into the underlying type.
4160class UnresolvedUsingType : public Type {
4161 friend class ASTContext; // ASTContext creates these.
4162
4163 UnresolvedUsingTypenameDecl *Decl;
4164
4165 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4166 : Type(UnresolvedUsing, QualType(), true, true, false,
4167 /*ContainsUnexpandedParameterPack=*/false),
4168 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4169
4170public:
4171 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4172
4173 bool isSugared() const { return false; }
4174 QualType desugar() const { return QualType(this, 0); }
4175
4176 static bool classof(const Type *T) {
4177 return T->getTypeClass() == UnresolvedUsing;
4178 }
4179
4180 void Profile(llvm::FoldingSetNodeID &ID) {
4181 return Profile(ID, Decl);
4182 }
4183
4184 static void Profile(llvm::FoldingSetNodeID &ID,
4185 UnresolvedUsingTypenameDecl *D) {
4186 ID.AddPointer(D);
4187 }
4188};
4189
4190class TypedefType : public Type {
4191 TypedefNameDecl *Decl;
4192
4193protected:
4194 friend class ASTContext; // ASTContext creates these.
4195
4196 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4197 : Type(tc, can, can->isDependentType(),
4198 can->isInstantiationDependentType(),
4199 can->isVariablyModifiedType(),
4200 /*ContainsUnexpandedParameterPack=*/false),
4201 Decl(const_cast<TypedefNameDecl*>(D)) {
4202 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4202, __PRETTY_FUNCTION__))
;
4203 }
4204
4205public:
4206 TypedefNameDecl *getDecl() const { return Decl; }
4207
4208 bool isSugared() const { return true; }
4209 QualType desugar() const;
4210
4211 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4212};
4213
4214/// Sugar type that represents a type that was qualified by a qualifier written
4215/// as a macro invocation.
4216class MacroQualifiedType : public Type {
4217 friend class ASTContext; // ASTContext creates these.
4218
4219 QualType UnderlyingTy;
4220 const IdentifierInfo *MacroII;
4221
4222 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4223 const IdentifierInfo *MacroII)
4224 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4225 UnderlyingTy->isInstantiationDependentType(),
4226 UnderlyingTy->isVariablyModifiedType(),
4227 UnderlyingTy->containsUnexpandedParameterPack()),
4228 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4229 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
4230 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
;
4231 }
4232
4233public:
4234 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4235 QualType getUnderlyingType() const { return UnderlyingTy; }
4236
4237 /// Return this attributed type's modified type with no qualifiers attached to
4238 /// it.
4239 QualType getModifiedType() const;
4240
4241 bool isSugared() const { return true; }
4242 QualType desugar() const;
4243
4244 static bool classof(const Type *T) {
4245 return T->getTypeClass() == MacroQualified;
4246 }
4247};
4248
4249/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4250class TypeOfExprType : public Type {
4251 Expr *TOExpr;
4252
4253protected:
4254 friend class ASTContext; // ASTContext creates these.
4255
4256 TypeOfExprType(Expr *E, QualType can = QualType());
4257
4258public:
4259 Expr *getUnderlyingExpr() const { return TOExpr; }
4260
4261 /// Remove a single level of sugar.
4262 QualType desugar() const;
4263
4264 /// Returns whether this type directly provides sugar.
4265 bool isSugared() const;
4266
4267 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4268};
4269
4270/// Internal representation of canonical, dependent
4271/// `typeof(expr)` types.
4272///
4273/// This class is used internally by the ASTContext to manage
4274/// canonical, dependent types, only. Clients will only see instances
4275/// of this class via TypeOfExprType nodes.
4276class DependentTypeOfExprType
4277 : public TypeOfExprType, public llvm::FoldingSetNode {
4278 const ASTContext &Context;
4279
4280public:
4281 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4282 : TypeOfExprType(E), Context(Context) {}
4283
4284 void Profile(llvm::FoldingSetNodeID &ID) {
4285 Profile(ID, Context, getUnderlyingExpr());
4286 }
4287
4288 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4289 Expr *E);
4290};
4291
4292/// Represents `typeof(type)`, a GCC extension.
4293class TypeOfType : public Type {
4294 friend class ASTContext; // ASTContext creates these.
4295
4296 QualType TOType;
4297
4298 TypeOfType(QualType T, QualType can)
4299 : Type(TypeOf, can, T->isDependentType(),
4300 T->isInstantiationDependentType(),
4301 T->isVariablyModifiedType(),
4302 T->containsUnexpandedParameterPack()),
4303 TOType(T) {
4304 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4304, __PRETTY_FUNCTION__))
;
4305 }
4306
4307public:
4308 QualType getUnderlyingType() const { return TOType; }
4309
4310 /// Remove a single level of sugar.
4311 QualType desugar() const { return getUnderlyingType(); }
4312
4313 /// Returns whether this type directly provides sugar.
4314 bool isSugared() const { return true; }
4315
4316 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4317};
4318
4319/// Represents the type `decltype(expr)` (C++11).
4320class DecltypeType : public Type {
4321 Expr *E;
4322 QualType UnderlyingType;
4323
4324protected:
4325 friend class ASTContext; // ASTContext creates these.
4326
4327 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4328
4329public:
4330 Expr *getUnderlyingExpr() const { return E; }
4331 QualType getUnderlyingType() const { return UnderlyingType; }
4332
4333 /// Remove a single level of sugar.
4334 QualType desugar() const;
4335
4336 /// Returns whether this type directly provides sugar.
4337 bool isSugared() const;
4338
4339 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4340};
4341
4342/// Internal representation of canonical, dependent
4343/// decltype(expr) types.
4344///
4345/// This class is used internally by the ASTContext to manage
4346/// canonical, dependent types, only. Clients will only see instances
4347/// of this class via DecltypeType nodes.
4348class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4349 const ASTContext &Context;
4350
4351public:
4352 DependentDecltypeType(const ASTContext &Context, Expr *E);
4353
4354 void Profile(llvm::FoldingSetNodeID &ID) {
4355 Profile(ID, Context, getUnderlyingExpr());
4356 }
4357
4358 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4359 Expr *E);
4360};
4361
4362/// A unary type transform, which is a type constructed from another.
4363class UnaryTransformType : public Type {
4364public:
4365 enum UTTKind {
4366 EnumUnderlyingType
4367 };
4368
4369private:
4370 /// The untransformed type.
4371 QualType BaseType;
4372
4373 /// The transformed type if not dependent, otherwise the same as BaseType.
4374 QualType UnderlyingType;
4375
4376 UTTKind UKind;
4377
4378protected:
4379 friend class ASTContext;
4380
4381 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4382 QualType CanonicalTy);
4383
4384public:
4385 bool isSugared() const { return !isDependentType(); }
4386 QualType desugar() const { return UnderlyingType; }
4387
4388 QualType getUnderlyingType() const { return UnderlyingType; }
4389 QualType getBaseType() const { return BaseType; }
4390
4391 UTTKind getUTTKind() const { return UKind; }
4392
4393 static bool classof(const Type *T) {
4394 return T->getTypeClass() == UnaryTransform;
4395 }
4396};
4397
4398/// Internal representation of canonical, dependent
4399/// __underlying_type(type) types.
4400///
4401/// This class is used internally by the ASTContext to manage
4402/// canonical, dependent types, only. Clients will only see instances
4403/// of this class via UnaryTransformType nodes.
4404class DependentUnaryTransformType : public UnaryTransformType,
4405 public llvm::FoldingSetNode {
4406public:
4407 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4408 UTTKind UKind);
4409
4410 void Profile(llvm::FoldingSetNodeID &ID) {
4411 Profile(ID, getBaseType(), getUTTKind());
4412 }
4413
4414 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4415 UTTKind UKind) {
4416 ID.AddPointer(BaseType.getAsOpaquePtr());
4417 ID.AddInteger((unsigned)UKind);
4418 }
4419};
4420
4421class TagType : public Type {
4422 friend class ASTReader;
4423
4424 /// Stores the TagDecl associated with this type. The decl may point to any
4425 /// TagDecl that declares the entity.
4426 TagDecl *decl;
4427
4428protected:
4429 TagType(TypeClass TC, const TagDecl *D, QualType can);
4430
4431public:
4432 TagDecl *getDecl() const;
4433
4434 /// Determines whether this type is in the process of being defined.
4435 bool isBeingDefined() const;
4436
4437 static bool classof(const Type *T) {
4438 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4439 }
4440};
4441
4442/// A helper class that allows the use of isa/cast/dyncast
4443/// to detect TagType objects of structs/unions/classes.
4444class RecordType : public TagType {
4445protected:
4446 friend class ASTContext; // ASTContext creates these.
4447
4448 explicit RecordType(const RecordDecl *D)
4449 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4450 explicit RecordType(TypeClass TC, RecordDecl *D)
4451 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4452
4453public:
4454 RecordDecl *getDecl() const {
4455 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4456 }
4457
4458 /// Recursively check all fields in the record for const-ness. If any field
4459 /// is declared const, return true. Otherwise, return false.
4460 bool hasConstFields() const;
4461
4462 bool isSugared() const { return false; }
4463 QualType desugar() const { return QualType(this, 0); }
4464
4465 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4466};
4467
4468/// A helper class that allows the use of isa/cast/dyncast
4469/// to detect TagType objects of enums.
4470class EnumType : public TagType {
4471 friend class ASTContext; // ASTContext creates these.
4472
4473 explicit EnumType(const EnumDecl *D)
4474 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4475
4476public:
4477 EnumDecl *getDecl() const {
4478 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4479 }
4480
4481 bool isSugared() const { return false; }
4482 QualType desugar() const { return QualType(this, 0); }
4483
4484 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4485};
4486
4487/// An attributed type is a type to which a type attribute has been applied.
4488///
4489/// The "modified type" is the fully-sugared type to which the attributed
4490/// type was applied; generally it is not canonically equivalent to the
4491/// attributed type. The "equivalent type" is the minimally-desugared type
4492/// which the type is canonically equivalent to.
4493///
4494/// For example, in the following attributed type:
4495/// int32_t __attribute__((vector_size(16)))
4496/// - the modified type is the TypedefType for int32_t
4497/// - the equivalent type is VectorType(16, int32_t)
4498/// - the canonical type is VectorType(16, int)
4499class AttributedType : public Type, public llvm::FoldingSetNode {
4500public:
4501 using Kind = attr::Kind;
4502
4503private:
4504 friend class ASTContext; // ASTContext creates these
4505
4506 QualType ModifiedType;
4507 QualType EquivalentType;
4508
4509 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4510 QualType equivalent)
4511 : Type(Attributed, canon, equivalent->isDependentType(),
4512 equivalent->isInstantiationDependentType(),
4513 equivalent->isVariablyModifiedType(),
4514 equivalent->containsUnexpandedParameterPack()),
4515 ModifiedType(modified), EquivalentType(equivalent) {
4516 AttributedTypeBits.AttrKind = attrKind;
4517 }
4518
4519public:
4520 Kind getAttrKind() const {
4521 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4522 }
4523
4524 QualType getModifiedType() const { return ModifiedType; }
4525 QualType getEquivalentType() const { return EquivalentType; }
4526
4527 bool isSugared() const { return true; }
4528 QualType desugar() const { return getEquivalentType(); }
4529
4530 /// Does this attribute behave like a type qualifier?
4531 ///
4532 /// A type qualifier adjusts a type to provide specialized rules for
4533 /// a specific object, like the standard const and volatile qualifiers.
4534 /// This includes attributes controlling things like nullability,
4535 /// address spaces, and ARC ownership. The value of the object is still
4536 /// largely described by the modified type.
4537 ///
4538 /// In contrast, many type attributes "rewrite" their modified type to
4539 /// produce a fundamentally different type, not necessarily related in any
4540 /// formalizable way to the original type. For example, calling convention
4541 /// and vector attributes are not simple type qualifiers.
4542 ///
4543 /// Type qualifiers are often, but not always, reflected in the canonical
4544 /// type.
4545 bool isQualifier() const;
4546
4547 bool isMSTypeSpec() const;
4548
4549 bool isCallingConv() const;
4550
4551 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4552
4553 /// Retrieve the attribute kind corresponding to the given
4554 /// nullability kind.
4555 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4556 switch (kind) {
4557 case NullabilityKind::NonNull:
4558 return attr::TypeNonNull;
4559
4560 case NullabilityKind::Nullable:
4561 return attr::TypeNullable;
4562
4563 case NullabilityKind::Unspecified:
4564 return attr::TypeNullUnspecified;
4565 }
4566 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4566)
;
4567 }
4568
4569 /// Strip off the top-level nullability annotation on the given
4570 /// type, if it's there.
4571 ///
4572 /// \param T The type to strip. If the type is exactly an
4573 /// AttributedType specifying nullability (without looking through
4574 /// type sugar), the nullability is returned and this type changed
4575 /// to the underlying modified type.
4576 ///
4577 /// \returns the top-level nullability, if present.
4578 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4579
4580 void Profile(llvm::FoldingSetNodeID &ID) {
4581 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4582 }
4583
4584 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4585 QualType modified, QualType equivalent) {
4586 ID.AddInteger(attrKind);
4587 ID.AddPointer(modified.getAsOpaquePtr());
4588 ID.AddPointer(equivalent.getAsOpaquePtr());
4589 }
4590
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == Attributed;
4593 }
4594};
4595
4596class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4597 friend class ASTContext; // ASTContext creates these
4598
4599 // Helper data collector for canonical types.
4600 struct CanonicalTTPTInfo {
4601 unsigned Depth : 15;
4602 unsigned ParameterPack : 1;
4603 unsigned Index : 16;
4604 };
4605
4606 union {
4607 // Info for the canonical type.
4608 CanonicalTTPTInfo CanTTPTInfo;
4609
4610 // Info for the non-canonical type.
4611 TemplateTypeParmDecl *TTPDecl;
4612 };
4613
4614 /// Build a non-canonical type.
4615 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4616 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4617 /*InstantiationDependent=*/true,
4618 /*VariablyModified=*/false,
4619 Canon->containsUnexpandedParameterPack()),
4620 TTPDecl(TTPDecl) {}
4621
4622 /// Build the canonical type.
4623 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4624 : Type(TemplateTypeParm, QualType(this, 0),
4625 /*Dependent=*/true,
4626 /*InstantiationDependent=*/true,
4627 /*VariablyModified=*/false, PP) {
4628 CanTTPTInfo.Depth = D;
4629 CanTTPTInfo.Index = I;
4630 CanTTPTInfo.ParameterPack = PP;
4631 }
4632
4633 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4634 QualType Can = getCanonicalTypeInternal();
4635 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4636 }
4637
4638public:
4639 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4640 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4641 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4642
4643 TemplateTypeParmDecl *getDecl() const {
4644 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4645 }
4646
4647 IdentifierInfo *getIdentifier() const;
4648
4649 bool isSugared() const { return false; }
4650 QualType desugar() const { return QualType(this, 0); }
4651
4652 void Profile(llvm::FoldingSetNodeID &ID) {
4653 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4654 }
4655
4656 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4657 unsigned Index, bool ParameterPack,
4658 TemplateTypeParmDecl *TTPDecl) {
4659 ID.AddInteger(Depth);
4660 ID.AddInteger(Index);
4661 ID.AddBoolean(ParameterPack);
4662 ID.AddPointer(TTPDecl);
4663 }
4664
4665 static bool classof(const Type *T) {
4666 return T->getTypeClass() == TemplateTypeParm;
4667 }
4668};
4669
4670/// Represents the result of substituting a type for a template
4671/// type parameter.
4672///
4673/// Within an instantiated template, all template type parameters have
4674/// been replaced with these. They are used solely to record that a
4675/// type was originally written as a template type parameter;
4676/// therefore they are never canonical.
4677class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4678 friend class ASTContext;
4679
4680 // The original type parameter.
4681 const TemplateTypeParmType *Replaced;
4682
4683 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4684 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4685 Canon->isInstantiationDependentType(),
4686 Canon->isVariablyModifiedType(),
4687 Canon->containsUnexpandedParameterPack()),
4688 Replaced(Param) {}
4689
4690public:
4691 /// Gets the template parameter that was substituted for.
4692 const TemplateTypeParmType *getReplacedParameter() const {
4693 return Replaced;
4694 }
4695
4696 /// Gets the type that was substituted for the template
4697 /// parameter.
4698 QualType getReplacementType() const {
4699 return getCanonicalTypeInternal();
4700 }
4701
4702 bool isSugared() const { return true; }
4703 QualType desugar() const { return getReplacementType(); }
4704
4705 void Profile(llvm::FoldingSetNodeID &ID) {
4706 Profile(ID, getReplacedParameter(), getReplacementType());
4707 }
4708
4709 static void Profile(llvm::FoldingSetNodeID &ID,
4710 const TemplateTypeParmType *Replaced,
4711 QualType Replacement) {
4712 ID.AddPointer(Replaced);
4713 ID.AddPointer(Replacement.getAsOpaquePtr());
4714 }
4715
4716 static bool classof(const Type *T) {
4717 return T->getTypeClass() == SubstTemplateTypeParm;
4718 }
4719};
4720
4721/// Represents the result of substituting a set of types for a template
4722/// type parameter pack.
4723///
4724/// When a pack expansion in the source code contains multiple parameter packs
4725/// and those parameter packs correspond to different levels of template
4726/// parameter lists, this type node is used to represent a template type
4727/// parameter pack from an outer level, which has already had its argument pack
4728/// substituted but that still lives within a pack expansion that itself
4729/// could not be instantiated. When actually performing a substitution into
4730/// that pack expansion (e.g., when all template parameters have corresponding
4731/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4732/// at the current pack substitution index.
4733class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4734 friend class ASTContext;
4735
4736 /// The original type parameter.
4737 const TemplateTypeParmType *Replaced;
4738
4739 /// A pointer to the set of template arguments that this
4740 /// parameter pack is instantiated with.
4741 const TemplateArgument *Arguments;
4742
4743 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4744 QualType Canon,
4745 const TemplateArgument &ArgPack);
4746
4747public:
4748 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4749
4750 /// Gets the template parameter that was substituted for.
4751 const TemplateTypeParmType *getReplacedParameter() const {
4752 return Replaced;
4753 }
4754
4755 unsigned getNumArgs() const {
4756 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4757 }
4758
4759 bool isSugared() const { return false; }
4760 QualType desugar() const { return QualType(this, 0); }
4761
4762 TemplateArgument getArgumentPack() const;
4763
4764 void Profile(llvm::FoldingSetNodeID &ID);
4765 static void Profile(llvm::FoldingSetNodeID &ID,
4766 const TemplateTypeParmType *Replaced,
4767 const TemplateArgument &ArgPack);
4768
4769 static bool classof(const Type *T) {
4770 return T->getTypeClass() == SubstTemplateTypeParmPack;
4771 }
4772};
4773
4774/// Common base class for placeholders for types that get replaced by
4775/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4776/// class template types, and (eventually) constrained type names from the C++
4777/// Concepts TS.
4778///
4779/// These types are usually a placeholder for a deduced type. However, before
4780/// the initializer is attached, or (usually) if the initializer is
4781/// type-dependent, there is no deduced type and the type is canonical. In
4782/// the latter case, it is also a dependent type.
4783class DeducedType : public Type {
4784protected:
4785 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4786 bool IsInstantiationDependent, bool ContainsParameterPack)
4787 : Type(TC,
4788 // FIXME: Retain the sugared deduced type?
4789 DeducedAsType.isNull() ? QualType(this, 0)
4790 : DeducedAsType.getCanonicalType(),
4791 IsDependent, IsInstantiationDependent,
4792 /*VariablyModified=*/false, ContainsParameterPack) {
4793 if (!DeducedAsType.isNull()) {
4794 if (DeducedAsType->isDependentType())
4795 setDependent();
4796 if (DeducedAsType->isInstantiationDependentType())
4797 setInstantiationDependent();
4798 if (DeducedAsType->containsUnexpandedParameterPack())
4799 setContainsUnexpandedParameterPack();
4800 }
4801 }
4802
4803public:
4804 bool isSugared() const { return !isCanonicalUnqualified(); }
4805 QualType desugar() const { return getCanonicalTypeInternal(); }
4806
4807 /// Get the type deduced for this placeholder type, or null if it's
4808 /// either not been deduced or was deduced to a dependent type.
4809 QualType getDeducedType() const {
4810 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4811 }
4812 bool isDeduced() const {
4813 return !isCanonicalUnqualified() || isDependentType();
4814 }
4815
4816 static bool classof(const Type *T) {
4817 return T->getTypeClass() == Auto ||
4818 T->getTypeClass() == DeducedTemplateSpecialization;
4819 }
4820};
4821
4822/// Represents a C++11 auto or C++14 decltype(auto) type.
4823class AutoType : public DeducedType, public llvm::FoldingSetNode {
4824 friend class ASTContext; // ASTContext creates these
4825
4826 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4827 bool IsDeducedAsDependent, bool IsDeducedAsPack)
4828 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4829 IsDeducedAsDependent, IsDeducedAsPack) {
4830 AutoTypeBits.Keyword = (unsigned)Keyword;
4831 }
4832
4833public:
4834 bool isDecltypeAuto() const {
4835 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4836 }
4837
4838 AutoTypeKeyword getKeyword() const {
4839 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4840 }
4841
4842 void Profile(llvm::FoldingSetNodeID &ID) {
4843 Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4844 containsUnexpandedParameterPack());
4845 }
4846
4847 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4848 AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4849 ID.AddPointer(Deduced.getAsOpaquePtr());
4850 ID.AddInteger((unsigned)Keyword);
4851 ID.AddBoolean(IsDependent);
4852 ID.AddBoolean(IsPack);
4853 }
4854
4855 static bool classof(const Type *T) {
4856 return T->getTypeClass() == Auto;
4857 }
4858};
4859
4860/// Represents a C++17 deduced template specialization type.
4861class DeducedTemplateSpecializationType : public DeducedType,
4862 public llvm::FoldingSetNode {
4863 friend class ASTContext; // ASTContext creates these
4864
4865 /// The name of the template whose arguments will be deduced.
4866 TemplateName Template;
4867
4868 DeducedTemplateSpecializationType(TemplateName Template,
4869 QualType DeducedAsType,
4870 bool IsDeducedAsDependent)
4871 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4872 IsDeducedAsDependent || Template.isDependent(),
4873 IsDeducedAsDependent || Template.isInstantiationDependent(),
4874 Template.containsUnexpandedParameterPack()),
4875 Template(Template) {}
4876
4877public:
4878 /// Retrieve the name of the template that we are deducing.
4879 TemplateName getTemplateName() const { return Template;}
4880
4881 void Profile(llvm::FoldingSetNodeID &ID) {
4882 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4883 }
4884
4885 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4886 QualType Deduced, bool IsDependent) {
4887 Template.Profile(ID);
4888 ID.AddPointer(Deduced.getAsOpaquePtr());
4889 ID.AddBoolean(IsDependent);
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == DeducedTemplateSpecialization;
4894 }
4895};
4896
4897/// Represents a type template specialization; the template
4898/// must be a class template, a type alias template, or a template
4899/// template parameter. A template which cannot be resolved to one of
4900/// these, e.g. because it is written with a dependent scope
4901/// specifier, is instead represented as a
4902/// @c DependentTemplateSpecializationType.
4903///
4904/// A non-dependent template specialization type is always "sugar",
4905/// typically for a \c RecordType. For example, a class template
4906/// specialization type of \c vector<int> will refer to a tag type for
4907/// the instantiation \c std::vector<int, std::allocator<int>>
4908///
4909/// Template specializations are dependent if either the template or
4910/// any of the template arguments are dependent, in which case the
4911/// type may also be canonical.
4912///
4913/// Instances of this type are allocated with a trailing array of
4914/// TemplateArguments, followed by a QualType representing the
4915/// non-canonical aliased type when the template is a type alias
4916/// template.
4917class alignas(8) TemplateSpecializationType
4918 : public Type,
4919 public llvm::FoldingSetNode {
4920 friend class ASTContext; // ASTContext creates these
4921
4922 /// The name of the template being specialized. This is
4923 /// either a TemplateName::Template (in which case it is a
4924 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4925 /// TypeAliasTemplateDecl*), a
4926 /// TemplateName::SubstTemplateTemplateParmPack, or a
4927 /// TemplateName::SubstTemplateTemplateParm (in which case the
4928 /// replacement must, recursively, be one of these).
4929 TemplateName Template;
4930
4931 TemplateSpecializationType(TemplateName T,
4932 ArrayRef<TemplateArgument> Args,
4933 QualType Canon,
4934 QualType Aliased);
4935
4936public:
4937 /// Determine whether any of the given template arguments are dependent.
4938 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4939 bool &InstantiationDependent);
4940
4941 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4942 bool &InstantiationDependent);
4943
4944 /// True if this template specialization type matches a current
4945 /// instantiation in the context in which it is found.
4946 bool isCurrentInstantiation() const {
4947 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4948 }
4949
4950 /// Determine if this template specialization type is for a type alias
4951 /// template that has been substituted.
4952 ///
4953 /// Nearly every template specialization type whose template is an alias
4954 /// template will be substituted. However, this is not the case when
4955 /// the specialization contains a pack expansion but the template alias
4956 /// does not have a corresponding parameter pack, e.g.,
4957 ///
4958 /// \code
4959 /// template<typename T, typename U, typename V> struct S;
4960 /// template<typename T, typename U> using A = S<T, int, U>;
4961 /// template<typename... Ts> struct X {
4962 /// typedef A<Ts...> type; // not a type alias
4963 /// };
4964 /// \endcode
4965 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4966
4967 /// Get the aliased type, if this is a specialization of a type alias
4968 /// template.
4969 QualType getAliasedType() const {
4970 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4970, __PRETTY_FUNCTION__))
;
4971 return *reinterpret_cast<const QualType*>(end());
4972 }
4973
4974 using iterator = const TemplateArgument *;
4975
4976 iterator begin() const { return getArgs(); }
4977 iterator end() const; // defined inline in TemplateBase.h
4978
4979 /// Retrieve the name of the template that we are specializing.
4980 TemplateName getTemplateName() const { return Template; }
4981
4982 /// Retrieve the template arguments.
4983 const TemplateArgument *getArgs() const {
4984 return reinterpret_cast<const TemplateArgument *>(this + 1);
4985 }
4986
4987 /// Retrieve the number of template arguments.
4988 unsigned getNumArgs() const {
4989 return TemplateSpecializationTypeBits.NumArgs;
4990 }
4991
4992 /// Retrieve a specific template argument as a type.
4993 /// \pre \c isArgType(Arg)
4994 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4995
4996 ArrayRef<TemplateArgument> template_arguments() const {
4997 return {getArgs(), getNumArgs()};
4998 }
4999
5000 bool isSugared() const {
5001 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5002 }
5003
5004 QualType desugar() const {
5005 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5006 }
5007
5008 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5009 Profile(ID, Template, template_arguments(), Ctx);
5010 if (isTypeAlias())
5011 getAliasedType().Profile(ID);
5012 }
5013
5014 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5015 ArrayRef<TemplateArgument> Args,
5016 const ASTContext &Context);
5017
5018 static bool classof(const Type *T) {
5019 return T->getTypeClass() == TemplateSpecialization;
5020 }
5021};
5022
5023/// Print a template argument list, including the '<' and '>'
5024/// enclosing the template arguments.
5025void printTemplateArgumentList(raw_ostream &OS,
5026 ArrayRef<TemplateArgument> Args,
5027 const PrintingPolicy &Policy);
5028
5029void printTemplateArgumentList(raw_ostream &OS,
5030 ArrayRef<TemplateArgumentLoc> Args,
5031 const PrintingPolicy &Policy);
5032
5033void printTemplateArgumentList(raw_ostream &OS,
5034 const TemplateArgumentListInfo &Args,
5035 const PrintingPolicy &Policy);
5036
5037/// The injected class name of a C++ class template or class
5038/// template partial specialization. Used to record that a type was
5039/// spelled with a bare identifier rather than as a template-id; the
5040/// equivalent for non-templated classes is just RecordType.
5041///
5042/// Injected class name types are always dependent. Template
5043/// instantiation turns these into RecordTypes.
5044///
5045/// Injected class name types are always canonical. This works
5046/// because it is impossible to compare an injected class name type
5047/// with the corresponding non-injected template type, for the same
5048/// reason that it is impossible to directly compare template
5049/// parameters from different dependent contexts: injected class name
5050/// types can only occur within the scope of a particular templated
5051/// declaration, and within that scope every template specialization
5052/// will canonicalize to the injected class name (when appropriate
5053/// according to the rules of the language).
5054class InjectedClassNameType : public Type {
5055 friend class ASTContext; // ASTContext creates these.
5056 friend class ASTNodeImporter;
5057 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5058 // currently suitable for AST reading, too much
5059 // interdependencies.
5060
5061 CXXRecordDecl *Decl;
5062
5063 /// The template specialization which this type represents.
5064 /// For example, in
5065 /// template <class T> class A { ... };
5066 /// this is A<T>, whereas in
5067 /// template <class X, class Y> class A<B<X,Y> > { ... };
5068 /// this is A<B<X,Y> >.
5069 ///
5070 /// It is always unqualified, always a template specialization type,
5071 /// and always dependent.
5072 QualType InjectedType;
5073
5074 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5075 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5076 /*InstantiationDependent=*/true,
5077 /*VariablyModified=*/false,
5078 /*ContainsUnexpandedParameterPack=*/false),
5079 Decl(D), InjectedType(TST) {
5080 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5080, __PRETTY_FUNCTION__))
;
5081 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5081, __PRETTY_FUNCTION__))
;
5082 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5082, __PRETTY_FUNCTION__))
;
5083 }
5084
5085public:
5086 QualType getInjectedSpecializationType() const { return InjectedType; }
5087
5088 const TemplateSpecializationType *getInjectedTST() const {
5089 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5090 }
5091
5092 TemplateName getTemplateName() const {
5093 return getInjectedTST()->getTemplateName();
5094 }
5095
5096 CXXRecordDecl *getDecl() const;
5097
5098 bool isSugared() const { return false; }
5099 QualType desugar() const { return QualType(this, 0); }
5100
5101 static bool classof(const Type *T) {
5102 return T->getTypeClass() == InjectedClassName;
5103 }
5104};
5105
5106/// The kind of a tag type.
5107enum TagTypeKind {
5108 /// The "struct" keyword.
5109 TTK_Struct,
5110
5111 /// The "__interface" keyword.
5112 TTK_Interface,
5113
5114 /// The "union" keyword.
5115 TTK_Union,
5116
5117 /// The "class" keyword.
5118 TTK_Class,
5119
5120 /// The "enum" keyword.
5121 TTK_Enum
5122};
5123
5124/// The elaboration keyword that precedes a qualified type name or
5125/// introduces an elaborated-type-specifier.
5126enum ElaboratedTypeKeyword {
5127 /// The "struct" keyword introduces the elaborated-type-specifier.
5128 ETK_Struct,
5129
5130 /// The "__interface" keyword introduces the elaborated-type-specifier.
5131 ETK_Interface,
5132
5133 /// The "union" keyword introduces the elaborated-type-specifier.
5134 ETK_Union,
5135
5136 /// The "class" keyword introduces the elaborated-type-specifier.
5137 ETK_Class,
5138
5139 /// The "enum" keyword introduces the elaborated-type-specifier.
5140 ETK_Enum,
5141
5142 /// The "typename" keyword precedes the qualified type name, e.g.,
5143 /// \c typename T::type.
5144 ETK_Typename,
5145
5146 /// No keyword precedes the qualified type name.
5147 ETK_None
5148};
5149
5150/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5151/// The keyword in stored in the free bits of the base class.
5152/// Also provides a few static helpers for converting and printing
5153/// elaborated type keyword and tag type kind enumerations.
5154class TypeWithKeyword : public Type {
5155protected:
5156 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5157 QualType Canonical, bool Dependent,
5158 bool InstantiationDependent, bool VariablyModified,
5159 bool ContainsUnexpandedParameterPack)
5160 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5161 ContainsUnexpandedParameterPack) {
5162 TypeWithKeywordBits.Keyword = Keyword;
5163 }
5164
5165public:
5166 ElaboratedTypeKeyword getKeyword() const {
5167 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5168 }
5169
5170 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5171 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5172
5173 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5174 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5175 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5176
5177 /// Converts a TagTypeKind into an elaborated type keyword.
5178 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5179
5180 /// Converts an elaborated type keyword into a TagTypeKind.
5181 /// It is an error to provide an elaborated type keyword
5182 /// which *isn't* a tag kind here.
5183 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5184
5185 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5186
5187 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5188
5189 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5190 return getKeywordName(getKeywordForTagTypeKind(Kind));
5191 }
5192
5193 class CannotCastToThisType {};
5194 static CannotCastToThisType classof(const Type *);
5195};
5196
5197/// Represents a type that was referred to using an elaborated type
5198/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5199/// or both.
5200///
5201/// This type is used to keep track of a type name as written in the
5202/// source code, including tag keywords and any nested-name-specifiers.
5203/// The type itself is always "sugar", used to express what was written
5204/// in the source code but containing no additional semantic information.
5205class ElaboratedType final
5206 : public TypeWithKeyword,
5207 public llvm::FoldingSetNode,
5208 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5209 friend class ASTContext; // ASTContext creates these
5210 friend TrailingObjects;
5211
5212 /// The nested name specifier containing the qualifier.
5213 NestedNameSpecifier *NNS;
5214
5215 /// The type that this qualified name refers to.
5216 QualType NamedType;
5217
5218 /// The (re)declaration of this tag type owned by this occurrence is stored
5219 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5220 /// it, or obtain a null pointer if there is none.
5221
5222 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5223 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5224 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5225 NamedType->isDependentType(),
5226 NamedType->isInstantiationDependentType(),
5227 NamedType->isVariablyModifiedType(),
5228 NamedType->containsUnexpandedParameterPack()),
5229 NNS(NNS), NamedType(NamedType) {
5230 ElaboratedTypeBits.HasOwnedTagDecl = false;
5231 if (OwnedTagDecl) {
5232 ElaboratedTypeBits.HasOwnedTagDecl = true;
5233 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5234 }
5235 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5236 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5237 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
;
5238 }
5239
5240public:
5241 /// Retrieve the qualification on this type.
5242 NestedNameSpecifier *getQualifier() const { return NNS; }
5243
5244 /// Retrieve the type named by the qualified-id.
5245 QualType getNamedType() const { return NamedType; }
5246
5247 /// Remove a single level of sugar.
5248 QualType desugar() const { return getNamedType(); }
5249
5250 /// Returns whether this type directly provides sugar.
5251 bool isSugared() const { return true; }
5252
5253 /// Return the (re)declaration of this type owned by this occurrence of this
5254 /// type, or nullptr if there is none.
5255 TagDecl *getOwnedTagDecl() const {
5256 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5257 : nullptr;
5258 }
5259
5260 void Profile(llvm::FoldingSetNodeID &ID) {
5261 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5262 }
5263
5264 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5265 NestedNameSpecifier *NNS, QualType NamedType,
5266 TagDecl *OwnedTagDecl) {
5267 ID.AddInteger(Keyword);
5268 ID.AddPointer(NNS);
5269 NamedType.Profile(ID);
5270 ID.AddPointer(OwnedTagDecl);
5271 }
5272
5273 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5274};
5275
5276/// Represents a qualified type name for which the type name is
5277/// dependent.
5278///
5279/// DependentNameType represents a class of dependent types that involve a
5280/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5281/// name of a type. The DependentNameType may start with a "typename" (for a
5282/// typename-specifier), "class", "struct", "union", or "enum" (for a
5283/// dependent elaborated-type-specifier), or nothing (in contexts where we
5284/// know that we must be referring to a type, e.g., in a base class specifier).
5285/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5286/// mode, this type is used with non-dependent names to delay name lookup until
5287/// instantiation.
5288class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5289 friend class ASTContext; // ASTContext creates these
5290
5291 /// The nested name specifier containing the qualifier.
5292 NestedNameSpecifier *NNS;
5293
5294 /// The type that this typename specifier refers to.
5295 const IdentifierInfo *Name;
5296
5297 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5298 const IdentifierInfo *Name, QualType CanonType)
5299 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5300 /*InstantiationDependent=*/true,
5301 /*VariablyModified=*/false,
5302 NNS->containsUnexpandedParameterPack()),
5303 NNS(NNS), Name(Name) {}
5304
5305public:
5306 /// Retrieve the qualification on this type.
5307 NestedNameSpecifier *getQualifier() const { return NNS; }
5308
5309 /// Retrieve the type named by the typename specifier as an identifier.
5310 ///
5311 /// This routine will return a non-NULL identifier pointer when the
5312 /// form of the original typename was terminated by an identifier,
5313 /// e.g., "typename T::type".
5314 const IdentifierInfo *getIdentifier() const {
5315 return Name;
5316 }
5317
5318 bool isSugared() const { return false; }
5319 QualType desugar() const { return QualType(this, 0); }
5320
5321 void Profile(llvm::FoldingSetNodeID &ID) {
5322 Profile(ID, getKeyword(), NNS, Name);
5323 }
5324
5325 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5326 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5327 ID.AddInteger(Keyword);
5328 ID.AddPointer(NNS);
5329 ID.AddPointer(Name);
5330 }
5331
5332 static bool classof(const Type *T) {
5333 return T->getTypeClass() == DependentName;
5334 }
5335};
5336
5337/// Represents a template specialization type whose template cannot be
5338/// resolved, e.g.
5339/// A<T>::template B<T>
5340class alignas(8) DependentTemplateSpecializationType
5341 : public TypeWithKeyword,
5342 public llvm::FoldingSetNode {
5343 friend class ASTContext; // ASTContext creates these
5344
5345 /// The nested name specifier containing the qualifier.
5346 NestedNameSpecifier *NNS;
5347
5348 /// The identifier of the template.
5349 const IdentifierInfo *Name;
5350
5351 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5352 NestedNameSpecifier *NNS,
5353 const IdentifierInfo *Name,
5354 ArrayRef<TemplateArgument> Args,
5355 QualType Canon);
5356
5357 const TemplateArgument *getArgBuffer() const {
5358 return reinterpret_cast<const TemplateArgument*>(this+1);
5359 }
5360
5361 TemplateArgument *getArgBuffer() {
5362 return reinterpret_cast<TemplateArgument*>(this+1);
5363 }
5364
5365public:
5366 NestedNameSpecifier *getQualifier() const { return NNS; }
5367 const IdentifierInfo *getIdentifier() const { return Name; }
5368
5369 /// Retrieve the template arguments.
5370 const TemplateArgument *getArgs() const {
5371 return getArgBuffer();
5372 }
5373
5374 /// Retrieve the number of template arguments.
5375 unsigned getNumArgs() const {
5376 return DependentTemplateSpecializationTypeBits.NumArgs;
5377 }
5378
5379 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5380
5381 ArrayRef<TemplateArgument> template_arguments() const {
5382 return {getArgs(), getNumArgs()};
5383 }
5384
5385 using iterator = const TemplateArgument *;
5386
5387 iterator begin() const { return getArgs(); }
5388 iterator end() const; // inline in TemplateBase.h
5389
5390 bool isSugared() const { return false; }
5391 QualType desugar() const { return QualType(this, 0); }
5392
5393 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5394 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5395 }
5396
5397 static void Profile(llvm::FoldingSetNodeID &ID,
5398 const ASTContext &Context,
5399 ElaboratedTypeKeyword Keyword,
5400 NestedNameSpecifier *Qualifier,
5401 const IdentifierInfo *Name,
5402 ArrayRef<TemplateArgument> Args);
5403
5404 static bool classof(const Type *T) {
5405 return T->getTypeClass() == DependentTemplateSpecialization;
5406 }
5407};
5408
5409/// Represents a pack expansion of types.
5410///
5411/// Pack expansions are part of C++11 variadic templates. A pack
5412/// expansion contains a pattern, which itself contains one or more
5413/// "unexpanded" parameter packs. When instantiated, a pack expansion
5414/// produces a series of types, each instantiated from the pattern of
5415/// the expansion, where the Ith instantiation of the pattern uses the
5416/// Ith arguments bound to each of the unexpanded parameter packs. The
5417/// pack expansion is considered to "expand" these unexpanded
5418/// parameter packs.
5419///
5420/// \code
5421/// template<typename ...Types> struct tuple;
5422///
5423/// template<typename ...Types>
5424/// struct tuple_of_references {
5425/// typedef tuple<Types&...> type;
5426/// };
5427/// \endcode
5428///
5429/// Here, the pack expansion \c Types&... is represented via a
5430/// PackExpansionType whose pattern is Types&.
5431class PackExpansionType : public Type, public llvm::FoldingSetNode {
5432 friend class ASTContext; // ASTContext creates these
5433
5434 /// The pattern of the pack expansion.
5435 QualType Pattern;
5436
5437 PackExpansionType(QualType Pattern, QualType Canon,
5438 Optional<unsigned> NumExpansions)
5439 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5440 /*InstantiationDependent=*/true,
5441 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5442 /*ContainsUnexpandedParameterPack=*/false),
5443 Pattern(Pattern) {
5444 PackExpansionTypeBits.NumExpansions =
5445 NumExpansions ? *NumExpansions + 1 : 0;
5446 }
5447
5448public:
5449 /// Retrieve the pattern of this pack expansion, which is the
5450 /// type that will be repeatedly instantiated when instantiating the
5451 /// pack expansion itself.
5452 QualType getPattern() const { return Pattern; }
5453
5454 /// Retrieve the number of expansions that this pack expansion will
5455 /// generate, if known.
5456 Optional<unsigned> getNumExpansions() const {
5457 if (PackExpansionTypeBits.NumExpansions)
5458 return PackExpansionTypeBits.NumExpansions - 1;
5459 return None;
5460 }
5461
5462 bool isSugared() const { return !Pattern->isDependentType(); }
5463 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5464
5465 void Profile(llvm::FoldingSetNodeID &ID) {
5466 Profile(ID, getPattern(), getNumExpansions());
5467 }
5468
5469 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5470 Optional<unsigned> NumExpansions) {
5471 ID.AddPointer(Pattern.getAsOpaquePtr());
5472 ID.AddBoolean(NumExpansions.hasValue());
5473 if (NumExpansions)
5474 ID.AddInteger(*NumExpansions);
5475 }
5476
5477 static bool classof(const Type *T) {
5478 return T->getTypeClass() == PackExpansion;
5479 }
5480};
5481
5482/// This class wraps the list of protocol qualifiers. For types that can
5483/// take ObjC protocol qualifers, they can subclass this class.
5484template <class T>
5485class ObjCProtocolQualifiers {
5486protected:
5487 ObjCProtocolQualifiers() = default;
5488
5489 ObjCProtocolDecl * const *getProtocolStorage() const {
5490 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5491 }
5492
5493 ObjCProtocolDecl **getProtocolStorage() {
5494 return static_cast<T*>(this)->getProtocolStorageImpl();
5495 }
5496
5497 void setNumProtocols(unsigned N) {
5498 static_cast<T*>(this)->setNumProtocolsImpl(N);
5499 }
5500
5501 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5502 setNumProtocols(protocols.size());
5503 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
5504 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
;
5505 if (!protocols.empty())
5506 memcpy(getProtocolStorage(), protocols.data(),
5507 protocols.size() * sizeof(ObjCProtocolDecl*));
5508 }
5509
5510public:
5511 using qual_iterator = ObjCProtocolDecl * const *;
5512 using qual_range = llvm::iterator_range<qual_iterator>;
5513
5514 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5515 qual_iterator qual_begin() const { return getProtocolStorage(); }
5516 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5517
5518 bool qual_empty() const { return getNumProtocols() == 0; }
5519
5520 /// Return the number of qualifying protocols in this type, or 0 if
5521 /// there are none.
5522 unsigned getNumProtocols() const {
5523 return static_cast<const T*>(this)->getNumProtocolsImpl();
5524 }
5525
5526 /// Fetch a protocol by index.
5527 ObjCProtocolDecl *getProtocol(unsigned I) const {
5528 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5528, __PRETTY_FUNCTION__))
;
5529 return qual_begin()[I];
5530 }
5531
5532 /// Retrieve all of the protocol qualifiers.
5533 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5534 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5535 }
5536};
5537
5538/// Represents a type parameter type in Objective C. It can take
5539/// a list of protocols.
5540class ObjCTypeParamType : public Type,
5541 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5542 public llvm::FoldingSetNode {
5543 friend class ASTContext;
5544 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5545
5546 /// The number of protocols stored on this type.
5547 unsigned NumProtocols : 6;
5548
5549 ObjCTypeParamDecl *OTPDecl;
5550
5551 /// The protocols are stored after the ObjCTypeParamType node. In the
5552 /// canonical type, the list of protocols are sorted alphabetically
5553 /// and uniqued.
5554 ObjCProtocolDecl **getProtocolStorageImpl();
5555
5556 /// Return the number of qualifying protocols in this interface type,
5557 /// or 0 if there are none.
5558 unsigned getNumProtocolsImpl() const {
5559 return NumProtocols;
5560 }
5561
5562 void setNumProtocolsImpl(unsigned N) {
5563 NumProtocols = N;
5564 }
5565
5566 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5567 QualType can,
5568 ArrayRef<ObjCProtocolDecl *> protocols);
5569
5570public:
5571 bool isSugared() const { return true; }
5572 QualType desugar() const { return getCanonicalTypeInternal(); }
5573
5574 static bool classof(const Type *T) {
5575 return T->getTypeClass() == ObjCTypeParam;
5576 }
5577
5578 void Profile(llvm::FoldingSetNodeID &ID);
5579 static void Profile(llvm::FoldingSetNodeID &ID,
5580 const ObjCTypeParamDecl *OTPDecl,
5581 ArrayRef<ObjCProtocolDecl *> protocols);
5582
5583 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5584};
5585
5586/// Represents a class type in Objective C.
5587///
5588/// Every Objective C type is a combination of a base type, a set of
5589/// type arguments (optional, for parameterized classes) and a list of
5590/// protocols.
5591///
5592/// Given the following declarations:
5593/// \code
5594/// \@class C<T>;
5595/// \@protocol P;
5596/// \endcode
5597///
5598/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5599/// with base C and no protocols.
5600///
5601/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5602/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5603/// protocol list.
5604/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5605/// and protocol list [P].
5606///
5607/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5608/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5609/// and no protocols.
5610///
5611/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5612/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5613/// this should get its own sugar class to better represent the source.
5614class ObjCObjectType : public Type,
5615 public ObjCProtocolQualifiers<ObjCObjectType> {
5616 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5617
5618 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5619 // after the ObjCObjectPointerType node.
5620 // ObjCObjectType.NumProtocols - the number of protocols stored
5621 // after the type arguments of ObjCObjectPointerType node.
5622 //
5623 // These protocols are those written directly on the type. If
5624 // protocol qualifiers ever become additive, the iterators will need
5625 // to get kindof complicated.
5626 //
5627 // In the canonical object type, these are sorted alphabetically
5628 // and uniqued.
5629
5630 /// Either a BuiltinType or an InterfaceType or sugar for either.
5631 QualType BaseType;
5632
5633 /// Cached superclass type.
5634 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5635 CachedSuperClassType;
5636
5637 QualType *getTypeArgStorage();
5638 const QualType *getTypeArgStorage() const {
5639 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5640 }
5641
5642 ObjCProtocolDecl **getProtocolStorageImpl();
5643 /// Return the number of qualifying protocols in this interface type,
5644 /// or 0 if there are none.
5645 unsigned getNumProtocolsImpl() const {
5646 return ObjCObjectTypeBits.NumProtocols;
5647 }
5648 void setNumProtocolsImpl(unsigned N) {
5649 ObjCObjectTypeBits.NumProtocols = N;
5650 }
5651
5652protected:
5653 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5654
5655 ObjCObjectType(QualType Canonical, QualType Base,
5656 ArrayRef<QualType> typeArgs,
5657 ArrayRef<ObjCProtocolDecl *> protocols,
5658 bool isKindOf);
5659
5660 ObjCObjectType(enum Nonce_ObjCInterface)
5661 : Type(ObjCInterface, QualType(), false, false, false, false),
5662 BaseType(QualType(this_(), 0)) {
5663 ObjCObjectTypeBits.NumProtocols = 0;
5664 ObjCObjectTypeBits.NumTypeArgs = 0;
5665 ObjCObjectTypeBits.IsKindOf = 0;
5666 }
5667
5668 void computeSuperClassTypeSlow() const;
5669
5670public:
5671 /// Gets the base type of this object type. This is always (possibly
5672 /// sugar for) one of:
5673 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5674 /// user, which is a typedef for an ObjCObjectPointerType)
5675 /// - the 'Class' builtin type (same caveat)
5676 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5677 QualType getBaseType() const { return BaseType; }
5678
5679 bool isObjCId() const {
5680 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5681 }
5682
5683 bool isObjCClass() const {
5684 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5685 }
5686
5687 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5688 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5689 bool isObjCUnqualifiedIdOrClass() const {
5690 if (!qual_empty()) return false;
5691 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5692 return T->getKind() == BuiltinType::ObjCId ||
5693 T->getKind() == BuiltinType::ObjCClass;
5694 return false;
5695 }
5696 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5697 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5698
5699 /// Gets the interface declaration for this object type, if the base type
5700 /// really is an interface.
5701 ObjCInterfaceDecl *getInterface() const;
5702
5703 /// Determine whether this object type is "specialized", meaning
5704 /// that it has type arguments.
5705 bool isSpecialized() const;
5706
5707 /// Determine whether this object type was written with type arguments.
5708 bool isSpecializedAsWritten() const {
5709 return ObjCObjectTypeBits.NumTypeArgs > 0;
5710 }
5711
5712 /// Determine whether this object type is "unspecialized", meaning
5713 /// that it has no type arguments.
5714 bool isUnspecialized() const { return !isSpecialized(); }
5715
5716 /// Determine whether this object type is "unspecialized" as
5717 /// written, meaning that it has no type arguments.
5718 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5719
5720 /// Retrieve the type arguments of this object type (semantically).
5721 ArrayRef<QualType> getTypeArgs() const;
5722
5723 /// Retrieve the type arguments of this object type as they were
5724 /// written.
5725 ArrayRef<QualType> getTypeArgsAsWritten() const {
5726 return llvm::makeArrayRef(getTypeArgStorage(),
5727 ObjCObjectTypeBits.NumTypeArgs);
5728 }
5729
5730 /// Whether this is a "__kindof" type as written.
5731 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5732
5733 /// Whether this ia a "__kindof" type (semantically).
5734 bool isKindOfType() const;
5735
5736 /// Retrieve the type of the superclass of this object type.
5737 ///
5738 /// This operation substitutes any type arguments into the
5739 /// superclass of the current class type, potentially producing a
5740 /// specialization of the superclass type. Produces a null type if
5741 /// there is no superclass.
5742 QualType getSuperClassType() const {
5743 if (!CachedSuperClassType.getInt())
5744 computeSuperClassTypeSlow();
5745
5746 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5746, __PRETTY_FUNCTION__))
;
5747 return QualType(CachedSuperClassType.getPointer(), 0);
5748 }
5749
5750 /// Strip off the Objective-C "kindof" type and (with it) any
5751 /// protocol qualifiers.
5752 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5753
5754 bool isSugared() const { return false; }
5755 QualType desugar() const { return QualType(this, 0); }
5756
5757 static bool classof(const Type *T) {
5758 return T->getTypeClass() == ObjCObject ||
5759 T->getTypeClass() == ObjCInterface;
5760 }
5761};
5762
5763/// A class providing a concrete implementation
5764/// of ObjCObjectType, so as to not increase the footprint of
5765/// ObjCInterfaceType. Code outside of ASTContext and the core type
5766/// system should not reference this type.
5767class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5768 friend class ASTContext;
5769
5770 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5771 // will need to be modified.
5772
5773 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5774 ArrayRef<QualType> typeArgs,
5775 ArrayRef<ObjCProtocolDecl *> protocols,
5776 bool isKindOf)
5777 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5778
5779public:
5780 void Profile(llvm::FoldingSetNodeID &ID);
5781 static void Profile(llvm::FoldingSetNodeID &ID,
5782 QualType Base,
5783 ArrayRef<QualType> typeArgs,
5784 ArrayRef<ObjCProtocolDecl *> protocols,
5785 bool isKindOf);
5786};
5787
5788inline QualType *ObjCObjectType::getTypeArgStorage() {
5789 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5790}
5791
5792inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5793 return reinterpret_cast<ObjCProtocolDecl**>(
5794 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5795}
5796
5797inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5798 return reinterpret_cast<ObjCProtocolDecl**>(
5799 static_cast<ObjCTypeParamType*>(this)+1);
5800}
5801
5802/// Interfaces are the core concept in Objective-C for object oriented design.
5803/// They basically correspond to C++ classes. There are two kinds of interface
5804/// types: normal interfaces like `NSString`, and qualified interfaces, which
5805/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5806///
5807/// ObjCInterfaceType guarantees the following properties when considered
5808/// as a subtype of its superclass, ObjCObjectType:
5809/// - There are no protocol qualifiers. To reinforce this, code which
5810/// tries to invoke the protocol methods via an ObjCInterfaceType will
5811/// fail to compile.
5812/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5813/// T->getBaseType() == QualType(T, 0).
5814class ObjCInterfaceType : public ObjCObjectType {
5815 friend class ASTContext; // ASTContext creates these.
5816 friend class ASTReader;
5817 friend class ObjCInterfaceDecl;
5818
5819 mutable ObjCInterfaceDecl *Decl;
5820
5821 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5822 : ObjCObjectType(Nonce_ObjCInterface),
5823 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5824
5825public:
5826 /// Get the declaration of this interface.
5827 ObjCInterfaceDecl *getDecl() const { return Decl; }
5828
5829 bool isSugared() const { return false; }
5830 QualType desugar() const { return QualType(this, 0); }
5831
5832 static bool classof(const Type *T) {
5833 return T->getTypeClass() == ObjCInterface;
5834 }
5835
5836 // Nonsense to "hide" certain members of ObjCObjectType within this
5837 // class. People asking for protocols on an ObjCInterfaceType are
5838 // not going to get what they want: ObjCInterfaceTypes are
5839 // guaranteed to have no protocols.
5840 enum {
5841 qual_iterator,
5842 qual_begin,
5843 qual_end,
5844 getNumProtocols,
5845 getProtocol
5846 };
5847};
5848
5849inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5850 QualType baseType = getBaseType();
5851 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5852 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5853 return T->getDecl();
5854
5855 baseType = ObjT->getBaseType();
5856 }
5857
5858 return nullptr;
5859}
5860
5861/// Represents a pointer to an Objective C object.
5862///
5863/// These are constructed from pointer declarators when the pointee type is
5864/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5865/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5866/// and 'Class<P>' are translated into these.
5867///
5868/// Pointers to pointers to Objective C objects are still PointerTypes;
5869/// only the first level of pointer gets it own type implementation.
5870class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5871 friend class ASTContext; // ASTContext creates these.
5872
5873 QualType PointeeType;
5874
5875 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5876 : Type(ObjCObjectPointer, Canonical,
5877 Pointee->isDependentType(),
5878 Pointee->isInstantiationDependentType(),
5879 Pointee->isVariablyModifiedType(),
5880 Pointee->containsUnexpandedParameterPack()),
5881 PointeeType(Pointee) {}
5882
5883public:
5884 /// Gets the type pointed to by this ObjC pointer.
5885 /// The result will always be an ObjCObjectType or sugar thereof.
5886 QualType getPointeeType() const { return PointeeType; }
5887
5888 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5889 ///
5890 /// This method is equivalent to getPointeeType() except that
5891 /// it discards any typedefs (or other sugar) between this
5892 /// type and the "outermost" object type. So for:
5893 /// \code
5894 /// \@class A; \@protocol P; \@protocol Q;
5895 /// typedef A<P> AP;
5896 /// typedef A A1;
5897 /// typedef A1<P> A1P;
5898 /// typedef A1P<Q> A1PQ;
5899 /// \endcode
5900 /// For 'A*', getObjectType() will return 'A'.
5901 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5902 /// For 'AP*', getObjectType() will return 'A<P>'.
5903 /// For 'A1*', getObjectType() will return 'A'.
5904 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5905 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5906 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5907 /// adding protocols to a protocol-qualified base discards the
5908 /// old qualifiers (for now). But if it didn't, getObjectType()
5909 /// would return 'A1P<Q>' (and we'd have to make iterating over
5910 /// qualifiers more complicated).
5911 const ObjCObjectType *getObjectType() const {
5912 return PointeeType->castAs<ObjCObjectType>();
5913 }
5914
5915 /// If this pointer points to an Objective C
5916 /// \@interface type, gets the type for that interface. Any protocol
5917 /// qualifiers on the interface are ignored.
5918 ///
5919 /// \return null if the base type for this pointer is 'id' or 'Class'
5920 const ObjCInterfaceType *getInterfaceType() const;
5921
5922 /// If this pointer points to an Objective \@interface
5923 /// type, gets the declaration for that interface.
5924 ///
5925 /// \return null if the base type for this pointer is 'id' or 'Class'
5926 ObjCInterfaceDecl *getInterfaceDecl() const {
5927 return getObjectType()->getInterface();
5928 }
5929
5930 /// True if this is equivalent to the 'id' type, i.e. if
5931 /// its object type is the primitive 'id' type with no protocols.
5932 bool isObjCIdType() const {
5933 return getObjectType()->isObjCUnqualifiedId();
5934 }
5935
5936 /// True if this is equivalent to the 'Class' type,
5937 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5938 bool isObjCClassType() const {
5939 return getObjectType()->isObjCUnqualifiedClass();
5940 }
5941
5942 /// True if this is equivalent to the 'id' or 'Class' type,
5943 bool isObjCIdOrClassType() const {
5944 return getObjectType()->isObjCUnqualifiedIdOrClass();
5945 }
5946
5947 /// True if this is equivalent to 'id<P>' for some non-empty set of
5948 /// protocols.
5949 bool isObjCQualifiedIdType() const {
5950 return getObjectType()->isObjCQualifiedId();
5951 }
5952
5953 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5954 /// protocols.
5955 bool isObjCQualifiedClassType() const {
5956 return getObjectType()->isObjCQualifiedClass();
5957 }
5958
5959 /// Whether this is a "__kindof" type.
5960 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5961
5962 /// Whether this type is specialized, meaning that it has type arguments.
5963 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5964
5965 /// Whether this type is specialized, meaning that it has type arguments.
5966 bool isSpecializedAsWritten() const {
5967 return getObjectType()->isSpecializedAsWritten();
5968 }
5969
5970 /// Whether this type is unspecialized, meaning that is has no type arguments.
5971 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5972
5973 /// Determine whether this object type is "unspecialized" as
5974 /// written, meaning that it has no type arguments.
5975 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5976
5977 /// Retrieve the type arguments for this type.
5978 ArrayRef<QualType> getTypeArgs() const {
5979 return getObjectType()->getTypeArgs();
5980 }
5981
5982 /// Retrieve the type arguments for this type.
5983 ArrayRef<QualType> getTypeArgsAsWritten() const {
5984 return getObjectType()->getTypeArgsAsWritten();
5985 }
5986
5987 /// An iterator over the qualifiers on the object type. Provided
5988 /// for convenience. This will always iterate over the full set of
5989 /// protocols on a type, not just those provided directly.
5990 using qual_iterator = ObjCObjectType::qual_iterator;
5991 using qual_range = llvm::iterator_range<qual_iterator>;
5992
5993 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5994
5995 qual_iterator qual_begin() const {
5996 return getObjectType()->qual_begin();
5997 }
5998
5999 qual_iterator qual_end() const {
6000 return getObjectType()->qual_end();
6001 }
6002
6003 bool qual_empty() const { return getObjectType()->qual_empty(); }
6004
6005 /// Return the number of qualifying protocols on the object type.
6006 unsigned getNumProtocols() const {
6007 return getObjectType()->getNumProtocols();
6008 }
6009
6010 /// Retrieve a qualifying protocol by index on the object type.
6011 ObjCProtocolDecl *getProtocol(unsigned I) const {
6012 return getObjectType()->getProtocol(I);
6013 }
6014
6015 bool isSugared() const { return false; }
6016 QualType desugar() const { return QualType(this, 0); }
6017
6018 /// Retrieve the type of the superclass of this object pointer type.
6019 ///
6020 /// This operation substitutes any type arguments into the
6021 /// superclass of the current class type, potentially producing a
6022 /// pointer to a specialization of the superclass type. Produces a
6023 /// null type if there is no superclass.
6024 QualType getSuperClassType() const;
6025
6026 /// Strip off the Objective-C "kindof" type and (with it) any
6027 /// protocol qualifiers.
6028 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6029 const ASTContext &ctx) const;
6030
6031 void Profile(llvm::FoldingSetNodeID &ID) {
6032 Profile(ID, getPointeeType());
6033 }
6034
6035 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6036 ID.AddPointer(T.getAsOpaquePtr());
6037 }
6038
6039 static bool classof(const Type *T) {
6040 return T->getTypeClass() == ObjCObjectPointer;
6041 }
6042};
6043
6044class AtomicType : public Type, public llvm::FoldingSetNode {
6045 friend class ASTContext; // ASTContext creates these.
6046
6047 QualType ValueType;
6048
6049 AtomicType(QualType ValTy, QualType Canonical)
6050 : Type(Atomic, Canonical, ValTy->isDependentType(),
6051 ValTy->isInstantiationDependentType(),
6052 ValTy->isVariablyModifiedType(),
6053 ValTy->containsUnexpandedParameterPack()),
6054 ValueType(ValTy) {}
6055
6056public:
6057 /// Gets the type contained by this atomic type, i.e.
6058 /// the type returned by performing an atomic load of this atomic type.
6059 QualType getValueType() const { return ValueType; }
6060
6061 bool isSugared() const { return false; }
6062 QualType desugar() const { return QualType(this, 0); }
6063
6064 void Profile(llvm::FoldingSetNodeID &ID) {
6065 Profile(ID, getValueType());
6066 }
6067
6068 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6069 ID.AddPointer(T.getAsOpaquePtr());
6070 }
6071
6072 static bool classof(const Type *T) {
6073 return T->getTypeClass() == Atomic;
6074 }
6075};
6076
6077/// PipeType - OpenCL20.
6078class PipeType : public Type, public llvm::FoldingSetNode {
6079 friend class ASTContext; // ASTContext creates these.
6080
6081 QualType ElementType;
6082 bool isRead;
6083
6084 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6085 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6086 elemType->isInstantiationDependentType(),
6087 elemType->isVariablyModifiedType(),
6088 elemType->containsUnexpandedParameterPack()),
6089 ElementType(elemType), isRead(isRead) {}
6090
6091public:
6092 QualType getElementType() const { return ElementType; }
6093
6094 bool isSugared() const { return false; }
6095
6096 QualType desugar() const { return QualType(this, 0); }
6097
6098 void Profile(llvm::FoldingSetNodeID &ID) {
6099 Profile(ID, getElementType(), isReadOnly());
6100 }
6101
6102 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6103 ID.AddPointer(T.getAsOpaquePtr());
6104 ID.AddBoolean(isRead);
6105 }
6106
6107 static bool classof(const Type *T) {
6108 return T->getTypeClass() == Pipe;
6109 }
6110
6111 bool isReadOnly() const { return isRead; }
6112};
6113
6114/// A qualifier set is used to build a set of qualifiers.
6115class QualifierCollector : public Qualifiers {
6116public:
6117 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6118
6119 /// Collect any qualifiers on the given type and return an
6120 /// unqualified type. The qualifiers are assumed to be consistent
6121 /// with those already in the type.
6122 const Type *strip(QualType type) {
6123 addFastQualifiers(type.getLocalFastQualifiers());
6124 if (!type.hasLocalNonFastQualifiers())
6125 return type.getTypePtrUnsafe();
6126
6127 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6128 addConsistentQualifiers(extQuals->getQualifiers());
6129 return extQuals->getBaseType();
6130 }
6131
6132 /// Apply the collected qualifiers to the given type.
6133 QualType apply(const ASTContext &Context, QualType QT) const;
6134
6135 /// Apply the collected qualifiers to the given type.
6136 QualType apply(const ASTContext &Context, const Type* T) const;
6137};
6138
6139// Inline function definitions.
6140
6141inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6142 SplitQualType desugar =
6143 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6144 desugar.Quals.addConsistentQualifiers(Quals);
6145 return desugar;
6146}
6147
6148inline const Type *QualType::getTypePtr() const {
6149 return getCommonPtr()->BaseType;
6150}
6151
6152inline const Type *QualType::getTypePtrOrNull() const {
6153 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6154}
6155
6156inline SplitQualType QualType::split() const {
6157 if (!hasLocalNonFastQualifiers())
6158 return SplitQualType(getTypePtrUnsafe(),
6159 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6160
6161 const ExtQuals *eq = getExtQualsUnsafe();
6162 Qualifiers qs = eq->getQualifiers();
6163 qs.addFastQualifiers(getLocalFastQualifiers());
6164 return SplitQualType(eq->getBaseType(), qs);
6165}
6166
6167inline Qualifiers QualType::getLocalQualifiers() const {
6168 Qualifiers Quals;
6169 if (hasLocalNonFastQualifiers())
6170 Quals = getExtQualsUnsafe()->getQualifiers();
6171 Quals.addFastQualifiers(getLocalFastQualifiers());
6172 return Quals;
6173}
6174
6175inline Qualifiers QualType::getQualifiers() const {
6176 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6177 quals.addFastQualifiers(getLocalFastQualifiers());
6178 return quals;
6179}
6180
6181inline unsigned QualType::getCVRQualifiers() const {
6182 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6183 cvr |= getLocalCVRQualifiers();
6184 return cvr;
6185}
6186
6187inline QualType QualType::getCanonicalType() const {
6188 QualType canon = getCommonPtr()->CanonicalType;
6189 return canon.withFastQualifiers(getLocalFastQualifiers());
6190}
6191
6192inline bool QualType::isCanonical() const {
6193 return getTypePtr()->isCanonicalUnqualified();
6194}
6195
6196inline bool QualType::isCanonicalAsParam() const {
6197 if (!isCanonical()) return false;
6198 if (hasLocalQualifiers()) return false;
6199
6200 const Type *T = getTypePtr();
6201 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6202 return false;
6203
6204 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6205}
6206
6207inline bool QualType::isConstQualified() const {
6208 return isLocalConstQualified() ||
6209 getCommonPtr()->CanonicalType.isLocalConstQualified();
6210}
6211
6212inline bool QualType::isRestrictQualified() const {
6213 return isLocalRestrictQualified() ||
6214 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6215}
6216
6217
6218inline bool QualType::isVolatileQualified() const {
6219 return isLocalVolatileQualified() ||
6220 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6221}
6222
6223inline bool QualType::hasQualifiers() const {
6224 return hasLocalQualifiers() ||
6225 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6226}
6227
6228inline QualType QualType::getUnqualifiedType() const {
6229 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6230 return QualType(getTypePtr(), 0);
6231
6232 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6233}
6234
6235inline SplitQualType QualType::getSplitUnqualifiedType() const {
6236 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6237 return split();
6238
6239 return getSplitUnqualifiedTypeImpl(*this);
6240}
6241
6242inline void QualType::removeLocalConst() {
6243 removeLocalFastQualifiers(Qualifiers::Const);
6244}
6245
6246inline void QualType::removeLocalRestrict() {
6247 removeLocalFastQualifiers(Qualifiers::Restrict);
6248}
6249
6250inline void QualType::removeLocalVolatile() {
6251 removeLocalFastQualifiers(Qualifiers::Volatile);
6252}
6253
6254inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6255 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6255, __PRETTY_FUNCTION__))
;
6256 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6257 "Fast bits differ from CVR bits!");
6258
6259 // Fast path: we don't need to touch the slow qualifiers.
6260 removeLocalFastQualifiers(Mask);
6261}
6262
6263/// Return the address space of this type.
6264inline LangAS QualType::getAddressSpace() const {
6265 return getQualifiers().getAddressSpace();
6266}
6267
6268/// Return the gc attribute of this type.
6269inline Qualifiers::GC QualType::getObjCGCAttr() const {
6270 return getQualifiers().getObjCGCAttr();
6271}
6272
6273inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6274 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6275 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6276 return false;
6277}
6278
6279inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6280 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6281 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6282 return false;
6283}
6284
6285inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6286 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6287 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6288 return false;
6289}
6290
6291inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6292 if (const auto *PT = t.getAs<PointerType>()) {
6293 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6294 return FT->getExtInfo();
6295 } else if (const auto *FT = t.getAs<FunctionType>())
6296 return FT->getExtInfo();
6297
6298 return FunctionType::ExtInfo();
6299}
6300
6301inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6302 return getFunctionExtInfo(*t);
6303}
6304
6305/// Determine whether this type is more
6306/// qualified than the Other type. For example, "const volatile int"
6307/// is more qualified than "const int", "volatile int", and
6308/// "int". However, it is not more qualified than "const volatile
6309/// int".
6310inline bool QualType::isMoreQualifiedThan(QualType other) const {
6311 Qualifiers MyQuals = getQualifiers();
6312 Qualifiers OtherQuals = other.getQualifiers();
6313 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6314}
6315
6316/// Determine whether this type is at last
6317/// as qualified as the Other type. For example, "const volatile
6318/// int" is at least as qualified as "const int", "volatile int",
6319/// "int", and "const volatile int".
6320inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6321 Qualifiers OtherQuals = other.getQualifiers();
6322
6323 // Ignore __unaligned qualifier if this type is a void.
6324 if (getUnqualifiedType()->isVoidType())
6325 OtherQuals.removeUnaligned();
6326
6327 return getQualifiers().compatiblyIncludes(OtherQuals);
6328}
6329
6330/// If Type is a reference type (e.g., const
6331/// int&), returns the type that the reference refers to ("const
6332/// int"). Otherwise, returns the type itself. This routine is used
6333/// throughout Sema to implement C++ 5p6:
6334///
6335/// If an expression initially has the type "reference to T" (8.3.2,
6336/// 8.5.3), the type is adjusted to "T" prior to any further
6337/// analysis, the expression designates the object or function
6338/// denoted by the reference, and the expression is an lvalue.
6339inline QualType QualType::getNonReferenceType() const {
6340 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6341 return RefType->getPointeeType();
6342 else
6343 return *this;
6344}
6345
6346inline bool QualType::isCForbiddenLValueType() const {
6347 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6348 getTypePtr()->isFunctionType());
6349}
6350
6351/// Tests whether the type is categorized as a fundamental type.
6352///
6353/// \returns True for types specified in C++0x [basic.fundamental].
6354inline bool Type::isFundamentalType() const {
6355 return isVoidType() ||
6356 isNullPtrType() ||
6357 // FIXME: It's really annoying that we don't have an
6358 // 'isArithmeticType()' which agrees with the standard definition.
6359 (isArithmeticType() && !isEnumeralType());
6360}
6361
6362/// Tests whether the type is categorized as a compound type.
6363///
6364/// \returns True for types specified in C++0x [basic.compound].
6365inline bool Type::isCompoundType() const {
6366 // C++0x [basic.compound]p1:
6367 // Compound types can be constructed in the following ways:
6368 // -- arrays of objects of a given type [...];
6369 return isArrayType() ||
6370 // -- functions, which have parameters of given types [...];
6371 isFunctionType() ||
6372 // -- pointers to void or objects or functions [...];
6373 isPointerType() ||
6374 // -- references to objects or functions of a given type. [...]
6375 isReferenceType() ||
6376 // -- classes containing a sequence of objects of various types, [...];
6377 isRecordType() ||
6378 // -- unions, which are classes capable of containing objects of different
6379 // types at different times;
6380 isUnionType() ||
6381 // -- enumerations, which comprise a set of named constant values. [...];
6382 isEnumeralType() ||
6383 // -- pointers to non-static class members, [...].
6384 isMemberPointerType();
6385}
6386
6387inline bool Type::isFunctionType() const {
6388 return isa<FunctionType>(CanonicalType);
6389}
6390
6391inline bool Type::isPointerType() const {
6392 return isa<PointerType>(CanonicalType);
20
Assuming field 'CanonicalType' is a 'PointerType'
21
Returning the value 1, which participates in a condition later
6393}
6394
6395inline bool Type::isAnyPointerType() const {
6396 return isPointerType() || isObjCObjectPointerType();
6397}
6398
6399inline bool Type::isBlockPointerType() const {
6400 return isa<BlockPointerType>(CanonicalType);
6401}
6402
6403inline bool Type::isReferenceType() const {
6404 return isa<ReferenceType>(CanonicalType);
6405}
6406
6407inline bool Type::isLValueReferenceType() const {
6408 return isa<LValueReferenceType>(CanonicalType);
6409}
6410
6411inline bool Type::isRValueReferenceType() const {
6412 return isa<RValueReferenceType>(CanonicalType);
6413}
6414
6415inline bool Type::isFunctionPointerType() const {
6416 if (const auto *T = getAs<PointerType>())
6417 return T->getPointeeType()->isFunctionType();
6418 else
6419 return false;
6420}
6421
6422inline bool Type::isFunctionReferenceType() const {
6423 if (const auto *T = getAs<ReferenceType>())
6424 return T->getPointeeType()->isFunctionType();
6425 else
6426 return false;
6427}
6428
6429inline bool Type::isMemberPointerType() const {
6430 return isa<MemberPointerType>(CanonicalType);
6431}
6432
6433inline bool Type::isMemberFunctionPointerType() const {
6434 if (const auto *T = getAs<MemberPointerType>())
6435 return T->isMemberFunctionPointer();
6436 else
6437 return false;
6438}
6439
6440inline bool Type::isMemberDataPointerType() const {
6441 if (const auto *T = getAs<MemberPointerType>())
6442 return T->isMemberDataPointer();
6443 else
6444 return false;
6445}
6446
6447inline bool Type::isArrayType() const {
6448 return isa<ArrayType>(CanonicalType);
6449}
6450
6451inline bool Type::isConstantArrayType() const {
6452 return isa<ConstantArrayType>(CanonicalType);
6453}
6454
6455inline bool Type::isIncompleteArrayType() const {
6456 return isa<IncompleteArrayType>(CanonicalType);
6457}
6458
6459inline bool Type::isVariableArrayType() const {
6460 return isa<VariableArrayType>(CanonicalType);
6461}
6462
6463inline bool Type::isDependentSizedArrayType() const {
6464 return isa<DependentSizedArrayType>(CanonicalType);
6465}
6466
6467inline bool Type::isBuiltinType() const {
6468 return isa<BuiltinType>(CanonicalType);
6469}
6470
6471inline bool Type::isRecordType() const {
6472 return isa<RecordType>(CanonicalType);
6473}
6474
6475inline bool Type::isEnumeralType() const {
6476 return isa<EnumType>(CanonicalType);
6477}
6478
6479inline bool Type::isAnyComplexType() const {
6480 return isa<ComplexType>(CanonicalType);
6481}
6482
6483inline bool Type::isVectorType() const {
6484 return isa<VectorType>(CanonicalType);
6485}
6486
6487inline bool Type::isExtVectorType() const {
6488 return isa<ExtVectorType>(CanonicalType);
6489}
6490
6491inline bool Type::isDependentAddressSpaceType() const {
6492 return isa<DependentAddressSpaceType>(CanonicalType);
6493}
6494
6495inline bool Type::isObjCObjectPointerType() const {
6496 return isa<ObjCObjectPointerType>(CanonicalType);
6497}
6498
6499inline bool Type::isObjCObjectType() const {
6500 return isa<ObjCObjectType>(CanonicalType);
6501}
6502
6503inline bool Type::isObjCObjectOrInterfaceType() const {
6504 return isa<ObjCInterfaceType>(CanonicalType) ||
6505 isa<ObjCObjectType>(CanonicalType);
6506}
6507
6508inline bool Type::isAtomicType() const {
6509 return isa<AtomicType>(CanonicalType);
6510}
6511
6512inline bool Type::isObjCQualifiedIdType() const {
6513 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6514 return OPT->isObjCQualifiedIdType();
6515 return false;
6516}
6517
6518inline bool Type::isObjCQualifiedClassType() const {
6519 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6520 return OPT->isObjCQualifiedClassType();
6521 return false;
6522}
6523
6524inline bool Type::isObjCIdType() const {
6525 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6526 return OPT->isObjCIdType();
6527 return false;
6528}
6529
6530inline bool Type::isObjCClassType() const {
6531 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6532 return OPT->isObjCClassType();
6533 return false;
6534}
6535
6536inline bool Type::isObjCSelType() const {
6537 if (const auto *OPT = getAs<PointerType>())
6538 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6539 return false;
6540}
6541
6542inline bool Type::isObjCBuiltinType() const {
6543 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6544}
6545
6546inline bool Type::isDecltypeType() const {
6547 return isa<DecltypeType>(this);
6548}
6549
6550#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6551 inline bool Type::is##Id##Type() const { \
6552 return isSpecificBuiltinType(BuiltinType::Id); \
6553 }
6554#include "clang/Basic/OpenCLImageTypes.def"
6555
6556inline bool Type::isSamplerT() const {
6557 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6558}
6559
6560inline bool Type::isEventT() const {
6561 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6562}
6563
6564inline bool Type::isClkEventT() const {
6565 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6566}
6567
6568inline bool Type::isQueueT() const {
6569 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6570}
6571
6572inline bool Type::isReserveIDT() const {
6573 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6574}
6575
6576inline bool Type::isImageType() const {
6577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6578 return
6579#include "clang/Basic/OpenCLImageTypes.def"
6580 false; // end boolean or operation
6581}
6582
6583inline bool Type::isPipeType() const {
6584 return isa<PipeType>(CanonicalType);
6585}
6586
6587#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6588 inline bool Type::is##Id##Type() const { \
6589 return isSpecificBuiltinType(BuiltinType::Id); \
6590 }
6591#include "clang/Basic/OpenCLExtensionTypes.def"
6592
6593inline bool Type::isOCLIntelSubgroupAVCType() const {
6594#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6595 isOCLIntelSubgroupAVC##Id##Type() ||
6596 return
6597#include "clang/Basic/OpenCLExtensionTypes.def"
6598 false; // end of boolean or operation
6599}
6600
6601inline bool Type::isOCLExtOpaqueType() const {
6602#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6603 return
6604#include "clang/Basic/OpenCLExtensionTypes.def"
6605 false; // end of boolean or operation
6606}
6607
6608inline bool Type::isOpenCLSpecificType() const {
6609 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6610 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6611}
6612
6613inline bool Type::isTemplateTypeParmType() const {
6614 return isa<TemplateTypeParmType>(CanonicalType);
6615}
6616
6617inline bool Type::isSpecificBuiltinType(unsigned K) const {
6618 if (const BuiltinType *BT = getAs<BuiltinType>())
6619 if (BT->getKind() == (BuiltinType::Kind) K)
6620 return true;
6621 return false;
6622}
6623
6624inline bool Type::isPlaceholderType() const {
6625 if (const auto *BT = dyn_cast<BuiltinType>(this))
6626 return BT->isPlaceholderType();
6627 return false;
6628}
6629
6630inline const BuiltinType *Type::getAsPlaceholderType() const {
6631 if (const auto *BT = dyn_cast<BuiltinType>(this))
6632 if (BT->isPlaceholderType())
6633 return BT;
6634 return nullptr;
6635}
6636
6637inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6638 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6638, __PRETTY_FUNCTION__))
;
6639 if (const auto *BT = dyn_cast<BuiltinType>(this))
6640 return (BT->getKind() == (BuiltinType::Kind) K);
6641 return false;
6642}
6643
6644inline bool Type::isNonOverloadPlaceholderType() const {
6645 if (const auto *BT = dyn_cast<BuiltinType>(this))
6646 return BT->isNonOverloadPlaceholderType();
6647 return false;
6648}
6649
6650inline bool Type::isVoidType() const {
6651 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6652 return BT->getKind() == BuiltinType::Void;
6653 return false;
6654}
6655
6656inline bool Type::isHalfType() const {
6657 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6658 return BT->getKind() == BuiltinType::Half;
6659 // FIXME: Should we allow complex __fp16? Probably not.
6660 return false;
6661}
6662
6663inline bool Type::isFloat16Type() const {
6664 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6665 return BT->getKind() == BuiltinType::Float16;
6666 return false;
6667}
6668
6669inline bool Type::isFloat128Type() const {
6670 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6671 return BT->getKind() == BuiltinType::Float128;
6672 return false;
6673}
6674
6675inline bool Type::isNullPtrType() const {
6676 if (const auto *BT = getAs<BuiltinType>())
6677 return BT->getKind() == BuiltinType::NullPtr;
6678 return false;
6679}
6680
6681bool IsEnumDeclComplete(EnumDecl *);
6682bool IsEnumDeclScoped(EnumDecl *);
6683
6684inline bool Type::isIntegerType() const {
6685 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6686 return BT->getKind() >= BuiltinType::Bool &&
6687 BT->getKind() <= BuiltinType::Int128;
6688 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6689 // Incomplete enum types are not treated as integer types.
6690 // FIXME: In C++, enum types are never integer types.
6691 return IsEnumDeclComplete(ET->getDecl()) &&
6692 !IsEnumDeclScoped(ET->getDecl());
6693 }
6694 return false;
6695}
6696
6697inline bool Type::isFixedPointType() const {
6698 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6699 return BT->getKind() >= BuiltinType::ShortAccum &&
6700 BT->getKind() <= BuiltinType::SatULongFract;
6701 }
6702 return false;
6703}
6704
6705inline bool Type::isFixedPointOrIntegerType() const {
6706 return isFixedPointType() || isIntegerType();
6707}
6708
6709inline bool Type::isSaturatedFixedPointType() const {
6710 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6711 return BT->getKind() >= BuiltinType::SatShortAccum &&
6712 BT->getKind() <= BuiltinType::SatULongFract;
6713 }
6714 return false;
6715}
6716
6717inline bool Type::isUnsaturatedFixedPointType() const {
6718 return isFixedPointType() && !isSaturatedFixedPointType();
6719}
6720
6721inline bool Type::isSignedFixedPointType() const {
6722 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6723 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6724 BT->getKind() <= BuiltinType::LongAccum) ||
6725 (BT->getKind() >= BuiltinType::ShortFract &&
6726 BT->getKind() <= BuiltinType::LongFract) ||
6727 (BT->getKind() >= BuiltinType::SatShortAccum &&
6728 BT->getKind() <= BuiltinType::SatLongAccum) ||
6729 (BT->getKind() >= BuiltinType::SatShortFract &&
6730 BT->getKind() <= BuiltinType::SatLongFract));
6731 }
6732 return false;
6733}
6734
6735inline bool Type::isUnsignedFixedPointType() const {
6736 return isFixedPointType() && !isSignedFixedPointType();
6737}
6738
6739inline bool Type::isScalarType() const {
6740 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6741 return BT->getKind() > BuiltinType::Void &&
6742 BT->getKind() <= BuiltinType::NullPtr;
6743 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6744 // Enums are scalar types, but only if they are defined. Incomplete enums
6745 // are not treated as scalar types.
6746 return IsEnumDeclComplete(ET->getDecl());
6747 return isa<PointerType>(CanonicalType) ||
6748 isa<BlockPointerType>(CanonicalType) ||
6749 isa<MemberPointerType>(CanonicalType) ||
6750 isa<ComplexType>(CanonicalType) ||
6751 isa<ObjCObjectPointerType>(CanonicalType);
6752}
6753
6754inline bool Type::isIntegralOrEnumerationType() const {
6755 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6756 return BT->getKind() >= BuiltinType::Bool &&
6757 BT->getKind() <= BuiltinType::Int128;
6758
6759 // Check for a complete enum type; incomplete enum types are not properly an
6760 // enumeration type in the sense required here.
6761 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6762 return IsEnumDeclComplete(ET->getDecl());
6763
6764 return false;
6765}
6766
6767inline bool Type::isBooleanType() const {
6768 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6769 return BT->getKind() == BuiltinType::Bool;
6770 return false;
6771}
6772
6773inline bool Type::isUndeducedType() const {
6774 auto *DT = getContainedDeducedType();
6775 return DT && !DT->isDeduced();
6776}
6777
6778/// Determines whether this is a type for which one can define
6779/// an overloaded operator.
6780inline bool Type::isOverloadableType() const {
6781 return isDependentType() || isRecordType() || isEnumeralType();
6782}
6783
6784/// Determines whether this type can decay to a pointer type.
6785inline bool Type::canDecayToPointerType() const {
6786 return isFunctionType() || isArrayType();
6787}
6788
6789inline bool Type::hasPointerRepresentation() const {
6790 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6791 isObjCObjectPointerType() || isNullPtrType());
6792}
6793
6794inline bool Type::hasObjCPointerRepresentation() const {
6795 return isObjCObjectPointerType();
6796}
6797
6798inline const Type *Type::getBaseElementTypeUnsafe() const {
6799 const Type *type = this;
6800 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6801 type = arrayType->getElementType().getTypePtr();
6802 return type;
6803}
6804
6805inline const Type *Type::getPointeeOrArrayElementType() const {
6806 const Type *type = this;
6807 if (type->isAnyPointerType())
6808 return type->getPointeeType().getTypePtr();
6809 else if (type->isArrayType())
6810 return type->getBaseElementTypeUnsafe();
6811 return type;
6812}
6813
6814/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6815/// diagnostic with <<.
6816inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6817 Qualifiers Q) {
6818 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6819 DiagnosticsEngine::ArgumentKind::ak_qual);
6820 return DB;
6821}
6822
6823/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6824/// into a diagnostic with <<.
6825inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6826 Qualifiers Q) {
6827 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6828 DiagnosticsEngine::ArgumentKind::ak_qual);
6829 return PD;
6830}
6831
6832/// Insertion operator for diagnostics. This allows sending QualType's into a
6833/// diagnostic with <<.
6834inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6835 QualType T) {
6836 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6837 DiagnosticsEngine::ak_qualtype);
6838 return DB;
6839}
6840
6841/// Insertion operator for partial diagnostics. This allows sending QualType's
6842/// into a diagnostic with <<.
6843inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6844 QualType T) {
6845 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6846 DiagnosticsEngine::ak_qualtype);
6847 return PD;
6848}
6849
6850// Helper class template that is used by Type::getAs to ensure that one does
6851// not try to look through a qualified type to get to an array type.
6852template <typename T>
6853using TypeIsArrayType =
6854 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6855 std::is_base_of<ArrayType, T>::value>;
6856
6857// Member-template getAs<specific type>'.
6858template <typename T> const T *Type::getAs() const {
6859 static_assert(!TypeIsArrayType<T>::value,
6860 "ArrayType cannot be used with getAs!");
6861
6862 // If this is directly a T type, return it.
6863 if (const auto *Ty = dyn_cast<T>(this))
6864 return Ty;
6865
6866 // If the canonical form of this type isn't the right kind, reject it.
6867 if (!isa<T>(CanonicalType))
6868 return nullptr;
6869
6870 // If this is a typedef for the type, strip the typedef off without
6871 // losing all typedef information.
6872 return cast<T>(getUnqualifiedDesugaredType());
6873}
6874
6875template <typename T> const T *Type::getAsAdjusted() const {
6876 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6877
6878 // If this is directly a T type, return it.
6879 if (const auto *Ty = dyn_cast<T>(this))
6880 return Ty;
6881
6882 // If the canonical form of this type isn't the right kind, reject it.
6883 if (!isa<T>(CanonicalType))
6884 return nullptr;
6885
6886 // Strip off type adjustments that do not modify the underlying nature of the
6887 // type.
6888 const Type *Ty = this;
6889 while (Ty) {
6890 if (const auto *A = dyn_cast<AttributedType>(Ty))
6891 Ty = A->getModifiedType().getTypePtr();
6892 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6893 Ty = E->desugar().getTypePtr();
6894 else if (const auto *P = dyn_cast<ParenType>(Ty))
6895 Ty = P->desugar().getTypePtr();
6896 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6897 Ty = A->desugar().getTypePtr();
6898 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
6899 Ty = M->desugar().getTypePtr();
6900 else
6901 break;
6902 }
6903
6904 // Just because the canonical type is correct does not mean we can use cast<>,
6905 // since we may not have stripped off all the sugar down to the base type.
6906 return dyn_cast<T>(Ty);
6907}
6908
6909inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6910 // If this is directly an array type, return it.
6911 if (const auto *arr = dyn_cast<ArrayType>(this))
6912 return arr;
6913
6914 // If the canonical form of this type isn't the right kind, reject it.
6915 if (!isa<ArrayType>(CanonicalType))
6916 return nullptr;
6917
6918 // If this is a typedef for the type, strip the typedef off without
6919 // losing all typedef information.
6920 return cast<ArrayType>(getUnqualifiedDesugaredType());
6921}
6922
6923template <typename T> const T *Type::castAs() const {
6924 static_assert(!TypeIsArrayType<T>::value,
6925 "ArrayType cannot be used with castAs!");
6926
6927 if (const auto *ty = dyn_cast<T>(this)) return ty;
6928 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6928, __PRETTY_FUNCTION__))
;
6929 return cast<T>(getUnqualifiedDesugaredType());
6930}
6931
6932inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6933 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6933, __PRETTY_FUNCTION__))
;
6934 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6935 return cast<ArrayType>(getUnqualifiedDesugaredType());
6936}
6937
6938DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6939 QualType CanonicalPtr)
6940 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6941#ifndef NDEBUG
6942 QualType Adjusted = getAdjustedType();
6943 (void)AttributedType::stripOuterNullability(Adjusted);
6944 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6944, __PRETTY_FUNCTION__))
;
6945#endif
6946}
6947
6948QualType DecayedType::getPointeeType() const {
6949 QualType Decayed = getDecayedType();
6950 (void)AttributedType::stripOuterNullability(Decayed);
6951 return cast<PointerType>(Decayed)->getPointeeType();
6952}
6953
6954// Get the decimal string representation of a fixed point type, represented
6955// as a scaled integer.
6956// TODO: At some point, we should change the arguments to instead just accept an
6957// APFixedPoint instead of APSInt and scale.
6958void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6959 unsigned Scale);
6960
6961} // namespace clang
6962
6963#endif // LLVM_CLANG_AST_TYPE_H