Bug Summary

File:lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp
Warning:line 1322, column 29
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -isystem /usr/include/libxml2 -D HAVE_ROUND -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Plugins/SymbolFile/NativePDB -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/source/Plugins/SymbolFile/NativePDB -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/include -I tools/lldb/include -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -I /usr/include/python3.9 -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/include -I tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/source -I tools/lldb/source -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-deprecated-register -Wno-vla-extension -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/source/Plugins/SymbolFile/NativePDB/PdbAstBuilder.cpp

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

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

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