Bug Summary

File:clang/lib/StaticAnalyzer/Core/MemRegion.cpp
Warning:line 925, 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-13~++20210722111111+b115c038d2d4/build-llvm/tools/clang/lib/StaticAnalyzer/Core -resource-dir /usr/lib/llvm-13/lib/clang/13.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-13~++20210722111111+b115c038d2d4/build-llvm/tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include -I /build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/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-13/lib/clang/13.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-13~++20210722111111+b115c038d2d4/build-llvm/tools/clang/lib/StaticAnalyzer/Core -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4=. -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-07-23-023125-8721-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp

/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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 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 if (Size.isZeroConstant()) {
776 if (isa<ConstantArrayType>(Ty))
777 return UnknownVal();
778 }
779
780 return Size;
781 }
782 // FIXME: The following are being used in 'SimpleSValBuilder' and in
783 // 'ArrayBoundChecker::checkLocation' because there is no symbol to
784 // represent the regions more appropriately.
785 case MemRegion::BlockDataRegionKind:
786 case MemRegion::BlockCodeRegionKind:
787 case MemRegion::FunctionCodeRegionKind:
788 return nonloc::SymbolVal(SymMgr.getExtentSymbol(SR));
789 default:
790 llvm_unreachable("Unhandled region")::llvm::llvm_unreachable_internal("Unhandled region", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 790)
;
791 }
792}
793
794template <typename REG>
795const REG *MemRegionManager::LazyAllocate(REG*& region) {
796 if (!region) {
797 region = A.Allocate<REG>();
798 new (region) REG(*this);
799 }
800
801 return region;
802}
803
804template <typename REG, typename ARG>
805const REG *MemRegionManager::LazyAllocate(REG*& region, ARG a) {
806 if (!region) {
807 region = A.Allocate<REG>();
808 new (region) REG(this, a);
809 }
810
811 return region;
812}
813
814const StackLocalsSpaceRegion*
815MemRegionManager::getStackLocalsRegion(const StackFrameContext *STC) {
816 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 816, __extension__ __PRETTY_FUNCTION__))
;
817 StackLocalsSpaceRegion *&R = StackLocalsSpaceRegions[STC];
818
819 if (R)
820 return R;
821
822 R = A.Allocate<StackLocalsSpaceRegion>();
823 new (R) StackLocalsSpaceRegion(*this, STC);
824 return R;
825}
826
827const StackArgumentsSpaceRegion *
828MemRegionManager::getStackArgumentsRegion(const StackFrameContext *STC) {
829 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 829, __extension__ __PRETTY_FUNCTION__))
;
830 StackArgumentsSpaceRegion *&R = StackArgumentsSpaceRegions[STC];
831
832 if (R)
833 return R;
834
835 R = A.Allocate<StackArgumentsSpaceRegion>();
836 new (R) StackArgumentsSpaceRegion(*this, STC);
837 return R;
838}
839
840const GlobalsSpaceRegion
841*MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
842 const CodeTextRegion *CR) {
843 if (!CR) {
844 if (K == MemRegion::GlobalSystemSpaceRegionKind)
845 return LazyAllocate(SystemGlobals);
846 if (K == MemRegion::GlobalImmutableSpaceRegionKind)
847 return LazyAllocate(ImmutableGlobals);
848 assert(K == MemRegion::GlobalInternalSpaceRegionKind)(static_cast <bool> (K == MemRegion::GlobalInternalSpaceRegionKind
) ? void (0) : __assert_fail ("K == MemRegion::GlobalInternalSpaceRegionKind"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 848, __extension__ __PRETTY_FUNCTION__))
;
849 return LazyAllocate(InternalGlobals);
850 }
851
852 assert(K == MemRegion::StaticGlobalSpaceRegionKind)(static_cast <bool> (K == MemRegion::StaticGlobalSpaceRegionKind
) ? void (0) : __assert_fail ("K == MemRegion::StaticGlobalSpaceRegionKind"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 852, __extension__ __PRETTY_FUNCTION__))
;
853 StaticGlobalSpaceRegion *&R = StaticsGlobalSpaceRegions[CR];
854 if (R)
855 return R;
856
857 R = A.Allocate<StaticGlobalSpaceRegion>();
858 new (R) StaticGlobalSpaceRegion(*this, CR);
859 return R;
860}
861
862const HeapSpaceRegion *MemRegionManager::getHeapRegion() {
863 return LazyAllocate(heap);
864}
865
866const UnknownSpaceRegion *MemRegionManager::getUnknownRegion() {
867 return LazyAllocate(unknown);
868}
869
870const CodeSpaceRegion *MemRegionManager::getCodeRegion() {
871 return LazyAllocate(code);
872}
873
874//===----------------------------------------------------------------------===//
875// Constructing regions.
876//===----------------------------------------------------------------------===//
877
878const StringRegion *MemRegionManager::getStringRegion(const StringLiteral *Str){
879 return getSubRegion<StringRegion>(
880 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
881}
882
883const ObjCStringRegion *
884MemRegionManager::getObjCStringRegion(const ObjCStringLiteral *Str){
885 return getSubRegion<ObjCStringRegion>(
886 Str, cast<GlobalInternalSpaceRegion>(getGlobalsRegion()));
887}
888
889/// Look through a chain of LocationContexts to either find the
890/// StackFrameContext that matches a DeclContext, or find a VarRegion
891/// for a variable captured by a block.
892static llvm::PointerUnion<const StackFrameContext *, const VarRegion *>
893getStackOrCaptureRegionForDeclContext(const LocationContext *LC,
894 const DeclContext *DC,
895 const VarDecl *VD) {
896 while (LC) {
897 if (const auto *SFC = dyn_cast<StackFrameContext>(LC)) {
898 if (cast<DeclContext>(SFC->getDecl()) == DC)
899 return SFC;
900 }
901 if (const auto *BC = dyn_cast<BlockInvocationContext>(LC)) {
902 const auto *BR = static_cast<const BlockDataRegion *>(BC->getData());
903 // FIXME: This can be made more efficient.
904 for (BlockDataRegion::referenced_vars_iterator
905 I = BR->referenced_vars_begin(),
906 E = BR->referenced_vars_end(); I != E; ++I) {
907 const TypedValueRegion *OrigR = I.getOriginalRegion();
908 if (const auto *VR = dyn_cast<VarRegion>(OrigR)) {
909 if (VR->getDecl() == VD)
910 return cast<VarRegion>(I.getCapturedRegion());
911 }
912 }
913 }
914
915 LC = LC->getParent();
916 }
917 return (const StackFrameContext *)nullptr;
918}
919
920const VarRegion *MemRegionManager::getVarRegion(const VarDecl *D,
921 const LocationContext *LC) {
922 const auto *PVD = dyn_cast<ParmVarDecl>(D);
28
Assuming 'D' is a 'ParmVarDecl'
923 if (PVD
28.1
'PVD' is non-null
28.1
'PVD' is non-null
28.1
'PVD' is non-null
) {
29
Taking true branch
924 unsigned Index = PVD->getFunctionScopeIndex();
925 const StackFrameContext *SFC = LC->getStackFrame();
30
Called C++ object pointer is null
926 const Stmt *CallSite = SFC->getCallSite();
927 if (CallSite) {
928 const Decl *D = SFC->getDecl();
929 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
930 if (Index < FD->param_size() && FD->parameters()[Index] == PVD)
931 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
932 getStackArgumentsRegion(SFC));
933 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
934 if (Index < BD->param_size() && BD->parameters()[Index] == PVD)
935 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
936 getStackArgumentsRegion(SFC));
937 } else {
938 return getSubRegion<ParamVarRegion>(cast<Expr>(CallSite), Index,
939 getStackArgumentsRegion(SFC));
940 }
941 }
942 }
943
944 D = D->getCanonicalDecl();
945 const MemRegion *sReg = nullptr;
946
947 if (D->hasGlobalStorage() && !D->isStaticLocal()) {
948
949 // First handle the globals defined in system headers.
950 if (Ctx.getSourceManager().isInSystemHeader(D->getLocation())) {
951 // Whitelist the system globals which often DO GET modified, assume the
952 // rest are immutable.
953 if (D->getName().find("errno") != StringRef::npos)
954 sReg = getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
955 else
956 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
957
958 // Treat other globals as GlobalInternal unless they are constants.
959 } else {
960 QualType GQT = D->getType();
961 const Type *GT = GQT.getTypePtrOrNull();
962 // TODO: We could walk the complex types here and see if everything is
963 // constified.
964 if (GT && GQT.isConstQualified() && GT->isArithmeticType())
965 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
966 else
967 sReg = getGlobalsRegion();
968 }
969
970 // Finally handle static locals.
971 } else {
972 // FIXME: Once we implement scope handling, we will need to properly lookup
973 // 'D' to the proper LocationContext.
974 const DeclContext *DC = D->getDeclContext();
975 llvm::PointerUnion<const StackFrameContext *, const VarRegion *> V =
976 getStackOrCaptureRegionForDeclContext(LC, DC, D);
977
978 if (V.is<const VarRegion*>())
979 return V.get<const VarRegion*>();
980
981 const auto *STC = V.get<const StackFrameContext *>();
982
983 if (!STC) {
984 // FIXME: Assign a more sensible memory space to static locals
985 // we see from within blocks that we analyze as top-level declarations.
986 sReg = getUnknownRegion();
987 } else {
988 if (D->hasLocalStorage()) {
989 sReg = isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)
990 ? static_cast<const MemRegion*>(getStackArgumentsRegion(STC))
991 : static_cast<const MemRegion*>(getStackLocalsRegion(STC));
992 }
993 else {
994 assert(D->isStaticLocal())(static_cast <bool> (D->isStaticLocal()) ? void (0) :
__assert_fail ("D->isStaticLocal()", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 994, __extension__ __PRETTY_FUNCTION__))
;
995 const Decl *STCD = STC->getDecl();
996 if (isa<FunctionDecl>(STCD) || isa<ObjCMethodDecl>(STCD))
997 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
998 getFunctionCodeRegion(cast<NamedDecl>(STCD)));
999 else if (const auto *BD = dyn_cast<BlockDecl>(STCD)) {
1000 // FIXME: The fallback type here is totally bogus -- though it should
1001 // never be queried, it will prevent uniquing with the real
1002 // BlockCodeRegion. Ideally we'd fix the AST so that we always had a
1003 // signature.
1004 QualType T;
1005 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten())
1006 T = TSI->getType();
1007 if (T.isNull())
1008 T = getContext().VoidTy;
1009 if (!T->getAs<FunctionType>())
1010 T = getContext().getFunctionNoProtoType(T);
1011 T = getContext().getBlockPointerType(T);
1012
1013 const BlockCodeRegion *BTR =
1014 getBlockCodeRegion(BD, Ctx.getCanonicalType(T),
1015 STC->getAnalysisDeclContext());
1016 sReg = getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
1017 BTR);
1018 }
1019 else {
1020 sReg = getGlobalsRegion();
1021 }
1022 }
1023 }
1024 }
1025
1026 return getSubRegion<NonParamVarRegion>(D, sReg);
1027}
1028
1029const NonParamVarRegion *
1030MemRegionManager::getNonParamVarRegion(const VarDecl *D,
1031 const MemRegion *superR) {
1032 D = D->getCanonicalDecl();
1033 return getSubRegion<NonParamVarRegion>(D, superR);
1034}
1035
1036const ParamVarRegion *
1037MemRegionManager::getParamVarRegion(const Expr *OriginExpr, unsigned Index,
1038 const LocationContext *LC) {
1039 const StackFrameContext *SFC = LC->getStackFrame();
1040 assert(SFC)(static_cast <bool> (SFC) ? void (0) : __assert_fail ("SFC"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1040, __extension__ __PRETTY_FUNCTION__))
;
1041 return getSubRegion<ParamVarRegion>(OriginExpr, Index,
1042 getStackArgumentsRegion(SFC));
1043}
1044
1045const BlockDataRegion *
1046MemRegionManager::getBlockDataRegion(const BlockCodeRegion *BC,
1047 const LocationContext *LC,
1048 unsigned blockCount) {
1049 const MemSpaceRegion *sReg = nullptr;
1050 const BlockDecl *BD = BC->getDecl();
1051 if (!BD->hasCaptures()) {
1052 // This handles 'static' blocks.
1053 sReg = getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
1054 }
1055 else {
1056 if (LC) {
1057 // FIXME: Once we implement scope handling, we want the parent region
1058 // to be the scope.
1059 const StackFrameContext *STC = LC->getStackFrame();
1060 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1060, __extension__ __PRETTY_FUNCTION__))
;
1061 sReg = getStackLocalsRegion(STC);
1062 }
1063 else {
1064 // We allow 'LC' to be NULL for cases where want BlockDataRegions
1065 // without context-sensitivity.
1066 sReg = getUnknownRegion();
1067 }
1068 }
1069
1070 return getSubRegion<BlockDataRegion>(BC, LC, blockCount, sReg);
1071}
1072
1073const CXXTempObjectRegion *
1074MemRegionManager::getCXXStaticTempObjectRegion(const Expr *Ex) {
1075 return getSubRegion<CXXTempObjectRegion>(
1076 Ex, getGlobalsRegion(MemRegion::GlobalInternalSpaceRegionKind, nullptr));
1077}
1078
1079const CompoundLiteralRegion*
1080MemRegionManager::getCompoundLiteralRegion(const CompoundLiteralExpr *CL,
1081 const LocationContext *LC) {
1082 const MemSpaceRegion *sReg = nullptr;
1083
1084 if (CL->isFileScope())
1085 sReg = getGlobalsRegion();
1086 else {
1087 const StackFrameContext *STC = LC->getStackFrame();
1088 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1088, __extension__ __PRETTY_FUNCTION__))
;
1089 sReg = getStackLocalsRegion(STC);
1090 }
1091
1092 return getSubRegion<CompoundLiteralRegion>(CL, sReg);
1093}
1094
1095const ElementRegion*
1096MemRegionManager::getElementRegion(QualType elementType, NonLoc Idx,
1097 const SubRegion* superRegion,
1098 ASTContext &Ctx){
1099 QualType T = Ctx.getCanonicalType(elementType).getUnqualifiedType();
1100
1101 llvm::FoldingSetNodeID ID;
1102 ElementRegion::ProfileRegion(ID, T, Idx, superRegion);
1103
1104 void *InsertPos;
1105 MemRegion* data = Regions.FindNodeOrInsertPos(ID, InsertPos);
1106 auto *R = cast_or_null<ElementRegion>(data);
1107
1108 if (!R) {
1109 R = A.Allocate<ElementRegion>();
1110 new (R) ElementRegion(T, Idx, superRegion);
1111 Regions.InsertNode(R, InsertPos);
1112 }
1113
1114 return R;
1115}
1116
1117const FunctionCodeRegion *
1118MemRegionManager::getFunctionCodeRegion(const NamedDecl *FD) {
1119 // To think: should we canonicalize the declaration here?
1120 return getSubRegion<FunctionCodeRegion>(FD, getCodeRegion());
1121}
1122
1123const BlockCodeRegion *
1124MemRegionManager::getBlockCodeRegion(const BlockDecl *BD, CanQualType locTy,
1125 AnalysisDeclContext *AC) {
1126 return getSubRegion<BlockCodeRegion>(BD, locTy, AC, getCodeRegion());
1127}
1128
1129/// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
1130const SymbolicRegion *MemRegionManager::getSymbolicRegion(SymbolRef sym) {
1131 return getSubRegion<SymbolicRegion>(sym, getUnknownRegion());
1132}
1133
1134const SymbolicRegion *MemRegionManager::getSymbolicHeapRegion(SymbolRef Sym) {
1135 return getSubRegion<SymbolicRegion>(Sym, getHeapRegion());
1136}
1137
1138const FieldRegion*
1139MemRegionManager::getFieldRegion(const FieldDecl *d,
1140 const SubRegion* superRegion){
1141 return getSubRegion<FieldRegion>(d, superRegion);
1142}
1143
1144const ObjCIvarRegion*
1145MemRegionManager::getObjCIvarRegion(const ObjCIvarDecl *d,
1146 const SubRegion* superRegion) {
1147 return getSubRegion<ObjCIvarRegion>(d, superRegion);
1148}
1149
1150const CXXTempObjectRegion*
1151MemRegionManager::getCXXTempObjectRegion(Expr const *E,
1152 LocationContext const *LC) {
1153 const StackFrameContext *SFC = LC->getStackFrame();
1154 assert(SFC)(static_cast <bool> (SFC) ? void (0) : __assert_fail ("SFC"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1154, __extension__ __PRETTY_FUNCTION__))
;
1155 return getSubRegion<CXXTempObjectRegion>(E, getStackLocalsRegion(SFC));
1156}
1157
1158/// Checks whether \p BaseClass is a valid virtual or direct non-virtual base
1159/// class of the type of \p Super.
1160static bool isValidBaseClass(const CXXRecordDecl *BaseClass,
1161 const TypedValueRegion *Super,
1162 bool IsVirtual) {
1163 BaseClass = BaseClass->getCanonicalDecl();
1164
1165 const CXXRecordDecl *Class = Super->getValueType()->getAsCXXRecordDecl();
1166 if (!Class)
1167 return true;
1168
1169 if (IsVirtual)
1170 return Class->isVirtuallyDerivedFrom(BaseClass);
1171
1172 for (const auto &I : Class->bases()) {
1173 if (I.getType()->getAsCXXRecordDecl()->getCanonicalDecl() == BaseClass)
1174 return true;
1175 }
1176
1177 return false;
1178}
1179
1180const CXXBaseObjectRegion *
1181MemRegionManager::getCXXBaseObjectRegion(const CXXRecordDecl *RD,
1182 const SubRegion *Super,
1183 bool IsVirtual) {
1184 if (isa<TypedValueRegion>(Super)) {
1185 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-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1185, __extension__ __PRETTY_FUNCTION__))
;
1186 (void)&isValidBaseClass;
1187
1188 if (IsVirtual) {
1189 // Virtual base regions should not be layered, since the layout rules
1190 // are different.
1191 while (const auto *Base = dyn_cast<CXXBaseObjectRegion>(Super))
1192 Super = cast<SubRegion>(Base->getSuperRegion());
1193 assert(Super && !isa<MemSpaceRegion>(Super))(static_cast <bool> (Super && !isa<MemSpaceRegion
>(Super)) ? void (0) : __assert_fail ("Super && !isa<MemSpaceRegion>(Super)"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1193, __extension__ __PRETTY_FUNCTION__))
;
1194 }
1195 }
1196
1197 return getSubRegion<CXXBaseObjectRegion>(RD, IsVirtual, Super);
1198}
1199
1200const CXXDerivedObjectRegion *
1201MemRegionManager::getCXXDerivedObjectRegion(const CXXRecordDecl *RD,
1202 const SubRegion *Super) {
1203 return getSubRegion<CXXDerivedObjectRegion>(RD, Super);
1204}
1205
1206const CXXThisRegion*
1207MemRegionManager::getCXXThisRegion(QualType thisPointerTy,
1208 const LocationContext *LC) {
1209 const auto *PT = thisPointerTy->getAs<PointerType>();
1210 assert(PT)(static_cast <bool> (PT) ? void (0) : __assert_fail ("PT"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1210, __extension__ __PRETTY_FUNCTION__))
;
1211 // Inside the body of the operator() of a lambda a this expr might refer to an
1212 // object in one of the parent location contexts.
1213 const auto *D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1214 // FIXME: when operator() of lambda is analyzed as a top level function and
1215 // 'this' refers to a this to the enclosing scope, there is no right region to
1216 // return.
1217 while (!LC->inTopFrame() && (!D || D->isStatic() ||
1218 PT != D->getThisType()->getAs<PointerType>())) {
1219 LC = LC->getParent();
1220 D = dyn_cast<CXXMethodDecl>(LC->getDecl());
1221 }
1222 const StackFrameContext *STC = LC->getStackFrame();
1223 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1223, __extension__ __PRETTY_FUNCTION__))
;
1224 return getSubRegion<CXXThisRegion>(PT, getStackArgumentsRegion(STC));
1225}
1226
1227const AllocaRegion*
1228MemRegionManager::getAllocaRegion(const Expr *E, unsigned cnt,
1229 const LocationContext *LC) {
1230 const StackFrameContext *STC = LC->getStackFrame();
1231 assert(STC)(static_cast <bool> (STC) ? void (0) : __assert_fail ("STC"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1231, __extension__ __PRETTY_FUNCTION__))
;
1232 return getSubRegion<AllocaRegion>(E, cnt, getStackLocalsRegion(STC));
1233}
1234
1235const MemSpaceRegion *MemRegion::getMemorySpace() const {
1236 const MemRegion *R = this;
1237 const auto *SR = dyn_cast<SubRegion>(this);
1238
1239 while (SR) {
1240 R = SR->getSuperRegion();
1241 SR = dyn_cast<SubRegion>(R);
1242 }
1243
1244 return dyn_cast<MemSpaceRegion>(R);
1245}
1246
1247bool MemRegion::hasStackStorage() const {
1248 return isa<StackSpaceRegion>(getMemorySpace());
1249}
1250
1251bool MemRegion::hasStackNonParametersStorage() const {
1252 return isa<StackLocalsSpaceRegion>(getMemorySpace());
1253}
1254
1255bool MemRegion::hasStackParametersStorage() const {
1256 return isa<StackArgumentsSpaceRegion>(getMemorySpace());
1257}
1258
1259bool MemRegion::hasGlobalsOrParametersStorage() const {
1260 const MemSpaceRegion *MS = getMemorySpace();
1261 return isa<StackArgumentsSpaceRegion>(MS) ||
1262 isa<GlobalsSpaceRegion>(MS);
1263}
1264
1265// getBaseRegion strips away all elements and fields, and get the base region
1266// of them.
1267const MemRegion *MemRegion::getBaseRegion() const {
1268 const MemRegion *R = this;
1269 while (true) {
1270 switch (R->getKind()) {
1271 case MemRegion::ElementRegionKind:
1272 case MemRegion::FieldRegionKind:
1273 case MemRegion::ObjCIvarRegionKind:
1274 case MemRegion::CXXBaseObjectRegionKind:
1275 case MemRegion::CXXDerivedObjectRegionKind:
1276 R = cast<SubRegion>(R)->getSuperRegion();
1277 continue;
1278 default:
1279 break;
1280 }
1281 break;
1282 }
1283 return R;
1284}
1285
1286// getgetMostDerivedObjectRegion gets the region of the root class of a C++
1287// class hierarchy.
1288const MemRegion *MemRegion::getMostDerivedObjectRegion() const {
1289 const MemRegion *R = this;
1290 while (const auto *BR = dyn_cast<CXXBaseObjectRegion>(R))
1291 R = BR->getSuperRegion();
1292 return R;
1293}
1294
1295bool MemRegion::isSubRegionOf(const MemRegion *) const {
1296 return false;
1297}
1298
1299//===----------------------------------------------------------------------===//
1300// View handling.
1301//===----------------------------------------------------------------------===//
1302
1303const MemRegion *MemRegion::StripCasts(bool StripBaseAndDerivedCasts) const {
1304 const MemRegion *R = this;
1305 while (true) {
1306 switch (R->getKind()) {
1307 case ElementRegionKind: {
1308 const auto *ER = cast<ElementRegion>(R);
1309 if (!ER->getIndex().isZeroConstant())
1310 return R;
1311 R = ER->getSuperRegion();
1312 break;
1313 }
1314 case CXXBaseObjectRegionKind:
1315 case CXXDerivedObjectRegionKind:
1316 if (!StripBaseAndDerivedCasts)
1317 return R;
1318 R = cast<TypedValueRegion>(R)->getSuperRegion();
1319 break;
1320 default:
1321 return R;
1322 }
1323 }
1324}
1325
1326const SymbolicRegion *MemRegion::getSymbolicBase() const {
1327 const auto *SubR = dyn_cast<SubRegion>(this);
1328
1329 while (SubR) {
1330 if (const auto *SymR = dyn_cast<SymbolicRegion>(SubR))
1331 return SymR;
1332 SubR = dyn_cast<SubRegion>(SubR->getSuperRegion());
1333 }
1334 return nullptr;
1335}
1336
1337RegionRawOffset ElementRegion::getAsArrayOffset() const {
1338 int64_t offset = 0;
1339 const ElementRegion *ER = this;
1340 const MemRegion *superR = nullptr;
1341 ASTContext &C = getContext();
1342
1343 // FIXME: Handle multi-dimensional arrays.
1344
1345 while (ER) {
1346 superR = ER->getSuperRegion();
1347
1348 // FIXME: generalize to symbolic offsets.
1349 SVal index = ER->getIndex();
1350 if (auto CI = index.getAs<nonloc::ConcreteInt>()) {
1351 // Update the offset.
1352 int64_t i = CI->getValue().getSExtValue();
1353
1354 if (i != 0) {
1355 QualType elemType = ER->getElementType();
1356
1357 // If we are pointing to an incomplete type, go no further.
1358 if (elemType->isIncompleteType()) {
1359 superR = ER;
1360 break;
1361 }
1362
1363 int64_t size = C.getTypeSizeInChars(elemType).getQuantity();
1364 if (auto NewOffset = llvm::checkedMulAdd(i, size, offset)) {
1365 offset = *NewOffset;
1366 } else {
1367 LLVM_DEBUG(llvm::dbgs() << "MemRegion::getAsArrayOffset: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("MemRegion")) { llvm::dbgs() << "MemRegion::getAsArrayOffset: "
<< "offset overflowing, returning unknown\n"; } } while
(false)
1368 << "offset overflowing, returning unknown\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("MemRegion")) { llvm::dbgs() << "MemRegion::getAsArrayOffset: "
<< "offset overflowing, returning unknown\n"; } } while
(false)
;
1369
1370 return nullptr;
1371 }
1372 }
1373
1374 // Go to the next ElementRegion (if any).
1375 ER = dyn_cast<ElementRegion>(superR);
1376 continue;
1377 }
1378
1379 return nullptr;
1380 }
1381
1382 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-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1382, __extension__ __PRETTY_FUNCTION__))
;
1383 return RegionRawOffset(superR, CharUnits::fromQuantity(offset));
1384}
1385
1386/// Returns true if \p Base is an immediate base class of \p Child
1387static bool isImmediateBase(const CXXRecordDecl *Child,
1388 const CXXRecordDecl *Base) {
1389 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-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1389, __extension__ __PRETTY_FUNCTION__))
;
1390 // Note that we do NOT canonicalize the base class here, because
1391 // ASTRecordLayout doesn't either. If that leads us down the wrong path,
1392 // so be it; at least we won't crash.
1393 for (const auto &I : Child->bases()) {
1394 if (I.getType()->getAsCXXRecordDecl() == Base)
1395 return true;
1396 }
1397
1398 return false;
1399}
1400
1401static RegionOffset calculateOffset(const MemRegion *R) {
1402 const MemRegion *SymbolicOffsetBase = nullptr;
1403 int64_t Offset = 0;
1404
1405 while (true) {
1406 switch (R->getKind()) {
1407 case MemRegion::CodeSpaceRegionKind:
1408 case MemRegion::StackLocalsSpaceRegionKind:
1409 case MemRegion::StackArgumentsSpaceRegionKind:
1410 case MemRegion::HeapSpaceRegionKind:
1411 case MemRegion::UnknownSpaceRegionKind:
1412 case MemRegion::StaticGlobalSpaceRegionKind:
1413 case MemRegion::GlobalInternalSpaceRegionKind:
1414 case MemRegion::GlobalSystemSpaceRegionKind:
1415 case MemRegion::GlobalImmutableSpaceRegionKind:
1416 // Stores can bind directly to a region space to set a default value.
1417 assert(Offset == 0 && !SymbolicOffsetBase)(static_cast <bool> (Offset == 0 && !SymbolicOffsetBase
) ? void (0) : __assert_fail ("Offset == 0 && !SymbolicOffsetBase"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1417, __extension__ __PRETTY_FUNCTION__))
;
1418 goto Finish;
1419
1420 case MemRegion::FunctionCodeRegionKind:
1421 case MemRegion::BlockCodeRegionKind:
1422 case MemRegion::BlockDataRegionKind:
1423 // These will never have bindings, but may end up having values requested
1424 // if the user does some strange casting.
1425 if (Offset != 0)
1426 SymbolicOffsetBase = R;
1427 goto Finish;
1428
1429 case MemRegion::SymbolicRegionKind:
1430 case MemRegion::AllocaRegionKind:
1431 case MemRegion::CompoundLiteralRegionKind:
1432 case MemRegion::CXXThisRegionKind:
1433 case MemRegion::StringRegionKind:
1434 case MemRegion::ObjCStringRegionKind:
1435 case MemRegion::NonParamVarRegionKind:
1436 case MemRegion::ParamVarRegionKind:
1437 case MemRegion::CXXTempObjectRegionKind:
1438 // Usual base regions.
1439 goto Finish;
1440
1441 case MemRegion::ObjCIvarRegionKind:
1442 // This is a little strange, but it's a compromise between
1443 // ObjCIvarRegions having unknown compile-time offsets (when using the
1444 // non-fragile runtime) and yet still being distinct, non-overlapping
1445 // regions. Thus we treat them as "like" base regions for the purposes
1446 // of computing offsets.
1447 goto Finish;
1448
1449 case MemRegion::CXXBaseObjectRegionKind: {
1450 const auto *BOR = cast<CXXBaseObjectRegion>(R);
1451 R = BOR->getSuperRegion();
1452
1453 QualType Ty;
1454 bool RootIsSymbolic = false;
1455 if (const auto *TVR = dyn_cast<TypedValueRegion>(R)) {
1456 Ty = TVR->getDesugaredValueType(R->getContext());
1457 } else if (const auto *SR = dyn_cast<SymbolicRegion>(R)) {
1458 // If our base region is symbolic, we don't know what type it really is.
1459 // Pretend the type of the symbol is the true dynamic type.
1460 // (This will at least be self-consistent for the life of the symbol.)
1461 Ty = SR->getSymbol()->getType()->getPointeeType();
1462 RootIsSymbolic = true;
1463 }
1464
1465 const CXXRecordDecl *Child = Ty->getAsCXXRecordDecl();
1466 if (!Child) {
1467 // We cannot compute the offset of the base class.
1468 SymbolicOffsetBase = R;
1469 } else {
1470 if (RootIsSymbolic) {
1471 // Base layers on symbolic regions may not be type-correct.
1472 // Double-check the inheritance here, and revert to a symbolic offset
1473 // if it's invalid (e.g. due to a reinterpret_cast).
1474 if (BOR->isVirtual()) {
1475 if (!Child->isVirtuallyDerivedFrom(BOR->getDecl()))
1476 SymbolicOffsetBase = R;
1477 } else {
1478 if (!isImmediateBase(Child, BOR->getDecl()))
1479 SymbolicOffsetBase = R;
1480 }
1481 }
1482 }
1483
1484 // Don't bother calculating precise offsets if we already have a
1485 // symbolic offset somewhere in the chain.
1486 if (SymbolicOffsetBase)
1487 continue;
1488
1489 CharUnits BaseOffset;
1490 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(Child);
1491 if (BOR->isVirtual())
1492 BaseOffset = Layout.getVBaseClassOffset(BOR->getDecl());
1493 else
1494 BaseOffset = Layout.getBaseClassOffset(BOR->getDecl());
1495
1496 // The base offset is in chars, not in bits.
1497 Offset += BaseOffset.getQuantity() * R->getContext().getCharWidth();
1498 break;
1499 }
1500
1501 case MemRegion::CXXDerivedObjectRegionKind: {
1502 // TODO: Store the base type in the CXXDerivedObjectRegion and use it.
1503 goto Finish;
1504 }
1505
1506 case MemRegion::ElementRegionKind: {
1507 const auto *ER = cast<ElementRegion>(R);
1508 R = ER->getSuperRegion();
1509
1510 QualType EleTy = ER->getValueType();
1511 if (EleTy->isIncompleteType()) {
1512 // We cannot compute the offset of the base class.
1513 SymbolicOffsetBase = R;
1514 continue;
1515 }
1516
1517 SVal Index = ER->getIndex();
1518 if (Optional<nonloc::ConcreteInt> CI =
1519 Index.getAs<nonloc::ConcreteInt>()) {
1520 // Don't bother calculating precise offsets if we already have a
1521 // symbolic offset somewhere in the chain.
1522 if (SymbolicOffsetBase)
1523 continue;
1524
1525 int64_t i = CI->getValue().getSExtValue();
1526 // This type size is in bits.
1527 Offset += i * R->getContext().getTypeSize(EleTy);
1528 } else {
1529 // We cannot compute offset for non-concrete index.
1530 SymbolicOffsetBase = R;
1531 }
1532 break;
1533 }
1534 case MemRegion::FieldRegionKind: {
1535 const auto *FR = cast<FieldRegion>(R);
1536 R = FR->getSuperRegion();
1537 assert(R)(static_cast <bool> (R) ? void (0) : __assert_fail ("R"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1537, __extension__ __PRETTY_FUNCTION__))
;
1538
1539 const RecordDecl *RD = FR->getDecl()->getParent();
1540 if (RD->isUnion() || !RD->isCompleteDefinition()) {
1541 // We cannot compute offset for incomplete type.
1542 // For unions, we could treat everything as offset 0, but we'd rather
1543 // treat each field as a symbolic offset so they aren't stored on top
1544 // of each other, since we depend on things in typed regions actually
1545 // matching their types.
1546 SymbolicOffsetBase = R;
1547 }
1548
1549 // Don't bother calculating precise offsets if we already have a
1550 // symbolic offset somewhere in the chain.
1551 if (SymbolicOffsetBase)
1552 continue;
1553
1554 // Get the field number.
1555 unsigned idx = 0;
1556 for (RecordDecl::field_iterator FI = RD->field_begin(),
1557 FE = RD->field_end(); FI != FE; ++FI, ++idx) {
1558 if (FR->getDecl() == *FI)
1559 break;
1560 }
1561 const ASTRecordLayout &Layout = R->getContext().getASTRecordLayout(RD);
1562 // This is offset in bits.
1563 Offset += Layout.getFieldOffset(idx);
1564 break;
1565 }
1566 }
1567 }
1568
1569 Finish:
1570 if (SymbolicOffsetBase)
1571 return RegionOffset(SymbolicOffsetBase, RegionOffset::Symbolic);
1572 return RegionOffset(R, Offset);
1573}
1574
1575RegionOffset MemRegion::getAsOffset() const {
1576 if (!cachedOffset)
1577 cachedOffset = calculateOffset(this);
1578 return *cachedOffset;
1579}
1580
1581//===----------------------------------------------------------------------===//
1582// BlockDataRegion
1583//===----------------------------------------------------------------------===//
1584
1585std::pair<const VarRegion *, const VarRegion *>
1586BlockDataRegion::getCaptureRegions(const VarDecl *VD) {
1587 MemRegionManager &MemMgr = getMemRegionManager();
9
Value assigned to field 'LC'
1588 const VarRegion *VR = nullptr;
1589 const VarRegion *OriginalVR = nullptr;
1590
1591 if (!VD->hasAttr<BlocksAttr>() && VD->hasLocalStorage()) {
10
Calling 'Decl::hasAttr'
13
Returning from 'Decl::hasAttr'
14
Calling 'VarDecl::hasLocalStorage'
21
Returning from 'VarDecl::hasLocalStorage'
22
Taking false branch
1592 VR = MemMgr.getNonParamVarRegion(VD, this);
1593 OriginalVR = MemMgr.getVarRegion(VD, LC);
1594 }
1595 else {
1596 if (LC) {
23
Assuming pointer value is null
24
Assuming field 'LC' is null
25
Taking false branch
1597 VR = MemMgr.getVarRegion(VD, LC);
1598 OriginalVR = VR;
1599 }
1600 else {
1601 VR = MemMgr.getNonParamVarRegion(VD, MemMgr.getUnknownRegion());
1602 OriginalVR = MemMgr.getVarRegion(VD, LC);
26
Passing null pointer value via 2nd parameter 'LC'
27
Calling 'MemRegionManager::getVarRegion'
1603 }
1604 }
1605 return std::make_pair(VR, OriginalVR);
1606}
1607
1608void BlockDataRegion::LazyInitializeReferencedVars() {
1609 if (ReferencedVars)
3
Assuming field 'ReferencedVars' is null
4
Taking false branch
1610 return;
1611
1612 AnalysisDeclContext *AC = getCodeRegion()->getAnalysisDeclContext();
1613 const auto &ReferencedBlockVars = AC->getReferencedBlockVars(BC->getDecl());
1614 auto NumBlockVars =
1615 std::distance(ReferencedBlockVars.begin(), ReferencedBlockVars.end());
1616
1617 if (NumBlockVars == 0) {
5
Assuming 'NumBlockVars' is not equal to 0
6
Taking false branch
1618 ReferencedVars = (void*) 0x1;
1619 return;
1620 }
1621
1622 MemRegionManager &MemMgr = getMemRegionManager();
1623 llvm::BumpPtrAllocator &A = MemMgr.getAllocator();
1624 BumpVectorContext BC(A);
1625
1626 using VarVec = BumpVector<const MemRegion *>;
1627
1628 auto *BV = A.Allocate<VarVec>();
1629 new (BV) VarVec(BC, NumBlockVars);
1630 auto *BVOriginal = A.Allocate<VarVec>();
1631 new (BVOriginal) VarVec(BC, NumBlockVars);
1632
1633 for (const auto *VD : ReferencedBlockVars) {
7
Assuming '__begin1' is not equal to '__end1'
1634 const VarRegion *VR = nullptr;
1635 const VarRegion *OriginalVR = nullptr;
1636 std::tie(VR, OriginalVR) = getCaptureRegions(VD);
8
Calling 'BlockDataRegion::getCaptureRegions'
1637 assert(VR)(static_cast <bool> (VR) ? void (0) : __assert_fail ("VR"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1637, __extension__ __PRETTY_FUNCTION__))
;
1638 assert(OriginalVR)(static_cast <bool> (OriginalVR) ? void (0) : __assert_fail
("OriginalVR", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1638, __extension__ __PRETTY_FUNCTION__))
;
1639 BV->push_back(VR, BC);
1640 BVOriginal->push_back(OriginalVR, BC);
1641 }
1642
1643 ReferencedVars = BV;
1644 OriginalVars = BVOriginal;
1645}
1646
1647BlockDataRegion::referenced_vars_iterator
1648BlockDataRegion::referenced_vars_begin() const {
1649 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
2
Calling 'BlockDataRegion::LazyInitializeReferencedVars'
1650
1651 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1652
1653 if (Vec == (void*) 0x1)
1654 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1655
1656 auto *VecOriginal =
1657 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1658
1659 return BlockDataRegion::referenced_vars_iterator(Vec->begin(),
1660 VecOriginal->begin());
1661}
1662
1663BlockDataRegion::referenced_vars_iterator
1664BlockDataRegion::referenced_vars_end() const {
1665 const_cast<BlockDataRegion*>(this)->LazyInitializeReferencedVars();
1666
1667 auto *Vec = static_cast<BumpVector<const MemRegion *> *>(ReferencedVars);
1668
1669 if (Vec == (void*) 0x1)
1670 return BlockDataRegion::referenced_vars_iterator(nullptr, nullptr);
1671
1672 auto *VecOriginal =
1673 static_cast<BumpVector<const MemRegion *> *>(OriginalVars);
1674
1675 return BlockDataRegion::referenced_vars_iterator(Vec->end(),
1676 VecOriginal->end());
1677}
1678
1679const VarRegion *BlockDataRegion::getOriginalRegion(const VarRegion *R) const {
1680 for (referenced_vars_iterator I = referenced_vars_begin(),
1
Calling 'BlockDataRegion::referenced_vars_begin'
1681 E = referenced_vars_end();
1682 I != E; ++I) {
1683 if (I.getCapturedRegion() == R)
1684 return I.getOriginalRegion();
1685 }
1686 return nullptr;
1687}
1688
1689//===----------------------------------------------------------------------===//
1690// RegionAndSymbolInvalidationTraits
1691//===----------------------------------------------------------------------===//
1692
1693void RegionAndSymbolInvalidationTraits::setTrait(SymbolRef Sym,
1694 InvalidationKinds IK) {
1695 SymTraitsMap[Sym] |= IK;
1696}
1697
1698void RegionAndSymbolInvalidationTraits::setTrait(const MemRegion *MR,
1699 InvalidationKinds IK) {
1700 assert(MR)(static_cast <bool> (MR) ? void (0) : __assert_fail ("MR"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/lib/StaticAnalyzer/Core/MemRegion.cpp"
, 1700, __extension__ __PRETTY_FUNCTION__))
;
1701 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1702 setTrait(SR->getSymbol(), IK);
1703 else
1704 MRTraitsMap[MR] |= IK;
1705}
1706
1707bool RegionAndSymbolInvalidationTraits::hasTrait(SymbolRef Sym,
1708 InvalidationKinds IK) const {
1709 const_symbol_iterator I = SymTraitsMap.find(Sym);
1710 if (I != SymTraitsMap.end())
1711 return I->second & IK;
1712
1713 return false;
1714}
1715
1716bool RegionAndSymbolInvalidationTraits::hasTrait(const MemRegion *MR,
1717 InvalidationKinds IK) const {
1718 if (!MR)
1719 return false;
1720
1721 if (const auto *SR = dyn_cast<SymbolicRegion>(MR))
1722 return hasTrait(SR->getSymbol(), IK);
1723
1724 const_region_iterator I = MRTraitsMap.find(MR);
1725 if (I != MRTraitsMap.end())
1726 return I->second & IK;
1727
1728 return false;
1729}

/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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 /// getPrimaryContext - There may be many different
2001 /// declarations of the same entity (including forward declarations
2002 /// of classes, multiple definitions of namespaces, etc.), each with
2003 /// a different set of declarations. This routine returns the
2004 /// "primary" DeclContext structure, which will contain the
2005 /// information needed to perform name lookup into this context.
2006 DeclContext *getPrimaryContext();
2007 const DeclContext *getPrimaryContext() const {
2008 return const_cast<DeclContext*>(this)->getPrimaryContext();
2009 }
2010
2011 /// getRedeclContext - Retrieve the context in which an entity conflicts with
2012 /// other entities of the same name, or where it is a redeclaration if the
2013 /// two entities are compatible. This skips through transparent contexts.
2014 DeclContext *getRedeclContext();
2015 const DeclContext *getRedeclContext() const {
2016 return const_cast<DeclContext *>(this)->getRedeclContext();
2017 }
2018
2019 /// Retrieve the nearest enclosing namespace context.
2020 DeclContext *getEnclosingNamespaceContext();
2021 const DeclContext *getEnclosingNamespaceContext() const {
2022 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
2023 }
2024
2025 /// Retrieve the outermost lexically enclosing record context.
2026 RecordDecl *getOuterLexicalRecordContext();
2027 const RecordDecl *getOuterLexicalRecordContext() const {
2028 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
2029 }
2030
2031 /// Test if this context is part of the enclosing namespace set of
2032 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
2033 /// isn't a namespace, this is equivalent to Equals().
2034 ///
2035 /// The enclosing namespace set of a namespace is the namespace and, if it is
2036 /// inline, its enclosing namespace, recursively.
2037 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
2038
2039 /// Collects all of the declaration contexts that are semantically
2040 /// connected to this declaration context.
2041 ///
2042 /// For declaration contexts that have multiple semantically connected but
2043 /// syntactically distinct contexts, such as C++ namespaces, this routine
2044 /// retrieves the complete set of such declaration contexts in source order.
2045 /// For example, given:
2046 ///
2047 /// \code
2048 /// namespace N {
2049 /// int x;
2050 /// }
2051 /// namespace N {
2052 /// int y;
2053 /// }
2054 /// \endcode
2055 ///
2056 /// The \c Contexts parameter will contain both definitions of N.
2057 ///
2058 /// \param Contexts Will be cleared and set to the set of declaration
2059 /// contexts that are semanticaly connected to this declaration context,
2060 /// in source order, including this context (which may be the only result,
2061 /// for non-namespace contexts).
2062 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2063
2064 /// decl_iterator - Iterates through the declarations stored
2065 /// within this context.
2066 class decl_iterator {
2067 /// Current - The current declaration.
2068 Decl *Current = nullptr;
2069
2070 public:
2071 using value_type = Decl *;
2072 using reference = const value_type &;
2073 using pointer = const value_type *;
2074 using iterator_category = std::forward_iterator_tag;
2075 using difference_type = std::ptrdiff_t;
2076
2077 decl_iterator() = default;
2078 explicit decl_iterator(Decl *C) : Current(C) {}
2079
2080 reference operator*() const { return Current; }
2081
2082 // This doesn't meet the iterator requirements, but it's convenient
2083 value_type operator->() const { return Current; }
2084
2085 decl_iterator& operator++() {
2086 Current = Current->getNextDeclInContext();
2087 return *this;
2088 }
2089
2090 decl_iterator operator++(int) {
2091 decl_iterator tmp(*this);
2092 ++(*this);
2093 return tmp;
2094 }
2095
2096 friend bool operator==(decl_iterator x, decl_iterator y) {
2097 return x.Current == y.Current;
2098 }
2099
2100 friend bool operator!=(decl_iterator x, decl_iterator y) {
2101 return x.Current != y.Current;
2102 }
2103 };
2104
2105 using decl_range = llvm::iterator_range<decl_iterator>;
2106
2107 /// decls_begin/decls_end - Iterate over the declarations stored in
2108 /// this context.
2109 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2110 decl_iterator decls_begin() const;
2111 decl_iterator decls_end() const { return decl_iterator(); }
2112 bool decls_empty() const;
2113
2114 /// noload_decls_begin/end - Iterate over the declarations stored in this
2115 /// context that are currently loaded; don't attempt to retrieve anything
2116 /// from an external source.
2117 decl_range noload_decls() const {
2118 return decl_range(noload_decls_begin(), noload_decls_end());
2119 }
2120 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2121 decl_iterator noload_decls_end() const { return decl_iterator(); }
2122
2123 /// specific_decl_iterator - Iterates over a subrange of
2124 /// declarations stored in a DeclContext, providing only those that
2125 /// are of type SpecificDecl (or a class derived from it). This
2126 /// iterator is used, for example, to provide iteration over just
2127 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2128 template<typename SpecificDecl>
2129 class specific_decl_iterator {
2130 /// Current - The current, underlying declaration iterator, which
2131 /// will either be NULL or will point to a declaration of
2132 /// type SpecificDecl.
2133 DeclContext::decl_iterator Current;
2134
2135 /// SkipToNextDecl - Advances the current position up to the next
2136 /// declaration of type SpecificDecl that also meets the criteria
2137 /// required by Acceptable.
2138 void SkipToNextDecl() {
2139 while (*Current && !isa<SpecificDecl>(*Current))
2140 ++Current;
2141 }
2142
2143 public:
2144 using value_type = SpecificDecl *;
2145 // TODO: Add reference and pointer types (with some appropriate proxy type)
2146 // if we ever have a need for them.
2147 using reference = void;
2148 using pointer = void;
2149 using difference_type =
2150 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2151 using iterator_category = std::forward_iterator_tag;
2152
2153 specific_decl_iterator() = default;
2154
2155 /// specific_decl_iterator - Construct a new iterator over a
2156 /// subset of the declarations the range [C,
2157 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2158 /// member function of SpecificDecl that should return true for
2159 /// all of the SpecificDecl instances that will be in the subset
2160 /// of iterators. For example, if you want Objective-C instance
2161 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2162 /// &ObjCMethodDecl::isInstanceMethod.
2163 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2164 SkipToNextDecl();
2165 }
2166
2167 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2168
2169 // This doesn't meet the iterator requirements, but it's convenient
2170 value_type operator->() const { return **this; }
2171
2172 specific_decl_iterator& operator++() {
2173 ++Current;
2174 SkipToNextDecl();
2175 return *this;
2176 }
2177
2178 specific_decl_iterator operator++(int) {
2179 specific_decl_iterator tmp(*this);
2180 ++(*this);
2181 return tmp;
2182 }
2183
2184 friend bool operator==(const specific_decl_iterator& x,
2185 const specific_decl_iterator& y) {
2186 return x.Current == y.Current;
2187 }
2188
2189 friend bool operator!=(const specific_decl_iterator& x,
2190 const specific_decl_iterator& y) {
2191 return x.Current != y.Current;
2192 }
2193 };
2194
2195 /// Iterates over a filtered subrange of declarations stored
2196 /// in a DeclContext.
2197 ///
2198 /// This iterator visits only those declarations that are of type
2199 /// SpecificDecl (or a class derived from it) and that meet some
2200 /// additional run-time criteria. This iterator is used, for
2201 /// example, to provide access to the instance methods within an
2202 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2203 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2204 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2205 class filtered_decl_iterator {
2206 /// Current - The current, underlying declaration iterator, which
2207 /// will either be NULL or will point to a declaration of
2208 /// type SpecificDecl.
2209 DeclContext::decl_iterator Current;
2210
2211 /// SkipToNextDecl - Advances the current position up to the next
2212 /// declaration of type SpecificDecl that also meets the criteria
2213 /// required by Acceptable.
2214 void SkipToNextDecl() {
2215 while (*Current &&
2216 (!isa<SpecificDecl>(*Current) ||
2217 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2218 ++Current;
2219 }
2220
2221 public:
2222 using value_type = SpecificDecl *;
2223 // TODO: Add reference and pointer types (with some appropriate proxy type)
2224 // if we ever have a need for them.
2225 using reference = void;
2226 using pointer = void;
2227 using difference_type =
2228 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2229 using iterator_category = std::forward_iterator_tag;
2230
2231 filtered_decl_iterator() = default;
2232
2233 /// filtered_decl_iterator - Construct a new iterator over a
2234 /// subset of the declarations the range [C,
2235 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2236 /// member function of SpecificDecl that should return true for
2237 /// all of the SpecificDecl instances that will be in the subset
2238 /// of iterators. For example, if you want Objective-C instance
2239 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2240 /// &ObjCMethodDecl::isInstanceMethod.
2241 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2242 SkipToNextDecl();
2243 }
2244
2245 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2246 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2247
2248 filtered_decl_iterator& operator++() {
2249 ++Current;
2250 SkipToNextDecl();
2251 return *this;
2252 }
2253
2254 filtered_decl_iterator operator++(int) {
2255 filtered_decl_iterator tmp(*this);
2256 ++(*this);
2257 return tmp;
2258 }
2259
2260 friend bool operator==(const filtered_decl_iterator& x,
2261 const filtered_decl_iterator& y) {
2262 return x.Current == y.Current;
2263 }
2264
2265 friend bool operator!=(const filtered_decl_iterator& x,
2266 const filtered_decl_iterator& y) {
2267 return x.Current != y.Current;
2268 }
2269 };
2270
2271 /// Add the declaration D into this context.
2272 ///
2273 /// This routine should be invoked when the declaration D has first
2274 /// been declared, to place D into the context where it was
2275 /// (lexically) defined. Every declaration must be added to one
2276 /// (and only one!) context, where it can be visited via
2277 /// [decls_begin(), decls_end()). Once a declaration has been added
2278 /// to its lexical context, the corresponding DeclContext owns the
2279 /// declaration.
2280 ///
2281 /// If D is also a NamedDecl, it will be made visible within its
2282 /// semantic context via makeDeclVisibleInContext.
2283 void addDecl(Decl *D);
2284
2285 /// Add the declaration D into this context, but suppress
2286 /// searches for external declarations with the same name.
2287 ///
2288 /// Although analogous in function to addDecl, this removes an
2289 /// important check. This is only useful if the Decl is being
2290 /// added in response to an external search; in all other cases,
2291 /// addDecl() is the right function to use.
2292 /// See the ASTImporter for use cases.
2293 void addDeclInternal(Decl *D);
2294
2295 /// Add the declaration D to this context without modifying
2296 /// any lookup tables.
2297 ///
2298 /// This is useful for some operations in dependent contexts where
2299 /// the semantic context might not be dependent; this basically
2300 /// only happens with friends.
2301 void addHiddenDecl(Decl *D);
2302
2303 /// Removes a declaration from this context.
2304 void removeDecl(Decl *D);
2305
2306 /// Checks whether a declaration is in this context.
2307 bool containsDecl(Decl *D) const;
2308
2309 /// Checks whether a declaration is in this context.
2310 /// This also loads the Decls from the external source before the check.
2311 bool containsDeclAndLoad(Decl *D) const;
2312
2313 using lookup_result = DeclContextLookupResult;
2314 using lookup_iterator = lookup_result::iterator;
2315
2316 /// lookup - Find the declarations (if any) with the given Name in
2317 /// this context. Returns a range of iterators that contains all of
2318 /// the declarations with this name, with object, function, member,
2319 /// and enumerator names preceding any tag name. Note that this
2320 /// routine will not look into parent contexts.
2321 lookup_result lookup(DeclarationName Name) const;
2322
2323 /// Find the declarations with the given name that are visible
2324 /// within this context; don't attempt to retrieve anything from an
2325 /// external source.
2326 lookup_result noload_lookup(DeclarationName Name);
2327
2328 /// A simplistic name lookup mechanism that performs name lookup
2329 /// into this declaration context without consulting the external source.
2330 ///
2331 /// This function should almost never be used, because it subverts the
2332 /// usual relationship between a DeclContext and the external source.
2333 /// See the ASTImporter for the (few, but important) use cases.
2334 ///
2335 /// FIXME: This is very inefficient; replace uses of it with uses of
2336 /// noload_lookup.
2337 void localUncachedLookup(DeclarationName Name,
2338 SmallVectorImpl<NamedDecl *> &Results);
2339
2340 /// Makes a declaration visible within this context.
2341 ///
2342 /// This routine makes the declaration D visible to name lookup
2343 /// within this context and, if this is a transparent context,
2344 /// within its parent contexts up to the first enclosing
2345 /// non-transparent context. Making a declaration visible within a
2346 /// context does not transfer ownership of a declaration, and a
2347 /// declaration can be visible in many contexts that aren't its
2348 /// lexical context.
2349 ///
2350 /// If D is a redeclaration of an existing declaration that is
2351 /// visible from this context, as determined by
2352 /// NamedDecl::declarationReplaces, the previous declaration will be
2353 /// replaced with D.
2354 void makeDeclVisibleInContext(NamedDecl *D);
2355
2356 /// all_lookups_iterator - An iterator that provides a view over the results
2357 /// of looking up every possible name.
2358 class all_lookups_iterator;
2359
2360 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2361
2362 lookups_range lookups() const;
2363 // Like lookups(), but avoids loading external declarations.
2364 // If PreserveInternalState, avoids building lookup data structures too.
2365 lookups_range noload_lookups(bool PreserveInternalState) const;
2366
2367 /// Iterators over all possible lookups within this context.
2368 all_lookups_iterator lookups_begin() const;
2369 all_lookups_iterator lookups_end() const;
2370
2371 /// Iterators over all possible lookups within this context that are
2372 /// currently loaded; don't attempt to retrieve anything from an external
2373 /// source.
2374 all_lookups_iterator noload_lookups_begin() const;
2375 all_lookups_iterator noload_lookups_end() const;
2376
2377 struct udir_iterator;
2378
2379 using udir_iterator_base =
2380 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2381 typename lookup_iterator::iterator_category,
2382 UsingDirectiveDecl *>;
2383
2384 struct udir_iterator : udir_iterator_base {
2385 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2386
2387 UsingDirectiveDecl *operator*() const;
2388 };
2389
2390 using udir_range = llvm::iterator_range<udir_iterator>;
2391
2392 udir_range using_directives() const;
2393
2394 // These are all defined in DependentDiagnostic.h.
2395 class ddiag_iterator;
2396
2397 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2398
2399 inline ddiag_range ddiags() const;
2400
2401 // Low-level accessors
2402
2403 /// Mark that there are external lexical declarations that we need
2404 /// to include in our lookup table (and that are not available as external
2405 /// visible lookups). These extra lookup results will be found by walking
2406 /// the lexical declarations of this context. This should be used only if
2407 /// setHasExternalLexicalStorage() has been called on any decl context for
2408 /// which this is the primary context.
2409 void setMustBuildLookupTable() {
2410 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-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/DeclBase.h"
, 2411, __extension__ __PRETTY_FUNCTION__))
2411 "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-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/DeclBase.h"
, 2411, __extension__ __PRETTY_FUNCTION__))
;
2412 DeclContextBits.HasLazyExternalLexicalLookups = true;
2413 }
2414
2415 /// Retrieve the internal representation of the lookup structure.
2416 /// This may omit some names if we are lazily building the structure.
2417 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2418
2419 /// Ensure the lookup structure is fully-built and return it.
2420 StoredDeclsMap *buildLookup();
2421
2422 /// Whether this DeclContext has external storage containing
2423 /// additional declarations that are lexically in this context.
2424 bool hasExternalLexicalStorage() const {
2425 return DeclContextBits.ExternalLexicalStorage;
2426 }
2427
2428 /// State whether this DeclContext has external storage for
2429 /// declarations lexically in this context.
2430 void setHasExternalLexicalStorage(bool ES = true) const {
2431 DeclContextBits.ExternalLexicalStorage = ES;
2432 }
2433
2434 /// Whether this DeclContext has external storage containing
2435 /// additional declarations that are visible in this context.
2436 bool hasExternalVisibleStorage() const {
2437 return DeclContextBits.ExternalVisibleStorage;
2438 }
2439
2440 /// State whether this DeclContext has external storage for
2441 /// declarations visible in this context.
2442 void setHasExternalVisibleStorage(bool ES = true) const {
2443 DeclContextBits.ExternalVisibleStorage = ES;
2444 if (ES && LookupPtr)
2445 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2446 }
2447
2448 /// Determine whether the given declaration is stored in the list of
2449 /// declarations lexically within this context.
2450 bool isDeclInLexicalTraversal(const Decl *D) const {
2451 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2452 D == LastDecl);
2453 }
2454
2455 bool setUseQualifiedLookup(bool use = true) const {
2456 bool old_value = DeclContextBits.UseQualifiedLookup;
2457 DeclContextBits.UseQualifiedLookup = use;
2458 return old_value;
2459 }
2460
2461 bool shouldUseQualifiedLookup() const {
2462 return DeclContextBits.UseQualifiedLookup;
2463 }
2464
2465 static bool classof(const Decl *D);
2466 static bool classof(const DeclContext *D) { return true; }
2467
2468 void dumpDeclContext() const;
2469 void dumpLookups() const;
2470 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2471 bool Deserialize = false) const;
2472
2473private:
2474 /// Whether this declaration context has had externally visible
2475 /// storage added since the last lookup. In this case, \c LookupPtr's
2476 /// invariant may not hold and needs to be fixed before we perform
2477 /// another lookup.
2478 bool hasNeedToReconcileExternalVisibleStorage() const {
2479 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2480 }
2481
2482 /// State that this declaration context has had externally visible
2483 /// storage added since the last lookup. In this case, \c LookupPtr's
2484 /// invariant may not hold and needs to be fixed before we perform
2485 /// another lookup.
2486 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2487 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2488 }
2489
2490 /// If \c true, this context may have local lexical declarations
2491 /// that are missing from the lookup table.
2492 bool hasLazyLocalLexicalLookups() const {
2493 return DeclContextBits.HasLazyLocalLexicalLookups;
2494 }
2495
2496 /// If \c true, this context may have local lexical declarations
2497 /// that are missing from the lookup table.
2498 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2499 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2500 }
2501
2502 /// If \c true, the external source may have lexical declarations
2503 /// that are missing from the lookup table.
2504 bool hasLazyExternalLexicalLookups() const {
2505 return DeclContextBits.HasLazyExternalLexicalLookups;
2506 }
2507
2508 /// If \c true, the external source may have lexical declarations
2509 /// that are missing from the lookup table.
2510 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2511 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2512 }
2513
2514 void reconcileExternalVisibleStorage() const;
2515 bool LoadLexicalDeclsFromExternalStorage() const;
2516
2517 /// Makes a declaration visible within this context, but
2518 /// suppresses searches for external declarations with the same
2519 /// name.
2520 ///
2521 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2522 /// use of addDeclInternal().
2523 void makeDeclVisibleInContextInternal(NamedDecl *D);
2524
2525 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2526
2527 void loadLazyLocalLexicalLookups();
2528 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2529 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2530 bool Rediscoverable);
2531 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2532};
2533
2534inline bool Decl::isTemplateParameter() const {
2535 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2536 getKind() == TemplateTemplateParm;
2537}
2538
2539// Specialization selected when ToTy is not a known subclass of DeclContext.
2540template <class ToTy,
2541 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2542struct cast_convert_decl_context {
2543 static const ToTy *doit(const DeclContext *Val) {
2544 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2545 }
2546
2547 static ToTy *doit(DeclContext *Val) {
2548 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2549 }
2550};
2551
2552// Specialization selected when ToTy is a known subclass of DeclContext.
2553template <class ToTy>
2554struct cast_convert_decl_context<ToTy, true> {
2555 static const ToTy *doit(const DeclContext *Val) {
2556 return static_cast<const ToTy*>(Val);
2557 }
2558
2559 static ToTy *doit(DeclContext *Val) {
2560 return static_cast<ToTy*>(Val);
2561 }
2562};
2563
2564} // namespace clang
2565
2566namespace llvm {
2567
2568/// isa<T>(DeclContext*)
2569template <typename To>
2570struct isa_impl<To, ::clang::DeclContext> {
2571 static bool doit(const ::clang::DeclContext &Val) {
2572 return To::classofKind(Val.getDeclKind());
2573 }
2574};
2575
2576/// cast<T>(DeclContext*)
2577template<class ToTy>
2578struct cast_convert_val<ToTy,
2579 const ::clang::DeclContext,const ::clang::DeclContext> {
2580 static const ToTy &doit(const ::clang::DeclContext &Val) {
2581 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2582 }
2583};
2584
2585template<class ToTy>
2586struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2587 static ToTy &doit(::clang::DeclContext &Val) {
2588 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2589 }
2590};
2591
2592template<class ToTy>
2593struct cast_convert_val<ToTy,
2594 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2595 static const ToTy *doit(const ::clang::DeclContext *Val) {
2596 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2597 }
2598};
2599
2600template<class ToTy>
2601struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2602 static ToTy *doit(::clang::DeclContext *Val) {
2603 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2604 }
2605};
2606
2607/// Implement cast_convert_val for Decl -> DeclContext conversions.
2608template<class FromTy>
2609struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2610 static ::clang::DeclContext &doit(const FromTy &Val) {
2611 return *FromTy::castToDeclContext(&Val);
2612 }
2613};
2614
2615template<class FromTy>
2616struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2617 static ::clang::DeclContext *doit(const FromTy *Val) {
2618 return FromTy::castToDeclContext(Val);
2619 }
2620};
2621
2622template<class FromTy>
2623struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2624 static const ::clang::DeclContext &doit(const FromTy &Val) {
2625 return *FromTy::castToDeclContext(&Val);
2626 }
2627};
2628
2629template<class FromTy>
2630struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2631 static const ::clang::DeclContext *doit(const FromTy *Val) {
2632 return FromTy::castToDeclContext(Val);
2633 }
2634};
2635
2636} // namespace llvm
2637
2638#endif // LLVM_CLANG_AST_DECLBASE_H

/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/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-13~++20210722111111+b115c038d2d4/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 auto Y = getParent()->lookup(Name);
618 return std::distance(X.begin(), X.end()) ==
619 std::distance(Y.begin(), Y.end());
620 }
621
622 /// Get the original (first) namespace declaration.
623 NamespaceDecl *getOriginalNamespace();
624
625 /// Get the original (first) namespace declaration.
626 const NamespaceDecl *getOriginalNamespace() const;
627
628 /// Return true if this declaration is an original (first) declaration
629 /// of the namespace. This is false for non-original (subsequent) namespace
630 /// declarations and anonymous namespaces.
631 bool isOriginalNamespace() const;
632
633 /// Retrieve the anonymous namespace nested inside this namespace,
634 /// if any.
635 NamespaceDecl *getAnonymousNamespace() const {
636 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
637 }
638
639 void setAnonymousNamespace(NamespaceDecl *D) {
640 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
641 }
642
643 /// Retrieves the canonical declaration of this namespace.
644 NamespaceDecl *getCanonicalDecl() override {
645 return getOriginalNamespace();
646 }
647 const NamespaceDecl *getCanonicalDecl() const {
648 return getOriginalNamespace();
649 }
650
651 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
652 return SourceRange(LocStart, RBraceLoc);
653 }
654
655 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
656 SourceLocation getRBraceLoc() const { return RBraceLoc; }
657 void setLocStart(SourceLocation L) { LocStart = L; }
658 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
659
660 // Implement isa/cast/dyncast/etc.
661 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
662 static bool classofKind(Kind K) { return K == Namespace; }
663 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
664 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
665 }
666 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
667 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
668 }
669};
670
671/// Represent the declaration of a variable (in which case it is
672/// an lvalue) a function (in which case it is a function designator) or
673/// an enum constant.
674class ValueDecl : public NamedDecl {
675 QualType DeclType;
676
677 void anchor() override;
678
679protected:
680 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
681 DeclarationName N, QualType T)
682 : NamedDecl(DK, DC, L, N), DeclType(T) {}
683
684public:
685 QualType getType() const { return DeclType; }
686 void setType(QualType newType) { DeclType = newType; }
687
688 /// Determine whether this symbol is weakly-imported,
689 /// or declared with the weak or weak-ref attr.
690 bool isWeak() const;
691
692 // Implement isa/cast/dyncast/etc.
693 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
694 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
695};
696
697/// A struct with extended info about a syntactic
698/// name qualifier, to be used for the case of out-of-line declarations.
699struct QualifierInfo {
700 NestedNameSpecifierLoc QualifierLoc;
701
702 /// The number of "outer" template parameter lists.
703 /// The count includes all of the template parameter lists that were matched
704 /// against the template-ids occurring into the NNS and possibly (in the
705 /// case of an explicit specialization) a final "template <>".
706 unsigned NumTemplParamLists = 0;
707
708 /// A new-allocated array of size NumTemplParamLists,
709 /// containing pointers to the "outer" template parameter lists.
710 /// It includes all of the template parameter lists that were matched
711 /// against the template-ids occurring into the NNS and possibly (in the
712 /// case of an explicit specialization) a final "template <>".
713 TemplateParameterList** TemplParamLists = nullptr;
714
715 QualifierInfo() = default;
716 QualifierInfo(const QualifierInfo &) = delete;
717 QualifierInfo& operator=(const QualifierInfo &) = delete;
718
719 /// Sets info about "outer" template parameter lists.
720 void setTemplateParameterListsInfo(ASTContext &Context,
721 ArrayRef<TemplateParameterList *> TPLists);
722};
723
724/// Represents a ValueDecl that came out of a declarator.
725/// Contains type source information through TypeSourceInfo.
726class DeclaratorDecl : public ValueDecl {
727 // A struct representing a TInfo, a trailing requires-clause and a syntactic
728 // qualifier, to be used for the (uncommon) case of out-of-line declarations
729 // and constrained function decls.
730 struct ExtInfo : public QualifierInfo {
731 TypeSourceInfo *TInfo;
732 Expr *TrailingRequiresClause = nullptr;
733 };
734
735 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
736
737 /// The start of the source range for this declaration,
738 /// ignoring outer template declarations.
739 SourceLocation InnerLocStart;
740
741 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
742 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
743 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
744
745protected:
746 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
747 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
748 SourceLocation StartL)
749 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
750
751public:
752 friend class ASTDeclReader;
753 friend class ASTDeclWriter;
754
755 TypeSourceInfo *getTypeSourceInfo() const {
756 return hasExtInfo()
757 ? getExtInfo()->TInfo
758 : DeclInfo.get<TypeSourceInfo*>();
759 }
760
761 void setTypeSourceInfo(TypeSourceInfo *TI) {
762 if (hasExtInfo())
763 getExtInfo()->TInfo = TI;
764 else
765 DeclInfo = TI;
766 }
767
768 /// Return start of source range ignoring outer template declarations.
769 SourceLocation getInnerLocStart() const { return InnerLocStart; }
770 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
771
772 /// Return start of source range taking into account any outer template
773 /// declarations.
774 SourceLocation getOuterLocStart() const;
775
776 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
777
778 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
779 return getOuterLocStart();
780 }
781
782 /// Retrieve the nested-name-specifier that qualifies the name of this
783 /// declaration, if it was present in the source.
784 NestedNameSpecifier *getQualifier() const {
785 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
786 : nullptr;
787 }
788
789 /// Retrieve the nested-name-specifier (with source-location
790 /// information) that qualifies the name of this declaration, if it was
791 /// present in the source.
792 NestedNameSpecifierLoc getQualifierLoc() const {
793 return hasExtInfo() ? getExtInfo()->QualifierLoc
794 : NestedNameSpecifierLoc();
795 }
796
797 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
798
799 /// \brief Get the constraint-expression introduced by the trailing
800 /// requires-clause in the function/member declaration, or null if no
801 /// requires-clause was provided.
802 Expr *getTrailingRequiresClause() {
803 return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
804 : nullptr;
805 }
806
807 const Expr *getTrailingRequiresClause() const {
808 return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
809 : nullptr;
810 }
811
812 void setTrailingRequiresClause(Expr *TrailingRequiresClause);
813
814 unsigned getNumTemplateParameterLists() const {
815 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
816 }
817
818 TemplateParameterList *getTemplateParameterList(unsigned index) const {
819 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 819, __extension__ __PRETTY_FUNCTION__))
;
820 return getExtInfo()->TemplParamLists[index];
821 }
822
823 void setTemplateParameterListsInfo(ASTContext &Context,
824 ArrayRef<TemplateParameterList *> TPLists);
825
826 SourceLocation getTypeSpecStartLoc() const;
827 SourceLocation getTypeSpecEndLoc() const;
828
829 // Implement isa/cast/dyncast/etc.
830 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
831 static bool classofKind(Kind K) {
832 return K >= firstDeclarator && K <= lastDeclarator;
833 }
834};
835
836/// Structure used to store a statement, the constant value to
837/// which it was evaluated (if any), and whether or not the statement
838/// is an integral constant expression (if known).
839struct EvaluatedStmt {
840 /// Whether this statement was already evaluated.
841 bool WasEvaluated : 1;
842
843 /// Whether this statement is being evaluated.
844 bool IsEvaluating : 1;
845
846 /// Whether this variable is known to have constant initialization. This is
847 /// currently only computed in C++, for static / thread storage duration
848 /// variables that might have constant initialization and for variables that
849 /// are usable in constant expressions.
850 bool HasConstantInitialization : 1;
851
852 /// Whether this variable is known to have constant destruction. That is,
853 /// whether running the destructor on the initial value is a side-effect
854 /// (and doesn't inspect any state that might have changed during program
855 /// execution). This is currently only computed if the destructor is
856 /// non-trivial.
857 bool HasConstantDestruction : 1;
858
859 /// In C++98, whether the initializer is an ICE. This affects whether the
860 /// variable is usable in constant expressions.
861 bool HasICEInit : 1;
862 bool CheckedForICEInit : 1;
863
864 Stmt *Value;
865 APValue Evaluated;
866
867 EvaluatedStmt()
868 : WasEvaluated(false), IsEvaluating(false),
869 HasConstantInitialization(false), HasConstantDestruction(false),
870 HasICEInit(false), CheckedForICEInit(false) {}
871};
872
873/// Represents a variable declaration or definition.
874class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
875public:
876 /// Initialization styles.
877 enum InitializationStyle {
878 /// C-style initialization with assignment
879 CInit,
880
881 /// Call-style initialization (C++98)
882 CallInit,
883
884 /// Direct list-initialization (C++11)
885 ListInit
886 };
887
888 /// Kinds of thread-local storage.
889 enum TLSKind {
890 /// Not a TLS variable.
891 TLS_None,
892
893 /// TLS with a known-constant initializer.
894 TLS_Static,
895
896 /// TLS with a dynamic initializer.
897 TLS_Dynamic
898 };
899
900 /// Return the string used to specify the storage class \p SC.
901 ///
902 /// It is illegal to call this function with SC == None.
903 static const char *getStorageClassSpecifierString(StorageClass SC);
904
905protected:
906 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
907 // have allocated the auxiliary struct of information there.
908 //
909 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
910 // this as *many* VarDecls are ParmVarDecls that don't have default
911 // arguments. We could save some space by moving this pointer union to be
912 // allocated in trailing space when necessary.
913 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
914
915 /// The initializer for this variable or, for a ParmVarDecl, the
916 /// C++ default argument.
917 mutable InitType Init;
918
919private:
920 friend class ASTDeclReader;
921 friend class ASTNodeImporter;
922 friend class StmtIteratorBase;
923
924 class VarDeclBitfields {
925 friend class ASTDeclReader;
926 friend class VarDecl;
927
928 unsigned SClass : 3;
929 unsigned TSCSpec : 2;
930 unsigned InitStyle : 2;
931
932 /// Whether this variable is an ARC pseudo-__strong variable; see
933 /// isARCPseudoStrong() for details.
934 unsigned ARCPseudoStrong : 1;
935 };
936 enum { NumVarDeclBits = 8 };
937
938protected:
939 enum { NumParameterIndexBits = 8 };
940
941 enum DefaultArgKind {
942 DAK_None,
943 DAK_Unparsed,
944 DAK_Uninstantiated,
945 DAK_Normal
946 };
947
948 enum { NumScopeDepthOrObjCQualsBits = 7 };
949
950 class ParmVarDeclBitfields {
951 friend class ASTDeclReader;
952 friend class ParmVarDecl;
953
954 unsigned : NumVarDeclBits;
955
956 /// Whether this parameter inherits a default argument from a
957 /// prior declaration.
958 unsigned HasInheritedDefaultArg : 1;
959
960 /// Describes the kind of default argument for this parameter. By default
961 /// this is none. If this is normal, then the default argument is stored in
962 /// the \c VarDecl initializer expression unless we were unable to parse
963 /// (even an invalid) expression for the default argument.
964 unsigned DefaultArgKind : 2;
965
966 /// Whether this parameter undergoes K&R argument promotion.
967 unsigned IsKNRPromoted : 1;
968
969 /// Whether this parameter is an ObjC method parameter or not.
970 unsigned IsObjCMethodParam : 1;
971
972 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
973 /// Otherwise, the number of function parameter scopes enclosing
974 /// the function parameter scope in which this parameter was
975 /// declared.
976 unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits;
977
978 /// The number of parameters preceding this parameter in the
979 /// function parameter scope in which it was declared.
980 unsigned ParameterIndex : NumParameterIndexBits;
981 };
982
983 class NonParmVarDeclBitfields {
984 friend class ASTDeclReader;
985 friend class ImplicitParamDecl;
986 friend class VarDecl;
987
988 unsigned : NumVarDeclBits;
989
990 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
991 /// Whether this variable is a definition which was demoted due to
992 /// module merge.
993 unsigned IsThisDeclarationADemotedDefinition : 1;
994
995 /// Whether this variable is the exception variable in a C++ catch
996 /// or an Objective-C @catch statement.
997 unsigned ExceptionVar : 1;
998
999 /// Whether this local variable could be allocated in the return
1000 /// slot of its function, enabling the named return value optimization
1001 /// (NRVO).
1002 unsigned NRVOVariable : 1;
1003
1004 /// Whether this variable is the for-range-declaration in a C++0x
1005 /// for-range statement.
1006 unsigned CXXForRangeDecl : 1;
1007
1008 /// Whether this variable is the for-in loop declaration in Objective-C.
1009 unsigned ObjCForDecl : 1;
1010
1011 /// Whether this variable is (C++1z) inline.
1012 unsigned IsInline : 1;
1013
1014 /// Whether this variable has (C++1z) inline explicitly specified.
1015 unsigned IsInlineSpecified : 1;
1016
1017 /// Whether this variable is (C++0x) constexpr.
1018 unsigned IsConstexpr : 1;
1019
1020 /// Whether this variable is the implicit variable for a lambda
1021 /// init-capture.
1022 unsigned IsInitCapture : 1;
1023
1024 /// Whether this local extern variable's previous declaration was
1025 /// declared in the same block scope. This controls whether we should merge
1026 /// the type of this declaration with its previous declaration.
1027 unsigned PreviousDeclInSameBlockScope : 1;
1028
1029 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
1030 /// something else.
1031 unsigned ImplicitParamKind : 3;
1032
1033 unsigned EscapingByref : 1;
1034 };
1035
1036 union {
1037 unsigned AllBits;
1038 VarDeclBitfields VarDeclBits;
1039 ParmVarDeclBitfields ParmVarDeclBits;
1040 NonParmVarDeclBitfields NonParmVarDeclBits;
1041 };
1042
1043 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1044 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1045 TypeSourceInfo *TInfo, StorageClass SC);
1046
1047 using redeclarable_base = Redeclarable<VarDecl>;
1048
1049 VarDecl *getNextRedeclarationImpl() override {
1050 return getNextRedeclaration();
1051 }
1052
1053 VarDecl *getPreviousDeclImpl() override {
1054 return getPreviousDecl();
1055 }
1056
1057 VarDecl *getMostRecentDeclImpl() override {
1058 return getMostRecentDecl();
1059 }
1060
1061public:
1062 using redecl_range = redeclarable_base::redecl_range;
1063 using redecl_iterator = redeclarable_base::redecl_iterator;
1064
1065 using redeclarable_base::redecls_begin;
1066 using redeclarable_base::redecls_end;
1067 using redeclarable_base::redecls;
1068 using redeclarable_base::getPreviousDecl;
1069 using redeclarable_base::getMostRecentDecl;
1070 using redeclarable_base::isFirstDecl;
1071
1072 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1073 SourceLocation StartLoc, SourceLocation IdLoc,
1074 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1075 StorageClass S);
1076
1077 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1078
1079 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1080
1081 /// Returns the storage class as written in the source. For the
1082 /// computed linkage of symbol, see getLinkage.
1083 StorageClass getStorageClass() const {
1084 return (StorageClass) VarDeclBits.SClass;
1085 }
1086 void setStorageClass(StorageClass SC);
1087
1088 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1089 VarDeclBits.TSCSpec = TSC;
1090 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1090, __extension__ __PRETTY_FUNCTION__))
;
1091 }
1092 ThreadStorageClassSpecifier getTSCSpec() const {
1093 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1094 }
1095 TLSKind getTLSKind() const;
1096
1097 /// Returns true if a variable with function scope is a non-static local
1098 /// variable.
1099 bool hasLocalStorage() const {
1100 if (getStorageClass() == SC_None) {
15
Assuming the condition is false
16
Taking false branch
1101 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1102 // used to describe variables allocated in global memory and which are
1103 // accessed inside a kernel(s) as read-only variables. As such, variables
1104 // in constant address space cannot have local storage.
1105 if (getType().getAddressSpace() == LangAS::opencl_constant)
1106 return false;
1107 // Second check is for C++11 [dcl.stc]p4.
1108 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1109 }
1110
1111 // Global Named Register (GNU extension)
1112 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
17
Assuming the condition is true
18
Assuming the condition is true
19
Taking true branch
1113 return false;
20
Returning zero, which participates in a condition later
1114
1115 // Return true for: Auto, Register.
1116 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1117
1118 return getStorageClass() >= SC_Auto;
1119 }
1120
1121 /// Returns true if a variable with function scope is a static local
1122 /// variable.
1123 bool isStaticLocal() const {
1124 return (getStorageClass() == SC_Static ||
1125 // C++11 [dcl.stc]p4
1126 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1127 && !isFileVarDecl();
1128 }
1129
1130 /// Returns true if a variable has extern or __private_extern__
1131 /// storage.
1132 bool hasExternalStorage() const {
1133 return getStorageClass() == SC_Extern ||
1134 getStorageClass() == SC_PrivateExtern;
1135 }
1136
1137 /// Returns true for all variables that do not have local storage.
1138 ///
1139 /// This includes all global variables as well as static variables declared
1140 /// within a function.
1141 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1142
1143 /// Get the storage duration of this variable, per C++ [basic.stc].
1144 StorageDuration getStorageDuration() const {
1145 return hasLocalStorage() ? SD_Automatic :
1146 getTSCSpec() ? SD_Thread : SD_Static;
1147 }
1148
1149 /// Compute the language linkage.
1150 LanguageLinkage getLanguageLinkage() const;
1151
1152 /// Determines whether this variable is a variable with external, C linkage.
1153 bool isExternC() const;
1154
1155 /// Determines whether this variable's context is, or is nested within,
1156 /// a C++ extern "C" linkage spec.
1157 bool isInExternCContext() const;
1158
1159 /// Determines whether this variable's context is, or is nested within,
1160 /// a C++ extern "C++" linkage spec.
1161 bool isInExternCXXContext() const;
1162
1163 /// Returns true for local variable declarations other than parameters.
1164 /// Note that this includes static variables inside of functions. It also
1165 /// includes variables inside blocks.
1166 ///
1167 /// void foo() { int x; static int y; extern int z; }
1168 bool isLocalVarDecl() const {
1169 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1170 return false;
1171 if (const DeclContext *DC = getLexicalDeclContext())
1172 return DC->getRedeclContext()->isFunctionOrMethod();
1173 return false;
1174 }
1175
1176 /// Similar to isLocalVarDecl but also includes parameters.
1177 bool isLocalVarDeclOrParm() const {
1178 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1179 }
1180
1181 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1182 bool isFunctionOrMethodVarDecl() const {
1183 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1184 return false;
1185 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1186 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1187 }
1188
1189 /// Determines whether this is a static data member.
1190 ///
1191 /// This will only be true in C++, and applies to, e.g., the
1192 /// variable 'x' in:
1193 /// \code
1194 /// struct S {
1195 /// static int x;
1196 /// };
1197 /// \endcode
1198 bool isStaticDataMember() const {
1199 // If it wasn't static, it would be a FieldDecl.
1200 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1201 }
1202
1203 VarDecl *getCanonicalDecl() override;
1204 const VarDecl *getCanonicalDecl() const {
1205 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1206 }
1207
1208 enum DefinitionKind {
1209 /// This declaration is only a declaration.
1210 DeclarationOnly,
1211
1212 /// This declaration is a tentative definition.
1213 TentativeDefinition,
1214
1215 /// This declaration is definitely a definition.
1216 Definition
1217 };
1218
1219 /// Check whether this declaration is a definition. If this could be
1220 /// a tentative definition (in C), don't check whether there's an overriding
1221 /// definition.
1222 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1223 DefinitionKind isThisDeclarationADefinition() const {
1224 return isThisDeclarationADefinition(getASTContext());
1225 }
1226
1227 /// Check whether this variable is defined in this translation unit.
1228 DefinitionKind hasDefinition(ASTContext &) const;
1229 DefinitionKind hasDefinition() const {
1230 return hasDefinition(getASTContext());
1231 }
1232
1233 /// Get the tentative definition that acts as the real definition in a TU.
1234 /// Returns null if there is a proper definition available.
1235 VarDecl *getActingDefinition();
1236 const VarDecl *getActingDefinition() const {
1237 return const_cast<VarDecl*>(this)->getActingDefinition();
1238 }
1239
1240 /// Get the real (not just tentative) definition for this declaration.
1241 VarDecl *getDefinition(ASTContext &);
1242 const VarDecl *getDefinition(ASTContext &C) const {
1243 return const_cast<VarDecl*>(this)->getDefinition(C);
1244 }
1245 VarDecl *getDefinition() {
1246 return getDefinition(getASTContext());
1247 }
1248 const VarDecl *getDefinition() const {
1249 return const_cast<VarDecl*>(this)->getDefinition();
1250 }
1251
1252 /// Determine whether this is or was instantiated from an out-of-line
1253 /// definition of a static data member.
1254 bool isOutOfLine() const override;
1255
1256 /// Returns true for file scoped variable declaration.
1257 bool isFileVarDecl() const {
1258 Kind K = getKind();
1259 if (K == ParmVar || K == ImplicitParam)
1260 return false;
1261
1262 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1263 return true;
1264
1265 if (isStaticDataMember())
1266 return true;
1267
1268 return false;
1269 }
1270
1271 /// Get the initializer for this variable, no matter which
1272 /// declaration it is attached to.
1273 const Expr *getAnyInitializer() const {
1274 const VarDecl *D;
1275 return getAnyInitializer(D);
1276 }
1277
1278 /// Get the initializer for this variable, no matter which
1279 /// declaration it is attached to. Also get that declaration.
1280 const Expr *getAnyInitializer(const VarDecl *&D) const;
1281
1282 bool hasInit() const;
1283 const Expr *getInit() const {
1284 return const_cast<VarDecl *>(this)->getInit();
1285 }
1286 Expr *getInit();
1287
1288 /// Retrieve the address of the initializer expression.
1289 Stmt **getInitAddress();
1290
1291 void setInit(Expr *I);
1292
1293 /// Get the initializing declaration of this variable, if any. This is
1294 /// usually the definition, except that for a static data member it can be
1295 /// the in-class declaration.
1296 VarDecl *getInitializingDeclaration();
1297 const VarDecl *getInitializingDeclaration() const {
1298 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1299 }
1300
1301 /// Determine whether this variable's value might be usable in a
1302 /// constant expression, according to the relevant language standard.
1303 /// This only checks properties of the declaration, and does not check
1304 /// whether the initializer is in fact a constant expression.
1305 ///
1306 /// This corresponds to C++20 [expr.const]p3's notion of a
1307 /// "potentially-constant" variable.
1308 bool mightBeUsableInConstantExpressions(const ASTContext &C) const;
1309
1310 /// Determine whether this variable's value can be used in a
1311 /// constant expression, according to the relevant language standard,
1312 /// including checking whether it was initialized by a constant expression.
1313 bool isUsableInConstantExpressions(const ASTContext &C) const;
1314
1315 EvaluatedStmt *ensureEvaluatedStmt() const;
1316 EvaluatedStmt *getEvaluatedStmt() const;
1317
1318 /// Attempt to evaluate the value of the initializer attached to this
1319 /// declaration, and produce notes explaining why it cannot be evaluated.
1320 /// Returns a pointer to the value if evaluation succeeded, 0 otherwise.
1321 APValue *evaluateValue() const;
1322
1323private:
1324 APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
1325 bool IsConstantInitialization) const;
1326
1327public:
1328 /// Return the already-evaluated value of this variable's
1329 /// initializer, or NULL if the value is not yet known. Returns pointer
1330 /// to untyped APValue if the value could not be evaluated.
1331 APValue *getEvaluatedValue() const;
1332
1333 /// Evaluate the destruction of this variable to determine if it constitutes
1334 /// constant destruction.
1335 ///
1336 /// \pre hasConstantInitialization()
1337 /// \return \c true if this variable has constant destruction, \c false if
1338 /// not.
1339 bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1340
1341 /// Determine whether this variable has constant initialization.
1342 ///
1343 /// This is only set in two cases: when the language semantics require
1344 /// constant initialization (globals in C and some globals in C++), and when
1345 /// the variable is usable in constant expressions (constexpr, const int, and
1346 /// reference variables in C++).
1347 bool hasConstantInitialization() const;
1348
1349 /// Determine whether the initializer of this variable is an integer constant
1350 /// expression. For use in C++98, where this affects whether the variable is
1351 /// usable in constant expressions.
1352 bool hasICEInitializer(const ASTContext &Context) const;
1353
1354 /// Evaluate the initializer of this variable to determine whether it's a
1355 /// constant initializer. Should only be called once, after completing the
1356 /// definition of the variable.
1357 bool checkForConstantInitialization(
1358 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1359
1360 void setInitStyle(InitializationStyle Style) {
1361 VarDeclBits.InitStyle = Style;
1362 }
1363
1364 /// The style of initialization for this declaration.
1365 ///
1366 /// C-style initialization is "int x = 1;". Call-style initialization is
1367 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1368 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1369 /// expression for class types. List-style initialization is C++11 syntax,
1370 /// e.g. "int x{1};". Clients can distinguish between different forms of
1371 /// initialization by checking this value. In particular, "int x = {1};" is
1372 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1373 /// Init expression in all three cases is an InitListExpr.
1374 InitializationStyle getInitStyle() const {
1375 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1376 }
1377
1378 /// Whether the initializer is a direct-initializer (list or call).
1379 bool isDirectInit() const {
1380 return getInitStyle() != CInit;
1381 }
1382
1383 /// If this definition should pretend to be a declaration.
1384 bool isThisDeclarationADemotedDefinition() const {
1385 return isa<ParmVarDecl>(this) ? false :
1386 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1387 }
1388
1389 /// This is a definition which should be demoted to a declaration.
1390 ///
1391 /// In some cases (mostly module merging) we can end up with two visible
1392 /// definitions one of which needs to be demoted to a declaration to keep
1393 /// the AST invariants.
1394 void demoteThisDefinitionToDeclaration() {
1395 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1395, __extension__ __PRETTY_FUNCTION__))
;
1396 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-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1396, __extension__ __PRETTY_FUNCTION__))
;
1397 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1398 }
1399
1400 /// Determine whether this variable is the exception variable in a
1401 /// C++ catch statememt or an Objective-C \@catch statement.
1402 bool isExceptionVariable() const {
1403 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1404 }
1405 void setExceptionVariable(bool EV) {
1406 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1406, __extension__ __PRETTY_FUNCTION__))
;
1407 NonParmVarDeclBits.ExceptionVar = EV;
1408 }
1409
1410 /// Determine whether this local variable can be used with the named
1411 /// return value optimization (NRVO).
1412 ///
1413 /// The named return value optimization (NRVO) works by marking certain
1414 /// non-volatile local variables of class type as NRVO objects. These
1415 /// locals can be allocated within the return slot of their containing
1416 /// function, in which case there is no need to copy the object to the
1417 /// return slot when returning from the function. Within the function body,
1418 /// each return that returns the NRVO object will have this variable as its
1419 /// NRVO candidate.
1420 bool isNRVOVariable() const {
1421 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1422 }
1423 void setNRVOVariable(bool NRVO) {
1424 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1424, __extension__ __PRETTY_FUNCTION__))
;
1425 NonParmVarDeclBits.NRVOVariable = NRVO;
1426 }
1427
1428 /// Determine whether this variable is the for-range-declaration in
1429 /// a C++0x for-range statement.
1430 bool isCXXForRangeDecl() const {
1431 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1432 }
1433 void setCXXForRangeDecl(bool FRD) {
1434 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1434, __extension__ __PRETTY_FUNCTION__))
;
1435 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1436 }
1437
1438 /// Determine whether this variable is a for-loop declaration for a
1439 /// for-in statement in Objective-C.
1440 bool isObjCForDecl() const {
1441 return NonParmVarDeclBits.ObjCForDecl;
1442 }
1443
1444 void setObjCForDecl(bool FRD) {
1445 NonParmVarDeclBits.ObjCForDecl = FRD;
1446 }
1447
1448 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1449 /// pseudo-__strong variable has a __strong-qualified type but does not
1450 /// actually retain the object written into it. Generally such variables are
1451 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1452 /// the variable is annotated with the objc_externally_retained attribute, 2)
1453 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1454 /// loop.
1455 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1456 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1457
1458 /// Whether this variable is (C++1z) inline.
1459 bool isInline() const {
1460 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1461 }
1462 bool isInlineSpecified() const {
1463 return isa<ParmVarDecl>(this) ? false
1464 : NonParmVarDeclBits.IsInlineSpecified;
1465 }
1466 void setInlineSpecified() {
1467 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1467, __extension__ __PRETTY_FUNCTION__))
;
1468 NonParmVarDeclBits.IsInline = true;
1469 NonParmVarDeclBits.IsInlineSpecified = true;
1470 }
1471 void setImplicitlyInline() {
1472 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1472, __extension__ __PRETTY_FUNCTION__))
;
1473 NonParmVarDeclBits.IsInline = true;
1474 }
1475
1476 /// Whether this variable is (C++11) constexpr.
1477 bool isConstexpr() const {
1478 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1479 }
1480 void setConstexpr(bool IC) {
1481 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1481, __extension__ __PRETTY_FUNCTION__))
;
1482 NonParmVarDeclBits.IsConstexpr = IC;
1483 }
1484
1485 /// Whether this variable is the implicit variable for a lambda init-capture.
1486 bool isInitCapture() const {
1487 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1488 }
1489 void setInitCapture(bool IC) {
1490 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1490, __extension__ __PRETTY_FUNCTION__))
;
1491 NonParmVarDeclBits.IsInitCapture = IC;
1492 }
1493
1494 /// Determine whether this variable is actually a function parameter pack or
1495 /// init-capture pack.
1496 bool isParameterPack() const;
1497
1498 /// Whether this local extern variable declaration's previous declaration
1499 /// was declared in the same block scope. Only correct in C++.
1500 bool isPreviousDeclInSameBlockScope() const {
1501 return isa<ParmVarDecl>(this)
1502 ? false
1503 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1504 }
1505 void setPreviousDeclInSameBlockScope(bool Same) {
1506 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-13~++20210722111111+b115c038d2d4/clang/include/clang/AST/Decl.h"
, 1506, __extension__ __PRETTY_FUNCTION__))
;
1507 No