Bug Summary

File:src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp
Warning:line 1205, column 29
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name PdbAstBuilder.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 -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../include -I /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/obj -I /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -I /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/include -I /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source -I /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/obj/../include/lldb/Plugins -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp

/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp

1#include "PdbAstBuilder.h"
2
3#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
4#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
5#include "llvm/DebugInfo/CodeView/RecordName.h"
6#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
7#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
8#include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
9#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
10#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
11#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
12#include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
13#include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
14#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
15#include "llvm/Demangle/MicrosoftDemangle.h"
16
17#include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
18#include "Plugins/ExpressionParser/Clang/ClangUtil.h"
19#include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
20#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
21#include "lldb/Core/Module.h"
22#include "lldb/Symbol/ObjectFile.h"
23#include "lldb/Utility/LLDBAssert.h"
24
25#include "PdbUtil.h"
26#include "UdtRecordCompleter.h"
27
28using namespace lldb_private;
29using namespace lldb_private::npdb;
30using namespace llvm::codeview;
31using namespace llvm::pdb;
32
33static llvm::Optional<PdbCompilandSymId> FindSymbolScope(PdbIndex &index,
34 PdbCompilandSymId id) {
35 CVSymbol sym = index.ReadSymbolRecord(id);
36 if (symbolOpensScope(sym.kind())) {
37 // If this exact symbol opens a scope, we can just directly access its
38 // parent.
39 id.offset = getScopeParentOffset(sym);
40 // Global symbols have parent offset of 0. Return llvm::None to indicate
41 // this.
42 if (id.offset == 0)
43 return llvm::None;
44 return id;
45 }
46
47 // Otherwise we need to start at the beginning and iterate forward until we
48 // reach (or pass) this particular symbol
49 CompilandIndexItem &cii = index.compilands().GetOrCreateCompiland(id.modi);
50 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
51
52 auto begin = syms.begin();
53 auto end = syms.at(id.offset);
54 std::vector<PdbCompilandSymId> scope_stack;
55
56 while (begin != end) {
57 if (id.offset == begin.offset()) {
58 // We have a match! Return the top of the stack
59 if (scope_stack.empty())
60 return llvm::None;
61 return scope_stack.back();
62 }
63 if (begin.offset() > id.offset) {
64 // We passed it. We couldn't even find this symbol record.
65 lldbassert(false && "Invalid compiland symbol id!")lldb_private::lldb_assert(static_cast<bool>(false &&
"Invalid compiland symbol id!"), "false && \"Invalid compiland symbol id!\""
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 65)
;
66 return llvm::None;
67 }
68
69 // We haven't found the symbol yet. Check if we need to open or close the
70 // scope stack.
71 if (symbolOpensScope(begin->kind())) {
72 // We can use the end offset of the scope to determine whether or not
73 // we can just outright skip this entire scope.
74 uint32_t scope_end = getScopeEndOffset(*begin);
75 if (scope_end < id.modi) {
76 begin = syms.at(scope_end);
77 } else {
78 // The symbol we're looking for is somewhere in this scope.
79 scope_stack.emplace_back(id.modi, begin.offset());
80 }
81 } else if (symbolEndsScope(begin->kind())) {
82 scope_stack.pop_back();
83 }
84 ++begin;
85 }
86
87 return llvm::None;
88}
89
90static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
91 switch (cr.Kind) {
92 case TypeRecordKind::Class:
93 return clang::TTK_Class;
94 case TypeRecordKind::Struct:
95 return clang::TTK_Struct;
96 case TypeRecordKind::Union:
97 return clang::TTK_Union;
98 case TypeRecordKind::Interface:
99 return clang::TTK_Interface;
100 case TypeRecordKind::Enum:
101 return clang::TTK_Enum;
102 default:
103 lldbassert(false && "Invalid tag record kind!")lldb_private::lldb_assert(static_cast<bool>(false &&
"Invalid tag record kind!"), "false && \"Invalid tag record kind!\""
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 103)
;
104 return clang::TTK_Struct;
105 }
106}
107
108static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
109 if (args.empty())
110 return false;
111 return args.back() == TypeIndex::None();
112}
113
114static bool
115AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) {
116 for (llvm::ms_demangle::Node *n : scopes) {
117 auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n);
118 if (idn->TemplateParams)
119 return true;
120 }
121 return false;
122}
123
124static llvm::Optional<clang::CallingConv>
125TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
126 using CC = llvm::codeview::CallingConvention;
127 switch (conv) {
128
129 case CC::NearC:
130 case CC::FarC:
131 return clang::CallingConv::CC_C;
132 case CC::NearPascal:
133 case CC::FarPascal:
134 return clang::CallingConv::CC_X86Pascal;
135 case CC::NearFast:
136 case CC::FarFast:
137 return clang::CallingConv::CC_X86FastCall;
138 case CC::NearStdCall:
139 case CC::FarStdCall:
140 return clang::CallingConv::CC_X86StdCall;
141 case CC::ThisCall:
142 return clang::CallingConv::CC_X86ThisCall;
143 case CC::NearVector:
144 return clang::CallingConv::CC_X86VectorCall;
145 default:
146 return llvm::None;
147 }
148}
149
150static llvm::Optional<CVTagRecord>
151GetNestedTagDefinition(const NestedTypeRecord &Record,
152 const CVTagRecord &parent, TpiStream &tpi) {
153 // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
154 // is also used to indicate the primary definition of a nested class. That is
155 // to say, if you have:
156 // struct A {
157 // struct B {};
158 // using C = B;
159 // };
160 // Then in the debug info, this will appear as:
161 // LF_STRUCTURE `A::B` [type index = N]
162 // LF_STRUCTURE `A`
163 // LF_NESTTYPE [name = `B`, index = N]
164 // LF_NESTTYPE [name = `C`, index = N]
165 // In order to accurately reconstruct the decl context hierarchy, we need to
166 // know which ones are actual definitions and which ones are just aliases.
167
168 // If it's a simple type, then this is something like `using foo = int`.
169 if (Record.Type.isSimple())
170 return llvm::None;
171
172 CVType cvt = tpi.getType(Record.Type);
173
174 if (!IsTagRecord(cvt))
175 return llvm::None;
176
177 // If it's an inner definition, then treat whatever name we have here as a
178 // single component of a mangled name. So we can inject it into the parent's
179 // mangled name to see if it matches.
180 CVTagRecord child = CVTagRecord::create(cvt);
181 std::string qname = std::string(parent.asTag().getUniqueName());
182 if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
183 return llvm::None;
184
185 // qname[3] is the tag type identifier (struct, class, union, etc). Since the
186 // inner tag type is not necessarily the same as the outer tag type, re-write
187 // it to match the inner tag type.
188 qname[3] = child.asTag().getUniqueName()[3];
189 std::string piece;
190 if (qname[3] == 'W')
191 piece = "4";
192 piece += Record.Name;
193 piece.push_back('@');
194 qname.insert(4, std::move(piece));
195 if (qname != child.asTag().UniqueName)
196 return llvm::None;
197
198 return std::move(child);
199}
200
201static bool IsAnonymousNamespaceName(llvm::StringRef name) {
202 return name == "`anonymous namespace'" || name == "`anonymous-namespace'";
203}
204
205PdbAstBuilder::PdbAstBuilder(ObjectFile &obj, PdbIndex &index, TypeSystemClang &clang)
206 : m_index(index), m_clang(clang) {
207 BuildParentMap();
208}
209
210lldb_private::CompilerDeclContext PdbAstBuilder::GetTranslationUnitDecl() {
211 return ToCompilerDeclContext(*m_clang.GetTranslationUnitDecl());
212}
213
214std::pair<clang::DeclContext *, std::string>
215PdbAstBuilder::CreateDeclInfoForType(const TagRecord &record, TypeIndex ti) {
216 // FIXME: Move this to GetDeclContextContainingUID.
217 if (!record.hasUniqueName())
218 return CreateDeclInfoForUndecoratedName(record.Name);
219
220 llvm::ms_demangle::Demangler demangler;
221 StringView sv(record.UniqueName.begin(), record.UniqueName.size());
222 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
223 if (demangler.Error)
224 return {m_clang.GetTranslationUnitDecl(), std::string(record.UniqueName)};
225
226 llvm::ms_demangle::IdentifierNode *idn =
227 ttn->QualifiedName->getUnqualifiedIdentifier();
228 std::string uname = idn->toString(llvm::ms_demangle::OF_NoTagSpecifier);
229
230 llvm::ms_demangle::NodeArrayNode *name_components =
231 ttn->QualifiedName->Components;
232 llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
233 name_components->Count - 1);
234
235 clang::DeclContext *context = m_clang.GetTranslationUnitDecl();
236
237 // If this type doesn't have a parent type in the debug info, then the best we
238 // can do is to say that it's either a series of namespaces (if the scope is
239 // non-empty), or the translation unit (if the scope is empty).
240 auto parent_iter = m_parent_types.find(ti);
241 if (parent_iter == m_parent_types.end()) {
242 if (scopes.empty())
243 return {context, uname};
244
245 // If there is no parent in the debug info, but some of the scopes have
246 // template params, then this is a case of bad debug info. See, for
247 // example, llvm.org/pr39607. We don't want to create an ambiguity between
248 // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at
249 // global scope with the fully qualified name.
250 if (AnyScopesHaveTemplateParams(scopes))
251 return {context, std::string(record.Name)};
252
253 for (llvm::ms_demangle::Node *scope : scopes) {
254 auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
255 std::string str = nii->toString();
256 context = GetOrCreateNamespaceDecl(str.c_str(), *context);
257 }
258 return {context, uname};
259 }
260
261 // Otherwise, all we need to do is get the parent type of this type and
262 // recurse into our lazy type creation / AST reconstruction logic to get an
263 // LLDB TypeSP for the parent. This will cause the AST to automatically get
264 // the right DeclContext created for any parent.
265 clang::QualType parent_qt = GetOrCreateType(parent_iter->second);
266
267 context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl());
268 return {context, uname};
269}
270
271void PdbAstBuilder::BuildParentMap() {
272 LazyRandomTypeCollection &types = m_index.tpi().typeCollection();
273
274 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full;
275 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward;
276
277 struct RecordIndices {
278 TypeIndex forward;
279 TypeIndex full;
280 };
281
282 llvm::StringMap<RecordIndices> record_indices;
283
284 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
285 CVType type = types.getType(*ti);
286 if (!IsTagRecord(type))
287 continue;
288
289 CVTagRecord tag = CVTagRecord::create(type);
290
291 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()];
292 if (tag.asTag().isForwardRef())
293 indices.forward = *ti;
294 else
295 indices.full = *ti;
296
297 if (indices.full != TypeIndex::None() &&
298 indices.forward != TypeIndex::None()) {
299 forward_to_full[indices.forward] = indices.full;
300 full_to_forward[indices.full] = indices.forward;
301 }
302
303 // We're looking for LF_NESTTYPE records in the field list, so ignore
304 // forward references (no field list), and anything without a nested class
305 // (since there won't be any LF_NESTTYPE records).
306 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
307 continue;
308
309 struct ProcessTpiStream : public TypeVisitorCallbacks {
310 ProcessTpiStream(PdbIndex &index, TypeIndex parent,
311 const CVTagRecord &parent_cvt,
312 llvm::DenseMap<TypeIndex, TypeIndex> &parents)
313 : index(index), parents(parents), parent(parent),
314 parent_cvt(parent_cvt) {}
315
316 PdbIndex &index;
317 llvm::DenseMap<TypeIndex, TypeIndex> &parents;
318
319 unsigned unnamed_type_index = 1;
320 TypeIndex parent;
321 const CVTagRecord &parent_cvt;
322
323 llvm::Error visitKnownMember(CVMemberRecord &CVR,
324 NestedTypeRecord &Record) override {
325 std::string unnamed_type_name;
326 if (Record.Name.empty()) {
327 unnamed_type_name =
328 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str();
329 Record.Name = unnamed_type_name;
330 ++unnamed_type_index;
331 }
332 llvm::Optional<CVTagRecord> tag =
333 GetNestedTagDefinition(Record, parent_cvt, index.tpi());
334 if (!tag)
335 return llvm::ErrorSuccess();
336
337 parents[Record.Type] = parent;
338 return llvm::ErrorSuccess();
339 }
340 };
341
342 CVType field_list = m_index.tpi().getType(tag.asTag().FieldList);
343 ProcessTpiStream process(m_index, *ti, tag, m_parent_types);
344 llvm::Error error = visitMemberRecordStream(field_list.data(), process);
345 if (error)
346 llvm::consumeError(std::move(error));
347 }
348
349 // Now that we know the forward -> full mapping of all type indices, we can
350 // re-write all the indices. At the end of this process, we want a mapping
351 // consisting of fwd -> full and full -> full for all child -> parent indices.
352 // We can re-write the values in place, but for the keys, we must save them
353 // off so that we don't modify the map in place while also iterating it.
354 std::vector<TypeIndex> full_keys;
355 std::vector<TypeIndex> fwd_keys;
356 for (auto &entry : m_parent_types) {
357 TypeIndex key = entry.first;
358 TypeIndex value = entry.second;
359
360 auto iter = forward_to_full.find(value);
361 if (iter != forward_to_full.end())
362 entry.second = iter->second;
363
364 iter = forward_to_full.find(key);
365 if (iter != forward_to_full.end())
366 fwd_keys.push_back(key);
367 else
368 full_keys.push_back(key);
369 }
370 for (TypeIndex fwd : fwd_keys) {
371 TypeIndex full = forward_to_full[fwd];
372 m_parent_types[full] = m_parent_types[fwd];
373 }
374 for (TypeIndex full : full_keys) {
375 TypeIndex fwd = full_to_forward[full];
376 m_parent_types[fwd] = m_parent_types[full];
377 }
378
379 // Now that
380}
381
382static bool isLocalVariableType(SymbolKind K) {
383 switch (K) {
384 case S_REGISTER:
385 case S_REGREL32:
386 case S_LOCAL:
387 return true;
388 default:
389 break;
390 }
391 return false;
392}
393
394static std::string
395RenderScopeList(llvm::ArrayRef<llvm::ms_demangle::Node *> nodes) {
396 lldbassert(!nodes.empty())lldb_private::lldb_assert(static_cast<bool>(!nodes.empty
()), "!nodes.empty()", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 396)
;
397
398 std::string result = nodes.front()->toString();
399 nodes = nodes.drop_front();
400 while (!nodes.empty()) {
401 result += "::";
402 result += nodes.front()->toString(llvm::ms_demangle::OF_NoTagSpecifier);
403 nodes = nodes.drop_front();
404 }
405 return result;
406}
407
408static llvm::Optional<PublicSym32> FindPublicSym(const SegmentOffset &addr,
409 SymbolStream &syms,
410 PublicsStream &publics) {
411 llvm::FixedStreamArray<ulittle32_t> addr_map = publics.getAddressMap();
412 auto iter = std::lower_bound(
413 addr_map.begin(), addr_map.end(), addr,
414 [&](const ulittle32_t &x, const SegmentOffset &y) {
415 CVSymbol s1 = syms.readRecord(x);
416 lldbassert(s1.kind() == S_PUB32)lldb_private::lldb_assert(static_cast<bool>(s1.kind() ==
S_PUB32), "s1.kind() == S_PUB32", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 416)
;
417 PublicSym32 p1;
418 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(s1, p1));
419 if (p1.Segment < y.segment)
420 return true;
421 return p1.Offset < y.offset;
422 });
423 if (iter == addr_map.end())
424 return llvm::None;
425 CVSymbol sym = syms.readRecord(*iter);
426 lldbassert(sym.kind() == S_PUB32)lldb_private::lldb_assert(static_cast<bool>(sym.kind() ==
S_PUB32), "sym.kind() == S_PUB32", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 426)
;
427 PublicSym32 p;
428 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(sym, p));
429 if (p.Segment == addr.segment && p.Offset == addr.offset)
430 return p;
431 return llvm::None;
432}
433
434clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) {
435 CVSymbol cvs = m_index.ReadSymbolRecord(id);
436
437 if (isLocalVariableType(cvs.kind())) {
438 clang::DeclContext *scope = GetParentDeclContext(id);
439 clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope);
440 PdbCompilandSymId scope_id(id.modi, m_decl_to_status[scope_decl].uid);
441 return GetOrCreateVariableDecl(scope_id, id);
442 }
443
444 switch (cvs.kind()) {
445 case S_GPROC32:
446 case S_LPROC32:
447 return GetOrCreateFunctionDecl(id);
448 case S_GDATA32:
449 case S_LDATA32:
450 case S_GTHREAD32:
451 case S_CONSTANT:
452 // global variable
453 return nullptr;
454 case S_BLOCK32:
455 return GetOrCreateBlockDecl(id);
456 default:
457 return nullptr;
458 }
459}
460
461llvm::Optional<CompilerDecl> PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) {
462 if (clang::Decl *result = TryGetDecl(uid))
463 return ToCompilerDecl(*result);
464
465 clang::Decl *result = nullptr;
466 switch (uid.kind()) {
467 case PdbSymUidKind::CompilandSym:
468 result = GetOrCreateSymbolForId(uid.asCompilandSym());
469 break;
470 case PdbSymUidKind::Type: {
471 clang::QualType qt = GetOrCreateType(uid.asTypeSym());
472 if (auto *tag = qt->getAsTagDecl()) {
473 result = tag;
474 break;
475 }
476 return llvm::None;
477 }
478 default:
479 return llvm::None;
480 }
481 m_uid_to_decl[toOpaqueUid(uid)] = result;
482 return ToCompilerDecl(*result);
483}
484
485clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) {
486 if (uid.kind() == PdbSymUidKind::CompilandSym) {
487 if (uid.asCompilandSym().offset == 0)
488 return FromCompilerDeclContext(GetTranslationUnitDecl());
489 }
490 auto option = GetOrCreateDeclForUid(uid);
491 if (!option)
492 return nullptr;
493 clang::Decl *decl = FromCompilerDecl(option.getValue());
494 if (!decl)
495 return nullptr;
496
497 return clang::Decl::castToDeclContext(decl);
498}
499
500std::pair<clang::DeclContext *, std::string>
501PdbAstBuilder::CreateDeclInfoForUndecoratedName(llvm::StringRef name) {
502 MSVCUndecoratedNameParser parser(name);
503 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
504
505 auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
506
507 llvm::StringRef uname = specs.back().GetBaseName();
508 specs = specs.drop_back();
509 if (specs.empty())
510 return {context, std::string(name)};
511
512 llvm::StringRef scope_name = specs.back().GetFullName();
513
514 // It might be a class name, try that first.
515 std::vector<TypeIndex> types = m_index.tpi().findRecordsByName(scope_name);
516 while (!types.empty()) {
517 clang::QualType qt = GetOrCreateType(types.back());
518 clang::TagDecl *tag = qt->getAsTagDecl();
519 if (tag)
520 return {clang::TagDecl::castToDeclContext(tag), std::string(uname)};
521 types.pop_back();
522 }
523
524 // If that fails, treat it as a series of namespaces.
525 for (const MSVCUndecoratedNameSpecifier &spec : specs) {
526 std::string ns_name = spec.GetBaseName().str();
527 context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context);
528 }
529 return {context, std::string(uname)};
530}
531
532clang::DeclContext *
533PdbAstBuilder::GetParentDeclContextForSymbol(const CVSymbol &sym) {
534 if (!SymbolHasAddress(sym))
535 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first;
536 SegmentOffset addr = GetSegmentAndOffset(sym);
537 llvm::Optional<PublicSym32> pub =
538 FindPublicSym(addr, m_index.symrecords(), m_index.publics());
539 if (!pub)
540 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first;
541
542 llvm::ms_demangle::Demangler demangler;
543 StringView name{pub->Name.begin(), pub->Name.size()};
544 llvm::ms_demangle::SymbolNode *node = demangler.parse(name);
545 if (!node)
546 return FromCompilerDeclContext(GetTranslationUnitDecl());
547 llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{
548 node->Name->Components->Nodes, node->Name->Components->Count - 1};
549
550 if (!name_components.empty()) {
551 // Render the current list of scope nodes as a fully qualified name, and
552 // look it up in the debug info as a type name. If we find something,
553 // this is a type (which may itself be prefixed by a namespace). If we
554 // don't, this is a list of namespaces.
555 std::string qname = RenderScopeList(name_components);
556 std::vector<TypeIndex> matches = m_index.tpi().findRecordsByName(qname);
557 while (!matches.empty()) {
558 clang::QualType qt = GetOrCreateType(matches.back());
559 clang::TagDecl *tag = qt->getAsTagDecl();
560 if (tag)
561 return clang::TagDecl::castToDeclContext(tag);
562 matches.pop_back();
563 }
564 }
565
566 // It's not a type. It must be a series of namespaces.
567 auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
568 while (!name_components.empty()) {
569 std::string ns = name_components.front()->toString();
570 context = GetOrCreateNamespaceDecl(ns.c_str(), *context);
571 name_components = name_components.drop_front();
572 }
573 return context;
574}
575
576clang::DeclContext *PdbAstBuilder::GetParentDeclContext(PdbSymUid uid) {
577 // We must do this *without* calling GetOrCreate on the current uid, as
578 // that would be an infinite recursion.
579 switch (uid.kind()) {
580 case PdbSymUidKind::CompilandSym: {
581 llvm::Optional<PdbCompilandSymId> scope =
582 FindSymbolScope(m_index, uid.asCompilandSym());
583 if (scope)
584 return GetOrCreateDeclContextForUid(*scope);
585
586 CVSymbol sym = m_index.ReadSymbolRecord(uid.asCompilandSym());
587 return GetParentDeclContextForSymbol(sym);
588 }
589 case PdbSymUidKind::Type: {
590 // It could be a namespace, class, or global. We don't support nested
591 // functions yet. Anyway, we just need to consult the parent type map.
592 PdbTypeSymId type_id = uid.asTypeSym();
593 auto iter = m_parent_types.find(type_id.index);
594 if (iter == m_parent_types.end())
595 return FromCompilerDeclContext(GetTranslationUnitDecl());
596 return GetOrCreateDeclContextForUid(PdbTypeSymId(iter->second));
597 }
598 case PdbSymUidKind::FieldListMember:
599 // In this case the parent DeclContext is the one for the class that this
600 // member is inside of.
601 break;
602 case PdbSymUidKind::GlobalSym: {
603 // If this refers to a compiland symbol, just recurse in with that symbol.
604 // The only other possibilities are S_CONSTANT and S_UDT, in which case we
605 // need to parse the undecorated name to figure out the scope, then look
606 // that up in the TPI stream. If it's found, it's a type, othewrise it's
607 // a series of namespaces.
608 // FIXME: do this.
609 CVSymbol global = m_index.ReadSymbolRecord(uid.asGlobalSym());
610 switch (global.kind()) {
611 case SymbolKind::S_GDATA32:
612 case SymbolKind::S_LDATA32:
613 return GetParentDeclContextForSymbol(global);
614 case SymbolKind::S_PROCREF:
615 case SymbolKind::S_LPROCREF: {
616 ProcRefSym ref{global.kind()};
617 llvm::cantFail(
618 SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref));
619 PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset};
620 return GetParentDeclContext(cu_sym_id);
621 }
622 case SymbolKind::S_CONSTANT:
623 case SymbolKind::S_UDT:
624 return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first;
625 default:
626 break;
627 }
628 break;
629 }
630 default:
631 break;
632 }
633 return FromCompilerDeclContext(GetTranslationUnitDecl());
634}
635
636bool PdbAstBuilder::CompleteType(clang::QualType qt) {
637 clang::TagDecl *tag = qt->getAsTagDecl();
638 if (!tag)
639 return false;
640
641 return CompleteTagDecl(*tag);
642}
643
644bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) {
645 // If this is not in our map, it's an error.
646 auto status_iter = m_decl_to_status.find(&tag);
647 lldbassert(status_iter != m_decl_to_status.end())lldb_private::lldb_assert(static_cast<bool>(status_iter
!= m_decl_to_status.end()), "status_iter != m_decl_to_status.end()"
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 647)
;
648
649 // If it's already complete, just return.
650 DeclStatus &status = status_iter->second;
651 if (status.resolved)
652 return true;
653
654 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
655
656 lldbassert(IsTagRecord(type_id, m_index.tpi()))lldb_private::lldb_assert(static_cast<bool>(IsTagRecord
(type_id, m_index.tpi())), "IsTagRecord(type_id, m_index.tpi())"
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 656)
;
657
658 clang::QualType tag_qt = m_clang.getASTContext().getTypeDeclType(&tag);
659 TypeSystemClang::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false);
660
661 TypeIndex tag_ti = type_id.index;
662 CVType cvt = m_index.tpi().getType(tag_ti);
663 if (cvt.kind() == LF_MODIFIER)
664 tag_ti = LookThroughModifierRecord(cvt);
665
666 PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi());
667 cvt = m_index.tpi().getType(best_ti.index);
668 lldbassert(IsTagRecord(cvt))lldb_private::lldb_assert(static_cast<bool>(IsTagRecord
(cvt)), "IsTagRecord(cvt)", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 668)
;
669
670 if (IsForwardRefUdt(cvt)) {
671 // If we can't find a full decl for this forward ref anywhere in the debug
672 // info, then we have no way to complete it.
673 return false;
674 }
675
676 TypeIndex field_list_ti = GetFieldListIndex(cvt);
677 CVType field_list_cvt = m_index.tpi().getType(field_list_ti);
678 if (field_list_cvt.kind() != LF_FIELDLIST)
679 return false;
680
681 // Visit all members of this class, then perform any finalization necessary
682 // to complete the class.
683 CompilerType ct = ToCompilerType(tag_qt);
684 UdtRecordCompleter completer(best_ti, ct, tag, *this, m_index);
685 auto error =
686 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
687 completer.complete();
688
689 status.resolved = true;
690 if (!error)
691 return true;
692
693 llvm::consumeError(std::move(error));
694 return false;
695}
696
697clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) {
698 if (ti == TypeIndex::NullptrT())
699 return GetBasicType(lldb::eBasicTypeNullPtr);
700
701 if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
702 clang::QualType direct_type = GetOrCreateType(ti.makeDirect());
703 return m_clang.getASTContext().getPointerType(direct_type);
704 }
705
706 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
707 return {};
708
709 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
710 if (bt == lldb::eBasicTypeInvalid)
711 return {};
712
713 return GetBasicType(bt);
714}
715
716clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) {
717 clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType);
718
719 // This can happen for pointers to LF_VTSHAPE records, which we shouldn't
720 // create in the AST.
721 if (pointee_type.isNull())
722 return {};
723
724 if (pointer.isPointerToMember()) {
725 MemberPointerInfo mpi = pointer.getMemberInfo();
726 clang::QualType class_type = GetOrCreateType(mpi.ContainingType);
727
728 return m_clang.getASTContext().getMemberPointerType(
729 pointee_type, class_type.getTypePtr());
730 }
731
732 clang::QualType pointer_type;
733 if (pointer.getMode() == PointerMode::LValueReference)
734 pointer_type = m_clang.getASTContext().getLValueReferenceType(pointee_type);
735 else if (pointer.getMode() == PointerMode::RValueReference)
736 pointer_type = m_clang.getASTContext().getRValueReferenceType(pointee_type);
737 else
738 pointer_type = m_clang.getASTContext().getPointerType(pointee_type);
739
740 if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None)
741 pointer_type.addConst();
742
743 if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
744 pointer_type.addVolatile();
745
746 if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
747 pointer_type.addRestrict();
748
749 return pointer_type;
750}
751
752clang::QualType
753PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) {
754 clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType);
755 if (unmodified_type.isNull())
756 return {};
757
758 if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
759 unmodified_type.addConst();
760 if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
761 unmodified_type.addVolatile();
762
763 return unmodified_type;
764}
765
766clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id,
767 const TagRecord &record) {
768 clang::DeclContext *context = nullptr;
769 std::string uname;
770 std::tie(context, uname) = CreateDeclInfoForType(record, id.index);
771 clang::TagTypeKind ttk = TranslateUdtKind(record);
772 lldb::AccessType access =
773 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
774
775 ClangASTMetadata metadata;
776 metadata.SetUserID(toOpaqueUid(id));
777 metadata.SetIsDynamicCXXType(false);
778
779 CompilerType ct =
780 m_clang.CreateRecordType(context, OptionalClangModuleID(), access, uname,
781 ttk, lldb::eLanguageTypeC_plus_plus, &metadata);
782
783 lldbassert(ct.IsValid())lldb_private::lldb_assert(static_cast<bool>(ct.IsValid(
)), "ct.IsValid()", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 783)
;
784
785 TypeSystemClang::StartTagDeclarationDefinition(ct);
786
787 // Even if it's possible, don't complete it at this point. Just mark it
788 // forward resolved, and if/when LLDB needs the full definition, it can
789 // ask us.
790 clang::QualType result =
791 clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
792
793 TypeSystemClang::SetHasExternalStorage(result.getAsOpaquePtr(), true);
794 return result;
795}
796
797clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const {
798 auto iter = m_uid_to_decl.find(toOpaqueUid(uid));
799 if (iter != m_uid_to_decl.end())
800 return iter->second;
801 return nullptr;
802}
803
804clang::NamespaceDecl *
805PdbAstBuilder::GetOrCreateNamespaceDecl(const char *name,
806 clang::DeclContext &context) {
807 return m_clang.GetUniqueNamespaceDeclaration(
808 IsAnonymousNamespaceName(name) ? nullptr : name, &context,
809 OptionalClangModuleID());
810}
811
812clang::BlockDecl *
813PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) {
814 if (clang::Decl *decl = TryGetDecl(block_id))
815 return llvm::dyn_cast<clang::BlockDecl>(decl);
816
817 clang::DeclContext *scope = GetParentDeclContext(block_id);
818
819 clang::BlockDecl *block_decl =
820 m_clang.CreateBlockDeclaration(scope, OptionalClangModuleID());
821 m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl});
822
823 DeclStatus status;
824 status.resolved = true;
825 status.uid = toOpaqueUid(block_id);
826 m_decl_to_status.insert({block_decl, status});
827
828 return block_decl;
829}
830
831clang::VarDecl *PdbAstBuilder::CreateVariableDecl(PdbSymUid uid, CVSymbol sym,
832 clang::DeclContext &scope) {
833 VariableInfo var_info = GetVariableNameInfo(sym);
834 clang::QualType qt = GetOrCreateType(var_info.type);
835
836 clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration(
837 &scope, OptionalClangModuleID(), var_info.name.str().c_str(), qt);
838
839 m_uid_to_decl[toOpaqueUid(uid)] = var_decl;
840 DeclStatus status;
841 status.resolved = true;
842 status.uid = toOpaqueUid(uid);
843 m_decl_to_status.insert({var_decl, status});
844 return var_decl;
845}
846
847clang::VarDecl *
848PdbAstBuilder::GetOrCreateVariableDecl(PdbCompilandSymId scope_id,
849 PdbCompilandSymId var_id) {
850 if (clang::Decl *decl = TryGetDecl(var_id))
851 return llvm::dyn_cast<clang::VarDecl>(decl);
852
853 clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id);
854
855 CVSymbol sym = m_index.ReadSymbolRecord(var_id);
856 return CreateVariableDecl(PdbSymUid(var_id), sym, *scope);
857}
858
859clang::VarDecl *PdbAstBuilder::GetOrCreateVariableDecl(PdbGlobalSymId var_id) {
860 if (clang::Decl *decl = TryGetDecl(var_id))
861 return llvm::dyn_cast<clang::VarDecl>(decl);
862
863 CVSymbol sym = m_index.ReadSymbolRecord(var_id);
864 auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
865 return CreateVariableDecl(PdbSymUid(var_id), sym, *context);
866}
867
868clang::TypedefNameDecl *
869PdbAstBuilder::GetOrCreateTypedefDecl(PdbGlobalSymId id) {
870 if (clang::Decl *decl = TryGetDecl(id))
871 return llvm::dyn_cast<clang::TypedefNameDecl>(decl);
872
873 CVSymbol sym = m_index.ReadSymbolRecord(id);
874 lldbassert(sym.kind() == S_UDT)lldb_private::lldb_assert(static_cast<bool>(sym.kind() ==
S_UDT), "sym.kind() == S_UDT", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 874)
;
875 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
876
877 clang::DeclContext *scope = GetParentDeclContext(id);
878
879 PdbTypeSymId real_type_id{udt.Type, false};
880 clang::QualType qt = GetOrCreateType(real_type_id);
881
882 std::string uname = std::string(DropNameScope(udt.Name));
883
884 CompilerType ct = ToCompilerType(qt).CreateTypedef(
885 uname.c_str(), ToCompilerDeclContext(*scope), 0);
886 clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct);
887 DeclStatus status;
888 status.resolved = true;
889 status.uid = toOpaqueUid(id);
890 m_decl_to_status.insert({tnd, status});
891 return tnd;
892}
893
894clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) {
895 CompilerType ct = m_clang.GetBasicType(type);
896 return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
897}
898
899clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) {
900 if (type.index.isSimple())
901 return CreateSimpleType(type.index);
902
903 CVType cvt = m_index.tpi().getType(type.index);
904
905 if (cvt.kind() == LF_MODIFIER) {
906 ModifierRecord modifier;
907 llvm::cantFail(
908 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
909 return CreateModifierType(modifier);
910 }
911
912 if (cvt.kind() == LF_POINTER) {
913 PointerRecord pointer;
914 llvm::cantFail(
915 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
916 return CreatePointerType(pointer);
917 }
918
919 if (IsTagRecord(cvt)) {
920 CVTagRecord tag = CVTagRecord::create(cvt);
921 if (tag.kind() == CVTagRecord::Union)
922 return CreateRecordType(type.index, tag.asUnion());
923 if (tag.kind() == CVTagRecord::Enum)
924 return CreateEnumType(type.index, tag.asEnum());
925 return CreateRecordType(type.index, tag.asClass());
926 }
927
928 if (cvt.kind() == LF_ARRAY) {
929 ArrayRecord ar;
930 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
931 return CreateArrayType(ar);
932 }
933
934 if (cvt.kind() == LF_PROCEDURE) {
935 ProcedureRecord pr;
936 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
937 return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv);
938 }
939
940 if (cvt.kind() == LF_MFUNCTION) {
941 MemberFunctionRecord mfr;
942 llvm::cantFail(
943 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
944 return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv);
945 }
946
947 return {};
948}
949
950clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) {
951 lldb::user_id_t uid = toOpaqueUid(type);
952 auto iter = m_uid_to_type.find(uid);
953 if (iter != m_uid_to_type.end())
954 return iter->second;
955
956 PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi());
957
958 clang::QualType qt;
959 if (best_type.index != type.index) {
960 // This is a forward decl. Call GetOrCreate on the full decl, then map the
961 // forward decl id to the full decl QualType.
962 clang::QualType qt = GetOrCreateType(best_type);
963 m_uid_to_type[toOpaqueUid(type)] = qt;
964 return qt;
965 }
966
967 // This is either a full decl, or a forward decl with no matching full decl
968 // in the debug info.
969 qt = CreateType(type);
970 m_uid_to_type[toOpaqueUid(type)] = qt;
971 if (IsTagRecord(type, m_index.tpi())) {
972 clang::TagDecl *tag = qt->getAsTagDecl();
973 lldbassert(m_decl_to_status.count(tag) == 0)lldb_private::lldb_assert(static_cast<bool>(m_decl_to_status
.count(tag) == 0), "m_decl_to_status.count(tag) == 0", __FUNCTION__
, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 973)
;
974
975 DeclStatus &status = m_decl_to_status[tag];
976 status.uid = uid;
977 status.resolved = false;
978 }
979 return qt;
980}
981
982clang::FunctionDecl *
983PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) {
984 if (clang::Decl *decl = TryGetDecl(func_id))
985 return llvm::dyn_cast<clang::FunctionDecl>(decl);
986
987 clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id));
988 std::string context_name;
989 if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) {
990 context_name = ns->getQualifiedNameAsString();
991 } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) {
992 context_name = tag->getQualifiedNameAsString();
993 }
994
995 CVSymbol cvs = m_index.ReadSymbolRecord(func_id);
996 ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind()));
997 llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc));
998
999 PdbTypeSymId type_id(proc.FunctionType);
1000 clang::QualType qt = GetOrCreateType(type_id);
1001 if (qt.isNull())
1002 return nullptr;
1003
1004 clang::StorageClass storage = clang::SC_None;
1005 if (proc.Kind == SymbolRecordKind::ProcSym)
1006 storage = clang::SC_Static;
1007
1008 const clang::FunctionProtoType *func_type =
1009 llvm::dyn_cast<clang::FunctionProtoType>(qt);
1010
1011 CompilerType func_ct = ToCompilerType(qt);
1012
1013 llvm::StringRef proc_name = proc.Name;
1014 proc_name.consume_front(context_name);
1015 proc_name.consume_front("::");
1016
1017 clang::FunctionDecl *function_decl = m_clang.CreateFunctionDeclaration(
1018 parent, OptionalClangModuleID(), proc_name, func_ct, storage, false);
1019
1020 lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0)lldb_private::lldb_assert(static_cast<bool>(m_uid_to_decl
.count(toOpaqueUid(func_id)) == 0), "m_uid_to_decl.count(toOpaqueUid(func_id)) == 0"
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 1020)
;
1021 m_uid_to_decl[toOpaqueUid(func_id)] = function_decl;
1022 DeclStatus status;
1023 status.resolved = true;
1024 status.uid = toOpaqueUid(func_id);
1025 m_decl_to_status.insert({function_decl, status});
1026
1027 CreateFunctionParameters(func_id, *function_decl, func_type->getNumParams());
1028
1029 return function_decl;
1030}
1031
1032void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id,
1033 clang::FunctionDecl &function_decl,
1034 uint32_t param_count) {
1035 CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi);
1036 CVSymbolArray scope =
1037 cii->m_debug_stream.getSymbolArrayForScope(func_id.offset);
1038
1039 auto begin = scope.begin();
1040 auto end = scope.end();
1041 std::vector<clang::ParmVarDecl *> params;
1042 while (begin != end && param_count > 0) {
1043 uint32_t record_offset = begin.offset();
1044 CVSymbol sym = *begin++;
1045
1046 TypeIndex param_type;
1047 llvm::StringRef param_name;
1048 switch (sym.kind()) {
1049 case S_REGREL32: {
1050 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
1051 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
1052 param_type = reg.Type;
1053 param_name = reg.Name;
1054 break;
1055 }
1056 case S_REGISTER: {
1057 RegisterSym reg(SymbolRecordKind::RegisterSym);
1058 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
1059 param_type = reg.Index;
1060 param_name = reg.Name;
1061 break;
1062 }
1063 case S_LOCAL: {
1064 LocalSym local(SymbolRecordKind::LocalSym);
1065 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
1066 if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None)
1067 continue;
1068 param_type = local.Type;
1069 param_name = local.Name;
1070 break;
1071 }
1072 case S_BLOCK32:
1073 // All parameters should come before the first block. If that isn't the
1074 // case, then perhaps this is bad debug info that doesn't contain
1075 // information about all parameters.
1076 return;
1077 default:
1078 continue;
1079 }
1080
1081 PdbCompilandSymId param_uid(func_id.modi, record_offset);
1082 clang::QualType qt = GetOrCreateType(param_type);
1083
1084 CompilerType param_type_ct = m_clang.GetType(qt);
1085 clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration(
1086 &function_decl, OptionalClangModuleID(), param_name.str().c_str(),
1087 param_type_ct, clang::SC_None, true);
1088 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0)lldb_private::lldb_assert(static_cast<bool>(m_uid_to_decl
.count(toOpaqueUid(param_uid)) == 0), "m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0"
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 1088)
;
1089
1090 m_uid_to_decl[toOpaqueUid(param_uid)] = param;
1091 params.push_back(param);
1092 --param_count;
1093 }
1094
1095 if (!params.empty())
1096 m_clang.SetFunctionParameters(&function_decl, params);
1097}
1098
1099clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id,
1100 const EnumRecord &er) {
1101 clang::DeclContext *decl_context = nullptr;
1102 std::string uname;
1103 std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index);
1104 clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType);
1105
1106 Declaration declaration;
1107 CompilerType enum_ct = m_clang.CreateEnumerationType(
1108 uname.c_str(), decl_context, OptionalClangModuleID(), declaration,
1109 ToCompilerType(underlying_type), er.isScoped());
1110
1111 TypeSystemClang::StartTagDeclarationDefinition(enum_ct);
1112 TypeSystemClang::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
1113
1114 return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType());
1115}
1116
1117clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) {
1118 clang::QualType element_type = GetOrCreateType(ar.ElementType);
1119
1120 uint64_t element_count =
1121 ar.Size / GetSizeOfType({ar.ElementType}, m_index.tpi());
1122
1123 CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type),
1124 element_count, false);
1125 return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType());
1126}
1127
1128clang::QualType PdbAstBuilder::CreateFunctionType(
1129 TypeIndex args_type_idx, TypeIndex return_type_idx,
1130 llvm::codeview::CallingConvention calling_convention) {
1131 TpiStream &stream = m_index.tpi();
1132 CVType args_cvt = stream.getType(args_type_idx);
1133 ArgListRecord args;
1134 llvm::cantFail(
1135 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
1136
1137 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
1138 bool is_variadic = IsCVarArgsFunction(arg_indices);
1139 if (is_variadic)
1140 arg_indices = arg_indices.drop_back();
1141
1142 std::vector<CompilerType> arg_types;
1143 arg_types.reserve(arg_indices.size());
1144
1145 for (TypeIndex arg_index : arg_indices) {
1146 clang::QualType arg_type = GetOrCreateType(arg_index);
1147 arg_types.push_back(ToCompilerType(arg_type));
1148 }
1149
1150 clang::QualType return_type = GetOrCreateType(return_type_idx);
1151
1152 llvm::Optional<clang::CallingConv> cc =
1153 TranslateCallingConvention(calling_convention);
1154 if (!cc)
1155 return {};
1156
1157 CompilerType return_ct = ToCompilerType(return_type);
1158 CompilerType func_sig_ast_type = m_clang.CreateFunctionType(
1159 return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc);
1160
1161 return clang::QualType::getFromOpaquePtr(
1162 func_sig_ast_type.GetOpaqueQualType());
1163}
1164
1165static bool isTagDecl(clang::DeclContext &context) {
1166 return !!llvm::dyn_cast<clang::TagDecl>(&context);
1167}
1168
1169static bool isFunctionDecl(clang::DeclContext &context) {
1170 return !!llvm::dyn_cast<clang::FunctionDecl>(&context);
1171}
1172
1173static bool isBlockDecl(clang::DeclContext &context) {
1174 return !!llvm::dyn_cast<clang::BlockDecl>(&context);
1175}
1176
1177void PdbAstBuilder::ParseAllNamespacesPlusChildrenOf(
1178 llvm::Optional<llvm::StringRef> parent) {
1179 TypeIndex ti{m_index.tpi().TypeIndexBegin()};
1180 for (const CVType &cvt : m_index.tpi().typeArray()) {
1181 PdbTypeSymId tid{ti};
1182 ++ti;
1183
1184 if (!IsTagRecord(cvt))
5
Assuming the condition is false
6
Taking false branch
1185 continue;
1186
1187 CVTagRecord tag = CVTagRecord::create(cvt);
1188
1189 if (!parent.hasValue()) {
7
Calling 'Optional::hasValue'
12
Returning from 'Optional::hasValue'
13
Taking false branch
1190 clang::QualType qt = GetOrCreateType(tid);
1191 CompleteType(qt);
1192 continue;
1193 }
1194
1195 // Call CreateDeclInfoForType unconditionally so that the namespace info
1196 // gets created. But only call CreateRecordType if the namespace name
1197 // matches.
1198 clang::DeclContext *context = nullptr;
1199 std::string uname;
1200 std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index);
1201 if (!context->isNamespace())
14
Calling 'DeclContext::isNamespace'
17
Returning from 'DeclContext::isNamespace'
18
Taking false branch
1202 continue;
1203
1204 clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(context);
19
Assuming 'context' is not a 'NamespaceDecl'
20
'ns' initialized to a null pointer value
1205 std::string actual_ns = ns->getQualifiedNameAsString();
21
Called C++ object pointer is null
1206 if (llvm::StringRef(actual_ns).startswith(*parent)) {
1207 clang::QualType qt = GetOrCreateType(tid);
1208 CompleteType(qt);
1209 continue;
1210 }
1211 }
1212
1213 uint32_t module_count = m_index.dbi().modules().getModuleCount();
1214 for (uint16_t modi = 0; modi < module_count; ++modi) {
1215 CompilandIndexItem &cii = m_index.compilands().GetOrCreateCompiland(modi);
1216 const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray();
1217 auto iter = symbols.begin();
1218 while (iter != symbols.end()) {
1219 PdbCompilandSymId sym_id{modi, iter.offset()};
1220
1221 switch (iter->kind()) {
1222 case S_GPROC32:
1223 case S_LPROC32:
1224 GetOrCreateFunctionDecl(sym_id);
1225 iter = symbols.at(getScopeEndOffset(*iter));
1226 break;
1227 case S_GDATA32:
1228 case S_GTHREAD32:
1229 case S_LDATA32:
1230 case S_LTHREAD32:
1231 GetOrCreateVariableDecl(PdbCompilandSymId(modi, 0), sym_id);
1232 ++iter;
1233 break;
1234 default:
1235 ++iter;
1236 continue;
1237 }
1238 }
1239 }
1240}
1241
1242static CVSymbolArray skipFunctionParameters(clang::Decl &decl,
1243 const CVSymbolArray &symbols) {
1244 clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl);
1245 if (!func_decl)
1246 return symbols;
1247 unsigned int params = func_decl->getNumParams();
1248 if (params == 0)
1249 return symbols;
1250
1251 CVSymbolArray result = symbols;
1252
1253 while (!result.empty()) {
1254 if (params == 0)
1255 return result;
1256
1257 CVSymbol sym = *result.begin();
1258 result.drop_front();
1259
1260 if (!isLocalVariableType(sym.kind()))
1261 continue;
1262
1263 --params;
1264 }
1265 return result;
1266}
1267
1268void PdbAstBuilder::ParseBlockChildren(PdbCompilandSymId block_id) {
1269 CVSymbol sym = m_index.ReadSymbolRecord(block_id);
1270 lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 ||lldb_private::lldb_assert(static_cast<bool>(sym.kind() ==
S_GPROC32 || sym.kind() == S_LPROC32 || sym.kind() == S_BLOCK32
), "sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 || sym.kind() == S_BLOCK32"
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 1271)
1271 sym.kind() == S_BLOCK32)lldb_private::lldb_assert(static_cast<bool>(sym.kind() ==
S_GPROC32 || sym.kind() == S_LPROC32 || sym.kind() == S_BLOCK32
), "sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 || sym.kind() == S_BLOCK32"
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 1271)
;
1272 CompilandIndexItem &cii =
1273 m_index.compilands().GetOrCreateCompiland(block_id.modi);
1274 CVSymbolArray symbols =
1275 cii.m_debug_stream.getSymbolArrayForScope(block_id.offset);
1276
1277 // Function parameters should already have been created when the function was
1278 // parsed.
1279 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32)
1280 symbols =
1281 skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols);
1282
1283 auto begin = symbols.begin();
1284 while (begin != symbols.end()) {
1285 PdbCompilandSymId child_sym_id(block_id.modi, begin.offset());
1286 GetOrCreateSymbolForId(child_sym_id);
1287 if (begin->kind() == S_BLOCK32) {
1288 ParseBlockChildren(child_sym_id);
1289 begin = symbols.at(getScopeEndOffset(*begin));
1290 }
1291 ++begin;
1292 }
1293}
1294
1295void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) {
1296
1297 clang::Decl *decl = clang::Decl::castFromDeclContext(&context);
1298 lldbassert(decl)lldb_private::lldb_assert(static_cast<bool>(decl), "decl"
, __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 1298)
;
1299
1300 auto iter = m_decl_to_status.find(decl);
1301 lldbassert(iter != m_decl_to_status.end())lldb_private::lldb_assert(static_cast<bool>(iter != m_decl_to_status
.end()), "iter != m_decl_to_status.end()", __FUNCTION__, "/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp"
, 1301)
;
1302
1303 if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) {
1304 CompleteTagDecl(*tag);
1305 return;
1306 }
1307
1308 if (isFunctionDecl(context) || isBlockDecl(context)) {
1309 PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym();
1310 ParseBlockChildren(block_id);
1311 }
1312}
1313
1314void PdbAstBuilder::ParseDeclsForContext(clang::DeclContext &context) {
1315 // Namespaces aren't explicitly represented in the debug info, and the only
1316 // way to parse them is to parse all type info, demangling every single type
1317 // and trying to reconstruct the DeclContext hierarchy this way. Since this
1318 // is an expensive operation, we have to special case it so that we do other
1319 // work (such as parsing the items that appear within the namespaces) at the
1320 // same time.
1321 if (context.isTranslationUnit()) {
1
Taking false branch
1322 ParseAllNamespacesPlusChildrenOf(llvm::None);
1323 return;
1324 }
1325
1326 if (context.isNamespace()) {
2
Taking true branch
1327 clang::NamespaceDecl &ns = *llvm::dyn_cast<clang::NamespaceDecl>(&context);
3
Assuming the object is a 'NamespaceDecl'
1328 std::string qname = ns.getQualifiedNameAsString();
1329 ParseAllNamespacesPlusChildrenOf(llvm::StringRef{qname});
4
Calling 'PdbAstBuilder::ParseAllNamespacesPlusChildrenOf'
1330 return;
1331 }
1332
1333 if (isTagDecl(context) || isFunctionDecl(context) || isBlockDecl(context)) {
1334 ParseDeclsForSimpleContext(context);
1335 return;
1336 }
1337}
1338
1339CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) {
1340 return m_clang.GetCompilerDecl(&decl);
1341}
1342
1343CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) {
1344 return {&m_clang, qt.getAsOpaquePtr()};
1345}
1346
1347CompilerDeclContext
1348PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) {
1349 return m_clang.CreateDeclContext(&context);
1350}
1351
1352clang::Decl * PdbAstBuilder::FromCompilerDecl(CompilerDecl decl) {
1353 return ClangUtil::GetDecl(decl);
1354}
1355
1356clang::DeclContext *
1357PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) {
1358 return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
1359}
1360
1361void PdbAstBuilder::Dump(Stream &stream) { m_clang.Dump(stream); }

/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/llvm/include/llvm/ADT/Optional.h

1//===- Optional.h - Simple variant for passing optional values --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Optional, a template class modeled in the spirit of
10// OCaml's 'opt' variant. The idea is to strongly type whether or not
11// a value can be optional.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_OPTIONAL_H
16#define LLVM_ADT_OPTIONAL_H
17
18#include "llvm/ADT/Hashing.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/STLForwardCompat.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/type_traits.h"
23#include <cassert>
24#include <memory>
25#include <new>
26#include <utility>
27
28namespace llvm {
29
30class raw_ostream;
31
32namespace optional_detail {
33
34/// Storage for any type.
35//
36// The specialization condition intentionally uses
37// llvm::is_trivially_copy_constructible instead of
38// std::is_trivially_copy_constructible. GCC versions prior to 7.4 may
39// instantiate the copy constructor of `T` when
40// std::is_trivially_copy_constructible is instantiated. This causes
41// compilation to fail if we query the trivially copy constructible property of
42// a class which is not copy constructible.
43//
44// The current implementation of OptionalStorage insists that in order to use
45// the trivial specialization, the value_type must be trivially copy
46// constructible and trivially copy assignable due to =default implementations
47// of the copy/move constructor/assignment. It does not follow that this is
48// necessarily the case std::is_trivially_copyable is true (hence the expanded
49// specialization condition).
50//
51// The move constructible / assignable conditions emulate the remaining behavior
52// of std::is_trivially_copyable.
53template <typename T, bool = (llvm::is_trivially_copy_constructible<T>::value &&
54 std::is_trivially_copy_assignable<T>::value &&
55 (std::is_trivially_move_constructible<T>::value ||
56 !std::is_move_constructible<T>::value) &&
57 (std::is_trivially_move_assignable<T>::value ||
58 !std::is_move_assignable<T>::value))>
59class OptionalStorage {
60 union {
61 char empty;
62 T value;
63 };
64 bool hasVal;
65
66public:
67 ~OptionalStorage() { reset(); }
68
69 constexpr OptionalStorage() noexcept : empty(), hasVal(false) {}
70
71 constexpr OptionalStorage(OptionalStorage const &other) : OptionalStorage() {
72 if (other.hasValue()) {
73 emplace(other.value);
74 }
75 }
76 constexpr OptionalStorage(OptionalStorage &&other) : OptionalStorage() {
77 if (other.hasValue()) {
78 emplace(std::move(other.value));
79 }
80 }
81
82 template <class... Args>
83 constexpr explicit OptionalStorage(in_place_t, Args &&... args)
84 : value(std::forward<Args>(args)...), hasVal(true) {}
85
86 void reset() noexcept {
87 if (hasVal) {
88 value.~T();
89 hasVal = false;
90 }
91 }
92
93 constexpr bool hasValue() const noexcept { return hasVal; }
94
95 T &getValue() LLVM_LVALUE_FUNCTION& noexcept {
96 assert(hasVal)((void)0);
97 return value;
98 }
99 constexpr T const &getValue() const LLVM_LVALUE_FUNCTION& noexcept {
100 assert(hasVal)((void)0);
101 return value;
102 }
103#if LLVM_HAS_RVALUE_REFERENCE_THIS1
104 T &&getValue() && noexcept {
105 assert(hasVal)((void)0);
106 return std::move(value);
107 }
108#endif
109
110 template <class... Args> void emplace(Args &&... args) {
111 reset();
112 ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...);
113 hasVal = true;
114 }
115
116 OptionalStorage &operator=(T const &y) {
117 if (hasValue()) {
118 value = y;
119 } else {
120 ::new ((void *)std::addressof(value)) T(y);
121 hasVal = true;
122 }
123 return *this;
124 }
125 OptionalStorage &operator=(T &&y) {
126 if (hasValue()) {
127 value = std::move(y);
128 } else {
129 ::new ((void *)std::addressof(value)) T(std::move(y));
130 hasVal = true;
131 }
132 return *this;
133 }
134
135 OptionalStorage &operator=(OptionalStorage const &other) {
136 if (other.hasValue()) {
137 if (hasValue()) {
138 value = other.value;
139 } else {
140 ::new ((void *)std::addressof(value)) T(other.value);
141 hasVal = true;
142 }
143 } else {
144 reset();
145 }
146 return *this;
147 }
148
149 OptionalStorage &operator=(OptionalStorage &&other) {
150 if (other.hasValue()) {
151 if (hasValue()) {
152 value = std::move(other.value);
153 } else {
154 ::new ((void *)std::addressof(value)) T(std::move(other.value));
155 hasVal = true;
156 }
157 } else {
158 reset();
159 }
160 return *this;
161 }
162};
163
164template <typename T> class OptionalStorage<T, true> {
165 union {
166 char empty;
167 T value;
168 };
169 bool hasVal = false;
170
171public:
172 ~OptionalStorage() = default;
173
174 constexpr OptionalStorage() noexcept : empty{} {}
175
176 constexpr OptionalStorage(OptionalStorage const &other) = default;
177 constexpr OptionalStorage(OptionalStorage &&other) = default;
178
179 OptionalStorage &operator=(OptionalStorage const &other) = default;
180 OptionalStorage &operator=(OptionalStorage &&other) = default;
181
182 template <class... Args>
183 constexpr explicit OptionalStorage(in_place_t, Args &&... args)
184 : value(std::forward<Args>(args)...), hasVal(true) {}
185
186 void reset() noexcept {
187 if (hasVal) {
188 value.~T();
189 hasVal = false;
190 }
191 }
192
193 constexpr bool hasValue() const noexcept { return hasVal; }
9
Returning the value 1, which participates in a condition later
194
195 T &getValue() LLVM_LVALUE_FUNCTION& noexcept {
196 assert(hasVal)((void)0);
197 return value;
198 }
199 constexpr T const &getValue() const LLVM_LVALUE_FUNCTION& noexcept {
200 assert(hasVal)((void)0);
201 return value;
202 }
203#if LLVM_HAS_RVALUE_REFERENCE_THIS1
204 T &&getValue() && noexcept {
205 assert(hasVal)((void)0);
206 return std::move(value);
207 }
208#endif
209
210 template <class... Args> void emplace(Args &&... args) {
211 reset();
212 ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...);
213 hasVal = true;
214 }
215
216 OptionalStorage &operator=(T const &y) {
217 if (hasValue()) {
218 value = y;
219 } else {
220 ::new ((void *)std::addressof(value)) T(y);
221 hasVal = true;
222 }
223 return *this;
224 }
225 OptionalStorage &operator=(T &&y) {
226 if (hasValue()) {
227 value = std::move(y);
228 } else {
229 ::new ((void *)std::addressof(value)) T(std::move(y));
230 hasVal = true;
231 }
232 return *this;
233 }
234};
235
236} // namespace optional_detail
237
238template <typename T> class Optional {
239 optional_detail::OptionalStorage<T> Storage;
240
241public:
242 using value_type = T;
243
244 constexpr Optional() {}
245 constexpr Optional(NoneType) {}
246
247 constexpr Optional(const T &y) : Storage(in_place, y) {}
248 constexpr Optional(const Optional &O) = default;
249
250 constexpr Optional(T &&y) : Storage(in_place, std::move(y)) {}
251 constexpr Optional(Optional &&O) = default;
252
253 template <typename... ArgTypes>
254 constexpr Optional(in_place_t, ArgTypes &&...Args)
255 : Storage(in_place, std::forward<ArgTypes>(Args)...) {}
256
257 Optional &operator=(T &&y) {
258 Storage = std::move(y);
259 return *this;
260 }
261 Optional &operator=(Optional &&O) = default;
262
263 /// Create a new object by constructing it in place with the given arguments.
264 template <typename... ArgTypes> void emplace(ArgTypes &&... Args) {
265 Storage.emplace(std::forward<ArgTypes>(Args)...);
266 }
267
268 static constexpr Optional create(const T *y) {
269 return y ? Optional(*y) : Optional();
270 }
271
272 Optional &operator=(const T &y) {
273 Storage = y;
274 return *this;
275 }
276 Optional &operator=(const Optional &O) = default;
277
278 void reset() { Storage.reset(); }
279
280 constexpr const T *getPointer() const { return &Storage.getValue(); }
281 T *getPointer() { return &Storage.getValue(); }
282 constexpr const T &getValue() const LLVM_LVALUE_FUNCTION& {
283 return Storage.getValue();
284 }
285 T &getValue() LLVM_LVALUE_FUNCTION& { return Storage.getValue(); }
286
287 constexpr explicit operator bool() const { return hasValue(); }
288 constexpr bool hasValue() const { return Storage.hasValue(); }
8
Calling 'OptionalStorage::hasValue'
10
Returning from 'OptionalStorage::hasValue'
11
Returning the value 1, which participates in a condition later
289 constexpr const T *operator->() const { return getPointer(); }
290 T *operator->() { return getPointer(); }
291 constexpr const T &operator*() const LLVM_LVALUE_FUNCTION& {
292 return getValue();
293 }
294 T &operator*() LLVM_LVALUE_FUNCTION& { return getValue(); }
295
296 template <typename U>
297 constexpr T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION& {
298 return hasValue() ? getValue() : std::forward<U>(value);
299 }
300
301 /// Apply a function to the value if present; otherwise return None.
302 template <class Function>
303 auto map(const Function &F) const LLVM_LVALUE_FUNCTION&
304 -> Optional<decltype(F(getValue()))> {
305 if (*this) return F(getValue());
306 return None;
307 }
308
309#if LLVM_HAS_RVALUE_REFERENCE_THIS1
310 T &&getValue() && { return std::move(Storage.getValue()); }
311 T &&operator*() && { return std::move(Storage.getValue()); }
312
313 template <typename U>
314 T getValueOr(U &&value) && {
315 return hasValue() ? std::move(getValue()) : std::forward<U>(value);
316 }
317
318 /// Apply a function to the value if present; otherwise return None.
319 template <class Function>
320 auto map(const Function &F) &&
321 -> Optional<decltype(F(std::move(*this).getValue()))> {
322 if (*this) return F(std::move(*this).getValue());
323 return None;
324 }
325#endif
326};
327
328template <class T> llvm::hash_code hash_value(const Optional<T> &O) {
329 return O ? hash_combine(true, *O) : hash_value(false);
330}
331
332template <typename T, typename U>
333constexpr bool operator==(const Optional<T> &X, const Optional<U> &Y) {
334 if (X && Y)
335 return *X == *Y;
336 return X.hasValue() == Y.hasValue();
337}
338
339template <typename T, typename U>
340constexpr bool operator!=(const Optional<T> &X, const Optional<U> &Y) {
341 return !(X == Y);
342}
343
344template <typename T, typename U>
345constexpr bool operator<(const Optional<T> &X, const Optional<U> &Y) {
346 if (X && Y)
347 return *X < *Y;
348 return X.hasValue() < Y.hasValue();
349}
350
351template <typename T, typename U>
352constexpr bool operator<=(const Optional<T> &X, const Optional<U> &Y) {
353 return !(Y < X);
354}
355
356template <typename T, typename U>
357constexpr bool operator>(const Optional<T> &X, const Optional<U> &Y) {
358 return Y < X;
359}
360
361template <typename T, typename U>
362constexpr bool operator>=(const Optional<T> &X, const Optional<U> &Y) {
363 return !(X < Y);
364}
365
366template <typename T>
367constexpr bool operator==(const Optional<T> &X, NoneType) {
368 return !X;
369}
370
371template <typename T>
372constexpr bool operator==(NoneType, const Optional<T> &X) {
373 return X == None;
374}
375
376template <typename T>
377constexpr bool operator!=(const Optional<T> &X, NoneType) {
378 return !(X == None);
379}
380
381template <typename T>
382constexpr bool operator!=(NoneType, const Optional<T> &X) {
383 return X != None;
384}
385
386template <typename T> constexpr bool operator<(const Optional<T> &, NoneType) {
387 return false;
388}
389
390template <typename T> constexpr bool operator<(NoneType, const Optional<T> &X) {
391 return X.hasValue();
392}
393
394template <typename T>
395constexpr bool operator<=(const Optional<T> &X, NoneType) {
396 return !(None < X);
397}
398
399template <typename T>
400constexpr bool operator<=(NoneType, const Optional<T> &X) {
401 return !(X < None);
402}
403
404template <typename T> constexpr bool operator>(const Optional<T> &X, NoneType) {
405 return None < X;
406}
407
408template <typename T> constexpr bool operator>(NoneType, const Optional<T> &X) {
409 return X < None;
410}
411
412template <typename T>
413constexpr bool operator>=(const Optional<T> &X, NoneType) {
414 return None <= X;
415}
416
417template <typename T>
418constexpr bool operator>=(NoneType, const Optional<T> &X) {
419 return X <= None;
420}
421
422template <typename T>
423constexpr bool operator==(const Optional<T> &X, const T &Y) {
424 return X && *X == Y;
425}
426
427template <typename T>
428constexpr bool operator==(const T &X, const Optional<T> &Y) {
429 return Y && X == *Y;
430}
431
432template <typename T>
433constexpr bool operator!=(const Optional<T> &X, const T &Y) {
434 return !(X == Y);
435}
436
437template <typename T>
438constexpr bool operator!=(const T &X, const Optional<T> &Y) {
439 return !(X == Y);
440}
441
442template <typename T>
443constexpr bool operator<(const Optional<T> &X, const T &Y) {
444 return !X || *X < Y;
445}
446
447template <typename T>
448constexpr bool operator<(const T &X, const Optional<T> &Y) {
449 return Y && X < *Y;
450}
451
452template <typename T>
453constexpr bool operator<=(const Optional<T> &X, const T &Y) {
454 return !(Y < X);
455}
456
457template <typename T>
458constexpr bool operator<=(const T &X, const Optional<T> &Y) {
459 return !(Y < X);
460}
461
462template <typename T>
463constexpr bool operator>(const Optional<T> &X, const T &Y) {
464 return Y < X;
465}
466
467template <typename T>
468constexpr bool operator>(const T &X, const Optional<T> &Y) {
469 return Y < X;
470}
471
472template <typename T>
473constexpr bool operator>=(const Optional<T> &X, const T &Y) {
474 return !(X < Y);
475}
476
477template <typename T>
478constexpr bool operator>=(const T &X, const Optional<T> &Y) {
479 return !(X < Y);
480}
481
482raw_ostream &operator<<(raw_ostream &OS, NoneType);
483
484template <typename T, typename = decltype(std::declval<raw_ostream &>()
485 << std::declval<const T &>())>
486raw_ostream &operator<<(raw_ostream &OS, const Optional<T> &O) {
487 if (O)
488 OS << *O;
489 else
490 OS << None;
491 return OS;
492}
493
494} // end namespace llvm
495
496#endif // LLVM_ADT_OPTIONAL_H

/usr/src/gnu/usr.bin/clang/liblldbPluginSymbolFile/../../../llvm/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())((void)0);
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())((void)0);
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());
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")((void)0);
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() &&((void)0)
757 "owned local decl but no local module storage")((void)0);
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&((void)0)
762 hasLocalOwningModuleStorage() &&((void)0)
763 "should not have a cached owning module")((void)0);
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 &&((void)0)
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((void)0)
809 !hasLocalOwningModuleStorage()) &&((void)0)
810 "no storage available for owning module for this declaration")((void)0);
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")((void)0);
946 // Get either previous decl or latest decl.
947 Decl *Next = Current->getNextRedeclarationImpl();
948 assert(Next && "Should return next redeclaration or itself, never null!")((void)0);
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 &&((void)0)
1082 "namespace is not ordinary")((void)0);
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 |((void)0)
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |((void)0)
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((void)0)
1108 "namespace includes neither ordinary nor tag")((void)0);
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |((void)0)
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |((void)0)
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((void)0)
1112 "namespace includes other than ordinary or tag")((void)0);
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)((void)0);
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&((void)0)
1155 "visible non-member operators should be in ordinary namespace")((void)0);
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")((void)0);
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")((void)0);
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; }
15
Assuming the condition is true
16
Returning the value 1, which participates in a condition later
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() &&((void)0)
2411 "should only be called on primary context")((void)0);
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