Bug Summary

File:clang/lib/StaticAnalyzer/Core/MemRegion.cpp
Warning:line 938, column 36
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MemRegion.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/StaticAnalyzer/Core -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/StaticAnalyzer/Core -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp

1//===- MemRegion.cpp - Abstract memory regions for static analysis --------===//
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 MemRegion and its subclasses. MemRegion defines a
10// partially-typed abstraction of memory useful for path-sensitive dataflow
11// analyses.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/PrettyPrinter.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/Type.h"
26#include "clang/Analysis/AnalysisDeclContext.h"
27#include "clang/Analysis/Support/BumpVector.h"
28#include "clang/Basic/IdentifierTable.h"
29#include "clang/Basic/LLVM.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
32#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
35#include "llvm/ADT/APInt.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerUnion.h"
39#include "llvm/ADT/SmallString.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/Support/Allocator.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/CheckedArithmetic.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/raw_ostream.h"
49#include <cassert>
50#include <cstdint>
51#include <functional>
52#include <iterator>
53#include <string>
54#include <tuple>
55#include <utility>
56
57using namespace clang;
58using namespace ento;
59
60#define DEBUG_TYPE"MemRegion" "MemRegion"
61
62//===----------------------------------------------------------------------===//
63// MemRegion Construction.
64//===----------------------------------------------------------------------===//
65
66template <typename RegionTy, typename SuperTy, typename Arg1Ty>
67RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1,
68 const SuperTy *superRegion) {
69 llvm::FoldingSetNodeID ID;
70 RegionTy::ProfileRegion(ID, arg1, superRegion);
71 void *InsertPos;
72 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
73
74 if (!R) {
75 R = A.Allocate<RegionTy>();
76 new (R) RegionTy(arg1, superRegion);
77 Regions.InsertNode(R, InsertPos);
78 }
79
80 return R;
81}
82
83template <typename RegionTy, typename SuperTy, typename Arg1Ty, typename Arg2Ty>
84RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
85 const SuperTy *superRegion) {
86 llvm::FoldingSetNodeID ID;
87 RegionTy::ProfileRegion(ID, arg1, arg2, superRegion);
88 void *InsertPos;
89 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
90
91 if (!R) {
92 R = A.Allocate<RegionTy>();
93 new (R) RegionTy(arg1, arg2, superRegion);
94 Regions.InsertNode(R, InsertPos);
95 }
96
97 return R;
98}
99
100template <typename RegionTy, typename SuperTy,
101 typename Arg1Ty, typename Arg2Ty, typename Arg3Ty>
102RegionTy* MemRegionManager::getSubRegion(const Arg1Ty arg1, const Arg2Ty arg2,
103 const Arg3Ty arg3,
104 const SuperTy *superRegion) {
105 llvm::FoldingSetNodeID ID;
106 RegionTy::ProfileRegion(ID, arg1, arg2, arg3, superRegion);
107 void *InsertPos;
108 auto *R = cast_or_null<RegionTy>(Regions.FindNodeOrInsertPos(ID, InsertPos));
109
110 if (!R) {
111 R = A.Allocate<RegionTy>();
112 new (R) RegionTy(arg1, arg2, arg3, superRegion);
113 Regions.InsertNode(R, InsertPos);
114 }
115
116 return R;
117}
118
119//===----------------------------------------------------------------------===//
120// Object destruction.
121//===----------------------------------------------------------------------===//
122
123MemRegion::~MemRegion() = default;
124
125// All regions and their data are BumpPtrAllocated. No need to call their
126// destructors.
127MemRegionManager::~MemRegionManager() = default;
128
129//===----------------------------------------------------------------------===//
130// Basic methods.
131//===----------------------------------------------------------------------===//
132
133bool SubRegion::isSubRegionOf(const MemRegion* R) const {
134 const MemRegion* r = this;
135 do {
136 if (r == R)
137 return true;
138 if (const auto *sr = dyn_cast<SubRegion>(r))
139 r = sr->getSuperRegion();
140 else
141 break;
142 } while (r != nullptr);
143 return false;
144}
145
146MemRegionManager &SubRegion::getMemRegionManager() const {
147 const SubRegion* r = this;
148 do {
149 const MemRegion *superRegion = r->getSuperRegion();
150 if (const auto *sr = dyn_cast<SubRegion>(superRegion)) {
151 r = sr;
152 continue;
153 }
154 return superRegion->getMemRegionManager();
155 } while (true);
156}
157
158const StackFrameContext *VarRegion::getStackFrame() const {
159 const auto *SSR = dyn_cast<StackSpaceRegion>(getMemorySpace());
160 return SSR ? SSR->getStackFrame() : nullptr;
161}
162
163ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const SubRegion *sReg)
164 : DeclRegion(sReg, ObjCIvarRegionKind), IVD(ivd) {}
165
166const ObjCIvarDecl *ObjCIvarRegion::getDecl() const { return IVD; }
167
168QualType ObjCIvarRegion::getValueType() const {
169 return getDecl()->getType();
170}
171
172QualType CXXBaseObjectRegion::getValueType() const {
173 return QualType(getDecl()->getTypeForDecl(), 0);
174}
175
176QualType CXXDerivedObjectRegion::getValueType() const {
177 return QualType(getDecl()->getTypeForDecl(), 0);
178}
179
180QualType ParamVarRegion::getValueType() const {
181 assert(getDecl() &&(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 183, __extension__ __PRETTY_FUNCTION__))
182 "`ParamVarRegion` support functions without `Decl` not implemented"(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 183, __extension__ __PRETTY_FUNCTION__))
183 " yet.")(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 183, __extension__ __PRETTY_FUNCTION__))
;
184 return getDecl()->getType();
185}
186
187const ParmVarDecl *ParamVarRegion::getDecl() const {
188 const Decl *D = getStackFrame()->getDecl();
189
190 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
191 assert(Index < FD->param_size())(static_cast <bool> (Index < FD->param_size()) ? void
(0) : __assert_fail ("Index < FD->param_size()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 191, __extension__ __PRETTY_FUNCTION__))
;
192 return FD->parameters()[Index];
193 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
194 assert(Index < BD->param_size())(static_cast <bool> (Index < BD->param_size()) ? void
(0) : __assert_fail ("Index < BD->param_size()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 194, __extension__ __PRETTY_FUNCTION__))
;
195 return BD->parameters()[Index];
196 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
197 assert(Index < MD->param_size())(static_cast <bool> (Index < MD->param_size()) ? void
(0) : __assert_fail ("Index < MD->param_size()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 197, __extension__ __PRETTY_FUNCTION__))
;
198 return MD->parameters()[Index];
199 } else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
200 assert(Index < CD->param_size())(static_cast <bool> (Index < CD->param_size()) ? void
(0) : __assert_fail ("Index < CD->param_size()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 200, __extension__ __PRETTY_FUNCTION__))
;
201 return CD->parameters()[Index];
202 } else {
203 llvm_unreachable("Unexpected Decl kind!")::llvm::llvm_unreachable_internal("Unexpected Decl kind!", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 203)
;
204 }
205}
206
207//===----------------------------------------------------------------------===//
208// FoldingSet profiling.
209//===----------------------------------------------------------------------===//
210
211void MemSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
212 ID.AddInteger(static_cast<unsigned>(getKind()));
213}
214
215void StackSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
216 ID.AddInteger(static_cast<unsigned>(getKind()));
217 ID.AddPointer(getStackFrame());
218}
219
220void StaticGlobalSpaceRegion::Profile(llvm::FoldingSetNodeID &ID) const {
221 ID.AddInteger(static_cast<unsigned>(getKind()));
222 ID.AddPointer(getCodeRegion());
223}
224
225void StringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
226 const StringLiteral *Str,
227 const MemRegion *superRegion) {
228 ID.AddInteger(static_cast<unsigned>(StringRegionKind));
229 ID.AddPointer(Str);
230 ID.AddPointer(superRegion);
231}
232
233void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
234 const ObjCStringLiteral *Str,
235 const MemRegion *superRegion) {
236 ID.AddInteger(static_cast<unsigned>(ObjCStringRegionKind));
237 ID.AddPointer(Str);
238 ID.AddPointer(superRegion);
239}
240
241void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
242 const Expr *Ex, unsigned cnt,
243 const MemRegion *superRegion) {
244 ID.AddInteger(static_cast<unsigned>(AllocaRegionKind));
245 ID.AddPointer(Ex);
246 ID.AddInteger(cnt);
247 ID.AddPointer(superRegion);
248}
249
250void AllocaRegion::Profile(llvm::FoldingSetNodeID& ID) const {
251 ProfileRegion(ID, Ex, Cnt, superRegion);
252}
253
254void CompoundLiteralRegion::Profile(llvm::FoldingSetNodeID& ID) const {
255 CompoundLiteralRegion::ProfileRegion(ID, CL, superRegion);
256}
257
258void CompoundLiteralRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
259 const CompoundLiteralExpr *CL,
260 const MemRegion* superRegion) {
261 ID.AddInteger(static_cast<unsigned>(CompoundLiteralRegionKind));
262 ID.AddPointer(CL);
263 ID.AddPointer(superRegion);
264}
265
266void CXXThisRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
267 const PointerType *PT,
268 const MemRegion *sRegion) {
269 ID.AddInteger(static_cast<unsigned>(CXXThisRegionKind));
270 ID.AddPointer(PT);
271 ID.AddPointer(sRegion);
272}
273
274void CXXThisRegion::Profile(llvm::FoldingSetNodeID &ID) const {
275 CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
276}
277
278void FieldRegion::Profile(llvm::FoldingSetNodeID &ID) const {
279 ProfileRegion(ID, getDecl(), superRegion);
280}
281
282void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
283 const ObjCIvarDecl *ivd,
284 const MemRegion* superRegion) {
285 ID.AddInteger(static_cast<unsigned>(ObjCIvarRegionKind));
286 ID.AddPointer(ivd);
287 ID.AddPointer(superRegion);
288}
289
290void ObjCIvarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
291 ProfileRegion(ID, getDecl(), superRegion);
292}
293
294void NonParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
295 const VarDecl *VD,
296 const MemRegion *superRegion) {
297 ID.AddInteger(static_cast<unsigned>(NonParamVarRegionKind));
298 ID.AddPointer(VD);
299 ID.AddPointer(superRegion);
300}
301
302void NonParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
303 ProfileRegion(ID, getDecl(), superRegion);
304}
305
306void ParamVarRegion::ProfileRegion(llvm::FoldingSetNodeID &ID, const Expr *OE,
307 unsigned Idx, const MemRegion *SReg) {
308 ID.AddInteger(static_cast<unsigned>(ParamVarRegionKind));
309 ID.AddPointer(OE);
310 ID.AddInteger(Idx);
311 ID.AddPointer(SReg);
312}
313
314void ParamVarRegion::Profile(llvm::FoldingSetNodeID &ID) const {
315 ProfileRegion(ID, getOriginExpr(), getIndex(), superRegion);
316}
317
318void SymbolicRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, SymbolRef sym,
319 const MemRegion *sreg) {
320 ID.AddInteger(static_cast<unsigned>(MemRegion::SymbolicRegionKind));
321 ID.Add(sym);
322 ID.AddPointer(sreg);
323}
324
325void SymbolicRegion::Profile(llvm::FoldingSetNodeID& ID) const {
326 SymbolicRegion::ProfileRegion(ID, sym, getSuperRegion());
327}
328
329void ElementRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
330 QualType ElementType, SVal Idx,
331 const MemRegion* superRegion) {
332 ID.AddInteger(MemRegion::ElementRegionKind);
333 ID.Add(ElementType);
334 ID.AddPointer(superRegion);
335 Idx.Profile(ID);
336}
337
338void ElementRegion::Profile(llvm::FoldingSetNodeID& ID) const {
339 ElementRegion::ProfileRegion(ID, ElementType, Index, superRegion);
340}
341
342void FunctionCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
343 const NamedDecl *FD,
344 const MemRegion*) {
345 ID.AddInteger(MemRegion::FunctionCodeRegionKind);
346 ID.AddPointer(FD);
347}
348
349void FunctionCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
350 FunctionCodeRegion::ProfileRegion(ID, FD, superRegion);
351}
352
353void BlockCodeRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
354 const BlockDecl *BD, CanQualType,
355 const AnalysisDeclContext *AC,
356 const MemRegion*) {
357 ID.AddInteger(MemRegion::BlockCodeRegionKind);
358 ID.AddPointer(BD);
359}
360
361void BlockCodeRegion::Profile(llvm::FoldingSetNodeID& ID) const {
362 BlockCodeRegion::ProfileRegion(ID, BD, locTy, AC, superRegion);
363}
364
365void BlockDataRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
366 const BlockCodeRegion *BC,
367 const LocationContext *LC,
368 unsigned BlkCount,
369 const MemRegion *sReg) {
370 ID.AddInteger(MemRegion::BlockDataRegionKind);
371 ID.AddPointer(BC);
372 ID.AddPointer(LC);
373 ID.AddInteger(BlkCount);
374 ID.AddPointer(sReg);
375}
376
377void BlockDataRegion::Profile(llvm::FoldingSetNodeID& ID) const {
378 BlockDataRegion::ProfileRegion(ID, BC, LC, BlockCount, getSuperRegion());
379}
380
381void CXXTempObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
382 Expr const *Ex,
383 const MemRegion *sReg) {
384 ID.AddPointer(Ex);
385 ID.AddPointer(sReg);
386}
387
388void CXXTempObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
389 ProfileRegion(ID, Ex, getSuperRegion());
390}
391
392void CXXBaseObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
393 const CXXRecordDecl *RD,
394 bool IsVirtual,
395 const MemRegion *SReg) {
396 ID.AddPointer(RD);
397 ID.AddBoolean(IsVirtual);
398 ID.AddPointer(SReg);
399}
400
401void CXXBaseObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
402 ProfileRegion(ID, getDecl(), isVirtual(), superRegion);
403}
404
405void CXXDerivedObjectRegion::ProfileRegion(llvm::FoldingSetNodeID &ID,
406 const CXXRecordDecl *RD,
407 const MemRegion *SReg) {
408 ID.AddPointer(RD);
409 ID.AddPointer(SReg);
410}
411
412void CXXDerivedObjectRegion::Profile(llvm::FoldingSetNodeID &ID) const {
413 ProfileRegion(ID, getDecl(), superRegion);
414}
415
416//===----------------------------------------------------------------------===//
417// Region anchors.
418//===----------------------------------------------------------------------===//
419
420void GlobalsSpaceRegion::anchor() {}
421
422void NonStaticGlobalSpaceRegion::anchor() {}
423
424void StackSpaceRegion::anchor() {}
425
426void TypedRegion::anchor() {}
427
428void TypedValueRegion::anchor() {}
429
430void CodeTextRegion::anchor() {}
431
432void SubRegion::anchor() {}
433
434//===----------------------------------------------------------------------===//
435// Region pretty-printing.
436//===----------------------------------------------------------------------===//
437
438LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MemRegion::dump() const {
439 dumpToStream(llvm::errs());
440}
441
442std::string MemRegion::getString() const {
443 std::string s;
444 llvm::raw_string_ostream os(s);
445 dumpToStream(os);
446 return os.str();
447}
448
449void MemRegion::dumpToStream(raw_ostream &os) const {
450 os << "<Unknown Region>";
451}
452
453void AllocaRegion::dumpToStream(raw_ostream &os) const {
454 os << "alloca{S" << Ex->getID(getContext()) << ',' << Cnt << '}';
455}
456
457void FunctionCodeRegion::dumpToStream(raw_ostream &os) const {
458 os << "code{" << getDecl()->getDeclName().getAsString() << '}';
459}
460
461void BlockCodeRegion::dumpToStream(raw_ostream &os) const {
462 os << "block_code{" << static_cast<const void *>(this) << '}';
463}
464
465void BlockDataRegion::dumpToStream(raw_ostream &os) const {
466 os << "block_data{" << BC;
467 os << "; ";
468 for (BlockDataRegion::referenced_vars_iterator
469 I = referenced_vars_begin(),
470 E = referenced_vars_end(); I != E; ++I)
471 os << "(" << I.getCapturedRegion() << "<-" <<
472 I.getOriginalRegion() << ") ";
473 os << '}';
474}
475
476void CompoundLiteralRegion::dumpToStream(raw_ostream &os) const {
477 // FIXME: More elaborate pretty-printing.
478 os << "{ S" << CL->getID(getContext()) << " }";
479}
480
481void CXXTempObjectRegion::dumpToStream(raw_ostream &os) const {
482 os << "temp_object{" << getValueType().getAsString() << ", "
483 << "S" << Ex->getID(getContext()) << '}';
484}
485
486void CXXBaseObjectRegion::dumpToStream(raw_ostream &os) const {
487 os << "Base{" << superRegion << ',' << getDecl()->getName() << '}';
488}
489
490void CXXDerivedObjectRegion::dumpToStream(raw_ostream &os) const {
491 os << "Derived{" << superRegion << ',' << getDecl()->getName() << '}';
492}
493
494void CXXThisRegion::dumpToStream(raw_ostream &os) const {
495 os << "this";
496}
497
498void ElementRegion::dumpToStream(raw_ostream &os) const {
499 os << "Element{" << superRegion << ','
500 << Index << ',' << getElementType().getAsString() << '}';
501}
502
503void FieldRegion::dumpToStream(raw_ostream &os) const {
504 os << superRegion << "." << *getDecl();
505}
506
507void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
508 os << "Ivar{" << superRegion << ',' << *getDecl() << '}';
509}
510
511void StringRegion::dumpToStream(raw_ostream &os) const {
512 assert(Str != nullptr && "Expecting non-null StringLiteral")(static_cast <bool> (Str != nullptr && "Expecting non-null StringLiteral"
) ? void (0) : __assert_fail ("Str != nullptr && \"Expecting non-null StringLiteral\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 512, __extension__ __PRETTY_FUNCTION__))
;
513 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
514}
515
516void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
517 assert(Str != nullptr && "Expecting non-null ObjCStringLiteral")(static_cast <bool> (Str != nullptr && "Expecting non-null ObjCStringLiteral"
) ? void (0) : __assert_fail ("Str != nullptr && \"Expecting non-null ObjCStringLiteral\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 517, __extension__ __PRETTY_FUNCTION__))
;
518 Str->printPretty(os, nullptr, PrintingPolicy(getContext().getLangOpts()));
519}
520
521void SymbolicRegion::dumpToStream(raw_ostream &os) const {
522 if (isa<HeapSpaceRegion>(getSuperRegion()))
523 os << "Heap";
524 os << "SymRegion{" << sym << '}';
525}
526
527void NonParamVarRegion::dumpToStream(raw_ostream &os) const {
528 if (const IdentifierInfo *ID = VD->getIdentifier())
529 os << ID->getName();
530 else
531 os << "NonParamVarRegion{D" << VD->getID() << '}';
532}
533
534LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RegionRawOffset::dump() const {
535 dumpToStream(llvm::errs());
536}
537
538void RegionRawOffset::dumpToStream(raw_ostream &os) const {
539 os << "raw_offset{" << getRegion() << ',' << getOffset().getQuantity() << '}';
540}
541
542void CodeSpaceRegion::dumpToStream(raw_ostream &os) const {
543 os << "CodeSpaceRegion";
544}
545
546void StaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
547 os << "StaticGlobalsMemSpace{" << CR << '}';
548}
549
550void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
551 os << "GlobalInternalSpaceRegion";
552}
553
554void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
555 os << "GlobalSystemSpaceRegion";
556}
557
558void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
559 os << "GlobalImmutableSpaceRegion";
560}
561
562void HeapSpaceRegion::dumpToStream(raw_ostream &os) const {
563 os << "HeapSpaceRegion";
564}
565
566void UnknownSpaceRegion::dumpToStream(raw_ostream &os) const {
567 os << "UnknownSpaceRegion";
568}
569
570void StackArgumentsSpaceRegion::dumpToStream(raw_ostream &os) const {
571 os << "StackArgumentsSpaceRegion";
572}
573
574void StackLocalsSpaceRegion::dumpToStream(raw_ostream &os) const {
575 os << "StackLocalsSpaceRegion";
576}
577
578void ParamVarRegion::dumpToStream(raw_ostream &os) const {
579 const ParmVarDecl *PVD = getDecl();
580 assert(PVD &&(static_cast <bool> (PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 582, __extension__ __PRETTY_FUNCTION__))
581 "`ParamVarRegion` support functions without `Decl` not implemented"(static_cast <bool> (PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 582, __extension__ __PRETTY_FUNCTION__))
582 " yet.")(static_cast <bool> (PVD && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("PVD && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 582, __extension__ __PRETTY_FUNCTION__))
;
583 if (const IdentifierInfo *ID = PVD->getIdentifier()) {
584 os << ID->getName();
585 } else {
586 os << "ParamVarRegion{P" << PVD->getID() << '}';
587 }
588}
589
590bool MemRegion::canPrintPretty() const {
591 return canPrintPrettyAsExpr();
592}
593
594bool MemRegion::canPrintPrettyAsExpr() const {
595 return false;
596}
597
598void MemRegion::printPretty(raw_ostream &os) const {
599 assert(canPrintPretty() && "This region cannot be printed pretty.")(static_cast <bool> (canPrintPretty() && "This region cannot be printed pretty."
) ? void (0) : __assert_fail ("canPrintPretty() && \"This region cannot be printed pretty.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 599, __extension__ __PRETTY_FUNCTION__))
;
600 os << "'";
601 printPrettyAsExpr(os);
602 os << "'";
603}
604
605void MemRegion::printPrettyAsExpr(raw_ostream &) const {
606 llvm_unreachable("This region cannot be printed pretty.")::llvm::llvm_unreachable_internal("This region cannot be printed pretty."
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 606)
;
607}
608
609bool NonParamVarRegion::canPrintPrettyAsExpr() const { return true; }
610
611void NonParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
612 os << getDecl()->getName();
613}
614
615bool ParamVarRegion::canPrintPrettyAsExpr() const { return true; }
616
617void ParamVarRegion::printPrettyAsExpr(raw_ostream &os) const {
618 assert(getDecl() &&(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 620, __extension__ __PRETTY_FUNCTION__))
619 "`ParamVarRegion` support functions without `Decl` not implemented"(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 620, __extension__ __PRETTY_FUNCTION__))
620 " yet.")(static_cast <bool> (getDecl() && "`ParamVarRegion` support functions without `Decl` not implemented"
" yet.") ? void (0) : __assert_fail ("getDecl() && \"`ParamVarRegion` support functions without `Decl` not implemented\" \" yet.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 620, __extension__ __PRETTY_FUNCTION__))
;
621 os << getDecl()->getName();
622}
623
624bool ObjCIvarRegion::canPrintPrettyAsExpr() const {
625 return true;
626}
627
628void ObjCIvarRegion::printPrettyAsExpr(raw_ostream &os) const {
629 os << getDecl()->getName();
630}
631
632bool FieldRegion::canPrintPretty() const {
633 return true;
634}
635
636bool FieldRegion::canPrintPrettyAsExpr() const {
637 return superRegion->canPrintPrettyAsExpr();
638}
639
640void FieldRegion::printPrettyAsExpr(raw_ostream &os) const {
641 assert(canPrintPrettyAsExpr())(static_cast <bool> (canPrintPrettyAsExpr()) ? void (0)
: __assert_fail ("canPrintPrettyAsExpr()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 641, __extension__ __PRETTY_FUNCTION__))
;
642 superRegion->printPrettyAsExpr(os);
643 os << "." << getDecl()->getName();
644}
645
646void FieldRegion::printPretty(raw_ostream &os) const {
647 if (canPrintPrettyAsExpr()) {
648 os << "\'";
649 printPrettyAsExpr(os);
650 os << "'";
651 } else {
652 os << "field " << "\'" << getDecl()->getName() << "'";
653 }
654}
655
656bool CXXBaseObjectRegion::canPrintPrettyAsExpr() const {
657 return superRegion->canPrintPrettyAsExpr();
658}
659
660void CXXBaseObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
661 superRegion->printPrettyAsExpr(os);
662}
663
664bool CXXDerivedObjectRegion::canPrintPrettyAsExpr() const {
665 return superRegion->canPrintPrettyAsExpr();
666}
667
668void CXXDerivedObjectRegion::printPrettyAsExpr(raw_ostream &os) const {
669 superRegion->printPrettyAsExpr(os);
670}
671
672std::string MemRegion::getDescriptiveName(bool UseQuotes) const {
673 std::string VariableName;
674 std::string ArrayIndices;
675 const MemRegion *R = this;
676 SmallString<50> buf;
677 llvm::raw_svector_ostream os(buf);
678
679 // Obtain array indices to add them to the variable name.
680 const ElementRegion *ER = nullptr;
681 while ((ER = R->getAs<ElementRegion>())) {
682 // Index is a ConcreteInt.
683 if (auto CI = ER->getIndex().getAs<nonloc::ConcreteInt>()) {
684 llvm::SmallString<2> Idx;
685 CI->getValue().toString(Idx);
686 ArrayIndices = (llvm::Twine("[") + Idx.str() + "]" + ArrayIndices).str();
687 }
688 // If not a ConcreteInt, try to obtain the variable
689 // name by calling 'getDescriptiveName' recursively.
690 else {
691 std::string Idx = ER->getDescriptiveName(false);
692 if (!Idx.empty()) {
693 ArrayIndices = (llvm::Twine("[") + Idx + "]" + ArrayIndices).str();
694 }
695 }
696 R = ER->getSuperRegion();
697 }
698
699 // Get variable name.
700 if (R && R->canPrintPrettyAsExpr()) {
701 R->printPrettyAsExpr(os);
702 if (UseQuotes)
703 return (llvm::Twine("'") + os.str() + ArrayIndices + "'").str();
704 else
705 return (llvm::Twine(os.str()) + ArrayIndices).str();
706 }
707
708 return VariableName;
709}
710
711SourceRange MemRegion::sourceRange() const {
712 const auto *const VR = dyn_cast<VarRegion>(this->getBaseRegion());
713 const auto *const FR = dyn_cast<FieldRegion>(this);
714
715 // Check for more specific regions first.
716 // FieldRegion
717 if (FR) {
718 return FR->getDecl()->getSourceRange();
719 }
720 // VarRegion
721 else if (VR) {
722 return VR->getDecl()->getSourceRange();
723 }
724 // Return invalid source range (can be checked by client).
725 else
726 return {};
727}
728
729//===----------------------------------------------------------------------===//
730// MemRegionManager methods.
731//===----------------------------------------------------------------------===//
732
733DefinedOrUnknownSVal MemRegionManager::getStaticSize(const MemRegion *MR,
734 SValBuilder &SVB) const {
735 const auto *SR = cast<SubRegion>(MR);
736 SymbolManager &SymMgr = SVB.getSymbolManager();
737
738 switch (SR->getKind()) {
739 case MemRegion::AllocaRegionKind:
740 case MemRegion::SymbolicRegionKind:
741 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
742 case MemRegion::StringRegionKind:
743 return SVB.makeIntVal(
744 cast<StringRegion>(SR)->getStringLiteral()->getByteLength() + 1,
745 SVB.getArrayIndexType());
746 case MemRegion::CompoundLiteralRegionKind:
747 case MemRegion::CXXBaseObjectRegionKind:
748 case MemRegion::CXXDerivedObjectRegionKind:
749 case MemRegion::CXXTempObjectRegionKind:
750 case MemRegion::CXXThisRegionKind:
751 case MemRegion::ObjCIvarRegionKind:
752 case MemRegion::NonParamVarRegionKind:
753 case MemRegion::ParamVarRegionKind:
754 case MemRegion::ElementRegionKind:
755 case MemRegion::ObjCStringRegionKind: {
756 QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
757 if (isa<VariableArrayType>(Ty))
758 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
759
760 if (Ty->isIncompleteType())
761 return UnknownVal();
762
763 return getElementExtent(Ty, SVB);
764 }
765 case MemRegion::FieldRegionKind: {
766 // Force callers to deal with bitfields explicitly.
767 if (cast<FieldRegion>(SR)->getDecl()->isBitField())
768 return UnknownVal();
769
770 QualType Ty = cast<TypedValueRegion>(SR)->getDesugaredValueType(Ctx);
771 const DefinedOrUnknownSVal Size = getElementExtent(Ty, SVB);
772
773 // A zero-length array at the end of a struct often stands for dynamically
774 // allocated extra memory.
775 const auto isFlexibleArrayMemberCandidate = [this](QualType Ty) -> bool {
776 const ArrayType *AT = Ctx.getAsArrayType(Ty);
777 if (!AT)
778 return false;
779 if (isa<IncompleteArrayType>(AT))
780 return true;
781
782 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
783 const llvm::APInt &Size = CAT->getSize();
784 if (Size.isNullValue())
785 return true;
786 }
787 return false;
788 };
789
790 if (isFlexibleArrayMemberCandidate(Ty))
791 return UnknownVal();
792
793 return Size;
794 }
795 // FIXME: The following are being used in 'SimpleSValBuilder' and in
796 // 'ArrayBoundChecker::checkLocation' because there is no symbol to
797 // represent the regions more appropriately.
798 case MemRegion::BlockDataRegionKind:
799 case MemRegion::BlockCodeRegionKind:
800 case MemRegion::FunctionCodeRegionKind:
801 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
802 default:
803 llvm_unreachable("Unhandled region")::llvm::llvm_unreachable_internal("Unhandled region", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 803)
;
804 }
805}
806
807template <typename REG>
808const REG *MemRegionManager::LazyAllocate(REG*& region) {
809 if (!region) {
810 region = A.Allocate<REG>();
811 new (region) REG(*this);
812 }
813
814 return region;
815}
816
817template <typename REG, typename ARG>
818const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
819 if (!region) {
820 region = A.Allocate<REG>();
821 new (region) REG(this, a);
822 }
823
824 return region;
825}
826
827const StackLocalsSpaceRegion*
828MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
829 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 829, __extension__ __PRETTY_FUNCTION__))
;
830 StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
831
832 if (R)
833 return R;
834
835 R = A.Allocate<StackLocalsSpaceRegion>();
836 new (R) StackLocalsSpaceRegion(*this, STC);
837 return R;
838}
839
840const StackArgumentsSpaceRegion *
841MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
842 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 842, __extension__ __PRETTY_FUNCTION__))
;
843 StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
844
845 if (R)
846 return R;
847
848 R = A.Allocate<StackArgumentsSpaceRegion>();
849 new (R) StackArgumentsSpaceRegion(*this, STC);
850 return R;
851}
852
853const GlobalsSpaceRegion
854*MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
855 const CodeTextRegion *CR) {
856 if (!CR) {
857 if (K == MemRegion::GlobalSystemSpaceRegionKind)
858 return LazyAllocate(SystemGlobals);
859 if (K == MemRegion::GlobalImmutableSpaceRegionKind)
860 return LazyAllocate(ImmutableGlobals);
861 assert(K == MemRegion::GlobalInternalSpaceRegionKind)(static_cast <bool> (K == MemRegion::GlobalInternalSpaceRegionKind
) ? void (0) : __assert_fail ("K == MemRegion::GlobalInternalSpaceRegionKind"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 861, __extension__ __PRETTY_FUNCTION__))
;
862 return LazyAllocate(InternalGlobals);
863 }
864
865 assert(K == MemRegion::StaticGlobalSpaceRegionKind)(static_cast <bool> (K == MemRegion::StaticGlobalSpaceRegionKind
) ? void (0) : __assert_fail ("K == MemRegion::StaticGlobalSpaceRegionKind"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 865, __extension__ __PRETTY_FUNCTION__))
;
866 StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
867 if (R)
868 return R;
869
870 R = A.Allocate<StaticGlobalSpaceRegion>();
871 new (R) StaticGlobalSpaceRegion(*this, CR);
872 return R;
873}
874
875const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
876 return LazyAllocate(heap);
877}
878
879const UnknownSpaceRegion *MemRegionManager::getUnknownRegion() {
880 return LazyAllocate(unknown);
881}
882
883const CodeSpaceRegion *MemRegionManager::getCodeRegion() {
884 return LazyAllocate(code);
885}
886
887//===----------------------------------------------------------------------===//
888// Constructing regions.
889//===----------------------------------------------------------------------===//
890
891const StringRegion *MemRegionManager::getStringRegion(const StringLiteral *Str){
892 return getSubRegion<StringRegion>(
893 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
894}
895
896const ObjCStringRegion *
897MemRegionManager::getObjCStringRegion(const ObjCStringLiteral *Str){
898 return getSubRegion<ObjCStringRegion>(
899 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
900}
901
902/// Look through a chain of LocationContexts to either find the
903/// StackFrameContext that matches a DeclContext, or find a VarRegion
904/// for a variable captured by a block.
905static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
906getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
907 const DeclContext *DC,
908 const VarDecl *VD) {
909 while (LC) {
910 if (const auto *SFC = dyn_cast<StackFrameContext>(LC)) {
911 if (cast<DeclContext>(SFC->getDecl()) == DC)
912 return SFC;
913 }
914 if (const auto *BC = dyn_cast<BlockInvocationContext>(LC)) {
915 const auto *BR = static_cast<const BlockDataRegion *>(BC->getData());
916 // FIXME: This can be made more efficient.
917 for (BlockDataRegion::referenced_vars_iterator
918 I = BR->referenced_vars_begin(),
919 E = BR->referenced_vars_end(); I != E; ++I) {
920 const TypedValueRegion *OrigR = I.getOriginalRegion();
921 if (const auto *VR = dyn_cast<VarRegion>(OrigR)) {
922 if (VR->getDecl() == VD)
923 return cast<VarRegion>(I.getCapturedRegion());
924 }
925 }
926 }
927
928 LC = LC->getParent();
929 }
930 return (const StackFrameContext *)nullptr;
931}
932
933const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
934 const LocationContext *LC) {
935 const auto *PVD = dyn_cast<ParmVarDecl>(D);
26
Assuming 'D' is a 'ParmVarDecl'
936 if (PVD
26.1
'PVD' is non-null
26.1
'PVD' is non-null
26.1
'PVD' is non-null
) {
27
Taking true branch
937 unsigned Index = PVD->getFunctionScopeIndex();
938 const StackFrameContext *SFC = LC->getStackFrame();
28
Called C++ object pointer is null
939 const Stmt *CallSite = SFC->getCallSite();
940 if (CallSite) {
941 const Decl *D = SFC->getDecl();
942 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
943 if (Index < FD->param_size() && FD->parameters()[Index] == PVD)
944 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
945 getStackArgumentsRegion(SFC));
946 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
947 if (Index < BD->param_size() && BD->parameters()[Index] == PVD)
948 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
949 getStackArgumentsRegion(SFC));
950 } else {
951 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
952 getStackArgumentsRegion(SFC));
953 }
954 }
955 }
956
957 D = D->getCanonicalDecl();
958 const MemRegion *sReg = nullptr;
959
960 if (D->hasGlobalStorage() && !D->isStaticLocal()) {
961
962 // First handle the globals defined in system headers.
963 if (Ctx.getSourceManager().isInSystemHeader(D->getLocation())) {
964 // Whitelist the system globals which often DO GET modified, assume the
965 // rest are immutable.
966 if (D->getName().find("errno") != StringRef::npos)
967 sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
968 else
969 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
970
971 // Treat other globals as GlobalInternal unless they are constants.
972 } else {
973 QualType GQT = D->getType();
974 const Type *GT = GQT.getTypePtrOrNull();
975 // TODO: We could walk the complex types here and see if everything is
976 // constified.
977 if (GT && GQT.isConstQualified() && GT->isArithmeticType())
978 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
979 else
980 sReg = getGlobalsRegion();
981 }
982
983 // Finally handle static locals.
984 } else {
985 // FIXME: Once we implement scope handling, we will need to properly lookup
986 // 'D' to the proper LocationContext.
987 const DeclContext *DC = D->getDeclContext();
988 llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
989 getStackOrCaptureRegionForDeclContext(LC, DC, D);
990
991 if (V.is<const VarRegion*>())
992 return V.get<const VarRegion*>();
993
994 const auto *STC = V.get<const StackFrameContext *>();
995
996 if (!STC) {
997 // FIXME: Assign a more sensible memory space to static locals
998 // we see from within blocks that we analyze as top-level declarations.
999 sReg = getUnknownRegion();
1000 } else {
1001 if (D->hasLocalStorage()) {
1002 sReg = isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)
1003 ? static_cast<const MemRegion*>(getStackArgumentsRegion(STC))
1004 : static_cast<const MemRegion*>(getStackLocalsRegion(STC));
1005 }
1006 else {
1007 assert(D->isStaticLocal())(static_cast <bool> (D->isStaticLocal()) ? void (0) :
__assert_fail ("D->isStaticLocal()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1007, __extension__ __PRETTY_FUNCTION__))
;
1008 const Decl *STCD = STC->getDecl();
1009 if (isa<FunctionDecl>(STCD) || isa<ObjCMethodDecl>(STCD))
1010 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1011 getFunctionCodeRegion(cast<NamedDecl>(STCD)));
1012 else if (const auto *BD = dyn_cast<BlockDecl>(STCD)) {
1013 // FIXME: The fallback type here is totally bogus -- though it should
1014 // never be queried, it will prevent uniquing with the real
1015 // BlockCodeRegion. Ideally we'd fix the AST so that we always had a
1016 // signature.
1017 QualType T;
1018 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten())
1019 T = TSI->getType();
1020 if (T.isNull())
1021 T = getContext().VoidTy;
1022 if (!T->getAs<FunctionType>())
1023 T = getContext().getFunctionNoProtoType(T);
1024 T = getContext().getBlockPointerType(T);
1025
1026 const BlockCodeRegion *BTR =
1027 getBlockCodeRegion(BD, Ctx.getCanonicalType(T),
1028 STC->getAnalysisDeclContext());
1029 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1030 BTR);
1031 }
1032 else {
1033 sReg = getGlobalsRegion();
1034 }
1035 }
1036 }
1037 }
1038
1039 return getSubRegion<NonParamVarRegion>(D, sReg);
1040}
1041
1042const NonParamVarRegion *
1043MemRegionManager::getNonParamVarRegion(const VarDecl *D,
1044 const MemRegion *superR) {
1045 D = D->getCanonicalDecl();
1046 return getSubRegion<NonParamVarRegion>(D, superR);
1047}
1048
1049const ParamVarRegion *
1050MemRegionManager::getParamVarRegion(const Expr *OriginExpr, unsigned Index,
1051 const LocationContext *LC) {
1052 const StackFrameContext *SFC = LC->getStackFrame();
1053 assert(SFC)(static_cast <bool> (SFC) ? void (0) : __assert_fail ("SFC"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1053, __extension__ __PRETTY_FUNCTION__))
;
1054 return getSubRegion<ParamVarRegion>(OriginExpr, Index,
1055 getStackArgumentsRegion(SFC));
1056}
1057
1058const BlockDataRegion *
1059MemRegionManager::getBlockDataRegion(const BlockCodeRegion *BC,
1060 const LocationContext *LC,
1061 unsigned blockCount) {
1062 const MemSpaceRegion *sReg = nullptr;
1063 const BlockDecl *BD = BC->getDecl();
1064 if (!BD->hasCaptures()) {
1065 // This handles 'static' blocks.
1066 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
1067 }
1068 else {
1069 if (LC) {
1070 // FIXME: Once we implement scope handling, we want the parent region
1071 // to be the scope.
1072 const StackFrameContext *STC = LC->getStackFrame();
1073 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1073, __extension__ __PRETTY_FUNCTION__))
;
1074 sReg = getStackLocalsRegion(STC);
1075 }
1076 else {
1077 // We allow 'LC' to be NULL for cases where want BlockDataRegions
1078 // without context-sensitivity.
1079 sReg = getUnknownRegion();
1080 }
1081 }
1082
1083 return getSubRegion<BlockDataRegion>(BC, LC, blockCount, sReg);
1084}
1085
1086const CXXTempObjectRegion *
1087MemRegionManager::getCXXStaticTempObjectRegion(const Expr *Ex) {
1088 return getSubRegion<CXXTempObjectRegion>(
1089 Ex, getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr));
1090}
1091
1092const CompoundLiteralRegion*
1093MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
1094 const LocationContext *LC) {
1095 const MemSpaceRegion *sReg = nullptr;
1096
1097 if (CL->isFileScope())
1098 sReg = getGlobalsRegion();
1099 else {
1100 const StackFrameContext *STC = LC->getStackFrame();
1101 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1101, __extension__ __PRETTY_FUNCTION__))
;
1102 sReg = getStackLocalsRegion(STC);
1103 }
1104
1105 return getSubRegion<CompoundLiteralRegion>(CL, sReg);
1106}
1107
1108const ElementRegion*
1109MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
1110 const SubRegion* superRegion,
1111 ASTContext &Ctx){
1112 QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
1113
1114 llvm::FoldingSetNodeID ID;
1115 ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
1116
1117 void *InsertPos;
1118 MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
1119 auto *R = cast_or_null<ElementRegion>(data);
1120
1121 if (!R) {
1122 R = A.Allocate<ElementRegion>();
1123 new (R) ElementRegion(T, Idx, superRegion);
1124 Regions.InsertNode(R, InsertPos);
1125 }
1126
1127 return R;
1128}
1129
1130const FunctionCodeRegion *
1131MemRegionManager::getFunctionCodeRegion(const NamedDecl *FD) {
1132 // To think: should we canonicalize the declaration here?
1133 return getSubRegion<FunctionCodeRegion>(FD, getCodeRegion());
1134}
1135
1136const BlockCodeRegion *
1137MemRegionManager::getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy,
1138 AnalysisDeclContext *AC) {
1139 return getSubRegion<BlockCodeRegion>(BD, locTy, AC, getCodeRegion());
1140}
1141
1142/// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
1143const SymbolicRegion *MemRegionManager::getSymbolicRegion(SymbolRef sym) {
1144 return getSubRegion<SymbolicRegion>(sym, getUnknownRegion());
1145}
1146
1147const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
1148 return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
1149}
1150
1151const FieldRegion*
1152MemRegionManager::getFieldRegion(const FieldDecl *d,
1153 const SubRegion* superRegion){
1154 return getSubRegion<FieldRegion>(d, superRegion);
1155}
1156
1157const ObjCIvarRegion*
1158MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
1159 const SubRegion* superRegion) {
1160 return getSubRegion<ObjCIvarRegion>(d, superRegion);
1161}
1162
1163const CXXTempObjectRegion*
1164MemRegionManager::getCXXTempObjectRegion(Expr const *E,
1165 LocationContext const *LC) {
1166 const StackFrameContext *SFC = LC->getStackFrame();
1167 assert(SFC)(static_cast <bool> (SFC) ? void (0) : __assert_fail ("SFC"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1167, __extension__ __PRETTY_FUNCTION__))
;
1168 return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
1169}
1170
1171/// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
1172/// class of the type of \p Super.
1173static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
1174 const TypedValueRegion *Super,
1175 bool IsVirtual) {
1176 BaseClass = BaseClass->getCanonicalDecl();
1177
1178 const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
1179 if (!Class)
1180 return true;
1181
1182 if (IsVirtual)
1183 return Class->isVirtuallyDerivedFrom(BaseClass);
1184
1185 for (const auto &I : Class->bases()) {
1186 if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
1187 return true;
1188 }
1189
1190 return false;
1191}
1192
1193const CXXBaseObjectRegion *
1194MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
1195 const SubRegion *Super,
1196 bool IsVirtual) {
1197 if (isa<TypedValueRegion>(Super)) {
1198 assert(isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual))(static_cast <bool> (isValidBaseClass(RD, cast<TypedValueRegion
>(Super), IsVirtual)) ? void (0) : __assert_fail ("isValidBaseClass(RD, cast<TypedValueRegion>(Super), IsVirtual)"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1198, __extension__ __PRETTY_FUNCTION__))
;
1199 (void)&isValidBaseClass;
1200
1201 if (IsVirtual) {
1202 // Virtual base regions should not be layered, since the layout rules
1203 // are different.
1204 while (const auto *Base = dyn_cast<CXXBaseObjectRegion>(Super))
1205 Super = cast<SubRegion>(Base->getSuperRegion());
1206 assert(Super && !isa<MemSpaceRegion>(Super))(static_cast <bool> (Super && !isa<MemSpaceRegion
>(Super)) ? void (0) : __assert_fail ("Super && !isa<MemSpaceRegion>(Super)"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1206, __extension__ __PRETTY_FUNCTION__))
;
1207 }
1208 }
1209
1210 return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
1211}
1212
1213const CXXDerivedObjectRegion *
1214MemRegionManager::getCXXDerivedObjectRegion(const CXXRecordDecl *RD,
1215 const SubRegion *Super) {
1216 return getSubRegion<CXXDerivedObjectRegion>(RD, Super);
1217}
1218
1219const CXXThisRegion*
1220MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
1221 const LocationContext *LC) {
1222 const auto *PT = thisPointerTy->getAs<PointerType>();
1223 assert(PT)(static_cast <bool> (PT) ? void (0) : __assert_fail ("PT"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1223, __extension__ __PRETTY_FUNCTION__))
;
1224 // Inside the body of the operator() of a lambda a this expr might refer to an
1225 // object in one of the parent location contexts.
1226 const auto *D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1227 // FIXME: when operator() of lambda is analyzed as a top level function and
1228 // 'this' refers to a this to the enclosing scope, there is no right region to
1229 // return.
1230 while (!LC->inTopFrame() && (!D || D->isStatic() ||
1231 PT != D->getThisType()->getAs<PointerType>())) {
1232 LC = LC->getParent();
1233 D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1234 }
1235 const StackFrameContext *STC = LC->getStackFrame();
1236 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1236, __extension__ __PRETTY_FUNCTION__))
;
1237 return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
1238}
1239
1240const AllocaRegion*
1241MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
1242 const LocationContext *LC) {
1243 const StackFrameContext *STC = LC->getStackFrame();
1244 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1244, __extension__ __PRETTY_FUNCTION__))
;
1245 return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
1246}
1247
1248const MemSpaceRegion *MemRegion::getMemorySpace() const {
1249 const MemRegion *R = this;
1250 const auto *SR = dyn_cast<SubRegion>(this);
1251
1252 while (SR) {
1253 R = SR->getSuperRegion();
1254 SR = dyn_cast<SubRegion>(R);
1255 }
1256
1257 return dyn_cast<MemSpaceRegion>(R);
1258}
1259
1260bool MemRegion::hasStackStorage() const {
1261 return isa<StackSpaceRegion>(getMemorySpace());
1262}
1263
1264bool MemRegion::hasStackNonParametersStorage() const {
1265 return isa<StackLocalsSpaceRegion>(getMemorySpace());
1266}
1267
1268bool MemRegion::hasStackParametersStorage() const {
1269 return isa<StackArgumentsSpaceRegion>(getMemorySpace());
1270}
1271
1272bool MemRegion::hasGlobalsOrParametersStorage() const {
1273 const MemSpaceRegion *MS = getMemorySpace();
1274 return isa<StackArgumentsSpaceRegion>(MS) ||
1275 isa<GlobalsSpaceRegion>(MS);
1276}
1277
1278// getBaseRegion strips away all elements and fields, and get the base region
1279// of them.
1280const MemRegion *MemRegion::getBaseRegion() const {
1281 const MemRegion *R = this;
1282 while (true) {
1283 switch (R->getKind()) {
1284 case MemRegion::ElementRegionKind:
1285 case MemRegion::FieldRegionKind:
1286 case MemRegion::ObjCIvarRegionKind:
1287 case MemRegion::CXXBaseObjectRegionKind:
1288 case MemRegion::CXXDerivedObjectRegionKind:
1289 R = cast<SubRegion>(R)->getSuperRegion();
1290 continue;
1291 default:
1292 break;
1293 }
1294 break;
1295 }
1296 return R;
1297}
1298
1299// getgetMostDerivedObjectRegion gets the region of the root class of a C++
1300// class hierarchy.
1301const MemRegion *MemRegion::getMostDerivedObjectRegion() const {
1302 const MemRegion *R = this;
1303 while (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
1304 R = BR->getSuperRegion();
1305 return R;
1306}
1307
1308bool MemRegion::isSubRegionOf(const MemRegion *) const {
1309 return false;
1310}
1311
1312//===----------------------------------------------------------------------===//
1313// View handling.
1314//===----------------------------------------------------------------------===//
1315
1316const MemRegion *MemRegion::StripCasts(bool StripBaseAndDerivedCasts) const {
1317 const MemRegion *R = this;
1318 while (true) {
1319 switch (R->getKind()) {
1320 case ElementRegionKind: {
1321 const auto *ER = cast<ElementRegion>(R);
1322 if (!ER->getIndex().isZeroConstant())
1323 return R;
1324 R = ER->getSuperRegion();
1325 break;
1326 }
1327 case CXXBaseObjectRegionKind:
1328 case CXXDerivedObjectRegionKind:
1329 if (!StripBaseAndDerivedCasts)
1330 return R;
1331 R = cast<TypedValueRegion>(R)->getSuperRegion();
1332 break;
1333 default:
1334 return R;
1335 }
1336 }
1337}
1338
1339const SymbolicRegion *MemRegion::getSymbolicBase() const {
1340 const auto *SubR = dyn_cast<SubRegion>(this);
1341
1342 while (SubR) {
1343 if (const auto *SymR = dyn_cast<SymbolicRegion>(SubR))
1344 return SymR;
1345 SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1346 }
1347 return nullptr;
1348}
1349
1350RegionRawOffset ElementRegion::getAsArrayOffset() const {
1351 int64_t offset = 0;
1352 const ElementRegion *ER = this;
1353 const MemRegion *superR = nullptr;
1354 ASTContext &C = getContext();
1355
1356 // FIXME: Handle multi-dimensional arrays.
1357
1358 while (ER) {
1359 superR = ER->getSuperRegion();
1360
1361 // FIXME: generalize to symbolic offsets.
1362 SVal index = ER->getIndex();
1363 if (auto CI = index.getAs<nonloc::ConcreteInt>()) {
1364 // Update the offset.
1365 int64_t i = CI->getValue().getSExtValue();
1366
1367 if (i != 0) {
1368 QualType elemType = ER->getElementType();
1369
1370 // If we are pointing to an incomplete type, go no further.
1371 if (elemType->isIncompleteType()) {
1372 superR = ER;
1373 break;
1374 }
1375
1376 int64_t size = C.getTypeSizeInChars(elemType).getQuantity();
1377 if (auto NewOffset = llvm::checkedMulAdd(i, size, offset)) {
1378 offset = *NewOffset;
1379 } else {
1380 LLVM_DEBUG(llvm::dbgs() << "MemRegion::getAsArrayOffset: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("MemRegion")) { llvm::dbgs() << "MemRegion::getAsArrayOffset: "
<< "offset overflowing, returning unknown\n"; } } while
(false)
1381 << "offset overflowing, returning unknown\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("MemRegion")) { llvm::dbgs() << "MemRegion::getAsArrayOffset: "
<< "offset overflowing, returning unknown\n"; } } while
(false)
;
1382
1383 return nullptr;
1384 }
1385 }
1386
1387 // Go to the next ElementRegion (if any).
1388 ER = dyn_cast<ElementRegion>(superR);
1389 continue;
1390 }
1391
1392 return nullptr;
1393 }
1394
1395 assert(superR && "super region cannot be NULL")(static_cast <bool> (superR && "super region cannot be NULL"
) ? void (0) : __assert_fail ("superR && \"super region cannot be NULL\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1395, __extension__ __PRETTY_FUNCTION__))
;
1396 return RegionRawOffset(superR, CharUnits::fromQuantity(offset));
1397}
1398
1399/// Returns true if \p Base is an immediate base class of \p Child
1400static bool isImmediateBase(const CXXRecordDecl *Child,
1401 const CXXRecordDecl *Base) {
1402 assert(Child && "Child must not be null")(static_cast <bool> (Child && "Child must not be null"
) ? void (0) : __assert_fail ("Child && \"Child must not be null\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1402, __extension__ __PRETTY_FUNCTION__))
;
1403 // Note that we do NOT canonicalize the base class here, because
1404 // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1405 // so be it; at least we won't crash.
1406 for (const auto &I : Child->bases()) {
1407 if (I.getType()->getAsCXXRecordDecl() == Base)
1408 return true;
1409 }
1410
1411 return false;
1412}
1413
1414static RegionOffset calculateOffset(const MemRegion *R) {
1415 const MemRegion *SymbolicOffsetBase = nullptr;
1416 int64_t Offset = 0;
1417
1418 while (true) {
1419 switch (R->getKind()) {
1420 case MemRegion::CodeSpaceRegionKind:
1421 case MemRegion::StackLocalsSpaceRegionKind:
1422 case MemRegion::StackArgumentsSpaceRegionKind:
1423 case MemRegion::HeapSpaceRegionKind:
1424 case MemRegion::UnknownSpaceRegionKind:
1425 case MemRegion::StaticGlobalSpaceRegionKind:
1426 case MemRegion::GlobalInternalSpaceRegionKind:
1427 case MemRegion::GlobalSystemSpaceRegionKind:
1428 case MemRegion::GlobalImmutableSpaceRegionKind:
1429 // Stores can bind directly to a region space to set a default value.
1430 assert(Offset == 0 && !SymbolicOffsetBase)(static_cast <bool> (Offset == 0 && !SymbolicOffsetBase
) ? void (0) : __assert_fail ("Offset == 0 && !SymbolicOffsetBase"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1430, __extension__ __PRETTY_FUNCTION__))
;
1431 goto Finish;
1432
1433 case MemRegion::FunctionCodeRegionKind:
1434 case MemRegion::BlockCodeRegionKind:
1435 case MemRegion::BlockDataRegionKind:
1436 // These will never have bindings, but may end up having values requested
1437 // if the user does some strange casting.
1438 if (Offset != 0)
1439 SymbolicOffsetBase = R;
1440 goto Finish;
1441
1442 case MemRegion::SymbolicRegionKind:
1443 case MemRegion::AllocaRegionKind:
1444 case MemRegion::CompoundLiteralRegionKind:
1445 case MemRegion::CXXThisRegionKind:
1446 case MemRegion::StringRegionKind:
1447 case MemRegion::ObjCStringRegionKind:
1448 case MemRegion::NonParamVarRegionKind:
1449 case MemRegion::ParamVarRegionKind:
1450 case MemRegion::CXXTempObjectRegionKind:
1451 // Usual base regions.
1452 goto Finish;
1453
1454 case MemRegion::ObjCIvarRegionKind:
1455 // This is a little strange, but it's a compromise between
1456 // ObjCIvarRegions having unknown compile-time offsets (when using the
1457 // non-fragile runtime) and yet still being distinct, non-overlapping
1458 // regions. Thus we treat them as "like" base regions for the purposes
1459 // of computing offsets.
1460 goto Finish;
1461
1462 case MemRegion::CXXBaseObjectRegionKind: {
1463 const auto *BOR = cast<CXXBaseObjectRegion>(R);
1464 R = BOR->getSuperRegion();
1465
1466 QualType Ty;
1467 bool RootIsSymbolic = false;
1468 if (const auto *TVR = dyn_cast<TypedValueRegion>(R)) {
1469 Ty = TVR->getDesugaredValueType(R->getContext());
1470 } else if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
1471 // If our base region is symbolic, we don't know what type it really is.
1472 // Pretend the type of the symbol is the true dynamic type.
1473 // (This will at least be self-consistent for the life of the symbol.)
1474 Ty = SR->getSymbol()->getType()->getPointeeType();
1475 RootIsSymbolic = true;
1476 }
1477
1478 const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1479 if (!Child) {
1480 // We cannot compute the offset of the base class.
1481 SymbolicOffsetBase = R;
1482 } else {
1483 if (RootIsSymbolic) {
1484 // Base layers on symbolic regions may not be type-correct.
1485 // Double-check the inheritance here, and revert to a symbolic offset
1486 // if it's invalid (e.g. due to a reinterpret_cast).
1487 if (BOR->isVirtual()) {
1488 if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1489 SymbolicOffsetBase = R;
1490 } else {
1491 if (!isImmediateBase(Child, BOR->getDecl()))
1492 SymbolicOffsetBase = R;
1493 }
1494 }
1495 }
1496
1497 // Don't bother calculating precise offsets if we already have a
1498 // symbolic offset somewhere in the chain.
1499 if (SymbolicOffsetBase)
1500 continue;
1501
1502 CharUnits BaseOffset;
1503 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(Child);
1504 if (BOR->isVirtual())
1505 BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1506 else
1507 BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1508
1509 // The base offset is in chars, not in bits.
1510 Offset += BaseOffset.getQuantity() * R->getContext().getCharWidth();
1511 break;
1512 }
1513
1514 case MemRegion::CXXDerivedObjectRegionKind: {
1515 // TODO: Store the base type in the CXXDerivedObjectRegion and use it.
1516 goto Finish;
1517 }
1518
1519 case MemRegion::ElementRegionKind: {
1520 const auto *ER = cast<ElementRegion>(R);
1521 R = ER->getSuperRegion();
1522
1523 QualType EleTy = ER->getValueType();
1524 if (EleTy->isIncompleteType()) {
1525 // We cannot compute the offset of the base class.
1526 SymbolicOffsetBase = R;
1527 continue;
1528 }
1529
1530 SVal Index = ER->getIndex();
1531 if (Optional<nonloc::ConcreteInt> CI =
1532 Index.getAs<nonloc::ConcreteInt>()) {
1533 // Don't bother calculating precise offsets if we already have a
1534 // symbolic offset somewhere in the chain.
1535 if (SymbolicOffsetBase)
1536 continue;
1537
1538 int64_t i = CI->getValue().getSExtValue();
1539 // This type size is in bits.
1540 Offset += i * R->getContext().getTypeSize(EleTy);
1541 } else {
1542 // We cannot compute offset for non-concrete index.
1543 SymbolicOffsetBase = R;
1544 }
1545 break;
1546 }
1547 case MemRegion::FieldRegionKind: {
1548 const auto *FR = cast<FieldRegion>(R);
1549 R = FR->getSuperRegion();
1550 assert(R)(static_cast <bool> (R) ? void (0) : __assert_fail ("R"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1550, __extension__ __PRETTY_FUNCTION__))
;
1551
1552 const RecordDecl *RD = FR->getDecl()->getParent();
1553 if (RD->isUnion() || !RD->isCompleteDefinition()) {
1554 // We cannot compute offset for incomplete type.
1555 // For unions, we could treat everything as offset 0, but we'd rather
1556 // treat each field as a symbolic offset so they aren't stored on top
1557 // of each other, since we depend on things in typed regions actually
1558 // matching their types.
1559 SymbolicOffsetBase = R;
1560 }
1561
1562 // Don't bother calculating precise offsets if we already have a
1563 // symbolic offset somewhere in the chain.
1564 if (SymbolicOffsetBase)
1565 continue;
1566
1567 // Get the field number.
1568 unsigned idx = 0;
1569 for (RecordDecl::field_iterator FI = RD->field_begin(),
1570 FE = RD->field_end(); FI != FE; ++FI, ++idx) {
1571 if (FR->getDecl() == *FI)
1572 break;
1573 }
1574 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(RD);
1575 // This is offset in bits.
1576 Offset += Layout.getFieldOffset(idx);
1577 break;
1578 }
1579 }
1580 }
1581
1582 Finish:
1583 if (SymbolicOffsetBase)
1584 return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1585 return RegionOffset(R, Offset);
1586}
1587
1588RegionOffset MemRegion::getAsOffset() const {
1589 if (!cachedOffset)
1590 cachedOffset = calculateOffset(this);
1591 return *cachedOffset;
1592}
1593
1594//===----------------------------------------------------------------------===//
1595// BlockDataRegion
1596//===----------------------------------------------------------------------===//
1597
1598std::pair<const VarRegion *, const VarRegion *>
1599BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1600 MemRegionManager &MemMgr = getMemRegionManager();
9
Value assigned to field 'LC'
1601 const VarRegion *VR = nullptr;
1602 const VarRegion *OriginalVR = nullptr;
1603
1604 if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) {
10
Calling 'Decl::hasAttr'
13
Returning from 'Decl::hasAttr'
14
Calling 'VarDecl::hasLocalStorage'
20
Returning from 'VarDecl::hasLocalStorage'
21
Taking false branch
1605 VR = MemMgr.getNonParamVarRegion(VD, this);
1606 OriginalVR = MemMgr.getVarRegion(VD, LC);
1607 }
1608 else {
1609 if (LC) {
22
Assuming field 'LC' is null
23
Taking false branch
1610 VR = MemMgr.getVarRegion(VD, LC);
1611 OriginalVR = VR;
1612 }
1613 else {
1614 VR = MemMgr.getNonParamVarRegion(VD, MemMgr.getUnknownRegion());
1615 OriginalVR = MemMgr.getVarRegion(VD, LC);
24
Passing null pointer value via 2nd parameter 'LC'
25
Calling 'MemRegionManager::getVarRegion'
1616 }
1617 }
1618 return std::make_pair(VR, OriginalVR);
1619}
1620
1621void BlockDataRegion::LazyInitializeReferencedVars() {
1622 if (ReferencedVars)
3
Assuming field 'ReferencedVars' is null
4
Taking false branch
1623 return;
1624
1625 AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1626 const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
1627 auto NumBlockVars =
1628 std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
1629
1630 if (NumBlockVars == 0) {
5
Assuming 'NumBlockVars' is not equal to 0
6
Taking false branch
1631 ReferencedVars = (void*) 0x1;
1632 return;
1633 }
1634
1635 MemRegionManager &MemMgr = getMemRegionManager();
1636 llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1637 BumpVectorContext BC(A);
1638
1639 using VarVec = BumpVector<const MemRegion *>;
1640
1641 auto *BV = A.Allocate<VarVec>();
1642 new (BV) VarVec(BC, NumBlockVars);
1643 auto *BVOriginal = A.Allocate<VarVec>();
1644 new (BVOriginal) VarVec(BC, NumBlockVars);
1645
1646 for (const auto *VD : ReferencedBlockVars) {
7
Assuming '__begin1' is not equal to '__end1'
1647 const VarRegion *VR = nullptr;
1648 const VarRegion *OriginalVR = nullptr;
1649 std::tie(VR, OriginalVR) = getCaptureRegions(VD);
8
Calling 'BlockDataRegion::getCaptureRegions'
1650 assert(VR)(static_cast <bool> (VR) ? void (0) : __assert_fail ("VR"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1650, __extension__ __PRETTY_FUNCTION__))
;
1651 assert(OriginalVR)(static_cast <bool> (OriginalVR) ? void (0) : __assert_fail
("OriginalVR", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1651, __extension__ __PRETTY_FUNCTION__))
;
1652 BV->push_back(VR, BC);
1653 BVOriginal->push_back(OriginalVR, BC);
1654 }
1655
1656 ReferencedVars = BV;
1657 OriginalVars = BVOriginal;
1658}
1659
1660BlockDataRegion::referenced_vars_iterator
1661BlockDataRegion::referenced_vars_begin() const {
1662 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
2
Calling 'BlockDataRegion::LazyInitializeReferencedVars'
1663
1664 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1665
1666 if (Vec == (void*) 0x1)
1667 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1668
1669 auto *VecOriginal =
1670 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1671
1672 return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1673 VecOriginal->begin());
1674}
1675
1676BlockDataRegion::referenced_vars_iterator
1677BlockDataRegion::referenced_vars_end() const {
1678 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1679
1680 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1681
1682 if (Vec == (void*) 0x1)
1683 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1684
1685 auto *VecOriginal =
1686 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1687
1688 return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1689 VecOriginal->end());
1690}
1691
1692const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1693 for (referenced_vars_iterator I = referenced_vars_begin(),
1
Calling 'BlockDataRegion::referenced_vars_begin'
1694 E = referenced_vars_end();
1695 I != E; ++I) {
1696 if (I.getCapturedRegion() == R)
1697 return I.getOriginalRegion();
1698 }
1699 return nullptr;
1700}
1701
1702//===----------------------------------------------------------------------===//
1703// RegionAndSymbolInvalidationTraits
1704//===----------------------------------------------------------------------===//
1705
1706void RegionAndSymbolInvalidationTraits::setTrait(SymbolRef Sym,
1707 InvalidationKinds IK) {
1708 SymTraitsMap[Sym] |= IK;
1709}
1710
1711void RegionAndSymbolInvalidationTraits::setTrait(const MemRegion *MR,
1712 InvalidationKinds IK) {
1713 assert(MR)(static_cast <bool> (MR) ? void (0) : __assert_fail ("MR"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1713, __extension__ __PRETTY_FUNCTION__))
;
1714 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1715 setTrait(SR->getSymbol(), IK);
1716 else
1717 MRTraitsMap[MR] |= IK;
1718}
1719
1720bool RegionAndSymbolInvalidationTraits::hasTrait(SymbolRef Sym,
1721 InvalidationKinds IK) const {
1722 const_symbol_iterator I = SymTraitsMap.find(Sym);
1723 if (I != SymTraitsMap.end())
1724 return I->second & IK;
1725
1726 return false;
1727}
1728
1729bool RegionAndSymbolInvalidationTraits::hasTrait(const MemRegion *MR,
1730 InvalidationKinds IK) const {
1731 if (!MR)
1732 return false;
1733
1734 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1735 return hasTrait(SR->getSymbol(), IK);
1736
1737 const_region_iterator I = MRTraitsMap.find(MR);
1738 if (I != MRTraitsMap.end())
1739 return I->second & IK;
1740
1741 return false;
1742}

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base 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 and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TemplateParameterList;
70class TranslationUnitDecl;
71class UsingDirectiveDecl;
72
73/// Captures the result of checking the availability of a
74/// declaration.
75enum AvailabilityResult {
76 AR_Available = 0,
77 AR_NotYetIntroduced,
78 AR_Deprecated,
79 AR_Unavailable
80};
81
82/// Decl - This represents one declaration (or definition), e.g. a variable,
83/// typedef, function, struct, etc.
84///
85/// Note: There are objects tacked on before the *beginning* of Decl
86/// (and its subclasses) in its Decl::operator new(). Proper alignment
87/// of all subclasses (not requiring more than the alignment of Decl) is
88/// asserted in DeclBase.cpp.
89class alignas(8) Decl {
90public:
91 /// Lists the kind of concrete classes of Decl.
92 enum Kind {
93#define DECL(DERIVED, BASE) DERIVED,
94#define ABSTRACT_DECL(DECL)
95#define DECL_RANGE(BASE, START, END) \
96 first##BASE = START, last##BASE = END,
97#define LAST_DECL_RANGE(BASE, START, END) \
98 first##BASE = START, last##BASE = END
99#include "clang/AST/DeclNodes.inc"
100 };
101
102 /// A placeholder type used to construct an empty shell of a
103 /// decl-derived type that will be filled in later (e.g., by some
104 /// deserialization method).
105 struct EmptyShell {};
106
107 /// IdentifierNamespace - The different namespaces in which
108 /// declarations may appear. According to C99 6.2.3, there are
109 /// four namespaces, labels, tags, members and ordinary
110 /// identifiers. C++ describes lookup completely differently:
111 /// certain lookups merely "ignore" certain kinds of declarations,
112 /// usually based on whether the declaration is of a type, etc.
113 ///
114 /// These are meant as bitmasks, so that searches in
115 /// C++ can look into the "tag" namespace during ordinary lookup.
116 ///
117 /// Decl currently provides 15 bits of IDNS bits.
118 enum IdentifierNamespace {
119 /// Labels, declared with 'x:' and referenced with 'goto x'.
120 IDNS_Label = 0x0001,
121
122 /// Tags, declared with 'struct foo;' and referenced with
123 /// 'struct foo'. All tags are also types. This is what
124 /// elaborated-type-specifiers look for in C.
125 /// This also contains names that conflict with tags in the
126 /// same scope but that are otherwise ordinary names (non-type
127 /// template parameters and indirect field declarations).
128 IDNS_Tag = 0x0002,
129
130 /// Types, declared with 'struct foo', typedefs, etc.
131 /// This is what elaborated-type-specifiers look for in C++,
132 /// but note that it's ill-formed to find a non-tag.
133 IDNS_Type = 0x0004,
134
135 /// Members, declared with object declarations within tag
136 /// definitions. In C, these can only be found by "qualified"
137 /// lookup in member expressions. In C++, they're found by
138 /// normal lookup.
139 IDNS_Member = 0x0008,
140
141 /// Namespaces, declared with 'namespace foo {}'.
142 /// Lookup for nested-name-specifiers find these.
143 IDNS_Namespace = 0x0010,
144
145 /// Ordinary names. In C, everything that's not a label, tag,
146 /// member, or function-local extern ends up here.
147 IDNS_Ordinary = 0x0020,
148
149 /// Objective C \@protocol.
150 IDNS_ObjCProtocol = 0x0040,
151
152 /// This declaration is a friend function. A friend function
153 /// declaration is always in this namespace but may also be in
154 /// IDNS_Ordinary if it was previously declared.
155 IDNS_OrdinaryFriend = 0x0080,
156
157 /// This declaration is a friend class. A friend class
158 /// declaration is always in this namespace but may also be in
159 /// IDNS_Tag|IDNS_Type if it was previously declared.
160 IDNS_TagFriend = 0x0100,
161
162 /// This declaration is a using declaration. A using declaration
163 /// *introduces* a number of other declarations into the current
164 /// scope, and those declarations use the IDNS of their targets,
165 /// but the actual using declarations go in this namespace.
166 IDNS_Using = 0x0200,
167
168 /// This declaration is a C++ operator declared in a non-class
169 /// context. All such operators are also in IDNS_Ordinary.
170 /// C++ lexical operator lookup looks for these.
171 IDNS_NonMemberOperator = 0x0400,
172
173 /// This declaration is a function-local extern declaration of a
174 /// variable or function. This may also be IDNS_Ordinary if it
175 /// has been declared outside any function. These act mostly like
176 /// invisible friend declarations, but are also visible to unqualified
177 /// lookup within the scope of the declaring function.
178 IDNS_LocalExtern = 0x0800,
179
180 /// This declaration is an OpenMP user defined reduction construction.
181 IDNS_OMPReduction = 0x1000,
182
183 /// This declaration is an OpenMP user defined mapper.
184 IDNS_OMPMapper = 0x2000,
185 };
186
187 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
188 /// parameter types in method declarations. Other than remembering
189 /// them and mangling them into the method's signature string, these
190 /// are ignored by the compiler; they are consumed by certain
191 /// remote-messaging frameworks.
192 ///
193 /// in, inout, and out are mutually exclusive and apply only to
194 /// method parameters. bycopy and byref are mutually exclusive and
195 /// apply only to method parameters (?). oneway applies only to
196 /// results. All of these expect their corresponding parameter to
197 /// have a particular type. None of this is currently enforced by
198 /// clang.
199 ///
200 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
201 enum ObjCDeclQualifier {
202 OBJC_TQ_None = 0x0,
203 OBJC_TQ_In = 0x1,
204 OBJC_TQ_Inout = 0x2,
205 OBJC_TQ_Out = 0x4,
206 OBJC_TQ_Bycopy = 0x8,
207 OBJC_TQ_Byref = 0x10,
208 OBJC_TQ_Oneway = 0x20,
209
210 /// The nullability qualifier is set when the nullability of the
211 /// result or parameter was expressed via a context-sensitive
212 /// keyword.
213 OBJC_TQ_CSNullability = 0x40
214 };
215
216 /// The kind of ownership a declaration has, for visibility purposes.
217 /// This enumeration is designed such that higher values represent higher
218 /// levels of name hiding.
219 enum class ModuleOwnershipKind : unsigned {
220 /// This declaration is not owned by a module.
221 Unowned,
222
223 /// This declaration has an owning module, but is globally visible
224 /// (typically because its owning module is visible and we know that
225 /// modules cannot later become hidden in this compilation).
226 /// After serialization and deserialization, this will be converted
227 /// to VisibleWhenImported.
228 Visible,
229
230 /// This declaration has an owning module, and is visible when that
231 /// module is imported.
232 VisibleWhenImported,
233
234 /// This declaration has an owning module, but is only visible to
235 /// lookups that occur within that module.
236 ModulePrivate
237 };
238
239protected:
240 /// The next declaration within the same lexical
241 /// DeclContext. These pointers form the linked list that is
242 /// traversed via DeclContext's decls_begin()/decls_end().
243 ///
244 /// The extra two bits are used for the ModuleOwnershipKind.
245 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
246
247private:
248 friend class DeclContext;
249
250 struct MultipleDC {
251 DeclContext *SemanticDC;
252 DeclContext *LexicalDC;
253 };
254
255 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
256 /// For declarations that don't contain C++ scope specifiers, it contains
257 /// the DeclContext where the Decl was declared.
258 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
259 /// with the context where it semantically belongs (SemanticDC) and the
260 /// context where it was lexically declared (LexicalDC).
261 /// e.g.:
262 ///
263 /// namespace A {
264 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
265 /// }
266 /// void A::f(); // SemanticDC == namespace 'A'
267 /// // LexicalDC == global namespace
268 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
269
270 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
271 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
272
273 MultipleDC *getMultipleDC() const {
274 return DeclCtx.get<MultipleDC*>();
275 }
276
277 DeclContext *getSemanticDC() const {
278 return DeclCtx.get<DeclContext*>();
279 }
280
281 /// Loc - The location of this decl.
282 SourceLocation Loc;
283
284 /// DeclKind - This indicates which class this is.
285 unsigned DeclKind : 7;
286
287 /// InvalidDecl - This indicates a semantic error occurred.
288 unsigned InvalidDecl : 1;
289
290 /// HasAttrs - This indicates whether the decl has attributes or not.
291 unsigned HasAttrs : 1;
292
293 /// Implicit - Whether this declaration was implicitly generated by
294 /// the implementation rather than explicitly written by the user.
295 unsigned Implicit : 1;
296
297 /// Whether this declaration was "used", meaning that a definition is
298 /// required.
299 unsigned Used : 1;
300
301 /// Whether this declaration was "referenced".
302 /// The difference with 'Used' is whether the reference appears in a
303 /// evaluated context or not, e.g. functions used in uninstantiated templates
304 /// are regarded as "referenced" but not "used".
305 unsigned Referenced : 1;
306
307 /// Whether this declaration is a top-level declaration (function,
308 /// global variable, etc.) that is lexically inside an objc container
309 /// definition.
310 unsigned TopLevelDeclInObjCContainer : 1;
311
312 /// Whether statistic collection is enabled.
313 static bool StatisticsEnabled;
314
315protected:
316 friend class ASTDeclReader;
317 friend class ASTDeclWriter;
318 friend class ASTNodeImporter;
319 friend class ASTReader;
320 friend class CXXClassMemberWrapper;
321 friend class LinkageComputer;
322 template<typename decl_type> friend class Redeclarable;
323
324 /// Access - Used by C++ decls for the access specifier.
325 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
326 unsigned Access : 2;
327
328 /// Whether this declaration was loaded from an AST file.
329 unsigned FromASTFile : 1;
330
331 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
332 unsigned IdentifierNamespace : 14;
333
334 /// If 0, we have not computed the linkage of this declaration.
335 /// Otherwise, it is the linkage + 1.
336 mutable unsigned CacheValidAndLinkage : 3;
337
338 /// Allocate memory for a deserialized declaration.
339 ///
340 /// This routine must be used to allocate memory for any declaration that is
341 /// deserialized from a module file.
342 ///
343 /// \param Size The size of the allocated object.
344 /// \param Ctx The context in which we will allocate memory.
345 /// \param ID The global ID of the deserialized declaration.
346 /// \param Extra The amount of extra space to allocate after the object.
347 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
348 std::size_t Extra = 0);
349
350 /// Allocate memory for a non-deserialized declaration.
351 void *operator new(std::size_t Size, const ASTContext &Ctx,
352 DeclContext *Parent, std::size_t Extra = 0);
353
354private:
355 bool AccessDeclContextSanity() const;
356
357 /// Get the module ownership kind to use for a local lexical child of \p DC,
358 /// which may be either a local or (rarely) an imported declaration.
359 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
360 if (DC) {
361 auto *D = cast<Decl>(DC);
362 auto MOK = D->getModuleOwnershipKind();
363 if (MOK != ModuleOwnershipKind::Unowned &&
364 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
365 return MOK;
366 // If D is not local and we have no local module storage, then we don't
367 // need to track module ownership at all.
368 }
369 return ModuleOwnershipKind::Unowned;
370 }
371
372public:
373 Decl() = delete;
374 Decl(const Decl&) = delete;
375 Decl(Decl &&) = delete;
376 Decl &operator=(const Decl&) = delete;
377 Decl &operator=(Decl&&) = delete;
378
379protected:
380 Decl(Kind DK, DeclContext *DC, SourceLocation L)
381 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
382 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
383 Implicit(false), Used(false), Referenced(false),
384 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
385 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
386 CacheValidAndLinkage(0) {
387 if (StatisticsEnabled) add(DK);
388 }
389
390 Decl(Kind DK, EmptyShell Empty)
391 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
392 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
393 Access(AS_none), FromASTFile(0),
394 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
395 CacheValidAndLinkage(0) {
396 if (StatisticsEnabled) add(DK);
397 }
398
399 virtual ~Decl();
400
401 /// Update a potentially out-of-date declaration.
402 void updateOutOfDate(IdentifierInfo &II) const;
403
404 Linkage getCachedLinkage() const {
405 return Linkage(CacheValidAndLinkage - 1);
406 }
407
408 void setCachedLinkage(Linkage L) const {
409 CacheValidAndLinkage = L + 1;
410 }
411
412 bool hasCachedLinkage() const {
413 return CacheValidAndLinkage;
414 }
415
416public:
417 /// Source range that this declaration covers.
418 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
419 return SourceRange(getLocation(), getLocation());
420 }
421
422 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
423 return getSourceRange().getBegin();
424 }
425
426 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
427 return getSourceRange().getEnd();
428 }
429
430 SourceLocation getLocation() const { return Loc; }
431 void setLocation(SourceLocation L) { Loc = L; }
432
433 Kind getKind() const { return static_cast<Kind>(DeclKind); }
434 const char *getDeclKindName() const;
435
436 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
437 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
438
439 DeclContext *getDeclContext() {
440 if (isInSemaDC())
441 return getSemanticDC();
442 return getMultipleDC()->SemanticDC;
443 }
444 const DeclContext *getDeclContext() const {
445 return const_cast<Decl*>(this)->getDeclContext();
446 }
447
448 /// Find the innermost non-closure ancestor of this declaration,
449 /// walking up through blocks, lambdas, etc. If that ancestor is
450 /// not a code context (!isFunctionOrMethod()), returns null.
451 ///
452 /// A declaration may be its own non-closure context.
453 Decl *getNonClosureContext();
454 const Decl *getNonClosureContext() const {
455 return const_cast<Decl*>(this)->getNonClosureContext();
456 }
457
458 TranslationUnitDecl *getTranslationUnitDecl();
459 const TranslationUnitDecl *getTranslationUnitDecl() const {
460 return const_cast<Decl*>(this)->getTranslationUnitDecl();
461 }
462
463 bool isInAnonymousNamespace() const;
464
465 bool isInStdNamespace() const;
466
467 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
468
469 /// Helper to get the language options from the ASTContext.
470 /// Defined out of line to avoid depending on ASTContext.h.
471 const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__));
472
473 void setAccess(AccessSpecifier AS) {
474 Access = AS;
475 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 475, __extension__ __PRETTY_FUNCTION__))
;
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 479, __extension__ __PRETTY_FUNCTION__))
;
480 return AccessSpecifier(Access);
481 }
482
483 /// Retrieve the access specifier for this declaration, even though
484 /// it may not yet have been properly set.
485 AccessSpecifier getAccessUnsafe() const {
486 return AccessSpecifier(Access);
487 }
488
489 bool hasAttrs() const { return HasAttrs; }
490
491 void setAttrs(const AttrVec& Attrs) {
492 return setAttrsImpl(Attrs, getASTContext());
493 }
494
495 AttrVec &getAttrs() {
496 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
497 }
498
499 const AttrVec &getAttrs() const;
500 void dropAttrs();
501 void addAttr(Attr *A);
502
503 using attr_iterator = AttrVec::const_iterator;
504 using attr_range = llvm::iterator_range<attr_iterator>;
505
506 attr_range attrs() const {
507 return attr_range(attr_begin(), attr_end());
508 }
509
510 attr_iterator attr_begin() const {
511 return hasAttrs() ? getAttrs().begin() : nullptr;
512 }
513 attr_iterator attr_end() const {
514 return hasAttrs() ? getAttrs().end() : nullptr;
515 }
516
517 template <typename T>
518 void dropAttr() {
519 if (!HasAttrs) return;
520
521 AttrVec &Vec = getAttrs();
522 llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
523
524 if (Vec.empty())
525 HasAttrs = false;
526 }
527
528 template <typename T>
529 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
530 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_begin() const {
535 return specific_attr_iterator<T>(attr_begin());
536 }
537
538 template <typename T>
539 specific_attr_iterator<T> specific_attr_end() const {
540 return specific_attr_iterator<T>(attr_end());
541 }
542
543 template<typename T> T *getAttr() const {
544 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
545 }
546
547 template<typename T> bool hasAttr() const {
548 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
11
Assuming the condition is false
12
Returning zero, which participates in a condition later
549 }
550
551 /// getMaxAlignment - return the maximum alignment specified by attributes
552 /// on this decl, 0 if there are none.
553 unsigned getMaxAlignment() const;
554
555 /// setInvalidDecl - Indicates the Decl had a semantic error. This
556 /// allows for graceful error recovery.
557 void setInvalidDecl(bool Invalid = true);
558 bool isInvalidDecl() const { return (bool) InvalidDecl; }
559
560 /// isImplicit - Indicates whether the declaration was implicitly
561 /// generated by the implementation. If false, this declaration
562 /// was written explicitly in the source code.
563 bool isImplicit() const { return Implicit; }
564 void setImplicit(bool I = true) { Implicit = I; }
565
566 /// Whether *any* (re-)declaration of the entity was used, meaning that
567 /// a definition is required.
568 ///
569 /// \param CheckUsedAttr When true, also consider the "used" attribute
570 /// (in addition to the "used" bit set by \c setUsed()) when determining
571 /// whether the function is used.
572 bool isUsed(bool CheckUsedAttr = true) const;
573
574 /// Set whether the declaration is used, in the sense of odr-use.
575 ///
576 /// This should only be used immediately after creating a declaration.
577 /// It intentionally doesn't notify any listeners.
578 void setIsUsed() { getCanonicalDecl()->Used = true; }
579
580 /// Mark the declaration used, in the sense of odr-use.
581 ///
582 /// This notifies any mutation listeners in addition to setting a bit
583 /// indicating the declaration is used.
584 void markUsed(ASTContext &C);
585
586 /// Whether any declaration of this entity was referenced.
587 bool isReferenced() const;
588
589 /// Whether this declaration was referenced. This should not be relied
590 /// upon for anything other than debugging.
591 bool isThisDeclarationReferenced() const { return Referenced; }
592
593 void setReferenced(bool R = true) { Referenced = R; }
594
595 /// Whether this declaration is a top-level declaration (function,
596 /// global variable, etc.) that is lexically inside an objc container
597 /// definition.
598 bool isTopLevelDeclInObjCContainer() const {
599 return TopLevelDeclInObjCContainer;
600 }
601
602 void setTopLevelDeclInObjCContainer(bool V = true) {
603 TopLevelDeclInObjCContainer = V;
604 }
605
606 /// Looks on this and related declarations for an applicable
607 /// external source symbol attribute.
608 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
609
610 /// Whether this declaration was marked as being private to the
611 /// module in which it was defined.
612 bool isModulePrivate() const {
613 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
614 }
615
616 /// Return true if this declaration has an attribute which acts as
617 /// definition of the entity, such as 'alias' or 'ifunc'.
618 bool hasDefiningAttr() const;
619
620 /// Return this declaration's defining attribute if it has one.
621 const Attr *getDefiningAttr() const;
622
623protected:
624 /// Specify that this declaration was marked as being private
625 /// to the module in which it was defined.
626 void setModulePrivate() {
627 // The module-private specifier has no effect on unowned declarations.
628 // FIXME: We should track this in some way for source fidelity.
629 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
630 return;
631 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
632 }
633
634public:
635 /// Set the FromASTFile flag. This indicates that this declaration
636 /// was deserialized and not parsed from source code and enables
637 /// features such as module ownership information.
638 void setFromASTFile() {
639 FromASTFile = true;
640 }
641
642 /// Set the owning module ID. This may only be called for
643 /// deserialized Decls.
644 void setOwningModuleID(unsigned ID) {
645 assert(isFromASTFile() && "Only works on a deserialized declaration")(static_cast <bool> (isFromASTFile() && "Only works on a deserialized declaration"
) ? void (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 645, __extension__ __PRETTY_FUNCTION__))
;
646 *((unsigned*)this - 2) = ID;
647 }
648
649public:
650 /// Determine the availability of the given declaration.
651 ///
652 /// This routine will determine the most restrictive availability of
653 /// the given declaration (e.g., preferring 'unavailable' to
654 /// 'deprecated').
655 ///
656 /// \param Message If non-NULL and the result is not \c
657 /// AR_Available, will be set to a (possibly empty) message
658 /// describing why the declaration has not been introduced, is
659 /// deprecated, or is unavailable.
660 ///
661 /// \param EnclosingVersion The version to compare with. If empty, assume the
662 /// deployment target version.
663 ///
664 /// \param RealizedPlatform If non-NULL and the availability result is found
665 /// in an available attribute it will set to the platform which is written in
666 /// the available attribute.
667 AvailabilityResult
668 getAvailability(std::string *Message = nullptr,
669 VersionTuple EnclosingVersion = VersionTuple(),
670 StringRef *RealizedPlatform = nullptr) const;
671
672 /// Retrieve the version of the target platform in which this
673 /// declaration was introduced.
674 ///
675 /// \returns An empty version tuple if this declaration has no 'introduced'
676 /// availability attributes, or the version tuple that's specified in the
677 /// attribute otherwise.
678 VersionTuple getVersionIntroduced() const;
679
680 /// Determine whether this declaration is marked 'deprecated'.
681 ///
682 /// \param Message If non-NULL and the declaration is deprecated,
683 /// this will be set to the message describing why the declaration
684 /// was deprecated (which may be empty).
685 bool isDeprecated(std::string *Message = nullptr) const {
686 return getAvailability(Message) == AR_Deprecated;
687 }
688
689 /// Determine whether this declaration is marked 'unavailable'.
690 ///
691 /// \param Message If non-NULL and the declaration is unavailable,
692 /// this will be set to the message describing why the declaration
693 /// was made unavailable (which may be empty).
694 bool isUnavailable(std::string *Message = nullptr) const {
695 return getAvailability(Message) == AR_Unavailable;
696 }
697
698 /// Determine whether this is a weak-imported symbol.
699 ///
700 /// Weak-imported symbols are typically marked with the
701 /// 'weak_import' attribute, but may also be marked with an
702 /// 'availability' attribute where we're targing a platform prior to
703 /// the introduction of this feature.
704 bool isWeakImported() const;
705
706 /// Determines whether this symbol can be weak-imported,
707 /// e.g., whether it would be well-formed to add the weak_import
708 /// attribute.
709 ///
710 /// \param IsDefinition Set to \c true to indicate that this
711 /// declaration cannot be weak-imported because it has a definition.
712 bool canBeWeakImported(bool &IsDefinition) const;
713
714 /// Determine whether this declaration came from an AST file (such as
715 /// a precompiled header or module) rather than having been parsed.
716 bool isFromASTFile() const { return FromASTFile; }
717
718 /// Retrieve the global declaration ID associated with this
719 /// declaration, which specifies where this Decl was loaded from.
720 unsigned getGlobalID() const {
721 if (isFromASTFile())
722 return *((const unsigned*)this - 1);
723 return 0;
724 }
725
726 /// Retrieve the global ID of the module that owns this particular
727 /// declaration.
728 unsigned getOwningModuleID() const {
729 if (isFromASTFile())
730 return *((const unsigned*)this - 2);
731 return 0;
732 }
733
734private:
735 Module *getOwningModuleSlow() const;
736
737protected:
738 bool hasLocalOwningModuleStorage() const;
739
740public:
741 /// Get the imported owning module, if this decl is from an imported
742 /// (non-local) module.
743 Module *getImportedOwningModule() const {
744 if (!isFromASTFile() || !hasOwningModule())
745 return nullptr;
746
747 return getOwningModuleSlow();
748 }
749
750 /// Get the local owning module, if known. Returns nullptr if owner is
751 /// not yet known or declaration is not from a module.
752 Module *getLocalOwningModule() const {
753 if (isFromASTFile() || !hasOwningModule())
754 return nullptr;
755
756 assert(hasLocalOwningModuleStorage() &&(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 757, __extension__ __PRETTY_FUNCTION__))
757 "owned local decl but no local module storage")(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 757, __extension__ __PRETTY_FUNCTION__))
;
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
762 hasLocalOwningModuleStorage() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
763 "should not have a cached owning module")(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 763, __extension__ __PRETTY_FUNCTION__))
;
764 reinterpret_cast<Module **>(this)[-1] = M;
765 }
766
767 /// Is this declaration owned by some module?
768 bool hasOwningModule() const {
769 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
770 }
771
772 /// Get the module that owns this declaration (for visibility purposes).
773 Module *getOwningModule() const {
774 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
775 }
776
777 /// Get the module that owns this declaration for linkage purposes.
778 /// There only ever is such a module under the C++ Modules TS.
779 ///
780 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
781 /// all declarations in a global module fragment are unowned.
782 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
783
784 /// Determine whether this declaration is definitely visible to name lookup,
785 /// independent of whether the owning module is visible.
786 /// Note: The declaration may be visible even if this returns \c false if the
787 /// owning module is visible within the query context. This is a low-level
788 /// helper function; most code should be calling Sema::isVisible() instead.
789 bool isUnconditionallyVisible() const {
790 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
791 }
792
793 /// Set that this declaration is globally visible, even if it came from a
794 /// module that is not visible.
795 void setVisibleDespiteOwningModule() {
796 if (!isUnconditionallyVisible())
797 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
798 }
799
800 /// Get the kind of module ownership for this declaration.
801 ModuleOwnershipKind getModuleOwnershipKind() const {
802 return NextInContextAndBits.getInt();
803 }
804
805 /// Set whether this declaration is hidden from name lookup.
806 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
807 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
809 !hasLocalOwningModuleStorage()) &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
810 "no storage available for owning module for this declaration")(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 810, __extension__ __PRETTY_FUNCTION__))
;
811 NextInContextAndBits.setInt(MOK);
812 }
813
814 unsigned getIdentifierNamespace() const {
815 return IdentifierNamespace;
816 }
817
818 bool isInIdentifierNamespace(unsigned NS) const {
819 return getIdentifierNamespace() & NS;
820 }
821
822 static unsigned getIdentifierNamespaceForKind(Kind DK);
823
824 bool hasTagIdentifierNamespace() const {
825 return isTagIdentifierNamespace(getIdentifierNamespace());
826 }
827
828 static bool isTagIdentifierNamespace(unsigned NS) {
829 // TagDecls have Tag and Type set and may also have TagFriend.
830 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
831 }
832
833 /// getLexicalDeclContext - The declaration context where this Decl was
834 /// lexically declared (LexicalDC). May be different from
835 /// getDeclContext() (SemanticDC).
836 /// e.g.:
837 ///
838 /// namespace A {
839 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
840 /// }
841 /// void A::f(); // SemanticDC == namespace 'A'
842 /// // LexicalDC == global namespace
843 DeclContext *getLexicalDeclContext() {
844 if (isInSemaDC())
845 return getSemanticDC();
846 return getMultipleDC()->LexicalDC;
847 }
848 const DeclContext *getLexicalDeclContext() const {
849 return const_cast<Decl*>(this)->getLexicalDeclContext();
850 }
851
852 /// Determine whether this declaration is declared out of line (outside its
853 /// semantic context).
854 virtual bool isOutOfLine() const;
855
856 /// setDeclContext - Set both the semantic and lexical DeclContext
857 /// to DC.
858 void setDeclContext(DeclContext *DC);
859
860 void setLexicalDeclContext(DeclContext *DC);
861
862 /// Determine whether this declaration is a templated entity (whether it is
863 // within the scope of a template parameter).
864 bool isTemplated() const;
865
866 /// Determine the number of levels of template parameter surrounding this
867 /// declaration.
868 unsigned getTemplateDepth() const;
869
870 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
871 /// scoped decl is defined outside the current function or method. This is
872 /// roughly global variables and functions, but also handles enums (which
873 /// could be defined inside or outside a function etc).
874 bool isDefinedOutsideFunctionOrMethod() const {
875 return getParentFunctionOrMethod() == nullptr;
876 }
877
878 /// Determine whether a substitution into this declaration would occur as
879 /// part of a substitution into a dependent local scope. Such a substitution
880 /// transitively substitutes into all constructs nested within this
881 /// declaration.
882 ///
883 /// This recognizes non-defining declarations as well as members of local
884 /// classes and lambdas:
885 /// \code
886 /// template<typename T> void foo() { void bar(); }
887 /// template<typename T> void foo2() { class ABC { void bar(); }; }
888 /// template<typename T> inline int x = [](){ return 0; }();
889 /// \endcode
890 bool isInLocalScopeForInstantiation() const;
891
892 /// If this decl is defined inside a function/method/block it returns
893 /// the corresponding DeclContext, otherwise it returns null.
894 const DeclContext *getParentFunctionOrMethod() const;
895 DeclContext *getParentFunctionOrMethod() {
896 return const_cast<DeclContext*>(
897 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
898 }
899
900 /// Retrieves the "canonical" declaration of the given declaration.
901 virtual Decl *getCanonicalDecl() { return this; }
902 const Decl *getCanonicalDecl() const {
903 return const_cast<Decl*>(this)->getCanonicalDecl();
904 }
905
906 /// Whether this particular Decl is a canonical one.
907 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
908
909protected:
910 /// Returns the next redeclaration or itself if this is the only decl.
911 ///
912 /// Decl subclasses that can be redeclared should override this method so that
913 /// Decl::redecl_iterator can iterate over them.
914 virtual Decl *getNextRedeclarationImpl() { return this; }
915
916 /// Implementation of getPreviousDecl(), to be overridden by any
917 /// subclass that has a redeclaration chain.
918 virtual Decl *getPreviousDeclImpl() { return nullptr; }
919
920 /// Implementation of getMostRecentDecl(), to be overridden by any
921 /// subclass that has a redeclaration chain.
922 virtual Decl *getMostRecentDeclImpl() { return this; }
923
924public:
925 /// Iterates through all the redeclarations of the same decl.
926 class redecl_iterator {
927 /// Current - The current declaration.
928 Decl *Current = nullptr;
929 Decl *Starter;
930
931 public:
932 using value_type = Decl *;
933 using reference = const value_type &;
934 using pointer = const value_type *;
935 using iterator_category = std::forward_iterator_tag;
936 using difference_type = std::ptrdiff_t;
937
938 redecl_iterator() = default;
939 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
940
941 reference operator*() const { return Current; }
942 value_type operator->() const { return Current; }
943
944 redecl_iterator& operator++() {
945 assert(Current && "Advancing while iterator has reached end")(static_cast <bool> (Current && "Advancing while iterator has reached end"
) ? void (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 945, __extension__ __PRETTY_FUNCTION__))
;
946 // Get either previous decl or latest decl.
947 Decl *Next = Current->getNextRedeclarationImpl();
948 assert(Next && "Should return next redeclaration or itself, never null!")(static_cast <bool> (Next && "Should return next redeclaration or itself, never null!"
) ? void (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 948, __extension__ __PRETTY_FUNCTION__))
;
949 Current = (Next != Starter) ? Next : nullptr;
950 return *this;
951 }
952
953 redecl_iterator operator++(int) {
954 redecl_iterator tmp(*this);
955 ++(*this);
956 return tmp;
957 }
958
959 friend bool operator==(redecl_iterator x, redecl_iterator y) {
960 return x.Current == y.Current;
961 }
962
963 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
964 return x.Current != y.Current;
965 }
966 };
967
968 using redecl_range = llvm::iterator_range<redecl_iterator>;
969
970 /// Returns an iterator range for all the redeclarations of the same
971 /// decl. It will iterate at least once (when this decl is the only one).
972 redecl_range redecls() const {
973 return redecl_range(redecls_begin(), redecls_end());
974 }
975
976 redecl_iterator redecls_begin() const {
977 return redecl_iterator(const_cast<Decl *>(this));
978 }
979
980 redecl_iterator redecls_end() const { return redecl_iterator(); }
981
982 /// Retrieve the previous declaration that declares the same entity
983 /// as this declaration, or NULL if there is no previous declaration.
984 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
985
986 /// Retrieve the previous declaration that declares the same entity
987 /// as this declaration, or NULL if there is no previous declaration.
988 const Decl *getPreviousDecl() const {
989 return const_cast<Decl *>(this)->getPreviousDeclImpl();
990 }
991
992 /// True if this is the first declaration in its redeclaration chain.
993 bool isFirstDecl() const {
994 return getPreviousDecl() == nullptr;
995 }
996
997 /// Retrieve the most recent declaration that declares the same entity
998 /// as this declaration (which may be this declaration).
999 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
1000
1001 /// Retrieve the most recent declaration that declares the same entity
1002 /// as this declaration (which may be this declaration).
1003 const Decl *getMostRecentDecl() const {
1004 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
1005 }
1006
1007 /// getBody - If this Decl represents a declaration for a body of code,
1008 /// such as a function or method definition, this method returns the
1009 /// top-level Stmt* of that body. Otherwise this method returns null.
1010 virtual Stmt* getBody() const { return nullptr; }
1011
1012 /// Returns true if this \c Decl represents a declaration for a body of
1013 /// code, such as a function or method definition.
1014 /// Note that \c hasBody can also return true if any redeclaration of this
1015 /// \c Decl represents a declaration for a body of code.
1016 virtual bool hasBody() const { return getBody() != nullptr; }
1017
1018 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1019 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1020 SourceLocation getBodyRBrace() const;
1021
1022 // global temp stats (until we have a per-module visitor)
1023 static void add(Kind k);
1024 static void EnableStatistics();
1025 static void PrintStats();
1026
1027 /// isTemplateParameter - Determines whether this declaration is a
1028 /// template parameter.
1029 bool isTemplateParameter() const;
1030
1031 /// isTemplateParameter - Determines whether this declaration is a
1032 /// template parameter pack.
1033 bool isTemplateParameterPack() const;
1034
1035 /// Whether this declaration is a parameter pack.
1036 bool isParameterPack() const;
1037
1038 /// returns true if this declaration is a template
1039 bool isTemplateDecl() const;
1040
1041 /// Whether this declaration is a function or function template.
1042 bool isFunctionOrFunctionTemplate() const {
1043 return (DeclKind >= Decl::firstFunction &&
1044 DeclKind <= Decl::lastFunction) ||
1045 DeclKind == FunctionTemplate;
1046 }
1047
1048 /// If this is a declaration that describes some template, this
1049 /// method returns that template declaration.
1050 ///
1051 /// Note that this returns nullptr for partial specializations, because they
1052 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1053 /// those cases.
1054 TemplateDecl *getDescribedTemplate() const;
1055
1056 /// If this is a declaration that describes some template or partial
1057 /// specialization, this returns the corresponding template parameter list.
1058 const TemplateParameterList *getDescribedTemplateParams() const;
1059
1060 /// Returns the function itself, or the templated function if this is a
1061 /// function template.
1062 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1063
1064 const FunctionDecl *getAsFunction() const {
1065 return const_cast<Decl *>(this)->getAsFunction();
1066 }
1067
1068 /// Changes the namespace of this declaration to reflect that it's
1069 /// a function-local extern declaration.
1070 ///
1071 /// These declarations appear in the lexical context of the extern
1072 /// declaration, but in the semantic context of the enclosing namespace
1073 /// scope.
1074 void setLocalExternDecl() {
1075 Decl *Prev = getPreviousDecl();
1076 IdentifierNamespace &= ~IDNS_Ordinary;
1077
1078 // It's OK for the declaration to still have the "invisible friend" flag or
1079 // the "conflicts with tag declarations in this scope" flag for the outer
1080 // scope.
1081 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1082, __extension__ __PRETTY_FUNCTION__))
1082 "namespace is not ordinary")(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1082, __extension__ __PRETTY_FUNCTION__))
;
1083
1084 IdentifierNamespace |= IDNS_LocalExtern;
1085 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1086 IdentifierNamespace |= IDNS_Ordinary;
1087 }
1088
1089 /// Determine whether this is a block-scope declaration with linkage.
1090 /// This will either be a local variable declaration declared 'extern', or a
1091 /// local function declaration.
1092 bool isLocalExternDecl() {
1093 return IdentifierNamespace & IDNS_LocalExtern;
1094 }
1095
1096 /// Changes the namespace of this declaration to reflect that it's
1097 /// the object of a friend declaration.
1098 ///
1099 /// These declarations appear in the lexical context of the friending
1100 /// class, but in the semantic context of the actual entity. This property
1101 /// applies only to a specific decl object; other redeclarations of the
1102 /// same entity may not (and probably don't) share this property.
1103 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1104 unsigned OldNS = IdentifierNamespace;
1105 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
1108 "namespace includes neither ordinary nor tag")(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1108, __extension__ __PRETTY_FUNCTION__))
;
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
1112 "namespace includes other than ordinary or tag")(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
;
1113
1114 Decl *Prev = getPreviousDecl();
1115 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1116
1117 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1118 IdentifierNamespace |= IDNS_TagFriend;
1119 if (PerformFriendInjection ||
1120 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1121 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1122 }
1123
1124 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1125 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1126 IdentifierNamespace |= IDNS_OrdinaryFriend;
1127 if (PerformFriendInjection ||
1128 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1129 IdentifierNamespace |= IDNS_Ordinary;
1130 }
1131 }
1132
1133 enum FriendObjectKind {
1134 FOK_None, ///< Not a friend object.
1135 FOK_Declared, ///< A friend of a previously-declared entity.
1136 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1137 };
1138
1139 /// Determines whether this declaration is the object of a
1140 /// friend declaration and, if so, what kind.
1141 ///
1142 /// There is currently no direct way to find the associated FriendDecl.
1143 FriendObjectKind getFriendObjectKind() const {
1144 unsigned mask =
1145 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1146 if (!mask) return FOK_None;
1147 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1148 : FOK_Undeclared);
1149 }
1150
1151 /// Specifies that this declaration is a C++ overloaded non-member.
1152 void setNonMemberOperator() {
1153 assert(getKind() == Function || getKind() == FunctionTemplate)(static_cast <bool> (getKind() == Function || getKind()
== FunctionTemplate) ? void (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1153, __extension__ __PRETTY_FUNCTION__))
;
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1155, __extension__ __PRETTY_FUNCTION__))
1155 "visible non-member operators should be in ordinary namespace")(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1155, __extension__ __PRETTY_FUNCTION__))
;
1156 IdentifierNamespace |= IDNS_NonMemberOperator;
1157 }
1158
1159 static bool classofKind(Kind K) { return true; }
1160 static DeclContext *castToDeclContext(const Decl *);
1161 static Decl *castFromDeclContext(const DeclContext *);
1162
1163 void print(raw_ostream &Out, unsigned Indentation = 0,
1164 bool PrintInstantiation = false) const;
1165 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1166 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1167 static void printGroup(Decl** Begin, unsigned NumDecls,
1168 raw_ostream &Out, const PrintingPolicy &Policy,
1169 unsigned Indentation = 0);
1170
1171 // Debuggers don't usually respect default arguments.
1172 void dump() const;
1173
1174 // Same as dump(), but forces color printing.
1175 void dumpColor() const;
1176
1177 void dump(raw_ostream &Out, bool Deserialize = false,
1178 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1179
1180 /// \return Unique reproducible object identifier
1181 int64_t getID() const;
1182
1183 /// Looks through the Decl's underlying type to extract a FunctionType
1184 /// when possible. Will return null if the type underlying the Decl does not
1185 /// have a FunctionType.
1186 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1187
1188private:
1189 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1190 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1191 ASTContext &Ctx);
1192
1193protected:
1194 ASTMutationListener *getASTMutationListener() const;
1195};
1196
1197/// Determine whether two declarations declare the same entity.
1198inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1199 if (!D1 || !D2)
1200 return false;
1201
1202 if (D1 == D2)
1203 return true;
1204
1205 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1206}
1207
1208/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1209/// doing something to a specific decl.
1210class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1211 const Decl *TheDecl;
1212 SourceLocation Loc;
1213 SourceManager &SM;
1214 const char *Message;
1215
1216public:
1217 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1218 SourceManager &sm, const char *Msg)
1219 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1220
1221 void print(raw_ostream &OS) const override;
1222};
1223} // namespace clang
1224
1225// Required to determine the layout of the PointerUnion<NamedDecl*> before
1226// seeing the NamedDecl definition being first used in DeclListNode::operator*.
1227namespace llvm {
1228 template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> {
1229 static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; }
1230 static inline ::clang::NamedDecl *getFromVoidPointer(void *P) {
1231 return static_cast<::clang::NamedDecl *>(P);
1232 }
1233 static constexpr int NumLowBitsAvailable = 3;
1234 };
1235}
1236
1237namespace clang {
1238/// A list storing NamedDecls in the lookup tables.
1239class DeclListNode {
1240 friend class ASTContext; // allocate, deallocate nodes.
1241 friend class StoredDeclsList;
1242public:
1243 using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>;
1244 class iterator {
1245 friend class DeclContextLookupResult;
1246 friend class StoredDeclsList;
1247
1248 Decls Ptr;
1249 iterator(Decls Node) : Ptr(Node) { }
1250 public:
1251 using difference_type = ptrdiff_t;
1252 using value_type = NamedDecl*;
1253 using pointer = void;
1254 using reference = value_type;
1255 using iterator_category = std::forward_iterator_tag;
1256
1257 iterator() = default;
1258
1259 reference operator*() const {
1260 assert(Ptr && "dereferencing end() iterator")(static_cast <bool> (Ptr && "dereferencing end() iterator"
) ? void (0) : __assert_fail ("Ptr && \"dereferencing end() iterator\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1260, __extension__ __PRETTY_FUNCTION__))
;
1261 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1262 return CurNode->D;
1263 return Ptr.get<NamedDecl*>();
1264 }
1265 void operator->() const { } // Unsupported.
1266 bool operator==(const iterator &X) const { return Ptr == X.Ptr; }
1267 bool operator!=(const iterator &X) const { return Ptr != X.Ptr; }
1268 inline iterator &operator++() { // ++It
1269 assert(!Ptr.isNull() && "Advancing empty iterator")(static_cast <bool> (!Ptr.isNull() && "Advancing empty iterator"
) ? void (0) : __assert_fail ("!Ptr.isNull() && \"Advancing empty iterator\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 1269, __extension__ __PRETTY_FUNCTION__))
;
1270
1271 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1272 Ptr = CurNode->Rest;
1273 else
1274 Ptr = nullptr;
1275 return *this;
1276 }
1277 iterator operator++(int) { // It++
1278 iterator temp = *this;
1279 ++(*this);
1280 return temp;
1281 }
1282 // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I)
1283 iterator end() { return iterator(); }
1284 };
1285private:
1286 NamedDecl *D = nullptr;
1287 Decls Rest = nullptr;
1288 DeclListNode(NamedDecl *ND) : D(ND) {}
1289};
1290
1291/// The results of name lookup within a DeclContext.
1292class DeclContextLookupResult {
1293 using Decls = DeclListNode::Decls;
1294
1295 /// When in collection form, this is what the Data pointer points to.
1296 Decls Result;
1297
1298public:
1299 DeclContextLookupResult() = default;
1300 DeclContextLookupResult(Decls Result) : Result(Result) {}
1301
1302 using iterator = DeclListNode::iterator;
1303 using const_iterator = iterator;
1304 using reference = iterator::reference;
1305
1306 iterator begin() { return iterator(Result); }
1307 iterator end() { return iterator(); }
1308 const_iterator begin() const {
1309 return const_cast<DeclContextLookupResult*>(this)->begin();
1310 }
1311 const_iterator end() const { return iterator(); }
1312
1313 bool empty() const { return Result.isNull(); }
1314 bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); }
1315 reference front() const { return *begin(); }
1316
1317 // Find the first declaration of the given type in the list. Note that this
1318 // is not in general the earliest-declared declaration, and should only be
1319 // used when it's not possible for there to be more than one match or where
1320 // it doesn't matter which one is found.
1321 template<class T> T *find_first() const {
1322 for (auto *D : *this)
1323 if (T *Decl = dyn_cast<T>(D))
1324 return Decl;
1325
1326 return nullptr;
1327 }
1328};
1329
1330/// DeclContext - This is used only as base class of specific decl types that
1331/// can act as declaration contexts. These decls are (only the top classes
1332/// that directly derive from DeclContext are mentioned, not their subclasses):
1333///
1334/// TranslationUnitDecl
1335/// ExternCContext
1336/// NamespaceDecl
1337/// TagDecl
1338/// OMPDeclareReductionDecl
1339/// OMPDeclareMapperDecl
1340/// FunctionDecl
1341/// ObjCMethodDecl
1342/// ObjCContainerDecl
1343/// LinkageSpecDecl
1344/// ExportDecl
1345/// BlockDecl
1346/// CapturedDecl
1347class DeclContext {
1348 /// For makeDeclVisibleInContextImpl
1349 friend class ASTDeclReader;
1350 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1351 /// hasNeedToReconcileExternalVisibleStorage
1352 friend class ExternalASTSource;
1353 /// For CreateStoredDeclsMap
1354 friend class DependentDiagnostic;
1355 /// For hasNeedToReconcileExternalVisibleStorage,
1356 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1357 friend class ASTWriter;
1358
1359 // We use uint64_t in the bit-fields below since some bit-fields
1360 // cross the unsigned boundary and this breaks the packing.
1361
1362 /// Stores the bits used by DeclContext.
1363 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1364 /// methods in DeclContext should be updated appropriately.
1365 class DeclContextBitfields {
1366 friend class DeclContext;
1367 /// DeclKind - This indicates which class this is.
1368 uint64_t DeclKind : 7;
1369
1370 /// Whether this declaration context also has some external
1371 /// storage that contains additional declarations that are lexically
1372 /// part of this context.
1373 mutable uint64_t ExternalLexicalStorage : 1;
1374
1375 /// Whether this declaration context also has some external
1376 /// storage that contains additional declarations that are visible
1377 /// in this context.
1378 mutable uint64_t ExternalVisibleStorage : 1;
1379
1380 /// Whether this declaration context has had externally visible
1381 /// storage added since the last lookup. In this case, \c LookupPtr's
1382 /// invariant may not hold and needs to be fixed before we perform
1383 /// another lookup.
1384 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1385
1386 /// If \c true, this context may have local lexical declarations
1387 /// that are missing from the lookup table.
1388 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1389
1390 /// If \c true, the external source may have lexical declarations
1391 /// that are missing from the lookup table.
1392 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1393
1394 /// If \c true, lookups should only return identifier from
1395 /// DeclContext scope (for example TranslationUnit). Used in
1396 /// LookupQualifiedName()
1397 mutable uint64_t UseQualifiedLookup : 1;
1398 };
1399
1400 /// Number of bits in DeclContextBitfields.
1401 enum { NumDeclContextBits = 13 };
1402
1403 /// Stores the bits used by TagDecl.
1404 /// If modified NumTagDeclBits and the accessor
1405 /// methods in TagDecl should be updated appropriately.
1406 class TagDeclBitfields {
1407 friend class TagDecl;
1408 /// For the bits in DeclContextBitfields
1409 uint64_t : NumDeclContextBits;
1410
1411 /// The TagKind enum.
1412 uint64_t TagDeclKind : 3;
1413
1414 /// True if this is a definition ("struct foo {};"), false if it is a
1415 /// declaration ("struct foo;"). It is not considered a definition
1416 /// until the definition has been fully processed.
1417 uint64_t IsCompleteDefinition : 1;
1418
1419 /// True if this is currently being defined.
1420 uint64_t IsBeingDefined : 1;
1421
1422 /// True if this tag declaration is "embedded" (i.e., defined or declared
1423 /// for the very first time) in the syntax of a declarator.
1424 uint64_t IsEmbeddedInDeclarator : 1;
1425
1426 /// True if this tag is free standing, e.g. "struct foo;".
1427 uint64_t IsFreeStanding : 1;
1428
1429 /// Indicates whether it is possible for declarations of this kind
1430 /// to have an out-of-date definition.
1431 ///
1432 /// This option is only enabled when modules are enabled.
1433 uint64_t MayHaveOutOfDateDef : 1;
1434
1435 /// Has the full definition of this type been required by a use somewhere in
1436 /// the TU.
1437 uint64_t IsCompleteDefinitionRequired : 1;
1438 };
1439
1440 /// Number of non-inherited bits in TagDeclBitfields.
1441 enum { NumTagDeclBits = 9 };
1442
1443 /// Stores the bits used by EnumDecl.
1444 /// If modified NumEnumDeclBit and the accessor
1445 /// methods in EnumDecl should be updated appropriately.
1446 class EnumDeclBitfields {
1447 friend class EnumDecl;
1448 /// For the bits in DeclContextBitfields.
1449 uint64_t : NumDeclContextBits;
1450 /// For the bits in TagDeclBitfields.
1451 uint64_t : NumTagDeclBits;
1452
1453 /// Width in bits required to store all the non-negative
1454 /// enumerators of this enum.
1455 uint64_t NumPositiveBits : 8;
1456
1457 /// Width in bits required to store all the negative
1458 /// enumerators of this enum.
1459 uint64_t NumNegativeBits : 8;
1460
1461 /// True if this tag declaration is a scoped enumeration. Only
1462 /// possible in C++11 mode.
1463 uint64_t IsScoped : 1;
1464
1465 /// If this tag declaration is a scoped enum,
1466 /// then this is true if the scoped enum was declared using the class
1467 /// tag, false if it was declared with the struct tag. No meaning is
1468 /// associated if this tag declaration is not a scoped enum.
1469 uint64_t IsScopedUsingClassTag : 1;
1470
1471 /// True if this is an enumeration with fixed underlying type. Only
1472 /// possible in C++11, Microsoft extensions, or Objective C mode.
1473 uint64_t IsFixed : 1;
1474
1475 /// True if a valid hash is stored in ODRHash.
1476 uint64_t HasODRHash : 1;
1477 };
1478
1479 /// Number of non-inherited bits in EnumDeclBitfields.
1480 enum { NumEnumDeclBits = 20 };
1481
1482 /// Stores the bits used by RecordDecl.
1483 /// If modified NumRecordDeclBits and the accessor
1484 /// methods in RecordDecl should be updated appropriately.
1485 class RecordDeclBitfields {
1486 friend class RecordDecl;
1487 /// For the bits in DeclContextBitfields.
1488 uint64_t : NumDeclContextBits;
1489 /// For the bits in TagDeclBitfields.
1490 uint64_t : NumTagDeclBits;
1491
1492 /// This is true if this struct ends with a flexible
1493 /// array member (e.g. int X[]) or if this union contains a struct that does.
1494 /// If so, this cannot be contained in arrays or other structs as a member.
1495 uint64_t HasFlexibleArrayMember : 1;
1496
1497 /// Whether this is the type of an anonymous struct or union.
1498 uint64_t AnonymousStructOrUnion : 1;
1499
1500 /// This is true if this struct has at least one member
1501 /// containing an Objective-C object pointer type.
1502 uint64_t HasObjectMember : 1;
1503
1504 /// This is true if struct has at least one member of
1505 /// 'volatile' type.
1506 uint64_t HasVolatileMember : 1;
1507
1508 /// Whether the field declarations of this record have been loaded
1509 /// from external storage. To avoid unnecessary deserialization of
1510 /// methods/nested types we allow deserialization of just the fields
1511 /// when needed.
1512 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1513
1514 /// Basic properties of non-trivial C structs.
1515 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1516 uint64_t NonTrivialToPrimitiveCopy : 1;
1517 uint64_t NonTrivialToPrimitiveDestroy : 1;
1518
1519 /// The following bits indicate whether this is or contains a C union that
1520 /// is non-trivial to default-initialize, destruct, or copy. These bits
1521 /// imply the associated basic non-triviality predicates declared above.
1522 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1523 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1524 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1525
1526 /// Indicates whether this struct is destroyed in the callee.
1527 uint64_t ParamDestroyedInCallee : 1;
1528
1529 /// Represents the way this type is passed to a function.
1530 uint64_t ArgPassingRestrictions : 2;
1531 };
1532
1533 /// Number of non-inherited bits in RecordDeclBitfields.
1534 enum { NumRecordDeclBits = 14 };
1535
1536 /// Stores the bits used by OMPDeclareReductionDecl.
1537 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1538 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1539 class OMPDeclareReductionDeclBitfields {
1540 friend class OMPDeclareReductionDecl;
1541 /// For the bits in DeclContextBitfields
1542 uint64_t : NumDeclContextBits;
1543
1544 /// Kind of initializer,
1545 /// function call or omp_priv<init_expr> initializtion.
1546 uint64_t InitializerKind : 2;
1547 };
1548
1549 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1550 enum { NumOMPDeclareReductionDeclBits = 2 };
1551
1552 /// Stores the bits used by FunctionDecl.
1553 /// If modified NumFunctionDeclBits and the accessor
1554 /// methods in FunctionDecl and CXXDeductionGuideDecl
1555 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1556 class FunctionDeclBitfields {
1557 friend class FunctionDecl;
1558 /// For IsCopyDeductionCandidate
1559 friend class CXXDeductionGuideDecl;
1560 /// For the bits in DeclContextBitfields.
1561 uint64_t : NumDeclContextBits;
1562
1563 uint64_t SClass : 3;
1564 uint64_t IsInline : 1;
1565 uint64_t IsInlineSpecified : 1;
1566
1567 uint64_t IsVirtualAsWritten : 1;
1568 uint64_t IsPure : 1;
1569 uint64_t HasInheritedPrototype : 1;
1570 uint64_t HasWrittenPrototype : 1;
1571 uint64_t IsDeleted : 1;
1572 /// Used by CXXMethodDecl
1573 uint64_t IsTrivial : 1;
1574
1575 /// This flag indicates whether this function is trivial for the purpose of
1576 /// calls. This is meaningful only when this function is a copy/move
1577 /// constructor or a destructor.
1578 uint64_t IsTrivialForCall : 1;
1579
1580 uint64_t IsDefaulted : 1;
1581 uint64_t IsExplicitlyDefaulted : 1;
1582 uint64_t HasDefaultedFunctionInfo : 1;
1583 uint64_t HasImplicitReturnZero : 1;
1584 uint64_t IsLateTemplateParsed : 1;
1585
1586 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1587 uint64_t ConstexprKind : 2;
1588 uint64_t InstantiationIsPending : 1;
1589
1590 /// Indicates if the function uses __try.
1591 uint64_t UsesSEHTry : 1;
1592
1593 /// Indicates if the function was a definition
1594 /// but its body was skipped.
1595 uint64_t HasSkippedBody : 1;
1596
1597 /// Indicates if the function declaration will
1598 /// have a body, once we're done parsing it.
1599 uint64_t WillHaveBody : 1;
1600
1601 /// Indicates that this function is a multiversioned
1602 /// function using attribute 'target'.
1603 uint64_t IsMultiVersion : 1;
1604
1605 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1606 /// the Deduction Guide is the implicitly generated 'copy
1607 /// deduction candidate' (is used during overload resolution).
1608 uint64_t IsCopyDeductionCandidate : 1;
1609
1610 /// Store the ODRHash after first calculation.
1611 uint64_t HasODRHash : 1;
1612
1613 /// Indicates if the function uses Floating Point Constrained Intrinsics
1614 uint64_t UsesFPIntrin : 1;
1615 };
1616
1617 /// Number of non-inherited bits in FunctionDeclBitfields.
1618 enum { NumFunctionDeclBits = 27 };
1619
1620 /// Stores the bits used by CXXConstructorDecl. If modified
1621 /// NumCXXConstructorDeclBits and the accessor
1622 /// methods in CXXConstructorDecl should be updated appropriately.
1623 class CXXConstructorDeclBitfields {
1624 friend class CXXConstructorDecl;
1625 /// For the bits in DeclContextBitfields.
1626 uint64_t : NumDeclContextBits;
1627 /// For the bits in FunctionDeclBitfields.
1628 uint64_t : NumFunctionDeclBits;
1629
1630 /// 24 bits to fit in the remaining available space.
1631 /// Note that this makes CXXConstructorDeclBitfields take
1632 /// exactly 64 bits and thus the width of NumCtorInitializers
1633 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1634 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1635 uint64_t NumCtorInitializers : 21;
1636 uint64_t IsInheritingConstructor : 1;
1637
1638 /// Whether this constructor has a trail-allocated explicit specifier.
1639 uint64_t HasTrailingExplicitSpecifier : 1;
1640 /// If this constructor does't have a trail-allocated explicit specifier.
1641 /// Whether this constructor is explicit specified.
1642 uint64_t IsSimpleExplicit : 1;
1643 };
1644
1645 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1646 enum {
1647 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1648 };
1649
1650 /// Stores the bits used by ObjCMethodDecl.
1651 /// If modified NumObjCMethodDeclBits and the accessor
1652 /// methods in ObjCMethodDecl should be updated appropriately.
1653 class ObjCMethodDeclBitfields {
1654 friend class ObjCMethodDecl;
1655
1656 /// For the bits in DeclContextBitfields.
1657 uint64_t : NumDeclContextBits;
1658
1659 /// The conventional meaning of this method; an ObjCMethodFamily.
1660 /// This is not serialized; instead, it is computed on demand and
1661 /// cached.
1662 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1663
1664 /// instance (true) or class (false) method.
1665 uint64_t IsInstance : 1;
1666 uint64_t IsVariadic : 1;
1667
1668 /// True if this method is the getter or setter for an explicit property.
1669 uint64_t IsPropertyAccessor : 1;
1670
1671 /// True if this method is a synthesized property accessor stub.
1672 uint64_t IsSynthesizedAccessorStub : 1;
1673
1674 /// Method has a definition.
1675 uint64_t IsDefined : 1;
1676
1677 /// Method redeclaration in the same interface.
1678 uint64_t IsRedeclaration : 1;
1679
1680 /// Is redeclared in the same interface.
1681 mutable uint64_t HasRedeclaration : 1;
1682
1683 /// \@required/\@optional
1684 uint64_t DeclImplementation : 2;
1685
1686 /// in, inout, etc.
1687 uint64_t objcDeclQualifier : 7;
1688
1689 /// Indicates whether this method has a related result type.
1690 uint64_t RelatedResultType : 1;
1691
1692 /// Whether the locations of the selector identifiers are in a
1693 /// "standard" position, a enum SelectorLocationsKind.
1694 uint64_t SelLocsKind : 2;
1695
1696 /// Whether this method overrides any other in the class hierarchy.
1697 ///
1698 /// A method is said to override any method in the class's
1699 /// base classes, its protocols, or its categories' protocols, that has
1700 /// the same selector and is of the same kind (class or instance).
1701 /// A method in an implementation is not considered as overriding the same
1702 /// method in the interface or its categories.
1703 uint64_t IsOverriding : 1;
1704
1705 /// Indicates if the method was a definition but its body was skipped.
1706 uint64_t HasSkippedBody : 1;
1707 };
1708
1709 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1710 enum { NumObjCMethodDeclBits = 24 };
1711
1712 /// Stores the bits used by ObjCContainerDecl.
1713 /// If modified NumObjCContainerDeclBits and the accessor
1714 /// methods in ObjCContainerDecl should be updated appropriately.
1715 class ObjCContainerDeclBitfields {
1716 friend class ObjCContainerDecl;
1717 /// For the bits in DeclContextBitfields
1718 uint32_t : NumDeclContextBits;
1719
1720 // Not a bitfield but this saves space.
1721 // Note that ObjCContainerDeclBitfields is full.
1722 SourceLocation AtStart;
1723 };
1724
1725 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1726 /// Note that here we rely on the fact that SourceLocation is 32 bits
1727 /// wide. We check this with the static_assert in the ctor of DeclContext.
1728 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1729
1730 /// Stores the bits used by LinkageSpecDecl.
1731 /// If modified NumLinkageSpecDeclBits and the accessor
1732 /// methods in LinkageSpecDecl should be updated appropriately.
1733 class LinkageSpecDeclBitfields {
1734 friend class LinkageSpecDecl;
1735 /// For the bits in DeclContextBitfields.
1736 uint64_t : NumDeclContextBits;
1737
1738 /// The language for this linkage specification with values
1739 /// in the enum LinkageSpecDecl::LanguageIDs.
1740 uint64_t Language : 3;
1741
1742 /// True if this linkage spec has braces.
1743 /// This is needed so that hasBraces() returns the correct result while the
1744 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1745 /// not used, so it doesn't need to be serialized.
1746 uint64_t HasBraces : 1;
1747 };
1748
1749 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1750 enum { NumLinkageSpecDeclBits = 4 };
1751
1752 /// Stores the bits used by BlockDecl.
1753 /// If modified NumBlockDeclBits and the accessor
1754 /// methods in BlockDecl should be updated appropriately.
1755 class BlockDeclBitfields {
1756 friend class BlockDecl;
1757 /// For the bits in DeclContextBitfields.
1758 uint64_t : NumDeclContextBits;
1759
1760 uint64_t IsVariadic : 1;
1761 uint64_t CapturesCXXThis : 1;
1762 uint64_t BlockMissingReturnType : 1;
1763 uint64_t IsConversionFromLambda : 1;
1764
1765 /// A bit that indicates this block is passed directly to a function as a
1766 /// non-escaping parameter.
1767 uint64_t DoesNotEscape : 1;
1768
1769 /// A bit that indicates whether it's possible to avoid coying this block to
1770 /// the heap when it initializes or is assigned to a local variable with
1771 /// automatic storage.
1772 uint64_t CanAvoidCopyToHeap : 1;
1773 };
1774
1775 /// Number of non-inherited bits in BlockDeclBitfields.
1776 enum { NumBlockDeclBits = 5 };
1777
1778 /// Pointer to the data structure used to lookup declarations
1779 /// within this context (or a DependentStoredDeclsMap if this is a
1780 /// dependent context). We maintain the invariant that, if the map
1781 /// contains an entry for a DeclarationName (and we haven't lazily
1782 /// omitted anything), then it contains all relevant entries for that
1783 /// name (modulo the hasExternalDecls() flag).
1784 mutable StoredDeclsMap *LookupPtr = nullptr;
1785
1786protected:
1787 /// This anonymous union stores the bits belonging to DeclContext and classes
1788 /// deriving from it. The goal is to use otherwise wasted
1789 /// space in DeclContext to store data belonging to derived classes.
1790 /// The space saved is especially significient when pointers are aligned
1791 /// to 8 bytes. In this case due to alignment requirements we have a
1792 /// little less than 8 bytes free in DeclContext which we can use.
1793 /// We check that none of the classes in this union is larger than
1794 /// 8 bytes with static_asserts in the ctor of DeclContext.
1795 union {
1796 DeclContextBitfields DeclContextBits;
1797 TagDeclBitfields TagDeclBits;
1798 EnumDeclBitfields EnumDeclBits;
1799 RecordDeclBitfields RecordDeclBits;
1800 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1801 FunctionDeclBitfields FunctionDeclBits;
1802 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1803 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1804 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1805 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1806 BlockDeclBitfields BlockDeclBits;
1807
1808 static_assert(sizeof(DeclContextBitfields) <= 8,
1809 "DeclContextBitfields is larger than 8 bytes!");
1810 static_assert(sizeof(TagDeclBitfields) <= 8,
1811 "TagDeclBitfields is larger than 8 bytes!");
1812 static_assert(sizeof(EnumDeclBitfields) <= 8,
1813 "EnumDeclBitfields is larger than 8 bytes!");
1814 static_assert(sizeof(RecordDeclBitfields) <= 8,
1815 "RecordDeclBitfields is larger than 8 bytes!");
1816 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1817 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1818 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1819 "FunctionDeclBitfields is larger than 8 bytes!");
1820 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1821 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1822 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1823 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1824 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1825 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1826 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1827 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1828 static_assert(sizeof(BlockDeclBitfields) <= 8,
1829 "BlockDeclBitfields is larger than 8 bytes!");
1830 };
1831
1832 /// FirstDecl - The first declaration stored within this declaration
1833 /// context.
1834 mutable Decl *FirstDecl = nullptr;
1835
1836 /// LastDecl - The last declaration stored within this declaration
1837 /// context. FIXME: We could probably cache this value somewhere
1838 /// outside of the DeclContext, to reduce the size of DeclContext by
1839 /// another pointer.
1840 mutable Decl *LastDecl = nullptr;
1841
1842 /// Build up a chain of declarations.
1843 ///
1844 /// \returns the first/last pair of declarations.
1845 static std::pair<Decl *, Decl *>
1846 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1847
1848 DeclContext(Decl::Kind K);
1849
1850public:
1851 ~DeclContext();
1852
1853 Decl::Kind getDeclKind() const {
1854 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1855 }
1856
1857 const char *getDeclKindName() const;
1858
1859 /// getParent - Returns the containing DeclContext.
1860 DeclContext *getParent() {
1861 return cast<Decl>(this)->getDeclContext();
1862 }
1863 const DeclContext *getParent() const {
1864 return const_cast<DeclContext*>(this)->getParent();
1865 }
1866
1867 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1868 /// different from getParent, e.g.:
1869 ///
1870 /// namespace A {
1871 /// struct S;
1872 /// }
1873 /// struct A::S {}; // getParent() == namespace 'A'
1874 /// // getLexicalParent() == translation unit
1875 ///
1876 DeclContext *getLexicalParent() {
1877 return cast<Decl>(this)->getLexicalDeclContext();
1878 }
1879 const DeclContext *getLexicalParent() const {
1880 return const_cast<DeclContext*>(this)->getLexicalParent();
1881 }
1882
1883 DeclContext *getLookupParent();
1884
1885 const DeclContext *getLookupParent() const {
1886 return const_cast<DeclContext*>(this)->getLookupParent();
1887 }
1888
1889 ASTContext &getParentASTContext() const {
1890 return cast<Decl>(this)->getASTContext();
1891 }
1892
1893 bool isClosure() const { return getDeclKind() == Decl::Block; }
1894
1895 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1896 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1897 const BlockDecl *getInnermostBlockDecl() const;
1898
1899 bool isObjCContainer() const {
1900 switch (getDeclKind()) {
1901 case Decl::ObjCCategory:
1902 case Decl::ObjCCategoryImpl:
1903 case Decl::ObjCImplementation:
1904 case Decl::ObjCInterface:
1905 case Decl::ObjCProtocol:
1906 return true;
1907 default:
1908 return false;
1909 }
1910 }
1911
1912 bool isFunctionOrMethod() const {
1913 switch (getDeclKind()) {
1914 case Decl::Block:
1915 case Decl::Captured:
1916 case Decl::ObjCMethod:
1917 return true;
1918 default:
1919 return getDeclKind() >= Decl::firstFunction &&
1920 getDeclKind() <= Decl::lastFunction;
1921 }
1922 }
1923
1924 /// Test whether the context supports looking up names.
1925 bool isLookupContext() const {
1926 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1927 getDeclKind() != Decl::Export;
1928 }
1929
1930 bool isFileContext() const {
1931 return getDeclKind() == Decl::TranslationUnit ||
1932 getDeclKind() == Decl::Namespace;
1933 }
1934
1935 bool isTranslationUnit() const {
1936 return getDeclKind() == Decl::TranslationUnit;
1937 }
1938
1939 bool isRecord() const {
1940 return getDeclKind() >= Decl::firstRecord &&
1941 getDeclKind() <= Decl::lastRecord;
1942 }
1943
1944 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1945
1946 bool isStdNamespace() const;
1947
1948 bool isInlineNamespace() const;
1949
1950 /// Determines whether this context is dependent on a
1951 /// template parameter.
1952 bool isDependentContext() const;
1953
1954 /// isTransparentContext - Determines whether this context is a
1955 /// "transparent" context, meaning that the members declared in this
1956 /// context are semantically declared in the nearest enclosing
1957 /// non-transparent (opaque) context but are lexically declared in
1958 /// this context. For example, consider the enumerators of an
1959 /// enumeration type:
1960 /// @code
1961 /// enum E {
1962 /// Val1
1963 /// };
1964 /// @endcode
1965 /// Here, E is a transparent context, so its enumerator (Val1) will
1966 /// appear (semantically) that it is in the same context of E.
1967 /// Examples of transparent contexts include: enumerations (except for
1968 /// C++0x scoped enums), and C++ linkage specifications.
1969 bool isTransparentContext() const;
1970
1971 /// Determines whether this context or some of its ancestors is a
1972 /// linkage specification context that specifies C linkage.
1973 bool isExternCContext() const;
1974
1975 /// Retrieve the nearest enclosing C linkage specification context.
1976 const LinkageSpecDecl *getExternCContext() const;
1977
1978 /// Determines whether this context or some of its ancestors is a
1979 /// linkage specification context that specifies C++ linkage.
1980 bool isExternCXXContext() const;
1981
1982 /// Determine whether this declaration context is equivalent
1983 /// to the declaration context DC.
1984 bool Equals(const DeclContext *DC) const {
1985 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1986 }
1987
1988 /// Determine whether this declaration context encloses the
1989 /// declaration context DC.
1990 bool Encloses(const DeclContext *DC) const;
1991
1992 /// Find the nearest non-closure ancestor of this context,
1993 /// i.e. the innermost semantic parent of this context which is not
1994 /// a closure. A context may be its own non-closure ancestor.
1995 Decl *getNonClosureAncestor();
1996 const Decl *getNonClosureAncestor() const {
1997 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1998 }
1999
2000 // Retrieve the nearest context that is not a transparent context.
2001 DeclContext *getNonTransparentContext();
2002 const DeclContext *getNonTransparentContext() const {
2003 return const_cast<DeclContext *>(this)->getNonTransparentContext();
2004 }
2005
2006 /// getPrimaryContext - There may be many different
2007 /// declarations of the same entity (including forward declarations
2008 /// of classes, multiple definitions of namespaces, etc.), each with
2009 /// a different set of declarations. This routine returns the
2010 /// "primary" DeclContext structure, which will contain the
2011 /// information needed to perform name lookup into this context.
2012 DeclContext *getPrimaryContext();
2013 const DeclContext *getPrimaryContext() const {
2014 return const_cast<DeclContext*>(this)->getPrimaryContext();
2015 }
2016
2017 /// getRedeclContext - Retrieve the context in which an entity conflicts with
2018 /// other entities of the same name, or where it is a redeclaration if the
2019 /// two entities are compatible. This skips through transparent contexts.
2020 DeclContext *getRedeclContext();
2021 const DeclContext *getRedeclContext() const {
2022 return const_cast<DeclContext *>(this)->getRedeclContext();
2023 }
2024
2025 /// Retrieve the nearest enclosing namespace context.
2026 DeclContext *getEnclosingNamespaceContext();
2027 const DeclContext *getEnclosingNamespaceContext() const {
2028 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
2029 }
2030
2031 /// Retrieve the outermost lexically enclosing record context.
2032 RecordDecl *getOuterLexicalRecordContext();
2033 const RecordDecl *getOuterLexicalRecordContext() const {
2034 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
2035 }
2036
2037 /// Test if this context is part of the enclosing namespace set of
2038 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
2039 /// isn't a namespace, this is equivalent to Equals().
2040 ///
2041 /// The enclosing namespace set of a namespace is the namespace and, if it is
2042 /// inline, its enclosing namespace, recursively.
2043 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
2044
2045 /// Collects all of the declaration contexts that are semantically
2046 /// connected to this declaration context.
2047 ///
2048 /// For declaration contexts that have multiple semantically connected but
2049 /// syntactically distinct contexts, such as C++ namespaces, this routine
2050 /// retrieves the complete set of such declaration contexts in source order.
2051 /// For example, given:
2052 ///
2053 /// \code
2054 /// namespace N {
2055 /// int x;
2056 /// }
2057 /// namespace N {
2058 /// int y;
2059 /// }
2060 /// \endcode
2061 ///
2062 /// The \c Contexts parameter will contain both definitions of N.
2063 ///
2064 /// \param Contexts Will be cleared and set to the set of declaration
2065 /// contexts that are semanticaly connected to this declaration context,
2066 /// in source order, including this context (which may be the only result,
2067 /// for non-namespace contexts).
2068 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2069
2070 /// decl_iterator - Iterates through the declarations stored
2071 /// within this context.
2072 class decl_iterator {
2073 /// Current - The current declaration.
2074 Decl *Current = nullptr;
2075
2076 public:
2077 using value_type = Decl *;
2078 using reference = const value_type &;
2079 using pointer = const value_type *;
2080 using iterator_category = std::forward_iterator_tag;
2081 using difference_type = std::ptrdiff_t;
2082
2083 decl_iterator() = default;
2084 explicit decl_iterator(Decl *C) : Current(C) {}
2085
2086 reference operator*() const { return Current; }
2087
2088 // This doesn't meet the iterator requirements, but it's convenient
2089 value_type operator->() const { return Current; }
2090
2091 decl_iterator& operator++() {
2092 Current = Current->getNextDeclInContext();
2093 return *this;
2094 }
2095
2096 decl_iterator operator++(int) {
2097 decl_iterator tmp(*this);
2098 ++(*this);
2099 return tmp;
2100 }
2101
2102 friend bool operator==(decl_iterator x, decl_iterator y) {
2103 return x.Current == y.Current;
2104 }
2105
2106 friend bool operator!=(decl_iterator x, decl_iterator y) {
2107 return x.Current != y.Current;
2108 }
2109 };
2110
2111 using decl_range = llvm::iterator_range<decl_iterator>;
2112
2113 /// decls_begin/decls_end - Iterate over the declarations stored in
2114 /// this context.
2115 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2116 decl_iterator decls_begin() const;
2117 decl_iterator decls_end() const { return decl_iterator(); }
2118 bool decls_empty() const;
2119
2120 /// noload_decls_begin/end - Iterate over the declarations stored in this
2121 /// context that are currently loaded; don't attempt to retrieve anything
2122 /// from an external source.
2123 decl_range noload_decls() const {
2124 return decl_range(noload_decls_begin(), noload_decls_end());
2125 }
2126 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2127 decl_iterator noload_decls_end() const { return decl_iterator(); }
2128
2129 /// specific_decl_iterator - Iterates over a subrange of
2130 /// declarations stored in a DeclContext, providing only those that
2131 /// are of type SpecificDecl (or a class derived from it). This
2132 /// iterator is used, for example, to provide iteration over just
2133 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2134 template<typename SpecificDecl>
2135 class specific_decl_iterator {
2136 /// Current - The current, underlying declaration iterator, which
2137 /// will either be NULL or will point to a declaration of
2138 /// type SpecificDecl.
2139 DeclContext::decl_iterator Current;
2140
2141 /// SkipToNextDecl - Advances the current position up to the next
2142 /// declaration of type SpecificDecl that also meets the criteria
2143 /// required by Acceptable.
2144 void SkipToNextDecl() {
2145 while (*Current && !isa<SpecificDecl>(*Current))
2146 ++Current;
2147 }
2148
2149 public:
2150 using value_type = SpecificDecl *;
2151 // TODO: Add reference and pointer types (with some appropriate proxy type)
2152 // if we ever have a need for them.
2153 using reference = void;
2154 using pointer = void;
2155 using difference_type =
2156 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2157 using iterator_category = std::forward_iterator_tag;
2158
2159 specific_decl_iterator() = default;
2160
2161 /// specific_decl_iterator - Construct a new iterator over a
2162 /// subset of the declarations the range [C,
2163 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2164 /// member function of SpecificDecl that should return true for
2165 /// all of the SpecificDecl instances that will be in the subset
2166 /// of iterators. For example, if you want Objective-C instance
2167 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2168 /// &ObjCMethodDecl::isInstanceMethod.
2169 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2170 SkipToNextDecl();
2171 }
2172
2173 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2174
2175 // This doesn't meet the iterator requirements, but it's convenient
2176 value_type operator->() const { return **this; }
2177
2178 specific_decl_iterator& operator++() {
2179 ++Current;
2180 SkipToNextDecl();
2181 return *this;
2182 }
2183
2184 specific_decl_iterator operator++(int) {
2185 specific_decl_iterator tmp(*this);
2186 ++(*this);
2187 return tmp;
2188 }
2189
2190 friend bool operator==(const specific_decl_iterator& x,
2191 const specific_decl_iterator& y) {
2192 return x.Current == y.Current;
2193 }
2194
2195 friend bool operator!=(const specific_decl_iterator& x,
2196 const specific_decl_iterator& y) {
2197 return x.Current != y.Current;
2198 }
2199 };
2200
2201 /// Iterates over a filtered subrange of declarations stored
2202 /// in a DeclContext.
2203 ///
2204 /// This iterator visits only those declarations that are of type
2205 /// SpecificDecl (or a class derived from it) and that meet some
2206 /// additional run-time criteria. This iterator is used, for
2207 /// example, to provide access to the instance methods within an
2208 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2209 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2210 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2211 class filtered_decl_iterator {
2212 /// Current - The current, underlying declaration iterator, which
2213 /// will either be NULL or will point to a declaration of
2214 /// type SpecificDecl.
2215 DeclContext::decl_iterator Current;
2216
2217 /// SkipToNextDecl - Advances the current position up to the next
2218 /// declaration of type SpecificDecl that also meets the criteria
2219 /// required by Acceptable.
2220 void SkipToNextDecl() {
2221 while (*Current &&
2222 (!isa<SpecificDecl>(*Current) ||
2223 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2224 ++Current;
2225 }
2226
2227 public:
2228 using value_type = SpecificDecl *;
2229 // TODO: Add reference and pointer types (with some appropriate proxy type)
2230 // if we ever have a need for them.
2231 using reference = void;
2232 using pointer = void;
2233 using difference_type =
2234 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2235 using iterator_category = std::forward_iterator_tag;
2236
2237 filtered_decl_iterator() = default;
2238
2239 /// filtered_decl_iterator - Construct a new iterator over a
2240 /// subset of the declarations the range [C,
2241 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2242 /// member function of SpecificDecl that should return true for
2243 /// all of the SpecificDecl instances that will be in the subset
2244 /// of iterators. For example, if you want Objective-C instance
2245 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2246 /// &ObjCMethodDecl::isInstanceMethod.
2247 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2248 SkipToNextDecl();
2249 }
2250
2251 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2252 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2253
2254 filtered_decl_iterator& operator++() {
2255 ++Current;
2256 SkipToNextDecl();
2257 return *this;
2258 }
2259
2260 filtered_decl_iterator operator++(int) {
2261 filtered_decl_iterator tmp(*this);
2262 ++(*this);
2263 return tmp;
2264 }
2265
2266 friend bool operator==(const filtered_decl_iterator& x,
2267 const filtered_decl_iterator& y) {
2268 return x.Current == y.Current;
2269 }
2270
2271 friend bool operator!=(const filtered_decl_iterator& x,
2272 const filtered_decl_iterator& y) {
2273 return x.Current != y.Current;
2274 }
2275 };
2276
2277 /// Add the declaration D into this context.
2278 ///
2279 /// This routine should be invoked when the declaration D has first
2280 /// been declared, to place D into the context where it was
2281 /// (lexically) defined. Every declaration must be added to one
2282 /// (and only one!) context, where it can be visited via
2283 /// [decls_begin(), decls_end()). Once a declaration has been added
2284 /// to its lexical context, the corresponding DeclContext owns the
2285 /// declaration.
2286 ///
2287 /// If D is also a NamedDecl, it will be made visible within its
2288 /// semantic context via makeDeclVisibleInContext.
2289 void addDecl(Decl *D);
2290
2291 /// Add the declaration D into this context, but suppress
2292 /// searches for external declarations with the same name.
2293 ///
2294 /// Although analogous in function to addDecl, this removes an
2295 /// important check. This is only useful if the Decl is being
2296 /// added in response to an external search; in all other cases,
2297 /// addDecl() is the right function to use.
2298 /// See the ASTImporter for use cases.
2299 void addDeclInternal(Decl *D);
2300
2301 /// Add the declaration D to this context without modifying
2302 /// any lookup tables.
2303 ///
2304 /// This is useful for some operations in dependent contexts where
2305 /// the semantic context might not be dependent; this basically
2306 /// only happens with friends.
2307 void addHiddenDecl(Decl *D);
2308
2309 /// Removes a declaration from this context.
2310 void removeDecl(Decl *D);
2311
2312 /// Checks whether a declaration is in this context.
2313 bool containsDecl(Decl *D) const;
2314
2315 /// Checks whether a declaration is in this context.
2316 /// This also loads the Decls from the external source before the check.
2317 bool containsDeclAndLoad(Decl *D) const;
2318
2319 using lookup_result = DeclContextLookupResult;
2320 using lookup_iterator = lookup_result::iterator;
2321
2322 /// lookup - Find the declarations (if any) with the given Name in
2323 /// this context. Returns a range of iterators that contains all of
2324 /// the declarations with this name, with object, function, member,
2325 /// and enumerator names preceding any tag name. Note that this
2326 /// routine will not look into parent contexts.
2327 lookup_result lookup(DeclarationName Name) const;
2328
2329 /// Find the declarations with the given name that are visible
2330 /// within this context; don't attempt to retrieve anything from an
2331 /// external source.
2332 lookup_result noload_lookup(DeclarationName Name);
2333
2334 /// A simplistic name lookup mechanism that performs name lookup
2335 /// into this declaration context without consulting the external source.
2336 ///
2337 /// This function should almost never be used, because it subverts the
2338 /// usual relationship between a DeclContext and the external source.
2339 /// See the ASTImporter for the (few, but important) use cases.
2340 ///
2341 /// FIXME: This is very inefficient; replace uses of it with uses of
2342 /// noload_lookup.
2343 void localUncachedLookup(DeclarationName Name,
2344 SmallVectorImpl<NamedDecl *> &Results);
2345
2346 /// Makes a declaration visible within this context.
2347 ///
2348 /// This routine makes the declaration D visible to name lookup
2349 /// within this context and, if this is a transparent context,
2350 /// within its parent contexts up to the first enclosing
2351 /// non-transparent context. Making a declaration visible within a
2352 /// context does not transfer ownership of a declaration, and a
2353 /// declaration can be visible in many contexts that aren't its
2354 /// lexical context.
2355 ///
2356 /// If D is a redeclaration of an existing declaration that is
2357 /// visible from this context, as determined by
2358 /// NamedDecl::declarationReplaces, the previous declaration will be
2359 /// replaced with D.
2360 void makeDeclVisibleInContext(NamedDecl *D);
2361
2362 /// all_lookups_iterator - An iterator that provides a view over the results
2363 /// of looking up every possible name.
2364 class all_lookups_iterator;
2365
2366 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2367
2368 lookups_range lookups() const;
2369 // Like lookups(), but avoids loading external declarations.
2370 // If PreserveInternalState, avoids building lookup data structures too.
2371 lookups_range noload_lookups(bool PreserveInternalState) const;
2372
2373 /// Iterators over all possible lookups within this context.
2374 all_lookups_iterator lookups_begin() const;
2375 all_lookups_iterator lookups_end() const;
2376
2377 /// Iterators over all possible lookups within this context that are
2378 /// currently loaded; don't attempt to retrieve anything from an external
2379 /// source.
2380 all_lookups_iterator noload_lookups_begin() const;
2381 all_lookups_iterator noload_lookups_end() const;
2382
2383 struct udir_iterator;
2384
2385 using udir_iterator_base =
2386 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2387 typename lookup_iterator::iterator_category,
2388 UsingDirectiveDecl *>;
2389
2390 struct udir_iterator : udir_iterator_base {
2391 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2392
2393 UsingDirectiveDecl *operator*() const;
2394 };
2395
2396 using udir_range = llvm::iterator_range<udir_iterator>;
2397
2398 udir_range using_directives() const;
2399
2400 // These are all defined in DependentDiagnostic.h.
2401 class ddiag_iterator;
2402
2403 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2404
2405 inline ddiag_range ddiags() const;
2406
2407 // Low-level accessors
2408
2409 /// Mark that there are external lexical declarations that we need
2410 /// to include in our lookup table (and that are not available as external
2411 /// visible lookups). These extra lookup results will be found by walking
2412 /// the lexical declarations of this context. This should be used only if
2413 /// setHasExternalLexicalStorage() has been called on any decl context for
2414 /// which this is the primary context.
2415 void setMustBuildLookupTable() {
2416 assert(this == getPrimaryContext() &&(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 2417, __extension__ __PRETTY_FUNCTION__))
2417 "should only be called on primary context")(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include/clang/AST/DeclBase.h"
, 2417, __extension__ __PRETTY_FUNCTION__))
;
2418 DeclContextBits.HasLazyExternalLexicalLookups = true;
2419 }
2420
2421 /// Retrieve the internal representation of the lookup structure.
2422 /// This may omit some names if we are lazily building the structure.
2423 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2424
2425 /// Ensure the lookup structure is fully-built and return it.
2426 StoredDeclsMap *buildLookup();
2427
2428 /// Whether this DeclContext has external storage containing
2429 /// additional declarations that are lexically in this context.
2430 bool hasExternalLexicalStorage() const {
2431 return DeclContextBits.ExternalLexicalStorage;
2432 }
2433
2434 /// State whether this DeclContext has external storage for
2435 /// declarations lexically in this context.
2436 void setHasExternalLexicalStorage(bool ES = true) const {
2437 DeclContextBits.ExternalLexicalStorage = ES;
2438 }
2439
2440 /// Whether this DeclContext has external storage containing
2441 /// additional declarations that are visible in this context.
2442 bool hasExternalVisibleStorage() const {
2443 return DeclContextBits.ExternalVisibleStorage;
2444 }
2445
2446 /// State whether this DeclContext has external storage for
2447 /// declarations visible in this context.
2448 void setHasExternalVisibleStorage(bool ES = true) const {
2449 DeclContextBits.ExternalVisibleStorage = ES;
2450 if (ES && LookupPtr)
2451 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2452 }
2453
2454 /// Determine whether the given declaration is stored in the list of
2455 /// declarations lexically within this context.
2456 bool isDeclInLexicalTraversal(const Decl *D) const {
2457 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2458 D == LastDecl);
2459 }
2460
2461 bool setUseQualifiedLookup(bool use = true) const {
2462 bool old_value = DeclContextBits.UseQualifiedLookup;
2463 DeclContextBits.UseQualifiedLookup = use;
2464 return old_value;
2465 }
2466
2467 bool shouldUseQualifiedLookup() const {
2468 return DeclContextBits.UseQualifiedLookup;
2469 }
2470
2471 static bool classof(const Decl *D);
2472 static bool classof(const DeclContext *D) { return true; }
2473
2474 void dumpDeclContext() const;
2475 void dumpLookups() const;
2476 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2477 bool Deserialize = false) const;
2478
2479private:
2480 /// Whether this declaration context has had externally visible
2481 /// storage added since the last lookup. In this case, \c LookupPtr's
2482 /// invariant may not hold and needs to be fixed before we perform
2483 /// another lookup.
2484 bool hasNeedToReconcileExternalVisibleStorage() const {
2485 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2486 }
2487
2488 /// State that this declaration context has had externally visible
2489 /// storage added since the last lookup. In this case, \c LookupPtr's
2490 /// invariant may not hold and needs to be fixed before we perform
2491 /// another lookup.
2492 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2493 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2494 }
2495
2496 /// If \c true, this context may have local lexical declarations
2497 /// that are missing from the lookup table.
2498 bool hasLazyLocalLexicalLookups() const {
2499 return DeclContextBits.HasLazyLocalLexicalLookups;
2500 }
2501
2502 /// If \c true, this context may have local lexical declarations
2503 /// that are missing from the lookup table.
2504 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2505 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2506 }
2507
2508 /// If \c true, the external source may have lexical declarations
2509 /// that are missing from the lookup table.
2510 bool hasLazyExternalLexicalLookups() const {
2511 return DeclContextBits.HasLazyExternalLexicalLookups;
2512 }
2513
2514 /// If \c true, the external source may have lexical declarations
2515 /// that are missing from the lookup table.
2516 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2517 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2518 }
2519
2520 void reconcileExternalVisibleStorage() const;
2521 bool LoadLexicalDeclsFromExternalStorage() const;
2522
2523 /// Makes a declaration visible within this context, but
2524 /// suppresses searches for external declarations with the same
2525 /// name.
2526 ///
2527 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2528 /// use of addDeclInternal().
2529 void makeDeclVisibleInContextInternal(NamedDecl *D);
2530
2531 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2532
2533 void loadLazyLocalLexicalLookups();
2534 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2535 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2536 bool Rediscoverable);
2537 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2538};
2539
2540inline bool Decl::isTemplateParameter() const {
2541 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2542 getKind() == TemplateTemplateParm;
2543}
2544
2545// Specialization selected when ToTy is not a known subclass of DeclContext.
2546template <class ToTy,
2547 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2548struct cast_convert_decl_context {
2549 static const ToTy *doit(const DeclContext *Val) {
2550 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2551 }
2552
2553 static ToTy *doit(DeclContext *Val) {
2554 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2555 }
2556};
2557
2558// Specialization selected when ToTy is a known subclass of DeclContext.
2559template <class ToTy>
2560struct cast_convert_decl_context<ToTy, true> {
2561 static const ToTy *doit(const DeclContext *Val) {
2562 return static_cast<const ToTy*>(Val);
2563 }
2564
2565 static ToTy *doit(DeclContext *Val) {
2566 return static_cast<ToTy*>(Val);
2567 }
2568};
2569
2570} // namespace clang
2571
2572namespace llvm {
2573
2574/// isa<T>(DeclContext*)
2575template <typename To>
2576struct isa_impl<To, ::clang::DeclContext> {
2577 static bool doit(const ::clang::DeclContext &Val) {
2578 return To::classofKind(Val.getDeclKind());
2579 }
2580};
2581
2582/// cast<T>(DeclContext*)
2583template<class ToTy>
2584struct cast_convert_val<ToTy,
2585 const ::clang::DeclContext,const ::clang::DeclContext> {
2586 static const ToTy &doit(const ::clang::DeclContext &Val) {
2587 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2588 }
2589};
2590
2591template<class ToTy>
2592struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2593 static ToTy &doit(::clang::DeclContext &Val) {
2594 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2595 }
2596};
2597
2598template<class ToTy>
2599struct cast_convert_val<ToTy,
2600 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2601 static const ToTy *doit(const ::clang::DeclContext *Val) {
2602 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2603 }
2604};
2605
2606template<class ToTy>
2607struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2608 static ToTy *doit(::clang::DeclContext *Val) {
2609 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2610 }
2611};
2612
2613/// Implement cast_convert_val for Decl -> DeclContext conversions.
2614template<class FromTy>
2615struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2616 static ::clang::DeclContext &doit(const FromTy &Val) {
2617 return *FromTy::castToDeclContext(&Val);
2618 }
2619};
2620
2621template<class FromTy>
2622struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2623 static ::clang::DeclContext *doit(const FromTy *Val) {
2624 return FromTy::castToDeclContext(Val);
2625 }
2626};
2627
2628template<class FromTy>
2629struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2630 static const ::clang::DeclContext &doit(const FromTy &Val) {
2631 return *FromTy::castToDeclContext(&Val);
2632 }
2633};
2634
2635template<class FromTy>
2636struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2637 static const ::clang::DeclContext *doit(const FromTy *Val) {
2638 return FromTy::castToDeclContext(Val);
2639 }
2640};
2641
2642} // namespace llvm
2643
2644#endif // LLVM_CLANG_AST_DECLBASE_H

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