Bug Summary

File:tools/clang/lib/Sema/SemaExceptionSpec.cpp
Warning:line 268, column 11
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 SemaExceptionSpec.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~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp

1//===--- SemaExceptionSpec.cpp - C++ Exception Specifications ---*- 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// This file provides Sema routines for C++ exception specification testing.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/SemaInternal.h"
14#include "clang/AST/ASTMutationListener.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/TypeLoc.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/SourceManager.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallString.h"
23
24namespace clang {
25
26static const FunctionProtoType *GetUnderlyingFunction(QualType T)
27{
28 if (const PointerType *PtrTy = T->getAs<PointerType>())
29 T = PtrTy->getPointeeType();
30 else if (const ReferenceType *RefTy = T->getAs<ReferenceType>())
31 T = RefTy->getPointeeType();
32 else if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
33 T = MPTy->getPointeeType();
34 return T->getAs<FunctionProtoType>();
35}
36
37/// HACK: libstdc++ has a bug where it shadows std::swap with a member
38/// swap function then tries to call std::swap unqualified from the exception
39/// specification of that function. This function detects whether we're in
40/// such a case and turns off delay-parsing of exception specifications.
41bool Sema::isLibstdcxxEagerExceptionSpecHack(const Declarator &D) {
42 auto *RD = dyn_cast<CXXRecordDecl>(CurContext);
43
44 // All the problem cases are member functions named "swap" within class
45 // templates declared directly within namespace std or std::__debug or
46 // std::__profile.
47 if (!RD || !RD->getIdentifier() || !RD->getDescribedClassTemplate() ||
48 !D.getIdentifier() || !D.getIdentifier()->isStr("swap"))
49 return false;
50
51 auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext());
52 if (!ND)
53 return false;
54
55 bool IsInStd = ND->isStdNamespace();
56 if (!IsInStd) {
57 // This isn't a direct member of namespace std, but it might still be
58 // libstdc++'s std::__debug::array or std::__profile::array.
59 IdentifierInfo *II = ND->getIdentifier();
60 if (!II || !(II->isStr("__debug") || II->isStr("__profile")) ||
61 !ND->isInStdNamespace())
62 return false;
63 }
64
65 // Only apply this hack within a system header.
66 if (!Context.getSourceManager().isInSystemHeader(D.getBeginLoc()))
67 return false;
68
69 return llvm::StringSwitch<bool>(RD->getIdentifier()->getName())
70 .Case("array", true)
71 .Case("pair", IsInStd)
72 .Case("priority_queue", IsInStd)
73 .Case("stack", IsInStd)
74 .Case("queue", IsInStd)
75 .Default(false);
76}
77
78ExprResult Sema::ActOnNoexceptSpec(SourceLocation NoexceptLoc,
79 Expr *NoexceptExpr,
80 ExceptionSpecificationType &EST) {
81 // FIXME: This is bogus, a noexcept expression is not a condition.
82 ExprResult Converted = CheckBooleanCondition(NoexceptLoc, NoexceptExpr);
83 if (Converted.isInvalid())
84 return Converted;
85
86 if (Converted.get()->isValueDependent()) {
87 EST = EST_DependentNoexcept;
88 return Converted;
89 }
90
91 llvm::APSInt Result;
92 Converted = VerifyIntegerConstantExpression(
93 Converted.get(), &Result,
94 diag::err_noexcept_needs_constant_expression,
95 /*AllowFold*/ false);
96 if (!Converted.isInvalid())
97 EST = !Result ? EST_NoexceptFalse : EST_NoexceptTrue;
98 return Converted;
99}
100
101/// CheckSpecifiedExceptionType - Check if the given type is valid in an
102/// exception specification. Incomplete types, or pointers to incomplete types
103/// other than void are not allowed.
104///
105/// \param[in,out] T The exception type. This will be decayed to a pointer type
106/// when the input is an array or a function type.
107bool Sema::CheckSpecifiedExceptionType(QualType &T, SourceRange Range) {
108 // C++11 [except.spec]p2:
109 // A type cv T, "array of T", or "function returning T" denoted
110 // in an exception-specification is adjusted to type T, "pointer to T", or
111 // "pointer to function returning T", respectively.
112 //
113 // We also apply this rule in C++98.
114 if (T->isArrayType())
115 T = Context.getArrayDecayedType(T);
116 else if (T->isFunctionType())
117 T = Context.getPointerType(T);
118
119 int Kind = 0;
120 QualType PointeeT = T;
121 if (const PointerType *PT = T->getAs<PointerType>()) {
122 PointeeT = PT->getPointeeType();
123 Kind = 1;
124
125 // cv void* is explicitly permitted, despite being a pointer to an
126 // incomplete type.
127 if (PointeeT->isVoidType())
128 return false;
129 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
130 PointeeT = RT->getPointeeType();
131 Kind = 2;
132
133 if (RT->isRValueReferenceType()) {
134 // C++11 [except.spec]p2:
135 // A type denoted in an exception-specification shall not denote [...]
136 // an rvalue reference type.
137 Diag(Range.getBegin(), diag::err_rref_in_exception_spec)
138 << T << Range;
139 return true;
140 }
141 }
142
143 // C++11 [except.spec]p2:
144 // A type denoted in an exception-specification shall not denote an
145 // incomplete type other than a class currently being defined [...].
146 // A type denoted in an exception-specification shall not denote a
147 // pointer or reference to an incomplete type, other than (cv) void* or a
148 // pointer or reference to a class currently being defined.
149 // In Microsoft mode, downgrade this to a warning.
150 unsigned DiagID = diag::err_incomplete_in_exception_spec;
151 bool ReturnValueOnError = true;
152 if (getLangOpts().MSVCCompat) {
153 DiagID = diag::ext_incomplete_in_exception_spec;
154 ReturnValueOnError = false;
155 }
156 if (!(PointeeT->isRecordType() &&
157 PointeeT->castAs<RecordType>()->isBeingDefined()) &&
158 RequireCompleteType(Range.getBegin(), PointeeT, DiagID, Kind, Range))
159 return ReturnValueOnError;
160
161 return false;
162}
163
164/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
165/// to member to a function with an exception specification. This means that
166/// it is invalid to add another level of indirection.
167bool Sema::CheckDistantExceptionSpec(QualType T) {
168 // C++17 removes this rule in favor of putting exception specifications into
169 // the type system.
170 if (getLangOpts().CPlusPlus17)
171 return false;
172
173 if (const PointerType *PT = T->getAs<PointerType>())
174 T = PT->getPointeeType();
175 else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
176 T = PT->getPointeeType();
177 else
178 return false;
179
180 const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
181 if (!FnT)
182 return false;
183
184 return FnT->hasExceptionSpec();
185}
186
187const FunctionProtoType *
188Sema::ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT) {
189 if (FPT->getExceptionSpecType() == EST_Unparsed) {
190 Diag(Loc, diag::err_exception_spec_not_parsed);
191 return nullptr;
192 }
193
194 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
195 return FPT;
196
197 FunctionDecl *SourceDecl = FPT->getExceptionSpecDecl();
198 const FunctionProtoType *SourceFPT =
199 SourceDecl->getType()->castAs<FunctionProtoType>();
200
201 // If the exception specification has already been resolved, just return it.
202 if (!isUnresolvedExceptionSpec(SourceFPT->getExceptionSpecType()))
203 return SourceFPT;
204
205 // Compute or instantiate the exception specification now.
206 if (SourceFPT->getExceptionSpecType() == EST_Unevaluated)
207 EvaluateImplicitExceptionSpec(Loc, cast<CXXMethodDecl>(SourceDecl));
208 else
209 InstantiateExceptionSpec(Loc, SourceDecl);
210
211 const FunctionProtoType *Proto =
212 SourceDecl->getType()->castAs<FunctionProtoType>();
213 if (Proto->getExceptionSpecType() == clang::EST_Unparsed) {
214 Diag(Loc, diag::err_exception_spec_not_parsed);
215 Proto = nullptr;
216 }
217 return Proto;
218}
219
220void
221Sema::UpdateExceptionSpec(FunctionDecl *FD,
222 const FunctionProtoType::ExceptionSpecInfo &ESI) {
223 // If we've fully resolved the exception specification, notify listeners.
224 if (!isUnresolvedExceptionSpec(ESI.Type))
225 if (auto *Listener = getASTMutationListener())
226 Listener->ResolvedExceptionSpec(FD);
227
228 for (FunctionDecl *Redecl : FD->redecls())
229 Context.adjustExceptionSpec(Redecl, ESI);
230}
231
232static bool exceptionSpecNotKnownYet(const FunctionDecl *FD) {
233 auto *MD = dyn_cast<CXXMethodDecl>(FD);
234 if (!MD)
235 return false;
236
237 auto EST = MD->getType()->castAs<FunctionProtoType>()->getExceptionSpecType();
238 return EST == EST_Unparsed ||
239 (EST == EST_Unevaluated && MD->getParent()->isBeingDefined());
240}
241
242static bool CheckEquivalentExceptionSpecImpl(
243 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
244 const FunctionProtoType *Old, SourceLocation OldLoc,
245 const FunctionProtoType *New, SourceLocation NewLoc,
246 bool *MissingExceptionSpecification = nullptr,
247 bool *MissingEmptyExceptionSpecification = nullptr,
248 bool AllowNoexceptAllMatchWithNoSpec = false, bool IsOperatorNew = false);
249
250/// Determine whether a function has an implicitly-generated exception
251/// specification.
252static bool hasImplicitExceptionSpec(FunctionDecl *Decl) {
253 if (!isa<CXXDestructorDecl>(Decl) &&
11
Assuming 'Decl' is a 'CXXDestructorDecl'
12
Taking false branch
254 Decl->getDeclName().getCXXOverloadedOperator() != OO_Delete &&
255 Decl->getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
256 return false;
257
258 // For a function that the user didn't declare:
259 // - if this is a destructor, its exception specification is implicit.
260 // - if this is 'operator delete' or 'operator delete[]', the exception
261 // specification is as-if an explicit exception specification was given
262 // (per [basic.stc.dynamic]p2).
263 if (!Decl->getTypeSourceInfo())
13
Calling 'DeclaratorDecl::getTypeSourceInfo'
20
Returning from 'DeclaratorDecl::getTypeSourceInfo'
21
Assuming the condition is false
22
Taking false branch
264 return isa<CXXDestructorDecl>(Decl);
265
266 const FunctionProtoType *Ty =
24
'Ty' initialized to a null pointer value
267 Decl->getTypeSourceInfo()->getType()->getAs<FunctionProtoType>();
23
Assuming the object is not a 'FunctionProtoType'
268 return !Ty->hasExceptionSpec();
25
Called C++ object pointer is null
269}
270
271bool Sema::CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New) {
272 // Just completely ignore this under -fno-exceptions prior to C++17.
273 // In C++17 onwards, the exception specification is part of the type and
274 // we will diagnose mismatches anyway, so it's better to check for them here.
275 if (!getLangOpts().CXXExceptions && !getLangOpts().CPlusPlus17)
1
Assuming field 'CXXExceptions' is not equal to 0
276 return false;
277
278 OverloadedOperatorKind OO = New->getDeclName().getCXXOverloadedOperator();
279 bool IsOperatorNew = OO
1.1
'OO' is not equal to OO_New
1.1
'OO' is not equal to OO_New
1.1
'OO' is not equal to OO_New
== OO_New || OO == OO_Array_New;
280 bool MissingExceptionSpecification = false;
281 bool MissingEmptyExceptionSpecification = false;
282
283 unsigned DiagID = diag::err_mismatched_exception_spec;
284 bool ReturnValueOnError = true;
285 if (getLangOpts().MSVCCompat) {
2
Assuming field 'MSVCCompat' is 0
3
Taking false branch
286 DiagID = diag::ext_mismatched_exception_spec;
287 ReturnValueOnError = false;
288 }
289
290 // If we're befriending a member function of a class that's currently being
291 // defined, we might not be able to work out its exception specification yet.
292 // If not, defer the check until later.
293 if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
4
Taking false branch
294 DelayedEquivalentExceptionSpecChecks.push_back({New, Old});
295 return false;
296 }
297
298 // Check the types as written: they must match before any exception
299 // specification adjustment is applied.
300 if (!CheckEquivalentExceptionSpecImpl(
7
Taking true branch
301 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
302 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
5
Assuming the object is not a 'FunctionProtoType'
303 New->getType()->getAs<FunctionProtoType>(), New->getLocation(),
6
Assuming the object is not a 'FunctionProtoType'
304 &MissingExceptionSpecification, &MissingEmptyExceptionSpecification,
305 /*AllowNoexceptAllMatchWithNoSpec=*/true, IsOperatorNew)) {
306 // C++11 [except.spec]p4 [DR1492]:
307 // If a declaration of a function has an implicit
308 // exception-specification, other declarations of the function shall
309 // not specify an exception-specification.
310 if (getLangOpts().CPlusPlus11 && getLangOpts().CXXExceptions &&
8
Assuming field 'CPlusPlus11' is not equal to 0
9
Assuming field 'CXXExceptions' is not equal to 0
311 hasImplicitExceptionSpec(Old) != hasImplicitExceptionSpec(New)) {
10
Calling 'hasImplicitExceptionSpec'
312 Diag(New->getLocation(), diag::ext_implicit_exception_spec_mismatch)
313 << hasImplicitExceptionSpec(Old);
314 if (Old->getLocation().isValid())
315 Diag(Old->getLocation(), diag::note_previous_declaration);
316 }
317 return false;
318 }
319
320 // The failure was something other than an missing exception
321 // specification; return an error, except in MS mode where this is a warning.
322 if (!MissingExceptionSpecification)
323 return ReturnValueOnError;
324
325 const FunctionProtoType *NewProto =
326 New->getType()->castAs<FunctionProtoType>();
327
328 // The new function declaration is only missing an empty exception
329 // specification "throw()". If the throw() specification came from a
330 // function in a system header that has C linkage, just add an empty
331 // exception specification to the "new" declaration. Note that C library
332 // implementations are permitted to add these nothrow exception
333 // specifications.
334 //
335 // Likewise if the old function is a builtin.
336 if (MissingEmptyExceptionSpecification && NewProto &&
337 (Old->getLocation().isInvalid() ||
338 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
339 Old->getBuiltinID()) &&
340 Old->isExternC()) {
341 New->setType(Context.getFunctionType(
342 NewProto->getReturnType(), NewProto->getParamTypes(),
343 NewProto->getExtProtoInfo().withExceptionSpec(EST_DynamicNone)));
344 return false;
345 }
346
347 const FunctionProtoType *OldProto =
348 Old->getType()->castAs<FunctionProtoType>();
349
350 FunctionProtoType::ExceptionSpecInfo ESI = OldProto->getExceptionSpecType();
351 if (ESI.Type == EST_Dynamic) {
352 // FIXME: What if the exceptions are described in terms of the old
353 // prototype's parameters?
354 ESI.Exceptions = OldProto->exceptions();
355 }
356
357 if (ESI.Type == EST_NoexceptFalse)
358 ESI.Type = EST_None;
359 if (ESI.Type == EST_NoexceptTrue)
360 ESI.Type = EST_BasicNoexcept;
361
362 // For dependent noexcept, we can't just take the expression from the old
363 // prototype. It likely contains references to the old prototype's parameters.
364 if (ESI.Type == EST_DependentNoexcept) {
365 New->setInvalidDecl();
366 } else {
367 // Update the type of the function with the appropriate exception
368 // specification.
369 New->setType(Context.getFunctionType(
370 NewProto->getReturnType(), NewProto->getParamTypes(),
371 NewProto->getExtProtoInfo().withExceptionSpec(ESI)));
372 }
373
374 if (getLangOpts().MSVCCompat && ESI.Type != EST_DependentNoexcept) {
375 // Allow missing exception specifications in redeclarations as an extension.
376 DiagID = diag::ext_ms_missing_exception_specification;
377 ReturnValueOnError = false;
378 } else if (New->isReplaceableGlobalAllocationFunction() &&
379 ESI.Type != EST_DependentNoexcept) {
380 // Allow missing exception specifications in redeclarations as an extension,
381 // when declaring a replaceable global allocation function.
382 DiagID = diag::ext_missing_exception_specification;
383 ReturnValueOnError = false;
384 } else if (ESI.Type == EST_NoThrow) {
385 // Allow missing attribute 'nothrow' in redeclarations, since this is a very
386 // common omission.
387 DiagID = diag::ext_missing_exception_specification;
388 ReturnValueOnError = false;
389 } else {
390 DiagID = diag::err_missing_exception_specification;
391 ReturnValueOnError = true;
392 }
393
394 // Warn about the lack of exception specification.
395 SmallString<128> ExceptionSpecString;
396 llvm::raw_svector_ostream OS(ExceptionSpecString);
397 switch (OldProto->getExceptionSpecType()) {
398 case EST_DynamicNone:
399 OS << "throw()";
400 break;
401
402 case EST_Dynamic: {
403 OS << "throw(";
404 bool OnFirstException = true;
405 for (const auto &E : OldProto->exceptions()) {
406 if (OnFirstException)
407 OnFirstException = false;
408 else
409 OS << ", ";
410
411 OS << E.getAsString(getPrintingPolicy());
412 }
413 OS << ")";
414 break;
415 }
416
417 case EST_BasicNoexcept:
418 OS << "noexcept";
419 break;
420
421 case EST_DependentNoexcept:
422 case EST_NoexceptFalse:
423 case EST_NoexceptTrue:
424 OS << "noexcept(";
425 assert(OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr")((OldProto->getNoexceptExpr() != nullptr && "Expected non-null Expr"
) ? static_cast<void> (0) : __assert_fail ("OldProto->getNoexceptExpr() != nullptr && \"Expected non-null Expr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 425, __PRETTY_FUNCTION__))
;
426 OldProto->getNoexceptExpr()->printPretty(OS, nullptr, getPrintingPolicy());
427 OS << ")";
428 break;
429 case EST_NoThrow:
430 OS <<"__attribute__((nothrow))";
431 break;
432 case EST_None:
433 case EST_MSAny:
434 case EST_Unevaluated:
435 case EST_Uninstantiated:
436 case EST_Unparsed:
437 llvm_unreachable("This spec type is compatible with none.")::llvm::llvm_unreachable_internal("This spec type is compatible with none."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 437)
;
438 }
439
440 SourceLocation FixItLoc;
441 if (TypeSourceInfo *TSInfo = New->getTypeSourceInfo()) {
442 TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
443 // FIXME: Preserve enough information so that we can produce a correct fixit
444 // location when there is a trailing return type.
445 if (auto FTLoc = TL.getAs<FunctionProtoTypeLoc>())
446 if (!FTLoc.getTypePtr()->hasTrailingReturn())
447 FixItLoc = getLocForEndOfToken(FTLoc.getLocalRangeEnd());
448 }
449
450 if (FixItLoc.isInvalid())
451 Diag(New->getLocation(), DiagID)
452 << New << OS.str();
453 else {
454 Diag(New->getLocation(), DiagID)
455 << New << OS.str()
456 << FixItHint::CreateInsertion(FixItLoc, " " + OS.str().str());
457 }
458
459 if (Old->getLocation().isValid())
460 Diag(Old->getLocation(), diag::note_previous_declaration);
461
462 return ReturnValueOnError;
463}
464
465/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
466/// exception specifications. Exception specifications are equivalent if
467/// they allow exactly the same set of exception types. It does not matter how
468/// that is achieved. See C++ [except.spec]p2.
469bool Sema::CheckEquivalentExceptionSpec(
470 const FunctionProtoType *Old, SourceLocation OldLoc,
471 const FunctionProtoType *New, SourceLocation NewLoc) {
472 if (!getLangOpts().CXXExceptions)
473 return false;
474
475 unsigned DiagID = diag::err_mismatched_exception_spec;
476 if (getLangOpts().MSVCCompat)
477 DiagID = diag::ext_mismatched_exception_spec;
478 bool Result = CheckEquivalentExceptionSpecImpl(
479 *this, PDiag(DiagID), PDiag(diag::note_previous_declaration),
480 Old, OldLoc, New, NewLoc);
481
482 // In Microsoft mode, mismatching exception specifications just cause a warning.
483 if (getLangOpts().MSVCCompat)
484 return false;
485 return Result;
486}
487
488/// CheckEquivalentExceptionSpec - Check if the two types have compatible
489/// exception specifications. See C++ [except.spec]p3.
490///
491/// \return \c false if the exception specifications match, \c true if there is
492/// a problem. If \c true is returned, either a diagnostic has already been
493/// produced or \c *MissingExceptionSpecification is set to \c true.
494static bool CheckEquivalentExceptionSpecImpl(
495 Sema &S, const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
496 const FunctionProtoType *Old, SourceLocation OldLoc,
497 const FunctionProtoType *New, SourceLocation NewLoc,
498 bool *MissingExceptionSpecification,
499 bool *MissingEmptyExceptionSpecification,
500 bool AllowNoexceptAllMatchWithNoSpec, bool IsOperatorNew) {
501 if (MissingExceptionSpecification)
502 *MissingExceptionSpecification = false;
503
504 if (MissingEmptyExceptionSpecification)
505 *MissingEmptyExceptionSpecification = false;
506
507 Old = S.ResolveExceptionSpec(NewLoc, Old);
508 if (!Old)
509 return false;
510 New = S.ResolveExceptionSpec(NewLoc, New);
511 if (!New)
512 return false;
513
514 // C++0x [except.spec]p3: Two exception-specifications are compatible if:
515 // - both are non-throwing, regardless of their form,
516 // - both have the form noexcept(constant-expression) and the constant-
517 // expressions are equivalent,
518 // - both are dynamic-exception-specifications that have the same set of
519 // adjusted types.
520 //
521 // C++0x [except.spec]p12: An exception-specification is non-throwing if it is
522 // of the form throw(), noexcept, or noexcept(constant-expression) where the
523 // constant-expression yields true.
524 //
525 // C++0x [except.spec]p4: If any declaration of a function has an exception-
526 // specifier that is not a noexcept-specification allowing all exceptions,
527 // all declarations [...] of that function shall have a compatible
528 // exception-specification.
529 //
530 // That last point basically means that noexcept(false) matches no spec.
531 // It's considered when AllowNoexceptAllMatchWithNoSpec is true.
532
533 ExceptionSpecificationType OldEST = Old->getExceptionSpecType();
534 ExceptionSpecificationType NewEST = New->getExceptionSpecType();
535
536 assert(!isUnresolvedExceptionSpec(OldEST) &&((!isUnresolvedExceptionSpec(OldEST) && !isUnresolvedExceptionSpec
(NewEST) && "Shouldn't see unknown exception specifications here"
) ? static_cast<void> (0) : __assert_fail ("!isUnresolvedExceptionSpec(OldEST) && !isUnresolvedExceptionSpec(NewEST) && \"Shouldn't see unknown exception specifications here\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 538, __PRETTY_FUNCTION__))
537 !isUnresolvedExceptionSpec(NewEST) &&((!isUnresolvedExceptionSpec(OldEST) && !isUnresolvedExceptionSpec
(NewEST) && "Shouldn't see unknown exception specifications here"
) ? static_cast<void> (0) : __assert_fail ("!isUnresolvedExceptionSpec(OldEST) && !isUnresolvedExceptionSpec(NewEST) && \"Shouldn't see unknown exception specifications here\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 538, __PRETTY_FUNCTION__))
538 "Shouldn't see unknown exception specifications here")((!isUnresolvedExceptionSpec(OldEST) && !isUnresolvedExceptionSpec
(NewEST) && "Shouldn't see unknown exception specifications here"
) ? static_cast<void> (0) : __assert_fail ("!isUnresolvedExceptionSpec(OldEST) && !isUnresolvedExceptionSpec(NewEST) && \"Shouldn't see unknown exception specifications here\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 538, __PRETTY_FUNCTION__))
;
539
540 CanThrowResult OldCanThrow = Old->canThrow();
541 CanThrowResult NewCanThrow = New->canThrow();
542
543 // Any non-throwing specifications are compatible.
544 if (OldCanThrow == CT_Cannot && NewCanThrow == CT_Cannot)
545 return false;
546
547 // Any throws-anything specifications are usually compatible.
548 if (OldCanThrow == CT_Can && OldEST != EST_Dynamic &&
549 NewCanThrow == CT_Can && NewEST != EST_Dynamic) {
550 // The exception is that the absence of an exception specification only
551 // matches noexcept(false) for functions, as described above.
552 if (!AllowNoexceptAllMatchWithNoSpec &&
553 ((OldEST == EST_None && NewEST == EST_NoexceptFalse) ||
554 (OldEST == EST_NoexceptFalse && NewEST == EST_None))) {
555 // This is the disallowed case.
556 } else {
557 return false;
558 }
559 }
560
561 // C++14 [except.spec]p3:
562 // Two exception-specifications are compatible if [...] both have the form
563 // noexcept(constant-expression) and the constant-expressions are equivalent
564 if (OldEST == EST_DependentNoexcept && NewEST == EST_DependentNoexcept) {
565 llvm::FoldingSetNodeID OldFSN, NewFSN;
566 Old->getNoexceptExpr()->Profile(OldFSN, S.Context, true);
567 New->getNoexceptExpr()->Profile(NewFSN, S.Context, true);
568 if (OldFSN == NewFSN)
569 return false;
570 }
571
572 // Dynamic exception specifications with the same set of adjusted types
573 // are compatible.
574 if (OldEST == EST_Dynamic && NewEST == EST_Dynamic) {
575 bool Success = true;
576 // Both have a dynamic exception spec. Collect the first set, then compare
577 // to the second.
578 llvm::SmallPtrSet<CanQualType, 8> OldTypes, NewTypes;
579 for (const auto &I : Old->exceptions())
580 OldTypes.insert(S.Context.getCanonicalType(I).getUnqualifiedType());
581
582 for (const auto &I : New->exceptions()) {
583 CanQualType TypePtr = S.Context.getCanonicalType(I).getUnqualifiedType();
584 if (OldTypes.count(TypePtr))
585 NewTypes.insert(TypePtr);
586 else {
587 Success = false;
588 break;
589 }
590 }
591
592 if (Success && OldTypes.size() == NewTypes.size())
593 return false;
594 }
595
596 // As a special compatibility feature, under C++0x we accept no spec and
597 // throw(std::bad_alloc) as equivalent for operator new and operator new[].
598 // This is because the implicit declaration changed, but old code would break.
599 if (S.getLangOpts().CPlusPlus11 && IsOperatorNew) {
600 const FunctionProtoType *WithExceptions = nullptr;
601 if (OldEST == EST_None && NewEST == EST_Dynamic)
602 WithExceptions = New;
603 else if (OldEST == EST_Dynamic && NewEST == EST_None)
604 WithExceptions = Old;
605 if (WithExceptions && WithExceptions->getNumExceptions() == 1) {
606 // One has no spec, the other throw(something). If that something is
607 // std::bad_alloc, all conditions are met.
608 QualType Exception = *WithExceptions->exception_begin();
609 if (CXXRecordDecl *ExRecord = Exception->getAsCXXRecordDecl()) {
610 IdentifierInfo* Name = ExRecord->getIdentifier();
611 if (Name && Name->getName() == "bad_alloc") {
612 // It's called bad_alloc, but is it in std?
613 if (ExRecord->isInStdNamespace()) {
614 return false;
615 }
616 }
617 }
618 }
619 }
620
621 // If the caller wants to handle the case that the new function is
622 // incompatible due to a missing exception specification, let it.
623 if (MissingExceptionSpecification && OldEST != EST_None &&
624 NewEST == EST_None) {
625 // The old type has an exception specification of some sort, but
626 // the new type does not.
627 *MissingExceptionSpecification = true;
628
629 if (MissingEmptyExceptionSpecification && OldCanThrow == CT_Cannot) {
630 // The old type has a throw() or noexcept(true) exception specification
631 // and the new type has no exception specification, and the caller asked
632 // to handle this itself.
633 *MissingEmptyExceptionSpecification = true;
634 }
635
636 return true;
637 }
638
639 S.Diag(NewLoc, DiagID);
640 if (NoteID.getDiagID() != 0 && OldLoc.isValid())
641 S.Diag(OldLoc, NoteID);
642 return true;
643}
644
645bool Sema::CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
646 const PartialDiagnostic &NoteID,
647 const FunctionProtoType *Old,
648 SourceLocation OldLoc,
649 const FunctionProtoType *New,
650 SourceLocation NewLoc) {
651 if (!getLangOpts().CXXExceptions)
652 return false;
653 return CheckEquivalentExceptionSpecImpl(*this, DiagID, NoteID, Old, OldLoc,
654 New, NewLoc);
655}
656
657bool Sema::handlerCanCatch(QualType HandlerType, QualType ExceptionType) {
658 // [except.handle]p3:
659 // A handler is a match for an exception object of type E if:
660
661 // HandlerType must be ExceptionType or derived from it, or pointer or
662 // reference to such types.
663 const ReferenceType *RefTy = HandlerType->getAs<ReferenceType>();
664 if (RefTy)
665 HandlerType = RefTy->getPointeeType();
666
667 // -- the handler is of type cv T or cv T& and E and T are the same type
668 if (Context.hasSameUnqualifiedType(ExceptionType, HandlerType))
669 return true;
670
671 // FIXME: ObjC pointer types?
672 if (HandlerType->isPointerType() || HandlerType->isMemberPointerType()) {
673 if (RefTy && (!HandlerType.isConstQualified() ||
674 HandlerType.isVolatileQualified()))
675 return false;
676
677 // -- the handler is of type cv T or const T& where T is a pointer or
678 // pointer to member type and E is std::nullptr_t
679 if (ExceptionType->isNullPtrType())
680 return true;
681
682 // -- the handler is of type cv T or const T& where T is a pointer or
683 // pointer to member type and E is a pointer or pointer to member type
684 // that can be converted to T by one or more of
685 // -- a qualification conversion
686 // -- a function pointer conversion
687 bool LifetimeConv;
688 QualType Result;
689 // FIXME: Should we treat the exception as catchable if a lifetime
690 // conversion is required?
691 if (IsQualificationConversion(ExceptionType, HandlerType, false,
692 LifetimeConv) ||
693 IsFunctionConversion(ExceptionType, HandlerType, Result))
694 return true;
695
696 // -- a standard pointer conversion [...]
697 if (!ExceptionType->isPointerType() || !HandlerType->isPointerType())
698 return false;
699
700 // Handle the "qualification conversion" portion.
701 Qualifiers EQuals, HQuals;
702 ExceptionType = Context.getUnqualifiedArrayType(
703 ExceptionType->getPointeeType(), EQuals);
704 HandlerType = Context.getUnqualifiedArrayType(
705 HandlerType->getPointeeType(), HQuals);
706 if (!HQuals.compatiblyIncludes(EQuals))
707 return false;
708
709 if (HandlerType->isVoidType() && ExceptionType->isObjectType())
710 return true;
711
712 // The only remaining case is a derived-to-base conversion.
713 }
714
715 // -- the handler is of type cg T or cv T& and T is an unambiguous public
716 // base class of E
717 if (!ExceptionType->isRecordType() || !HandlerType->isRecordType())
718 return false;
719 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
720 /*DetectVirtual=*/false);
721 if (!IsDerivedFrom(SourceLocation(), ExceptionType, HandlerType, Paths) ||
722 Paths.isAmbiguous(Context.getCanonicalType(HandlerType)))
723 return false;
724
725 // Do this check from a context without privileges.
726 switch (CheckBaseClassAccess(SourceLocation(), HandlerType, ExceptionType,
727 Paths.front(),
728 /*Diagnostic*/ 0,
729 /*ForceCheck*/ true,
730 /*ForceUnprivileged*/ true)) {
731 case AR_accessible: return true;
732 case AR_inaccessible: return false;
733 case AR_dependent:
734 llvm_unreachable("access check dependent for unprivileged context")::llvm::llvm_unreachable_internal("access check dependent for unprivileged context"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 734)
;
735 case AR_delayed:
736 llvm_unreachable("access check delayed in non-declaration")::llvm::llvm_unreachable_internal("access check delayed in non-declaration"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 736)
;
737 }
738 llvm_unreachable("unexpected access check result")::llvm::llvm_unreachable_internal("unexpected access check result"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 738)
;
739}
740
741/// CheckExceptionSpecSubset - Check whether the second function type's
742/// exception specification is a subset (or equivalent) of the first function
743/// type. This is used by override and pointer assignment checks.
744bool Sema::CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
745 const PartialDiagnostic &NestedDiagID,
746 const PartialDiagnostic &NoteID,
747 const PartialDiagnostic &NoThrowDiagID,
748 const FunctionProtoType *Superset,
749 SourceLocation SuperLoc,
750 const FunctionProtoType *Subset,
751 SourceLocation SubLoc) {
752
753 // Just auto-succeed under -fno-exceptions.
754 if (!getLangOpts().CXXExceptions)
755 return false;
756
757 // FIXME: As usual, we could be more specific in our error messages, but
758 // that better waits until we've got types with source locations.
759
760 if (!SubLoc.isValid())
761 SubLoc = SuperLoc;
762
763 // Resolve the exception specifications, if needed.
764 Superset = ResolveExceptionSpec(SuperLoc, Superset);
765 if (!Superset)
766 return false;
767 Subset = ResolveExceptionSpec(SubLoc, Subset);
768 if (!Subset)
769 return false;
770
771 ExceptionSpecificationType SuperEST = Superset->getExceptionSpecType();
772 ExceptionSpecificationType SubEST = Subset->getExceptionSpecType();
773 assert(!isUnresolvedExceptionSpec(SuperEST) &&((!isUnresolvedExceptionSpec(SuperEST) && !isUnresolvedExceptionSpec
(SubEST) && "Shouldn't see unknown exception specifications here"
) ? static_cast<void> (0) : __assert_fail ("!isUnresolvedExceptionSpec(SuperEST) && !isUnresolvedExceptionSpec(SubEST) && \"Shouldn't see unknown exception specifications here\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 775, __PRETTY_FUNCTION__))
774 !isUnresolvedExceptionSpec(SubEST) &&((!isUnresolvedExceptionSpec(SuperEST) && !isUnresolvedExceptionSpec
(SubEST) && "Shouldn't see unknown exception specifications here"
) ? static_cast<void> (0) : __assert_fail ("!isUnresolvedExceptionSpec(SuperEST) && !isUnresolvedExceptionSpec(SubEST) && \"Shouldn't see unknown exception specifications here\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 775, __PRETTY_FUNCTION__))
775 "Shouldn't see unknown exception specifications here")((!isUnresolvedExceptionSpec(SuperEST) && !isUnresolvedExceptionSpec
(SubEST) && "Shouldn't see unknown exception specifications here"
) ? static_cast<void> (0) : __assert_fail ("!isUnresolvedExceptionSpec(SuperEST) && !isUnresolvedExceptionSpec(SubEST) && \"Shouldn't see unknown exception specifications here\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 775, __PRETTY_FUNCTION__))
;
776
777 // If there are dependent noexcept specs, assume everything is fine. Unlike
778 // with the equivalency check, this is safe in this case, because we don't
779 // want to merge declarations. Checks after instantiation will catch any
780 // omissions we make here.
781 if (SuperEST == EST_DependentNoexcept || SubEST == EST_DependentNoexcept)
782 return false;
783
784 CanThrowResult SuperCanThrow = Superset->canThrow();
785 CanThrowResult SubCanThrow = Subset->canThrow();
786
787 // If the superset contains everything or the subset contains nothing, we're
788 // done.
789 if ((SuperCanThrow == CT_Can && SuperEST != EST_Dynamic) ||
790 SubCanThrow == CT_Cannot)
791 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
792 Subset, SubLoc);
793
794 // Allow __declspec(nothrow) to be missing on redeclaration as an extension in
795 // some cases.
796 if (NoThrowDiagID.getDiagID() != 0 && SubCanThrow == CT_Can &&
797 SuperCanThrow == CT_Cannot && SuperEST == EST_NoThrow) {
798 Diag(SubLoc, NoThrowDiagID);
799 if (NoteID.getDiagID() != 0)
800 Diag(SuperLoc, NoteID);
801 return true;
802 }
803
804 // If the subset contains everything or the superset contains nothing, we've
805 // failed.
806 if ((SubCanThrow == CT_Can && SubEST != EST_Dynamic) ||
807 SuperCanThrow == CT_Cannot) {
808 Diag(SubLoc, DiagID);
809 if (NoteID.getDiagID() != 0)
810 Diag(SuperLoc, NoteID);
811 return true;
812 }
813
814 assert(SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&((SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
"Exception spec subset: non-dynamic case slipped through.") ?
static_cast<void> (0) : __assert_fail ("SuperEST == EST_Dynamic && SubEST == EST_Dynamic && \"Exception spec subset: non-dynamic case slipped through.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 815, __PRETTY_FUNCTION__))
815 "Exception spec subset: non-dynamic case slipped through.")((SuperEST == EST_Dynamic && SubEST == EST_Dynamic &&
"Exception spec subset: non-dynamic case slipped through.") ?
static_cast<void> (0) : __assert_fail ("SuperEST == EST_Dynamic && SubEST == EST_Dynamic && \"Exception spec subset: non-dynamic case slipped through.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 815, __PRETTY_FUNCTION__))
;
816
817 // Neither contains everything or nothing. Do a proper comparison.
818 for (QualType SubI : Subset->exceptions()) {
819 if (const ReferenceType *RefTy = SubI->getAs<ReferenceType>())
820 SubI = RefTy->getPointeeType();
821
822 // Make sure it's in the superset.
823 bool Contained = false;
824 for (QualType SuperI : Superset->exceptions()) {
825 // [except.spec]p5:
826 // the target entity shall allow at least the exceptions allowed by the
827 // source
828 //
829 // We interpret this as meaning that a handler for some target type would
830 // catch an exception of each source type.
831 if (handlerCanCatch(SuperI, SubI)) {
832 Contained = true;
833 break;
834 }
835 }
836 if (!Contained) {
837 Diag(SubLoc, DiagID);
838 if (NoteID.getDiagID() != 0)
839 Diag(SuperLoc, NoteID);
840 return true;
841 }
842 }
843 // We've run half the gauntlet.
844 return CheckParamExceptionSpec(NestedDiagID, NoteID, Superset, SuperLoc,
845 Subset, SubLoc);
846}
847
848static bool
849CheckSpecForTypesEquivalent(Sema &S, const PartialDiagnostic &DiagID,
850 const PartialDiagnostic &NoteID, QualType Target,
851 SourceLocation TargetLoc, QualType Source,
852 SourceLocation SourceLoc) {
853 const FunctionProtoType *TFunc = GetUnderlyingFunction(Target);
854 if (!TFunc)
855 return false;
856 const FunctionProtoType *SFunc = GetUnderlyingFunction(Source);
857 if (!SFunc)
858 return false;
859
860 return S.CheckEquivalentExceptionSpec(DiagID, NoteID, TFunc, TargetLoc,
861 SFunc, SourceLoc);
862}
863
864/// CheckParamExceptionSpec - Check if the parameter and return types of the
865/// two functions have equivalent exception specs. This is part of the
866/// assignment and override compatibility check. We do not check the parameters
867/// of parameter function pointers recursively, as no sane programmer would
868/// even be able to write such a function type.
869bool Sema::CheckParamExceptionSpec(const PartialDiagnostic &DiagID,
870 const PartialDiagnostic &NoteID,
871 const FunctionProtoType *Target,
872 SourceLocation TargetLoc,
873 const FunctionProtoType *Source,
874 SourceLocation SourceLoc) {
875 auto RetDiag = DiagID;
876 RetDiag << 0;
877 if (CheckSpecForTypesEquivalent(
878 *this, RetDiag, PDiag(),
879 Target->getReturnType(), TargetLoc, Source->getReturnType(),
880 SourceLoc))
881 return true;
882
883 // We shouldn't even be testing this unless the arguments are otherwise
884 // compatible.
885 assert(Target->getNumParams() == Source->getNumParams() &&((Target->getNumParams() == Source->getNumParams() &&
"Functions have different argument counts.") ? static_cast<
void> (0) : __assert_fail ("Target->getNumParams() == Source->getNumParams() && \"Functions have different argument counts.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 886, __PRETTY_FUNCTION__))
886 "Functions have different argument counts.")((Target->getNumParams() == Source->getNumParams() &&
"Functions have different argument counts.") ? static_cast<
void> (0) : __assert_fail ("Target->getNumParams() == Source->getNumParams() && \"Functions have different argument counts.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 886, __PRETTY_FUNCTION__))
;
887 for (unsigned i = 0, E = Target->getNumParams(); i != E; ++i) {
888 auto ParamDiag = DiagID;
889 ParamDiag << 1;
890 if (CheckSpecForTypesEquivalent(
891 *this, ParamDiag, PDiag(),
892 Target->getParamType(i), TargetLoc, Source->getParamType(i),
893 SourceLoc))
894 return true;
895 }
896 return false;
897}
898
899bool Sema::CheckExceptionSpecCompatibility(Expr *From, QualType ToType) {
900 // First we check for applicability.
901 // Target type must be a function, function pointer or function reference.
902 const FunctionProtoType *ToFunc = GetUnderlyingFunction(ToType);
903 if (!ToFunc || ToFunc->hasDependentExceptionSpec())
904 return false;
905
906 // SourceType must be a function or function pointer.
907 const FunctionProtoType *FromFunc = GetUnderlyingFunction(From->getType());
908 if (!FromFunc || FromFunc->hasDependentExceptionSpec())
909 return false;
910
911 unsigned DiagID = diag::err_incompatible_exception_specs;
912 unsigned NestedDiagID = diag::err_deep_exception_specs_differ;
913 // This is not an error in C++17 onwards, unless the noexceptness doesn't
914 // match, but in that case we have a full-on type mismatch, not just a
915 // type sugar mismatch.
916 if (getLangOpts().CPlusPlus17) {
917 DiagID = diag::warn_incompatible_exception_specs;
918 NestedDiagID = diag::warn_deep_exception_specs_differ;
919 }
920
921 // Now we've got the correct types on both sides, check their compatibility.
922 // This means that the source of the conversion can only throw a subset of
923 // the exceptions of the target, and any exception specs on arguments or
924 // return types must be equivalent.
925 //
926 // FIXME: If there is a nested dependent exception specification, we should
927 // not be checking it here. This is fine:
928 // template<typename T> void f() {
929 // void (*p)(void (*) throw(T));
930 // void (*q)(void (*) throw(int)) = p;
931 // }
932 // ... because it might be instantiated with T=int.
933 return CheckExceptionSpecSubset(
934 PDiag(DiagID), PDiag(NestedDiagID), PDiag(), PDiag(), ToFunc,
935 From->getSourceRange().getBegin(), FromFunc, SourceLocation()) &&
936 !getLangOpts().CPlusPlus17;
937}
938
939bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
940 const CXXMethodDecl *Old) {
941 // If the new exception specification hasn't been parsed yet, skip the check.
942 // We'll get called again once it's been parsed.
943 if (New->getType()->castAs<FunctionProtoType>()->getExceptionSpecType() ==
944 EST_Unparsed)
945 return false;
946
947 // Don't check uninstantiated template destructors at all. We can only
948 // synthesize correct specs after the template is instantiated.
949 if (isa<CXXDestructorDecl>(New) && New->getParent()->isDependentType())
950 return false;
951
952 // If the old exception specification hasn't been parsed yet, or the new
953 // exception specification can't be computed yet, remember that we need to
954 // perform this check when we get to the end of the outermost
955 // lexically-surrounding class.
956 if (exceptionSpecNotKnownYet(Old) || exceptionSpecNotKnownYet(New)) {
957 DelayedOverridingExceptionSpecChecks.push_back({New, Old});
958 return false;
959 }
960
961 unsigned DiagID = diag::err_override_exception_spec;
962 if (getLangOpts().MSVCCompat)
963 DiagID = diag::ext_override_exception_spec;
964 return CheckExceptionSpecSubset(PDiag(DiagID),
965 PDiag(diag::err_deep_exception_specs_differ),
966 PDiag(diag::note_overridden_virtual_function),
967 PDiag(diag::ext_override_exception_spec),
968 Old->getType()->getAs<FunctionProtoType>(),
969 Old->getLocation(),
970 New->getType()->getAs<FunctionProtoType>(),
971 New->getLocation());
972}
973
974static CanThrowResult canSubExprsThrow(Sema &S, const Expr *E) {
975 CanThrowResult R = CT_Cannot;
976 for (const Stmt *SubStmt : E->children()) {
977 R = mergeCanThrow(R, S.canThrow(cast<Expr>(SubStmt)));
978 if (R == CT_Can)
979 break;
980 }
981 return R;
982}
983
984static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D) {
985 // As an extension, we assume that __attribute__((nothrow)) functions don't
986 // throw.
987 if (D && isa<FunctionDecl>(D) && D->hasAttr<NoThrowAttr>())
988 return CT_Cannot;
989
990 QualType T;
991
992 // In C++1z, just look at the function type of the callee.
993 if (S.getLangOpts().CPlusPlus17 && isa<CallExpr>(E)) {
994 E = cast<CallExpr>(E)->getCallee();
995 T = E->getType();
996 if (T->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
997 // Sadly we don't preserve the actual type as part of the "bound member"
998 // placeholder, so we need to reconstruct it.
999 E = E->IgnoreParenImpCasts();
1000
1001 // Could be a call to a pointer-to-member or a plain member access.
1002 if (auto *Op = dyn_cast<BinaryOperator>(E)) {
1003 assert(Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI)((Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI
) ? static_cast<void> (0) : __assert_fail ("Op->getOpcode() == BO_PtrMemD || Op->getOpcode() == BO_PtrMemI"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 1003, __PRETTY_FUNCTION__))
;
1004 T = Op->getRHS()->getType()
1005 ->castAs<MemberPointerType>()->getPointeeType();
1006 } else {
1007 T = cast<MemberExpr>(E)->getMemberDecl()->getType();
1008 }
1009 }
1010 } else if (const ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D))
1011 T = VD->getType();
1012 else
1013 // If we have no clue what we're calling, assume the worst.
1014 return CT_Can;
1015
1016 const FunctionProtoType *FT;
1017 if ((FT = T->getAs<FunctionProtoType>())) {
1018 } else if (const PointerType *PT = T->getAs<PointerType>())
1019 FT = PT->getPointeeType()->getAs<FunctionProtoType>();
1020 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
1021 FT = RT->getPointeeType()->getAs<FunctionProtoType>();
1022 else if (const MemberPointerType *MT = T->getAs<MemberPointerType>())
1023 FT = MT->getPointeeType()->getAs<FunctionProtoType>();
1024 else if (const BlockPointerType *BT = T->getAs<BlockPointerType>())
1025 FT = BT->getPointeeType()->getAs<FunctionProtoType>();
1026
1027 if (!FT)
1028 return CT_Can;
1029
1030 FT = S.ResolveExceptionSpec(E->getBeginLoc(), FT);
1031 if (!FT)
1032 return CT_Can;
1033
1034 return FT->canThrow();
1035}
1036
1037static CanThrowResult canDynamicCastThrow(const CXXDynamicCastExpr *DC) {
1038 if (DC->isTypeDependent())
1039 return CT_Dependent;
1040
1041 if (!DC->getTypeAsWritten()->isReferenceType())
1042 return CT_Cannot;
1043
1044 if (DC->getSubExpr()->isTypeDependent())
1045 return CT_Dependent;
1046
1047 return DC->getCastKind() == clang::CK_Dynamic? CT_Can : CT_Cannot;
1048}
1049
1050static CanThrowResult canTypeidThrow(Sema &S, const CXXTypeidExpr *DC) {
1051 if (DC->isTypeOperand())
1052 return CT_Cannot;
1053
1054 Expr *Op = DC->getExprOperand();
1055 if (Op->isTypeDependent())
1056 return CT_Dependent;
1057
1058 const RecordType *RT = Op->getType()->getAs<RecordType>();
1059 if (!RT)
1060 return CT_Cannot;
1061
1062 if (!cast<CXXRecordDecl>(RT->getDecl())->isPolymorphic())
1063 return CT_Cannot;
1064
1065 if (Op->Classify(S.Context).isPRValue())
1066 return CT_Cannot;
1067
1068 return CT_Can;
1069}
1070
1071CanThrowResult Sema::canThrow(const Expr *E) {
1072 // C++ [expr.unary.noexcept]p3:
1073 // [Can throw] if in a potentially-evaluated context the expression would
1074 // contain:
1075 switch (E->getStmtClass()) {
1076 case Expr::ConstantExprClass:
1077 return canThrow(cast<ConstantExpr>(E)->getSubExpr());
1078
1079 case Expr::CXXThrowExprClass:
1080 // - a potentially evaluated throw-expression
1081 return CT_Can;
1082
1083 case Expr::CXXDynamicCastExprClass: {
1084 // - a potentially evaluated dynamic_cast expression dynamic_cast<T>(v),
1085 // where T is a reference type, that requires a run-time check
1086 CanThrowResult CT = canDynamicCastThrow(cast<CXXDynamicCastExpr>(E));
1087 if (CT == CT_Can)
1088 return CT;
1089 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1090 }
1091
1092 case Expr::CXXTypeidExprClass:
1093 // - a potentially evaluated typeid expression applied to a glvalue
1094 // expression whose type is a polymorphic class type
1095 return canTypeidThrow(*this, cast<CXXTypeidExpr>(E));
1096
1097 // - a potentially evaluated call to a function, member function, function
1098 // pointer, or member function pointer that does not have a non-throwing
1099 // exception-specification
1100 case Expr::CallExprClass:
1101 case Expr::CXXMemberCallExprClass:
1102 case Expr::CXXOperatorCallExprClass:
1103 case Expr::UserDefinedLiteralClass: {
1104 const CallExpr *CE = cast<CallExpr>(E);
1105 CanThrowResult CT;
1106 if (E->isTypeDependent())
1107 CT = CT_Dependent;
1108 else if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens()))
1109 CT = CT_Cannot;
1110 else
1111 CT = canCalleeThrow(*this, E, CE->getCalleeDecl());
1112 if (CT == CT_Can)
1113 return CT;
1114 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1115 }
1116
1117 case Expr::CXXConstructExprClass:
1118 case Expr::CXXTemporaryObjectExprClass: {
1119 CanThrowResult CT = canCalleeThrow(*this, E,
1120 cast<CXXConstructExpr>(E)->getConstructor());
1121 if (CT == CT_Can)
1122 return CT;
1123 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1124 }
1125
1126 case Expr::CXXInheritedCtorInitExprClass:
1127 return canCalleeThrow(*this, E,
1128 cast<CXXInheritedCtorInitExpr>(E)->getConstructor());
1129
1130 case Expr::LambdaExprClass: {
1131 const LambdaExpr *Lambda = cast<LambdaExpr>(E);
1132 CanThrowResult CT = CT_Cannot;
1133 for (LambdaExpr::const_capture_init_iterator
1134 Cap = Lambda->capture_init_begin(),
1135 CapEnd = Lambda->capture_init_end();
1136 Cap != CapEnd; ++Cap)
1137 CT = mergeCanThrow(CT, canThrow(*Cap));
1138 return CT;
1139 }
1140
1141 case Expr::CXXNewExprClass: {
1142 CanThrowResult CT;
1143 if (E->isTypeDependent())
1144 CT = CT_Dependent;
1145 else
1146 CT = canCalleeThrow(*this, E, cast<CXXNewExpr>(E)->getOperatorNew());
1147 if (CT == CT_Can)
1148 return CT;
1149 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1150 }
1151
1152 case Expr::CXXDeleteExprClass: {
1153 CanThrowResult CT;
1154 QualType DTy = cast<CXXDeleteExpr>(E)->getDestroyedType();
1155 if (DTy.isNull() || DTy->isDependentType()) {
1156 CT = CT_Dependent;
1157 } else {
1158 CT = canCalleeThrow(*this, E,
1159 cast<CXXDeleteExpr>(E)->getOperatorDelete());
1160 if (const RecordType *RT = DTy->getAs<RecordType>()) {
1161 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1162 const CXXDestructorDecl *DD = RD->getDestructor();
1163 if (DD)
1164 CT = mergeCanThrow(CT, canCalleeThrow(*this, E, DD));
1165 }
1166 if (CT == CT_Can)
1167 return CT;
1168 }
1169 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1170 }
1171
1172 case Expr::CXXBindTemporaryExprClass: {
1173 // The bound temporary has to be destroyed again, which might throw.
1174 CanThrowResult CT = canCalleeThrow(*this, E,
1175 cast<CXXBindTemporaryExpr>(E)->getTemporary()->getDestructor());
1176 if (CT == CT_Can)
1177 return CT;
1178 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1179 }
1180
1181 // ObjC message sends are like function calls, but never have exception
1182 // specs.
1183 case Expr::ObjCMessageExprClass:
1184 case Expr::ObjCPropertyRefExprClass:
1185 case Expr::ObjCSubscriptRefExprClass:
1186 return CT_Can;
1187
1188 // All the ObjC literals that are implemented as calls are
1189 // potentially throwing unless we decide to close off that
1190 // possibility.
1191 case Expr::ObjCArrayLiteralClass:
1192 case Expr::ObjCDictionaryLiteralClass:
1193 case Expr::ObjCBoxedExprClass:
1194 return CT_Can;
1195
1196 // Many other things have subexpressions, so we have to test those.
1197 // Some are simple:
1198 case Expr::CoawaitExprClass:
1199 case Expr::ConditionalOperatorClass:
1200 case Expr::CompoundLiteralExprClass:
1201 case Expr::CoyieldExprClass:
1202 case Expr::CXXConstCastExprClass:
1203 case Expr::CXXReinterpretCastExprClass:
1204 case Expr::BuiltinBitCastExprClass:
1205 case Expr::CXXStdInitializerListExprClass:
1206 case Expr::DesignatedInitExprClass:
1207 case Expr::DesignatedInitUpdateExprClass:
1208 case Expr::ExprWithCleanupsClass:
1209 case Expr::ExtVectorElementExprClass:
1210 case Expr::InitListExprClass:
1211 case Expr::ArrayInitLoopExprClass:
1212 case Expr::MemberExprClass:
1213 case Expr::ObjCIsaExprClass:
1214 case Expr::ObjCIvarRefExprClass:
1215 case Expr::ParenExprClass:
1216 case Expr::ParenListExprClass:
1217 case Expr::ShuffleVectorExprClass:
1218 case Expr::ConvertVectorExprClass:
1219 case Expr::VAArgExprClass:
1220 return canSubExprsThrow(*this, E);
1221
1222 // Some might be dependent for other reasons.
1223 case Expr::ArraySubscriptExprClass:
1224 case Expr::OMPArraySectionExprClass:
1225 case Expr::BinaryOperatorClass:
1226 case Expr::DependentCoawaitExprClass:
1227 case Expr::CompoundAssignOperatorClass:
1228 case Expr::CStyleCastExprClass:
1229 case Expr::CXXStaticCastExprClass:
1230 case Expr::CXXFunctionalCastExprClass:
1231 case Expr::ImplicitCastExprClass:
1232 case Expr::MaterializeTemporaryExprClass:
1233 case Expr::UnaryOperatorClass: {
1234 CanThrowResult CT = E->isTypeDependent() ? CT_Dependent : CT_Cannot;
1235 return mergeCanThrow(CT, canSubExprsThrow(*this, E));
1236 }
1237
1238 // FIXME: We should handle StmtExpr, but that opens a MASSIVE can of worms.
1239 case Expr::StmtExprClass:
1240 return CT_Can;
1241
1242 case Expr::CXXDefaultArgExprClass:
1243 return canThrow(cast<CXXDefaultArgExpr>(E)->getExpr());
1244
1245 case Expr::CXXDefaultInitExprClass:
1246 return canThrow(cast<CXXDefaultInitExpr>(E)->getExpr());
1247
1248 case Expr::ChooseExprClass:
1249 if (E->isTypeDependent() || E->isValueDependent())
1250 return CT_Dependent;
1251 return canThrow(cast<ChooseExpr>(E)->getChosenSubExpr());
1252
1253 case Expr::GenericSelectionExprClass:
1254 if (cast<GenericSelectionExpr>(E)->isResultDependent())
1255 return CT_Dependent;
1256 return canThrow(cast<GenericSelectionExpr>(E)->getResultExpr());
1257
1258 // Some expressions are always dependent.
1259 case Expr::CXXDependentScopeMemberExprClass:
1260 case Expr::CXXUnresolvedConstructExprClass:
1261 case Expr::DependentScopeDeclRefExprClass:
1262 case Expr::CXXFoldExprClass:
1263 return CT_Dependent;
1264
1265 case Expr::AsTypeExprClass:
1266 case Expr::BinaryConditionalOperatorClass:
1267 case Expr::BlockExprClass:
1268 case Expr::CUDAKernelCallExprClass:
1269 case Expr::DeclRefExprClass:
1270 case Expr::ObjCBridgedCastExprClass:
1271 case Expr::ObjCIndirectCopyRestoreExprClass:
1272 case Expr::ObjCProtocolExprClass:
1273 case Expr::ObjCSelectorExprClass:
1274 case Expr::ObjCAvailabilityCheckExprClass:
1275 case Expr::OffsetOfExprClass:
1276 case Expr::PackExpansionExprClass:
1277 case Expr::PseudoObjectExprClass:
1278 case Expr::SubstNonTypeTemplateParmExprClass:
1279 case Expr::SubstNonTypeTemplateParmPackExprClass:
1280 case Expr::FunctionParmPackExprClass:
1281 case Expr::UnaryExprOrTypeTraitExprClass:
1282 case Expr::UnresolvedLookupExprClass:
1283 case Expr::UnresolvedMemberExprClass:
1284 case Expr::TypoExprClass:
1285 // FIXME: Can any of the above throw? If so, when?
1286 return CT_Cannot;
1287
1288 case Expr::AddrLabelExprClass:
1289 case Expr::ArrayTypeTraitExprClass:
1290 case Expr::AtomicExprClass:
1291 case Expr::TypeTraitExprClass:
1292 case Expr::CXXBoolLiteralExprClass:
1293 case Expr::CXXNoexceptExprClass:
1294 case Expr::CXXNullPtrLiteralExprClass:
1295 case Expr::CXXPseudoDestructorExprClass:
1296 case Expr::CXXScalarValueInitExprClass:
1297 case Expr::CXXThisExprClass:
1298 case Expr::CXXUuidofExprClass:
1299 case Expr::CharacterLiteralClass:
1300 case Expr::ExpressionTraitExprClass:
1301 case Expr::FloatingLiteralClass:
1302 case Expr::GNUNullExprClass:
1303 case Expr::ImaginaryLiteralClass:
1304 case Expr::ImplicitValueInitExprClass:
1305 case Expr::IntegerLiteralClass:
1306 case Expr::FixedPointLiteralClass:
1307 case Expr::ArrayInitIndexExprClass:
1308 case Expr::NoInitExprClass:
1309 case Expr::ObjCEncodeExprClass:
1310 case Expr::ObjCStringLiteralClass:
1311 case Expr::ObjCBoolLiteralExprClass:
1312 case Expr::OpaqueValueExprClass:
1313 case Expr::PredefinedExprClass:
1314 case Expr::SizeOfPackExprClass:
1315 case Expr::StringLiteralClass:
1316 case Expr::SourceLocExprClass:
1317 // These expressions can never throw.
1318 return CT_Cannot;
1319
1320 case Expr::MSPropertyRefExprClass:
1321 case Expr::MSPropertySubscriptExprClass:
1322 llvm_unreachable("Invalid class for expression")::llvm::llvm_unreachable_internal("Invalid class for expression"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 1322)
;
1323
1324#define STMT(CLASS, PARENT) case Expr::CLASS##Class:
1325#define STMT_RANGE(Base, First, Last)
1326#define LAST_STMT_RANGE(BASE, FIRST, LAST)
1327#define EXPR(CLASS, PARENT)
1328#define ABSTRACT_STMT(STMT)
1329#include "clang/AST/StmtNodes.inc"
1330 case Expr::NoStmtClass:
1331 llvm_unreachable("Invalid class for expression")::llvm::llvm_unreachable_internal("Invalid class for expression"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 1331)
;
1332 }
1333 llvm_unreachable("Bogus StmtClass")::llvm::llvm_unreachable_internal("Bogus StmtClass", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaExceptionSpec.cpp"
, 1333)
;
1334}
1335
1336} // end namespace clang

/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- 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// This file defines the Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECL_H
14#define LLVM_CLANG_AST_DECL_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTContextAllocate.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.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/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getBeginLoc().print(OS, SrcMgr);
85/// @endcode
86class alignas(8) TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// This represents a decl that may have a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245///
246/// Note that not every NamedDecl is actually named (e.g., a struct might
247/// be anonymous), and not every name is an identifier.
248class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
253
254 virtual void anchor();
255
256private:
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
258
259protected:
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
262
263public:
264 /// Get the identifier that names this declaration, if there is one.
265 ///
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
270
271 /// Get the name of identifier for this declaration as a StringRef.
272 ///
273 /// This requires that the declaration have a name and that it be a simple
274 /// identifier.
275 StringRef getName() const {
276 assert(Name.isIdentifier() && "Name is not a simple identifier")((Name.isIdentifier() && "Name is not a simple identifier"
) ? static_cast<void> (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 276, __PRETTY_FUNCTION__))
;
277 return getIdentifier() ? getIdentifier()->getName() : "";
278 }
279
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
282 ///
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
286 //
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
289 //
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
292
293 virtual void printName(raw_ostream &os) const;
294
295 /// Get the actual, stored name of the declaration, which may be a special
296 /// name.
297 DeclarationName getDeclName() const { return Name; }
298
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
301
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
304 ///
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
307 ///
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
312
313 /// Print only the nested name specifier part of a fully-qualified name,
314 /// including the '::' at the end. E.g.
315 /// when `printQualifiedName(D)` prints "A::B::i",
316 /// this function prints "A::B::".
317 void printNestedNameSpecifier(raw_ostream &OS) const;
318 void printNestedNameSpecifier(raw_ostream &OS,
319 const PrintingPolicy &Policy) const;
320
321 // FIXME: Remove string version.
322 std::string getQualifiedNameAsString() const;
323
324 /// Appends a human-readable name for this declaration into the given stream.
325 ///
326 /// This is the method invoked by Sema when displaying a NamedDecl
327 /// in a diagnostic. It does not necessarily produce the same
328 /// result as printName(); for example, class template
329 /// specializations are printed with their template arguments.
330 virtual void getNameForDiagnostic(raw_ostream &OS,
331 const PrintingPolicy &Policy,
332 bool Qualified) const;
333
334 /// Determine whether this declaration, if known to be well-formed within
335 /// its context, will replace the declaration OldD if introduced into scope.
336 ///
337 /// A declaration will replace another declaration if, for example, it is
338 /// a redeclaration of the same variable or function, but not if it is a
339 /// declaration of a different kind (function vs. class) or an overloaded
340 /// function.
341 ///
342 /// \param IsKnownNewer \c true if this declaration is known to be newer
343 /// than \p OldD (for instance, if this declaration is newly-created).
344 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
345
346 /// Determine whether this declaration has linkage.
347 bool hasLinkage() const;
348
349 using Decl::isModulePrivate;
350 using Decl::setModulePrivate;
351
352 /// Determine whether this declaration is a C++ class member.
353 bool isCXXClassMember() const {
354 const DeclContext *DC = getDeclContext();
355
356 // C++0x [class.mem]p1:
357 // The enumerators of an unscoped enumeration defined in
358 // the class are members of the class.
359 if (isa<EnumDecl>(DC))
360 DC = DC->getRedeclContext();
361
362 return DC->isRecord();
363 }
364
365 /// Determine whether the given declaration is an instance member of
366 /// a C++ class.
367 bool isCXXInstanceMember() const;
368
369 /// Determine what kind of linkage this entity has.
370 ///
371 /// This is not the linkage as defined by the standard or the codegen notion
372 /// of linkage. It is just an implementation detail that is used to compute
373 /// those.
374 Linkage getLinkageInternal() const;
375
376 /// Get the linkage from a semantic point of view. Entities in
377 /// anonymous namespaces are external (in c++98).
378 Linkage getFormalLinkage() const {
379 return clang::getFormalLinkage(getLinkageInternal());
380 }
381
382 /// True if this decl has external linkage.
383 bool hasExternalFormalLinkage() const {
384 return isExternalFormalLinkage(getLinkageInternal());
385 }
386
387 bool isExternallyVisible() const {
388 return clang::isExternallyVisible(getLinkageInternal());
389 }
390
391 /// Determine whether this declaration can be redeclared in a
392 /// different translation unit.
393 bool isExternallyDeclarable() const {
394 return isExternallyVisible() && !getOwningModuleForLinkage();
395 }
396
397 /// Determines the visibility of this entity.
398 Visibility getVisibility() const {
399 return getLinkageAndVisibility().getVisibility();
400 }
401
402 /// Determines the linkage and visibility of this entity.
403 LinkageInfo getLinkageAndVisibility() const;
404
405 /// Kinds of explicit visibility.
406 enum ExplicitVisibilityKind {
407 /// Do an LV computation for, ultimately, a type.
408 /// Visibility may be restricted by type visibility settings and
409 /// the visibility of template arguments.
410 VisibilityForType,
411
412 /// Do an LV computation for, ultimately, a non-type declaration.
413 /// Visibility may be restricted by value visibility settings and
414 /// the visibility of template arguments.
415 VisibilityForValue
416 };
417
418 /// If visibility was explicitly specified for this
419 /// declaration, return that visibility.
420 Optional<Visibility>
421 getExplicitVisibility(ExplicitVisibilityKind kind) const;
422
423 /// True if the computed linkage is valid. Used for consistency
424 /// checking. Should always return true.
425 bool isLinkageValid() const;
426
427 /// True if something has required us to compute the linkage
428 /// of this declaration.
429 ///
430 /// Language features which can retroactively change linkage (like a
431 /// typedef name for linkage purposes) may need to consider this,
432 /// but hopefully only in transitory ways during parsing.
433 bool hasLinkageBeenComputed() const {
434 return hasCachedLinkage();
435 }
436
437 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
438 /// the underlying named decl.
439 NamedDecl *getUnderlyingDecl() {
440 // Fast-path the common case.
441 if (this->getKind() != UsingShadow &&
442 this->getKind() != ConstructorUsingShadow &&
443 this->getKind() != ObjCCompatibleAlias &&
444 this->getKind() != NamespaceAlias)
445 return this;
446
447 return getUnderlyingDeclImpl();
448 }
449 const NamedDecl *getUnderlyingDecl() const {
450 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
451 }
452
453 NamedDecl *getMostRecentDecl() {
454 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
455 }
456 const NamedDecl *getMostRecentDecl() const {
457 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
458 }
459
460 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
461
462 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
463 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
464};
465
466inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
467 ND.printName(OS);
468 return OS;
469}
470
471/// Represents the declaration of a label. Labels also have a
472/// corresponding LabelStmt, which indicates the position that the label was
473/// defined at. For normal labels, the location of the decl is the same as the
474/// location of the statement. For GNU local labels (__label__), the decl
475/// location is where the __label__ is.
476class LabelDecl : public NamedDecl {
477 LabelStmt *TheStmt;
478 StringRef MSAsmName;
479 bool MSAsmNameResolved = false;
480
481 /// For normal labels, this is the same as the main declaration
482 /// label, i.e., the location of the identifier; for GNU local labels,
483 /// this is the location of the __label__ keyword.
484 SourceLocation LocStart;
485
486 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
487 LabelStmt *S, SourceLocation StartL)
488 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
489
490 void anchor() override;
491
492public:
493 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
494 SourceLocation IdentL, IdentifierInfo *II);
495 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
496 SourceLocation IdentL, IdentifierInfo *II,
497 SourceLocation GnuLabelL);
498 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
499
500 LabelStmt *getStmt() const { return TheStmt; }
501 void setStmt(LabelStmt *T) { TheStmt = T; }
502
503 bool isGnuLocal() const { return LocStart != getLocation(); }
504 void setLocStart(SourceLocation L) { LocStart = L; }
505
506 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
507 return SourceRange(LocStart, getLocation());
508 }
509
510 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
511 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
512 void setMSAsmLabel(StringRef Name);
513 StringRef getMSAsmLabel() const { return MSAsmName; }
514 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
515
516 // Implement isa/cast/dyncast/etc.
517 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
518 static bool classofKind(Kind K) { return K == Label; }
519};
520
521/// Represent a C++ namespace.
522class NamespaceDecl : public NamedDecl, public DeclContext,
523 public Redeclarable<NamespaceDecl>
524{
525 /// The starting location of the source range, pointing
526 /// to either the namespace or the inline keyword.
527 SourceLocation LocStart;
528
529 /// The ending location of the source range.
530 SourceLocation RBraceLoc;
531
532 /// A pointer to either the anonymous namespace that lives just inside
533 /// this namespace or to the first namespace in the chain (the latter case
534 /// only when this is not the first in the chain), along with a
535 /// boolean value indicating whether this is an inline namespace.
536 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
537
538 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
539 SourceLocation StartLoc, SourceLocation IdLoc,
540 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
541
542 using redeclarable_base = Redeclarable<NamespaceDecl>;
543
544 NamespaceDecl *getNextRedeclarationImpl() override;
545 NamespaceDecl *getPreviousDeclImpl() override;
546 NamespaceDecl *getMostRecentDeclImpl() override;
547
548public:
549 friend class ASTDeclReader;
550 friend class ASTDeclWriter;
551
552 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
553 bool Inline, SourceLocation StartLoc,
554 SourceLocation IdLoc, IdentifierInfo *Id,
555 NamespaceDecl *PrevDecl);
556
557 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
558
559 using redecl_range = redeclarable_base::redecl_range;
560 using redecl_iterator = redeclarable_base::redecl_iterator;
561
562 using redeclarable_base::redecls_begin;
563 using redeclarable_base::redecls_end;
564 using redeclarable_base::redecls;
565 using redeclarable_base::getPreviousDecl;
566 using redeclarable_base::getMostRecentDecl;
567 using redeclarable_base::isFirstDecl;
568
569 /// Returns true if this is an anonymous namespace declaration.
570 ///
571 /// For example:
572 /// \code
573 /// namespace {
574 /// ...
575 /// };
576 /// \endcode
577 /// q.v. C++ [namespace.unnamed]
578 bool isAnonymousNamespace() const {
579 return !getIdentifier();
580 }
581
582 /// Returns true if this is an inline namespace declaration.
583 bool isInline() const {
584 return AnonOrFirstNamespaceAndInline.getInt();
585 }
586
587 /// Set whether this is an inline namespace declaration.
588 void setInline(bool Inline) {
589 AnonOrFirstNamespaceAndInline.setInt(Inline);
590 }
591
592 /// Get the original (first) namespace declaration.
593 NamespaceDecl *getOriginalNamespace();
594
595 /// Get the original (first) namespace declaration.
596 const NamespaceDecl *getOriginalNamespace() const;
597
598 /// Return true if this declaration is an original (first) declaration
599 /// of the namespace. This is false for non-original (subsequent) namespace
600 /// declarations and anonymous namespaces.
601 bool isOriginalNamespace() const;
602
603 /// Retrieve the anonymous namespace nested inside this namespace,
604 /// if any.
605 NamespaceDecl *getAnonymousNamespace() const {
606 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
607 }
608
609 void setAnonymousNamespace(NamespaceDecl *D) {
610 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
611 }
612
613 /// Retrieves the canonical declaration of this namespace.
614 NamespaceDecl *getCanonicalDecl() override {
615 return getOriginalNamespace();
616 }
617 const NamespaceDecl *getCanonicalDecl() const {
618 return getOriginalNamespace();
619 }
620
621 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
622 return SourceRange(LocStart, RBraceLoc);
623 }
624
625 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
626 SourceLocation getRBraceLoc() const { return RBraceLoc; }
627 void setLocStart(SourceLocation L) { LocStart = L; }
628 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
629
630 // Implement isa/cast/dyncast/etc.
631 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
632 static bool classofKind(Kind K) { return K == Namespace; }
633 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
634 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
635 }
636 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
637 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
638 }
639};
640
641/// Represent the declaration of a variable (in which case it is
642/// an lvalue) a function (in which case it is a function designator) or
643/// an enum constant.
644class ValueDecl : public NamedDecl {
645 QualType DeclType;
646
647 void anchor() override;
648
649protected:
650 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
651 DeclarationName N, QualType T)
652 : NamedDecl(DK, DC, L, N), DeclType(T) {}
653
654public:
655 QualType getType() const { return DeclType; }
656 void setType(QualType newType) { DeclType = newType; }
657
658 /// Determine whether this symbol is weakly-imported,
659 /// or declared with the weak or weak-ref attr.
660 bool isWeak() const;
661
662 // Implement isa/cast/dyncast/etc.
663 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
664 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
665};
666
667/// A struct with extended info about a syntactic
668/// name qualifier, to be used for the case of out-of-line declarations.
669struct QualifierInfo {
670 NestedNameSpecifierLoc QualifierLoc;
671
672 /// The number of "outer" template parameter lists.
673 /// The count includes all of the template parameter lists that were matched
674 /// against the template-ids occurring into the NNS and possibly (in the
675 /// case of an explicit specialization) a final "template <>".
676 unsigned NumTemplParamLists = 0;
677
678 /// A new-allocated array of size NumTemplParamLists,
679 /// containing pointers to the "outer" template parameter lists.
680 /// It includes all of the template parameter lists that were matched
681 /// against the template-ids occurring into the NNS and possibly (in the
682 /// case of an explicit specialization) a final "template <>".
683 TemplateParameterList** TemplParamLists = nullptr;
684
685 QualifierInfo() = default;
686 QualifierInfo(const QualifierInfo &) = delete;
687 QualifierInfo& operator=(const QualifierInfo &) = delete;
688
689 /// Sets info about "outer" template parameter lists.
690 void setTemplateParameterListsInfo(ASTContext &Context,
691 ArrayRef<TemplateParameterList *> TPLists);
692};
693
694/// Represents a ValueDecl that came out of a declarator.
695/// Contains type source information through TypeSourceInfo.
696class DeclaratorDecl : public ValueDecl {
697 // A struct representing both a TInfo and a syntactic qualifier,
698 // to be used for the (uncommon) case of out-of-line declarations.
699 struct ExtInfo : public QualifierInfo {
700 TypeSourceInfo *TInfo;
701 };
702
703 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
704
705 /// The start of the source range for this declaration,
706 /// ignoring outer template declarations.
707 SourceLocation InnerLocStart;
708
709 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
710 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
711 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
712
713protected:
714 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
715 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
716 SourceLocation StartL)
717 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
718
719public:
720 friend class ASTDeclReader;
721 friend class ASTDeclWriter;
722
723 TypeSourceInfo *getTypeSourceInfo() const {
724 return hasExtInfo()
14
'?' condition is false
19
Returning pointer, which participates in a condition later
725 ? getExtInfo()->TInfo
726 : DeclInfo.get<TypeSourceInfo*>();
15
Calling 'PointerUnion::get'
18
Returning from 'PointerUnion::get'
727 }
728
729 void setTypeSourceInfo(TypeSourceInfo *TI) {
730 if (hasExtInfo())
731 getExtInfo()->TInfo = TI;
732 else
733 DeclInfo = TI;
734 }
735
736 /// Return start of source range ignoring outer template declarations.
737 SourceLocation getInnerLocStart() const { return InnerLocStart; }
738 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
739
740 /// Return start of source range taking into account any outer template
741 /// declarations.
742 SourceLocation getOuterLocStart() const;
743
744 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
745
746 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
747 return getOuterLocStart();
748 }
749
750 /// Retrieve the nested-name-specifier that qualifies the name of this
751 /// declaration, if it was present in the source.
752 NestedNameSpecifier *getQualifier() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
754 : nullptr;
755 }
756
757 /// Retrieve the nested-name-specifier (with source-location
758 /// information) that qualifies the name of this declaration, if it was
759 /// present in the source.
760 NestedNameSpecifierLoc getQualifierLoc() const {
761 return hasExtInfo() ? getExtInfo()->QualifierLoc
762 : NestedNameSpecifierLoc();
763 }
764
765 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
766
767 unsigned getNumTemplateParameterLists() const {
768 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
769 }
770
771 TemplateParameterList *getTemplateParameterList(unsigned index) const {
772 assert(index < getNumTemplateParameterLists())((index < getNumTemplateParameterLists()) ? static_cast<
void> (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 772, __PRETTY_FUNCTION__))
;
773 return getExtInfo()->TemplParamLists[index];
774 }
775
776 void setTemplateParameterListsInfo(ASTContext &Context,
777 ArrayRef<TemplateParameterList *> TPLists);
778
779 SourceLocation getTypeSpecStartLoc() const;
780
781 // Implement isa/cast/dyncast/etc.
782 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
783 static bool classofKind(Kind K) {
784 return K >= firstDeclarator && K <= lastDeclarator;
785 }
786};
787
788/// Structure used to store a statement, the constant value to
789/// which it was evaluated (if any), and whether or not the statement
790/// is an integral constant expression (if known).
791struct EvaluatedStmt {
792 /// Whether this statement was already evaluated.
793 bool WasEvaluated : 1;
794
795 /// Whether this statement is being evaluated.
796 bool IsEvaluating : 1;
797
798 /// Whether we already checked whether this statement was an
799 /// integral constant expression.
800 bool CheckedICE : 1;
801
802 /// Whether we are checking whether this statement is an
803 /// integral constant expression.
804 bool CheckingICE : 1;
805
806 /// Whether this statement is an integral constant expression,
807 /// or in C++11, whether the statement is a constant expression. Only
808 /// valid if CheckedICE is true.
809 bool IsICE : 1;
810
811 /// Whether this variable is known to have constant destruction. That is,
812 /// whether running the destructor on the initial value is a side-effect
813 /// (and doesn't inspect any state that might have changed during program
814 /// execution). This is currently only computed if the destructor is
815 /// non-trivial.
816 bool HasConstantDestruction : 1;
817
818 Stmt *Value;
819 APValue Evaluated;
820
821 EvaluatedStmt()
822 : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
823 CheckingICE(false), IsICE(false), HasConstantDestruction(false) {}
824};
825
826/// Represents a variable declaration or definition.
827class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
828public:
829 /// Initialization styles.
830 enum InitializationStyle {
831 /// C-style initialization with assignment
832 CInit,
833
834 /// Call-style initialization (C++98)
835 CallInit,
836
837 /// Direct list-initialization (C++11)
838 ListInit
839 };
840
841 /// Kinds of thread-local storage.
842 enum TLSKind {
843 /// Not a TLS variable.
844 TLS_None,
845
846 /// TLS with a known-constant initializer.
847 TLS_Static,
848
849 /// TLS with a dynamic initializer.
850 TLS_Dynamic
851 };
852
853 /// Return the string used to specify the storage class \p SC.
854 ///
855 /// It is illegal to call this function with SC == None.
856 static const char *getStorageClassSpecifierString(StorageClass SC);
857
858protected:
859 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
860 // have allocated the auxiliary struct of information there.
861 //
862 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
863 // this as *many* VarDecls are ParmVarDecls that don't have default
864 // arguments. We could save some space by moving this pointer union to be
865 // allocated in trailing space when necessary.
866 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
867
868 /// The initializer for this variable or, for a ParmVarDecl, the
869 /// C++ default argument.
870 mutable InitType Init;
871
872private:
873 friend class ASTDeclReader;
874 friend class ASTNodeImporter;
875 friend class StmtIteratorBase;
876
877 class VarDeclBitfields {
878 friend class ASTDeclReader;
879 friend class VarDecl;
880
881 unsigned SClass : 3;
882 unsigned TSCSpec : 2;
883 unsigned InitStyle : 2;
884
885 /// Whether this variable is an ARC pseudo-__strong variable; see
886 /// isARCPseudoStrong() for details.
887 unsigned ARCPseudoStrong : 1;
888 };
889 enum { NumVarDeclBits = 8 };
890
891protected:
892 enum { NumParameterIndexBits = 8 };
893
894 enum DefaultArgKind {
895 DAK_None,
896 DAK_Unparsed,
897 DAK_Uninstantiated,
898 DAK_Normal
899 };
900
901 class ParmVarDeclBitfields {
902 friend class ASTDeclReader;
903 friend class ParmVarDecl;
904
905 unsigned : NumVarDeclBits;
906
907 /// Whether this parameter inherits a default argument from a
908 /// prior declaration.
909 unsigned HasInheritedDefaultArg : 1;
910
911 /// Describes the kind of default argument for this parameter. By default
912 /// this is none. If this is normal, then the default argument is stored in
913 /// the \c VarDecl initializer expression unless we were unable to parse
914 /// (even an invalid) expression for the default argument.
915 unsigned DefaultArgKind : 2;
916
917 /// Whether this parameter undergoes K&R argument promotion.
918 unsigned IsKNRPromoted : 1;
919
920 /// Whether this parameter is an ObjC method parameter or not.
921 unsigned IsObjCMethodParam : 1;
922
923 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
924 /// Otherwise, the number of function parameter scopes enclosing
925 /// the function parameter scope in which this parameter was
926 /// declared.
927 unsigned ScopeDepthOrObjCQuals : 7;
928
929 /// The number of parameters preceding this parameter in the
930 /// function parameter scope in which it was declared.
931 unsigned ParameterIndex : NumParameterIndexBits;
932 };
933
934 class NonParmVarDeclBitfields {
935 friend class ASTDeclReader;
936 friend class ImplicitParamDecl;
937 friend class VarDecl;
938
939 unsigned : NumVarDeclBits;
940
941 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
942 /// Whether this variable is a definition which was demoted due to
943 /// module merge.
944 unsigned IsThisDeclarationADemotedDefinition : 1;
945
946 /// Whether this variable is the exception variable in a C++ catch
947 /// or an Objective-C @catch statement.
948 unsigned ExceptionVar : 1;
949
950 /// Whether this local variable could be allocated in the return
951 /// slot of its function, enabling the named return value optimization
952 /// (NRVO).
953 unsigned NRVOVariable : 1;
954
955 /// Whether this variable is the for-range-declaration in a C++0x
956 /// for-range statement.
957 unsigned CXXForRangeDecl : 1;
958
959 /// Whether this variable is the for-in loop declaration in Objective-C.
960 unsigned ObjCForDecl : 1;
961
962 /// Whether this variable is (C++1z) inline.
963 unsigned IsInline : 1;
964
965 /// Whether this variable has (C++1z) inline explicitly specified.
966 unsigned IsInlineSpecified : 1;
967
968 /// Whether this variable is (C++0x) constexpr.
969 unsigned IsConstexpr : 1;
970
971 /// Whether this variable is the implicit variable for a lambda
972 /// init-capture.
973 unsigned IsInitCapture : 1;
974
975 /// Whether this local extern variable's previous declaration was
976 /// declared in the same block scope. This controls whether we should merge
977 /// the type of this declaration with its previous declaration.
978 unsigned PreviousDeclInSameBlockScope : 1;
979
980 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
981 /// something else.
982 unsigned ImplicitParamKind : 3;
983
984 unsigned EscapingByref : 1;
985 };
986
987 union {
988 unsigned AllBits;
989 VarDeclBitfields VarDeclBits;
990 ParmVarDeclBitfields ParmVarDeclBits;
991 NonParmVarDeclBitfields NonParmVarDeclBits;
992 };
993
994 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
995 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
996 TypeSourceInfo *TInfo, StorageClass SC);
997
998 using redeclarable_base = Redeclarable<VarDecl>;
999
1000 VarDecl *getNextRedeclarationImpl() override {
1001 return getNextRedeclaration();
1002 }
1003
1004 VarDecl *getPreviousDeclImpl() override {
1005 return getPreviousDecl();
1006 }
1007
1008 VarDecl *getMostRecentDeclImpl() override {
1009 return getMostRecentDecl();
1010 }
1011
1012public:
1013 using redecl_range = redeclarable_base::redecl_range;
1014 using redecl_iterator = redeclarable_base::redecl_iterator;
1015
1016 using redeclarable_base::redecls_begin;
1017 using redeclarable_base::redecls_end;
1018 using redeclarable_base::redecls;
1019 using redeclarable_base::getPreviousDecl;
1020 using redeclarable_base::getMostRecentDecl;
1021 using redeclarable_base::isFirstDecl;
1022
1023 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1024 SourceLocation StartLoc, SourceLocation IdLoc,
1025 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1026 StorageClass S);
1027
1028 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1029
1030 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1031
1032 /// Returns the storage class as written in the source. For the
1033 /// computed linkage of symbol, see getLinkage.
1034 StorageClass getStorageClass() const {
1035 return (StorageClass) VarDeclBits.SClass;
1036 }
1037 void setStorageClass(StorageClass SC);
1038
1039 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1040 VarDeclBits.TSCSpec = TSC;
1041 assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast
<void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1041, __PRETTY_FUNCTION__))
;
1042 }
1043 ThreadStorageClassSpecifier getTSCSpec() const {
1044 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1045 }
1046 TLSKind getTLSKind() const;
1047
1048 /// Returns true if a variable with function scope is a non-static local
1049 /// variable.
1050 bool hasLocalStorage() const {
1051 if (getStorageClass() == SC_None) {
1052 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1053 // used to describe variables allocated in global memory and which are
1054 // accessed inside a kernel(s) as read-only variables. As such, variables
1055 // in constant address space cannot have local storage.
1056 if (getType().getAddressSpace() == LangAS::opencl_constant)
1057 return false;
1058 // Second check is for C++11 [dcl.stc]p4.
1059 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1060 }
1061
1062 // Global Named Register (GNU extension)
1063 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1064 return false;
1065
1066 // Return true for: Auto, Register.
1067 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1068
1069 return getStorageClass() >= SC_Auto;
1070 }
1071
1072 /// Returns true if a variable with function scope is a static local
1073 /// variable.
1074 bool isStaticLocal() const {
1075 return (getStorageClass() == SC_Static ||
1076 // C++11 [dcl.stc]p4
1077 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1078 && !isFileVarDecl();
1079 }
1080
1081 /// Returns true if a variable has extern or __private_extern__
1082 /// storage.
1083 bool hasExternalStorage() const {
1084 return getStorageClass() == SC_Extern ||
1085 getStorageClass() == SC_PrivateExtern;
1086 }
1087
1088 /// Returns true for all variables that do not have local storage.
1089 ///
1090 /// This includes all global variables as well as static variables declared
1091 /// within a function.
1092 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1093
1094 /// Get the storage duration of this variable, per C++ [basic.stc].
1095 StorageDuration getStorageDuration() const {
1096 return hasLocalStorage() ? SD_Automatic :
1097 getTSCSpec() ? SD_Thread : SD_Static;
1098 }
1099
1100 /// Compute the language linkage.
1101 LanguageLinkage getLanguageLinkage() const;
1102
1103 /// Determines whether this variable is a variable with external, C linkage.
1104 bool isExternC() const;
1105
1106 /// Determines whether this variable's context is, or is nested within,
1107 /// a C++ extern "C" linkage spec.
1108 bool isInExternCContext() const;
1109
1110 /// Determines whether this variable's context is, or is nested within,
1111 /// a C++ extern "C++" linkage spec.
1112 bool isInExternCXXContext() const;
1113
1114 /// Returns true for local variable declarations other than parameters.
1115 /// Note that this includes static variables inside of functions. It also
1116 /// includes variables inside blocks.
1117 ///
1118 /// void foo() { int x; static int y; extern int z; }
1119 bool isLocalVarDecl() const {
1120 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1121 return false;
1122 if (const DeclContext *DC = getLexicalDeclContext())
1123 return DC->getRedeclContext()->isFunctionOrMethod();
1124 return false;
1125 }
1126
1127 /// Similar to isLocalVarDecl but also includes parameters.
1128 bool isLocalVarDeclOrParm() const {
1129 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1130 }
1131
1132 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1133 bool isFunctionOrMethodVarDecl() const {
1134 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1135 return false;
1136 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1137 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1138 }
1139
1140 /// Determines whether this is a static data member.
1141 ///
1142 /// This will only be true in C++, and applies to, e.g., the
1143 /// variable 'x' in:
1144 /// \code
1145 /// struct S {
1146 /// static int x;
1147 /// };
1148 /// \endcode
1149 bool isStaticDataMember() const {
1150 // If it wasn't static, it would be a FieldDecl.
1151 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1152 }
1153
1154 VarDecl *getCanonicalDecl() override;
1155 const VarDecl *getCanonicalDecl() const {
1156 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1157 }
1158
1159 enum DefinitionKind {
1160 /// This declaration is only a declaration.
1161 DeclarationOnly,
1162
1163 /// This declaration is a tentative definition.
1164 TentativeDefinition,
1165
1166 /// This declaration is definitely a definition.
1167 Definition
1168 };
1169
1170 /// Check whether this declaration is a definition. If this could be
1171 /// a tentative definition (in C), don't check whether there's an overriding
1172 /// definition.
1173 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1174 DefinitionKind isThisDeclarationADefinition() const {
1175 return isThisDeclarationADefinition(getASTContext());
1176 }
1177
1178 /// Check whether this variable is defined in this translation unit.
1179 DefinitionKind hasDefinition(ASTContext &) const;
1180 DefinitionKind hasDefinition() const {
1181 return hasDefinition(getASTContext());
1182 }
1183
1184 /// Get the tentative definition that acts as the real definition in a TU.
1185 /// Returns null if there is a proper definition available.
1186 VarDecl *getActingDefinition();
1187 const VarDecl *getActingDefinition() const {
1188 return const_cast<VarDecl*>(this)->getActingDefinition();
1189 }
1190
1191 /// Get the real (not just tentative) definition for this declaration.
1192 VarDecl *getDefinition(ASTContext &);
1193 const VarDecl *getDefinition(ASTContext &C) const {
1194 return const_cast<VarDecl*>(this)->getDefinition(C);
1195 }
1196 VarDecl *getDefinition() {
1197 return getDefinition(getASTContext());
1198 }
1199 const VarDecl *getDefinition() const {
1200 return const_cast<VarDecl*>(this)->getDefinition();
1201 }
1202
1203 /// Determine whether this is or was instantiated from an out-of-line
1204 /// definition of a static data member.
1205 bool isOutOfLine() const override;
1206
1207 /// Returns true for file scoped variable declaration.
1208 bool isFileVarDecl() const {
1209 Kind K = getKind();
1210 if (K == ParmVar || K == ImplicitParam)
1211 return false;
1212
1213 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1214 return true;
1215
1216 if (isStaticDataMember())
1217 return true;
1218
1219 return false;
1220 }
1221
1222 /// Get the initializer for this variable, no matter which
1223 /// declaration it is attached to.
1224 const Expr *getAnyInitializer() const {
1225 const VarDecl *D;
1226 return getAnyInitializer(D);
1227 }
1228
1229 /// Get the initializer for this variable, no matter which
1230 /// declaration it is attached to. Also get that declaration.
1231 const Expr *getAnyInitializer(const VarDecl *&D) const;
1232
1233 bool hasInit() const;
1234 const Expr *getInit() const {
1235 return const_cast<VarDecl *>(this)->getInit();
1236 }
1237 Expr *getInit();
1238
1239 /// Retrieve the address of the initializer expression.
1240 Stmt **getInitAddress();
1241
1242 void setInit(Expr *I);
1243
1244 /// Get the initializing declaration of this variable, if any. This is
1245 /// usually the definition, except that for a static data member it can be
1246 /// the in-class declaration.
1247 VarDecl *getInitializingDeclaration();
1248 const VarDecl *getInitializingDeclaration() const {
1249 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1250 }
1251
1252 /// Determine whether this variable's value might be usable in a
1253 /// constant expression, according to the relevant language standard.
1254 /// This only checks properties of the declaration, and does not check
1255 /// whether the initializer is in fact a constant expression.
1256 bool mightBeUsableInConstantExpressions(ASTContext &C) const;
1257
1258 /// Determine whether this variable's value can be used in a
1259 /// constant expression, according to the relevant language standard,
1260 /// including checking whether it was initialized by a constant expression.
1261 bool isUsableInConstantExpressions(ASTContext &C) const;
1262
1263 EvaluatedStmt *ensureEvaluatedStmt() const;
1264
1265 /// Attempt to evaluate the value of the initializer attached to this
1266 /// declaration, and produce notes explaining why it cannot be evaluated or is
1267 /// not a constant expression. Returns a pointer to the value if evaluation
1268 /// succeeded, 0 otherwise.
1269 APValue *evaluateValue() const;
1270 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1271
1272 /// Return the already-evaluated value of this variable's
1273 /// initializer, or NULL if the value is not yet known. Returns pointer
1274 /// to untyped APValue if the value could not be evaluated.
1275 APValue *getEvaluatedValue() const;
1276
1277 /// Evaluate the destruction of this variable to determine if it constitutes
1278 /// constant destruction.
1279 ///
1280 /// \pre isInitICE()
1281 /// \return \c true if this variable has constant destruction, \c false if
1282 /// not.
1283 bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1284
1285 /// Determines whether it is already known whether the
1286 /// initializer is an integral constant expression or not.
1287 bool isInitKnownICE() const;
1288
1289 /// Determines whether the initializer is an integral constant
1290 /// expression, or in C++11, whether the initializer is a constant
1291 /// expression.
1292 ///
1293 /// \pre isInitKnownICE()
1294 bool isInitICE() const;
1295
1296 /// Determine whether the value of the initializer attached to this
1297 /// declaration is an integral constant expression.
1298 bool checkInitIsICE() const;
1299
1300 void setInitStyle(InitializationStyle Style) {
1301 VarDeclBits.InitStyle = Style;
1302 }
1303
1304 /// The style of initialization for this declaration.
1305 ///
1306 /// C-style initialization is "int x = 1;". Call-style initialization is
1307 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1308 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1309 /// expression for class types. List-style initialization is C++11 syntax,
1310 /// e.g. "int x{1};". Clients can distinguish between different forms of
1311 /// initialization by checking this value. In particular, "int x = {1};" is
1312 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1313 /// Init expression in all three cases is an InitListExpr.
1314 InitializationStyle getInitStyle() const {
1315 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1316 }
1317
1318 /// Whether the initializer is a direct-initializer (list or call).
1319 bool isDirectInit() const {
1320 return getInitStyle() != CInit;
1321 }
1322
1323 /// If this definition should pretend to be a declaration.
1324 bool isThisDeclarationADemotedDefinition() const {
1325 return isa<ParmVarDecl>(this) ? false :
1326 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1327 }
1328
1329 /// This is a definition which should be demoted to a declaration.
1330 ///
1331 /// In some cases (mostly module merging) we can end up with two visible
1332 /// definitions one of which needs to be demoted to a declaration to keep
1333 /// the AST invariants.
1334 void demoteThisDefinitionToDeclaration() {
1335 assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!"
) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1335, __PRETTY_FUNCTION__))
;
1336 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")((!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1336, __PRETTY_FUNCTION__))
;
1337 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1338 }
1339
1340 /// Determine whether this variable is the exception variable in a
1341 /// C++ catch statememt or an Objective-C \@catch statement.
1342 bool isExceptionVariable() const {
1343 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1344 }
1345 void setExceptionVariable(bool EV) {
1346 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1346, __PRETTY_FUNCTION__))
;
1347 NonParmVarDeclBits.ExceptionVar = EV;
1348 }
1349
1350 /// Determine whether this local variable can be used with the named
1351 /// return value optimization (NRVO).
1352 ///
1353 /// The named return value optimization (NRVO) works by marking certain
1354 /// non-volatile local variables of class type as NRVO objects. These
1355 /// locals can be allocated within the return slot of their containing
1356 /// function, in which case there is no need to copy the object to the
1357 /// return slot when returning from the function. Within the function body,
1358 /// each return that returns the NRVO object will have this variable as its
1359 /// NRVO candidate.
1360 bool isNRVOVariable() const {
1361 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1362 }
1363 void setNRVOVariable(bool NRVO) {
1364 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1364, __PRETTY_FUNCTION__))
;
1365 NonParmVarDeclBits.NRVOVariable = NRVO;
1366 }
1367
1368 /// Determine whether this variable is the for-range-declaration in
1369 /// a C++0x for-range statement.
1370 bool isCXXForRangeDecl() const {
1371 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1372 }
1373 void setCXXForRangeDecl(bool FRD) {
1374 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1374, __PRETTY_FUNCTION__))
;
1375 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1376 }
1377
1378 /// Determine whether this variable is a for-loop declaration for a
1379 /// for-in statement in Objective-C.
1380 bool isObjCForDecl() const {
1381 return NonParmVarDeclBits.ObjCForDecl;
1382 }
1383
1384 void setObjCForDecl(bool FRD) {
1385 NonParmVarDeclBits.ObjCForDecl = FRD;
1386 }
1387
1388 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1389 /// pseudo-__strong variable has a __strong-qualified type but does not
1390 /// actually retain the object written into it. Generally such variables are
1391 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1392 /// the variable is annotated with the objc_externally_retained attribute, 2)
1393 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1394 /// loop.
1395 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1396 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1397
1398 /// Whether this variable is (C++1z) inline.
1399 bool isInline() const {
1400 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1401 }
1402 bool isInlineSpecified() const {
1403 return isa<ParmVarDecl>(this) ? false
1404 : NonParmVarDeclBits.IsInlineSpecified;
1405 }
1406 void setInlineSpecified() {
1407 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1407, __PRETTY_FUNCTION__))
;
1408 NonParmVarDeclBits.IsInline = true;
1409 NonParmVarDeclBits.IsInlineSpecified = true;
1410 }
1411 void setImplicitlyInline() {
1412 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1412, __PRETTY_FUNCTION__))
;
1413 NonParmVarDeclBits.IsInline = true;
1414 }
1415
1416 /// Whether this variable is (C++11) constexpr.
1417 bool isConstexpr() const {
1418 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1419 }
1420 void setConstexpr(bool IC) {
1421 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1421, __PRETTY_FUNCTION__))
;
1422 NonParmVarDeclBits.IsConstexpr = IC;
1423 }
1424
1425 /// Whether this variable is the implicit variable for a lambda init-capture.
1426 bool isInitCapture() const {
1427 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1428 }
1429 void setInitCapture(bool IC) {
1430 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1430, __PRETTY_FUNCTION__))
;
1431 NonParmVarDeclBits.IsInitCapture = IC;
1432 }
1433
1434 /// Determine whether this variable is actually a function parameter pack or
1435 /// init-capture pack.
1436 bool isParameterPack() const;
1437
1438 /// Whether this local extern variable declaration's previous declaration
1439 /// was declared in the same block scope. Only correct in C++.
1440 bool isPreviousDeclInSameBlockScope() const {
1441 return isa<ParmVarDecl>(this)
1442 ? false
1443 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1444 }
1445 void setPreviousDeclInSameBlockScope(bool Same) {
1446 assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0
) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1446, __PRETTY_FUNCTION__))
;
1447 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1448 }
1449
1450 /// Indicates the capture is a __block variable that is captured by a block
1451 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1452 /// returns false).
1453 bool isEscapingByref() const;
1454
1455 /// Indicates the capture is a __block variable that is never captured by an
1456 /// escaping block.
1457 bool isNonEscapingByref() const;
1458
1459 void setEscapingByref() {
1460 NonParmVarDeclBits.EscapingByref = true;
1461 }
1462
1463 /// Retrieve the variable declaration from which this variable could
1464 /// be instantiated, if it is an instantiation (rather than a non-template).
1465 VarDecl *getTemplateInstantiationPattern() const;
1466
1467 /// If this variable is an instantiated static data member of a
1468 /// class template specialization, returns the templated static data member
1469 /// from which it was instantiated.
1470 VarDecl *getInstantiatedFromStaticDataMember() const;
1471
1472 /// If this variable is an instantiation of a variable template or a
1473 /// static data member of a class template, determine what kind of
1474 /// template specialization or instantiation this is.
1475 TemplateSpecializationKind getTemplateSpecializationKind() const;
1476
1477 /// Get the template specialization kind of this variable for the purposes of
1478 /// template instantiation. This differs from getTemplateSpecializationKind()
1479 /// for an instantiation of a class-scope explicit specialization.
1480 TemplateSpecializationKind
1481 getTemplateSpecializationKindForInstantiation() const;
1482
1483 /// If this variable is an instantiation of a variable template or a
1484 /// static data member of a class template, determine its point of
1485 /// instantiation.
1486 SourceLocation getPointOfInstantiation() const;
1487
1488 /// If this variable is an instantiation of a static data member of a
1489 /// class template specialization, retrieves the member specialization
1490 /// information.
1491 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1492
1493 /// For a static data member that was instantiated from a static
1494 /// data member of a class template, set the template specialiation kind.
1495 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1496 SourceLocation PointOfInstantiation = SourceLocation());
1497
1498 /// Specify that this variable is an instantiation of the
1499 /// static data member VD.
1500 void setInstantiationOfStaticDataMember(VarDecl *VD,
1501 TemplateSpecializationKind TSK);
1502
1503 /// Retrieves the variable template that is described by this
1504 /// variable declaration.
1505 ///
1506 /// Every variable template is represented as a VarTemplateDecl and a
1507 /// VarDecl. The former contains template properties (such as
1508 /// the template parameter lists) while the latter contains the
1509 /// actual description of the template's
1510 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1511 /// VarDecl that from a VarTemplateDecl, while
1512 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1513 /// a VarDecl.
1514 VarTemplateDecl *getDescribedVarTemplate() const;
1515
1516 void setDescribedVarTemplate(VarTemplateDecl *Template);
1517
1518 // Is this variable known to have a definition somewhere in the complete
1519 // program? This may be true even if the declaration has internal linkage and
1520 // has no definition within this source file.
1521 bool isKnownToBeDefined() const;
1522
1523 /// Is destruction of this variable entirely suppressed? If so, the variable
1524 /// need not have a usable destructor at all.
1525 bool isNoDestroy(const ASTContext &) const;
1526
1527 /// Do we need to emit an exit-time destructor for this variable, and if so,
1528 /// what kind?
1529 QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
1530
1531 // Implement isa/cast/dyncast/etc.
1532 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1533 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1534};
1535
1536class ImplicitParamDecl : public VarDecl {
1537 void anchor() override;
1538
1539public:
1540 /// Defines the kind of the implicit parameter: is this an implicit parameter
1541 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1542 /// context or something else.
1543 enum ImplicitParamKind : unsigned {
1544 /// Parameter for Objective-C 'self' argument
1545 ObjCSelf,
1546
1547 /// Parameter for Objective-C '_cmd' argument
1548 ObjCCmd,
1549
1550 /// Parameter for C++ 'this' argument
1551 CXXThis,
1552
1553 /// Parameter for C++ virtual table pointers
1554 CXXVTT,
1555
1556 /// Parameter for captured context
1557 CapturedContext,
1558
1559 /// Other implicit parameter
1560 Other,
1561 };
1562
1563 /// Create implicit parameter.
1564 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1565 SourceLocation IdLoc, IdentifierInfo *Id,
1566 QualType T, ImplicitParamKind ParamKind);
1567 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1568 ImplicitParamKind ParamKind);
1569
1570 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1571
1572 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1573 IdentifierInfo *Id, QualType Type,
1574 ImplicitParamKind ParamKind)
1575 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1576 /*TInfo=*/nullptr, SC_None) {
1577 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1578 setImplicit();
1579 }
1580
1581 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1582 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1583 SourceLocation(), /*Id=*/nullptr, Type,
1584 /*TInfo=*/nullptr, SC_None) {
1585 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1586 setImplicit();
1587 }
1588
1589 /// Returns the implicit parameter kind.
1590 ImplicitParamKind getParameterKind() const {
1591 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1592 }
1593
1594 // Implement isa/cast/dyncast/etc.
1595 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1596 static bool classofKind(Kind K) { return K == ImplicitParam; }
1597};
1598
1599/// Represents a parameter to a function.
1600class ParmVarDecl : public VarDecl {
1601public:
1602 enum { MaxFunctionScopeDepth = 255 };
1603 enum { MaxFunctionScopeIndex = 255 };
1604
1605protected:
1606 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1607 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1608 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1609 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1610 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)((ParmVarDeclBits.HasInheritedDefaultArg == false) ? static_cast
<void> (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1610, __PRETTY_FUNCTION__))
;
1611 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)((ParmVarDeclBits.DefaultArgKind == DAK_None) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1611, __PRETTY_FUNCTION__))
;
1612 assert(ParmVarDeclBits.IsKNRPromoted == false)((ParmVarDeclBits.IsKNRPromoted == false) ? static_cast<void
> (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1612, __PRETTY_FUNCTION__))
;
1613 assert(ParmVarDeclBits.IsObjCMethodParam == false)((ParmVarDeclBits.IsObjCMethodParam == false) ? static_cast<
void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1613, __PRETTY_FUNCTION__))
;
1614 setDefaultArg(DefArg);
1615 }
1616
1617public:
1618 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1619 SourceLocation StartLoc,
1620 SourceLocation IdLoc, IdentifierInfo *Id,
1621 QualType T, TypeSourceInfo *TInfo,
1622 StorageClass S, Expr *DefArg);
1623
1624 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1625
1626 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1627
1628 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1629 ParmVarDeclBits.IsObjCMethodParam = true;
1630 setParameterIndex(parameterIndex);
1631 }
1632
1633 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1634 assert(!ParmVarDeclBits.IsObjCMethodParam)((!ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1634, __PRETTY_FUNCTION__))
;
1635
1636 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1637 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1638, __PRETTY_FUNCTION__))
1638 && "truncation!")((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1638, __PRETTY_FUNCTION__))
;
1639
1640 setParameterIndex(parameterIndex);
1641 }
1642
1643 bool isObjCMethodParameter() const {
1644 return ParmVarDeclBits.IsObjCMethodParam;
1645 }
1646
1647 unsigned getFunctionScopeDepth() const {
1648 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1649 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1650 }
1651
1652 /// Returns the index of this parameter in its prototype or method scope.
1653 unsigned getFunctionScopeIndex() const {
1654 return getParameterIndex();
1655 }
1656
1657 ObjCDeclQualifier getObjCDeclQualifier() const {
1658 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1659 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1660 }
1661 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1662 assert(ParmVarDeclBits.IsObjCMethodParam)((ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void>
(0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1662, __PRETTY_FUNCTION__))
;
1663 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1664 }
1665
1666 /// True if the value passed to this parameter must undergo
1667 /// K&R-style default argument promotion:
1668 ///
1669 /// C99 6.5.2.2.
1670 /// If the expression that denotes the called function has a type
1671 /// that does not include a prototype, the integer promotions are
1672 /// performed on each argument, and arguments that have type float
1673 /// are promoted to double.
1674 bool isKNRPromoted() const {
1675 return ParmVarDeclBits.IsKNRPromoted;
1676 }
1677 void setKNRPromoted(bool promoted) {
1678 ParmVarDeclBits.IsKNRPromoted = promoted;
1679 }
1680
1681 Expr *getDefaultArg();
1682 const Expr *getDefaultArg() const {
1683 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1684 }
1685
1686 void setDefaultArg(Expr *defarg);
1687
1688 /// Retrieve the source range that covers the entire default
1689 /// argument.
1690 SourceRange getDefaultArgRange() const;
1691 void setUninstantiatedDefaultArg(Expr *arg);
1692 Expr *getUninstantiatedDefaultArg();
1693 const Expr *getUninstantiatedDefaultArg() const {
1694 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1695 }
1696
1697 /// Determines whether this parameter has a default argument,
1698 /// either parsed or not.
1699 bool hasDefaultArg() const;
1700
1701 /// Determines whether this parameter has a default argument that has not
1702 /// yet been parsed. This will occur during the processing of a C++ class
1703 /// whose member functions have default arguments, e.g.,
1704 /// @code
1705 /// class X {
1706 /// public:
1707 /// void f(int x = 17); // x has an unparsed default argument now
1708 /// }; // x has a regular default argument now
1709 /// @endcode
1710 bool hasUnparsedDefaultArg() const {
1711 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1712 }
1713
1714 bool hasUninstantiatedDefaultArg() const {
1715 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1716 }
1717
1718 /// Specify that this parameter has an unparsed default argument.
1719 /// The argument will be replaced with a real default argument via
1720 /// setDefaultArg when the class definition enclosing the function
1721 /// declaration that owns this default argument is completed.
1722 void setUnparsedDefaultArg() {
1723 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1724 }
1725
1726 bool hasInheritedDefaultArg() const {
1727 return ParmVarDeclBits.HasInheritedDefaultArg;
1728 }
1729
1730 void setHasInheritedDefaultArg(bool I = true) {
1731 ParmVarDeclBits.HasInheritedDefaultArg = I;
1732 }
1733
1734 QualType getOriginalType() const;
1735
1736 /// Sets the function declaration that owns this
1737 /// ParmVarDecl. Since ParmVarDecls are often created before the
1738 /// FunctionDecls that own them, this routine is required to update
1739 /// the DeclContext appropriately.
1740 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1741
1742 // Implement isa/cast/dyncast/etc.
1743 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1744 static bool classofKind(Kind K) { return K == ParmVar; }
1745
1746private:
1747 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1748
1749 void setParameterIndex(unsigned parameterIndex) {
1750 if (parameterIndex >= ParameterIndexSentinel) {
1751 setParameterIndexLarge(parameterIndex);
1752 return;
1753 }
1754
1755 ParmVarDeclBits.ParameterIndex = parameterIndex;
1756 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")((ParmVarDeclBits.ParameterIndex == parameterIndex &&
"truncation!") ? static_cast<void> (0) : __assert_fail
("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 1756, __PRETTY_FUNCTION__))
;
1757 }
1758 unsigned getParameterIndex() const {
1759 unsigned d = ParmVarDeclBits.ParameterIndex;
1760 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1761 }
1762
1763 void setParameterIndexLarge(unsigned parameterIndex);
1764 unsigned getParameterIndexLarge() const;
1765};
1766
1767enum class MultiVersionKind {
1768 None,
1769 Target,
1770 CPUSpecific,
1771 CPUDispatch
1772};
1773
1774/// Represents a function declaration or definition.
1775///
1776/// Since a given function can be declared several times in a program,
1777/// there may be several FunctionDecls that correspond to that
1778/// function. Only one of those FunctionDecls will be found when
1779/// traversing the list of declarations in the context of the
1780/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1781/// contains all of the information known about the function. Other,
1782/// previous declarations of the function are available via the
1783/// getPreviousDecl() chain.
1784class FunctionDecl : public DeclaratorDecl,
1785 public DeclContext,
1786 public Redeclarable<FunctionDecl> {
1787 // This class stores some data in DeclContext::FunctionDeclBits
1788 // to save some space. Use the provided accessors to access it.
1789public:
1790 /// The kind of templated function a FunctionDecl can be.
1791 enum TemplatedKind {
1792 // Not templated.
1793 TK_NonTemplate,
1794 // The pattern in a function template declaration.
1795 TK_FunctionTemplate,
1796 // A non-template function that is an instantiation or explicit
1797 // specialization of a member of a templated class.
1798 TK_MemberSpecialization,
1799 // An instantiation or explicit specialization of a function template.
1800 // Note: this might have been instantiated from a templated class if it
1801 // is a class-scope explicit specialization.
1802 TK_FunctionTemplateSpecialization,
1803 // A function template specialization that hasn't yet been resolved to a
1804 // particular specialized function template.
1805 TK_DependentFunctionTemplateSpecialization
1806 };
1807
1808private:
1809 /// A new[]'d array of pointers to VarDecls for the formal
1810 /// parameters of this function. This is null if a prototype or if there are
1811 /// no formals.
1812 ParmVarDecl **ParamInfo = nullptr;
1813
1814 LazyDeclStmtPtr Body;
1815
1816 unsigned ODRHash;
1817
1818 /// End part of this FunctionDecl's source range.
1819 ///
1820 /// We could compute the full range in getSourceRange(). However, when we're
1821 /// dealing with a function definition deserialized from a PCH/AST file,
1822 /// we can only compute the full range once the function body has been
1823 /// de-serialized, so it's far better to have the (sometimes-redundant)
1824 /// EndRangeLoc.
1825 SourceLocation EndRangeLoc;
1826
1827 /// The template or declaration that this declaration
1828 /// describes or was instantiated from, respectively.
1829 ///
1830 /// For non-templates, this value will be NULL. For function
1831 /// declarations that describe a function template, this will be a
1832 /// pointer to a FunctionTemplateDecl. For member functions
1833 /// of class template specializations, this will be a MemberSpecializationInfo
1834 /// pointer containing information about the specialization.
1835 /// For function template specializations, this will be a
1836 /// FunctionTemplateSpecializationInfo, which contains information about
1837 /// the template being specialized and the template arguments involved in
1838 /// that specialization.
1839 llvm::PointerUnion4<FunctionTemplateDecl *,
1840 MemberSpecializationInfo *,
1841 FunctionTemplateSpecializationInfo *,
1842 DependentFunctionTemplateSpecializationInfo *>
1843 TemplateOrSpecialization;
1844
1845 /// Provides source/type location info for the declaration name embedded in
1846 /// the DeclaratorDecl base class.
1847 DeclarationNameLoc DNLoc;
1848
1849 /// Specify that this function declaration is actually a function
1850 /// template specialization.
1851 ///
1852 /// \param C the ASTContext.
1853 ///
1854 /// \param Template the function template that this function template
1855 /// specialization specializes.
1856 ///
1857 /// \param TemplateArgs the template arguments that produced this
1858 /// function template specialization from the template.
1859 ///
1860 /// \param InsertPos If non-NULL, the position in the function template
1861 /// specialization set where the function template specialization data will
1862 /// be inserted.
1863 ///
1864 /// \param TSK the kind of template specialization this is.
1865 ///
1866 /// \param TemplateArgsAsWritten location info of template arguments.
1867 ///
1868 /// \param PointOfInstantiation point at which the function template
1869 /// specialization was first instantiated.
1870 void setFunctionTemplateSpecialization(ASTContext &C,
1871 FunctionTemplateDecl *Template,
1872 const TemplateArgumentList *TemplateArgs,
1873 void *InsertPos,
1874 TemplateSpecializationKind TSK,
1875 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1876 SourceLocation PointOfInstantiation);
1877
1878 /// Specify that this record is an instantiation of the
1879 /// member function FD.
1880 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1881 TemplateSpecializationKind TSK);
1882
1883 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1884
1885 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
1886 // need to access this bit but we want to avoid making ASTDeclWriter
1887 // a friend of FunctionDeclBitfields just for this.
1888 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
1889
1890 /// Whether an ODRHash has been stored.
1891 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
1892
1893 /// State that an ODRHash has been stored.
1894 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
1895
1896protected:
1897 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1898 const DeclarationNameInfo &NameInfo, QualType T,
1899 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1900 ConstexprSpecKind ConstexprKind);
1901
1902 using redeclarable_base = Redeclarable<FunctionDecl>;
1903
1904 FunctionDecl *getNextRedeclarationImpl() override {
1905 return getNextRedeclaration();
1906 }
1907
1908 FunctionDecl *getPreviousDeclImpl() override {
1909 return getPreviousDecl();
1910 }
1911
1912 FunctionDecl *getMostRecentDeclImpl() override {
1913 return getMostRecentDecl();
1914 }
1915
1916public:
1917 friend class ASTDeclReader;
1918 friend class ASTDeclWriter;
1919
1920 using redecl_range = redeclarable_base::redecl_range;
1921 using redecl_iterator = redeclarable_base::redecl_iterator;
1922
1923 using redeclarable_base::redecls_begin;
1924 using redeclarable_base::redecls_end;
1925 using redeclarable_base::redecls;
1926 using redeclarable_base::getPreviousDecl;
1927 using redeclarable_base::getMostRecentDecl;
1928 using redeclarable_base::isFirstDecl;
1929
1930 static FunctionDecl *
1931 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1932 SourceLocation NLoc, DeclarationName N, QualType T,
1933 TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false,
1934 bool hasWrittenPrototype = true,
1935 ConstexprSpecKind ConstexprKind = CSK_unspecified) {
1936 DeclarationNameInfo NameInfo(N, NLoc);
1937 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
1938 isInlineSpecified, hasWrittenPrototype,
1939 ConstexprKind);
1940 }
1941
1942 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1943 SourceLocation StartLoc,
1944 const DeclarationNameInfo &NameInfo, QualType T,
1945 TypeSourceInfo *TInfo, StorageClass SC,
1946 bool isInlineSpecified, bool hasWrittenPrototype,
1947 ConstexprSpecKind ConstexprKind);
1948
1949 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1950
1951 DeclarationNameInfo getNameInfo() const {
1952 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1953 }
1954
1955 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1956 bool Qualified) const override;
1957
1958 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1959
1960 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1961
1962 // Function definitions.
1963 //
1964 // A function declaration may be:
1965 // - a non defining declaration,
1966 // - a definition. A function may be defined because:
1967 // - it has a body, or will have it in the case of late parsing.
1968 // - it has an uninstantiated body. The body does not exist because the
1969 // function is not used yet, but the declaration is considered a
1970 // definition and does not allow other definition of this function.
1971 // - it does not have a user specified body, but it does not allow
1972 // redefinition, because it is deleted/defaulted or is defined through
1973 // some other mechanism (alias, ifunc).
1974
1975 /// Returns true if the function has a body.
1976 ///
1977 /// The function body might be in any of the (re-)declarations of this
1978 /// function. The variant that accepts a FunctionDecl pointer will set that
1979 /// function declaration to the actual declaration containing the body (if
1980 /// there is one).
1981 bool hasBody(const FunctionDecl *&Definition) const;
1982
1983 bool hasBody() const override {
1984 const FunctionDecl* Definition;
1985 return hasBody(Definition);
1986 }
1987
1988 /// Returns whether the function has a trivial body that does not require any
1989 /// specific codegen.
1990 bool hasTrivialBody() const;
1991
1992 /// Returns true if the function has a definition that does not need to be
1993 /// instantiated.
1994 ///
1995 /// The variant that accepts a FunctionDecl pointer will set that function
1996 /// declaration to the declaration that is a definition (if there is one).
1997 bool isDefined(const FunctionDecl *&Definition) const;
1998
1999 virtual bool isDefined() const {
2000 const FunctionDecl* Definition;
2001 return isDefined(Definition);
2002 }
2003
2004 /// Get the definition for this declaration.
2005 FunctionDecl *getDefinition() {
2006 const FunctionDecl *Definition;
2007 if (isDefined(Definition))
2008 return const_cast<FunctionDecl *>(Definition);
2009 return nullptr;
2010 }
2011 const FunctionDecl *getDefinition() const {
2012 return const_cast<FunctionDecl *>(this)->getDefinition();
2013 }
2014
2015 /// Retrieve the body (definition) of the function. The function body might be
2016 /// in any of the (re-)declarations of this function. The variant that accepts
2017 /// a FunctionDecl pointer will set that function declaration to the actual
2018 /// declaration containing the body (if there is one).
2019 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2020 /// unnecessary AST de-serialization of the body.
2021 Stmt *getBody(const FunctionDecl *&Definition) const;
2022
2023 Stmt *getBody() const override {
2024 const FunctionDecl* Definition;
2025 return getBody(Definition);
2026 }
2027
2028 /// Returns whether this specific declaration of the function is also a
2029 /// definition that does not contain uninstantiated body.
2030 ///
2031 /// This does not determine whether the function has been defined (e.g., in a
2032 /// previous definition); for that information, use isDefined.
2033 bool isThisDeclarationADefinition() const {
2034 return isDeletedAsWritten() || isDefaulted() || Body || hasSkippedBody() ||
2035 isLateTemplateParsed() || willHaveBody() || hasDefiningAttr();
2036 }
2037
2038 /// Returns whether this specific declaration of the function has a body.
2039 bool doesThisDeclarationHaveABody() const {
2040 return Body || isLateTemplateParsed();
2041 }
2042
2043 void setBody(Stmt *B);
2044 void setLazyBody(uint64_t Offset) { Body = Offset; }
2045
2046 /// Whether this function is variadic.
2047 bool isVariadic() const;
2048
2049 /// Whether this function is marked as virtual explicitly.
2050 bool isVirtualAsWritten() const {
2051 return FunctionDeclBits.IsVirtualAsWritten;
2052 }
2053
2054 /// State that this function is marked as virtual explicitly.
2055 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2056
2057 /// Whether this virtual function is pure, i.e. makes the containing class
2058 /// abstract.
2059 bool isPure() const { return FunctionDeclBits.IsPure; }
2060 void setPure(bool P = true);
2061
2062 /// Whether this templated function will be late parsed.
2063 bool isLateTemplateParsed() const {
2064 return FunctionDeclBits.IsLateTemplateParsed;
2065 }
2066
2067 /// State that this templated function will be late parsed.
2068 void setLateTemplateParsed(bool ILT = true) {
2069 FunctionDeclBits.IsLateTemplateParsed = ILT;
2070 }
2071
2072 /// Whether this function is "trivial" in some specialized C++ senses.
2073 /// Can only be true for default constructors, copy constructors,
2074 /// copy assignment operators, and destructors. Not meaningful until
2075 /// the class has been fully built by Sema.
2076 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2077 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2078
2079 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2080 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2081
2082 /// Whether this function is defaulted per C++0x. Only valid for
2083 /// special member functions.
2084 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2085 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2086
2087 /// Whether this function is explicitly defaulted per C++0x. Only valid
2088 /// for special member functions.
2089 bool isExplicitlyDefaulted() const {
2090 return FunctionDeclBits.IsExplicitlyDefaulted;
2091 }
2092
2093 /// State that this function is explicitly defaulted per C++0x. Only valid
2094 /// for special member functions.
2095 void setExplicitlyDefaulted(bool ED = true) {
2096 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2097 }
2098
2099 /// Whether falling off this function implicitly returns null/zero.
2100 /// If a more specific implicit return value is required, front-ends
2101 /// should synthesize the appropriate return statements.
2102 bool hasImplicitReturnZero() const {
2103 return FunctionDeclBits.HasImplicitReturnZero;
2104 }
2105
2106 /// State that falling off this function implicitly returns null/zero.
2107 /// If a more specific implicit return value is required, front-ends
2108 /// should synthesize the appropriate return statements.
2109 void setHasImplicitReturnZero(bool IRZ) {
2110 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2111 }
2112
2113 /// Whether this function has a prototype, either because one
2114 /// was explicitly written or because it was "inherited" by merging
2115 /// a declaration without a prototype with a declaration that has a
2116 /// prototype.
2117 bool hasPrototype() const {
2118 return hasWrittenPrototype() || hasInheritedPrototype();
2119 }
2120
2121 /// Whether this function has a written prototype.
2122 bool hasWrittenPrototype() const {
2123 return FunctionDeclBits.HasWrittenPrototype;
2124 }
2125
2126 /// State that this function has a written prototype.
2127 void setHasWrittenPrototype(bool P = true) {
2128 FunctionDeclBits.HasWrittenPrototype = P;
2129 }
2130
2131 /// Whether this function inherited its prototype from a
2132 /// previous declaration.
2133 bool hasInheritedPrototype() const {
2134 return FunctionDeclBits.HasInheritedPrototype;
2135 }
2136
2137 /// State that this function inherited its prototype from a
2138 /// previous declaration.
2139 void setHasInheritedPrototype(bool P = true) {
2140 FunctionDeclBits.HasInheritedPrototype = P;
2141 }
2142
2143 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2144 bool isConstexpr() const {
2145 return FunctionDeclBits.ConstexprKind != CSK_unspecified;
2146 }
2147 void setConstexprKind(ConstexprSpecKind CSK) {
2148 FunctionDeclBits.ConstexprKind = CSK;
2149 }
2150 ConstexprSpecKind getConstexprKind() const {
2151 return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2152 }
2153 bool isConstexprSpecified() const {
2154 return FunctionDeclBits.ConstexprKind == CSK_constexpr;
2155 }
2156 bool isConsteval() const {
2157 return FunctionDeclBits.ConstexprKind == CSK_consteval;
2158 }
2159
2160 /// Whether the instantiation of this function is pending.
2161 /// This bit is set when the decision to instantiate this function is made
2162 /// and unset if and when the function body is created. That leaves out
2163 /// cases where instantiation did not happen because the template definition
2164 /// was not seen in this TU. This bit remains set in those cases, under the
2165 /// assumption that the instantiation will happen in some other TU.
2166 bool instantiationIsPending() const {
2167 return FunctionDeclBits.InstantiationIsPending;
2168 }
2169
2170 /// State that the instantiation of this function is pending.
2171 /// (see instantiationIsPending)
2172 void setInstantiationIsPending(bool IC) {
2173 FunctionDeclBits.InstantiationIsPending = IC;
2174 }
2175
2176 /// Indicates the function uses __try.
2177 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2178 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2179
2180 /// Whether this function has been deleted.
2181 ///
2182 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2183 /// acts like a normal function, except that it cannot actually be
2184 /// called or have its address taken. Deleted functions are
2185 /// typically used in C++ overload resolution to attract arguments
2186 /// whose type or lvalue/rvalue-ness would permit the use of a
2187 /// different overload that would behave incorrectly. For example,
2188 /// one might use deleted functions to ban implicit conversion from
2189 /// a floating-point number to an Integer type:
2190 ///
2191 /// @code
2192 /// struct Integer {
2193 /// Integer(long); // construct from a long
2194 /// Integer(double) = delete; // no construction from float or double
2195 /// Integer(long double) = delete; // no construction from long double
2196 /// };
2197 /// @endcode
2198 // If a function is deleted, its first declaration must be.
2199 bool isDeleted() const {
2200 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2201 }
2202
2203 bool isDeletedAsWritten() const {
2204 return FunctionDeclBits.IsDeleted && !isDefaulted();
2205 }
2206
2207 void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2208
2209 /// Determines whether this function is "main", which is the
2210 /// entry point into an executable program.
2211 bool isMain() const;
2212
2213 /// Determines whether this function is a MSVCRT user defined entry
2214 /// point.
2215 bool isMSVCRTEntryPoint() const;
2216
2217 /// Determines whether this operator new or delete is one
2218 /// of the reserved global placement operators:
2219 /// void *operator new(size_t, void *);
2220 /// void *operator new[](size_t, void *);
2221 /// void operator delete(void *, void *);
2222 /// void operator delete[](void *, void *);
2223 /// These functions have special behavior under [new.delete.placement]:
2224 /// These functions are reserved, a C++ program may not define
2225 /// functions that displace the versions in the Standard C++ library.
2226 /// The provisions of [basic.stc.dynamic] do not apply to these
2227 /// reserved placement forms of operator new and operator delete.
2228 ///
2229 /// This function must be an allocation or deallocation function.
2230 bool isReservedGlobalPlacementOperator() const;
2231
2232 /// Determines whether this function is one of the replaceable
2233 /// global allocation functions:
2234 /// void *operator new(size_t);
2235 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2236 /// void *operator new[](size_t);
2237 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2238 /// void operator delete(void *) noexcept;
2239 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2240 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2241 /// void operator delete[](void *) noexcept;
2242 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2243 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2244 /// These functions have special behavior under C++1y [expr.new]:
2245 /// An implementation is allowed to omit a call to a replaceable global
2246 /// allocation function. [...]
2247 ///
2248 /// If this function is an aligned allocation/deallocation function, return
2249 /// true through IsAligned.
2250 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2251
2252 /// Determine whether this is a destroying operator delete.
2253 bool isDestroyingOperatorDelete() const;
2254
2255 /// Compute the language linkage.
2256 LanguageLinkage getLanguageLinkage() const;
2257
2258 /// Determines whether this function is a function with
2259 /// external, C linkage.
2260 bool isExternC() const;
2261
2262 /// Determines whether this function's context is, or is nested within,
2263 /// a C++ extern "C" linkage spec.
2264 bool isInExternCContext() const;
2265
2266 /// Determines whether this function's context is, or is nested within,
2267 /// a C++ extern "C++" linkage spec.
2268 bool isInExternCXXContext() const;
2269
2270 /// Determines whether this is a global function.
2271 bool isGlobal() const;
2272
2273 /// Determines whether this function is known to be 'noreturn', through
2274 /// an attribute on its declaration or its type.
2275 bool isNoReturn() const;
2276
2277 /// True if the function was a definition but its body was skipped.
2278 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2279 void setHasSkippedBody(bool Skipped = true) {
2280 FunctionDeclBits.HasSkippedBody = Skipped;
2281 }
2282
2283 /// True if this function will eventually have a body, once it's fully parsed.
2284 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2285 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2286
2287 /// True if this function is considered a multiversioned function.
2288 bool isMultiVersion() const {
2289 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2290 }
2291
2292 /// Sets the multiversion state for this declaration and all of its
2293 /// redeclarations.
2294 void setIsMultiVersion(bool V = true) {
2295 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2296 }
2297
2298 /// Gets the kind of multiversioning attribute this declaration has. Note that
2299 /// this can return a value even if the function is not multiversion, such as
2300 /// the case of 'target'.
2301 MultiVersionKind getMultiVersionKind() const;
2302
2303
2304 /// True if this function is a multiversioned dispatch function as a part of
2305 /// the cpu_specific/cpu_dispatch functionality.
2306 bool isCPUDispatchMultiVersion() const;
2307 /// True if this function is a multiversioned processor specific function as a
2308 /// part of the cpu_specific/cpu_dispatch functionality.
2309 bool isCPUSpecificMultiVersion() const;
2310
2311 /// True if this function is a multiversioned dispatch function as a part of
2312 /// the target functionality.
2313 bool isTargetMultiVersion() const;
2314
2315 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2316
2317 FunctionDecl *getCanonicalDecl() override;
2318 const FunctionDecl *getCanonicalDecl() const {
2319 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2320 }
2321
2322 unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2323
2324 // ArrayRef interface to parameters.
2325 ArrayRef<ParmVarDecl *> parameters() const {
2326 return {ParamInfo, getNumParams()};
2327 }
2328 MutableArrayRef<ParmVarDecl *> parameters() {
2329 return {ParamInfo, getNumParams()};
2330 }
2331
2332 // Iterator access to formal parameters.
2333 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2334 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2335
2336 bool param_empty() const { return parameters().empty(); }
2337 param_iterator param_begin() { return parameters().begin(); }
2338 param_iterator param_end() { return parameters().end(); }
2339 param_const_iterator param_begin() const { return parameters().begin(); }
2340 param_const_iterator param_end() const { return parameters().end(); }
2341 size_t param_size() const { return parameters().size(); }
2342
2343 /// Return the number of parameters this function must have based on its
2344 /// FunctionType. This is the length of the ParamInfo array after it has been
2345 /// created.
2346 unsigned getNumParams() const;
2347
2348 const ParmVarDecl *getParamDecl(unsigned i) const {
2349 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2349, __PRETTY_FUNCTION__))
;
2350 return ParamInfo[i];
2351 }
2352 ParmVarDecl *getParamDecl(unsigned i) {
2353 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2353, __PRETTY_FUNCTION__))
;
2354 return ParamInfo[i];
2355 }
2356 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2357 setParams(getASTContext(), NewParamInfo);
2358 }
2359
2360 /// Returns the minimum number of arguments needed to call this function. This
2361 /// may be fewer than the number of function parameters, if some of the
2362 /// parameters have default arguments (in C++).
2363 unsigned getMinRequiredArguments() const;
2364
2365 QualType getReturnType() const {
2366 return getType()->castAs<FunctionType>()->getReturnType();
2367 }
2368
2369 /// Attempt to compute an informative source range covering the
2370 /// function return type. This may omit qualifiers and other information with
2371 /// limited representation in the AST.
2372 SourceRange getReturnTypeSourceRange() const;
2373
2374 /// Get the declared return type, which may differ from the actual return
2375 /// type if the return type is deduced.
2376 QualType getDeclaredReturnType() const {
2377 auto *TSI = getTypeSourceInfo();
2378 QualType T = TSI ? TSI->getType() : getType();
2379 return T->castAs<FunctionType>()->getReturnType();
2380 }
2381
2382 /// Gets the ExceptionSpecificationType as declared.
2383 ExceptionSpecificationType getExceptionSpecType() const {
2384 auto *TSI = getTypeSourceInfo();
2385 QualType T = TSI ? TSI->getType() : getType();
2386 const auto *FPT = T->getAs<FunctionProtoType>();
2387 return FPT ? FPT->getExceptionSpecType() : EST_None;
2388 }
2389
2390 /// Attempt to compute an informative source range covering the
2391 /// function exception specification, if any.
2392 SourceRange getExceptionSpecSourceRange() const;
2393
2394 /// Determine the type of an expression that calls this function.
2395 QualType getCallResultType() const {
2396 return getType()->castAs<FunctionType>()->getCallResultType(
2397 getASTContext());
2398 }
2399
2400 /// Returns the storage class as written in the source. For the
2401 /// computed linkage of symbol, see getLinkage.
2402 StorageClass getStorageClass() const {
2403 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2404 }
2405
2406 /// Sets the storage class as written in the source.
2407 void setStorageClass(StorageClass SClass) {
2408 FunctionDeclBits.SClass = SClass;
2409 }
2410
2411 /// Determine whether the "inline" keyword was specified for this
2412 /// function.
2413 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2414
2415 /// Set whether the "inline" keyword was specified for this function.
2416 void setInlineSpecified(bool I) {
2417 FunctionDeclBits.IsInlineSpecified = I;
2418 FunctionDeclBits.IsInline = I;
2419 }
2420
2421 /// Flag that this function is implicitly inline.
2422 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2423
2424 /// Determine whether this function should be inlined, because it is
2425 /// either marked "inline" or "constexpr" or is a member function of a class
2426 /// that was defined in the class body.
2427 bool isInlined() const { return FunctionDeclBits.IsInline; }
2428
2429 bool isInlineDefinitionExternallyVisible() const;
2430
2431 bool isMSExternInline() const;
2432
2433 bool doesDeclarationForceExternallyVisibleDefinition() const;
2434
2435 bool isStatic() const { return getStorageClass() == SC_Static; }
2436
2437 /// Whether this function declaration represents an C++ overloaded
2438 /// operator, e.g., "operator+".
2439 bool isOverloadedOperator() const {
2440 return getOverloadedOperator() != OO_None;
2441 }
2442
2443 OverloadedOperatorKind getOverloadedOperator() const;
2444
2445 const IdentifierInfo *getLiteralIdentifier() const;
2446
2447 /// If this function is an instantiation of a member function
2448 /// of a class template specialization, retrieves the function from
2449 /// which it was instantiated.
2450 ///
2451 /// This routine will return non-NULL for (non-templated) member
2452 /// functions of class templates and for instantiations of function
2453 /// templates. For example, given:
2454 ///
2455 /// \code
2456 /// template<typename T>
2457 /// struct X {
2458 /// void f(T);
2459 /// };
2460 /// \endcode
2461 ///
2462 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2463 /// whose parent is the class template specialization X<int>. For
2464 /// this declaration, getInstantiatedFromFunction() will return
2465 /// the FunctionDecl X<T>::A. When a complete definition of
2466 /// X<int>::A is required, it will be instantiated from the
2467 /// declaration returned by getInstantiatedFromMemberFunction().
2468 FunctionDecl *getInstantiatedFromMemberFunction() const;
2469
2470 /// What kind of templated function this is.
2471 TemplatedKind getTemplatedKind() const;
2472
2473 /// If this function is an instantiation of a member function of a
2474 /// class template specialization, retrieves the member specialization
2475 /// information.
2476 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2477
2478 /// Specify that this record is an instantiation of the
2479 /// member function FD.
2480 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2481 TemplateSpecializationKind TSK) {
2482 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2483 }
2484
2485 /// Retrieves the function template that is described by this
2486 /// function declaration.
2487 ///
2488 /// Every function template is represented as a FunctionTemplateDecl
2489 /// and a FunctionDecl (or something derived from FunctionDecl). The
2490 /// former contains template properties (such as the template
2491 /// parameter lists) while the latter contains the actual
2492 /// description of the template's
2493 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2494 /// FunctionDecl that describes the function template,
2495 /// getDescribedFunctionTemplate() retrieves the
2496 /// FunctionTemplateDecl from a FunctionDecl.
2497 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2498
2499 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2500
2501 /// Determine whether this function is a function template
2502 /// specialization.
2503 bool isFunctionTemplateSpecialization() const {
2504 return getPrimaryTemplate() != nullptr;
2505 }
2506
2507 /// If this function is actually a function template specialization,
2508 /// retrieve information about this function template specialization.
2509 /// Otherwise, returns NULL.
2510 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2511
2512 /// Determines whether this function is a function template
2513 /// specialization or a member of a class template specialization that can
2514 /// be implicitly instantiated.
2515 bool isImplicitlyInstantiable() const;
2516
2517 /// Determines if the given function was instantiated from a
2518 /// function template.
2519 bool isTemplateInstantiation() const;
2520
2521 /// Retrieve the function declaration from which this function could
2522 /// be instantiated, if it is an instantiation (rather than a non-template
2523 /// or a specialization, for example).
2524 FunctionDecl *getTemplateInstantiationPattern() const;
2525
2526 /// Retrieve the primary template that this function template
2527 /// specialization either specializes or was instantiated from.
2528 ///
2529 /// If this function declaration is not a function template specialization,
2530 /// returns NULL.
2531 FunctionTemplateDecl *getPrimaryTemplate() const;
2532
2533 /// Retrieve the template arguments used to produce this function
2534 /// template specialization from the primary template.
2535 ///
2536 /// If this function declaration is not a function template specialization,
2537 /// returns NULL.
2538 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2539
2540 /// Retrieve the template argument list as written in the sources,
2541 /// if any.
2542 ///
2543 /// If this function declaration is not a function template specialization
2544 /// or if it had no explicit template argument list, returns NULL.
2545 /// Note that it an explicit template argument list may be written empty,
2546 /// e.g., template<> void foo<>(char* s);
2547 const ASTTemplateArgumentListInfo*
2548 getTemplateSpecializationArgsAsWritten() const;
2549
2550 /// Specify that this function declaration is actually a function
2551 /// template specialization.
2552 ///
2553 /// \param Template the function template that this function template
2554 /// specialization specializes.
2555 ///
2556 /// \param TemplateArgs the template arguments that produced this
2557 /// function template specialization from the template.
2558 ///
2559 /// \param InsertPos If non-NULL, the position in the function template
2560 /// specialization set where the function template specialization data will
2561 /// be inserted.
2562 ///
2563 /// \param TSK the kind of template specialization this is.
2564 ///
2565 /// \param TemplateArgsAsWritten location info of template arguments.
2566 ///
2567 /// \param PointOfInstantiation point at which the function template
2568 /// specialization was first instantiated.
2569 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2570 const TemplateArgumentList *TemplateArgs,
2571 void *InsertPos,
2572 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2573 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2574 SourceLocation PointOfInstantiation = SourceLocation()) {
2575 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2576 InsertPos, TSK, TemplateArgsAsWritten,
2577 PointOfInstantiation);
2578 }
2579
2580 /// Specifies that this function declaration is actually a
2581 /// dependent function template specialization.
2582 void setDependentTemplateSpecialization(ASTContext &Context,
2583 const UnresolvedSetImpl &Templates,
2584 const TemplateArgumentListInfo &TemplateArgs);
2585
2586 DependentFunctionTemplateSpecializationInfo *
2587 getDependentSpecializationInfo() const;
2588
2589 /// Determine what kind of template instantiation this function
2590 /// represents.
2591 TemplateSpecializationKind getTemplateSpecializationKind() const;
2592
2593 /// Determine the kind of template specialization this function represents
2594 /// for the purpose of template instantiation.
2595 TemplateSpecializationKind
2596 getTemplateSpecializationKindForInstantiation() const;
2597
2598 /// Determine what kind of template instantiation this function
2599 /// represents.
2600 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2601 SourceLocation PointOfInstantiation = SourceLocation());
2602
2603 /// Retrieve the (first) point of instantiation of a function template
2604 /// specialization or a member of a class template specialization.
2605 ///
2606 /// \returns the first point of instantiation, if this function was
2607 /// instantiated from a template; otherwise, returns an invalid source
2608 /// location.
2609 SourceLocation getPointOfInstantiation() const;
2610
2611 /// Determine whether this is or was instantiated from an out-of-line
2612 /// definition of a member function.
2613 bool isOutOfLine() const override;
2614
2615 /// Identify a memory copying or setting function.
2616 /// If the given function is a memory copy or setting function, returns
2617 /// the corresponding Builtin ID. If the function is not a memory function,
2618 /// returns 0.
2619 unsigned getMemoryFunctionKind() const;
2620
2621 /// Returns ODRHash of the function. This value is calculated and
2622 /// stored on first call, then the stored value returned on the other calls.
2623 unsigned getODRHash();
2624
2625 /// Returns cached ODRHash of the function. This must have been previously
2626 /// computed and stored.
2627 unsigned getODRHash() const;
2628
2629 // Implement isa/cast/dyncast/etc.
2630 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2631 static bool classofKind(Kind K) {
2632 return K >= firstFunction && K <= lastFunction;
2633 }
2634 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2635 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2636 }
2637 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2638 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2639 }
2640};
2641
2642/// Represents a member of a struct/union/class.
2643class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2644 unsigned BitField : 1;
2645 unsigned Mutable : 1;
2646 mutable unsigned CachedFieldIndex : 30;
2647
2648 /// The kinds of value we can store in InitializerOrBitWidth.
2649 ///
2650 /// Note that this is compatible with InClassInitStyle except for
2651 /// ISK_CapturedVLAType.
2652 enum InitStorageKind {
2653 /// If the pointer is null, there's nothing special. Otherwise,
2654 /// this is a bitfield and the pointer is the Expr* storing the
2655 /// bit-width.
2656 ISK_NoInit = (unsigned) ICIS_NoInit,
2657
2658 /// The pointer is an (optional due to delayed parsing) Expr*
2659 /// holding the copy-initializer.
2660 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2661
2662 /// The pointer is an (optional due to delayed parsing) Expr*
2663 /// holding the list-initializer.
2664 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2665
2666 /// The pointer is a VariableArrayType* that's been captured;
2667 /// the enclosing context is a lambda or captured statement.
2668 ISK_CapturedVLAType,
2669 };
2670
2671 /// If this is a bitfield with a default member initializer, this
2672 /// structure is used to represent the two expressions.
2673 struct InitAndBitWidth {
2674 Expr *Init;
2675 Expr *BitWidth;
2676 };
2677
2678 /// Storage for either the bit-width, the in-class initializer, or
2679 /// both (via InitAndBitWidth), or the captured variable length array bound.
2680 ///
2681 /// If the storage kind is ISK_InClassCopyInit or
2682 /// ISK_InClassListInit, but the initializer is null, then this
2683 /// field has an in-class initializer that has not yet been parsed
2684 /// and attached.
2685 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2686 // overwhelmingly common case that we have none of these things.
2687 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2688
2689protected:
2690 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2691 SourceLocation IdLoc, IdentifierInfo *Id,
2692 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2693 InClassInitStyle InitStyle)
2694 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2695 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2696 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2697 if (BW)
2698 setBitWidth(BW);
2699 }
2700
2701public:
2702 friend class ASTDeclReader;
2703 friend class ASTDeclWriter;
2704
2705 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2706 SourceLocation StartLoc, SourceLocation IdLoc,
2707 IdentifierInfo *Id, QualType T,
2708 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2709 InClassInitStyle InitStyle);
2710
2711 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2712
2713 /// Returns the index of this field within its record,
2714 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2715 unsigned getFieldIndex() const;
2716
2717 /// Determines whether this field is mutable (C++ only).
2718 bool isMutable() const { return Mutable; }
2719
2720 /// Determines whether this field is a bitfield.
2721 bool isBitField() const { return BitField; }
2722
2723 /// Determines whether this is an unnamed bitfield.
2724 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2725
2726 /// Determines whether this field is a
2727 /// representative for an anonymous struct or union. Such fields are
2728 /// unnamed and are implicitly generated by the implementation to
2729 /// store the data for the anonymous union or struct.
2730 bool isAnonymousStructOrUnion() const;
2731
2732 Expr *getBitWidth() const {
2733 if (!BitField)
2734 return nullptr;
2735 void *Ptr = InitStorage.getPointer();
2736 if (getInClassInitStyle())
2737 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2738 return static_cast<Expr*>(Ptr);
2739 }
2740
2741 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2742
2743 /// Set the bit-field width for this member.
2744 // Note: used by some clients (i.e., do not remove it).
2745 void setBitWidth(Expr *Width) {
2746 assert(!hasCapturedVLAType() && !BitField &&((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2747, __PRETTY_FUNCTION__))
2747 "bit width or captured type already set")((!hasCapturedVLAType() && !BitField && "bit width or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2747, __PRETTY_FUNCTION__))
;
2748 assert(Width && "no bit width specified")((Width && "no bit width specified") ? static_cast<
void> (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2748, __PRETTY_FUNCTION__))
;
2749 InitStorage.setPointer(
2750 InitStorage.getInt()
2751 ? new (getASTContext())
2752 InitAndBitWidth{getInClassInitializer(), Width}
2753 : static_cast<void*>(Width));
2754 BitField = true;
2755 }
2756
2757 /// Remove the bit-field width from this member.
2758 // Note: used by some clients (i.e., do not remove it).
2759 void removeBitWidth() {
2760 assert(isBitField() && "no bitfield width to remove")((isBitField() && "no bitfield width to remove") ? static_cast
<void> (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2760, __PRETTY_FUNCTION__))
;
2761 InitStorage.setPointer(getInClassInitializer());
2762 BitField = false;
2763 }
2764
2765 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
2766 /// at all and instead act as a separator between contiguous runs of other
2767 /// bit-fields.
2768 bool isZeroLengthBitField(const ASTContext &Ctx) const;
2769
2770 /// Determine if this field is a subobject of zero size, that is, either a
2771 /// zero-length bit-field or a field of empty class type with the
2772 /// [[no_unique_address]] attribute.
2773 bool isZeroSize(const ASTContext &Ctx) const;
2774
2775 /// Get the kind of (C++11) default member initializer that this field has.
2776 InClassInitStyle getInClassInitStyle() const {
2777 InitStorageKind storageKind = InitStorage.getInt();
2778 return (storageKind == ISK_CapturedVLAType
2779 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2780 }
2781
2782 /// Determine whether this member has a C++11 default member initializer.
2783 bool hasInClassInitializer() const {
2784 return getInClassInitStyle() != ICIS_NoInit;
2785 }
2786
2787 /// Get the C++11 default member initializer for this member, or null if one
2788 /// has not been set. If a valid declaration has a default member initializer,
2789 /// but this returns null, then we have not parsed and attached it yet.
2790 Expr *getInClassInitializer() const {
2791 if (!hasInClassInitializer())
2792 return nullptr;
2793 void *Ptr = InitStorage.getPointer();
2794 if (BitField)
2795 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2796 return static_cast<Expr*>(Ptr);
2797 }
2798
2799 /// Set the C++11 in-class initializer for this member.
2800 void setInClassInitializer(Expr *Init) {
2801 assert(hasInClassInitializer() && !getInClassInitializer())((hasInClassInitializer() && !getInClassInitializer()
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2801, __PRETTY_FUNCTION__))
;
2802 if (BitField)
2803 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2804 else
2805 InitStorage.setPointer(Init);
2806 }
2807
2808 /// Remove the C++11 in-class initializer from this member.
2809 void removeInClassInitializer() {
2810 assert(hasInClassInitializer() && "no initializer to remove")((hasInClassInitializer() && "no initializer to remove"
) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2810, __PRETTY_FUNCTION__))
;
2811 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2812 }
2813
2814 /// Determine whether this member captures the variable length array
2815 /// type.
2816 bool hasCapturedVLAType() const {
2817 return InitStorage.getInt() == ISK_CapturedVLAType;
2818 }
2819
2820 /// Get the captured variable length array type.
2821 const VariableArrayType *getCapturedVLAType() const {
2822 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2823 InitStorage.getPointer())
2824 : nullptr;
2825 }
2826
2827 /// Set the captured variable length array type for this field.
2828 void setCapturedVLAType(const VariableArrayType *VLAType);
2829
2830 /// Returns the parent of this field declaration, which
2831 /// is the struct in which this field is defined.
2832 const RecordDecl *getParent() const {
2833 return cast<RecordDecl>(getDeclContext());
2834 }
2835
2836 RecordDecl *getParent() {
2837 return cast<RecordDecl>(getDeclContext());
2838 }
2839
2840 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2841
2842 /// Retrieves the canonical declaration of this field.
2843 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2844 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2845
2846 // Implement isa/cast/dyncast/etc.
2847 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2848 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2849};
2850
2851/// An instance of this object exists for each enum constant
2852/// that is defined. For example, in "enum X {a,b}", each of a/b are
2853/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2854/// TagType for the X EnumDecl.
2855class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2856 Stmt *Init; // an integer constant expression
2857 llvm::APSInt Val; // The value.
2858
2859protected:
2860 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2861 IdentifierInfo *Id, QualType T, Expr *E,
2862 const llvm::APSInt &V)
2863 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2864
2865public:
2866 friend class StmtIteratorBase;
2867
2868 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2869 SourceLocation L, IdentifierInfo *Id,
2870 QualType T, Expr *E,
2871 const llvm::APSInt &V);
2872 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2873
2874 const Expr *getInitExpr() const { return (const Expr*) Init; }
2875 Expr *getInitExpr() { return (Expr*) Init; }
2876 const llvm::APSInt &getInitVal() const { return Val; }
2877
2878 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2879 void setInitVal(const llvm::APSInt &V) { Val = V; }
2880
2881 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2882
2883 /// Retrieves the canonical declaration of this enumerator.
2884 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2885 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2886
2887 // Implement isa/cast/dyncast/etc.
2888 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2889 static bool classofKind(Kind K) { return K == EnumConstant; }
2890};
2891
2892/// Represents a field injected from an anonymous union/struct into the parent
2893/// scope. These are always implicit.
2894class IndirectFieldDecl : public ValueDecl,
2895 public Mergeable<IndirectFieldDecl> {
2896 NamedDecl **Chaining;
2897 unsigned ChainingSize;
2898
2899 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2900 DeclarationName N, QualType T,
2901 MutableArrayRef<NamedDecl *> CH);
2902
2903 void anchor() override;
2904
2905public:
2906 friend class ASTDeclReader;
2907
2908 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2909 SourceLocation L, IdentifierInfo *Id,
2910 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2911
2912 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2913
2914 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2915
2916 ArrayRef<NamedDecl *> chain() const {
2917 return llvm::makeArrayRef(Chaining, ChainingSize);
2918 }
2919 chain_iterator chain_begin() const { return chain().begin(); }
2920 chain_iterator chain_end() const { return chain().end(); }
2921
2922 unsigned getChainingSize() const { return ChainingSize; }
2923
2924 FieldDecl *getAnonField() const {
2925 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2925, __PRETTY_FUNCTION__))
;
2926 return cast<FieldDecl>(chain().back());
2927 }
2928
2929 VarDecl *getVarDecl() const {
2930 assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail
("chain().size() >= 2", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 2930, __PRETTY_FUNCTION__))
;
2931 return dyn_cast<VarDecl>(chain().front());
2932 }
2933
2934 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2935 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2936
2937 // Implement isa/cast/dyncast/etc.
2938 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2939 static bool classofKind(Kind K) { return K == IndirectField; }
2940};
2941
2942/// Represents a declaration of a type.
2943class TypeDecl : public NamedDecl {
2944 friend class ASTContext;
2945
2946 /// This indicates the Type object that represents
2947 /// this TypeDecl. It is a cache maintained by
2948 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2949 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2950 mutable const Type *TypeForDecl = nullptr;
2951
2952 /// The start of the source range for this declaration.
2953 SourceLocation LocStart;
2954
2955 void anchor() override;
2956
2957protected:
2958 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2959 SourceLocation StartL = SourceLocation())
2960 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
2961
2962public:
2963 // Low-level accessor. If you just want the type defined by this node,
2964 // check out ASTContext::getTypeDeclType or one of
2965 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2966 // already know the specific kind of node this is.
2967 const Type *getTypeForDecl() const { return TypeForDecl; }
2968 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2969
2970 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
2971 void setLocStart(SourceLocation L) { LocStart = L; }
2972 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2973 if (LocStart.isValid())
2974 return SourceRange(LocStart, getLocation());
2975 else
2976 return SourceRange(getLocation());
2977 }
2978
2979 // Implement isa/cast/dyncast/etc.
2980 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2981 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2982};
2983
2984/// Base class for declarations which introduce a typedef-name.
2985class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2986 struct alignas(8) ModedTInfo {
2987 TypeSourceInfo *first;
2988 QualType second;
2989 };
2990
2991 /// If int part is 0, we have not computed IsTransparentTag.
2992 /// Otherwise, IsTransparentTag is (getInt() >> 1).
2993 mutable llvm::PointerIntPair<
2994 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
2995 MaybeModedTInfo;
2996
2997 void anchor() override;
2998
2999protected:
3000 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
3001 SourceLocation StartLoc, SourceLocation IdLoc,
3002 IdentifierInfo *Id, TypeSourceInfo *TInfo)
3003 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
3004 MaybeModedTInfo(TInfo, 0) {}
3005
3006 using redeclarable_base = Redeclarable<TypedefNameDecl>;
3007
3008 TypedefNameDecl *getNextRedeclarationImpl() override {
3009 return getNextRedeclaration();
3010 }
3011
3012 TypedefNameDecl *getPreviousDeclImpl() override {
3013 return getPreviousDecl();
3014 }
3015
3016 TypedefNameDecl *getMostRecentDeclImpl() override {
3017 return getMostRecentDecl();
3018 }
3019
3020public:
3021 using redecl_range = redeclarable_base::redecl_range;
3022 using redecl_iterator = redeclarable_base::redecl_iterator;
3023
3024 using redeclarable_base::redecls_begin;
3025 using redeclarable_base::redecls_end;
3026 using redeclarable_base::redecls;
3027 using redeclarable_base::getPreviousDecl;
3028 using redeclarable_base::getMostRecentDecl;
3029 using redeclarable_base::isFirstDecl;
3030
3031 bool isModed() const {
3032 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
3033 }
3034
3035 TypeSourceInfo *getTypeSourceInfo() const {
3036 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
3037 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
3038 }
3039
3040 QualType getUnderlyingType() const {
3041 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
3042 : MaybeModedTInfo.getPointer()
3043 .get<TypeSourceInfo *>()
3044 ->getType();
3045 }
3046
3047 void setTypeSourceInfo(TypeSourceInfo *newType) {
3048 MaybeModedTInfo.setPointer(newType);
3049 }
3050
3051 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
3052 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
3053 ModedTInfo({unmodedTSI, modedTy}));
3054 }
3055
3056 /// Retrieves the canonical declaration of this typedef-name.
3057 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
3058 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
3059
3060 /// Retrieves the tag declaration for which this is the typedef name for
3061 /// linkage purposes, if any.
3062 ///
3063 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3064 /// this typedef declaration.
3065 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3066
3067 /// Determines if this typedef shares a name and spelling location with its
3068 /// underlying tag type, as is the case with the NS_ENUM macro.
3069 bool isTransparentTag() const {
3070 if (MaybeModedTInfo.getInt())
3071 return MaybeModedTInfo.getInt() & 0x2;
3072 return isTransparentTagSlow();
3073 }
3074
3075 // Implement isa/cast/dyncast/etc.
3076 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3077 static bool classofKind(Kind K) {
3078 return K >= firstTypedefName && K <= lastTypedefName;
3079 }
3080
3081private:
3082 bool isTransparentTagSlow() const;
3083};
3084
3085/// Represents the declaration of a typedef-name via the 'typedef'
3086/// type specifier.
3087class TypedefDecl : public TypedefNameDecl {
3088 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3089 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3090 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3091
3092public:
3093 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3094 SourceLocation StartLoc, SourceLocation IdLoc,
3095 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3096 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3097
3098 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3099
3100 // Implement isa/cast/dyncast/etc.
3101 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3102 static bool classofKind(Kind K) { return K == Typedef; }
3103};
3104
3105/// Represents the declaration of a typedef-name via a C++11
3106/// alias-declaration.
3107class TypeAliasDecl : public TypedefNameDecl {
3108 /// The template for which this is the pattern, if any.
3109 TypeAliasTemplateDecl *Template;
3110
3111 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3112 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3113 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3114 Template(nullptr) {}
3115
3116public:
3117 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3118 SourceLocation StartLoc, SourceLocation IdLoc,
3119 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3120 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3121
3122 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3123
3124 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3125 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3126
3127 // Implement isa/cast/dyncast/etc.
3128 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3129 static bool classofKind(Kind K) { return K == TypeAlias; }
3130};
3131
3132/// Represents the declaration of a struct/union/class/enum.
3133class TagDecl : public TypeDecl,
3134 public DeclContext,
3135 public Redeclarable<TagDecl> {
3136 // This class stores some data in DeclContext::TagDeclBits
3137 // to save some space. Use the provided accessors to access it.
3138public:
3139 // This is really ugly.
3140 using TagKind = TagTypeKind;
3141
3142private:
3143 SourceRange BraceRange;
3144
3145 // A struct representing syntactic qualifier info,
3146 // to be used for the (uncommon) case of out-of-line declarations.
3147 using ExtInfo = QualifierInfo;
3148
3149 /// If the (out-of-line) tag declaration name
3150 /// is qualified, it points to the qualifier info (nns and range);
3151 /// otherwise, if the tag declaration is anonymous and it is part of
3152 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3153 /// otherwise, if the tag declaration is anonymous and it is used as a
3154 /// declaration specifier for variables, it points to the first VarDecl (used
3155 /// for mangling);
3156 /// otherwise, it is a null (TypedefNameDecl) pointer.
3157 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3158
3159 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3160 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3161 const ExtInfo *getExtInfo() const {
3162 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3163 }
3164
3165protected:
3166 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3167 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3168 SourceLocation StartL);
3169
3170 using redeclarable_base = Redeclarable<TagDecl>;
3171
3172 TagDecl *getNextRedeclarationImpl() override {
3173 return getNextRedeclaration();
3174 }
3175
3176 TagDecl *getPreviousDeclImpl() override {
3177 return getPreviousDecl();
3178 }
3179
3180 TagDecl *getMostRecentDeclImpl() override {
3181 return getMostRecentDecl();
3182 }
3183
3184 /// Completes the definition of this tag declaration.
3185 ///
3186 /// This is a helper function for derived classes.
3187 void completeDefinition();
3188
3189 /// True if this decl is currently being defined.
3190 void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3191
3192 /// Indicates whether it is possible for declarations of this kind
3193 /// to have an out-of-date definition.
3194 ///
3195 /// This option is only enabled when modules are enabled.
3196 void setMayHaveOutOfDateDef(bool V = true) {
3197 TagDeclBits.MayHaveOutOfDateDef = V;
3198 }
3199
3200public:
3201 friend class ASTDeclReader;
3202 friend class ASTDeclWriter;
3203
3204 using redecl_range = redeclarable_base::redecl_range;
3205 using redecl_iterator = redeclarable_base::redecl_iterator;
3206
3207 using redeclarable_base::redecls_begin;
3208 using redeclarable_base::redecls_end;
3209 using redeclarable_base::redecls;
3210 using redeclarable_base::getPreviousDecl;
3211 using redeclarable_base::getMostRecentDecl;
3212 using redeclarable_base::isFirstDecl;
3213
3214 SourceRange getBraceRange() const { return BraceRange; }
3215 void setBraceRange(SourceRange R) { BraceRange = R; }
3216
3217 /// Return SourceLocation representing start of source
3218 /// range ignoring outer template declarations.
3219 SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3220
3221 /// Return SourceLocation representing start of source
3222 /// range taking into account any outer template declarations.
3223 SourceLocation getOuterLocStart() const;
3224 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3225
3226 TagDecl *getCanonicalDecl() override;
3227 const TagDecl *getCanonicalDecl() const {
3228 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3229 }
3230
3231 /// Return true if this declaration is a completion definition of the type.
3232 /// Provided for consistency.
3233 bool isThisDeclarationADefinition() const {
3234 return isCompleteDefinition();
3235 }
3236
3237 /// Return true if this decl has its body fully specified.
3238 bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3239
3240 /// True if this decl has its body fully specified.
3241 void setCompleteDefinition(bool V = true) {
3242 TagDeclBits.IsCompleteDefinition = V;
3243 }
3244
3245 /// Return true if this complete decl is
3246 /// required to be complete for some existing use.
3247 bool isCompleteDefinitionRequired() const {
3248 return TagDeclBits.IsCompleteDefinitionRequired;
3249 }
3250
3251 /// True if this complete decl is
3252 /// required to be complete for some existing use.
3253 void setCompleteDefinitionRequired(bool V = true) {
3254 TagDeclBits.IsCompleteDefinitionRequired = V;
3255 }
3256
3257 /// Return true if this decl is currently being defined.
3258 bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3259
3260 /// True if this tag declaration is "embedded" (i.e., defined or declared
3261 /// for the very first time) in the syntax of a declarator.
3262 bool isEmbeddedInDeclarator() const {
3263 return TagDeclBits.IsEmbeddedInDeclarator;
3264 }
3265
3266 /// True if this tag declaration is "embedded" (i.e., defined or declared
3267 /// for the very first time) in the syntax of a declarator.
3268 void setEmbeddedInDeclarator(bool isInDeclarator) {
3269 TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3270 }
3271
3272 /// True if this tag is free standing, e.g. "struct foo;".
3273 bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3274
3275 /// True if this tag is free standing, e.g. "struct foo;".
3276 void setFreeStanding(bool isFreeStanding = true) {
3277 TagDeclBits.IsFreeStanding = isFreeStanding;
3278 }
3279
3280 /// Indicates whether it is possible for declarations of this kind
3281 /// to have an out-of-date definition.
3282 ///
3283 /// This option is only enabled when modules are enabled.
3284 bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3285
3286 /// Whether this declaration declares a type that is
3287 /// dependent, i.e., a type that somehow depends on template
3288 /// parameters.
3289 bool isDependentType() const { return isDependentContext(); }
3290
3291 /// Starts the definition of this tag declaration.
3292 ///
3293 /// This method should be invoked at the beginning of the definition
3294 /// of this tag declaration. It will set the tag type into a state
3295 /// where it is in the process of being defined.
3296 void startDefinition();
3297
3298 /// Returns the TagDecl that actually defines this
3299 /// struct/union/class/enum. When determining whether or not a
3300 /// struct/union/class/enum has a definition, one should use this
3301 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3302 /// whether or not a specific TagDecl is defining declaration, not
3303 /// whether or not the struct/union/class/enum type is defined.
3304 /// This method returns NULL if there is no TagDecl that defines
3305 /// the struct/union/class/enum.
3306 TagDecl *getDefinition() const;
3307
3308 StringRef getKindName() const {
3309 return TypeWithKeyword::getTagTypeKindName(getTagKind());
3310 }
3311
3312 TagKind getTagKind() const {
3313 return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3314 }
3315
3316 void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
3317
3318 bool isStruct() const { return getTagKind() == TTK_Struct; }
3319 bool isInterface() const { return getTagKind() == TTK_Interface; }
3320 bool isClass() const { return getTagKind() == TTK_Class; }
3321 bool isUnion() const { return getTagKind() == TTK_Union; }
3322 bool isEnum() const { return getTagKind() == TTK_Enum; }
3323
3324 /// Is this tag type named, either directly or via being defined in
3325 /// a typedef of this type?
3326 ///
3327 /// C++11 [basic.link]p8:
3328 /// A type is said to have linkage if and only if:
3329 /// - it is a class or enumeration type that is named (or has a
3330 /// name for linkage purposes) and the name has linkage; ...
3331 /// C++11 [dcl.typedef]p9:
3332 /// If the typedef declaration defines an unnamed class (or enum),
3333 /// the first typedef-name declared by the declaration to be that
3334 /// class type (or enum type) is used to denote the class type (or
3335 /// enum type) for linkage purposes only.
3336 ///
3337 /// C does not have an analogous rule, but the same concept is
3338 /// nonetheless useful in some places.
3339 bool hasNameForLinkage() const {
3340 return (getDeclName() || getTypedefNameForAnonDecl());
3341 }
3342
3343 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3344 return hasExtInfo() ? nullptr
3345 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3346 }
3347
3348 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3349
3350 /// Retrieve the nested-name-specifier that qualifies the name of this
3351 /// declaration, if it was present in the source.
3352 NestedNameSpecifier *getQualifier() const {
3353 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3354 : nullptr;
3355 }
3356
3357 /// Retrieve the nested-name-specifier (with source-location
3358 /// information) that qualifies the name of this declaration, if it was
3359 /// present in the source.
3360 NestedNameSpecifierLoc getQualifierLoc() const {
3361 return hasExtInfo() ? getExtInfo()->QualifierLoc
3362 : NestedNameSpecifierLoc();
3363 }
3364
3365 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3366
3367 unsigned getNumTemplateParameterLists() const {
3368 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3369 }
3370
3371 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3372 assert(i < getNumTemplateParameterLists())((i < getNumTemplateParameterLists()) ? static_cast<void
> (0) : __assert_fail ("i < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 3372, __PRETTY_FUNCTION__))
;
3373 return getExtInfo()->TemplParamLists[i];
3374 }
3375
3376 void setTemplateParameterListsInfo(ASTContext &Context,
3377 ArrayRef<TemplateParameterList *> TPLists);
3378
3379 // Implement isa/cast/dyncast/etc.
3380 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3381 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3382
3383 static DeclContext *castToDeclContext(const TagDecl *D) {
3384 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3385 }
3386
3387 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3388 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3389 }
3390};
3391
3392/// Represents an enum. In C++11, enums can be forward-declared
3393/// with a fixed underlying type, and in C we allow them to be forward-declared
3394/// with no underlying type as an extension.
3395class EnumDecl : public TagDecl {
3396 // This class stores some data in DeclContext::EnumDeclBits
3397 // to save some space. Use the provided accessors to access it.
3398
3399 /// This represent the integer type that the enum corresponds
3400 /// to for code generation purposes. Note that the enumerator constants may
3401 /// have a different type than this does.
3402 ///
3403 /// If the underlying integer type was explicitly stated in the source
3404 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3405 /// was automatically deduced somehow, and this is a Type*.
3406 ///
3407 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3408 /// some cases it won't.
3409 ///
3410 /// The underlying type of an enumeration never has any qualifiers, so
3411 /// we can get away with just storing a raw Type*, and thus save an
3412 /// extra pointer when TypeSourceInfo is needed.
3413 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3414
3415 /// The integer type that values of this type should
3416 /// promote to. In C, enumerators are generally of an integer type
3417 /// directly, but gcc-style large enumerators (and all enumerators
3418 /// in C++) are of the enum type instead.
3419 QualType PromotionType;
3420
3421 /// If this enumeration is an instantiation of a member enumeration
3422 /// of a class template specialization, this is the member specialization
3423 /// information.
3424 MemberSpecializationInfo *SpecializationInfo = nullptr;
3425
3426 /// Store the ODRHash after first calculation.
3427 /// The corresponding flag HasODRHash is in EnumDeclBits
3428 /// and can be accessed with the provided accessors.
3429 unsigned ODRHash;
3430
3431 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3432 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3433 bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3434
3435 void anchor() override;
3436
3437 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3438 TemplateSpecializationKind TSK);
3439
3440 /// Sets the width in bits required to store all the
3441 /// non-negative enumerators of this enum.
3442 void setNumPositiveBits(unsigned Num) {
3443 EnumDeclBits.NumPositiveBits = Num;
3444 assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")((EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount"
) ? static_cast<void> (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 3444, __PRETTY_FUNCTION__))
;
3445 }
3446
3447 /// Returns the width in bits required to store all the
3448 /// negative enumerators of this enum. (see getNumNegativeBits)
3449 void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3450
3451 /// True if this tag declaration is a scoped enumeration. Only
3452 /// possible in C++11 mode.
3453 void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3454
3455 /// If this tag declaration is a scoped enum,
3456 /// then this is true if the scoped enum was declared using the class
3457 /// tag, false if it was declared with the struct tag. No meaning is
3458 /// associated if this tag declaration is not a scoped enum.
3459 void setScopedUsingClassTag(bool ScopedUCT = true) {
3460 EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3461 }
3462
3463 /// True if this is an Objective-C, C++11, or
3464 /// Microsoft-style enumeration with a fixed underlying type.
3465 void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3466
3467 /// True if a valid hash is stored in ODRHash.
3468 bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3469 void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3470
3471public:
3472 friend class ASTDeclReader;
3473
3474 EnumDecl *getCanonicalDecl() override {
3475 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3476 }
3477 const EnumDecl *getCanonicalDecl() const {
3478 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3479 }
3480
3481 EnumDecl *getPreviousDecl() {
3482 return cast_or_null<EnumDecl>(
3483 static_cast<TagDecl *>(this)->getPreviousDecl());
3484 }
3485 const EnumDecl *getPreviousDecl() const {
3486 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3487 }
3488
3489 EnumDecl *getMostRecentDecl() {
3490 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3491 }
3492 const EnumDecl *getMostRecentDecl() const {
3493 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3494 }
3495
3496 EnumDecl *getDefinition() const {
3497 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3498 }
3499
3500 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3501 SourceLocation StartLoc, SourceLocation IdLoc,
3502 IdentifierInfo *Id, EnumDecl *PrevDecl,
3503 bool IsScoped, bool IsScopedUsingClassTag,
3504 bool IsFixed);
3505 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3506
3507 /// When created, the EnumDecl corresponds to a
3508 /// forward-declared enum. This method is used to mark the
3509 /// declaration as being defined; its enumerators have already been
3510 /// added (via DeclContext::addDecl). NewType is the new underlying
3511 /// type of the enumeration type.
3512 void completeDefinition(QualType NewType,
3513 QualType PromotionType,
3514 unsigned NumPositiveBits,
3515 unsigned NumNegativeBits);
3516
3517 // Iterates through the enumerators of this enumeration.
3518 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3519 using enumerator_range =
3520 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3521
3522 enumerator_range enumerators() const {
3523 return enumerator_range(enumerator_begin(), enumerator_end());
3524 }
3525
3526 enumerator_iterator enumerator_begin() const {
3527 const EnumDecl *E = getDefinition();
3528 if (!E)
3529 E = this;
3530 return enumerator_iterator(E->decls_begin());
3531 }
3532
3533 enumerator_iterator enumerator_end() const {
3534 const EnumDecl *E = getDefinition();
3535 if (!E)
3536 E = this;
3537 return enumerator_iterator(E->decls_end());
3538 }
3539
3540 /// Return the integer type that enumerators should promote to.
3541 QualType getPromotionType() const { return PromotionType; }
3542
3543 /// Set the promotion type.
3544 void setPromotionType(QualType T) { PromotionType = T; }
3545
3546 /// Return the integer type this enum decl corresponds to.
3547 /// This returns a null QualType for an enum forward definition with no fixed
3548 /// underlying type.
3549 QualType getIntegerType() const {
3550 if (!IntegerType)
3551 return QualType();
3552 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3553 return QualType(T, 0);
3554 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3555 }
3556
3557 /// Set the underlying integer type.
3558 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3559
3560 /// Set the underlying integer type source info.
3561 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3562
3563 /// Return the type source info for the underlying integer type,
3564 /// if no type source info exists, return 0.
3565 TypeSourceInfo *getIntegerTypeSourceInfo() const {
3566 return IntegerType.dyn_cast<TypeSourceInfo*>();
3567 }
3568
3569 /// Retrieve the source range that covers the underlying type if
3570 /// specified.
3571 SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__));
3572
3573 /// Returns the width in bits required to store all the
3574 /// non-negative enumerators of this enum.
3575 unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
3576
3577 /// Returns the width in bits required to store all the
3578 /// negative enumerators of this enum. These widths include
3579 /// the rightmost leading 1; that is:
3580 ///
3581 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
3582 /// ------------------------ ------- -----------------
3583 /// -1 1111111 1
3584 /// -10 1110110 5
3585 /// -101 1001011 8
3586 unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
3587
3588 /// Returns true if this is a C++11 scoped enumeration.
3589 bool isScoped() const { return EnumDeclBits.IsScoped; }
3590
3591 /// Returns true if this is a C++11 scoped enumeration.
3592 bool isScopedUsingClassTag() const {
3593 return EnumDeclBits.IsScopedUsingClassTag;
3594 }
3595
3596 /// Returns true if this is an Objective-C, C++11, or
3597 /// Microsoft-style enumeration with a fixed underlying type.
3598 bool isFixed() const { return EnumDeclBits.IsFixed; }
3599
3600 unsigned getODRHash();
3601
3602 /// Returns true if this can be considered a complete type.
3603 bool isComplete() const {
3604 // IntegerType is set for fixed type enums and non-fixed but implicitly
3605 // int-sized Microsoft enums.
3606 return isCompleteDefinition() || IntegerType;
3607 }
3608
3609 /// Returns true if this enum is either annotated with
3610 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3611 bool isClosed() const;
3612
3613 /// Returns true if this enum is annotated with flag_enum and isn't annotated
3614 /// with enum_extensibility(open).
3615 bool isClosedFlag() const;
3616
3617 /// Returns true if this enum is annotated with neither flag_enum nor
3618 /// enum_extensibility(open).
3619 bool isClosedNonFlag() const;
3620
3621 /// Retrieve the enum definition from which this enumeration could
3622 /// be instantiated, if it is an instantiation (rather than a non-template).
3623 EnumDecl *getTemplateInstantiationPattern() const;
3624
3625 /// Returns the enumeration (declared within the template)
3626 /// from which this enumeration type was instantiated, or NULL if
3627 /// this enumeration was not instantiated from any template.
3628 EnumDecl *getInstantiatedFromMemberEnum() const;
3629
3630 /// If this enumeration is a member of a specialization of a
3631 /// templated class, determine what kind of template specialization
3632 /// or instantiation this is.
3633 TemplateSpecializationKind getTemplateSpecializationKind() const;
3634
3635 /// For an enumeration member that was instantiated from a member
3636 /// enumeration of a templated class, set the template specialiation kind.
3637 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3638 SourceLocation PointOfInstantiation = SourceLocation());
3639
3640 /// If this enumeration is an instantiation of a member enumeration of
3641 /// a class template specialization, retrieves the member specialization
3642 /// information.
3643 MemberSpecializationInfo *getMemberSpecializationInfo() const {
3644 return SpecializationInfo;
3645 }
3646
3647 /// Specify that this enumeration is an instantiation of the
3648 /// member enumeration ED.
3649 void setInstantiationOfMemberEnum(EnumDecl *ED,
3650 TemplateSpecializationKind TSK) {
3651 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3652 }
3653
3654 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3655 static bool classofKind(Kind K) { return K == Enum; }
3656};
3657
3658/// Represents a struct/union/class. For example:
3659/// struct X; // Forward declaration, no "body".
3660/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
3661/// This decl will be marked invalid if *any* members are invalid.
3662class RecordDecl : public TagDecl {
3663 // This class stores some data in DeclContext::RecordDeclBits
3664 // to save some space. Use the provided accessors to access it.
3665public:
3666 friend class DeclContext;
3667 /// Enum that represents the different ways arguments are passed to and
3668 /// returned from function calls. This takes into account the target-specific
3669 /// and version-specific rules along with the rules determined by the
3670 /// language.
3671 enum ArgPassingKind : unsigned {
3672 /// The argument of this type can be passed directly in registers.
3673 APK_CanPassInRegs,
3674
3675 /// The argument of this type cannot be passed directly in registers.
3676 /// Records containing this type as a subobject are not forced to be passed
3677 /// indirectly. This value is used only in C++. This value is required by
3678 /// C++ because, in uncommon situations, it is possible for a class to have
3679 /// only trivial copy/move constructors even when one of its subobjects has
3680 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
3681 /// constructor in the derived class is deleted).
3682 APK_CannotPassInRegs,
3683
3684 /// The argument of this type cannot be passed directly in registers.
3685 /// Records containing this type as a subobject are forced to be passed
3686 /// indirectly.
3687 APK_CanNeverPassInRegs
3688 };
3689
3690protected:
3691 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3692 SourceLocation StartLoc, SourceLocation IdLoc,
3693 IdentifierInfo *Id, RecordDecl *PrevDecl);
3694
3695public:
3696 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3697 SourceLocation StartLoc, SourceLocation IdLoc,
3698 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3699 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3700
3701 RecordDecl *getPreviousDecl() {
3702 return cast_or_null<RecordDecl>(
3703 static_cast<TagDecl *>(this)->getPreviousDecl());
3704 }
3705 const RecordDecl *getPreviousDecl() const {
3706 return const_cast<RecordDecl*>(this)->getPreviousDecl();
3707 }
3708
3709 RecordDecl *getMostRecentDecl() {
3710 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3711 }
3712 const RecordDecl *getMostRecentDecl() const {
3713 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3714 }
3715
3716 bool hasFlexibleArrayMember() const {
3717 return RecordDeclBits.HasFlexibleArrayMember;
3718 }
3719
3720 void setHasFlexibleArrayMember(bool V) {
3721 RecordDeclBits.HasFlexibleArrayMember = V;
3722 }
3723
3724 /// Whether this is an anonymous struct or union. To be an anonymous
3725 /// struct or union, it must have been declared without a name and
3726 /// there must be no objects of this type declared, e.g.,
3727 /// @code
3728 /// union { int i; float f; };
3729 /// @endcode
3730 /// is an anonymous union but neither of the following are:
3731 /// @code
3732 /// union X { int i; float f; };
3733 /// union { int i; float f; } obj;
3734 /// @endcode
3735 bool isAnonymousStructOrUnion() const {
3736 return RecordDeclBits.AnonymousStructOrUnion;
3737 }
3738
3739 void setAnonymousStructOrUnion(bool Anon) {
3740 RecordDeclBits.AnonymousStructOrUnion = Anon;
3741 }
3742
3743 bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
3744 void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
3745
3746 bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
3747
3748 void setHasVolatileMember(bool val) {
3749 RecordDeclBits.HasVolatileMember = val;
3750 }
3751
3752 bool hasLoadedFieldsFromExternalStorage() const {
3753 return RecordDeclBits.LoadedFieldsFromExternalStorage;
3754 }
3755
3756 void setHasLoadedFieldsFromExternalStorage(bool val) const {
3757 RecordDeclBits.LoadedFieldsFromExternalStorage = val;
3758 }
3759
3760 /// Functions to query basic properties of non-trivial C structs.
3761 bool isNonTrivialToPrimitiveDefaultInitialize() const {
3762 return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
3763 }
3764
3765 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
3766 RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
3767 }
3768
3769 bool isNonTrivialToPrimitiveCopy() const {
3770 return RecordDeclBits.NonTrivialToPrimitiveCopy;
3771 }
3772
3773 void setNonTrivialToPrimitiveCopy(bool V) {
3774 RecordDeclBits.NonTrivialToPrimitiveCopy = V;
3775 }
3776
3777 bool isNonTrivialToPrimitiveDestroy() const {
3778 return RecordDeclBits.NonTrivialToPrimitiveDestroy;
3779 }
3780
3781 void setNonTrivialToPrimitiveDestroy(bool V) {
3782 RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
3783 }
3784
3785 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
3786 return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
3787 }
3788
3789 void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
3790 RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
3791 }
3792
3793 bool hasNonTrivialToPrimitiveDestructCUnion() const {
3794 return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
3795 }
3796
3797 void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
3798 RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
3799 }
3800
3801 bool hasNonTrivialToPrimitiveCopyCUnion() const {
3802 return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
3803 }
3804
3805 void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
3806 RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
3807 }
3808
3809 /// Determine whether this class can be passed in registers. In C++ mode,
3810 /// it must have at least one trivial, non-deleted copy or move constructor.
3811 /// FIXME: This should be set as part of completeDefinition.
3812 bool canPassInRegisters() const {
3813 return getArgPassingRestrictions() == APK_CanPassInRegs;
3814 }
3815
3816 ArgPassingKind getArgPassingRestrictions() const {
3817 return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
3818 }
3819
3820 void setArgPassingRestrictions(ArgPassingKind Kind) {
3821 RecordDeclBits.ArgPassingRestrictions = Kind;
3822 }
3823
3824 bool isParamDestroyedInCallee() const {
3825 return RecordDeclBits.ParamDestroyedInCallee;
3826 }
3827
3828 void setParamDestroyedInCallee(bool V) {
3829 RecordDeclBits.ParamDestroyedInCallee = V;
3830 }
3831
3832 /// Determines whether this declaration represents the
3833 /// injected class name.
3834 ///
3835 /// The injected class name in C++ is the name of the class that
3836 /// appears inside the class itself. For example:
3837 ///
3838 /// \code
3839 /// struct C {
3840 /// // C is implicitly declared here as a synonym for the class name.
3841 /// };
3842 ///
3843 /// C::C c; // same as "C c;"
3844 /// \endcode
3845 bool isInjectedClassName() const;
3846
3847 /// Determine whether this record is a class describing a lambda
3848 /// function object.
3849 bool isLambda() const;
3850
3851 /// Determine whether this record is a record for captured variables in
3852 /// CapturedStmt construct.
3853 bool isCapturedRecord() const;
3854
3855 /// Mark the record as a record for captured variables in CapturedStmt
3856 /// construct.
3857 void setCapturedRecord();
3858
3859 /// Returns the RecordDecl that actually defines
3860 /// this struct/union/class. When determining whether or not a
3861 /// struct/union/class is completely defined, one should use this
3862 /// method as opposed to 'isCompleteDefinition'.
3863 /// 'isCompleteDefinition' indicates whether or not a specific
3864 /// RecordDecl is a completed definition, not whether or not the
3865 /// record type is defined. This method returns NULL if there is
3866 /// no RecordDecl that defines the struct/union/tag.
3867 RecordDecl *getDefinition() const {
3868 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3869 }
3870
3871 // Iterator access to field members. The field iterator only visits
3872 // the non-static data members of this class, ignoring any static
3873 // data members, functions, constructors, destructors, etc.
3874 using field_iterator = specific_decl_iterator<FieldDecl>;
3875 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
3876
3877 field_range fields() const { return field_range(field_begin(), field_end()); }
3878 field_iterator field_begin() const;
3879
3880 field_iterator field_end() const {
3881 return field_iterator(decl_iterator());
3882 }
3883
3884 // Whether there are any fields (non-static data members) in this record.
3885 bool field_empty() const {
3886 return field_begin() == field_end();
3887 }
3888
3889 /// Note that the definition of this type is now complete.
3890 virtual void completeDefinition();
3891
3892 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3893 static bool classofKind(Kind K) {
3894 return K >= firstRecord && K <= lastRecord;
3895 }
3896
3897 /// Get whether or not this is an ms_struct which can
3898 /// be turned on with an attribute, pragma, or -mms-bitfields
3899 /// commandline option.
3900 bool isMsStruct(const ASTContext &C) const;
3901
3902 /// Whether we are allowed to insert extra padding between fields.
3903 /// These padding are added to help AddressSanitizer detect
3904 /// intra-object-overflow bugs.
3905 bool mayInsertExtraPadding(bool EmitRemark = false) const;
3906
3907 /// Finds the first data member which has a name.
3908 /// nullptr is returned if no named data member exists.
3909 const FieldDecl *findFirstNamedDataMember() const;
3910
3911private:
3912 /// Deserialize just the fields.
3913 void LoadFieldsFromExternalStorage() const;
3914};
3915
3916class FileScopeAsmDecl : public Decl {
3917 StringLiteral *AsmString;
3918 SourceLocation RParenLoc;
3919
3920 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3921 SourceLocation StartL, SourceLocation EndL)
3922 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3923
3924 virtual void anchor();
3925
3926public:
3927 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3928 StringLiteral *Str, SourceLocation AsmLoc,
3929 SourceLocation RParenLoc);
3930
3931 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3932
3933 SourceLocation getAsmLoc() const { return getLocation(); }
3934 SourceLocation getRParenLoc() const { return RParenLoc; }
3935 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3936 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3937 return SourceRange(getAsmLoc(), getRParenLoc());
3938 }
3939
3940 const StringLiteral *getAsmString() const { return AsmString; }
3941 StringLiteral *getAsmString() { return AsmString; }
3942 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3943
3944 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3945 static bool classofKind(Kind K) { return K == FileScopeAsm; }
3946};
3947
3948/// Represents a block literal declaration, which is like an
3949/// unnamed FunctionDecl. For example:
3950/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
3951class BlockDecl : public Decl, public DeclContext {
3952 // This class stores some data in DeclContext::BlockDeclBits
3953 // to save some space. Use the provided accessors to access it.
3954public:
3955 /// A class which contains all the information about a particular
3956 /// captured value.
3957 class Capture {
3958 enum {
3959 flag_isByRef = 0x1,
3960 flag_isNested = 0x2
3961 };
3962
3963 /// The variable being captured.
3964 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3965
3966 /// The copy expression, expressed in terms of a DeclRef (or
3967 /// BlockDeclRef) to the captured variable. Only required if the
3968 /// variable has a C++ class type.
3969 Expr *CopyExpr;
3970
3971 public:
3972 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3973 : VariableAndFlags(variable,
3974 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3975 CopyExpr(copy) {}
3976
3977 /// The variable being captured.
3978 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3979
3980 /// Whether this is a "by ref" capture, i.e. a capture of a __block
3981 /// variable.
3982 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3983
3984 bool isEscapingByref() const {
3985 return getVariable()->isEscapingByref();
3986 }
3987
3988 bool isNonEscapingByref() const {
3989 return getVariable()->isNonEscapingByref();
3990 }
3991
3992 /// Whether this is a nested capture, i.e. the variable captured
3993 /// is not from outside the immediately enclosing function/block.
3994 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3995
3996 bool hasCopyExpr() const { return CopyExpr != nullptr; }
3997 Expr *getCopyExpr() const { return CopyExpr; }
3998 void setCopyExpr(Expr *e) { CopyExpr = e; }
3999 };
4000
4001private:
4002 /// A new[]'d array of pointers to ParmVarDecls for the formal
4003 /// parameters of this function. This is null if a prototype or if there are
4004 /// no formals.
4005 ParmVarDecl **ParamInfo = nullptr;
4006 unsigned NumParams = 0;
4007
4008 Stmt *Body = nullptr;
4009 TypeSourceInfo *SignatureAsWritten = nullptr;
4010
4011 const Capture *Captures = nullptr;
4012 unsigned NumCaptures = 0;
4013
4014 unsigned ManglingNumber = 0;
4015 Decl *ManglingContextDecl = nullptr;
4016
4017protected:
4018 BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
4019
4020public:
4021 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
4022 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4023
4024 SourceLocation getCaretLocation() const { return getLocation(); }
4025
4026 bool isVariadic() const { return BlockDeclBits.IsVariadic; }
4027 void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
4028
4029 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
4030 Stmt *getBody() const override { return (Stmt*) Body; }
4031 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
4032
4033 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
4034 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
4035
4036 // ArrayRef access to formal parameters.
4037 ArrayRef<ParmVarDecl *> parameters() const {
4038 return {ParamInfo, getNumParams()};
4039 }
4040 MutableArrayRef<ParmVarDecl *> parameters() {
4041 return {ParamInfo, getNumParams()};
4042 }
4043
4044 // Iterator access to formal parameters.
4045 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
4046 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
4047
4048 bool param_empty() const { return parameters().empty(); }
4049 param_iterator param_begin() { return parameters().begin(); }
4050 param_iterator param_end() { return parameters().end(); }
4051 param_const_iterator param_begin() const { return parameters().begin(); }
4052 param_const_iterator param_end() const { return parameters().end(); }
4053 size_t param_size() const { return parameters().size(); }
4054
4055 unsigned getNumParams() const { return NumParams; }
4056
4057 const ParmVarDecl *getParamDecl(unsigned i) const {
4058 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4058, __PRETTY_FUNCTION__))
;
4059 return ParamInfo[i];
4060 }
4061 ParmVarDecl *getParamDecl(unsigned i) {
4062 assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast
<void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4062, __PRETTY_FUNCTION__))
;
4063 return ParamInfo[i];
4064 }
4065
4066 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
4067
4068 /// True if this block (or its nested blocks) captures
4069 /// anything of local storage from its enclosing scopes.
4070 bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
4071
4072 /// Returns the number of captured variables.
4073 /// Does not include an entry for 'this'.
4074 unsigned getNumCaptures() const { return NumCaptures; }
4075
4076 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
4077
4078 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
4079
4080 capture_const_iterator capture_begin() const { return captures().begin(); }
4081 capture_const_iterator capture_end() const { return captures().end(); }
4082
4083 bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
4084 void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
4085
4086 bool blockMissingReturnType() const {
4087 return BlockDeclBits.BlockMissingReturnType;
4088 }
4089
4090 void setBlockMissingReturnType(bool val = true) {
4091 BlockDeclBits.BlockMissingReturnType = val;
4092 }
4093
4094 bool isConversionFromLambda() const {
4095 return BlockDeclBits.IsConversionFromLambda;
4096 }
4097
4098 void setIsConversionFromLambda(bool val = true) {
4099 BlockDeclBits.IsConversionFromLambda = val;
4100 }
4101
4102 bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4103 void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4104
4105 bool canAvoidCopyToHeap() const {
4106 return BlockDeclBits.CanAvoidCopyToHeap;
4107 }
4108 void setCanAvoidCopyToHeap(bool B = true) {
4109 BlockDeclBits.CanAvoidCopyToHeap = B;
4110 }
4111
4112 bool capturesVariable(const VarDecl *var) const;
4113
4114 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4115 bool CapturesCXXThis);
4116
4117 unsigned getBlockManglingNumber() const { return ManglingNumber; }
4118
4119 Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; }
4120
4121 void setBlockMangling(unsigned Number, Decl *Ctx) {
4122 ManglingNumber = Number;
4123 ManglingContextDecl = Ctx;
4124 }
4125
4126 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4127
4128 // Implement isa/cast/dyncast/etc.
4129 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4130 static bool classofKind(Kind K) { return K == Block; }
4131 static DeclContext *castToDeclContext(const BlockDecl *D) {
4132 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4133 }
4134 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4135 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4136 }
4137};
4138
4139/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4140class CapturedDecl final
4141 : public Decl,
4142 public DeclContext,
4143 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4144protected:
4145 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4146 return NumParams;
4147 }
4148
4149private:
4150 /// The number of parameters to the outlined function.
4151 unsigned NumParams;
4152
4153 /// The position of context parameter in list of parameters.
4154 unsigned ContextParam;
4155
4156 /// The body of the outlined function.
4157 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4158
4159 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4160
4161 ImplicitParamDecl *const *getParams() const {
4162 return getTrailingObjects<ImplicitParamDecl *>();
4163 }
4164
4165 ImplicitParamDecl **getParams() {
4166 return getTrailingObjects<ImplicitParamDecl *>();
4167 }
4168
4169public:
4170 friend class ASTDeclReader;
4171 friend class ASTDeclWriter;
4172 friend TrailingObjects;
4173
4174 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4175 unsigned NumParams);
4176 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4177 unsigned NumParams);
4178
4179 Stmt *getBody() const override;
4180 void setBody(Stmt *B);
4181
4182 bool isNothrow() const;
4183 void setNothrow(bool Nothrow = true);
4184
4185 unsigned getNumParams() const { return NumParams; }
4186
4187 ImplicitParamDecl *getParam(unsigned i) const {
4188 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4188, __PRETTY_FUNCTION__))
;
4189 return getParams()[i];
4190 }
4191 void setParam(unsigned i, ImplicitParamDecl *P) {
4192 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4192, __PRETTY_FUNCTION__))
;
4193 getParams()[i] = P;
4194 }
4195
4196 // ArrayRef interface to parameters.
4197 ArrayRef<ImplicitParamDecl *> parameters() const {
4198 return {getParams(), getNumParams()};
4199 }
4200 MutableArrayRef<ImplicitParamDecl *> parameters() {
4201 return {getParams(), getNumParams()};
4202 }
4203
4204 /// Retrieve the parameter containing captured variables.
4205 ImplicitParamDecl *getContextParam() const {
4206 assert(ContextParam < NumParams)((ContextParam < NumParams) ? static_cast<void> (0) :
__assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4206, __PRETTY_FUNCTION__))
;
4207 return getParam(ContextParam);
4208 }
4209 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4210 assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail
("i < NumParams", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4210, __PRETTY_FUNCTION__))
;
4211 ContextParam = i;
4212 setParam(i, P);
4213 }
4214 unsigned getContextParamPosition() const { return ContextParam; }
4215
4216 using param_iterator = ImplicitParamDecl *const *;
4217 using param_range = llvm::iterator_range<param_iterator>;
4218
4219 /// Retrieve an iterator pointing to the first parameter decl.
4220 param_iterator param_begin() const { return getParams(); }
4221 /// Retrieve an iterator one past the last parameter decl.
4222 param_iterator param_end() const { return getParams() + NumParams; }
4223
4224 // Implement isa/cast/dyncast/etc.
4225 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4226 static bool classofKind(Kind K) { return K == Captured; }
4227 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4228 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4229 }
4230 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4231 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4232 }
4233};
4234
4235/// Describes a module import declaration, which makes the contents
4236/// of the named module visible in the current translation unit.
4237///
4238/// An import declaration imports the named module (or submodule). For example:
4239/// \code
4240/// @import std.vector;
4241/// \endcode
4242///
4243/// Import declarations can also be implicitly generated from
4244/// \#include/\#import directives.
4245class ImportDecl final : public Decl,
4246 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4247 friend class ASTContext;
4248 friend class ASTDeclReader;
4249 friend class ASTReader;
4250 friend TrailingObjects;
4251
4252 /// The imported module, along with a bit that indicates whether
4253 /// we have source-location information for each identifier in the module
4254 /// name.
4255 ///
4256 /// When the bit is false, we only have a single source location for the
4257 /// end of the import declaration.
4258 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
4259
4260 /// The next import in the list of imports local to the translation
4261 /// unit being parsed (not loaded from an AST file).
4262 ImportDecl *NextLocalImport = nullptr;
4263
4264 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4265 ArrayRef<SourceLocation> IdentifierLocs);
4266
4267 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4268 SourceLocation EndLoc);
4269
4270 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4271
4272public:
4273 /// Create a new module import declaration.
4274 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4275 SourceLocation StartLoc, Module *Imported,
4276 ArrayRef<SourceLocation> IdentifierLocs);
4277
4278 /// Create a new module import declaration for an implicitly-generated
4279 /// import.
4280 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4281 SourceLocation StartLoc, Module *Imported,
4282 SourceLocation EndLoc);
4283
4284 /// Create a new, deserialized module import declaration.
4285 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4286 unsigned NumLocations);
4287
4288 /// Retrieve the module that was imported by the import declaration.
4289 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
4290
4291 /// Retrieves the locations of each of the identifiers that make up
4292 /// the complete module name in the import declaration.
4293 ///
4294 /// This will return an empty array if the locations of the individual
4295 /// identifiers aren't available.
4296 ArrayRef<SourceLocation> getIdentifierLocs() const;
4297
4298 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
4299
4300 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4301 static bool classofKind(Kind K) { return K == Import; }
4302};
4303
4304/// Represents a C++ Modules TS module export declaration.
4305///
4306/// For example:
4307/// \code
4308/// export void foo();
4309/// \endcode
4310class ExportDecl final : public Decl, public DeclContext {
4311 virtual void anchor();
4312
4313private:
4314 friend class ASTDeclReader;
4315
4316 /// The source location for the right brace (if valid).
4317 SourceLocation RBraceLoc;
4318
4319 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4320 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4321 RBraceLoc(SourceLocation()) {}
4322
4323public:
4324 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4325 SourceLocation ExportLoc);
4326 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4327
4328 SourceLocation getExportLoc() const { return getLocation(); }
4329 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4330 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4331
4332 bool hasBraces() const { return RBraceLoc.isValid(); }
4333
4334 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4335 if (hasBraces())
4336 return RBraceLoc;
4337 // No braces: get the end location of the (only) declaration in context
4338 // (if present).
4339 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4340 }
4341
4342 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
4343 return SourceRange(getLocation(), getEndLoc());
4344 }
4345
4346 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4347 static bool classofKind(Kind K) { return K == Export; }
4348 static DeclContext *castToDeclContext(const ExportDecl *D) {
4349 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4350 }
4351 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4352 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4353 }
4354};
4355
4356/// Represents an empty-declaration.
4357class EmptyDecl : public Decl {
4358 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4359
4360 virtual void anchor();
4361
4362public:
4363 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4364 SourceLocation L);
4365 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4366
4367 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4368 static bool classofKind(Kind K) { return K == Empty; }
4369};
4370
4371/// Insertion operator for diagnostics. This allows sending NamedDecl's
4372/// into a diagnostic with <<.
4373inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4374 const NamedDecl* ND) {
4375 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4376 DiagnosticsEngine::ak_nameddecl);
4377 return DB;
4378}
4379inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4380 const NamedDecl* ND) {
4381 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
4382 DiagnosticsEngine::ak_nameddecl);
4383 return PD;
4384}
4385
4386template<typename decl_type>
4387void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4388 // Note: This routine is implemented here because we need both NamedDecl
4389 // and Redeclarable to be defined.
4390 assert(RedeclLink.isFirst() &&((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4391, __PRETTY_FUNCTION__))
4391 "setPreviousDecl on a decl already in a redeclaration chain")((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4391, __PRETTY_FUNCTION__))
;
4392
4393 if (PrevDecl) {
4394 // Point to previous. Make sure that this is actually the most recent
4395 // redeclaration, or we can build invalid chains. If the most recent
4396 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4397 First = PrevDecl->getFirstDecl();
4398 assert(First->RedeclLink.isFirst() && "Expected first")((First->RedeclLink.isFirst() && "Expected first")
? static_cast<void> (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4398, __PRETTY_FUNCTION__))
;
4399 decl_type *MostRecent = First->getNextRedeclaration();
4400 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
4401
4402 // If the declaration was previously visible, a redeclaration of it remains
4403 // visible even if it wouldn't be visible by itself.
4404 static_cast<decl_type*>(this)->IdentifierNamespace |=
4405 MostRecent->getIdentifierNamespace() &
4406 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4407 } else {
4408 // Make this first.
4409 First = static_cast<decl_type*>(this);
4410 }
4411
4412 // First one will point to this one as latest.
4413 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4414
4415 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4416, __PRETTY_FUNCTION__))
4416 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())((!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->
isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include/clang/AST/Decl.h"
, 4416, __PRETTY_FUNCTION__))
;
4417}
4418
4419// Inline function definitions.
4420
4421/// Check if the given decl is complete.
4422///
4423/// We use this function to break a cycle between the inline definitions in
4424/// Type.h and Decl.h.
4425inline bool IsEnumDeclComplete(EnumDecl *ED) {
4426 return ED->isComplete();
4427}
4428
4429/// Check if the given decl is scoped.
4430///
4431/// We use this function to break a cycle between the inline definitions in
4432/// Type.h and Decl.h.
4433inline bool IsEnumDeclScoped(EnumDecl *ED) {
4434 return ED->isScoped();
4435}
4436
4437} // namespace clang
4438
4439#endif // LLVM_CLANG_AST_DECL_H

/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- 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// This file defines the PointerUnion class, which is a discriminated union of
10// pointer types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERUNION_H
15#define LLVM_ADT_POINTERUNION_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include <cassert>
21#include <cstddef>
22#include <cstdint>
23
24namespace llvm {
25
26template <typename T> struct PointerUnionTypeSelectorReturn {
27 using Return = T;
28};
29
30/// Get a type based on whether two types are the same or not.
31///
32/// For:
33///
34/// \code
35/// using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return;
36/// \endcode
37///
38/// Ret will be EQ type if T1 is same as T2 or NE type otherwise.
39template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
40struct PointerUnionTypeSelector {
41 using Return = typename PointerUnionTypeSelectorReturn<RET_NE>::Return;
42};
43
44template <typename T, typename RET_EQ, typename RET_NE>
45struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> {
46 using Return = typename PointerUnionTypeSelectorReturn<RET_EQ>::Return;
47};
48
49template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
50struct PointerUnionTypeSelectorReturn<
51 PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> {
52 using Return =
53 typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return;
54};
55
56namespace pointer_union_detail {
57 /// Determine the number of bits required to store integers with values < n.
58 /// This is ceil(log2(n)).
59 constexpr int bitsRequired(unsigned n) {
60 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
61 }
62
63 template <typename... Ts> constexpr int lowBitsAvailable() {
64 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
65 }
66
67 /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
68 /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
69 /// list.
70 template <typename T, typename ...Us> struct TypeIndex;
71 template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> {
72 static constexpr int Index = 0;
73 };
74 template <typename T, typename U, typename... Us>
75 struct TypeIndex<T, U, Us...> {
76 static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
77 };
78 template <typename T> struct TypeIndex<T> {
79 static constexpr int Index = 0;
80 };
81
82 /// Find the first type in a list of types.
83 template <typename T, typename...> struct GetFirstType {
84 using type = T;
85 };
86
87 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
88 /// for the template arguments.
89 template <typename ...PTs> class PointerUnionUIntTraits {
90 public:
91 static inline void *getAsVoidPointer(void *P) { return P; }
92 static inline void *getFromVoidPointer(void *P) { return P; }
93 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
94 };
95
96 /// Implement assigment in terms of construction.
97 template <typename Derived, typename T> struct AssignableFrom {
98 Derived &operator=(T t) {
99 return static_cast<Derived &>(*this) = Derived(t);
100 }
101 };
102
103 template <typename Derived, typename ValTy, int I, typename ...Types>
104 class PointerUnionMembers;
105
106 template <typename Derived, typename ValTy, int I>
107 class PointerUnionMembers<Derived, ValTy, I> {
108 protected:
109 ValTy Val;
110 PointerUnionMembers() = default;
111 PointerUnionMembers(ValTy Val) : Val(Val) {}
112
113 friend struct PointerLikeTypeTraits<Derived>;
114 };
115
116 template <typename Derived, typename ValTy, int I, typename Type,
117 typename ...Types>
118 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
119 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
120 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
121 public:
122 using Base::Base;
123 PointerUnionMembers() = default;
124 PointerUnionMembers(Type V)
125 : Base(ValTy(const_cast<void *>(
126 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
127 I)) {}
128
129 using Base::operator=;
130 Derived &operator=(Type V) {
131 this->Val = ValTy(
132 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
133 I);
134 return static_cast<Derived &>(*this);
135 };
136 };
137}
138
139/// A discriminated union of two or more pointer types, with the discriminator
140/// in the low bit of the pointer.
141///
142/// This implementation is extremely efficient in space due to leveraging the
143/// low bits of the pointer, while exposing a natural and type-safe API.
144///
145/// Common use patterns would be something like this:
146/// PointerUnion<int*, float*> P;
147/// P = (int*)0;
148/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
149/// X = P.get<int*>(); // ok.
150/// Y = P.get<float*>(); // runtime assertion failure.
151/// Z = P.get<double*>(); // compile time failure.
152/// P = (float*)0;
153/// Y = P.get<float*>(); // ok.
154/// X = P.get<int*>(); // runtime assertion failure.
155template <typename... PTs>
156class PointerUnion
157 : public pointer_union_detail::PointerUnionMembers<
158 PointerUnion<PTs...>,
159 PointerIntPair<
160 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
161 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
162 0, PTs...> {
163 // The first type is special because we want to directly cast a pointer to a
164 // default-initialized union to a pointer to the first type. But we don't
165 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
166 // because it's much more convenient to have a name for the whole pack. So
167 // split off the first type here.
168 using First = typename pointer_union_detail::GetFirstType<PTs...>::type;
169 using Base = typename PointerUnion::PointerUnionMembers;
170
171public:
172 PointerUnion() = default;
173
174 PointerUnion(std::nullptr_t) : PointerUnion() {}
175 using Base::Base;
176
177 /// Test if the pointer held in the union is null, regardless of
178 /// which type it is.
179 bool isNull() const { return !this->Val.getPointer(); }
180
181 explicit operator bool() const { return !isNull(); }
182
183 /// Test if the Union currently holds the type matching T.
184 template <typename T> int is() const {
185 constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index;
186 static_assert(Index < sizeof...(PTs),
187 "PointerUnion::is<T> given type not in the union");
188 return this->Val.getInt() == Index;
189 }
190
191 /// Returns the value of the specified pointer type.
192 ///
193 /// If the specified pointer type is incorrect, assert.
194 template <typename T> T get() const {
195 assert(is<T>() && "Invalid accessor called")((is<T>() && "Invalid accessor called") ? static_cast
<void> (0) : __assert_fail ("is<T>() && \"Invalid accessor called\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 195, __PRETTY_FUNCTION__))
;
16
'?' condition is true
196 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
17
Returning pointer, which participates in a condition later
197 }
198
199 /// Returns the current pointer if it is of the specified pointer type,
200 /// otherwises returns null.
201 template <typename T> T dyn_cast() const {
202 if (is<T>())
203 return get<T>();
204 return T();
205 }
206
207 /// If the union is set to the first pointer type get an address pointing to
208 /// it.
209 First const *getAddrOfPtr1() const {
210 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
211 }
212
213 /// If the union is set to the first pointer type get an address pointing to
214 /// it.
215 First *getAddrOfPtr1() {
216 assert(is<First>() && "Val is not the first pointer")((is<First>() && "Val is not the first pointer"
) ? static_cast<void> (0) : __assert_fail ("is<First>() && \"Val is not the first pointer\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 216, __PRETTY_FUNCTION__))
;
217 assert(((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
218 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
219 this->Val.getPointer() &&((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
220 "Can't get the address because PointerLikeTypeTraits changes the ptr")((PointerLikeTypeTraits<First>::getAsVoidPointer(get<
First>()) == this->Val.getPointer() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? static_cast<void> (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/ADT/PointerUnion.h"
, 220, __PRETTY_FUNCTION__))
;
221 return const_cast<First *>(
222 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
223 }
224
225 /// Assignment from nullptr which just clears the union.
226 const PointerUnion &operator=(std::nullptr_t) {
227 this->Val.initWithPointer(nullptr);
228 return *this;
229 }
230
231 /// Assignment from elements of the union.
232 using Base::operator=;
233
234 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
235 static inline PointerUnion getFromOpaqueValue(void *VP) {
236 PointerUnion V;
237 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
238 return V;
239 }
240};
241
242template <typename ...PTs>
243bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
244 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
245}
246
247template <typename ...PTs>
248bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
249 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
250}
251
252template <typename ...PTs>
253bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
254 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
255}
256
257// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
258// # low bits available = min(PT1bits,PT2bits)-1.
259template <typename ...PTs>
260struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
261 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
262 return P.getOpaqueValue();
263 }
264
265 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
266 return PointerUnion<PTs...>::getFromOpaqueValue(P);
267 }
268
269 // The number of bits available are the min of the pointer types minus the
270 // bits needed for the discriminator.
271 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
272 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
273};
274
275/// A pointer union of three pointer types. See documentation for PointerUnion
276/// for usage.
277template <typename PT1, typename PT2, typename PT3>
278using PointerUnion3 = PointerUnion<PT1, PT2, PT3>;
279
280/// A pointer union of four pointer types. See documentation for PointerUnion
281/// for usage.
282template <typename PT1, typename PT2, typename PT3, typename PT4>
283using PointerUnion4 = PointerUnion<PT1, PT2, PT3, PT4>;
284
285// Teach DenseMap how to use PointerUnions as keys.
286template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
287 using Union = PointerUnion<PTs...>;
288 using FirstInfo =
289 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
290
291 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
292
293 static inline Union getTombstoneKey() {
294 return Union(FirstInfo::getTombstoneKey());
295 }
296
297 static unsigned getHashValue(const Union &UnionVal) {
298 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
299 return DenseMapInfo<intptr_t>::getHashValue(key);
300 }
301
302 static bool isEqual(const Union &LHS, const Union &RHS) {
303 return LHS == RHS;
304 }
305};
306
307} // end namespace llvm
308
309#endif // LLVM_ADT_POINTERUNION_H