Bug Summary

File:build/source/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
Warning:line 9205, column 17
Although the value stored to 'bytes_read' is used in the enclosing expression, the value is never actually read from 'bytes_read'

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 TypeSystemClang.cpp -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/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -isystem /usr/include/libxml2 -D HAVE_ROUND -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Plugins/TypeSystem/Clang -I /build/source/lldb/source/Plugins/TypeSystem/Clang -I /build/source/lldb/include -I tools/lldb/include -I include -I /build/source/llvm/include -I /usr/include/python3.9 -I /build/source/clang/include -I tools/lldb/../clang/include -I /build/source/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-17/lib/clang/17/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/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -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-misleading-indentation -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-stringop-truncation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -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-2023-05-10-133810-16478-1 -x c++ /build/source/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
1//===-- TypeSystemClang.cpp -----------------------------------------------==='//
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#include "TypeSystemClang.h"
10
11#include "clang/AST/DeclBase.h"
12#include "llvm/Support/Casting.h"
13#include "llvm/Support/FormatAdapters.h"
14#include "llvm/Support/FormatVariadic.h"
15
16#include <mutex>
17#include <memory>
18#include <string>
19#include <vector>
20
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/ASTImporter.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/CXXInheritance.h"
25#include "clang/AST/DeclObjC.h"
26#include "clang/AST/DeclTemplate.h"
27#include "clang/AST/Mangle.h"
28#include "clang/AST/RecordLayout.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/VTableBuilder.h"
31#include "clang/Basic/Builtins.h"
32#include "clang/Basic/Diagnostic.h"
33#include "clang/Basic/FileManager.h"
34#include "clang/Basic/FileSystemOptions.h"
35#include "clang/Basic/LangStandard.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/TargetOptions.h"
39#include "clang/Frontend/FrontendOptions.h"
40#include "clang/Lex/HeaderSearch.h"
41#include "clang/Lex/HeaderSearchOptions.h"
42#include "clang/Lex/ModuleMap.h"
43#include "clang/Sema/Sema.h"
44
45#include "llvm/Support/Signals.h"
46#include "llvm/Support/Threading.h"
47
48#include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
49#include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
50#include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"
51#include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
52#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
53#include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
54#include "Plugins/ExpressionParser/Clang/ClangUtil.h"
55#include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
56#include "lldb/Core/DumpDataExtractor.h"
57#include "lldb/Core/Module.h"
58#include "lldb/Core/PluginManager.h"
59#include "lldb/Core/StreamFile.h"
60#include "lldb/Core/ThreadSafeDenseMap.h"
61#include "lldb/Core/UniqueCStringMap.h"
62#include "lldb/Symbol/ObjectFile.h"
63#include "lldb/Symbol/SymbolFile.h"
64#include "lldb/Target/ExecutionContext.h"
65#include "lldb/Target/Language.h"
66#include "lldb/Target/Process.h"
67#include "lldb/Target/Target.h"
68#include "lldb/Utility/ArchSpec.h"
69#include "lldb/Utility/DataExtractor.h"
70#include "lldb/Utility/Flags.h"
71#include "lldb/Utility/LLDBAssert.h"
72#include "lldb/Utility/LLDBLog.h"
73#include "lldb/Utility/RegularExpression.h"
74#include "lldb/Utility/Scalar.h"
75
76#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
77#include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
78#include "Plugins/SymbolFile/PDB/PDBASTParser.h"
79#include "Plugins/SymbolFile/NativePDB/PdbAstBuilder.h"
80
81#include <cstdio>
82
83#include <mutex>
84#include <optional>
85
86using namespace lldb;
87using namespace lldb_private;
88using namespace lldb_private::dwarf;
89using namespace clang;
90using llvm::StringSwitch;
91
92LLDB_PLUGIN_DEFINE(TypeSystemClang)namespace lldb_private { void lldb_initialize_TypeSystemClang
() { TypeSystemClang::Initialize(); } void lldb_terminate_TypeSystemClang
() { TypeSystemClang::Terminate(); } }
93
94namespace {
95static void VerifyDecl(clang::Decl *decl) {
96 assert(decl && "VerifyDecl called with nullptr?")(static_cast <bool> (decl && "VerifyDecl called with nullptr?"
) ? void (0) : __assert_fail ("decl && \"VerifyDecl called with nullptr?\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
96, __extension__ __PRETTY_FUNCTION__))
;
97#ifndef NDEBUG
98 // We don't care about the actual access value here but only want to trigger
99 // that Clang calls its internal Decl::AccessDeclContextCheck validation.
100 decl->getAccess();
101#endif
102}
103
104static inline bool
105TypeSystemClangSupportsLanguage(lldb::LanguageType language) {
106 return language == eLanguageTypeUnknown || // Clang is the default type system
107 lldb_private::Language::LanguageIsC(language) ||
108 lldb_private::Language::LanguageIsCPlusPlus(language) ||
109 lldb_private::Language::LanguageIsObjC(language) ||
110 lldb_private::Language::LanguageIsPascal(language) ||
111 // Use Clang for Rust until there is a proper language plugin for it
112 language == eLanguageTypeRust ||
113 // Use Clang for D until there is a proper language plugin for it
114 language == eLanguageTypeD ||
115 // Open Dylan compiler debug info is designed to be Clang-compatible
116 language == eLanguageTypeDylan;
117}
118
119// Checks whether m1 is an overload of m2 (as opposed to an override). This is
120// called by addOverridesForMethod to distinguish overrides (which share a
121// vtable entry) from overloads (which require distinct entries).
122bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) {
123 // FIXME: This should detect covariant return types, but currently doesn't.
124 lldbassert(&m1->getASTContext() == &m2->getASTContext() &&lldb_private::lldb_assert(static_cast<bool>(&m1->
getASTContext() == &m2->getASTContext() && "Methods should have the same AST context"
), "&m1->getASTContext() == &m2->getASTContext() && \"Methods should have the same AST context\""
, __FUNCTION__, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 125)
125 "Methods should have the same AST context")lldb_private::lldb_assert(static_cast<bool>(&m1->
getASTContext() == &m2->getASTContext() && "Methods should have the same AST context"
), "&m1->getASTContext() == &m2->getASTContext() && \"Methods should have the same AST context\""
, __FUNCTION__, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 125)
;
126 clang::ASTContext &context = m1->getASTContext();
127
128 const auto *m1Type = llvm::cast<clang::FunctionProtoType>(
129 context.getCanonicalType(m1->getType()));
130
131 const auto *m2Type = llvm::cast<clang::FunctionProtoType>(
132 context.getCanonicalType(m2->getType()));
133
134 auto compareArgTypes = [&context](const clang::QualType &m1p,
135 const clang::QualType &m2p) {
136 return context.hasSameType(m1p.getUnqualifiedType(),
137 m2p.getUnqualifiedType());
138 };
139
140 // FIXME: In C++14 and later, we can just pass m2Type->param_type_end()
141 // as a fourth parameter to std::equal().
142 return (m1->getNumParams() != m2->getNumParams()) ||
143 !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(),
144 m2Type->param_type_begin(), compareArgTypes);
145}
146
147// If decl is a virtual method, walk the base classes looking for methods that
148// decl overrides. This table of overridden methods is used by IRGen to
149// determine the vtable layout for decl's parent class.
150void addOverridesForMethod(clang::CXXMethodDecl *decl) {
151 if (!decl->isVirtual())
152 return;
153
154 clang::CXXBasePaths paths;
155 llvm::SmallVector<clang::NamedDecl *, 4> decls;
156
157 auto find_overridden_methods =
158 [&decls, decl](const clang::CXXBaseSpecifier *specifier,
159 clang::CXXBasePath &path) {
160 if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>(
161 specifier->getType()->castAs<clang::RecordType>()->getDecl())) {
162
163 clang::DeclarationName name = decl->getDeclName();
164
165 // If this is a destructor, check whether the base class destructor is
166 // virtual.
167 if (name.getNameKind() == clang::DeclarationName::CXXDestructorName)
168 if (auto *baseDtorDecl = base_record->getDestructor()) {
169 if (baseDtorDecl->isVirtual()) {
170 decls.push_back(baseDtorDecl);
171 return true;
172 } else
173 return false;
174 }
175
176 // Otherwise, search for name in the base class.
177 for (path.Decls = base_record->lookup(name).begin();
178 path.Decls != path.Decls.end(); ++path.Decls) {
179 if (auto *method_decl =
180 llvm::dyn_cast<clang::CXXMethodDecl>(*path.Decls))
181 if (method_decl->isVirtual() && !isOverload(decl, method_decl)) {
182 decls.push_back(method_decl);
183 return true;
184 }
185 }
186 }
187
188 return false;
189 };
190
191 if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) {
192 for (auto *overridden_decl : decls)
193 decl->addOverriddenMethod(
194 llvm::cast<clang::CXXMethodDecl>(overridden_decl));
195 }
196}
197}
198
199static lldb::addr_t GetVTableAddress(Process &process,
200 VTableContextBase &vtable_ctx,
201 ValueObject &valobj,
202 const ASTRecordLayout &record_layout) {
203 // Retrieve type info
204 CompilerType pointee_type;
205 CompilerType this_type(valobj.GetCompilerType());
206 uint32_t type_info = this_type.GetTypeInfo(&pointee_type);
207 if (!type_info)
208 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
209
210 // Check if it's a pointer or reference
211 bool ptr_or_ref = false;
212 if (type_info & (eTypeIsPointer | eTypeIsReference)) {
213 ptr_or_ref = true;
214 type_info = pointee_type.GetTypeInfo();
215 }
216
217 // We process only C++ classes
218 const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus;
219 if ((type_info & cpp_class) != cpp_class)
220 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
221
222 // Calculate offset to VTable pointer
223 lldb::offset_t vbtable_ptr_offset =
224 vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity()
225 : 0;
226
227 if (ptr_or_ref) {
228 // We have a pointer / ref to object, so read
229 // VTable pointer from process memory
230
231 if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad)
232 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
233
234 auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS(18446744073709551615UL));
235 if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS(18446744073709551615UL))
236 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
237
238 vbtable_ptr_addr += vbtable_ptr_offset;
239
240 Status err;
241 return process.ReadPointerFromMemory(vbtable_ptr_addr, err);
242 }
243
244 // We have an object already read from process memory,
245 // so just extract VTable pointer from it
246
247 DataExtractor data;
248 Status err;
249 auto size = valobj.GetData(data, err);
250 if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size)
251 return LLDB_INVALID_ADDRESS(18446744073709551615UL);
252
253 return data.GetAddress(&vbtable_ptr_offset);
254}
255
256static int64_t ReadVBaseOffsetFromVTable(Process &process,
257 VTableContextBase &vtable_ctx,
258 lldb::addr_t vtable_ptr,
259 const CXXRecordDecl *cxx_record_decl,
260 const CXXRecordDecl *base_class_decl) {
261 if (vtable_ctx.isMicrosoft()) {
262 clang::MicrosoftVTableContext &msoft_vtable_ctx =
263 static_cast<clang::MicrosoftVTableContext &>(vtable_ctx);
264
265 // Get the index into the virtual base table. The
266 // index is the index in uint32_t from vbtable_ptr
267 const unsigned vbtable_index =
268 msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl);
269 const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4;
270 Status err;
271 return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX(9223372036854775807L),
272 err);
273 }
274
275 clang::ItaniumVTableContext &itanium_vtable_ctx =
276 static_cast<clang::ItaniumVTableContext &>(vtable_ctx);
277
278 clang::CharUnits base_offset_offset =
279 itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl,
280 base_class_decl);
281 const lldb::addr_t base_offset_addr =
282 vtable_ptr + base_offset_offset.getQuantity();
283 const uint32_t base_offset_size = process.GetAddressByteSize();
284 Status err;
285 return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size,
286 INT64_MAX(9223372036854775807L), err);
287}
288
289static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx,
290 ValueObject &valobj,
291 const ASTRecordLayout &record_layout,
292 const CXXRecordDecl *cxx_record_decl,
293 const CXXRecordDecl *base_class_decl,
294 int32_t &bit_offset) {
295 ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
296 Process *process = exe_ctx.GetProcessPtr();
297 if (!process)
298 return false;
299
300 lldb::addr_t vtable_ptr =
301 GetVTableAddress(*process, vtable_ctx, valobj, record_layout);
302 if (vtable_ptr == LLDB_INVALID_ADDRESS(18446744073709551615UL))
303 return false;
304
305 auto base_offset = ReadVBaseOffsetFromVTable(
306 *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl);
307 if (base_offset == INT64_MAX(9223372036854775807L))
308 return false;
309
310 bit_offset = base_offset * 8;
311
312 return true;
313}
314
315typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, TypeSystemClang *>
316 ClangASTMap;
317
318static ClangASTMap &GetASTMap() {
319 static ClangASTMap *g_map_ptr = nullptr;
320 static llvm::once_flag g_once_flag;
321 llvm::call_once(g_once_flag, []() {
322 g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
323 });
324 return *g_map_ptr;
325}
326
327TypePayloadClang::TypePayloadClang(OptionalClangModuleID owning_module,
328 bool is_complete_objc_class)
329 : m_payload(owning_module.GetValue()) {
330 SetIsCompleteObjCClass(is_complete_objc_class);
331}
332
333void TypePayloadClang::SetOwningModule(OptionalClangModuleID id) {
334 assert(id.GetValue() < ObjCClassBit)(static_cast <bool> (id.GetValue() < ObjCClassBit) ?
void (0) : __assert_fail ("id.GetValue() < ObjCClassBit",
"lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp", 334
, __extension__ __PRETTY_FUNCTION__))
;
335 bool is_complete = IsCompleteObjCClass();
336 m_payload = id.GetValue();
337 SetIsCompleteObjCClass(is_complete);
338}
339
340static void SetMemberOwningModule(clang::Decl *member,
341 const clang::Decl *parent) {
342 if (!member || !parent)
343 return;
344
345 OptionalClangModuleID id(parent->getOwningModuleID());
346 if (!id.HasValue())
347 return;
348
349 member->setFromASTFile();
350 member->setOwningModuleID(id.GetValue());
351 member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
352 if (llvm::isa<clang::NamedDecl>(member))
353 if (auto *dc = llvm::dyn_cast<clang::DeclContext>(parent)) {
354 dc->setHasExternalVisibleStorage(true);
355 // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be
356 // called when searching for members.
357 dc->setHasExternalLexicalStorage(true);
358 }
359}
360
361char TypeSystemClang::ID;
362
363bool TypeSystemClang::IsOperator(llvm::StringRef name,
364 clang::OverloadedOperatorKind &op_kind) {
365 // All operators have to start with "operator".
366 if (!name.consume_front("operator"))
367 return false;
368
369 // Remember if there was a space after "operator". This is necessary to
370 // check for collisions with strangely named functions like "operatorint()".
371 bool space_after_operator = name.consume_front(" ");
372
373 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
374 .Case("+", clang::OO_Plus)
375 .Case("+=", clang::OO_PlusEqual)
376 .Case("++", clang::OO_PlusPlus)
377 .Case("-", clang::OO_Minus)
378 .Case("-=", clang::OO_MinusEqual)
379 .Case("--", clang::OO_MinusMinus)
380 .Case("->", clang::OO_Arrow)
381 .Case("->*", clang::OO_ArrowStar)
382 .Case("*", clang::OO_Star)
383 .Case("*=", clang::OO_StarEqual)
384 .Case("/", clang::OO_Slash)
385 .Case("/=", clang::OO_SlashEqual)
386 .Case("%", clang::OO_Percent)
387 .Case("%=", clang::OO_PercentEqual)
388 .Case("^", clang::OO_Caret)
389 .Case("^=", clang::OO_CaretEqual)
390 .Case("&", clang::OO_Amp)
391 .Case("&=", clang::OO_AmpEqual)
392 .Case("&&", clang::OO_AmpAmp)
393 .Case("|", clang::OO_Pipe)
394 .Case("|=", clang::OO_PipeEqual)
395 .Case("||", clang::OO_PipePipe)
396 .Case("~", clang::OO_Tilde)
397 .Case("!", clang::OO_Exclaim)
398 .Case("!=", clang::OO_ExclaimEqual)
399 .Case("=", clang::OO_Equal)
400 .Case("==", clang::OO_EqualEqual)
401 .Case("<", clang::OO_Less)
402 .Case("<=>", clang::OO_Spaceship)
403 .Case("<<", clang::OO_LessLess)
404 .Case("<<=", clang::OO_LessLessEqual)
405 .Case("<=", clang::OO_LessEqual)
406 .Case(">", clang::OO_Greater)
407 .Case(">>", clang::OO_GreaterGreater)
408 .Case(">>=", clang::OO_GreaterGreaterEqual)
409 .Case(">=", clang::OO_GreaterEqual)
410 .Case("()", clang::OO_Call)
411 .Case("[]", clang::OO_Subscript)
412 .Case(",", clang::OO_Comma)
413 .Default(clang::NUM_OVERLOADED_OPERATORS);
414
415 // We found a fitting operator, so we can exit now.
416 if (op_kind != clang::NUM_OVERLOADED_OPERATORS)
417 return true;
418
419 // After the "operator " or "operator" part is something unknown. This means
420 // it's either one of the named operators (new/delete), a conversion operator
421 // (e.g. operator bool) or a function which name starts with "operator"
422 // (e.g. void operatorbool).
423
424 // If it's a function that starts with operator it can't have a space after
425 // "operator" because identifiers can't contain spaces.
426 // E.g. "operator int" (conversion operator)
427 // vs. "operatorint" (function with colliding name).
428 if (!space_after_operator)
429 return false; // not an operator.
430
431 // Now the operator is either one of the named operators or a conversion
432 // operator.
433 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
434 .Case("new", clang::OO_New)
435 .Case("new[]", clang::OO_Array_New)
436 .Case("delete", clang::OO_Delete)
437 .Case("delete[]", clang::OO_Array_Delete)
438 // conversion operators hit this case.
439 .Default(clang::NUM_OVERLOADED_OPERATORS);
440
441 return true;
442}
443
444clang::AccessSpecifier
445TypeSystemClang::ConvertAccessTypeToAccessSpecifier(AccessType access) {
446 switch (access) {
447 default:
448 break;
449 case eAccessNone:
450 return AS_none;
451 case eAccessPublic:
452 return AS_public;
453 case eAccessPrivate:
454 return AS_private;
455 case eAccessProtected:
456 return AS_protected;
457 }
458 return AS_none;
459}
460
461static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) {
462 // FIXME: Cleanup per-file based stuff.
463
464 // Set some properties which depend solely on the input kind; it would be
465 // nice to move these to the language standard, and have the driver resolve
466 // the input kind + language standard.
467 if (IK.getLanguage() == clang::Language::Asm) {
468 Opts.AsmPreprocessor = 1;
469 } else if (IK.isObjectiveC()) {
470 Opts.ObjC = 1;
471 }
472
473 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
474
475 if (LangStd == LangStandard::lang_unspecified) {
476 // Based on the base language, pick one.
477 switch (IK.getLanguage()) {
478 case clang::Language::Unknown:
479 case clang::Language::LLVM_IR:
480 case clang::Language::RenderScript:
481 llvm_unreachable("Invalid input kind!")::llvm::llvm_unreachable_internal("Invalid input kind!", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 481)
;
482 case clang::Language::OpenCL:
483 LangStd = LangStandard::lang_opencl10;
484 break;
485 case clang::Language::OpenCLCXX:
486 LangStd = LangStandard::lang_openclcpp10;
487 break;
488 case clang::Language::CUDA:
489 LangStd = LangStandard::lang_cuda;
490 break;
491 case clang::Language::Asm:
492 case clang::Language::C:
493 case clang::Language::ObjC:
494 LangStd = LangStandard::lang_gnu99;
495 break;
496 case clang::Language::CXX:
497 case clang::Language::ObjCXX:
498 LangStd = LangStandard::lang_gnucxx98;
499 break;
500 case clang::Language::HIP:
501 LangStd = LangStandard::lang_hip;
502 break;
503 case clang::Language::HLSL:
504 LangStd = LangStandard::lang_hlsl;
505 break;
506 }
507 }
508
509 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
510 Opts.LineComment = Std.hasLineComments();
511 Opts.C99 = Std.isC99();
512 Opts.CPlusPlus = Std.isCPlusPlus();
513 Opts.CPlusPlus11 = Std.isCPlusPlus11();
514 Opts.CPlusPlus14 = Std.isCPlusPlus14();
515 Opts.CPlusPlus17 = Std.isCPlusPlus17();
516 Opts.CPlusPlus20 = Std.isCPlusPlus20();
517 Opts.Digraphs = Std.hasDigraphs();
518 Opts.GNUMode = Std.isGNUMode();
519 Opts.GNUInline = !Std.isC99();
520 Opts.HexFloats = Std.hasHexFloats();
521
522 Opts.WChar = true;
523
524 // OpenCL has some additional defaults.
525 if (LangStd == LangStandard::lang_opencl10) {
526 Opts.OpenCL = 1;
527 Opts.AltiVec = 1;
528 Opts.CXXOperatorNames = 1;
529 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::All);
530 }
531
532 // OpenCL and C++ both have bool, true, false keywords.
533 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
534
535 Opts.setValueVisibilityMode(DefaultVisibility);
536
537 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
538 // specified, or -std is set to a conforming mode.
539 Opts.Trigraphs = !Opts.GNUMode;
540 Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
541 Opts.OptimizeSize = 0;
542
543 // FIXME: Eliminate this dependency.
544 // unsigned Opt =
545 // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
546 // Opts.Optimize = Opt != 0;
547 unsigned Opt = 0;
548
549 // This is the __NO_INLINE__ define, which just depends on things like the
550 // optimization level and -fno-inline, not actually whether the backend has
551 // inlining enabled.
552 //
553 // FIXME: This is affected by other options (-fno-inline).
554 Opts.NoInlineDefine = !Opt;
555
556 // This is needed to allocate the extra space for the owning module
557 // on each decl.
558 Opts.ModulesLocalVisibility = 1;
559}
560
561TypeSystemClang::TypeSystemClang(llvm::StringRef name,
562 llvm::Triple target_triple) {
563 m_display_name = name.str();
564 if (!target_triple.str().empty())
565 SetTargetTriple(target_triple.str());
566 // The caller didn't pass an ASTContext so create a new one for this
567 // TypeSystemClang.
568 CreateASTContext();
569}
570
571TypeSystemClang::TypeSystemClang(llvm::StringRef name,
572 ASTContext &existing_ctxt) {
573 m_display_name = name.str();
574 SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str());
575
576 m_ast_up.reset(&existing_ctxt);
577 GetASTMap().Insert(&existing_ctxt, this);
578}
579
580// Destructor
581TypeSystemClang::~TypeSystemClang() { Finalize(); }
582
583lldb::TypeSystemSP TypeSystemClang::CreateInstance(lldb::LanguageType language,
584 lldb_private::Module *module,
585 Target *target) {
586 if (!TypeSystemClangSupportsLanguage(language))
587 return lldb::TypeSystemSP();
588 ArchSpec arch;
589 if (module)
590 arch = module->GetArchitecture();
591 else if (target)
592 arch = target->GetArchitecture();
593
594 if (!arch.IsValid())
595 return lldb::TypeSystemSP();
596
597 llvm::Triple triple = arch.GetTriple();
598 // LLVM wants this to be set to iOS or MacOSX; if we're working on
599 // a bare-boards type image, change the triple for llvm's benefit.
600 if (triple.getVendor() == llvm::Triple::Apple &&
601 triple.getOS() == llvm::Triple::UnknownOS) {
602 if (triple.getArch() == llvm::Triple::arm ||
603 triple.getArch() == llvm::Triple::aarch64 ||
604 triple.getArch() == llvm::Triple::aarch64_32 ||
605 triple.getArch() == llvm::Triple::thumb) {
606 triple.setOS(llvm::Triple::IOS);
607 } else {
608 triple.setOS(llvm::Triple::MacOSX);
609 }
610 }
611
612 if (module) {
613 std::string ast_name =
614 "ASTContext for '" + module->GetFileSpec().GetPath() + "'";
615 return std::make_shared<TypeSystemClang>(ast_name, triple);
616 } else if (target && target->IsValid())
617 return std::make_shared<ScratchTypeSystemClang>(*target, triple);
618 return lldb::TypeSystemSP();
619}
620
621LanguageSet TypeSystemClang::GetSupportedLanguagesForTypes() {
622 LanguageSet languages;
623 languages.Insert(lldb::eLanguageTypeC89);
624 languages.Insert(lldb::eLanguageTypeC);
625 languages.Insert(lldb::eLanguageTypeC11);
626 languages.Insert(lldb::eLanguageTypeC_plus_plus);
627 languages.Insert(lldb::eLanguageTypeC99);
628 languages.Insert(lldb::eLanguageTypeObjC);
629 languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
630 languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
631 languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
632 languages.Insert(lldb::eLanguageTypeC11);
633 languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
634 languages.Insert(lldb::eLanguageTypeC_plus_plus_17);
635 languages.Insert(lldb::eLanguageTypeC_plus_plus_20);
636 return languages;
637}
638
639LanguageSet TypeSystemClang::GetSupportedLanguagesForExpressions() {
640 LanguageSet languages;
641 languages.Insert(lldb::eLanguageTypeC_plus_plus);
642 languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
643 languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
644 languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
645 languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
646 languages.Insert(lldb::eLanguageTypeC_plus_plus_17);
647 languages.Insert(lldb::eLanguageTypeC_plus_plus_20);
648 return languages;
649}
650
651void TypeSystemClang::Initialize() {
652 PluginManager::RegisterPlugin(
653 GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance,
654 GetSupportedLanguagesForTypes(), GetSupportedLanguagesForExpressions());
655}
656
657void TypeSystemClang::Terminate() {
658 PluginManager::UnregisterPlugin(CreateInstance);
659}
660
661void TypeSystemClang::Finalize() {
662 assert(m_ast_up)(static_cast <bool> (m_ast_up) ? void (0) : __assert_fail
("m_ast_up", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 662, __extension__ __PRETTY_FUNCTION__))
;
663 GetASTMap().Erase(m_ast_up.get());
664 if (!m_ast_owned)
665 m_ast_up.release();
666
667 m_builtins_up.reset();
668 m_selector_table_up.reset();
669 m_identifier_table_up.reset();
670 m_target_info_up.reset();
671 m_target_options_rp.reset();
672 m_diagnostics_engine_up.reset();
673 m_source_manager_up.reset();
674 m_language_options_up.reset();
675}
676
677void TypeSystemClang::setSema(Sema *s) {
678 // Ensure that the new sema actually belongs to our ASTContext.
679 assert(s == nullptr || &s->getASTContext() == m_ast_up.get())(static_cast <bool> (s == nullptr || &s->getASTContext
() == m_ast_up.get()) ? void (0) : __assert_fail ("s == nullptr || &s->getASTContext() == m_ast_up.get()"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
679, __extension__ __PRETTY_FUNCTION__))
;
680 m_sema = s;
681}
682
683const char *TypeSystemClang::GetTargetTriple() {
684 return m_target_triple.c_str();
685}
686
687void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) {
688 m_target_triple = target_triple.str();
689}
690
691void TypeSystemClang::SetExternalSource(
692 llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
693 ASTContext &ast = getASTContext();
694 ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
695 ast.setExternalSource(ast_source_up);
696}
697
698ASTContext &TypeSystemClang::getASTContext() {
699 assert(m_ast_up)(static_cast <bool> (m_ast_up) ? void (0) : __assert_fail
("m_ast_up", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 699, __extension__ __PRETTY_FUNCTION__))
;
700 return *m_ast_up;
701}
702
703class NullDiagnosticConsumer : public DiagnosticConsumer {
704public:
705 NullDiagnosticConsumer() { m_log = GetLog(LLDBLog::Expressions); }
706
707 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
708 const clang::Diagnostic &info) override {
709 if (m_log) {
710 llvm::SmallVector<char, 32> diag_str(10);
711 info.FormatDiagnostic(diag_str);
712 diag_str.push_back('\0');
713 LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data())do { ::lldb_private::Log *log_private = (m_log); if (log_private
) log_private->Printf("Compiler diagnostic: %s\n", diag_str
.data()); } while (0)
;
714 }
715 }
716
717 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
718 return new NullDiagnosticConsumer();
719 }
720
721private:
722 Log *m_log;
723};
724
725void TypeSystemClang::CreateASTContext() {
726 assert(!m_ast_up)(static_cast <bool> (!m_ast_up) ? void (0) : __assert_fail
("!m_ast_up", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 726, __extension__ __PRETTY_FUNCTION__))
;
727 m_ast_owned = true;
728
729 m_language_options_up = std::make_unique<LangOptions>();
730 ParseLangArgs(*m_language_options_up, clang::Language::ObjCXX,
731 GetTargetTriple());
732
733 m_identifier_table_up =
734 std::make_unique<IdentifierTable>(*m_language_options_up, nullptr);
735 m_builtins_up = std::make_unique<Builtin::Context>();
736
737 m_selector_table_up = std::make_unique<SelectorTable>();
738
739 clang::FileSystemOptions file_system_options;
740 m_file_manager_up = std::make_unique<clang::FileManager>(
741 file_system_options, FileSystem::Instance().GetVirtualFileSystem());
742
743 llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
744 m_diagnostics_engine_up =
745 std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions());
746
747 m_source_manager_up = std::make_unique<clang::SourceManager>(
748 *m_diagnostics_engine_up, *m_file_manager_up);
749 m_ast_up = std::make_unique<ASTContext>(
750 *m_language_options_up, *m_source_manager_up, *m_identifier_table_up,
751 *m_selector_table_up, *m_builtins_up, TU_Complete);
752
753 m_diagnostic_consumer_up = std::make_unique<NullDiagnosticConsumer>();
754 m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), false);
755
756 // This can be NULL if we don't know anything about the architecture or if
757 // the target for an architecture isn't enabled in the llvm/clang that we
758 // built
759 TargetInfo *target_info = getTargetInfo();
760 if (target_info)
761 m_ast_up->InitBuiltinTypes(*target_info);
762
763 GetASTMap().Insert(m_ast_up.get(), this);
764
765 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
766 new ClangExternalASTSourceCallbacks(*this));
767 SetExternalSource(ast_source_up);
768}
769
770TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) {
771 TypeSystemClang *clang_ast = GetASTMap().Lookup(ast);
772 return clang_ast;
773}
774
775clang::MangleContext *TypeSystemClang::getMangleContext() {
776 if (m_mangle_ctx_up == nullptr)
777 m_mangle_ctx_up.reset(getASTContext().createMangleContext());
778 return m_mangle_ctx_up.get();
779}
780
781std::shared_ptr<clang::TargetOptions> &TypeSystemClang::getTargetOptions() {
782 if (m_target_options_rp == nullptr && !m_target_triple.empty()) {
783 m_target_options_rp = std::make_shared<clang::TargetOptions>();
784 if (m_target_options_rp != nullptr)
785 m_target_options_rp->Triple = m_target_triple;
786 }
787 return m_target_options_rp;
788}
789
790TargetInfo *TypeSystemClang::getTargetInfo() {
791 // target_triple should be something like "x86_64-apple-macosx"
792 if (m_target_info_up == nullptr && !m_target_triple.empty())
793 m_target_info_up.reset(TargetInfo::CreateTargetInfo(
794 getASTContext().getDiagnostics(), getTargetOptions()));
795 return m_target_info_up.get();
796}
797
798#pragma mark Basic Types
799
800static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
801 ASTContext &ast, QualType qual_type) {
802 uint64_t qual_type_bit_size = ast.getTypeSize(qual_type);
803 return qual_type_bit_size == bit_size;
804}
805
806CompilerType
807TypeSystemClang::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
808 size_t bit_size) {
809 ASTContext &ast = getASTContext();
810 switch (encoding) {
811 case eEncodingInvalid:
812 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
813 return GetType(ast.VoidPtrTy);
814 break;
815
816 case eEncodingUint:
817 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
818 return GetType(ast.UnsignedCharTy);
819 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
820 return GetType(ast.UnsignedShortTy);
821 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
822 return GetType(ast.UnsignedIntTy);
823 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
824 return GetType(ast.UnsignedLongTy);
825 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
826 return GetType(ast.UnsignedLongLongTy);
827 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
828 return GetType(ast.UnsignedInt128Ty);
829 break;
830
831 case eEncodingSint:
832 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
833 return GetType(ast.SignedCharTy);
834 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
835 return GetType(ast.ShortTy);
836 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
837 return GetType(ast.IntTy);
838 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
839 return GetType(ast.LongTy);
840 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
841 return GetType(ast.LongLongTy);
842 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
843 return GetType(ast.Int128Ty);
844 break;
845
846 case eEncodingIEEE754:
847 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
848 return GetType(ast.FloatTy);
849 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
850 return GetType(ast.DoubleTy);
851 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
852 return GetType(ast.LongDoubleTy);
853 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
854 return GetType(ast.HalfTy);
855 break;
856
857 case eEncodingVector:
858 // Sanity check that bit_size is a multiple of 8's.
859 if (bit_size && !(bit_size & 0x7u))
860 return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8));
861 break;
862 }
863
864 return CompilerType();
865}
866
867lldb::BasicType
868TypeSystemClang::GetBasicTypeEnumeration(ConstString name) {
869 if (name) {
870 typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
871 static TypeNameToBasicTypeMap g_type_map;
872 static llvm::once_flag g_once_flag;
873 llvm::call_once(g_once_flag, []() {
874 // "void"
875 g_type_map.Append(ConstString("void"), eBasicTypeVoid);
876
877 // "char"
878 g_type_map.Append(ConstString("char"), eBasicTypeChar);
879 g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar);
880 g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar);
881 g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar);
882 g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar);
883 g_type_map.Append(ConstString("unsigned wchar_t"),
884 eBasicTypeUnsignedWChar);
885 // "short"
886 g_type_map.Append(ConstString("short"), eBasicTypeShort);
887 g_type_map.Append(ConstString("short int"), eBasicTypeShort);
888 g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort);
889 g_type_map.Append(ConstString("unsigned short int"),
890 eBasicTypeUnsignedShort);
891
892 // "int"
893 g_type_map.Append(ConstString("int"), eBasicTypeInt);
894 g_type_map.Append(ConstString("signed int"), eBasicTypeInt);
895 g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt);
896 g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt);
897
898 // "long"
899 g_type_map.Append(ConstString("long"), eBasicTypeLong);
900 g_type_map.Append(ConstString("long int"), eBasicTypeLong);
901 g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong);
902 g_type_map.Append(ConstString("unsigned long int"),
903 eBasicTypeUnsignedLong);
904
905 // "long long"
906 g_type_map.Append(ConstString("long long"), eBasicTypeLongLong);
907 g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong);
908 g_type_map.Append(ConstString("unsigned long long"),
909 eBasicTypeUnsignedLongLong);
910 g_type_map.Append(ConstString("unsigned long long int"),
911 eBasicTypeUnsignedLongLong);
912
913 // "int128"
914 g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128);
915 g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128);
916
917 // Miscellaneous
918 g_type_map.Append(ConstString("bool"), eBasicTypeBool);
919 g_type_map.Append(ConstString("float"), eBasicTypeFloat);
920 g_type_map.Append(ConstString("double"), eBasicTypeDouble);
921 g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble);
922 g_type_map.Append(ConstString("id"), eBasicTypeObjCID);
923 g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel);
924 g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr);
925 g_type_map.Sort();
926 });
927
928 return g_type_map.Find(name, eBasicTypeInvalid);
929 }
930 return eBasicTypeInvalid;
931}
932
933uint32_t TypeSystemClang::GetPointerByteSize() {
934 if (m_pointer_byte_size == 0)
935 if (auto size = GetBasicType(lldb::eBasicTypeVoid)
936 .GetPointerType()
937 .GetByteSize(nullptr))
938 m_pointer_byte_size = *size;
939 return m_pointer_byte_size;
940}
941
942CompilerType TypeSystemClang::GetBasicType(lldb::BasicType basic_type) {
943 clang::ASTContext &ast = getASTContext();
944
945 lldb::opaque_compiler_type_t clang_type =
946 GetOpaqueCompilerType(&ast, basic_type);
947
948 if (clang_type)
949 return CompilerType(weak_from_this(), clang_type);
950 return CompilerType();
951}
952
953CompilerType TypeSystemClang::GetBuiltinTypeForDWARFEncodingAndBitSize(
954 llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) {
955 ASTContext &ast = getASTContext();
956
957 switch (dw_ate) {
958 default:
959 break;
960
961 case DW_ATE_address:
962 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
963 return GetType(ast.VoidPtrTy);
964 break;
965
966 case DW_ATE_boolean:
967 if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy))
968 return GetType(ast.BoolTy);
969 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
970 return GetType(ast.UnsignedCharTy);
971 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
972 return GetType(ast.UnsignedShortTy);
973 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
974 return GetType(ast.UnsignedIntTy);
975 break;
976
977 case DW_ATE_lo_user:
978 // This has been seen to mean DW_AT_complex_integer
979 if (type_name.contains("complex")) {
980 CompilerType complex_int_clang_type =
981 GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
982 bit_size / 2);
983 return GetType(
984 ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type)));
985 }
986 break;
987
988 case DW_ATE_complex_float: {
989 CanQualType FloatComplexTy = ast.getComplexType(ast.FloatTy);
990 if (QualTypeMatchesBitSize(bit_size, ast, FloatComplexTy))
991 return GetType(FloatComplexTy);
992
993 CanQualType DoubleComplexTy = ast.getComplexType(ast.DoubleTy);
994 if (QualTypeMatchesBitSize(bit_size, ast, DoubleComplexTy))
995 return GetType(DoubleComplexTy);
996
997 CanQualType LongDoubleComplexTy = ast.getComplexType(ast.LongDoubleTy);
998 if (QualTypeMatchesBitSize(bit_size, ast, LongDoubleComplexTy))
999 return GetType(LongDoubleComplexTy);
1000
1001 CompilerType complex_float_clang_type =
1002 GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
1003 bit_size / 2);
1004 return GetType(
1005 ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type)));
1006 }
1007
1008 case DW_ATE_float:
1009 if (type_name == "float" &&
1010 QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
1011 return GetType(ast.FloatTy);
1012 if (type_name == "double" &&
1013 QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
1014 return GetType(ast.DoubleTy);
1015 if (type_name == "long double" &&
1016 QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
1017 return GetType(ast.LongDoubleTy);
1018 // Fall back to not requiring a name match
1019 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
1020 return GetType(ast.FloatTy);
1021 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
1022 return GetType(ast.DoubleTy);
1023 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
1024 return GetType(ast.LongDoubleTy);
1025 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
1026 return GetType(ast.HalfTy);
1027 break;
1028
1029 case DW_ATE_signed:
1030 if (!type_name.empty()) {
1031 if (type_name == "wchar_t" &&
1032 QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) &&
1033 (getTargetInfo() &&
1034 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1035 return GetType(ast.WCharTy);
1036 if (type_name == "void" &&
1037 QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy))
1038 return GetType(ast.VoidTy);
1039 if (type_name.contains("long long") &&
1040 QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1041 return GetType(ast.LongLongTy);
1042 if (type_name.contains("long") &&
1043 QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1044 return GetType(ast.LongTy);
1045 if (type_name.contains("short") &&
1046 QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1047 return GetType(ast.ShortTy);
1048 if (type_name.contains("char")) {
1049 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1050 return GetType(ast.CharTy);
1051 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1052 return GetType(ast.SignedCharTy);
1053 }
1054 if (type_name.contains("int")) {
1055 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1056 return GetType(ast.IntTy);
1057 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1058 return GetType(ast.Int128Ty);
1059 }
1060 }
1061 // We weren't able to match up a type name, just search by size
1062 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1063 return GetType(ast.CharTy);
1064 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1065 return GetType(ast.ShortTy);
1066 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1067 return GetType(ast.IntTy);
1068 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1069 return GetType(ast.LongTy);
1070 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1071 return GetType(ast.LongLongTy);
1072 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1073 return GetType(ast.Int128Ty);
1074 break;
1075
1076 case DW_ATE_signed_char:
1077 if (type_name == "char") {
1078 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1079 return GetType(ast.CharTy);
1080 }
1081 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1082 return GetType(ast.SignedCharTy);
1083 break;
1084
1085 case DW_ATE_unsigned:
1086 if (!type_name.empty()) {
1087 if (type_name == "wchar_t") {
1088 if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) {
1089 if (!(getTargetInfo() &&
1090 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1091 return GetType(ast.WCharTy);
1092 }
1093 }
1094 if (type_name.contains("long long")) {
1095 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1096 return GetType(ast.UnsignedLongLongTy);
1097 } else if (type_name.contains("long")) {
1098 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1099 return GetType(ast.UnsignedLongTy);
1100 } else if (type_name.contains("short")) {
1101 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1102 return GetType(ast.UnsignedShortTy);
1103 } else if (type_name.contains("char")) {
1104 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1105 return GetType(ast.UnsignedCharTy);
1106 } else if (type_name.contains("int")) {
1107 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1108 return GetType(ast.UnsignedIntTy);
1109 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1110 return GetType(ast.UnsignedInt128Ty);
1111 }
1112 }
1113 // We weren't able to match up a type name, just search by size
1114 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1115 return GetType(ast.UnsignedCharTy);
1116 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1117 return GetType(ast.UnsignedShortTy);
1118 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1119 return GetType(ast.UnsignedIntTy);
1120 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1121 return GetType(ast.UnsignedLongTy);
1122 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1123 return GetType(ast.UnsignedLongLongTy);
1124 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1125 return GetType(ast.UnsignedInt128Ty);
1126 break;
1127
1128 case DW_ATE_unsigned_char:
1129 if (type_name == "char") {
1130 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1131 return GetType(ast.CharTy);
1132 }
1133 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1134 return GetType(ast.UnsignedCharTy);
1135 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1136 return GetType(ast.UnsignedShortTy);
1137 break;
1138
1139 case DW_ATE_imaginary_float:
1140 break;
1141
1142 case DW_ATE_UTF:
1143 switch (bit_size) {
1144 case 8:
1145 return GetType(ast.Char8Ty);
1146 case 16:
1147 return GetType(ast.Char16Ty);
1148 case 32:
1149 return GetType(ast.Char32Ty);
1150 default:
1151 if (!type_name.empty()) {
1152 if (type_name == "char16_t")
1153 return GetType(ast.Char16Ty);
1154 if (type_name == "char32_t")
1155 return GetType(ast.Char32Ty);
1156 if (type_name == "char8_t")
1157 return GetType(ast.Char8Ty);
1158 }
1159 }
1160 break;
1161 }
1162
1163 Log *log = GetLog(LLDBLog::Types);
1164 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "error: need to add support for DW_TAG_base_type '{0}' "
"encoded with DW_ATE = {1:x}, bit_size = {2}", type_name, dw_ate
, bit_size); } while (0)
1165 "error: need to add support for DW_TAG_base_type '{0}' "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "error: need to add support for DW_TAG_base_type '{0}' "
"encoded with DW_ATE = {1:x}, bit_size = {2}", type_name, dw_ate
, bit_size); } while (0)
1166 "encoded with DW_ATE = {1:x}, bit_size = {2}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "error: need to add support for DW_TAG_base_type '{0}' "
"encoded with DW_ATE = {1:x}, bit_size = {2}", type_name, dw_ate
, bit_size); } while (0)
1167 type_name, dw_ate, bit_size)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "error: need to add support for DW_TAG_base_type '{0}' "
"encoded with DW_ATE = {1:x}, bit_size = {2}", type_name, dw_ate
, bit_size); } while (0)
;
1168 return CompilerType();
1169}
1170
1171CompilerType TypeSystemClang::GetCStringType(bool is_const) {
1172 ASTContext &ast = getASTContext();
1173 QualType char_type(ast.CharTy);
1174
1175 if (is_const)
1176 char_type.addConst();
1177
1178 return GetType(ast.getPointerType(char_type));
1179}
1180
1181bool TypeSystemClang::AreTypesSame(CompilerType type1, CompilerType type2,
1182 bool ignore_qualifiers) {
1183 auto ast = type1.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
1184 if (!ast || type1.GetTypeSystem() != type2.GetTypeSystem())
1185 return false;
1186
1187 if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1188 return true;
1189
1190 QualType type1_qual = ClangUtil::GetQualType(type1);
1191 QualType type2_qual = ClangUtil::GetQualType(type2);
1192
1193 if (ignore_qualifiers) {
1194 type1_qual = type1_qual.getUnqualifiedType();
1195 type2_qual = type2_qual.getUnqualifiedType();
1196 }
1197
1198 return ast->getASTContext().hasSameType(type1_qual, type2_qual);
1199}
1200
1201CompilerType TypeSystemClang::GetTypeForDecl(void *opaque_decl) {
1202 if (!opaque_decl)
1203 return CompilerType();
1204
1205 clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl);
1206 if (auto *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl))
1207 return GetTypeForDecl(named_decl);
1208 return CompilerType();
1209}
1210
1211CompilerDeclContext TypeSystemClang::CreateDeclContext(DeclContext *ctx) {
1212 // Check that the DeclContext actually belongs to this ASTContext.
1213 assert(&ctx->getParentASTContext() == &getASTContext())(static_cast <bool> (&ctx->getParentASTContext()
== &getASTContext()) ? void (0) : __assert_fail ("&ctx->getParentASTContext() == &getASTContext()"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
1213, __extension__ __PRETTY_FUNCTION__))
;
1214 return CompilerDeclContext(this, ctx);
1215}
1216
1217CompilerType TypeSystemClang::GetTypeForDecl(clang::NamedDecl *decl) {
1218 if (clang::ObjCInterfaceDecl *interface_decl =
1219 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1220 return GetTypeForDecl(interface_decl);
1221 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1222 return GetTypeForDecl(tag_decl);
1223 return CompilerType();
1224}
1225
1226CompilerType TypeSystemClang::GetTypeForDecl(TagDecl *decl) {
1227 return GetType(getASTContext().getTagDeclType(decl));
1228}
1229
1230CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1231 return GetType(getASTContext().getObjCInterfaceType(decl));
1232}
1233
1234#pragma mark Structure, Unions, Classes
1235
1236void TypeSystemClang::SetOwningModule(clang::Decl *decl,
1237 OptionalClangModuleID owning_module) {
1238 if (!decl || !owning_module.HasValue())
1239 return;
1240
1241 decl->setFromASTFile();
1242 decl->setOwningModuleID(owning_module.GetValue());
1243 decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
1244}
1245
1246OptionalClangModuleID
1247TypeSystemClang::GetOrCreateClangModule(llvm::StringRef name,
1248 OptionalClangModuleID parent,
1249 bool is_framework, bool is_explicit) {
1250 // Get the external AST source which holds the modules.
1251 auto *ast_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1252 getASTContext().getExternalSource());
1253 assert(ast_source && "external ast source was lost")(static_cast <bool> (ast_source && "external ast source was lost"
) ? void (0) : __assert_fail ("ast_source && \"external ast source was lost\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
1253, __extension__ __PRETTY_FUNCTION__))
;
1254 if (!ast_source)
1255 return {};
1256
1257 // Lazily initialize the module map.
1258 if (!m_header_search_up) {
1259 auto HSOpts = std::make_shared<clang::HeaderSearchOptions>();
1260 m_header_search_up = std::make_unique<clang::HeaderSearch>(
1261 HSOpts, *m_source_manager_up, *m_diagnostics_engine_up,
1262 *m_language_options_up, m_target_info_up.get());
1263 m_module_map_up = std::make_unique<clang::ModuleMap>(
1264 *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up,
1265 m_target_info_up.get(), *m_header_search_up);
1266 }
1267
1268 // Get or create the module context.
1269 bool created;
1270 clang::Module *module;
1271 auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue());
1272 std::tie(module, created) = m_module_map_up->findOrCreateModule(
1273 name, parent_desc ? parent_desc->getModuleOrNull() : nullptr,
1274 is_framework, is_explicit);
1275 if (!created)
1276 return ast_source->GetIDForModule(module);
1277
1278 return ast_source->RegisterModule(module);
1279}
1280
1281CompilerType TypeSystemClang::CreateRecordType(
1282 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1283 AccessType access_type, llvm::StringRef name, int kind,
1284 LanguageType language, ClangASTMetadata *metadata, bool exports_symbols) {
1285 ASTContext &ast = getASTContext();
1286
1287 if (decl_ctx == nullptr)
1288 decl_ctx = ast.getTranslationUnitDecl();
1289
1290 if (language == eLanguageTypeObjC ||
1291 language == eLanguageTypeObjC_plus_plus) {
1292 bool isForwardDecl = true;
1293 bool isInternal = false;
1294 return CreateObjCClass(name, decl_ctx, owning_module, isForwardDecl,
1295 isInternal, metadata);
1296 }
1297
1298 // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1299 // we will need to update this code. I was told to currently always use the
1300 // CXXRecordDecl class since we often don't know from debug information if
1301 // something is struct or a class, so we default to always use the more
1302 // complete definition just in case.
1303
1304 bool has_name = !name.empty();
1305 CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, 0);
1306 decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1307 decl->setDeclContext(decl_ctx);
1308 if (has_name)
1309 decl->setDeclName(&ast.Idents.get(name));
1310 SetOwningModule(decl, owning_module);
1311
1312 if (!has_name) {
1313 // In C++ a lambda is also represented as an unnamed class. This is
1314 // different from an *anonymous class* that the user wrote:
1315 //
1316 // struct A {
1317 // // anonymous class (GNU/MSVC extension)
1318 // struct {
1319 // int x;
1320 // };
1321 // // unnamed class within a class
1322 // struct {
1323 // int y;
1324 // } B;
1325 // };
1326 //
1327 // void f() {
1328 // // unammed class outside of a class
1329 // struct {
1330 // int z;
1331 // } C;
1332 // }
1333 //
1334 // Anonymous classes is a GNU/MSVC extension that clang supports. It
1335 // requires the anonymous class be embedded within a class. So the new
1336 // heuristic verifies this condition.
1337 if (isa<CXXRecordDecl>(decl_ctx) && exports_symbols)
1338 decl->setAnonymousStructOrUnion(true);
1339 }
1340
1341 if (metadata)
1342 SetMetadata(decl, *metadata);
1343
1344 if (access_type != eAccessNone)
1345 decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1346
1347 if (decl_ctx)
1348 decl_ctx->addDecl(decl);
1349
1350 return GetType(ast.getTagDeclType(decl));
1351}
1352
1353namespace {
1354/// Returns true iff the given TemplateArgument should be represented as an
1355/// NonTypeTemplateParmDecl in the AST.
1356bool IsValueParam(const clang::TemplateArgument &argument) {
1357 return argument.getKind() == TemplateArgument::Integral;
1358}
1359
1360void AddAccessSpecifierDecl(clang::CXXRecordDecl *cxx_record_decl,
1361 ASTContext &ct,
1362 clang::AccessSpecifier previous_access,
1363 clang::AccessSpecifier access_specifier) {
1364 if (!cxx_record_decl->isClass() && !cxx_record_decl->isStruct())
1365 return;
1366 if (previous_access != access_specifier) {
1367 // For struct, don't add AS_public if it's the first AccessSpecDecl.
1368 // For class, don't add AS_private if it's the first AccessSpecDecl.
1369 if ((cxx_record_decl->isStruct() &&
1370 previous_access == clang::AccessSpecifier::AS_none &&
1371 access_specifier == clang::AccessSpecifier::AS_public) ||
1372 (cxx_record_decl->isClass() &&
1373 previous_access == clang::AccessSpecifier::AS_none &&
1374 access_specifier == clang::AccessSpecifier::AS_private)) {
1375 return;
1376 }
1377 cxx_record_decl->addDecl(
1378 AccessSpecDecl::Create(ct, access_specifier, cxx_record_decl,
1379 SourceLocation(), SourceLocation()));
1380 }
1381}
1382} // namespace
1383
1384static TemplateParameterList *CreateTemplateParameterList(
1385 ASTContext &ast,
1386 const TypeSystemClang::TemplateParameterInfos &template_param_infos,
1387 llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1388 const bool parameter_pack = false;
1389 const bool is_typename = false;
1390 const unsigned depth = 0;
1391 const size_t num_template_params = template_param_infos.Size();
1392 DeclContext *const decl_context =
1393 ast.getTranslationUnitDecl(); // Is this the right decl context?,
1394
1395 auto const &args = template_param_infos.GetArgs();
1396 auto const &names = template_param_infos.GetNames();
1397 for (size_t i = 0; i < num_template_params; ++i) {
1398 const char *name = names[i];
1399
1400 IdentifierInfo *identifier_info = nullptr;
1401 if (name && name[0])
1402 identifier_info = &ast.Idents.get(name);
1403 TemplateArgument const &targ = args[i];
1404 if (IsValueParam(targ)) {
1405 QualType template_param_type = targ.getIntegralType();
1406 template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1407 ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1408 identifier_info, template_param_type, parameter_pack,
1409 ast.getTrivialTypeSourceInfo(template_param_type)));
1410 } else {
1411 template_param_decls.push_back(TemplateTypeParmDecl::Create(
1412 ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1413 identifier_info, is_typename, parameter_pack));
1414 }
1415 }
1416
1417 if (template_param_infos.hasParameterPack()) {
1418 IdentifierInfo *identifier_info = nullptr;
1419 if (template_param_infos.HasPackName())
1420 identifier_info = &ast.Idents.get(template_param_infos.GetPackName());
1421 const bool parameter_pack_true = true;
1422
1423 if (!template_param_infos.GetParameterPack().IsEmpty() &&
1424 IsValueParam(template_param_infos.GetParameterPack().Front())) {
1425 QualType template_param_type =
1426 template_param_infos.GetParameterPack().Front().getIntegralType();
1427 template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1428 ast, decl_context, SourceLocation(), SourceLocation(), depth,
1429 num_template_params, identifier_info, template_param_type,
1430 parameter_pack_true,
1431 ast.getTrivialTypeSourceInfo(template_param_type)));
1432 } else {
1433 template_param_decls.push_back(TemplateTypeParmDecl::Create(
1434 ast, decl_context, SourceLocation(), SourceLocation(), depth,
1435 num_template_params, identifier_info, is_typename,
1436 parameter_pack_true));
1437 }
1438 }
1439 clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1440 TemplateParameterList *template_param_list = TemplateParameterList::Create(
1441 ast, SourceLocation(), SourceLocation(), template_param_decls,
1442 SourceLocation(), requires_clause);
1443 return template_param_list;
1444}
1445
1446std::string TypeSystemClang::PrintTemplateParams(
1447 const TemplateParameterInfos &template_param_infos) {
1448 llvm::SmallVector<NamedDecl *, 8> ignore;
1449 clang::TemplateParameterList *template_param_list =
1450 CreateTemplateParameterList(getASTContext(), template_param_infos,
1451 ignore);
1452 llvm::SmallVector<clang::TemplateArgument, 2> args(
1453 template_param_infos.GetArgs());
1454 if (template_param_infos.hasParameterPack()) {
1455 llvm::ArrayRef<TemplateArgument> pack_args =
1456 template_param_infos.GetParameterPackArgs();
1457 args.append(pack_args.begin(), pack_args.end());
1458 }
1459 std::string str;
1460 llvm::raw_string_ostream os(str);
1461 clang::printTemplateArgumentList(os, args, GetTypePrintingPolicy(),
1462 template_param_list);
1463 return str;
1464}
1465
1466clang::FunctionTemplateDecl *TypeSystemClang::CreateFunctionTemplateDecl(
1467 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1468 clang::FunctionDecl *func_decl,
1469 const TemplateParameterInfos &template_param_infos) {
1470 // /// Create a function template node.
1471 ASTContext &ast = getASTContext();
1472
1473 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1474 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1475 ast, template_param_infos, template_param_decls);
1476 FunctionTemplateDecl *func_tmpl_decl =
1477 FunctionTemplateDecl::CreateDeserialized(ast, 0);
1478 func_tmpl_decl->setDeclContext(decl_ctx);
1479 func_tmpl_decl->setLocation(func_decl->getLocation());
1480 func_tmpl_decl->setDeclName(func_decl->getDeclName());
1481 func_tmpl_decl->setTemplateParameters(template_param_list);
1482 func_tmpl_decl->init(func_decl);
1483 SetOwningModule(func_tmpl_decl, owning_module);
1484
1485 for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1486 i < template_param_decl_count; ++i) {
1487 // TODO: verify which decl context we should put template_param_decls into..
1488 template_param_decls[i]->setDeclContext(func_decl);
1489 }
1490 // Function templates inside a record need to have an access specifier.
1491 // It doesn't matter what access specifier we give the template as LLDB
1492 // anyway allows accessing everything inside a record.
1493 if (decl_ctx->isRecord())
1494 func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public);
1495
1496 return func_tmpl_decl;
1497}
1498
1499void TypeSystemClang::CreateFunctionTemplateSpecializationInfo(
1500 FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1501 const TemplateParameterInfos &infos) {
1502 TemplateArgumentList *template_args_ptr = TemplateArgumentList::CreateCopy(
1503 func_decl->getASTContext(), infos.GetArgs());
1504
1505 func_decl->setFunctionTemplateSpecialization(func_tmpl_decl,
1506 template_args_ptr, nullptr);
1507}
1508
1509/// Returns true if the given template parameter can represent the given value.
1510/// For example, `typename T` can represent `int` but not integral values such
1511/// as `int I = 3`.
1512static bool TemplateParameterAllowsValue(NamedDecl *param,
1513 const TemplateArgument &value) {
1514 if (llvm::isa<TemplateTypeParmDecl>(param)) {
1515 // Compare the argument kind, i.e. ensure that <typename> != <int>.
1516 if (value.getKind() != TemplateArgument::Type)
1517 return false;
1518 } else if (auto *type_param =
1519 llvm::dyn_cast<NonTypeTemplateParmDecl>(param)) {
1520 // Compare the argument kind, i.e. ensure that <typename> != <int>.
1521 if (!IsValueParam(value))
1522 return false;
1523 // Compare the integral type, i.e. ensure that <int> != <char>.
1524 if (type_param->getType() != value.getIntegralType())
1525 return false;
1526 } else {
1527 // There is no way to create other parameter decls at the moment, so we
1528 // can't reach this case during normal LLDB usage. Log that this happened
1529 // and assert.
1530 Log *log = GetLog(LLDBLog::Expressions);
1531 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "Don't know how to compare template parameter to passed"
" value. Decl kind of parameter is: {0}", param->getDeclKindName
()); } while (0)
1532 "Don't know how to compare template parameter to passed"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "Don't know how to compare template parameter to passed"
" value. Decl kind of parameter is: {0}", param->getDeclKindName
()); } while (0)
1533 " value. Decl kind of parameter is: {0}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "Don't know how to compare template parameter to passed"
" value. Decl kind of parameter is: {0}", param->getDeclKindName
()); } while (0)
1534 param->getDeclKindName())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "Don't know how to compare template parameter to passed"
" value. Decl kind of parameter is: {0}", param->getDeclKindName
()); } while (0)
;
1535 lldbassert(false && "Can't compare this TemplateParmDecl subclass")lldb_private::lldb_assert(static_cast<bool>(false &&
"Can't compare this TemplateParmDecl subclass"), "false && \"Can't compare this TemplateParmDecl subclass\""
, __FUNCTION__, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 1535)
;
1536 // In release builds just fall back to marking the parameter as not
1537 // accepting the value so that we don't try to fit an instantiation to a
1538 // template that doesn't fit. E.g., avoid that `S<1>` is being connected to
1539 // `template<typename T> struct S;`.
1540 return false;
1541 }
1542 return true;
1543}
1544
1545/// Returns true if the given class template declaration could produce an
1546/// instantiation with the specified values.
1547/// For example, `<typename T>` allows the arguments `float`, but not for
1548/// example `bool, float` or `3` (as an integer parameter value).
1549static bool ClassTemplateAllowsToInstantiationArgs(
1550 ClassTemplateDecl *class_template_decl,
1551 const TypeSystemClang::TemplateParameterInfos &instantiation_values) {
1552
1553 TemplateParameterList &params = *class_template_decl->getTemplateParameters();
1554
1555 // Save some work by iterating only once over the found parameters and
1556 // calculate the information related to parameter packs.
1557
1558 // Contains the first pack parameter (or non if there are none).
1559 std::optional<NamedDecl *> pack_parameter;
1560 // Contains the number of non-pack parameters.
1561 size_t non_pack_params = params.size();
1562 for (size_t i = 0; i < params.size(); ++i) {
1563 NamedDecl *param = params.getParam(i);
1564 if (param->isParameterPack()) {
1565 pack_parameter = param;
1566 non_pack_params = i;
1567 break;
1568 }
1569 }
1570
1571 // The found template needs to have compatible non-pack template arguments.
1572 // E.g., ensure that <typename, typename> != <typename>.
1573 // The pack parameters are compared later.
1574 if (non_pack_params != instantiation_values.Size())
1575 return false;
1576
1577 // Ensure that <typename...> != <typename>.
1578 if (pack_parameter.has_value() != instantiation_values.hasParameterPack())
1579 return false;
1580
1581 // Compare the first pack parameter that was found with the first pack
1582 // parameter value. The special case of having an empty parameter pack value
1583 // always fits to a pack parameter.
1584 // E.g., ensure that <int...> != <typename...>.
1585 if (pack_parameter && !instantiation_values.GetParameterPack().IsEmpty() &&
1586 !TemplateParameterAllowsValue(
1587 *pack_parameter, instantiation_values.GetParameterPack().Front()))
1588 return false;
1589
1590 // Compare all the non-pack parameters now.
1591 // E.g., ensure that <int> != <long>.
1592 for (const auto pair :
1593 llvm::zip_first(instantiation_values.GetArgs(), params)) {
1594 const TemplateArgument &passed_arg = std::get<0>(pair);
1595 NamedDecl *found_param = std::get<1>(pair);
1596 if (!TemplateParameterAllowsValue(found_param, passed_arg))
1597 return false;
1598 }
1599
1600 return class_template_decl;
1601}
1602
1603ClassTemplateDecl *TypeSystemClang::CreateClassTemplateDecl(
1604 DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1605 lldb::AccessType access_type, llvm::StringRef class_name, int kind,
1606 const TemplateParameterInfos &template_param_infos) {
1607 ASTContext &ast = getASTContext();
1608
1609 ClassTemplateDecl *class_template_decl = nullptr;
1610 if (decl_ctx == nullptr)
1611 decl_ctx = ast.getTranslationUnitDecl();
1612
1613 IdentifierInfo &identifier_info = ast.Idents.get(class_name);
1614 DeclarationName decl_name(&identifier_info);
1615
1616 // Search the AST for an existing ClassTemplateDecl that could be reused.
1617 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1618 for (NamedDecl *decl : result) {
1619 class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1620 if (!class_template_decl)
1621 continue;
1622 // The class template has to be able to represents the instantiation
1623 // values we received. Without this we might end up putting an instantiation
1624 // with arguments such as <int, int> to a template such as:
1625 // template<typename T> struct S;
1626 // Connecting the instantiation to an incompatible template could cause
1627 // problems later on.
1628 if (!ClassTemplateAllowsToInstantiationArgs(class_template_decl,
1629 template_param_infos))
1630 continue;
1631 return class_template_decl;
1632 }
1633
1634 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1635
1636 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1637 ast, template_param_infos, template_param_decls);
1638
1639 CXXRecordDecl *template_cxx_decl = CXXRecordDecl::CreateDeserialized(ast, 0);
1640 template_cxx_decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1641 // What decl context do we use here? TU? The actual decl context?
1642 template_cxx_decl->setDeclContext(decl_ctx);
1643 template_cxx_decl->setDeclName(decl_name);
1644 SetOwningModule(template_cxx_decl, owning_module);
1645
1646 for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1647 i < template_param_decl_count; ++i) {
1648 template_param_decls[i]->setDeclContext(template_cxx_decl);
1649 }
1650
1651 // With templated classes, we say that a class is templated with
1652 // specializations, but that the bare class has no functions.
1653 // template_cxx_decl->startDefinition();
1654 // template_cxx_decl->completeDefinition();
1655
1656 class_template_decl = ClassTemplateDecl::CreateDeserialized(ast, 0);
1657 // What decl context do we use here? TU? The actual decl context?
1658 class_template_decl->setDeclContext(decl_ctx);
1659 class_template_decl->setDeclName(decl_name);
1660 class_template_decl->setTemplateParameters(template_param_list);
1661 class_template_decl->init(template_cxx_decl);
1662 template_cxx_decl->setDescribedClassTemplate(class_template_decl);
1663 SetOwningModule(class_template_decl, owning_module);
1664
1665 if (access_type != eAccessNone)
1666 class_template_decl->setAccess(
1667 ConvertAccessTypeToAccessSpecifier(access_type));
1668
1669 decl_ctx->addDecl(class_template_decl);
1670
1671 VerifyDecl(class_template_decl);
1672
1673 return class_template_decl;
1674}
1675
1676TemplateTemplateParmDecl *
1677TypeSystemClang::CreateTemplateTemplateParmDecl(const char *template_name) {
1678 ASTContext &ast = getASTContext();
1679
1680 auto *decl_ctx = ast.getTranslationUnitDecl();
1681
1682 IdentifierInfo &identifier_info = ast.Idents.get(template_name);
1683 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1684
1685 TypeSystemClang::TemplateParameterInfos template_param_infos;
1686 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1687 ast, template_param_infos, template_param_decls);
1688
1689 // LLDB needs to create those decls only to be able to display a
1690 // type that includes a template template argument. Only the name matters for
1691 // this purpose, so we use dummy values for the other characteristics of the
1692 // type.
1693 return TemplateTemplateParmDecl::Create(
1694 ast, decl_ctx, SourceLocation(),
1695 /*Depth*/ 0, /*Position*/ 0,
1696 /*IsParameterPack*/ false, &identifier_info, template_param_list);
1697}
1698
1699ClassTemplateSpecializationDecl *
1700TypeSystemClang::CreateClassTemplateSpecializationDecl(
1701 DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1702 ClassTemplateDecl *class_template_decl, int kind,
1703 const TemplateParameterInfos &template_param_infos) {
1704 ASTContext &ast = getASTContext();
1705 llvm::SmallVector<clang::TemplateArgument, 2> args(
1706 template_param_infos.Size() +
1707 (template_param_infos.hasParameterPack() ? 1 : 0));
1708
1709 auto const &orig_args = template_param_infos.GetArgs();
1710 std::copy(orig_args.begin(), orig_args.end(), args.begin());
1711 if (template_param_infos.hasParameterPack()) {
1712 args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1713 ast, template_param_infos.GetParameterPackArgs());
1714 }
1715 ClassTemplateSpecializationDecl *class_template_specialization_decl =
1716 ClassTemplateSpecializationDecl::CreateDeserialized(ast, 0);
1717 class_template_specialization_decl->setTagKind(
1718 static_cast<TagDecl::TagKind>(kind));
1719 class_template_specialization_decl->setDeclContext(decl_ctx);
1720 class_template_specialization_decl->setInstantiationOf(class_template_decl);
1721 class_template_specialization_decl->setTemplateArgs(
1722 TemplateArgumentList::CreateCopy(ast, args));
1723 ast.getTypeDeclType(class_template_specialization_decl, nullptr);
1724 class_template_specialization_decl->setDeclName(
1725 class_template_decl->getDeclName());
1726 SetOwningModule(class_template_specialization_decl, owning_module);
1727 decl_ctx->addDecl(class_template_specialization_decl);
1728
1729 class_template_specialization_decl->setSpecializationKind(
1730 TSK_ExplicitSpecialization);
1731
1732 return class_template_specialization_decl;
1733}
1734
1735CompilerType TypeSystemClang::CreateClassTemplateSpecializationType(
1736 ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1737 if (class_template_specialization_decl) {
1738 ASTContext &ast = getASTContext();
1739 return GetType(ast.getTagDeclType(class_template_specialization_decl));
1740 }
1741 return CompilerType();
1742}
1743
1744static inline bool check_op_param(bool is_method,
1745 clang::OverloadedOperatorKind op_kind,
1746 bool unary, bool binary,
1747 uint32_t num_params) {
1748 // Special-case call since it can take any number of operands
1749 if (op_kind == OO_Call)
1750 return true;
1751
1752 // The parameter count doesn't include "this"
1753 if (is_method)
1754 ++num_params;
1755 if (num_params == 1)
1756 return unary;
1757 if (num_params == 2)
1758 return binary;
1759 else
1760 return false;
1761}
1762
1763bool TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
1764 bool is_method, clang::OverloadedOperatorKind op_kind,
1765 uint32_t num_params) {
1766 switch (op_kind) {
1767 default:
1768 break;
1769 // C++ standard allows any number of arguments to new/delete
1770 case OO_New:
1771 case OO_Array_New:
1772 case OO_Delete:
1773 case OO_Array_Delete:
1774 return true;
1775 }
1776
1777#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
1778 case OO_##Name: \
1779 return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1780 switch (op_kind) {
1781#include "clang/Basic/OperatorKinds.def"
1782 default:
1783 break;
1784 }
1785 return false;
1786}
1787
1788clang::AccessSpecifier
1789TypeSystemClang::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
1790 clang::AccessSpecifier rhs) {
1791 // Make the access equal to the stricter of the field and the nested field's
1792 // access
1793 if (lhs == AS_none || rhs == AS_none)
1794 return AS_none;
1795 if (lhs == AS_private || rhs == AS_private)
1796 return AS_private;
1797 if (lhs == AS_protected || rhs == AS_protected)
1798 return AS_protected;
1799 return AS_public;
1800}
1801
1802bool TypeSystemClang::FieldIsBitfield(FieldDecl *field,
1803 uint32_t &bitfield_bit_size) {
1804 ASTContext &ast = getASTContext();
1805 if (field == nullptr)
1806 return false;
1807
1808 if (field->isBitField()) {
1809 Expr *bit_width_expr = field->getBitWidth();
1810 if (bit_width_expr) {
1811 if (std::optional<llvm::APSInt> bit_width_apsint =
1812 bit_width_expr->getIntegerConstantExpr(ast)) {
1813 bitfield_bit_size = bit_width_apsint->getLimitedValue(UINT32_MAX(4294967295U));
1814 return true;
1815 }
1816 }
1817 }
1818 return false;
1819}
1820
1821bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) {
1822 if (record_decl == nullptr)
1823 return false;
1824
1825 if (!record_decl->field_empty())
1826 return true;
1827
1828 // No fields, lets check this is a CXX record and check the base classes
1829 const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1830 if (cxx_record_decl) {
1831 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1832 for (base_class = cxx_record_decl->bases_begin(),
1833 base_class_end = cxx_record_decl->bases_end();
1834 base_class != base_class_end; ++base_class) {
1835 const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1836 base_class->getType()->getAs<RecordType>()->getDecl());
1837 if (RecordHasFields(base_class_decl))
1838 return true;
1839 }
1840 }
1841
1842 // We always want forcefully completed types to show up so we can print a
1843 // message in the summary that indicates that the type is incomplete.
1844 // This will help users know when they are running into issues with
1845 // -flimit-debug-info instead of just seeing nothing if this is a base class
1846 // (since we were hiding empty base classes), or nothing when you turn open
1847 // an valiable whose type was incomplete.
1848 ClangASTMetadata *meta_data = GetMetadata(record_decl);
1849 if (meta_data && meta_data->IsForcefullyCompleted())
1850 return true;
1851
1852 return false;
1853}
1854
1855#pragma mark Objective-C Classes
1856
1857CompilerType TypeSystemClang::CreateObjCClass(
1858 llvm::StringRef name, clang::DeclContext *decl_ctx,
1859 OptionalClangModuleID owning_module, bool isForwardDecl, bool isInternal,
1860 ClangASTMetadata *metadata) {
1861 ASTContext &ast = getASTContext();
1862 assert(!name.empty())(static_cast <bool> (!name.empty()) ? void (0) : __assert_fail
("!name.empty()", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 1862, __extension__ __PRETTY_FUNCTION__))
;
1863 if (!decl_ctx)
1864 decl_ctx = ast.getTranslationUnitDecl();
1865
1866 ObjCInterfaceDecl *decl = ObjCInterfaceDecl::CreateDeserialized(ast, 0);
1867 decl->setDeclContext(decl_ctx);
1868 decl->setDeclName(&ast.Idents.get(name));
1869 /*isForwardDecl,*/
1870 decl->setImplicit(isInternal);
1871 SetOwningModule(decl, owning_module);
1872
1873 if (metadata)
1874 SetMetadata(decl, *metadata);
1875
1876 return GetType(ast.getObjCInterfaceType(decl));
1877}
1878
1879bool TypeSystemClang::BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1880 return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl());
1881}
1882
1883uint32_t
1884TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1885 bool omit_empty_base_classes) {
1886 uint32_t num_bases = 0;
1887 if (cxx_record_decl) {
1888 if (omit_empty_base_classes) {
1889 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1890 for (base_class = cxx_record_decl->bases_begin(),
1891 base_class_end = cxx_record_decl->bases_end();
1892 base_class != base_class_end; ++base_class) {
1893 // Skip empty base classes
1894 if (BaseSpecifierIsEmpty(base_class))
1895 continue;
1896 ++num_bases;
1897 }
1898 } else
1899 num_bases = cxx_record_decl->getNumBases();
1900 }
1901 return num_bases;
1902}
1903
1904#pragma mark Namespace Declarations
1905
1906NamespaceDecl *TypeSystemClang::GetUniqueNamespaceDeclaration(
1907 const char *name, clang::DeclContext *decl_ctx,
1908 OptionalClangModuleID owning_module, bool is_inline) {
1909 NamespaceDecl *namespace_decl = nullptr;
1910 ASTContext &ast = getASTContext();
1911 TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl();
1912 if (!decl_ctx)
1913 decl_ctx = translation_unit_decl;
1914
1915 if (name) {
1916 IdentifierInfo &identifier_info = ast.Idents.get(name);
1917 DeclarationName decl_name(&identifier_info);
1918 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1919 for (NamedDecl *decl : result) {
1920 namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1921 if (namespace_decl)
1922 return namespace_decl;
1923 }
1924
1925 namespace_decl = NamespaceDecl::Create(ast, decl_ctx, is_inline,
1926 SourceLocation(), SourceLocation(),
1927 &identifier_info, nullptr, false);
1928
1929 decl_ctx->addDecl(namespace_decl);
1930 } else {
1931 if (decl_ctx == translation_unit_decl) {
1932 namespace_decl = translation_unit_decl->getAnonymousNamespace();
1933 if (namespace_decl)
1934 return namespace_decl;
1935
1936 namespace_decl =
1937 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1938 SourceLocation(), nullptr, nullptr, false);
1939 translation_unit_decl->setAnonymousNamespace(namespace_decl);
1940 translation_unit_decl->addDecl(namespace_decl);
1941 assert(namespace_decl == translation_unit_decl->getAnonymousNamespace())(static_cast <bool> (namespace_decl == translation_unit_decl
->getAnonymousNamespace()) ? void (0) : __assert_fail ("namespace_decl == translation_unit_decl->getAnonymousNamespace()"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
1941, __extension__ __PRETTY_FUNCTION__))
;
1942 } else {
1943 NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1944 if (parent_namespace_decl) {
1945 namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1946 if (namespace_decl)
1947 return namespace_decl;
1948 namespace_decl =
1949 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1950 SourceLocation(), nullptr, nullptr, false);
1951 parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1952 parent_namespace_decl->addDecl(namespace_decl);
1953 assert(namespace_decl ==(static_cast <bool> (namespace_decl == parent_namespace_decl
->getAnonymousNamespace()) ? void (0) : __assert_fail ("namespace_decl == parent_namespace_decl->getAnonymousNamespace()"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
1954, __extension__ __PRETTY_FUNCTION__))
1954 parent_namespace_decl->getAnonymousNamespace())(static_cast <bool> (namespace_decl == parent_namespace_decl
->getAnonymousNamespace()) ? void (0) : __assert_fail ("namespace_decl == parent_namespace_decl->getAnonymousNamespace()"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
1954, __extension__ __PRETTY_FUNCTION__))
;
1955 } else {
1956 assert(false && "GetUniqueNamespaceDeclaration called with no name and "(static_cast <bool> (false && "GetUniqueNamespaceDeclaration called with no name and "
"no namespace as decl_ctx") ? void (0) : __assert_fail ("false && \"GetUniqueNamespaceDeclaration called with no name and \" \"no namespace as decl_ctx\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
1957, __extension__ __PRETTY_FUNCTION__))
1957 "no namespace as decl_ctx")(static_cast <bool> (false && "GetUniqueNamespaceDeclaration called with no name and "
"no namespace as decl_ctx") ? void (0) : __assert_fail ("false && \"GetUniqueNamespaceDeclaration called with no name and \" \"no namespace as decl_ctx\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
1957, __extension__ __PRETTY_FUNCTION__))
;
1958 }
1959 }
1960 }
1961 // Note: namespaces can span multiple modules, so perhaps this isn't a good
1962 // idea.
1963 SetOwningModule(namespace_decl, owning_module);
1964
1965 VerifyDecl(namespace_decl);
1966 return namespace_decl;
1967}
1968
1969clang::BlockDecl *
1970TypeSystemClang::CreateBlockDeclaration(clang::DeclContext *ctx,
1971 OptionalClangModuleID owning_module) {
1972 if (ctx) {
1973 clang::BlockDecl *decl =
1974 clang::BlockDecl::CreateDeserialized(getASTContext(), 0);
1975 decl->setDeclContext(ctx);
1976 ctx->addDecl(decl);
1977 SetOwningModule(decl, owning_module);
1978 return decl;
1979 }
1980 return nullptr;
1981}
1982
1983clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1984 clang::DeclContext *right,
1985 clang::DeclContext *root) {
1986 if (root == nullptr)
1987 return nullptr;
1988
1989 std::set<clang::DeclContext *> path_left;
1990 for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
1991 path_left.insert(d);
1992
1993 for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
1994 if (path_left.find(d) != path_left.end())
1995 return d;
1996
1997 return nullptr;
1998}
1999
2000clang::UsingDirectiveDecl *TypeSystemClang::CreateUsingDirectiveDeclaration(
2001 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2002 clang::NamespaceDecl *ns_decl) {
2003 if (decl_ctx && ns_decl) {
2004 auto *translation_unit = getASTContext().getTranslationUnitDecl();
2005 clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
2006 getASTContext(), decl_ctx, clang::SourceLocation(),
2007 clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
2008 clang::SourceLocation(), ns_decl,
2009 FindLCABetweenDecls(decl_ctx, ns_decl,
2010 translation_unit));
2011 decl_ctx->addDecl(using_decl);
2012 SetOwningModule(using_decl, owning_module);
2013 return using_decl;
2014 }
2015 return nullptr;
2016}
2017
2018clang::UsingDecl *
2019TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
2020 OptionalClangModuleID owning_module,
2021 clang::NamedDecl *target) {
2022 if (current_decl_ctx && target) {
2023 clang::UsingDecl *using_decl = clang::UsingDecl::Create(
2024 getASTContext(), current_decl_ctx, clang::SourceLocation(),
2025 clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
2026 SetOwningModule(using_decl, owning_module);
2027 clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
2028 getASTContext(), current_decl_ctx, clang::SourceLocation(),
2029 target->getDeclName(), using_decl, target);
2030 SetOwningModule(shadow_decl, owning_module);
2031 using_decl->addShadowDecl(shadow_decl);
2032 current_decl_ctx->addDecl(using_decl);
2033 return using_decl;
2034 }
2035 return nullptr;
2036}
2037
2038clang::VarDecl *TypeSystemClang::CreateVariableDeclaration(
2039 clang::DeclContext *decl_context, OptionalClangModuleID owning_module,
2040 const char *name, clang::QualType type) {
2041 if (decl_context) {
2042 clang::VarDecl *var_decl =
2043 clang::VarDecl::CreateDeserialized(getASTContext(), 0);
2044 var_decl->setDeclContext(decl_context);
2045 if (name && name[0])
2046 var_decl->setDeclName(&getASTContext().Idents.getOwn(name));
2047 var_decl->setType(type);
2048 SetOwningModule(var_decl, owning_module);
2049 var_decl->setAccess(clang::AS_public);
2050 decl_context->addDecl(var_decl);
2051 return var_decl;
2052 }
2053 return nullptr;
2054}
2055
2056lldb::opaque_compiler_type_t
2057TypeSystemClang::GetOpaqueCompilerType(clang::ASTContext *ast,
2058 lldb::BasicType basic_type) {
2059 switch (basic_type) {
2060 case eBasicTypeVoid:
2061 return ast->VoidTy.getAsOpaquePtr();
2062 case eBasicTypeChar:
2063 return ast->CharTy.getAsOpaquePtr();
2064 case eBasicTypeSignedChar:
2065 return ast->SignedCharTy.getAsOpaquePtr();
2066 case eBasicTypeUnsignedChar:
2067 return ast->UnsignedCharTy.getAsOpaquePtr();
2068 case eBasicTypeWChar:
2069 return ast->getWCharType().getAsOpaquePtr();
2070 case eBasicTypeSignedWChar:
2071 return ast->getSignedWCharType().getAsOpaquePtr();
2072 case eBasicTypeUnsignedWChar:
2073 return ast->getUnsignedWCharType().getAsOpaquePtr();
2074 case eBasicTypeChar8:
2075 return ast->Char8Ty.getAsOpaquePtr();
2076 case eBasicTypeChar16:
2077 return ast->Char16Ty.getAsOpaquePtr();
2078 case eBasicTypeChar32:
2079 return ast->Char32Ty.getAsOpaquePtr();
2080 case eBasicTypeShort:
2081 return ast->ShortTy.getAsOpaquePtr();
2082 case eBasicTypeUnsignedShort:
2083 return ast->UnsignedShortTy.getAsOpaquePtr();
2084 case eBasicTypeInt:
2085 return ast->IntTy.getAsOpaquePtr();
2086 case eBasicTypeUnsignedInt:
2087 return ast->UnsignedIntTy.getAsOpaquePtr();
2088 case eBasicTypeLong:
2089 return ast->LongTy.getAsOpaquePtr();
2090 case eBasicTypeUnsignedLong:
2091 return ast->UnsignedLongTy.getAsOpaquePtr();
2092 case eBasicTypeLongLong:
2093 return ast->LongLongTy.getAsOpaquePtr();
2094 case eBasicTypeUnsignedLongLong:
2095 return ast->UnsignedLongLongTy.getAsOpaquePtr();
2096 case eBasicTypeInt128:
2097 return ast->Int128Ty.getAsOpaquePtr();
2098 case eBasicTypeUnsignedInt128:
2099 return ast->UnsignedInt128Ty.getAsOpaquePtr();
2100 case eBasicTypeBool:
2101 return ast->BoolTy.getAsOpaquePtr();
2102 case eBasicTypeHalf:
2103 return ast->HalfTy.getAsOpaquePtr();
2104 case eBasicTypeFloat:
2105 return ast->FloatTy.getAsOpaquePtr();
2106 case eBasicTypeDouble:
2107 return ast->DoubleTy.getAsOpaquePtr();
2108 case eBasicTypeLongDouble:
2109 return ast->LongDoubleTy.getAsOpaquePtr();
2110 case eBasicTypeFloatComplex:
2111 return ast->getComplexType(ast->FloatTy).getAsOpaquePtr();
2112 case eBasicTypeDoubleComplex:
2113 return ast->getComplexType(ast->DoubleTy).getAsOpaquePtr();
2114 case eBasicTypeLongDoubleComplex:
2115 return ast->getComplexType(ast->LongDoubleTy).getAsOpaquePtr();
2116 case eBasicTypeObjCID:
2117 return ast->getObjCIdType().getAsOpaquePtr();
2118 case eBasicTypeObjCClass:
2119 return ast->getObjCClassType().getAsOpaquePtr();
2120 case eBasicTypeObjCSel:
2121 return ast->getObjCSelType().getAsOpaquePtr();
2122 case eBasicTypeNullPtr:
2123 return ast->NullPtrTy.getAsOpaquePtr();
2124 default:
2125 return nullptr;
2126 }
2127}
2128
2129#pragma mark Function Types
2130
2131clang::DeclarationName
2132TypeSystemClang::GetDeclarationName(llvm::StringRef name,
2133 const CompilerType &function_clang_type) {
2134 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
2135 if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
2136 return DeclarationName(&getASTContext().Idents.get(
2137 name)); // Not operator, but a regular function.
2138
2139 // Check the number of operator parameters. Sometimes we have seen bad DWARF
2140 // that doesn't correctly describe operators and if we try to create a method
2141 // and add it to the class, clang will assert and crash, so we need to make
2142 // sure things are acceptable.
2143 clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
2144 const clang::FunctionProtoType *function_type =
2145 llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
2146 if (function_type == nullptr)
2147 return clang::DeclarationName();
2148
2149 const bool is_method = false;
2150 const unsigned int num_params = function_type->getNumParams();
2151 if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
2152 is_method, op_kind, num_params))
2153 return clang::DeclarationName();
2154
2155 return getASTContext().DeclarationNames.getCXXOperatorName(op_kind);
2156}
2157
2158PrintingPolicy TypeSystemClang::GetTypePrintingPolicy() {
2159 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
2160 printing_policy.SuppressTagKeyword = true;
2161 // Inline namespaces are important for some type formatters (e.g., libc++
2162 // and libstdc++ are differentiated by their inline namespaces).
2163 printing_policy.SuppressInlineNamespace = false;
2164 printing_policy.SuppressUnwrittenScope = false;
2165 // Default arguments are also always important for type formatters. Otherwise
2166 // we would need to always specify two type names for the setups where we do
2167 // know the default arguments and where we don't know default arguments.
2168 //
2169 // For example, without this we would need to have formatters for both:
2170 // std::basic_string<char>
2171 // and
2172 // std::basic_string<char, std::char_traits<char>, std::allocator<char> >
2173 // to support setups where LLDB was able to reconstruct default arguments
2174 // (and we then would have suppressed them from the type name) and also setups
2175 // where LLDB wasn't able to reconstruct the default arguments.
2176 printing_policy.SuppressDefaultTemplateArgs = false;
2177 return printing_policy;
2178}
2179
2180std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl,
2181 bool qualified) {
2182 clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
2183 std::string result;
2184 llvm::raw_string_ostream os(result);
2185 named_decl->getNameForDiagnostic(os, printing_policy, qualified);
2186 return result;
2187}
2188
2189FunctionDecl *TypeSystemClang::CreateFunctionDeclaration(
2190 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2191 llvm::StringRef name, const CompilerType &function_clang_type,
2192 clang::StorageClass storage, bool is_inline) {
2193 FunctionDecl *func_decl = nullptr;
2194 ASTContext &ast = getASTContext();
2195 if (!decl_ctx)
2196 decl_ctx = ast.getTranslationUnitDecl();
2197
2198 const bool hasWrittenPrototype = true;
2199 const bool isConstexprSpecified = false;
2200
2201 clang::DeclarationName declarationName =
2202 GetDeclarationName(name, function_clang_type);
2203 func_decl = FunctionDecl::CreateDeserialized(ast, 0);
2204 func_decl->setDeclContext(decl_ctx);
2205 func_decl->setDeclName(declarationName);
2206 func_decl->setType(ClangUtil::GetQualType(function_clang_type));
2207 func_decl->setStorageClass(storage);
2208 func_decl->setInlineSpecified(is_inline);
2209 func_decl->setHasWrittenPrototype(hasWrittenPrototype);
2210 func_decl->setConstexprKind(isConstexprSpecified
2211 ? ConstexprSpecKind::Constexpr
2212 : ConstexprSpecKind::Unspecified);
2213 SetOwningModule(func_decl, owning_module);
2214 decl_ctx->addDecl(func_decl);
2215
2216 VerifyDecl(func_decl);
2217
2218 return func_decl;
2219}
2220
2221CompilerType TypeSystemClang::CreateFunctionType(
2222 const CompilerType &result_type, const CompilerType *args,
2223 unsigned num_args, bool is_variadic, unsigned type_quals,
2224 clang::CallingConv cc, clang::RefQualifierKind ref_qual) {
2225 if (!result_type || !ClangUtil::IsClangType(result_type))
2226 return CompilerType(); // invalid return type
2227
2228 std::vector<QualType> qual_type_args;
2229 if (num_args > 0 && args == nullptr)
2230 return CompilerType(); // invalid argument array passed in
2231
2232 // Verify that all arguments are valid and the right type
2233 for (unsigned i = 0; i < num_args; ++i) {
2234 if (args[i]) {
2235 // Make sure we have a clang type in args[i] and not a type from another
2236 // language whose name might match
2237 const bool is_clang_type = ClangUtil::IsClangType(args[i]);
2238 lldbassert(is_clang_type)lldb_private::lldb_assert(static_cast<bool>(is_clang_type
), "is_clang_type", __FUNCTION__, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 2238)
;
2239 if (is_clang_type)
2240 qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
2241 else
2242 return CompilerType(); // invalid argument type (must be a clang type)
2243 } else
2244 return CompilerType(); // invalid argument type (empty)
2245 }
2246
2247 // TODO: Detect calling convention in DWARF?
2248 FunctionProtoType::ExtProtoInfo proto_info;
2249 proto_info.ExtInfo = cc;
2250 proto_info.Variadic = is_variadic;
2251 proto_info.ExceptionSpec = EST_None;
2252 proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals);
2253 proto_info.RefQualifier = ref_qual;
2254
2255 return GetType(getASTContext().getFunctionType(
2256 ClangUtil::GetQualType(result_type), qual_type_args, proto_info));
2257}
2258
2259ParmVarDecl *TypeSystemClang::CreateParameterDeclaration(
2260 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2261 const char *name, const CompilerType &param_type, int storage,
2262 bool add_decl) {
2263 ASTContext &ast = getASTContext();
2264 auto *decl = ParmVarDecl::CreateDeserialized(ast, 0);
2265 decl->setDeclContext(decl_ctx);
2266 if (name && name[0])
2267 decl->setDeclName(&ast.Idents.get(name));
2268 decl->setType(ClangUtil::GetQualType(param_type));
2269 decl->setStorageClass(static_cast<clang::StorageClass>(storage));
2270 SetOwningModule(decl, owning_module);
2271 if (add_decl)
2272 decl_ctx->addDecl(decl);
2273
2274 return decl;
2275}
2276
2277void TypeSystemClang::SetFunctionParameters(
2278 FunctionDecl *function_decl, llvm::ArrayRef<ParmVarDecl *> params) {
2279 if (function_decl)
2280 function_decl->setParams(params);
2281}
2282
2283CompilerType
2284TypeSystemClang::CreateBlockPointerType(const CompilerType &function_type) {
2285 QualType block_type = m_ast_up->getBlockPointerType(
2286 clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2287
2288 return GetType(block_type);
2289}
2290
2291#pragma mark Array Types
2292
2293CompilerType TypeSystemClang::CreateArrayType(const CompilerType &element_type,
2294 size_t element_count,
2295 bool is_vector) {
2296 if (element_type.IsValid()) {
2297 ASTContext &ast = getASTContext();
2298
2299 if (is_vector) {
2300 return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type),
2301 element_count));
2302 } else {
2303
2304 llvm::APInt ap_element_count(64, element_count);
2305 if (element_count == 0) {
2306 return GetType(ast.getIncompleteArrayType(
2307 ClangUtil::GetQualType(element_type), clang::ArrayType::Normal, 0));
2308 } else {
2309 return GetType(ast.getConstantArrayType(
2310 ClangUtil::GetQualType(element_type), ap_element_count, nullptr,
2311 clang::ArrayType::Normal, 0));
2312 }
2313 }
2314 }
2315 return CompilerType();
2316}
2317
2318CompilerType TypeSystemClang::CreateStructForIdentifier(
2319 ConstString type_name,
2320 const std::initializer_list<std::pair<const char *, CompilerType>>
2321 &type_fields,
2322 bool packed) {
2323 CompilerType type;
2324 if (!type_name.IsEmpty() &&
2325 (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2326 .IsValid()) {
2327 lldbassert(0 && "Trying to create a type for an existing name")lldb_private::lldb_assert(static_cast<bool>(0 &&
"Trying to create a type for an existing name"), "0 && \"Trying to create a type for an existing name\""
, __FUNCTION__, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 2327)
;
2328 return type;
2329 }
2330
2331 type = CreateRecordType(nullptr, OptionalClangModuleID(), lldb::eAccessPublic,
2332 type_name.GetCString(), clang::TTK_Struct,
2333 lldb::eLanguageTypeC);
2334 StartTagDeclarationDefinition(type);
2335 for (const auto &field : type_fields)
2336 AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2337 0);
2338 if (packed)
2339 SetIsPacked(type);
2340 CompleteTagDeclarationDefinition(type);
2341 return type;
2342}
2343
2344CompilerType TypeSystemClang::GetOrCreateStructForIdentifier(
2345 ConstString type_name,
2346 const std::initializer_list<std::pair<const char *, CompilerType>>
2347 &type_fields,
2348 bool packed) {
2349 CompilerType type;
2350 if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2351 return type;
2352
2353 return CreateStructForIdentifier(type_name, type_fields, packed);
2354}
2355
2356#pragma mark Enumeration Types
2357
2358CompilerType TypeSystemClang::CreateEnumerationType(
2359 llvm::StringRef name, clang::DeclContext *decl_ctx,
2360 OptionalClangModuleID owning_module, const Declaration &decl,
2361 const CompilerType &integer_clang_type, bool is_scoped) {
2362 // TODO: Do something intelligent with the Declaration object passed in
2363 // like maybe filling in the SourceLocation with it...
2364 ASTContext &ast = getASTContext();
2365
2366 // TODO: ask about these...
2367 // const bool IsFixed = false;
2368 EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, 0);
2369 enum_decl->setDeclContext(decl_ctx);
2370 if (!name.empty())
2371 enum_decl->setDeclName(&ast.Idents.get(name));
2372 enum_decl->setScoped(is_scoped);
2373 enum_decl->setScopedUsingClassTag(is_scoped);
2374 enum_decl->setFixed(false);
2375 SetOwningModule(enum_decl, owning_module);
2376 if (decl_ctx)
2377 decl_ctx->addDecl(enum_decl);
2378
2379 // TODO: check if we should be setting the promotion type too?
2380 enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2381
2382 enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2383
2384 return GetType(ast.getTagDeclType(enum_decl));
2385}
2386
2387CompilerType TypeSystemClang::GetIntTypeFromBitSize(size_t bit_size,
2388 bool is_signed) {
2389 clang::ASTContext &ast = getASTContext();
2390
2391 if (is_signed) {
2392 if (bit_size == ast.getTypeSize(ast.SignedCharTy))
2393 return GetType(ast.SignedCharTy);
2394
2395 if (bit_size == ast.getTypeSize(ast.ShortTy))
2396 return GetType(ast.ShortTy);
2397
2398 if (bit_size == ast.getTypeSize(ast.IntTy))
2399 return GetType(ast.IntTy);
2400
2401 if (bit_size == ast.getTypeSize(ast.LongTy))
2402 return GetType(ast.LongTy);
2403
2404 if (bit_size == ast.getTypeSize(ast.LongLongTy))
2405 return GetType(ast.LongLongTy);
2406
2407 if (bit_size == ast.getTypeSize(ast.Int128Ty))
2408 return GetType(ast.Int128Ty);
2409 } else {
2410 if (bit_size == ast.getTypeSize(ast.UnsignedCharTy))
2411 return GetType(ast.UnsignedCharTy);
2412
2413 if (bit_size == ast.getTypeSize(ast.UnsignedShortTy))
2414 return GetType(ast.UnsignedShortTy);
2415
2416 if (bit_size == ast.getTypeSize(ast.UnsignedIntTy))
2417 return GetType(ast.UnsignedIntTy);
2418
2419 if (bit_size == ast.getTypeSize(ast.UnsignedLongTy))
2420 return GetType(ast.UnsignedLongTy);
2421
2422 if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy))
2423 return GetType(ast.UnsignedLongLongTy);
2424
2425 if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty))
2426 return GetType(ast.UnsignedInt128Ty);
2427 }
2428 return CompilerType();
2429}
2430
2431CompilerType TypeSystemClang::GetPointerSizedIntType(bool is_signed) {
2432 return GetIntTypeFromBitSize(
2433 getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed);
2434}
2435
2436void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2437 if (decl_ctx) {
2438 DumpDeclContextHiearchy(decl_ctx->getParent());
2439
2440 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2441 if (named_decl) {
2442 printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2443 named_decl->getDeclName().getAsString().c_str());
2444 } else {
2445 printf("%20s\n", decl_ctx->getDeclKindName());
2446 }
2447 }
2448}
2449
2450void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) {
2451 if (decl == nullptr)
2452 return;
2453 DumpDeclContextHiearchy(decl->getDeclContext());
2454
2455 clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2456 if (record_decl) {
2457 printf("%20s: %s%s\n", decl->getDeclKindName(),
2458 record_decl->getDeclName().getAsString().c_str(),
2459 record_decl->isInjectedClassName() ? " (injected class name)" : "");
2460
2461 } else {
2462 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2463 if (named_decl) {
2464 printf("%20s: %s\n", decl->getDeclKindName(),
2465 named_decl->getDeclName().getAsString().c_str());
2466 } else {
2467 printf("%20s\n", decl->getDeclKindName());
2468 }
2469 }
2470}
2471
2472bool TypeSystemClang::DeclsAreEquivalent(clang::Decl *lhs_decl,
2473 clang::Decl *rhs_decl) {
2474 if (lhs_decl && rhs_decl) {
2475 // Make sure the decl kinds match first
2476 const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind();
2477 const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind();
2478
2479 if (lhs_decl_kind == rhs_decl_kind) {
2480 // Now check that the decl contexts kinds are all equivalent before we
2481 // have to check any names of the decl contexts...
2482 clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext();
2483 clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext();
2484 if (lhs_decl_ctx && rhs_decl_ctx) {
2485 while (true) {
2486 if (lhs_decl_ctx && rhs_decl_ctx) {
2487 const clang::Decl::Kind lhs_decl_ctx_kind =
2488 lhs_decl_ctx->getDeclKind();
2489 const clang::Decl::Kind rhs_decl_ctx_kind =
2490 rhs_decl_ctx->getDeclKind();
2491 if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) {
2492 lhs_decl_ctx = lhs_decl_ctx->getParent();
2493 rhs_decl_ctx = rhs_decl_ctx->getParent();
2494
2495 if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr)
2496 break;
2497 } else
2498 return false;
2499 } else
2500 return false;
2501 }
2502
2503 // Now make sure the name of the decls match
2504 clang::NamedDecl *lhs_named_decl =
2505 llvm::dyn_cast<clang::NamedDecl>(lhs_decl);
2506 clang::NamedDecl *rhs_named_decl =
2507 llvm::dyn_cast<clang::NamedDecl>(rhs_decl);
2508 if (lhs_named_decl && rhs_named_decl) {
2509 clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName();
2510 clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName();
2511 if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2512 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2513 return false;
2514 } else
2515 return false;
2516 } else
2517 return false;
2518
2519 // We know that the decl context kinds all match, so now we need to
2520 // make sure the names match as well
2521 lhs_decl_ctx = lhs_decl->getDeclContext();
2522 rhs_decl_ctx = rhs_decl->getDeclContext();
2523 while (true) {
2524 switch (lhs_decl_ctx->getDeclKind()) {
2525 case clang::Decl::TranslationUnit:
2526 // We don't care about the translation unit names
2527 return true;
2528 default: {
2529 clang::NamedDecl *lhs_named_decl =
2530 llvm::dyn_cast<clang::NamedDecl>(lhs_decl_ctx);
2531 clang::NamedDecl *rhs_named_decl =
2532 llvm::dyn_cast<clang::NamedDecl>(rhs_decl_ctx);
2533 if (lhs_named_decl && rhs_named_decl) {
2534 clang::DeclarationName lhs_decl_name =
2535 lhs_named_decl->getDeclName();
2536 clang::DeclarationName rhs_decl_name =
2537 rhs_named_decl->getDeclName();
2538 if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2539 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2540 return false;
2541 } else
2542 return false;
2543 } else
2544 return false;
2545 } break;
2546 }
2547 lhs_decl_ctx = lhs_decl_ctx->getParent();
2548 rhs_decl_ctx = rhs_decl_ctx->getParent();
2549 }
2550 }
2551 }
2552 }
2553 return false;
2554}
2555bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast,
2556 clang::Decl *decl) {
2557 if (!decl)
2558 return false;
2559
2560 ExternalASTSource *ast_source = ast->getExternalSource();
2561
2562 if (!ast_source)
2563 return false;
2564
2565 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2566 if (tag_decl->isCompleteDefinition())
2567 return true;
2568
2569 if (!tag_decl->hasExternalLexicalStorage())
2570 return false;
2571
2572 ast_source->CompleteType(tag_decl);
2573
2574 return !tag_decl->getTypeForDecl()->isIncompleteType();
2575 } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2576 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2577 if (objc_interface_decl->getDefinition())
2578 return true;
2579
2580 if (!objc_interface_decl->hasExternalLexicalStorage())
2581 return false;
2582
2583 ast_source->CompleteType(objc_interface_decl);
2584
2585 return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2586 } else {
2587 return false;
2588 }
2589}
2590
2591void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl,
2592 user_id_t user_id) {
2593 ClangASTMetadata meta_data;
2594 meta_data.SetUserID(user_id);
2595 SetMetadata(decl, meta_data);
2596}
2597
2598void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type,
2599 user_id_t user_id) {
2600 ClangASTMetadata meta_data;
2601 meta_data.SetUserID(user_id);
2602 SetMetadata(type, meta_data);
2603}
2604
2605void TypeSystemClang::SetMetadata(const clang::Decl *object,
2606 ClangASTMetadata &metadata) {
2607 m_decl_metadata[object] = metadata;
2608}
2609
2610void TypeSystemClang::SetMetadata(const clang::Type *object,
2611 ClangASTMetadata &metadata) {
2612 m_type_metadata[object] = metadata;
2613}
2614
2615ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Decl *object) {
2616 auto It = m_decl_metadata.find(object);
2617 if (It != m_decl_metadata.end())
2618 return &It->second;
2619 return nullptr;
2620}
2621
2622ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Type *object) {
2623 auto It = m_type_metadata.find(object);
2624 if (It != m_type_metadata.end())
2625 return &It->second;
2626 return nullptr;
2627}
2628
2629void TypeSystemClang::SetCXXRecordDeclAccess(const clang::CXXRecordDecl *object,
2630 clang::AccessSpecifier access) {
2631 if (access == clang::AccessSpecifier::AS_none)
2632 m_cxx_record_decl_access.erase(object);
2633 else
2634 m_cxx_record_decl_access[object] = access;
2635}
2636
2637clang::AccessSpecifier
2638TypeSystemClang::GetCXXRecordDeclAccess(const clang::CXXRecordDecl *object) {
2639 auto It = m_cxx_record_decl_access.find(object);
2640 if (It != m_cxx_record_decl_access.end())
2641 return It->second;
2642 return clang::AccessSpecifier::AS_none;
2643}
2644
2645clang::DeclContext *
2646TypeSystemClang::GetDeclContextForType(const CompilerType &type) {
2647 return GetDeclContextForType(ClangUtil::GetQualType(type));
2648}
2649
2650/// Aggressively desugar the provided type, skipping past various kinds of
2651/// syntactic sugar and other constructs one typically wants to ignore.
2652/// The \p mask argument allows one to skip certain kinds of simplifications,
2653/// when one wishes to handle a certain kind of type directly.
2654static QualType
2655RemoveWrappingTypes(QualType type, ArrayRef<clang::Type::TypeClass> mask = {}) {
2656 while (true) {
2657 if (find(mask, type->getTypeClass()) != mask.end())
2658 return type;
2659 switch (type->getTypeClass()) {
2660 // This is not fully correct as _Atomic is more than sugar, but it is
2661 // sufficient for the purposes we care about.
2662 case clang::Type::Atomic:
2663 type = cast<clang::AtomicType>(type)->getValueType();
2664 break;
2665 case clang::Type::Auto:
2666 case clang::Type::Decltype:
2667 case clang::Type::Elaborated:
2668 case clang::Type::Paren:
2669 case clang::Type::SubstTemplateTypeParm:
2670 case clang::Type::TemplateSpecialization:
2671 case clang::Type::Typedef:
2672 case clang::Type::TypeOf:
2673 case clang::Type::TypeOfExpr:
2674 case clang::Type::Using:
2675 type = type->getLocallyUnqualifiedSingleStepDesugaredType();
2676 break;
2677 default:
2678 return type;
2679 }
2680 }
2681}
2682
2683clang::DeclContext *
2684TypeSystemClang::GetDeclContextForType(clang::QualType type) {
2685 if (type.isNull())
2686 return nullptr;
2687
2688 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
2689 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2690 switch (type_class) {
2691 case clang::Type::ObjCInterface:
2692 return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2693 ->getInterface();
2694 case clang::Type::ObjCObjectPointer:
2695 return GetDeclContextForType(
2696 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2697 ->getPointeeType());
2698 case clang::Type::Record:
2699 return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2700 case clang::Type::Enum:
2701 return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2702 default:
2703 break;
2704 }
2705 // No DeclContext in this type...
2706 return nullptr;
2707}
2708
2709static bool GetCompleteQualType(clang::ASTContext *ast,
2710 clang::QualType qual_type,
2711 bool allow_completion = true) {
2712 qual_type = RemoveWrappingTypes(qual_type);
2713 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2714 switch (type_class) {
2715 case clang::Type::ConstantArray:
2716 case clang::Type::IncompleteArray:
2717 case clang::Type::VariableArray: {
2718 const clang::ArrayType *array_type =
2719 llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2720
2721 if (array_type)
2722 return GetCompleteQualType(ast, array_type->getElementType(),
2723 allow_completion);
2724 } break;
2725 case clang::Type::Record: {
2726 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2727 if (cxx_record_decl) {
2728 if (cxx_record_decl->hasExternalLexicalStorage()) {
2729 const bool is_complete = cxx_record_decl->isCompleteDefinition();
2730 const bool fields_loaded =
2731 cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2732 if (is_complete && fields_loaded)
2733 return true;
2734
2735 if (!allow_completion)
2736 return false;
2737
2738 // Call the field_begin() accessor to for it to use the external source
2739 // to load the fields...
2740 clang::ExternalASTSource *external_ast_source =
2741 ast->getExternalSource();
2742 if (external_ast_source) {
2743 external_ast_source->CompleteType(cxx_record_decl);
2744 if (cxx_record_decl->isCompleteDefinition()) {
2745 cxx_record_decl->field_begin();
2746 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2747 }
2748 }
2749 }
2750 }
2751 const clang::TagType *tag_type =
2752 llvm::cast<clang::TagType>(qual_type.getTypePtr());
2753 return !tag_type->isIncompleteType();
2754 } break;
2755
2756 case clang::Type::Enum: {
2757 const clang::TagType *tag_type =
2758 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
2759 if (tag_type) {
2760 clang::TagDecl *tag_decl = tag_type->getDecl();
2761 if (tag_decl) {
2762 if (tag_decl->getDefinition())
2763 return true;
2764
2765 if (!allow_completion)
2766 return false;
2767
2768 if (tag_decl->hasExternalLexicalStorage()) {
2769 if (ast) {
2770 clang::ExternalASTSource *external_ast_source =
2771 ast->getExternalSource();
2772 if (external_ast_source) {
2773 external_ast_source->CompleteType(tag_decl);
2774 return !tag_type->isIncompleteType();
2775 }
2776 }
2777 }
2778 return false;
2779 }
2780 }
2781
2782 } break;
2783 case clang::Type::ObjCObject:
2784 case clang::Type::ObjCInterface: {
2785 const clang::ObjCObjectType *objc_class_type =
2786 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
2787 if (objc_class_type) {
2788 clang::ObjCInterfaceDecl *class_interface_decl =
2789 objc_class_type->getInterface();
2790 // We currently can't complete objective C types through the newly added
2791 // ASTContext because it only supports TagDecl objects right now...
2792 if (class_interface_decl) {
2793 if (class_interface_decl->getDefinition())
2794 return true;
2795
2796 if (!allow_completion)
2797 return false;
2798
2799 if (class_interface_decl->hasExternalLexicalStorage()) {
2800 if (ast) {
2801 clang::ExternalASTSource *external_ast_source =
2802 ast->getExternalSource();
2803 if (external_ast_source) {
2804 external_ast_source->CompleteType(class_interface_decl);
2805 return !objc_class_type->isIncompleteType();
2806 }
2807 }
2808 }
2809 return false;
2810 }
2811 }
2812 } break;
2813
2814 case clang::Type::Attributed:
2815 return GetCompleteQualType(
2816 ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2817 allow_completion);
2818
2819 default:
2820 break;
2821 }
2822
2823 return true;
2824}
2825
2826static clang::ObjCIvarDecl::AccessControl
2827ConvertAccessTypeToObjCIvarAccessControl(AccessType access) {
2828 switch (access) {
2829 case eAccessNone:
2830 return clang::ObjCIvarDecl::None;
2831 case eAccessPublic:
2832 return clang::ObjCIvarDecl::Public;
2833 case eAccessPrivate:
2834 return clang::ObjCIvarDecl::Private;
2835 case eAccessProtected:
2836 return clang::ObjCIvarDecl::Protected;
2837 case eAccessPackage:
2838 return clang::ObjCIvarDecl::Package;
2839 }
2840 return clang::ObjCIvarDecl::None;
2841}
2842
2843// Tests
2844
2845#ifndef NDEBUG
2846bool TypeSystemClang::Verify(lldb::opaque_compiler_type_t type) {
2847 return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr());
2848}
2849#endif
2850
2851bool TypeSystemClang::IsAggregateType(lldb::opaque_compiler_type_t type) {
2852 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2853
2854 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2855 switch (type_class) {
2856 case clang::Type::IncompleteArray:
2857 case clang::Type::VariableArray:
2858 case clang::Type::ConstantArray:
2859 case clang::Type::ExtVector:
2860 case clang::Type::Vector:
2861 case clang::Type::Record:
2862 case clang::Type::ObjCObject:
2863 case clang::Type::ObjCInterface:
2864 return true;
2865 default:
2866 break;
2867 }
2868 // The clang type does have a value
2869 return false;
2870}
2871
2872bool TypeSystemClang::IsAnonymousType(lldb::opaque_compiler_type_t type) {
2873 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2874
2875 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2876 switch (type_class) {
2877 case clang::Type::Record: {
2878 if (const clang::RecordType *record_type =
2879 llvm::dyn_cast_or_null<clang::RecordType>(
2880 qual_type.getTypePtrOrNull())) {
2881 if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2882 return record_decl->isAnonymousStructOrUnion();
2883 }
2884 }
2885 break;
2886 }
2887 default:
2888 break;
2889 }
2890 // The clang type does have a value
2891 return false;
2892}
2893
2894bool TypeSystemClang::IsArrayType(lldb::opaque_compiler_type_t type,
2895 CompilerType *element_type_ptr,
2896 uint64_t *size, bool *is_incomplete) {
2897 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2898
2899 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2900 switch (type_class) {
2901 default:
2902 break;
2903
2904 case clang::Type::ConstantArray:
2905 if (element_type_ptr)
2906 element_type_ptr->SetCompilerType(
2907 weak_from_this(), llvm::cast<clang::ConstantArrayType>(qual_type)
2908 ->getElementType()
2909 .getAsOpaquePtr());
2910 if (size)
2911 *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2912 ->getSize()
2913 .getLimitedValue(ULLONG_MAX(9223372036854775807LL*2ULL+1ULL));
2914 if (is_incomplete)
2915 *is_incomplete = false;
2916 return true;
2917
2918 case clang::Type::IncompleteArray:
2919 if (element_type_ptr)
2920 element_type_ptr->SetCompilerType(
2921 weak_from_this(), llvm::cast<clang::IncompleteArrayType>(qual_type)
2922 ->getElementType()
2923 .getAsOpaquePtr());
2924 if (size)
2925 *size = 0;
2926 if (is_incomplete)
2927 *is_incomplete = true;
2928 return true;
2929
2930 case clang::Type::VariableArray:
2931 if (element_type_ptr)
2932 element_type_ptr->SetCompilerType(
2933 weak_from_this(), llvm::cast<clang::VariableArrayType>(qual_type)
2934 ->getElementType()
2935 .getAsOpaquePtr());
2936 if (size)
2937 *size = 0;
2938 if (is_incomplete)
2939 *is_incomplete = false;
2940 return true;
2941
2942 case clang::Type::DependentSizedArray:
2943 if (element_type_ptr)
2944 element_type_ptr->SetCompilerType(
2945 weak_from_this(),
2946 llvm::cast<clang::DependentSizedArrayType>(qual_type)
2947 ->getElementType()
2948 .getAsOpaquePtr());
2949 if (size)
2950 *size = 0;
2951 if (is_incomplete)
2952 *is_incomplete = false;
2953 return true;
2954 }
2955 if (element_type_ptr)
2956 element_type_ptr->Clear();
2957 if (size)
2958 *size = 0;
2959 if (is_incomplete)
2960 *is_incomplete = false;
2961 return false;
2962}
2963
2964bool TypeSystemClang::IsVectorType(lldb::opaque_compiler_type_t type,
2965 CompilerType *element_type, uint64_t *size) {
2966 clang::QualType qual_type(GetCanonicalQualType(type));
2967
2968 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2969 switch (type_class) {
2970 case clang::Type::Vector: {
2971 const clang::VectorType *vector_type =
2972 qual_type->getAs<clang::VectorType>();
2973 if (vector_type) {
2974 if (size)
2975 *size = vector_type->getNumElements();
2976 if (element_type)
2977 *element_type = GetType(vector_type->getElementType());
2978 }
2979 return true;
2980 } break;
2981 case clang::Type::ExtVector: {
2982 const clang::ExtVectorType *ext_vector_type =
2983 qual_type->getAs<clang::ExtVectorType>();
2984 if (ext_vector_type) {
2985 if (size)
2986 *size = ext_vector_type->getNumElements();
2987 if (element_type)
2988 *element_type =
2989 CompilerType(weak_from_this(),
2990 ext_vector_type->getElementType().getAsOpaquePtr());
2991 }
2992 return true;
2993 }
2994 default:
2995 break;
2996 }
2997 return false;
2998}
2999
3000bool TypeSystemClang::IsRuntimeGeneratedType(
3001 lldb::opaque_compiler_type_t type) {
3002 clang::DeclContext *decl_ctx = GetDeclContextForType(GetQualType(type));
3003 if (!decl_ctx)
3004 return false;
3005
3006 if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
3007 return false;
3008
3009 clang::ObjCInterfaceDecl *result_iface_decl =
3010 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
3011
3012 ClangASTMetadata *ast_metadata = GetMetadata(result_iface_decl);
3013 if (!ast_metadata)
3014 return false;
3015 return (ast_metadata->GetISAPtr() != 0);
3016}
3017
3018bool TypeSystemClang::IsCharType(lldb::opaque_compiler_type_t type) {
3019 return GetQualType(type).getUnqualifiedType()->isCharType();
3020}
3021
3022bool TypeSystemClang::IsCompleteType(lldb::opaque_compiler_type_t type) {
3023 // If the type hasn't been lazily completed yet, complete it now so that we
3024 // can give the caller an accurate answer whether the type actually has a
3025 // definition. Without completing the type now we would just tell the user
3026 // the current (internal) completeness state of the type and most users don't
3027 // care (or even know) about this behavior.
3028 const bool allow_completion = true;
3029 return GetCompleteQualType(&getASTContext(), GetQualType(type),
3030 allow_completion);
3031}
3032
3033bool TypeSystemClang::IsConst(lldb::opaque_compiler_type_t type) {
3034 return GetQualType(type).isConstQualified();
3035}
3036
3037bool TypeSystemClang::IsCStringType(lldb::opaque_compiler_type_t type,
3038 uint32_t &length) {
3039 CompilerType pointee_or_element_clang_type;
3040 length = 0;
3041 Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
3042
3043 if (!pointee_or_element_clang_type.IsValid())
3044 return false;
3045
3046 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
3047 if (pointee_or_element_clang_type.IsCharType()) {
3048 if (type_flags.Test(eTypeIsArray)) {
3049 // We know the size of the array and it could be a C string since it is
3050 // an array of characters
3051 length = llvm::cast<clang::ConstantArrayType>(
3052 GetCanonicalQualType(type).getTypePtr())
3053 ->getSize()
3054 .getLimitedValue();
3055 }
3056 return true;
3057 }
3058 }
3059 return false;
3060}
3061
3062bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) {
3063 auto isFunctionType = [&](clang::QualType qual_type) {
3064 return qual_type->isFunctionType();
3065 };
3066
3067 return IsTypeImpl(type, isFunctionType);
3068}
3069
3070// Used to detect "Homogeneous Floating-point Aggregates"
3071uint32_t
3072TypeSystemClang::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
3073 CompilerType *base_type_ptr) {
3074 if (!type)
3075 return 0;
3076
3077 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
3078 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3079 switch (type_class) {
3080 case clang::Type::Record:
3081 if (GetCompleteType(type)) {
3082 const clang::CXXRecordDecl *cxx_record_decl =
3083 qual_type->getAsCXXRecordDecl();
3084 if (cxx_record_decl) {
3085 if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
3086 return 0;
3087 }
3088 const clang::RecordType *record_type =
3089 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3090 if (record_type) {
3091 const clang::RecordDecl *record_decl = record_type->getDecl();
3092 if (record_decl) {
3093 // We are looking for a structure that contains only floating point
3094 // types
3095 clang::RecordDecl::field_iterator field_pos,
3096 field_end = record_decl->field_end();
3097 uint32_t num_fields = 0;
3098 bool is_hva = false;
3099 bool is_hfa = false;
3100 clang::QualType base_qual_type;
3101 uint64_t base_bitwidth = 0;
3102 for (field_pos = record_decl->field_begin(); field_pos != field_end;
3103 ++field_pos) {
3104 clang::QualType field_qual_type = field_pos->getType();
3105 uint64_t field_bitwidth = getASTContext().getTypeSize(qual_type);
3106 if (field_qual_type->isFloatingType()) {
3107 if (field_qual_type->isComplexType())
3108 return 0;
3109 else {
3110 if (num_fields == 0)
3111 base_qual_type = field_qual_type;
3112 else {
3113 if (is_hva)
3114 return 0;
3115 is_hfa = true;
3116 if (field_qual_type.getTypePtr() !=
3117 base_qual_type.getTypePtr())
3118 return 0;
3119 }
3120 }
3121 } else if (field_qual_type->isVectorType() ||
3122 field_qual_type->isExtVectorType()) {
3123 if (num_fields == 0) {
3124 base_qual_type = field_qual_type;
3125 base_bitwidth = field_bitwidth;
3126 } else {
3127 if (is_hfa)
3128 return 0;
3129 is_hva = true;
3130 if (base_bitwidth != field_bitwidth)
3131 return 0;
3132 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3133 return 0;
3134 }
3135 } else
3136 return 0;
3137 ++num_fields;
3138 }
3139 if (base_type_ptr)
3140 *base_type_ptr =
3141 CompilerType(weak_from_this(), base_qual_type.getAsOpaquePtr());
3142 return num_fields;
3143 }
3144 }
3145 }
3146 break;
3147
3148 default:
3149 break;
3150 }
3151 return 0;
3152}
3153
3154size_t TypeSystemClang::GetNumberOfFunctionArguments(
3155 lldb::opaque_compiler_type_t type) {
3156 if (type) {
3157 clang::QualType qual_type(GetCanonicalQualType(type));
3158 const clang::FunctionProtoType *func =
3159 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3160 if (func)
3161 return func->getNumParams();
3162 }
3163 return 0;
3164}
3165
3166CompilerType
3167TypeSystemClang::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
3168 const size_t index) {
3169 if (type) {
3170 clang::QualType qual_type(GetQualType(type));
3171 const clang::FunctionProtoType *func =
3172 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3173 if (func) {
3174 if (index < func->getNumParams())
3175 return CompilerType(weak_from_this(), func->getParamType(index).getAsOpaquePtr());
3176 }
3177 }
3178 return CompilerType();
3179}
3180
3181bool TypeSystemClang::IsTypeImpl(
3182 lldb::opaque_compiler_type_t type,
3183 llvm::function_ref<bool(clang::QualType)> predicate) const {
3184 if (type) {
3185 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3186
3187 if (predicate(qual_type))
3188 return true;
3189
3190 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3191 switch (type_class) {
3192 default:
3193 break;
3194
3195 case clang::Type::LValueReference:
3196 case clang::Type::RValueReference: {
3197 const clang::ReferenceType *reference_type =
3198 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3199 if (reference_type)
3200 return IsTypeImpl(reference_type->getPointeeType().getAsOpaquePtr(), predicate);
3201 } break;
3202 }
3203 }
3204 return false;
3205}
3206
3207bool TypeSystemClang::IsMemberFunctionPointerType(
3208 lldb::opaque_compiler_type_t type) {
3209 auto isMemberFunctionPointerType = [](clang::QualType qual_type) {
3210 return qual_type->isMemberFunctionPointerType();
3211 };
3212
3213 return IsTypeImpl(type, isMemberFunctionPointerType);
3214}
3215
3216bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
3217 auto isFunctionPointerType = [](clang::QualType qual_type) {
3218 return qual_type->isFunctionPointerType();
3219 };
3220
3221 return IsTypeImpl(type, isFunctionPointerType);
3222}
3223
3224bool TypeSystemClang::IsBlockPointerType(
3225 lldb::opaque_compiler_type_t type,
3226 CompilerType *function_pointer_type_ptr) {
3227 auto isBlockPointerType = [&](clang::QualType qual_type) {
3228 if (qual_type->isBlockPointerType()) {
3229 if (function_pointer_type_ptr) {
3230 const clang::BlockPointerType *block_pointer_type =
3231 qual_type->castAs<clang::BlockPointerType>();
3232 QualType pointee_type = block_pointer_type->getPointeeType();
3233 QualType function_pointer_type = m_ast_up->getPointerType(pointee_type);
3234 *function_pointer_type_ptr = CompilerType(
3235 weak_from_this(), function_pointer_type.getAsOpaquePtr());
3236 }
3237 return true;
3238 }
3239
3240 return false;
3241 };
3242
3243 return IsTypeImpl(type, isBlockPointerType);
3244}
3245
3246bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type,
3247 bool &is_signed) {
3248 if (!type)
3249 return false;
3250
3251 clang::QualType qual_type(GetCanonicalQualType(type));
3252 const clang::BuiltinType *builtin_type =
3253 llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3254
3255 if (builtin_type) {
3256 if (builtin_type->isInteger()) {
3257 is_signed = builtin_type->isSignedInteger();
3258 return true;
3259 }
3260 }
3261
3262 return false;
3263}
3264
3265bool TypeSystemClang::IsEnumerationType(lldb::opaque_compiler_type_t type,
3266 bool &is_signed) {
3267 if (type) {
3268 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3269 GetCanonicalQualType(type)->getCanonicalTypeInternal());
3270
3271 if (enum_type) {
3272 IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3273 is_signed);
3274 return true;
3275 }
3276 }
3277
3278 return false;
3279}
3280
3281bool TypeSystemClang::IsScopedEnumerationType(
3282 lldb::opaque_compiler_type_t type) {
3283 if (type) {
3284 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3285 GetCanonicalQualType(type)->getCanonicalTypeInternal());
3286
3287 if (enum_type) {
3288 return enum_type->isScopedEnumeralType();
3289 }
3290 }
3291
3292 return false;
3293}
3294
3295bool TypeSystemClang::IsPointerType(lldb::opaque_compiler_type_t type,
3296 CompilerType *pointee_type) {
3297 if (type) {
3298 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3299 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3300 switch (type_class) {
3301 case clang::Type::Builtin:
3302 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3303 default:
3304 break;
3305 case clang::BuiltinType::ObjCId:
3306 case clang::BuiltinType::ObjCClass:
3307 return true;
3308 }
3309 return false;
3310 case clang::Type::ObjCObjectPointer:
3311 if (pointee_type)
3312 pointee_type->SetCompilerType(
3313 weak_from_this(),
3314 llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3315 ->getPointeeType()
3316 .getAsOpaquePtr());
3317 return true;
3318 case clang::Type::BlockPointer:
3319 if (pointee_type)
3320 pointee_type->SetCompilerType(
3321 weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type)
3322 ->getPointeeType()
3323 .getAsOpaquePtr());
3324 return true;
3325 case clang::Type::Pointer:
3326 if (pointee_type)
3327 pointee_type->SetCompilerType(weak_from_this(),
3328 llvm::cast<clang::PointerType>(qual_type)
3329 ->getPointeeType()
3330 .getAsOpaquePtr());
3331 return true;
3332 case clang::Type::MemberPointer:
3333 if (pointee_type)
3334 pointee_type->SetCompilerType(
3335 weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type)
3336 ->getPointeeType()
3337 .getAsOpaquePtr());
3338 return true;
3339 default:
3340 break;
3341 }
3342 }
3343 if (pointee_type)
3344 pointee_type->Clear();
3345 return false;
3346}
3347
3348bool TypeSystemClang::IsPointerOrReferenceType(
3349 lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3350 if (type) {
3351 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3352 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3353 switch (type_class) {
3354 case clang::Type::Builtin:
3355 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3356 default:
3357 break;
3358 case clang::BuiltinType::ObjCId:
3359 case clang::BuiltinType::ObjCClass:
3360 return true;
3361 }
3362 return false;
3363 case clang::Type::ObjCObjectPointer:
3364 if (pointee_type)
3365 pointee_type->SetCompilerType(
3366 weak_from_this(),
3367 llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3368 ->getPointeeType()
3369 .getAsOpaquePtr());
3370 return true;
3371 case clang::Type::BlockPointer:
3372 if (pointee_type)
3373 pointee_type->SetCompilerType(
3374 weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type)
3375 ->getPointeeType()
3376 .getAsOpaquePtr());
3377 return true;
3378 case clang::Type::Pointer:
3379 if (pointee_type)
3380 pointee_type->SetCompilerType(weak_from_this(),
3381 llvm::cast<clang::PointerType>(qual_type)
3382 ->getPointeeType()
3383 .getAsOpaquePtr());
3384 return true;
3385 case clang::Type::MemberPointer:
3386 if (pointee_type)
3387 pointee_type->SetCompilerType(
3388 weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type)
3389 ->getPointeeType()
3390 .getAsOpaquePtr());
3391 return true;
3392 case clang::Type::LValueReference:
3393 if (pointee_type)
3394 pointee_type->SetCompilerType(
3395 weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type)
3396 ->desugar()
3397 .getAsOpaquePtr());
3398 return true;
3399 case clang::Type::RValueReference:
3400 if (pointee_type)
3401 pointee_type->SetCompilerType(
3402 weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type)
3403 ->desugar()
3404 .getAsOpaquePtr());
3405 return true;
3406 default:
3407 break;
3408 }
3409 }
3410 if (pointee_type)
3411 pointee_type->Clear();
3412 return false;
3413}
3414
3415bool TypeSystemClang::IsReferenceType(lldb::opaque_compiler_type_t type,
3416 CompilerType *pointee_type,
3417 bool *is_rvalue) {
3418 if (type) {
3419 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3420 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3421
3422 switch (type_class) {
3423 case clang::Type::LValueReference:
3424 if (pointee_type)
3425 pointee_type->SetCompilerType(
3426 weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type)
3427 ->desugar()
3428 .getAsOpaquePtr());
3429 if (is_rvalue)
3430 *is_rvalue = false;
3431 return true;
3432 case clang::Type::RValueReference:
3433 if (pointee_type)
3434 pointee_type->SetCompilerType(
3435 weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type)
3436 ->desugar()
3437 .getAsOpaquePtr());
3438 if (is_rvalue)
3439 *is_rvalue = true;
3440 return true;
3441
3442 default:
3443 break;
3444 }
3445 }
3446 if (pointee_type)
3447 pointee_type->Clear();
3448 return false;
3449}
3450
3451bool TypeSystemClang::IsFloatingPointType(lldb::opaque_compiler_type_t type,
3452 uint32_t &count, bool &is_complex) {
3453 if (type) {
3454 clang::QualType qual_type(GetCanonicalQualType(type));
3455
3456 if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3457 qual_type->getCanonicalTypeInternal())) {
3458 clang::BuiltinType::Kind kind = BT->getKind();
3459 if (kind >= clang::BuiltinType::Float &&
3460 kind <= clang::BuiltinType::LongDouble) {
3461 count = 1;
3462 is_complex = false;
3463 return true;
3464 }
3465 } else if (const clang::ComplexType *CT =
3466 llvm::dyn_cast<clang::ComplexType>(
3467 qual_type->getCanonicalTypeInternal())) {
3468 if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3469 is_complex)) {
3470 count = 2;
3471 is_complex = true;
3472 return true;
3473 }
3474 } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3475 qual_type->getCanonicalTypeInternal())) {
3476 if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3477 is_complex)) {
3478 count = VT->getNumElements();
3479 is_complex = false;
3480 return true;
3481 }
3482 }
3483 }
3484 count = 0;
3485 is_complex = false;
3486 return false;
3487}
3488
3489bool TypeSystemClang::IsDefined(lldb::opaque_compiler_type_t type) {
3490 if (!type)
3491 return false;
3492
3493 clang::QualType qual_type(GetQualType(type));
3494 const clang::TagType *tag_type =
3495 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3496 if (tag_type) {
3497 clang::TagDecl *tag_decl = tag_type->getDecl();
3498 if (tag_decl)
3499 return tag_decl->isCompleteDefinition();
3500 return false;
3501 } else {
3502 const clang::ObjCObjectType *objc_class_type =
3503 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3504 if (objc_class_type) {
3505 clang::ObjCInterfaceDecl *class_interface_decl =
3506 objc_class_type->getInterface();
3507 if (class_interface_decl)
3508 return class_interface_decl->getDefinition() != nullptr;
3509 return false;
3510 }
3511 }
3512 return true;
3513}
3514
3515bool TypeSystemClang::IsObjCClassType(const CompilerType &type) {
3516 if (ClangUtil::IsClangType(type)) {
3517 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3518
3519 const clang::ObjCObjectPointerType *obj_pointer_type =
3520 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3521
3522 if (obj_pointer_type)
3523 return obj_pointer_type->isObjCClassType();
3524 }
3525 return false;
3526}
3527
3528bool TypeSystemClang::IsObjCObjectOrInterfaceType(const CompilerType &type) {
3529 if (ClangUtil::IsClangType(type))
3530 return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3531 return false;
3532}
3533
3534bool TypeSystemClang::IsClassType(lldb::opaque_compiler_type_t type) {
3535 if (!type)
3536 return false;
3537 clang::QualType qual_type(GetCanonicalQualType(type));
3538 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3539 return (type_class == clang::Type::Record);
3540}
3541
3542bool TypeSystemClang::IsEnumType(lldb::opaque_compiler_type_t type) {
3543 if (!type)
3544 return false;
3545 clang::QualType qual_type(GetCanonicalQualType(type));
3546 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3547 return (type_class == clang::Type::Enum);
3548}
3549
3550bool TypeSystemClang::IsPolymorphicClass(lldb::opaque_compiler_type_t type) {
3551 if (type) {
3552 clang::QualType qual_type(GetCanonicalQualType(type));
3553 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3554 switch (type_class) {
3555 case clang::Type::Record:
3556 if (GetCompleteType(type)) {
3557 const clang::RecordType *record_type =
3558 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3559 const clang::RecordDecl *record_decl = record_type->getDecl();
3560 if (record_decl) {
3561 const clang::CXXRecordDecl *cxx_record_decl =
3562 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3563 if (cxx_record_decl)
3564 return cxx_record_decl->isPolymorphic();
3565 }
3566 }
3567 break;
3568
3569 default:
3570 break;
3571 }
3572 }
3573 return false;
3574}
3575
3576bool TypeSystemClang::IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
3577 CompilerType *dynamic_pointee_type,
3578 bool check_cplusplus,
3579 bool check_objc) {
3580 clang::QualType pointee_qual_type;
3581 if (type) {
3582 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3583 bool success = false;
3584 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3585 switch (type_class) {
3586 case clang::Type::Builtin:
3587 if (check_objc &&
3588 llvm::cast<clang::BuiltinType>(qual_type)->getKind() ==
3589 clang::BuiltinType::ObjCId) {
3590 if (dynamic_pointee_type)
3591 dynamic_pointee_type->SetCompilerType(weak_from_this(), type);
3592 return true;
3593 }
3594 break;
3595
3596 case clang::Type::ObjCObjectPointer:
3597 if (check_objc) {
3598 if (const auto *objc_pointee_type =
3599 qual_type->getPointeeType().getTypePtrOrNull()) {
3600 if (const auto *objc_object_type =
3601 llvm::dyn_cast_or_null<clang::ObjCObjectType>(
3602 objc_pointee_type)) {
3603 if (objc_object_type->isObjCClass())
3604 return false;
3605 }
3606 }
3607 if (dynamic_pointee_type)
3608 dynamic_pointee_type->SetCompilerType(
3609 weak_from_this(),
3610 llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3611 ->getPointeeType()
3612 .getAsOpaquePtr());
3613 return true;
3614 }
3615 break;
3616
3617 case clang::Type::Pointer:
3618 pointee_qual_type =
3619 llvm::cast<clang::PointerType>(qual_type)->getPointeeType();
3620 success = true;
3621 break;
3622
3623 case clang::Type::LValueReference:
3624 case clang::Type::RValueReference:
3625 pointee_qual_type =
3626 llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType();
3627 success = true;
3628 break;
3629
3630 default:
3631 break;
3632 }
3633
3634 if (success) {
3635 // Check to make sure what we are pointing too is a possible dynamic C++
3636 // type We currently accept any "void *" (in case we have a class that
3637 // has been watered down to an opaque pointer) and virtual C++ classes.
3638 const clang::Type::TypeClass pointee_type_class =
3639 pointee_qual_type.getCanonicalType()->getTypeClass();
3640 switch (pointee_type_class) {
3641 case clang::Type::Builtin:
3642 switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) {
3643 case clang::BuiltinType::UnknownAny:
3644 case clang::BuiltinType::Void:
3645 if (dynamic_pointee_type)
3646 dynamic_pointee_type->SetCompilerType(
3647 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3648 return true;
3649 default:
3650 break;
3651 }
3652 break;
3653
3654 case clang::Type::Record:
3655 if (check_cplusplus) {
3656 clang::CXXRecordDecl *cxx_record_decl =
3657 pointee_qual_type->getAsCXXRecordDecl();
3658 if (cxx_record_decl) {
3659 bool is_complete = cxx_record_decl->isCompleteDefinition();
3660
3661 if (is_complete)
3662 success = cxx_record_decl->isDynamicClass();
3663 else {
3664 ClangASTMetadata *metadata = GetMetadata(cxx_record_decl);
3665 if (metadata)
3666 success = metadata->GetIsDynamicCXXType();
3667 else {
3668 is_complete = GetType(pointee_qual_type).GetCompleteType();
3669 if (is_complete)
3670 success = cxx_record_decl->isDynamicClass();
3671 else
3672 success = false;
3673 }
3674 }
3675
3676 if (success) {
3677 if (dynamic_pointee_type)
3678 dynamic_pointee_type->SetCompilerType(
3679 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3680 return true;
3681 }
3682 }
3683 }
3684 break;
3685
3686 case clang::Type::ObjCObject:
3687 case clang::Type::ObjCInterface:
3688 if (check_objc) {
3689 if (dynamic_pointee_type)
3690 dynamic_pointee_type->SetCompilerType(
3691 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3692 return true;
3693 }
3694 break;
3695
3696 default:
3697 break;
3698 }
3699 }
3700 }
3701 if (dynamic_pointee_type)
3702 dynamic_pointee_type->Clear();
3703 return false;
3704}
3705
3706bool TypeSystemClang::IsScalarType(lldb::opaque_compiler_type_t type) {
3707 if (!type)
3708 return false;
3709
3710 return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3711}
3712
3713bool TypeSystemClang::IsTypedefType(lldb::opaque_compiler_type_t type) {
3714 if (!type)
3715 return false;
3716 return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})
3717 ->getTypeClass() == clang::Type::Typedef;
3718}
3719
3720bool TypeSystemClang::IsVoidType(lldb::opaque_compiler_type_t type) {
3721 if (!type)
3722 return false;
3723 return GetCanonicalQualType(type)->isVoidType();
3724}
3725
3726bool TypeSystemClang::CanPassInRegisters(const CompilerType &type) {
3727 if (auto *record_decl =
3728 TypeSystemClang::GetAsRecordDecl(type)) {
3729 return record_decl->canPassInRegisters();
3730 }
3731 return false;
3732}
3733
3734bool TypeSystemClang::SupportsLanguage(lldb::LanguageType language) {
3735 return TypeSystemClangSupportsLanguage(language);
3736}
3737
3738std::optional<std::string>
3739TypeSystemClang::GetCXXClassName(const CompilerType &type) {
3740 if (!type)
3741 return std::nullopt;
3742
3743 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3744 if (qual_type.isNull())
3745 return std::nullopt;
3746
3747 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3748 if (!cxx_record_decl)
3749 return std::nullopt;
3750
3751 return std::string(cxx_record_decl->getIdentifier()->getNameStart());
3752}
3753
3754bool TypeSystemClang::IsCXXClassType(const CompilerType &type) {
3755 if (!type)
3756 return false;
3757
3758 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3759 return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr;
3760}
3761
3762bool TypeSystemClang::IsBeingDefined(lldb::opaque_compiler_type_t type) {
3763 if (!type)
3764 return false;
3765 clang::QualType qual_type(GetCanonicalQualType(type));
3766 const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type);
3767 if (tag_type)
3768 return tag_type->isBeingDefined();
3769 return false;
3770}
3771
3772bool TypeSystemClang::IsObjCObjectPointerType(const CompilerType &type,
3773 CompilerType *class_type_ptr) {
3774 if (!ClangUtil::IsClangType(type))
3775 return false;
3776
3777 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3778
3779 if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) {
3780 if (class_type_ptr) {
3781 if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) {
3782 const clang::ObjCObjectPointerType *obj_pointer_type =
3783 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3784 if (obj_pointer_type == nullptr)
3785 class_type_ptr->Clear();
3786 else
3787 class_type_ptr->SetCompilerType(
3788 type.GetTypeSystem(),
3789 clang::QualType(obj_pointer_type->getInterfaceType(), 0)
3790 .getAsOpaquePtr());
3791 }
3792 }
3793 return true;
3794 }
3795 if (class_type_ptr)
3796 class_type_ptr->Clear();
3797 return false;
3798}
3799
3800// Type Completion
3801
3802bool TypeSystemClang::GetCompleteType(lldb::opaque_compiler_type_t type) {
3803 if (!type)
3804 return false;
3805 const bool allow_completion = true;
3806 return GetCompleteQualType(&getASTContext(), GetQualType(type),
3807 allow_completion);
3808}
3809
3810ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type,
3811 bool base_only) {
3812 if (!type)
3813 return ConstString();
3814
3815 clang::QualType qual_type(GetQualType(type));
3816
3817 // Remove certain type sugar from the name. Sugar such as elaborated types
3818 // or template types which only serve to improve diagnostics shouldn't
3819 // act as their own types from the user's perspective (e.g., formatter
3820 // shouldn't format a variable differently depending on how the ser has
3821 // specified the type. '::Type' and 'Type' should behave the same).
3822 // Typedefs and atomic derived types are not removed as they are actually
3823 // useful for identifiying specific types.
3824 qual_type = RemoveWrappingTypes(qual_type,
3825 {clang::Type::Typedef, clang::Type::Atomic});
3826
3827 // For a typedef just return the qualified name.
3828 if (const auto *typedef_type = qual_type->getAs<clang::TypedefType>()) {
3829 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
3830 return ConstString(GetTypeNameForDecl(typedef_decl));
3831 }
3832
3833 // For consistency, this follows the same code path that clang uses to emit
3834 // debug info. This also handles when we don't want any scopes preceding the
3835 // name.
3836 if (auto *named_decl = qual_type->getAsTagDecl())
3837 return ConstString(GetTypeNameForDecl(named_decl, !base_only));
3838
3839 return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
3840}
3841
3842ConstString
3843TypeSystemClang::GetDisplayTypeName(lldb::opaque_compiler_type_t type) {
3844 if (!type)
3845 return ConstString();
3846
3847 clang::QualType qual_type(GetQualType(type));
3848 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
3849 printing_policy.SuppressTagKeyword = true;
3850 printing_policy.SuppressScope = false;
3851 printing_policy.SuppressUnwrittenScope = true;
3852 printing_policy.SuppressInlineNamespace = true;
3853 return ConstString(qual_type.getAsString(printing_policy));
3854}
3855
3856uint32_t
3857TypeSystemClang::GetTypeInfo(lldb::opaque_compiler_type_t type,
3858 CompilerType *pointee_or_element_clang_type) {
3859 if (!type)
3860 return 0;
3861
3862 if (pointee_or_element_clang_type)
3863 pointee_or_element_clang_type->Clear();
3864
3865 clang::QualType qual_type =
3866 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
3867
3868 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3869 switch (type_class) {
3870 case clang::Type::Attributed:
3871 return GetTypeInfo(qual_type->castAs<clang::AttributedType>()
3872 ->getModifiedType()
3873 .getAsOpaquePtr(),
3874 pointee_or_element_clang_type);
3875 case clang::Type::Builtin: {
3876 const clang::BuiltinType *builtin_type =
3877 llvm::cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3878
3879 uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
3880 switch (builtin_type->getKind()) {
3881 case clang::BuiltinType::ObjCId:
3882 case clang::BuiltinType::ObjCClass:
3883 if (pointee_or_element_clang_type)
3884 pointee_or_element_clang_type->SetCompilerType(
3885 weak_from_this(),
3886 getASTContext().ObjCBuiltinClassTy.getAsOpaquePtr());
3887 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3888 break;
3889
3890 case clang::BuiltinType::ObjCSel:
3891 if (pointee_or_element_clang_type)
3892 pointee_or_element_clang_type->SetCompilerType(
3893 weak_from_this(), getASTContext().CharTy.getAsOpaquePtr());
3894 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3895 break;
3896
3897 case clang::BuiltinType::Bool:
3898 case clang::BuiltinType::Char_U:
3899 case clang::BuiltinType::UChar:
3900 case clang::BuiltinType::WChar_U:
3901 case clang::BuiltinType::Char16:
3902 case clang::BuiltinType::Char32:
3903 case clang::BuiltinType::UShort:
3904 case clang::BuiltinType::UInt:
3905 case clang::BuiltinType::ULong:
3906 case clang::BuiltinType::ULongLong:
3907 case clang::BuiltinType::UInt128:
3908 case clang::BuiltinType::Char_S:
3909 case clang::BuiltinType::SChar:
3910 case clang::BuiltinType::WChar_S:
3911 case clang::BuiltinType::Short:
3912 case clang::BuiltinType::Int:
3913 case clang::BuiltinType::Long:
3914 case clang::BuiltinType::LongLong:
3915 case clang::BuiltinType::Int128:
3916 case clang::BuiltinType::Float:
3917 case clang::BuiltinType::Double:
3918 case clang::BuiltinType::LongDouble:
3919 builtin_type_flags |= eTypeIsScalar;
3920 if (builtin_type->isInteger()) {
3921 builtin_type_flags |= eTypeIsInteger;
3922 if (builtin_type->isSignedInteger())
3923 builtin_type_flags |= eTypeIsSigned;
3924 } else if (builtin_type->isFloatingPoint())
3925 builtin_type_flags |= eTypeIsFloat;
3926 break;
3927 default:
3928 break;
3929 }
3930 return builtin_type_flags;
3931 }
3932
3933 case clang::Type::BlockPointer:
3934 if (pointee_or_element_clang_type)
3935 pointee_or_element_clang_type->SetCompilerType(
3936 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
3937 return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
3938
3939 case clang::Type::Complex: {
3940 uint32_t complex_type_flags =
3941 eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
3942 const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>(
3943 qual_type->getCanonicalTypeInternal());
3944 if (complex_type) {
3945 clang::QualType complex_element_type(complex_type->getElementType());
3946 if (complex_element_type->isIntegerType())
3947 complex_type_flags |= eTypeIsFloat;
3948 else if (complex_element_type->isFloatingType())
3949 complex_type_flags |= eTypeIsInteger;
3950 }
3951 return complex_type_flags;
3952 } break;
3953
3954 case clang::Type::ConstantArray:
3955 case clang::Type::DependentSizedArray:
3956 case clang::Type::IncompleteArray:
3957 case clang::Type::VariableArray:
3958 if (pointee_or_element_clang_type)
3959 pointee_or_element_clang_type->SetCompilerType(
3960 weak_from_this(), llvm::cast<clang::ArrayType>(qual_type.getTypePtr())
3961 ->getElementType()
3962 .getAsOpaquePtr());
3963 return eTypeHasChildren | eTypeIsArray;
3964
3965 case clang::Type::DependentName:
3966 return 0;
3967 case clang::Type::DependentSizedExtVector:
3968 return eTypeHasChildren | eTypeIsVector;
3969 case clang::Type::DependentTemplateSpecialization:
3970 return eTypeIsTemplate;
3971
3972 case clang::Type::Enum:
3973 if (pointee_or_element_clang_type)
3974 pointee_or_element_clang_type->SetCompilerType(
3975 weak_from_this(), llvm::cast<clang::EnumType>(qual_type)
3976 ->getDecl()
3977 ->getIntegerType()
3978 .getAsOpaquePtr());
3979 return eTypeIsEnumeration | eTypeHasValue;
3980
3981 case clang::Type::FunctionProto:
3982 return eTypeIsFuncPrototype | eTypeHasValue;
3983 case clang::Type::FunctionNoProto:
3984 return eTypeIsFuncPrototype | eTypeHasValue;
3985 case clang::Type::InjectedClassName:
3986 return 0;
3987
3988 case clang::Type::LValueReference:
3989 case clang::Type::RValueReference:
3990 if (pointee_or_element_clang_type)
3991 pointee_or_element_clang_type->SetCompilerType(
3992 weak_from_this(),
3993 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr())
3994 ->getPointeeType()
3995 .getAsOpaquePtr());
3996 return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
3997
3998 case clang::Type::MemberPointer:
3999 return eTypeIsPointer | eTypeIsMember | eTypeHasValue;
4000
4001 case clang::Type::ObjCObjectPointer:
4002 if (pointee_or_element_clang_type)
4003 pointee_or_element_clang_type->SetCompilerType(
4004 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
4005 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer |
4006 eTypeHasValue;
4007
4008 case clang::Type::ObjCObject:
4009 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
4010 case clang::Type::ObjCInterface:
4011 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
4012
4013 case clang::Type::Pointer:
4014 if (pointee_or_element_clang_type)
4015 pointee_or_element_clang_type->SetCompilerType(
4016 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
4017 return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
4018
4019 case clang::Type::Record:
4020 if (qual_type->getAsCXXRecordDecl())
4021 return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
4022 else
4023 return eTypeHasChildren | eTypeIsStructUnion;
4024 break;
4025 case clang::Type::SubstTemplateTypeParm:
4026 return eTypeIsTemplate;
4027 case clang::Type::TemplateTypeParm:
4028 return eTypeIsTemplate;
4029 case clang::Type::TemplateSpecialization:
4030 return eTypeIsTemplate;
4031
4032 case clang::Type::Typedef:
4033 return eTypeIsTypedef | GetType(llvm::cast<clang::TypedefType>(qual_type)
4034 ->getDecl()
4035 ->getUnderlyingType())
4036 .GetTypeInfo(pointee_or_element_clang_type);
4037 case clang::Type::UnresolvedUsing:
4038 return 0;
4039
4040 case clang::Type::ExtVector:
4041 case clang::Type::Vector: {
4042 uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
4043 const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>(
4044 qual_type->getCanonicalTypeInternal());
4045 if (vector_type) {
4046 if (vector_type->isIntegerType())
4047 vector_type_flags |= eTypeIsFloat;
4048 else if (vector_type->isFloatingType())
4049 vector_type_flags |= eTypeIsInteger;
4050 }
4051 return vector_type_flags;
4052 }
4053 default:
4054 return 0;
4055 }
4056 return 0;
4057}
4058
4059lldb::LanguageType
4060TypeSystemClang::GetMinimumLanguage(lldb::opaque_compiler_type_t type) {
4061 if (!type)
4062 return lldb::eLanguageTypeC;
4063
4064 // If the type is a reference, then resolve it to what it refers to first:
4065 clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType());
4066 if (qual_type->isAnyPointerType()) {
4067 if (qual_type->isObjCObjectPointerType())
4068 return lldb::eLanguageTypeObjC;
4069 if (qual_type->getPointeeCXXRecordDecl())
4070 return lldb::eLanguageTypeC_plus_plus;
4071
4072 clang::QualType pointee_type(qual_type->getPointeeType());
4073 if (pointee_type->getPointeeCXXRecordDecl())
4074 return lldb::eLanguageTypeC_plus_plus;
4075 if (pointee_type->isObjCObjectOrInterfaceType())
4076 return lldb::eLanguageTypeObjC;
4077 if (pointee_type->isObjCClassType())
4078 return lldb::eLanguageTypeObjC;
4079 if (pointee_type.getTypePtr() ==
4080 getASTContext().ObjCBuiltinIdTy.getTypePtr())
4081 return lldb::eLanguageTypeObjC;
4082 } else {
4083 if (qual_type->isObjCObjectOrInterfaceType())
4084 return lldb::eLanguageTypeObjC;
4085 if (qual_type->getAsCXXRecordDecl())
4086 return lldb::eLanguageTypeC_plus_plus;
4087 switch (qual_type->getTypeClass()) {
4088 default:
4089 break;
4090 case clang::Type::Builtin:
4091 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4092 default:
4093 case clang::BuiltinType::Void:
4094 case clang::BuiltinType::Bool:
4095 case clang::BuiltinType::Char_U:
4096 case clang::BuiltinType::UChar:
4097 case clang::BuiltinType::WChar_U:
4098 case clang::BuiltinType::Char16:
4099 case clang::BuiltinType::Char32:
4100 case clang::BuiltinType::UShort:
4101 case clang::BuiltinType::UInt:
4102 case clang::BuiltinType::ULong:
4103 case clang::BuiltinType::ULongLong:
4104 case clang::BuiltinType::UInt128:
4105 case clang::BuiltinType::Char_S:
4106 case clang::BuiltinType::SChar:
4107 case clang::BuiltinType::WChar_S:
4108 case clang::BuiltinType::Short:
4109 case clang::BuiltinType::Int:
4110 case clang::BuiltinType::Long:
4111 case clang::BuiltinType::LongLong:
4112 case clang::BuiltinType::Int128:
4113 case clang::BuiltinType::Float:
4114 case clang::BuiltinType::Double:
4115 case clang::BuiltinType::LongDouble:
4116 break;
4117
4118 case clang::BuiltinType::NullPtr:
4119 return eLanguageTypeC_plus_plus;
4120
4121 case clang::BuiltinType::ObjCId:
4122 case clang::BuiltinType::ObjCClass:
4123 case clang::BuiltinType::ObjCSel:
4124 return eLanguageTypeObjC;
4125
4126 case clang::BuiltinType::Dependent:
4127 case clang::BuiltinType::Overload:
4128 case clang::BuiltinType::BoundMember:
4129 case clang::BuiltinType::UnknownAny:
4130 break;
4131 }
4132 break;
4133 case clang::Type::Typedef:
4134 return GetType(llvm::cast<clang::TypedefType>(qual_type)
4135 ->getDecl()
4136 ->getUnderlyingType())
4137 .GetMinimumLanguage();
4138 }
4139 }
4140 return lldb::eLanguageTypeC;
4141}
4142
4143lldb::TypeClass
4144TypeSystemClang::GetTypeClass(lldb::opaque_compiler_type_t type) {
4145 if (!type)
4146 return lldb::eTypeClassInvalid;
4147
4148 clang::QualType qual_type =
4149 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
4150
4151 switch (qual_type->getTypeClass()) {
4152 case clang::Type::Atomic:
4153 case clang::Type::Auto:
4154 case clang::Type::Decltype:
4155 case clang::Type::Elaborated:
4156 case clang::Type::Paren:
4157 case clang::Type::TypeOf:
4158 case clang::Type::TypeOfExpr:
4159 case clang::Type::Using:
4160 llvm_unreachable("Handled in RemoveWrappingTypes!")::llvm::llvm_unreachable_internal("Handled in RemoveWrappingTypes!"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
4160)
;
4161 case clang::Type::UnaryTransform:
4162 break;
4163 case clang::Type::FunctionNoProto:
4164 return lldb::eTypeClassFunction;
4165 case clang::Type::FunctionProto:
4166 return lldb::eTypeClassFunction;
4167 case clang::Type::IncompleteArray:
4168 return lldb::eTypeClassArray;
4169 case clang::Type::VariableArray:
4170 return lldb::eTypeClassArray;
4171 case clang::Type::ConstantArray:
4172 return lldb::eTypeClassArray;
4173 case clang::Type::DependentSizedArray:
4174 return lldb::eTypeClassArray;
4175 case clang::Type::DependentSizedExtVector:
4176 return lldb::eTypeClassVector;
4177 case clang::Type::DependentVector:
4178 return lldb::eTypeClassVector;
4179 case clang::Type::ExtVector:
4180 return lldb::eTypeClassVector;
4181 case clang::Type::Vector:
4182 return lldb::eTypeClassVector;
4183 case clang::Type::Builtin:
4184 // Ext-Int is just an integer type.
4185 case clang::Type::BitInt:
4186 case clang::Type::DependentBitInt:
4187 return lldb::eTypeClassBuiltin;
4188 case clang::Type::ObjCObjectPointer:
4189 return lldb::eTypeClassObjCObjectPointer;
4190 case clang::Type::BlockPointer:
4191 return lldb::eTypeClassBlockPointer;
4192 case clang::Type::Pointer:
4193 return lldb::eTypeClassPointer;
4194 case clang::Type::LValueReference:
4195 return lldb::eTypeClassReference;
4196 case clang::Type::RValueReference:
4197 return lldb::eTypeClassReference;
4198 case clang::Type::MemberPointer:
4199 return lldb::eTypeClassMemberPointer;
4200 case clang::Type::Complex:
4201 if (qual_type->isComplexType())
4202 return lldb::eTypeClassComplexFloat;
4203 else
4204 return lldb::eTypeClassComplexInteger;
4205 case clang::Type::ObjCObject:
4206 return lldb::eTypeClassObjCObject;
4207 case clang::Type::ObjCInterface:
4208 return lldb::eTypeClassObjCInterface;
4209 case clang::Type::Record: {
4210 const clang::RecordType *record_type =
4211 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4212 const clang::RecordDecl *record_decl = record_type->getDecl();
4213 if (record_decl->isUnion())
4214 return lldb::eTypeClassUnion;
4215 else if (record_decl->isStruct())
4216 return lldb::eTypeClassStruct;
4217 else
4218 return lldb::eTypeClassClass;
4219 } break;
4220 case clang::Type::Enum:
4221 return lldb::eTypeClassEnumeration;
4222 case clang::Type::Typedef:
4223 return lldb::eTypeClassTypedef;
4224 case clang::Type::UnresolvedUsing:
4225 break;
4226
4227 case clang::Type::Attributed:
4228 case clang::Type::BTFTagAttributed:
4229 break;
4230 case clang::Type::TemplateTypeParm:
4231 break;
4232 case clang::Type::SubstTemplateTypeParm:
4233 break;
4234 case clang::Type::SubstTemplateTypeParmPack:
4235 break;
4236 case clang::Type::InjectedClassName:
4237 break;
4238 case clang::Type::DependentName:
4239 break;
4240 case clang::Type::DependentTemplateSpecialization:
4241 break;
4242 case clang::Type::PackExpansion:
4243 break;
4244
4245 case clang::Type::TemplateSpecialization:
4246 break;
4247 case clang::Type::DeducedTemplateSpecialization:
4248 break;
4249 case clang::Type::Pipe:
4250 break;
4251
4252 // pointer type decayed from an array or function type.
4253 case clang::Type::Decayed:
4254 break;
4255 case clang::Type::Adjusted:
4256 break;
4257 case clang::Type::ObjCTypeParam:
4258 break;
4259
4260 case clang::Type::DependentAddressSpace:
4261 break;
4262 case clang::Type::MacroQualified:
4263 break;
4264
4265 // Matrix types that we're not sure how to display at the moment.
4266 case clang::Type::ConstantMatrix:
4267 case clang::Type::DependentSizedMatrix:
4268 break;
4269 }
4270 // We don't know hot to display this type...
4271 return lldb::eTypeClassOther;
4272}
4273
4274unsigned TypeSystemClang::GetTypeQualifiers(lldb::opaque_compiler_type_t type) {
4275 if (type)
4276 return GetQualType(type).getQualifiers().getCVRQualifiers();
4277 return 0;
4278}
4279
4280// Creating related types
4281
4282CompilerType
4283TypeSystemClang::GetArrayElementType(lldb::opaque_compiler_type_t type,
4284 ExecutionContextScope *exe_scope) {
4285 if (type) {
4286 clang::QualType qual_type(GetQualType(type));
4287
4288 const clang::Type *array_eletype =
4289 qual_type.getTypePtr()->getArrayElementTypeNoTypeQual();
4290
4291 if (!array_eletype)
4292 return CompilerType();
4293
4294 return GetType(clang::QualType(array_eletype, 0));
4295 }
4296 return CompilerType();
4297}
4298
4299CompilerType TypeSystemClang::GetArrayType(lldb::opaque_compiler_type_t type,
4300 uint64_t size) {
4301 if (type) {
4302 clang::QualType qual_type(GetCanonicalQualType(type));
4303 clang::ASTContext &ast_ctx = getASTContext();
4304 if (size != 0)
4305 return GetType(ast_ctx.getConstantArrayType(
4306 qual_type, llvm::APInt(64, size), nullptr,
4307 clang::ArrayType::ArraySizeModifier::Normal, 0));
4308 else
4309 return GetType(ast_ctx.getIncompleteArrayType(
4310 qual_type, clang::ArrayType::ArraySizeModifier::Normal, 0));
4311 }
4312
4313 return CompilerType();
4314}
4315
4316CompilerType
4317TypeSystemClang::GetCanonicalType(lldb::opaque_compiler_type_t type) {
4318 if (type)
4319 return GetType(GetCanonicalQualType(type));
4320 return CompilerType();
4321}
4322
4323static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast,
4324 clang::QualType qual_type) {
4325 if (qual_type->isPointerType())
4326 qual_type = ast->getPointerType(
4327 GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType()));
4328 else if (const ConstantArrayType *arr =
4329 ast->getAsConstantArrayType(qual_type)) {
4330 qual_type = ast->getConstantArrayType(
4331 GetFullyUnqualifiedType_Impl(ast, arr->getElementType()),
4332 arr->getSize(), arr->getSizeExpr(), arr->getSizeModifier(),
4333 arr->getIndexTypeQualifiers().getAsOpaqueValue());
4334 } else
4335 qual_type = qual_type.getUnqualifiedType();
4336 qual_type.removeLocalConst();
4337 qual_type.removeLocalRestrict();
4338 qual_type.removeLocalVolatile();
4339 return qual_type;
4340}
4341
4342CompilerType
4343TypeSystemClang::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) {
4344 if (type)
4345 return GetType(
4346 GetFullyUnqualifiedType_Impl(&getASTContext(), GetQualType(type)));
4347 return CompilerType();
4348}
4349
4350CompilerType
4351TypeSystemClang::GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) {
4352 if (type)
4353 return GetEnumerationIntegerType(GetType(GetCanonicalQualType(type)));
4354 return CompilerType();
4355}
4356
4357int TypeSystemClang::GetFunctionArgumentCount(
4358 lldb::opaque_compiler_type_t type) {
4359 if (type) {
4360 const clang::FunctionProtoType *func =
4361 llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type));
4362 if (func)
4363 return func->getNumParams();
4364 }
4365 return -1;
4366}
4367
4368CompilerType TypeSystemClang::GetFunctionArgumentTypeAtIndex(
4369 lldb::opaque_compiler_type_t type, size_t idx) {
4370 if (type) {
4371 const clang::FunctionProtoType *func =
4372 llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type));
4373 if (func) {
4374 const uint32_t num_args = func->getNumParams();
4375 if (idx < num_args)
4376 return GetType(func->getParamType(idx));
4377 }
4378 }
4379 return CompilerType();
4380}
4381
4382CompilerType
4383TypeSystemClang::GetFunctionReturnType(lldb::opaque_compiler_type_t type) {
4384 if (type) {
4385 clang::QualType qual_type(GetQualType(type));
4386 const clang::FunctionProtoType *func =
4387 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
4388 if (func)
4389 return GetType(func->getReturnType());
4390 }
4391 return CompilerType();
4392}
4393
4394size_t
4395TypeSystemClang::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) {
4396 size_t num_functions = 0;
4397 if (type) {
4398 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4399 switch (qual_type->getTypeClass()) {
4400 case clang::Type::Record:
4401 if (GetCompleteQualType(&getASTContext(), qual_type)) {
4402 const clang::RecordType *record_type =
4403 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4404 const clang::RecordDecl *record_decl = record_type->getDecl();
4405 assert(record_decl)(static_cast <bool> (record_decl) ? void (0) : __assert_fail
("record_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 4405, __extension__ __PRETTY_FUNCTION__))
;
4406 const clang::CXXRecordDecl *cxx_record_decl =
4407 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4408 if (cxx_record_decl)
4409 num_functions = std::distance(cxx_record_decl->method_begin(),
4410 cxx_record_decl->method_end());
4411 }
4412 break;
4413
4414 case clang::Type::ObjCObjectPointer: {
4415 const clang::ObjCObjectPointerType *objc_class_type =
4416 qual_type->castAs<clang::ObjCObjectPointerType>();
4417 const clang::ObjCInterfaceType *objc_interface_type =
4418 objc_class_type->getInterfaceType();
4419 if (objc_interface_type &&
4420 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4421 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4422 clang::ObjCInterfaceDecl *class_interface_decl =
4423 objc_interface_type->getDecl();
4424 if (class_interface_decl) {
4425 num_functions = std::distance(class_interface_decl->meth_begin(),
4426 class_interface_decl->meth_end());
4427 }
4428 }
4429 break;
4430 }
4431
4432 case clang::Type::ObjCObject:
4433 case clang::Type::ObjCInterface:
4434 if (GetCompleteType(type)) {
4435 const clang::ObjCObjectType *objc_class_type =
4436 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4437 if (objc_class_type) {
4438 clang::ObjCInterfaceDecl *class_interface_decl =
4439 objc_class_type->getInterface();
4440 if (class_interface_decl)
4441 num_functions = std::distance(class_interface_decl->meth_begin(),
4442 class_interface_decl->meth_end());
4443 }
4444 }
4445 break;
4446
4447 default:
4448 break;
4449 }
4450 }
4451 return num_functions;
4452}
4453
4454TypeMemberFunctionImpl
4455TypeSystemClang::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
4456 size_t idx) {
4457 std::string name;
4458 MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
4459 CompilerType clang_type;
4460 CompilerDecl clang_decl;
4461 if (type) {
4462 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4463 switch (qual_type->getTypeClass()) {
4464 case clang::Type::Record:
4465 if (GetCompleteQualType(&getASTContext(), qual_type)) {
4466 const clang::RecordType *record_type =
4467 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4468 const clang::RecordDecl *record_decl = record_type->getDecl();
4469 assert(record_decl)(static_cast <bool> (record_decl) ? void (0) : __assert_fail
("record_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 4469, __extension__ __PRETTY_FUNCTION__))
;
4470 const clang::CXXRecordDecl *cxx_record_decl =
4471 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4472 if (cxx_record_decl) {
4473 auto method_iter = cxx_record_decl->method_begin();
4474 auto method_end = cxx_record_decl->method_end();
4475 if (idx <
4476 static_cast<size_t>(std::distance(method_iter, method_end))) {
4477 std::advance(method_iter, idx);
4478 clang::CXXMethodDecl *cxx_method_decl =
4479 method_iter->getCanonicalDecl();
4480 if (cxx_method_decl) {
4481 name = cxx_method_decl->getDeclName().getAsString();
4482 if (cxx_method_decl->isStatic())
4483 kind = lldb::eMemberFunctionKindStaticMethod;
4484 else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4485 kind = lldb::eMemberFunctionKindConstructor;
4486 else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4487 kind = lldb::eMemberFunctionKindDestructor;
4488 else
4489 kind = lldb::eMemberFunctionKindInstanceMethod;
4490 clang_type = GetType(cxx_method_decl->getType());
4491 clang_decl = GetCompilerDecl(cxx_method_decl);
4492 }
4493 }
4494 }
4495 }
4496 break;
4497
4498 case clang::Type::ObjCObjectPointer: {
4499 const clang::ObjCObjectPointerType *objc_class_type =
4500 qual_type->castAs<clang::ObjCObjectPointerType>();
4501 const clang::ObjCInterfaceType *objc_interface_type =
4502 objc_class_type->getInterfaceType();
4503 if (objc_interface_type &&
4504 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4505 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4506 clang::ObjCInterfaceDecl *class_interface_decl =
4507 objc_interface_type->getDecl();
4508 if (class_interface_decl) {
4509 auto method_iter = class_interface_decl->meth_begin();
4510 auto method_end = class_interface_decl->meth_end();
4511 if (idx <
4512 static_cast<size_t>(std::distance(method_iter, method_end))) {
4513 std::advance(method_iter, idx);
4514 clang::ObjCMethodDecl *objc_method_decl =
4515 method_iter->getCanonicalDecl();
4516 if (objc_method_decl) {
4517 clang_decl = GetCompilerDecl(objc_method_decl);
4518 name = objc_method_decl->getSelector().getAsString();
4519 if (objc_method_decl->isClassMethod())
4520 kind = lldb::eMemberFunctionKindStaticMethod;
4521 else
4522 kind = lldb::eMemberFunctionKindInstanceMethod;
4523 }
4524 }
4525 }
4526 }
4527 break;
4528 }
4529
4530 case clang::Type::ObjCObject:
4531 case clang::Type::ObjCInterface:
4532 if (GetCompleteType(type)) {
4533 const clang::ObjCObjectType *objc_class_type =
4534 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4535 if (objc_class_type) {
4536 clang::ObjCInterfaceDecl *class_interface_decl =
4537 objc_class_type->getInterface();
4538 if (class_interface_decl) {
4539 auto method_iter = class_interface_decl->meth_begin();
4540 auto method_end = class_interface_decl->meth_end();
4541 if (idx <
4542 static_cast<size_t>(std::distance(method_iter, method_end))) {
4543 std::advance(method_iter, idx);
4544 clang::ObjCMethodDecl *objc_method_decl =
4545 method_iter->getCanonicalDecl();
4546 if (objc_method_decl) {
4547 clang_decl = GetCompilerDecl(objc_method_decl);
4548 name = objc_method_decl->getSelector().getAsString();
4549 if (objc_method_decl->isClassMethod())
4550 kind = lldb::eMemberFunctionKindStaticMethod;
4551 else
4552 kind = lldb::eMemberFunctionKindInstanceMethod;
4553 }
4554 }
4555 }
4556 }
4557 }
4558 break;
4559
4560 default:
4561 break;
4562 }
4563 }
4564
4565 if (kind == eMemberFunctionKindUnknown)
4566 return TypeMemberFunctionImpl();
4567 else
4568 return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind);
4569}
4570
4571CompilerType
4572TypeSystemClang::GetNonReferenceType(lldb::opaque_compiler_type_t type) {
4573 if (type)
4574 return GetType(GetQualType(type).getNonReferenceType());
4575 return CompilerType();
4576}
4577
4578CompilerType
4579TypeSystemClang::GetPointeeType(lldb::opaque_compiler_type_t type) {
4580 if (type) {
4581 clang::QualType qual_type(GetQualType(type));
4582 return GetType(qual_type.getTypePtr()->getPointeeType());
4583 }
4584 return CompilerType();
4585}
4586
4587CompilerType
4588TypeSystemClang::GetPointerType(lldb::opaque_compiler_type_t type) {
4589 if (type) {
4590 clang::QualType qual_type(GetQualType(type));
4591
4592 switch (qual_type.getDesugaredType(getASTContext())->getTypeClass()) {
4593 case clang::Type::ObjCObject:
4594 case clang::Type::ObjCInterface:
4595 return GetType(getASTContext().getObjCObjectPointerType(qual_type));
4596
4597 default:
4598 return GetType(getASTContext().getPointerType(qual_type));
4599 }
4600 }
4601 return CompilerType();
4602}
4603
4604CompilerType
4605TypeSystemClang::GetLValueReferenceType(lldb::opaque_compiler_type_t type) {
4606 if (type)
4607 return GetType(getASTContext().getLValueReferenceType(GetQualType(type)));
4608 else
4609 return CompilerType();
4610}
4611
4612CompilerType
4613TypeSystemClang::GetRValueReferenceType(lldb::opaque_compiler_type_t type) {
4614 if (type)
4615 return GetType(getASTContext().getRValueReferenceType(GetQualType(type)));
4616 else
4617 return CompilerType();
4618}
4619
4620CompilerType TypeSystemClang::GetAtomicType(lldb::opaque_compiler_type_t type) {
4621 if (!type)
4622 return CompilerType();
4623 return GetType(getASTContext().getAtomicType(GetQualType(type)));
4624}
4625
4626CompilerType
4627TypeSystemClang::AddConstModifier(lldb::opaque_compiler_type_t type) {
4628 if (type) {
4629 clang::QualType result(GetQualType(type));
4630 result.addConst();
4631 return GetType(result);
4632 }
4633 return CompilerType();
4634}
4635
4636CompilerType
4637TypeSystemClang::AddVolatileModifier(lldb::opaque_compiler_type_t type) {
4638 if (type) {
4639 clang::QualType result(GetQualType(type));
4640 result.addVolatile();
4641 return GetType(result);
4642 }
4643 return CompilerType();
4644}
4645
4646CompilerType
4647TypeSystemClang::AddRestrictModifier(lldb::opaque_compiler_type_t type) {
4648 if (type) {
4649 clang::QualType result(GetQualType(type));
4650 result.addRestrict();
4651 return GetType(result);
4652 }
4653 return CompilerType();
4654}
4655
4656CompilerType TypeSystemClang::CreateTypedef(
4657 lldb::opaque_compiler_type_t type, const char *typedef_name,
4658 const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) {
4659 if (type && typedef_name && typedef_name[0]) {
4660 clang::ASTContext &clang_ast = getASTContext();
4661 clang::QualType qual_type(GetQualType(type));
4662
4663 clang::DeclContext *decl_ctx =
4664 TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx);
4665 if (!decl_ctx)
4666 decl_ctx = getASTContext().getTranslationUnitDecl();
4667
4668 clang::TypedefDecl *decl =
4669 clang::TypedefDecl::CreateDeserialized(clang_ast, 0);
4670 decl->setDeclContext(decl_ctx);
4671 decl->setDeclName(&clang_ast.Idents.get(typedef_name));
4672 decl->setTypeSourceInfo(clang_ast.getTrivialTypeSourceInfo(qual_type));
4673 decl_ctx->addDecl(decl);
4674 SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule());
4675
4676 clang::TagDecl *tdecl = nullptr;
4677 if (!qual_type.isNull()) {
4678 if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>())
4679 tdecl = rt->getDecl();
4680 if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>())
4681 tdecl = et->getDecl();
4682 }
4683
4684 // Check whether this declaration is an anonymous struct, union, or enum,
4685 // hidden behind a typedef. If so, we try to check whether we have a
4686 // typedef tag to attach to the original record declaration
4687 if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl())
4688 tdecl->setTypedefNameForAnonDecl(decl);
4689
4690 decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4691
4692 // Get a uniqued clang::QualType for the typedef decl type
4693 return GetType(clang_ast.getTypedefType(decl));
4694 }
4695 return CompilerType();
4696}
4697
4698CompilerType
4699TypeSystemClang::GetTypedefedType(lldb::opaque_compiler_type_t type) {
4700 if (type) {
4701 const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(
4702 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}));
4703 if (typedef_type)
4704 return GetType(typedef_type->getDecl()->getUnderlyingType());
4705 }
4706 return CompilerType();
4707}
4708
4709// Create related types using the current type's AST
4710
4711CompilerType TypeSystemClang::GetBasicTypeFromAST(lldb::BasicType basic_type) {
4712 return TypeSystemClang::GetBasicType(basic_type);
4713}
4714// Exploring the type
4715
4716const llvm::fltSemantics &
4717TypeSystemClang::GetFloatTypeSemantics(size_t byte_size) {
4718 clang::ASTContext &ast = getASTContext();
4719 const size_t bit_size = byte_size * 8;
4720 if (bit_size == ast.getTypeSize(ast.FloatTy))
4721 return ast.getFloatTypeSemantics(ast.FloatTy);
4722 else if (bit_size == ast.getTypeSize(ast.DoubleTy))
4723 return ast.getFloatTypeSemantics(ast.DoubleTy);
4724 else if (bit_size == ast.getTypeSize(ast.LongDoubleTy) ||
4725 bit_size == llvm::APFloat::semanticsSizeInBits(
4726 ast.getFloatTypeSemantics(ast.LongDoubleTy)))
4727 return ast.getFloatTypeSemantics(ast.LongDoubleTy);
4728 else if (bit_size == ast.getTypeSize(ast.HalfTy))
4729 return ast.getFloatTypeSemantics(ast.HalfTy);
4730 return llvm::APFloatBase::Bogus();
4731}
4732
4733std::optional<uint64_t>
4734TypeSystemClang::GetBitSize(lldb::opaque_compiler_type_t type,
4735 ExecutionContextScope *exe_scope) {
4736 if (GetCompleteType(type)) {
4737 clang::QualType qual_type(GetCanonicalQualType(type));
4738 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4739 switch (type_class) {
4740 case clang::Type::Record:
4741 if (GetCompleteType(type))
4742 return getASTContext().getTypeSize(qual_type);
4743 else
4744 return std::nullopt;
4745 break;
4746
4747 case clang::Type::ObjCInterface:
4748 case clang::Type::ObjCObject: {
4749 ExecutionContext exe_ctx(exe_scope);
4750 Process *process = exe_ctx.GetProcessPtr();
4751 if (process) {
4752 ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
4753 if (objc_runtime) {
4754 uint64_t bit_size = 0;
4755 if (objc_runtime->GetTypeBitSize(GetType(qual_type), bit_size))
4756 return bit_size;
4757 }
4758 } else {
4759 static bool g_printed = false;
4760 if (!g_printed) {
4761 StreamString s;
4762 DumpTypeDescription(type, &s);
4763
4764 llvm::outs() << "warning: trying to determine the size of type ";
4765 llvm::outs() << s.GetString() << "\n";
4766 llvm::outs() << "without a valid ExecutionContext. this is not "
4767 "reliable. please file a bug against LLDB.\n";
4768 llvm::outs() << "backtrace:\n";
4769 llvm::sys::PrintStackTrace(llvm::outs());
4770 llvm::outs() << "\n";
4771 g_printed = true;
4772 }
4773 }
4774 }
4775 [[fallthrough]];
4776 default:
4777 const uint32_t bit_size = getASTContext().getTypeSize(qual_type);
4778 if (bit_size == 0) {
4779 if (qual_type->isIncompleteArrayType())
4780 return getASTContext().getTypeSize(
4781 qual_type->getArrayElementTypeNoTypeQual()
4782 ->getCanonicalTypeUnqualified());
4783 }
4784 if (qual_type->isObjCObjectOrInterfaceType())
4785 return bit_size +
4786 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy);
4787 // Function types actually have a size of 0, that's not an error.
4788 if (qual_type->isFunctionProtoType())
4789 return bit_size;
4790 if (bit_size)
4791 return bit_size;
4792 }
4793 }
4794 return std::nullopt;
4795}
4796
4797std::optional<size_t>
4798TypeSystemClang::GetTypeBitAlign(lldb::opaque_compiler_type_t type,
4799 ExecutionContextScope *exe_scope) {
4800 if (GetCompleteType(type))
4801 return getASTContext().getTypeAlign(GetQualType(type));
4802 return {};
4803}
4804
4805lldb::Encoding TypeSystemClang::GetEncoding(lldb::opaque_compiler_type_t type,
4806 uint64_t &count) {
4807 if (!type)
4808 return lldb::eEncodingInvalid;
4809
4810 count = 1;
4811 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4812
4813 switch (qual_type->getTypeClass()) {
4814 case clang::Type::Atomic:
4815 case clang::Type::Auto:
4816 case clang::Type::Decltype:
4817 case clang::Type::Elaborated:
4818 case clang::Type::Paren:
4819 case clang::Type::Typedef:
4820 case clang::Type::TypeOf:
4821 case clang::Type::TypeOfExpr:
4822 case clang::Type::Using:
4823 llvm_unreachable("Handled in RemoveWrappingTypes!")::llvm::llvm_unreachable_internal("Handled in RemoveWrappingTypes!"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
4823)
;
4824
4825 case clang::Type::UnaryTransform:
4826 break;
4827
4828 case clang::Type::FunctionNoProto:
4829 case clang::Type::FunctionProto:
4830 break;
4831
4832 case clang::Type::IncompleteArray:
4833 case clang::Type::VariableArray:
4834 break;
4835
4836 case clang::Type::ConstantArray:
4837 break;
4838
4839 case clang::Type::DependentVector:
4840 case clang::Type::ExtVector:
4841 case clang::Type::Vector:
4842 // TODO: Set this to more than one???
4843 break;
4844
4845 case clang::Type::BitInt:
4846 case clang::Type::DependentBitInt:
4847 return qual_type->isUnsignedIntegerType() ? lldb::eEncodingUint
4848 : lldb::eEncodingSint;
4849
4850 case clang::Type::Builtin:
4851 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4852 case clang::BuiltinType::Void:
4853 break;
4854
4855 case clang::BuiltinType::Char_S:
4856 case clang::BuiltinType::SChar:
4857 case clang::BuiltinType::WChar_S:
4858 case clang::BuiltinType::Short:
4859 case clang::BuiltinType::Int:
4860 case clang::BuiltinType::Long:
4861 case clang::BuiltinType::LongLong:
4862 case clang::BuiltinType::Int128:
4863 return lldb::eEncodingSint;
4864
4865 case clang::BuiltinType::Bool:
4866 case clang::BuiltinType::Char_U:
4867 case clang::BuiltinType::UChar:
4868 case clang::BuiltinType::WChar_U:
4869 case clang::BuiltinType::Char8:
4870 case clang::BuiltinType::Char16:
4871 case clang::BuiltinType::Char32:
4872 case clang::BuiltinType::UShort:
4873 case clang::BuiltinType::UInt:
4874 case clang::BuiltinType::ULong:
4875 case clang::BuiltinType::ULongLong:
4876 case clang::BuiltinType::UInt128:
4877 return lldb::eEncodingUint;
4878
4879 // Fixed point types. Note that they are currently ignored.
4880 case clang::BuiltinType::ShortAccum:
4881 case clang::BuiltinType::Accum:
4882 case clang::BuiltinType::LongAccum:
4883 case clang::BuiltinType::UShortAccum:
4884 case clang::BuiltinType::UAccum:
4885 case clang::BuiltinType::ULongAccum:
4886 case clang::BuiltinType::ShortFract:
4887 case clang::BuiltinType::Fract:
4888 case clang::BuiltinType::LongFract:
4889 case clang::BuiltinType::UShortFract:
4890 case clang::BuiltinType::UFract:
4891 case clang::BuiltinType::ULongFract:
4892 case clang::BuiltinType::SatShortAccum:
4893 case clang::BuiltinType::SatAccum:
4894 case clang::BuiltinType::SatLongAccum:
4895 case clang::BuiltinType::SatUShortAccum:
4896 case clang::BuiltinType::SatUAccum:
4897 case clang::BuiltinType::SatULongAccum:
4898 case clang::BuiltinType::SatShortFract:
4899 case clang::BuiltinType::SatFract:
4900 case clang::BuiltinType::SatLongFract:
4901 case clang::BuiltinType::SatUShortFract:
4902 case clang::BuiltinType::SatUFract:
4903 case clang::BuiltinType::SatULongFract:
4904 break;
4905
4906 case clang::BuiltinType::Half:
4907 case clang::BuiltinType::Float:
4908 case clang::BuiltinType::Float16:
4909 case clang::BuiltinType::Float128:
4910 case clang::BuiltinType::Double:
4911 case clang::BuiltinType::LongDouble:
4912 case clang::BuiltinType::BFloat16:
4913 case clang::BuiltinType::Ibm128:
4914 return lldb::eEncodingIEEE754;
4915
4916 case clang::BuiltinType::ObjCClass:
4917 case clang::BuiltinType::ObjCId:
4918 case clang::BuiltinType::ObjCSel:
4919 return lldb::eEncodingUint;
4920
4921 case clang::BuiltinType::NullPtr:
4922 return lldb::eEncodingUint;
4923
4924 case clang::BuiltinType::Kind::ARCUnbridgedCast:
4925 case clang::BuiltinType::Kind::BoundMember:
4926 case clang::BuiltinType::Kind::BuiltinFn:
4927 case clang::BuiltinType::Kind::Dependent:
4928 case clang::BuiltinType::Kind::OCLClkEvent:
4929 case clang::BuiltinType::Kind::OCLEvent:
4930 case clang::BuiltinType::Kind::OCLImage1dRO:
4931 case clang::BuiltinType::Kind::OCLImage1dWO:
4932 case clang::BuiltinType::Kind::OCLImage1dRW:
4933 case clang::BuiltinType::Kind::OCLImage1dArrayRO:
4934 case clang::BuiltinType::Kind::OCLImage1dArrayWO:
4935 case clang::BuiltinType::Kind::OCLImage1dArrayRW:
4936 case clang::BuiltinType::Kind::OCLImage1dBufferRO:
4937 case clang::BuiltinType::Kind::OCLImage1dBufferWO:
4938 case clang::BuiltinType::Kind::OCLImage1dBufferRW:
4939 case clang::BuiltinType::Kind::OCLImage2dRO:
4940 case clang::BuiltinType::Kind::OCLImage2dWO:
4941 case clang::BuiltinType::Kind::OCLImage2dRW:
4942 case clang::BuiltinType::Kind::OCLImage2dArrayRO:
4943 case clang::BuiltinType::Kind::OCLImage2dArrayWO:
4944 case clang::BuiltinType::Kind::OCLImage2dArrayRW:
4945 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO:
4946 case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO:
4947 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW:
4948 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO:
4949 case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO:
4950 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW:
4951 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO:
4952 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO:
4953 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW:
4954 case clang::BuiltinType::Kind::OCLImage2dDepthRO:
4955 case clang::BuiltinType::Kind::OCLImage2dDepthWO:
4956 case clang::BuiltinType::Kind::OCLImage2dDepthRW:
4957 case clang::BuiltinType::Kind::OCLImage2dMSAARO:
4958 case clang::BuiltinType::Kind::OCLImage2dMSAAWO:
4959 case clang::BuiltinType::Kind::OCLImage2dMSAARW:
4960 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO:
4961 case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO:
4962 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW:
4963 case clang::BuiltinType::Kind::OCLImage3dRO:
4964 case clang::BuiltinType::Kind::OCLImage3dWO:
4965 case clang::BuiltinType::Kind::OCLImage3dRW:
4966 case clang::BuiltinType::Kind::OCLQueue:
4967 case clang::BuiltinType::Kind::OCLReserveID:
4968 case clang::BuiltinType::Kind::OCLSampler:
4969 case clang::BuiltinType::Kind::OMPArraySection:
4970 case clang::BuiltinType::Kind::OMPArrayShaping:
4971 case clang::BuiltinType::Kind::OMPIterator:
4972 case clang::BuiltinType::Kind::Overload:
4973 case clang::BuiltinType::Kind::PseudoObject:
4974 case clang::BuiltinType::Kind::UnknownAny:
4975 break;
4976
4977 case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
4978 case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
4979 case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
4980 case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
4981 case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
4982 case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
4983 case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
4984 case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
4985 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleReferenceStreamout:
4986 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualReferenceStreamout:
4987 case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleReferenceStreamin:
4988 case clang::BuiltinType::OCLIntelSubgroupAVCImeDualReferenceStreamin:
4989 break;
4990
4991 // PowerPC -- Matrix Multiply Assist
4992 case clang::BuiltinType::VectorPair:
4993 case clang::BuiltinType::VectorQuad:
4994 break;
4995
4996 // ARM -- Scalable Vector Extension
4997 case clang::BuiltinType::SveBool:
4998 case clang::BuiltinType::SveBoolx2:
4999 case clang::BuiltinType::SveBoolx4:
5000 case clang::BuiltinType::SveCount:
5001 case clang::BuiltinType::SveInt8:
5002 case clang::BuiltinType::SveInt8x2:
5003 case clang::BuiltinType::SveInt8x3:
5004 case clang::BuiltinType::SveInt8x4:
5005 case clang::BuiltinType::SveInt16:
5006 case clang::BuiltinType::SveInt16x2:
5007 case clang::BuiltinType::SveInt16x3:
5008 case clang::BuiltinType::SveInt16x4:
5009 case clang::BuiltinType::SveInt32:
5010 case clang::BuiltinType::SveInt32x2:
5011 case clang::BuiltinType::SveInt32x3:
5012 case clang::BuiltinType::SveInt32x4:
5013 case clang::BuiltinType::SveInt64:
5014 case clang::BuiltinType::SveInt64x2:
5015 case clang::BuiltinType::SveInt64x3:
5016 case clang::BuiltinType::SveInt64x4:
5017 case clang::BuiltinType::SveUint8:
5018 case clang::BuiltinType::SveUint8x2:
5019 case clang::BuiltinType::SveUint8x3:
5020 case clang::BuiltinType::SveUint8x4:
5021 case clang::BuiltinType::SveUint16:
5022 case clang::BuiltinType::SveUint16x2:
5023 case clang::BuiltinType::SveUint16x3:
5024 case clang::BuiltinType::SveUint16x4:
5025 case clang::BuiltinType::SveUint32:
5026 case clang::BuiltinType::SveUint32x2:
5027 case clang::BuiltinType::SveUint32x3:
5028 case clang::BuiltinType::SveUint32x4:
5029 case clang::BuiltinType::SveUint64:
5030 case clang::BuiltinType::SveUint64x2:
5031 case clang::BuiltinType::SveUint64x3:
5032 case clang::BuiltinType::SveUint64x4:
5033 case clang::BuiltinType::SveFloat16:
5034 case clang::BuiltinType::SveBFloat16:
5035 case clang::BuiltinType::SveBFloat16x2:
5036 case clang::BuiltinType::SveBFloat16x3:
5037 case clang::BuiltinType::SveBFloat16x4:
5038 case clang::BuiltinType::SveFloat16x2:
5039 case clang::BuiltinType::SveFloat16x3:
5040 case clang::BuiltinType::SveFloat16x4:
5041 case clang::BuiltinType::SveFloat32:
5042 case clang::BuiltinType::SveFloat32x2:
5043 case clang::BuiltinType::SveFloat32x3:
5044 case clang::BuiltinType::SveFloat32x4:
5045 case clang::BuiltinType::SveFloat64:
5046 case clang::BuiltinType::SveFloat64x2:
5047 case clang::BuiltinType::SveFloat64x3:
5048 case clang::BuiltinType::SveFloat64x4:
5049 break;
5050
5051 // RISC-V V builtin types.
5052 case clang::BuiltinType::RvvInt8mf8:
5053 case clang::BuiltinType::RvvInt8mf4:
5054 case clang::BuiltinType::RvvInt8mf2:
5055 case clang::BuiltinType::RvvInt8m1:
5056 case clang::BuiltinType::RvvInt8m2:
5057 case clang::BuiltinType::RvvInt8m4:
5058 case clang::BuiltinType::RvvInt8m8:
5059 case clang::BuiltinType::RvvUint8mf8:
5060 case clang::BuiltinType::RvvUint8mf4:
5061 case clang::BuiltinType::RvvUint8mf2:
5062 case clang::BuiltinType::RvvUint8m1:
5063 case clang::BuiltinType::RvvUint8m2:
5064 case clang::BuiltinType::RvvUint8m4:
5065 case clang::BuiltinType::RvvUint8m8:
5066 case clang::BuiltinType::RvvInt16mf4:
5067 case clang::BuiltinType::RvvInt16mf2:
5068 case clang::BuiltinType::RvvInt16m1:
5069 case clang::BuiltinType::RvvInt16m2:
5070 case clang::BuiltinType::RvvInt16m4:
5071 case clang::BuiltinType::RvvInt16m8:
5072 case clang::BuiltinType::RvvUint16mf4:
5073 case clang::BuiltinType::RvvUint16mf2:
5074 case clang::BuiltinType::RvvUint16m1:
5075 case clang::BuiltinType::RvvUint16m2:
5076 case clang::BuiltinType::RvvUint16m4:
5077 case clang::BuiltinType::RvvUint16m8:
5078 case clang::BuiltinType::RvvInt32mf2:
5079 case clang::BuiltinType::RvvInt32m1:
5080 case clang::BuiltinType::RvvInt32m2:
5081 case clang::BuiltinType::RvvInt32m4:
5082 case clang::BuiltinType::RvvInt32m8:
5083 case clang::BuiltinType::RvvUint32mf2:
5084 case clang::BuiltinType::RvvUint32m1:
5085 case clang::BuiltinType::RvvUint32m2:
5086 case clang::BuiltinType::RvvUint32m4:
5087 case clang::BuiltinType::RvvUint32m8:
5088 case clang::BuiltinType::RvvInt64m1:
5089 case clang::BuiltinType::RvvInt64m2:
5090 case clang::BuiltinType::RvvInt64m4:
5091 case clang::BuiltinType::RvvInt64m8:
5092 case clang::BuiltinType::RvvUint64m1:
5093 case clang::BuiltinType::RvvUint64m2:
5094 case clang::BuiltinType::RvvUint64m4:
5095 case clang::BuiltinType::RvvUint64m8:
5096 case clang::BuiltinType::RvvFloat16mf4:
5097 case clang::BuiltinType::RvvFloat16mf2:
5098 case clang::BuiltinType::RvvFloat16m1:
5099 case clang::BuiltinType::RvvFloat16m2:
5100 case clang::BuiltinType::RvvFloat16m4:
5101 case clang::BuiltinType::RvvFloat16m8:
5102 case clang::BuiltinType::RvvFloat32mf2:
5103 case clang::BuiltinType::RvvFloat32m1:
5104 case clang::BuiltinType::RvvFloat32m2:
5105 case clang::BuiltinType::RvvFloat32m4:
5106 case clang::BuiltinType::RvvFloat32m8:
5107 case clang::BuiltinType::RvvFloat64m1:
5108 case clang::BuiltinType::RvvFloat64m2:
5109 case clang::BuiltinType::RvvFloat64m4:
5110 case clang::BuiltinType::RvvFloat64m8:
5111 case clang::BuiltinType::RvvBool1:
5112 case clang::BuiltinType::RvvBool2:
5113 case clang::BuiltinType::RvvBool4:
5114 case clang::BuiltinType::RvvBool8:
5115 case clang::BuiltinType::RvvBool16:
5116 case clang::BuiltinType::RvvBool32:
5117 case clang::BuiltinType::RvvBool64:
5118 break;
5119
5120 // WebAssembly builtin types.
5121 case clang::BuiltinType::WasmExternRef:
5122 break;
5123
5124 case clang::BuiltinType::IncompleteMatrixIdx:
5125 break;
5126 }
5127 break;
5128 // All pointer types are represented as unsigned integer encodings. We may
5129 // nee to add a eEncodingPointer if we ever need to know the difference
5130 case clang::Type::ObjCObjectPointer:
5131 case clang::Type::BlockPointer:
5132 case clang::Type::Pointer:
5133 case clang::Type::LValueReference:
5134 case clang::Type::RValueReference:
5135 case clang::Type::MemberPointer:
5136 return lldb::eEncodingUint;
5137 case clang::Type::Complex: {
5138 lldb::Encoding encoding = lldb::eEncodingIEEE754;
5139 if (qual_type->isComplexType())
5140 encoding = lldb::eEncodingIEEE754;
5141 else {
5142 const clang::ComplexType *complex_type =
5143 qual_type->getAsComplexIntegerType();
5144 if (complex_type)
5145 encoding = GetType(complex_type->getElementType()).GetEncoding(count);
5146 else
5147 encoding = lldb::eEncodingSint;
5148 }
5149 count = 2;
5150 return encoding;
5151 }
5152
5153 case clang::Type::ObjCInterface:
5154 break;
5155 case clang::Type::Record:
5156 break;
5157 case clang::Type::Enum:
5158 return qual_type->isUnsignedIntegerOrEnumerationType()
5159 ? lldb::eEncodingUint
5160 : lldb::eEncodingSint;
5161 case clang::Type::DependentSizedArray:
5162 case clang::Type::DependentSizedExtVector:
5163 case clang::Type::UnresolvedUsing:
5164 case clang::Type::Attributed:
5165 case clang::Type::BTFTagAttributed:
5166 case clang::Type::TemplateTypeParm:
5167 case clang::Type::SubstTemplateTypeParm:
5168 case clang::Type::SubstTemplateTypeParmPack:
5169 case clang::Type::InjectedClassName:
5170 case clang::Type::DependentName:
5171 case clang::Type::DependentTemplateSpecialization:
5172 case clang::Type::PackExpansion:
5173 case clang::Type::ObjCObject:
5174
5175 case clang::Type::TemplateSpecialization:
5176 case clang::Type::DeducedTemplateSpecialization:
5177 case clang::Type::Adjusted:
5178 case clang::Type::Pipe:
5179 break;
5180
5181 // pointer type decayed from an array or function type.
5182 case clang::Type::Decayed:
5183 break;
5184 case clang::Type::ObjCTypeParam:
5185 break;
5186
5187 case clang::Type::DependentAddressSpace:
5188 break;
5189 case clang::Type::MacroQualified:
5190 break;
5191
5192 case clang::Type::ConstantMatrix:
5193 case clang::Type::DependentSizedMatrix:
5194 break;
5195 }
5196 count = 0;
5197 return lldb::eEncodingInvalid;
5198}
5199
5200lldb::Format TypeSystemClang::GetFormat(lldb::opaque_compiler_type_t type) {
5201 if (!type)
5202 return lldb::eFormatDefault;
5203
5204 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5205
5206 switch (qual_type->getTypeClass()) {
5207 case clang::Type::Atomic:
5208 case clang::Type::Auto:
5209 case clang::Type::Decltype:
5210 case clang::Type::Elaborated:
5211 case clang::Type::Paren:
5212 case clang::Type::Typedef:
5213 case clang::Type::TypeOf:
5214 case clang::Type::TypeOfExpr:
5215 case clang::Type::Using:
5216 llvm_unreachable("Handled in RemoveWrappingTypes!")::llvm::llvm_unreachable_internal("Handled in RemoveWrappingTypes!"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
5216)
;
5217 case clang::Type::UnaryTransform:
5218 break;
5219
5220 case clang::Type::FunctionNoProto:
5221 case clang::Type::FunctionProto:
5222 break;
5223
5224 case clang::Type::IncompleteArray:
5225 case clang::Type::VariableArray:
5226 break;
5227
5228 case clang::Type::ConstantArray:
5229 return lldb::eFormatVoid; // no value
5230
5231 case clang::Type::DependentVector:
5232 case clang::Type::ExtVector:
5233 case clang::Type::Vector:
5234 break;
5235
5236 case clang::Type::BitInt:
5237 case clang::Type::DependentBitInt:
5238 return qual_type->isUnsignedIntegerType() ? lldb::eFormatUnsigned
5239 : lldb::eFormatDecimal;
5240
5241 case clang::Type::Builtin:
5242 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5243 case clang::BuiltinType::UnknownAny:
5244 case clang::BuiltinType::Void:
5245 case clang::BuiltinType::BoundMember:
5246 break;
5247
5248 case clang::BuiltinType::Bool:
5249 return lldb::eFormatBoolean;
5250 case clang::BuiltinType::Char_S:
5251 case clang::BuiltinType::SChar:
5252 case clang::BuiltinType::WChar_S:
5253 case clang::BuiltinType::Char_U:
5254 case clang::BuiltinType::UChar:
5255 case clang::BuiltinType::WChar_U:
5256 return lldb::eFormatChar;
5257 case clang::BuiltinType::Char8:
5258 return lldb::eFormatUnicode8;
5259 case clang::BuiltinType::Char16:
5260 return lldb::eFormatUnicode16;
5261 case clang::BuiltinType::Char32:
5262 return lldb::eFormatUnicode32;
5263 case clang::BuiltinType::UShort:
5264 return lldb::eFormatUnsigned;
5265 case clang::BuiltinType::Short:
5266 return lldb::eFormatDecimal;
5267 case clang::BuiltinType::UInt:
5268 return lldb::eFormatUnsigned;
5269 case clang::BuiltinType::Int:
5270 return lldb::eFormatDecimal;
5271 case clang::BuiltinType::ULong:
5272 return lldb::eFormatUnsigned;
5273 case clang::BuiltinType::Long:
5274 return lldb::eFormatDecimal;
5275 case clang::BuiltinType::ULongLong:
5276 return lldb::eFormatUnsigned;
5277 case clang::BuiltinType::LongLong:
5278 return lldb::eFormatDecimal;
5279 case clang::BuiltinType::UInt128:
5280 return lldb::eFormatUnsigned;
5281 case clang::BuiltinType::Int128:
5282 return lldb::eFormatDecimal;
5283 case clang::BuiltinType::Half:
5284 case clang::BuiltinType::Float:
5285 case clang::BuiltinType::Double:
5286 case clang::BuiltinType::LongDouble:
5287 return lldb::eFormatFloat;
5288 default:
5289 return lldb::eFormatHex;
5290 }
5291 break;
5292 case clang::Type::ObjCObjectPointer:
5293 return lldb::eFormatHex;
5294 case clang::Type::BlockPointer:
5295 return lldb::eFormatHex;
5296 case clang::Type::Pointer:
5297 return lldb::eFormatHex;
5298 case clang::Type::LValueReference:
5299 case clang::Type::RValueReference:
5300 return lldb::eFormatHex;
5301 case clang::Type::MemberPointer:
5302 return lldb::eFormatHex;
5303 case clang::Type::Complex: {
5304 if (qual_type->isComplexType())
5305 return lldb::eFormatComplex;
5306 else
5307 return lldb::eFormatComplexInteger;
5308 }
5309 case clang::Type::ObjCInterface:
5310 break;
5311 case clang::Type::Record:
5312 break;
5313 case clang::Type::Enum:
5314 return lldb::eFormatEnum;
5315 case clang::Type::DependentSizedArray:
5316 case clang::Type::DependentSizedExtVector:
5317 case clang::Type::UnresolvedUsing:
5318 case clang::Type::Attributed:
5319 case clang::Type::BTFTagAttributed:
5320 case clang::Type::TemplateTypeParm:
5321 case clang::Type::SubstTemplateTypeParm:
5322 case clang::Type::SubstTemplateTypeParmPack:
5323 case clang::Type::InjectedClassName:
5324 case clang::Type::DependentName:
5325 case clang::Type::DependentTemplateSpecialization:
5326 case clang::Type::PackExpansion:
5327 case clang::Type::ObjCObject:
5328
5329 case clang::Type::TemplateSpecialization:
5330 case clang::Type::DeducedTemplateSpecialization:
5331 case clang::Type::Adjusted:
5332 case clang::Type::Pipe:
5333 break;
5334
5335 // pointer type decayed from an array or function type.
5336 case clang::Type::Decayed:
5337 break;
5338 case clang::Type::ObjCTypeParam:
5339 break;
5340
5341 case clang::Type::DependentAddressSpace:
5342 break;
5343 case clang::Type::MacroQualified:
5344 break;
5345
5346 // Matrix types we're not sure how to display yet.
5347 case clang::Type::ConstantMatrix:
5348 case clang::Type::DependentSizedMatrix:
5349 break;
5350 }
5351 // We don't know hot to display this type...
5352 return lldb::eFormatBytes;
5353}
5354
5355static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl,
5356 bool check_superclass) {
5357 while (class_interface_decl) {
5358 if (class_interface_decl->ivar_size() > 0)
5359 return true;
5360
5361 if (check_superclass)
5362 class_interface_decl = class_interface_decl->getSuperClass();
5363 else
5364 break;
5365 }
5366 return false;
5367}
5368
5369static std::optional<SymbolFile::ArrayInfo>
5370GetDynamicArrayInfo(TypeSystemClang &ast, SymbolFile *sym_file,
5371 clang::QualType qual_type,
5372 const ExecutionContext *exe_ctx) {
5373 if (qual_type->isIncompleteArrayType())
5374 if (auto *metadata = ast.GetMetadata(qual_type.getTypePtr()))
5375 return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(),
5376 exe_ctx);
5377 return std::nullopt;
5378}
5379
5380uint32_t TypeSystemClang::GetNumChildren(lldb::opaque_compiler_type_t type,
5381 bool omit_empty_base_classes,
5382 const ExecutionContext *exe_ctx) {
5383 if (!type)
5384 return 0;
5385
5386 uint32_t num_children = 0;
5387 clang::QualType qual_type(RemoveWrappingTypes(GetQualType(type)));
5388 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5389 switch (type_class) {
5390 case clang::Type::Builtin:
5391 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5392 case clang::BuiltinType::ObjCId: // child is Class
5393 case clang::BuiltinType::ObjCClass: // child is Class
5394 num_children = 1;
5395 break;
5396
5397 default:
5398 break;
5399 }
5400 break;
5401
5402 case clang::Type::Complex:
5403 return 0;
5404 case clang::Type::Record:
5405 if (GetCompleteQualType(&getASTContext(), qual_type)) {
5406 const clang::RecordType *record_type =
5407 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5408 const clang::RecordDecl *record_decl = record_type->getDecl();
5409 assert(record_decl)(static_cast <bool> (record_decl) ? void (0) : __assert_fail
("record_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 5409, __extension__ __PRETTY_FUNCTION__))
;
5410 const clang::CXXRecordDecl *cxx_record_decl =
5411 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
5412 if (cxx_record_decl) {
5413 if (omit_empty_base_classes) {
5414 // Check each base classes to see if it or any of its base classes
5415 // contain any fields. This can help limit the noise in variable
5416 // views by not having to show base classes that contain no members.
5417 clang::CXXRecordDecl::base_class_const_iterator base_class,
5418 base_class_end;
5419 for (base_class = cxx_record_decl->bases_begin(),
5420 base_class_end = cxx_record_decl->bases_end();
5421 base_class != base_class_end; ++base_class) {
5422 const clang::CXXRecordDecl *base_class_decl =
5423 llvm::cast<clang::CXXRecordDecl>(
5424 base_class->getType()
5425 ->getAs<clang::RecordType>()
5426 ->getDecl());
5427
5428 // Skip empty base classes
5429 if (!TypeSystemClang::RecordHasFields(base_class_decl))
5430 continue;
5431
5432 num_children++;
5433 }
5434 } else {
5435 // Include all base classes
5436 num_children += cxx_record_decl->getNumBases();
5437 }
5438 }
5439 clang::RecordDecl::field_iterator field, field_end;
5440 for (field = record_decl->field_begin(),
5441 field_end = record_decl->field_end();
5442 field != field_end; ++field)
5443 ++num_children;
5444 }
5445 break;
5446
5447 case clang::Type::ObjCObject:
5448 case clang::Type::ObjCInterface:
5449 if (GetCompleteQualType(&getASTContext(), qual_type)) {
5450 const clang::ObjCObjectType *objc_class_type =
5451 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5452 assert(objc_class_type)(static_cast <bool> (objc_class_type) ? void (0) : __assert_fail
("objc_class_type", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 5452, __extension__ __PRETTY_FUNCTION__))
;
5453 if (objc_class_type) {
5454 clang::ObjCInterfaceDecl *class_interface_decl =
5455 objc_class_type->getInterface();
5456
5457 if (class_interface_decl) {
5458
5459 clang::ObjCInterfaceDecl *superclass_interface_decl =
5460 class_interface_decl->getSuperClass();
5461 if (superclass_interface_decl) {
5462 if (omit_empty_base_classes) {
5463 if (ObjCDeclHasIVars(superclass_interface_decl, true))
5464 ++num_children;
5465 } else
5466 ++num_children;
5467 }
5468
5469 num_children += class_interface_decl->ivar_size();
5470 }
5471 }
5472 }
5473 break;
5474
5475 case clang::Type::LValueReference:
5476 case clang::Type::RValueReference:
5477 case clang::Type::ObjCObjectPointer: {
5478 CompilerType pointee_clang_type(GetPointeeType(type));
5479
5480 uint32_t num_pointee_children = 0;
5481 if (pointee_clang_type.IsAggregateType())
5482 num_pointee_children =
5483 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5484 // If this type points to a simple type, then it has 1 child
5485 if (num_pointee_children == 0)
5486 num_children = 1;
5487 else
5488 num_children = num_pointee_children;
5489 } break;
5490
5491 case clang::Type::Vector:
5492 case clang::Type::ExtVector:
5493 num_children =
5494 llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements();
5495 break;
5496
5497 case clang::Type::ConstantArray:
5498 num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr())
5499 ->getSize()
5500 .getLimitedValue();
5501 break;
5502 case clang::Type::IncompleteArray:
5503 if (auto array_info =
5504 GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx))
5505 // Only 1-dimensional arrays are supported.
5506 num_children = array_info->element_orders.size()
5507 ? array_info->element_orders.back()
5508 : 0;
5509 break;
5510
5511 case clang::Type::Pointer: {
5512 const clang::PointerType *pointer_type =
5513 llvm::cast<clang::PointerType>(qual_type.getTypePtr());
5514 clang::QualType pointee_type(pointer_type->getPointeeType());
5515 CompilerType pointee_clang_type(GetType(pointee_type));
5516 uint32_t num_pointee_children = 0;
5517 if (pointee_clang_type.IsAggregateType())
5518 num_pointee_children =
5519 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5520 if (num_pointee_children == 0) {
5521 // We have a pointer to a pointee type that claims it has no children. We
5522 // will want to look at
5523 num_children = GetNumPointeeChildren(pointee_type);
5524 } else
5525 num_children = num_pointee_children;
5526 } break;
5527
5528 default:
5529 break;
5530 }
5531 return num_children;
5532}
5533
5534CompilerType TypeSystemClang::GetBuiltinTypeByName(ConstString name) {
5535 return GetBasicType(GetBasicTypeEnumeration(name));
5536}
5537
5538lldb::BasicType
5539TypeSystemClang::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) {
5540 if (type) {
5541 clang::QualType qual_type(GetQualType(type));
5542 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5543 if (type_class == clang::Type::Builtin) {
5544 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5545 case clang::BuiltinType::Void:
5546 return eBasicTypeVoid;
5547 case clang::BuiltinType::Bool:
5548 return eBasicTypeBool;
5549 case clang::BuiltinType::Char_S:
5550 return eBasicTypeSignedChar;
5551 case clang::BuiltinType::Char_U:
5552 return eBasicTypeUnsignedChar;
5553 case clang::BuiltinType::Char8:
5554 return eBasicTypeChar8;
5555 case clang::BuiltinType::Char16:
5556 return eBasicTypeChar16;
5557 case clang::BuiltinType::Char32:
5558 return eBasicTypeChar32;
5559 case clang::BuiltinType::UChar:
5560 return eBasicTypeUnsignedChar;
5561 case clang::BuiltinType::SChar:
5562 return eBasicTypeSignedChar;
5563 case clang::BuiltinType::WChar_S:
5564 return eBasicTypeSignedWChar;
5565 case clang::BuiltinType::WChar_U:
5566 return eBasicTypeUnsignedWChar;
5567 case clang::BuiltinType::Short:
5568 return eBasicTypeShort;
5569 case clang::BuiltinType::UShort:
5570 return eBasicTypeUnsignedShort;
5571 case clang::BuiltinType::Int:
5572 return eBasicTypeInt;
5573 case clang::BuiltinType::UInt:
5574 return eBasicTypeUnsignedInt;
5575 case clang::BuiltinType::Long:
5576 return eBasicTypeLong;
5577 case clang::BuiltinType::ULong:
5578 return eBasicTypeUnsignedLong;
5579 case clang::BuiltinType::LongLong:
5580 return eBasicTypeLongLong;
5581 case clang::BuiltinType::ULongLong:
5582 return eBasicTypeUnsignedLongLong;
5583 case clang::BuiltinType::Int128:
5584 return eBasicTypeInt128;
5585 case clang::BuiltinType::UInt128:
5586 return eBasicTypeUnsignedInt128;
5587
5588 case clang::BuiltinType::Half:
5589 return eBasicTypeHalf;
5590 case clang::BuiltinType::Float:
5591 return eBasicTypeFloat;
5592 case clang::BuiltinType::Double:
5593 return eBasicTypeDouble;
5594 case clang::BuiltinType::LongDouble:
5595 return eBasicTypeLongDouble;
5596
5597 case clang::BuiltinType::NullPtr:
5598 return eBasicTypeNullPtr;
5599 case clang::BuiltinType::ObjCId:
5600 return eBasicTypeObjCID;
5601 case clang::BuiltinType::ObjCClass:
5602 return eBasicTypeObjCClass;
5603 case clang::BuiltinType::ObjCSel:
5604 return eBasicTypeObjCSel;
5605 default:
5606 return eBasicTypeOther;
5607 }
5608 }
5609 }
5610 return eBasicTypeInvalid;
5611}
5612
5613void TypeSystemClang::ForEachEnumerator(
5614 lldb::opaque_compiler_type_t type,
5615 std::function<bool(const CompilerType &integer_type,
5616 ConstString name,
5617 const llvm::APSInt &value)> const &callback) {
5618 const clang::EnumType *enum_type =
5619 llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type));
5620 if (enum_type) {
5621 const clang::EnumDecl *enum_decl = enum_type->getDecl();
5622 if (enum_decl) {
5623 CompilerType integer_type = GetType(enum_decl->getIntegerType());
5624
5625 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
5626 for (enum_pos = enum_decl->enumerator_begin(),
5627 enum_end_pos = enum_decl->enumerator_end();
5628 enum_pos != enum_end_pos; ++enum_pos) {
5629 ConstString name(enum_pos->getNameAsString().c_str());
5630 if (!callback(integer_type, name, enum_pos->getInitVal()))
5631 break;
5632 }
5633 }
5634 }
5635}
5636
5637#pragma mark Aggregate Types
5638
5639uint32_t TypeSystemClang::GetNumFields(lldb::opaque_compiler_type_t type) {
5640 if (!type)
5641 return 0;
5642
5643 uint32_t count = 0;
5644 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5645 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5646 switch (type_class) {
5647 case clang::Type::Record:
5648 if (GetCompleteType(type)) {
5649 const clang::RecordType *record_type =
5650 llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
5651 if (record_type) {
5652 clang::RecordDecl *record_decl = record_type->getDecl();
5653 if (record_decl) {
5654 uint32_t field_idx = 0;
5655 clang::RecordDecl::field_iterator field, field_end;
5656 for (field = record_decl->field_begin(),
5657 field_end = record_decl->field_end();
5658 field != field_end; ++field)
5659 ++field_idx;
5660 count = field_idx;
5661 }
5662 }
5663 }
5664 break;
5665
5666 case clang::Type::ObjCObjectPointer: {
5667 const clang::ObjCObjectPointerType *objc_class_type =
5668 qual_type->castAs<clang::ObjCObjectPointerType>();
5669 const clang::ObjCInterfaceType *objc_interface_type =
5670 objc_class_type->getInterfaceType();
5671 if (objc_interface_type &&
5672 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5673 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5674 clang::ObjCInterfaceDecl *class_interface_decl =
5675 objc_interface_type->getDecl();
5676 if (class_interface_decl) {
5677 count = class_interface_decl->ivar_size();
5678 }
5679 }
5680 break;
5681 }
5682
5683 case clang::Type::ObjCObject:
5684 case clang::Type::ObjCInterface:
5685 if (GetCompleteType(type)) {
5686 const clang::ObjCObjectType *objc_class_type =
5687 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5688 if (objc_class_type) {
5689 clang::ObjCInterfaceDecl *class_interface_decl =
5690 objc_class_type->getInterface();
5691
5692 if (class_interface_decl)
5693 count = class_interface_decl->ivar_size();
5694 }
5695 }
5696 break;
5697
5698 default:
5699 break;
5700 }
5701 return count;
5702}
5703
5704static lldb::opaque_compiler_type_t
5705GetObjCFieldAtIndex(clang::ASTContext *ast,
5706 clang::ObjCInterfaceDecl *class_interface_decl, size_t idx,
5707 std::string &name, uint64_t *bit_offset_ptr,
5708 uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) {
5709 if (class_interface_decl) {
5710 if (idx < (class_interface_decl->ivar_size())) {
5711 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
5712 ivar_end = class_interface_decl->ivar_end();
5713 uint32_t ivar_idx = 0;
5714
5715 for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end;
5716 ++ivar_pos, ++ivar_idx) {
5717 if (ivar_idx == idx) {
5718 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
5719
5720 clang::QualType ivar_qual_type(ivar_decl->getType());
5721
5722 name.assign(ivar_decl->getNameAsString());
5723
5724 if (bit_offset_ptr) {
5725 const clang::ASTRecordLayout &interface_layout =
5726 ast->getASTObjCInterfaceLayout(class_interface_decl);
5727 *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx);
5728 }
5729
5730 const bool is_bitfield = ivar_pos->isBitField();
5731
5732 if (bitfield_bit_size_ptr) {
5733 *bitfield_bit_size_ptr = 0;
5734
5735 if (is_bitfield && ast) {
5736 clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
5737 clang::Expr::EvalResult result;
5738 if (bitfield_bit_size_expr &&
5739 bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) {
5740 llvm::APSInt bitfield_apsint = result.Val.getInt();
5741 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5742 }
5743 }
5744 }
5745 if (is_bitfield_ptr)
5746 *is_bitfield_ptr = is_bitfield;
5747
5748 return ivar_qual_type.getAsOpaquePtr();
5749 }
5750 }
5751 }
5752 }
5753 return nullptr;
5754}
5755
5756CompilerType TypeSystemClang::GetFieldAtIndex(lldb::opaque_compiler_type_t type,
5757 size_t idx, std::string &name,
5758 uint64_t *bit_offset_ptr,
5759 uint32_t *bitfield_bit_size_ptr,
5760 bool *is_bitfield_ptr) {
5761 if (!type)
5762 return CompilerType();
5763
5764 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5765 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5766 switch (type_class) {
5767 case clang::Type::Record:
5768 if (GetCompleteType(type)) {
5769 const clang::RecordType *record_type =
5770 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5771 const clang::RecordDecl *record_decl = record_type->getDecl();
5772 uint32_t field_idx = 0;
5773 clang::RecordDecl::field_iterator field, field_end;
5774 for (field = record_decl->field_begin(),
5775 field_end = record_decl->field_end();
5776 field != field_end; ++field, ++field_idx) {
5777 if (idx == field_idx) {
5778 // Print the member type if requested
5779 // Print the member name and equal sign
5780 name.assign(field->getNameAsString());
5781
5782 // Figure out the type byte size (field_type_info.first) and
5783 // alignment (field_type_info.second) from the AST context.
5784 if (bit_offset_ptr) {
5785 const clang::ASTRecordLayout &record_layout =
5786 getASTContext().getASTRecordLayout(record_decl);
5787 *bit_offset_ptr = record_layout.getFieldOffset(field_idx);
5788 }
5789
5790 const bool is_bitfield = field->isBitField();
5791
5792 if (bitfield_bit_size_ptr) {
5793 *bitfield_bit_size_ptr = 0;
5794
5795 if (is_bitfield) {
5796 clang::Expr *bitfield_bit_size_expr = field->getBitWidth();
5797 clang::Expr::EvalResult result;
5798 if (bitfield_bit_size_expr &&
5799 bitfield_bit_size_expr->EvaluateAsInt(result,
5800 getASTContext())) {
5801 llvm::APSInt bitfield_apsint = result.Val.getInt();
5802 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5803 }
5804 }
5805 }
5806 if (is_bitfield_ptr)
5807 *is_bitfield_ptr = is_bitfield;
5808
5809 return GetType(field->getType());
5810 }
5811 }
5812 }
5813 break;
5814
5815 case clang::Type::ObjCObjectPointer: {
5816 const clang::ObjCObjectPointerType *objc_class_type =
5817 qual_type->castAs<clang::ObjCObjectPointerType>();
5818 const clang::ObjCInterfaceType *objc_interface_type =
5819 objc_class_type->getInterfaceType();
5820 if (objc_interface_type &&
5821 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5822 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5823 clang::ObjCInterfaceDecl *class_interface_decl =
5824 objc_interface_type->getDecl();
5825 if (class_interface_decl) {
5826 return CompilerType(
5827 weak_from_this(),
5828 GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx,
5829 name, bit_offset_ptr, bitfield_bit_size_ptr,
5830 is_bitfield_ptr));
5831 }
5832 }
5833 break;
5834 }
5835
5836 case clang::Type::ObjCObject:
5837 case clang::Type::ObjCInterface:
5838 if (GetCompleteType(type)) {
5839 const clang::ObjCObjectType *objc_class_type =
5840 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5841 assert(objc_class_type)(static_cast <bool> (objc_class_type) ? void (0) : __assert_fail
("objc_class_type", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 5841, __extension__ __PRETTY_FUNCTION__))
;
5842 if (objc_class_type) {
5843 clang::ObjCInterfaceDecl *class_interface_decl =
5844 objc_class_type->getInterface();
5845 return CompilerType(
5846 weak_from_this(),
5847 GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx,
5848 name, bit_offset_ptr, bitfield_bit_size_ptr,
5849 is_bitfield_ptr));
5850 }
5851 }
5852 break;
5853
5854 default:
5855 break;
5856 }
5857 return CompilerType();
5858}
5859
5860uint32_t
5861TypeSystemClang::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) {
5862 uint32_t count = 0;
5863 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5864 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5865 switch (type_class) {
5866 case clang::Type::Record:
5867 if (GetCompleteType(type)) {
5868 const clang::CXXRecordDecl *cxx_record_decl =
5869 qual_type->getAsCXXRecordDecl();
5870 if (cxx_record_decl)
5871 count = cxx_record_decl->getNumBases();
5872 }
5873 break;
5874
5875 case clang::Type::ObjCObjectPointer:
5876 count = GetPointeeType(type).GetNumDirectBaseClasses();
5877 break;
5878
5879 case clang::Type::ObjCObject:
5880 if (GetCompleteType(type)) {
5881 const clang::ObjCObjectType *objc_class_type =
5882 qual_type->getAsObjCQualifiedInterfaceType();
5883 if (objc_class_type) {
5884 clang::ObjCInterfaceDecl *class_interface_decl =
5885 objc_class_type->getInterface();
5886
5887 if (class_interface_decl && class_interface_decl->getSuperClass())
5888 count = 1;
5889 }
5890 }
5891 break;
5892 case clang::Type::ObjCInterface:
5893 if (GetCompleteType(type)) {
5894 const clang::ObjCInterfaceType *objc_interface_type =
5895 qual_type->getAs<clang::ObjCInterfaceType>();
5896 if (objc_interface_type) {
5897 clang::ObjCInterfaceDecl *class_interface_decl =
5898 objc_interface_type->getInterface();
5899
5900 if (class_interface_decl && class_interface_decl->getSuperClass())
5901 count = 1;
5902 }
5903 }
5904 break;
5905
5906 default:
5907 break;
5908 }
5909 return count;
5910}
5911
5912uint32_t
5913TypeSystemClang::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) {
5914 uint32_t count = 0;
5915 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5916 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5917 switch (type_class) {
5918 case clang::Type::Record:
5919 if (GetCompleteType(type)) {
5920 const clang::CXXRecordDecl *cxx_record_decl =
5921 qual_type->getAsCXXRecordDecl();
5922 if (cxx_record_decl)
5923 count = cxx_record_decl->getNumVBases();
5924 }
5925 break;
5926
5927 default:
5928 break;
5929 }
5930 return count;
5931}
5932
5933CompilerType TypeSystemClang::GetDirectBaseClassAtIndex(
5934 lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5935 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5936 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5937 switch (type_class) {
5938 case clang::Type::Record:
5939 if (GetCompleteType(type)) {
5940 const clang::CXXRecordDecl *cxx_record_decl =
5941 qual_type->getAsCXXRecordDecl();
5942 if (cxx_record_decl) {
5943 uint32_t curr_idx = 0;
5944 clang::CXXRecordDecl::base_class_const_iterator base_class,
5945 base_class_end;
5946 for (base_class = cxx_record_decl->bases_begin(),
5947 base_class_end = cxx_record_decl->bases_end();
5948 base_class != base_class_end; ++base_class, ++curr_idx) {
5949 if (curr_idx == idx) {
5950 if (bit_offset_ptr) {
5951 const clang::ASTRecordLayout &record_layout =
5952 getASTContext().getASTRecordLayout(cxx_record_decl);
5953 const clang::CXXRecordDecl *base_class_decl =
5954 llvm::cast<clang::CXXRecordDecl>(
5955 base_class->getType()
5956 ->castAs<clang::RecordType>()
5957 ->getDecl());
5958 if (base_class->isVirtual())
5959 *bit_offset_ptr =
5960 record_layout.getVBaseClassOffset(base_class_decl)
5961 .getQuantity() *
5962 8;
5963 else
5964 *bit_offset_ptr =
5965 record_layout.getBaseClassOffset(base_class_decl)
5966 .getQuantity() *
5967 8;
5968 }
5969 return GetType(base_class->getType());
5970 }
5971 }
5972 }
5973 }
5974 break;
5975
5976 case clang::Type::ObjCObjectPointer:
5977 return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr);
5978
5979 case clang::Type::ObjCObject:
5980 if (idx == 0 && GetCompleteType(type)) {
5981 const clang::ObjCObjectType *objc_class_type =
5982 qual_type->getAsObjCQualifiedInterfaceType();
5983 if (objc_class_type) {
5984 clang::ObjCInterfaceDecl *class_interface_decl =
5985 objc_class_type->getInterface();
5986
5987 if (class_interface_decl) {
5988 clang::ObjCInterfaceDecl *superclass_interface_decl =
5989 class_interface_decl->getSuperClass();
5990 if (superclass_interface_decl) {
5991 if (bit_offset_ptr)
5992 *bit_offset_ptr = 0;
5993 return GetType(getASTContext().getObjCInterfaceType(
5994 superclass_interface_decl));
5995 }
5996 }
5997 }
5998 }
5999 break;
6000 case clang::Type::ObjCInterface:
6001 if (idx == 0 && GetCompleteType(type)) {
6002 const clang::ObjCObjectType *objc_interface_type =
6003 qual_type->getAs<clang::ObjCInterfaceType>();
6004 if (objc_interface_type) {
6005 clang::ObjCInterfaceDecl *class_interface_decl =
6006 objc_interface_type->getInterface();
6007
6008 if (class_interface_decl) {
6009 clang::ObjCInterfaceDecl *superclass_interface_decl =
6010 class_interface_decl->getSuperClass();
6011 if (superclass_interface_decl) {
6012 if (bit_offset_ptr)
6013 *bit_offset_ptr = 0;
6014 return GetType(getASTContext().getObjCInterfaceType(
6015 superclass_interface_decl));
6016 }
6017 }
6018 }
6019 }
6020 break;
6021
6022 default:
6023 break;
6024 }
6025 return CompilerType();
6026}
6027
6028CompilerType TypeSystemClang::GetVirtualBaseClassAtIndex(
6029 lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
6030 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6031 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6032 switch (type_class) {
6033 case clang::Type::Record:
6034 if (GetCompleteType(type)) {
6035 const clang::CXXRecordDecl *cxx_record_decl =
6036 qual_type->getAsCXXRecordDecl();
6037 if (cxx_record_decl) {
6038 uint32_t curr_idx = 0;
6039 clang::CXXRecordDecl::base_class_const_iterator base_class,
6040 base_class_end;
6041 for (base_class = cxx_record_decl->vbases_begin(),
6042 base_class_end = cxx_record_decl->vbases_end();
6043 base_class != base_class_end; ++base_class, ++curr_idx) {
6044 if (curr_idx == idx) {
6045 if (bit_offset_ptr) {
6046 const clang::ASTRecordLayout &record_layout =
6047 getASTContext().getASTRecordLayout(cxx_record_decl);
6048 const clang::CXXRecordDecl *base_class_decl =
6049 llvm::cast<clang::CXXRecordDecl>(
6050 base_class->getType()
6051 ->castAs<clang::RecordType>()
6052 ->getDecl());
6053 *bit_offset_ptr =
6054 record_layout.getVBaseClassOffset(base_class_decl)
6055 .getQuantity() *
6056 8;
6057 }
6058 return GetType(base_class->getType());
6059 }
6060 }
6061 }
6062 }
6063 break;
6064
6065 default:
6066 break;
6067 }
6068 return CompilerType();
6069}
6070
6071// If a pointer to a pointee type (the clang_type arg) says that it has no
6072// children, then we either need to trust it, or override it and return a
6073// different result. For example, an "int *" has one child that is an integer,
6074// but a function pointer doesn't have any children. Likewise if a Record type
6075// claims it has no children, then there really is nothing to show.
6076uint32_t TypeSystemClang::GetNumPointeeChildren(clang::QualType type) {
6077 if (type.isNull())
6078 return 0;
6079
6080 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
6081 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6082 switch (type_class) {
6083 case clang::Type::Builtin:
6084 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
6085 case clang::BuiltinType::UnknownAny:
6086 case clang::BuiltinType::Void:
6087 case clang::BuiltinType::NullPtr:
6088 case clang::BuiltinType::OCLEvent:
6089 case clang::BuiltinType::OCLImage1dRO:
6090 case clang::BuiltinType::OCLImage1dWO:
6091 case clang::BuiltinType::OCLImage1dRW:
6092 case clang::BuiltinType::OCLImage1dArrayRO:
6093 case clang::BuiltinType::OCLImage1dArrayWO:
6094 case clang::BuiltinType::OCLImage1dArrayRW:
6095 case clang::BuiltinType::OCLImage1dBufferRO:
6096 case clang::BuiltinType::OCLImage1dBufferWO:
6097 case clang::BuiltinType::OCLImage1dBufferRW:
6098 case clang::BuiltinType::OCLImage2dRO:
6099 case clang::BuiltinType::OCLImage2dWO:
6100 case clang::BuiltinType::OCLImage2dRW:
6101 case clang::BuiltinType::OCLImage2dArrayRO:
6102 case clang::BuiltinType::OCLImage2dArrayWO:
6103 case clang::BuiltinType::OCLImage2dArrayRW:
6104 case clang::BuiltinType::OCLImage3dRO:
6105 case clang::BuiltinType::OCLImage3dWO:
6106 case clang::BuiltinType::OCLImage3dRW:
6107 case clang::BuiltinType::OCLSampler:
6108 return 0;
6109 case clang::BuiltinType::Bool:
6110 case clang::BuiltinType::Char_U:
6111 case clang::BuiltinType::UChar:
6112 case clang::BuiltinType::WChar_U:
6113 case clang::BuiltinType::Char16:
6114 case clang::BuiltinType::Char32:
6115 case clang::BuiltinType::UShort:
6116 case clang::BuiltinType::UInt:
6117 case clang::BuiltinType::ULong:
6118 case clang::BuiltinType::ULongLong:
6119 case clang::BuiltinType::UInt128:
6120 case clang::BuiltinType::Char_S:
6121 case clang::BuiltinType::SChar:
6122 case clang::BuiltinType::WChar_S:
6123 case clang::BuiltinType::Short:
6124 case clang::BuiltinType::Int:
6125 case clang::BuiltinType::Long:
6126 case clang::BuiltinType::LongLong:
6127 case clang::BuiltinType::Int128:
6128 case clang::BuiltinType::Float:
6129 case clang::BuiltinType::Double:
6130 case clang::BuiltinType::LongDouble:
6131 case clang::BuiltinType::Dependent:
6132 case clang::BuiltinType::Overload:
6133 case clang::BuiltinType::ObjCId:
6134 case clang::BuiltinType::ObjCClass:
6135 case clang::BuiltinType::ObjCSel:
6136 case clang::BuiltinType::BoundMember:
6137 case clang::BuiltinType::Half:
6138 case clang::BuiltinType::ARCUnbridgedCast:
6139 case clang::BuiltinType::PseudoObject:
6140 case clang::BuiltinType::BuiltinFn:
6141 case clang::BuiltinType::OMPArraySection:
6142 return 1;
6143 default:
6144 return 0;
6145 }
6146 break;
6147
6148 case clang::Type::Complex:
6149 return 1;
6150 case clang::Type::Pointer:
6151 return 1;
6152 case clang::Type::BlockPointer:
6153 return 0; // If block pointers don't have debug info, then no children for
6154 // them
6155 case clang::Type::LValueReference:
6156 return 1;
6157 case clang::Type::RValueReference:
6158 return 1;
6159 case clang::Type::MemberPointer:
6160 return 0;
6161 case clang::Type::ConstantArray:
6162 return 0;
6163 case clang::Type::IncompleteArray:
6164 return 0;
6165 case clang::Type::VariableArray:
6166 return 0;
6167 case clang::Type::DependentSizedArray:
6168 return 0;
6169 case clang::Type::DependentSizedExtVector:
6170 return 0;
6171 case clang::Type::Vector:
6172 return 0;
6173 case clang::Type::ExtVector:
6174 return 0;
6175 case clang::Type::FunctionProto:
6176 return 0; // When we function pointers, they have no children...
6177 case clang::Type::FunctionNoProto:
6178 return 0; // When we function pointers, they have no children...
6179 case clang::Type::UnresolvedUsing:
6180 return 0;
6181 case clang::Type::Record:
6182 return 0;
6183 case clang::Type::Enum:
6184 return 1;
6185 case clang::Type::TemplateTypeParm:
6186 return 1;
6187 case clang::Type::SubstTemplateTypeParm:
6188 return 1;
6189 case clang::Type::TemplateSpecialization:
6190 return 1;
6191 case clang::Type::InjectedClassName:
6192 return 0;
6193 case clang::Type::DependentName:
6194 return 1;
6195 case clang::Type::DependentTemplateSpecialization:
6196 return 1;
6197 case clang::Type::ObjCObject:
6198 return 0;
6199 case clang::Type::ObjCInterface:
6200 return 0;
6201 case clang::Type::ObjCObjectPointer:
6202 return 1;
6203 default:
6204 break;
6205 }
6206 return 0;
6207}
6208
6209CompilerType TypeSystemClang::GetChildCompilerTypeAtIndex(
6210 lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
6211 bool transparent_pointers, bool omit_empty_base_classes,
6212 bool ignore_array_bounds, std::string &child_name,
6213 uint32_t &child_byte_size, int32_t &child_byte_offset,
6214 uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
6215 bool &child_is_base_class, bool &child_is_deref_of_parent,
6216 ValueObject *valobj, uint64_t &language_flags) {
6217 if (!type)
6218 return CompilerType();
6219
6220 auto get_exe_scope = [&exe_ctx]() {
6221 return exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
6222 };
6223
6224 clang::QualType parent_qual_type(
6225 RemoveWrappingTypes(GetCanonicalQualType(type)));
6226 const clang::Type::TypeClass parent_type_class =
6227 parent_qual_type->getTypeClass();
6228 child_bitfield_bit_size = 0;
6229 child_bitfield_bit_offset = 0;
6230 child_is_base_class = false;
6231 language_flags = 0;
6232
6233 const bool idx_is_valid =
6234 idx < GetNumChildren(type, omit_empty_base_classes, exe_ctx);
6235 int32_t bit_offset;
6236 switch (parent_type_class) {
6237 case clang::Type::Builtin:
6238 if (idx_is_valid) {
6239 switch (llvm::cast<clang::BuiltinType>(parent_qual_type)->getKind()) {
6240 case clang::BuiltinType::ObjCId:
6241 case clang::BuiltinType::ObjCClass:
6242 child_name = "isa";
6243 child_byte_size =
6244 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy) /
6245 CHAR_BIT8;
6246 return GetType(getASTContext().ObjCBuiltinClassTy);
6247
6248 default:
6249 break;
6250 }
6251 }
6252 break;
6253
6254 case clang::Type::Record:
6255 if (idx_is_valid && GetCompleteType(type)) {
6256 const clang::RecordType *record_type =
6257 llvm::cast<clang::RecordType>(parent_qual_type.getTypePtr());
6258 const clang::RecordDecl *record_decl = record_type->getDecl();
6259 assert(record_decl)(static_cast <bool> (record_decl) ? void (0) : __assert_fail
("record_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 6259, __extension__ __PRETTY_FUNCTION__))
;
6260 const clang::ASTRecordLayout &record_layout =
6261 getASTContext().getASTRecordLayout(record_decl);
6262 uint32_t child_idx = 0;
6263
6264 const clang::CXXRecordDecl *cxx_record_decl =
6265 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6266 if (cxx_record_decl) {
6267 // We might have base classes to print out first
6268 clang::CXXRecordDecl::base_class_const_iterator base_class,
6269 base_class_end;
6270 for (base_class = cxx_record_decl->bases_begin(),
6271 base_class_end = cxx_record_decl->bases_end();
6272 base_class != base_class_end; ++base_class) {
6273 const clang::CXXRecordDecl *base_class_decl = nullptr;
6274
6275 // Skip empty base classes
6276 if (omit_empty_base_classes) {
6277 base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6278 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6279 if (!TypeSystemClang::RecordHasFields(base_class_decl))
6280 continue;
6281 }
6282
6283 if (idx == child_idx) {
6284 if (base_class_decl == nullptr)
6285 base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6286 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6287
6288 if (base_class->isVirtual()) {
6289 bool handled = false;
6290 if (valobj) {
6291 clang::VTableContextBase *vtable_ctx =
6292 getASTContext().getVTableContext();
6293 if (vtable_ctx)
6294 handled = GetVBaseBitOffset(*vtable_ctx, *valobj,
6295 record_layout, cxx_record_decl,
6296 base_class_decl, bit_offset);
6297 }
6298 if (!handled)
6299 bit_offset = record_layout.getVBaseClassOffset(base_class_decl)
6300 .getQuantity() *
6301 8;
6302 } else
6303 bit_offset = record_layout.getBaseClassOffset(base_class_decl)
6304 .getQuantity() *
6305 8;
6306
6307 // Base classes should be a multiple of 8 bits in size
6308 child_byte_offset = bit_offset / 8;
6309 CompilerType base_class_clang_type = GetType(base_class->getType());
6310 child_name = base_class_clang_type.GetTypeName().AsCString("");
6311 std::optional<uint64_t> size =
6312 base_class_clang_type.GetBitSize(get_exe_scope());
6313 if (!size)
6314 return {};
6315 uint64_t base_class_clang_type_bit_size = *size;
6316
6317 // Base classes bit sizes should be a multiple of 8 bits in size
6318 assert(base_class_clang_type_bit_size % 8 == 0)(static_cast <bool> (base_class_clang_type_bit_size % 8
== 0) ? void (0) : __assert_fail ("base_class_clang_type_bit_size % 8 == 0"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
6318, __extension__ __PRETTY_FUNCTION__))
;
6319 child_byte_size = base_class_clang_type_bit_size / 8;
6320 child_is_base_class = true;
6321 return base_class_clang_type;
6322 }
6323 // We don't increment the child index in the for loop since we might
6324 // be skipping empty base classes
6325 ++child_idx;
6326 }
6327 }
6328 // Make sure index is in range...
6329 uint32_t field_idx = 0;
6330 clang::RecordDecl::field_iterator field, field_end;
6331 for (field = record_decl->field_begin(),
6332 field_end = record_decl->field_end();
6333 field != field_end; ++field, ++field_idx, ++child_idx) {
6334 if (idx == child_idx) {
6335 // Print the member type if requested
6336 // Print the member name and equal sign
6337 child_name.assign(field->getNameAsString());
6338
6339 // Figure out the type byte size (field_type_info.first) and
6340 // alignment (field_type_info.second) from the AST context.
6341 CompilerType field_clang_type = GetType(field->getType());
6342 assert(field_idx < record_layout.getFieldCount())(static_cast <bool> (field_idx < record_layout.getFieldCount
()) ? void (0) : __assert_fail ("field_idx < record_layout.getFieldCount()"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
6342, __extension__ __PRETTY_FUNCTION__))
;
6343 std::optional<uint64_t> size =
6344 field_clang_type.GetByteSize(get_exe_scope());
6345 if (!size)
6346 return {};
6347 child_byte_size = *size;
6348 const uint32_t child_bit_size = child_byte_size * 8;
6349
6350 // Figure out the field offset within the current struct/union/class
6351 // type
6352 bit_offset = record_layout.getFieldOffset(field_idx);
6353 if (FieldIsBitfield(*field, child_bitfield_bit_size)) {
6354 child_bitfield_bit_offset = bit_offset % child_bit_size;
6355 const uint32_t child_bit_offset =
6356 bit_offset - child_bitfield_bit_offset;
6357 child_byte_offset = child_bit_offset / 8;
6358 } else {
6359 child_byte_offset = bit_offset / 8;
6360 }
6361
6362 return field_clang_type;
6363 }
6364 }
6365 }
6366 break;
6367
6368 case clang::Type::ObjCObject:
6369 case clang::Type::ObjCInterface:
6370 if (idx_is_valid && GetCompleteType(type)) {
6371 const clang::ObjCObjectType *objc_class_type =
6372 llvm::dyn_cast<clang::ObjCObjectType>(parent_qual_type.getTypePtr());
6373 assert(objc_class_type)(static_cast <bool> (objc_class_type) ? void (0) : __assert_fail
("objc_class_type", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 6373, __extension__ __PRETTY_FUNCTION__))
;
6374 if (objc_class_type) {
6375 uint32_t child_idx = 0;
6376 clang::ObjCInterfaceDecl *class_interface_decl =
6377 objc_class_type->getInterface();
6378
6379 if (class_interface_decl) {
6380
6381 const clang::ASTRecordLayout &interface_layout =
6382 getASTContext().getASTObjCInterfaceLayout(class_interface_decl);
6383 clang::ObjCInterfaceDecl *superclass_interface_decl =
6384 class_interface_decl->getSuperClass();
6385 if (superclass_interface_decl) {
6386 if (omit_empty_base_classes) {
6387 CompilerType base_class_clang_type =
6388 GetType(getASTContext().getObjCInterfaceType(
6389 superclass_interface_decl));
6390 if (base_class_clang_type.GetNumChildren(omit_empty_base_classes,
6391 exe_ctx) > 0) {
6392 if (idx == 0) {
6393 clang::QualType ivar_qual_type(
6394 getASTContext().getObjCInterfaceType(
6395 superclass_interface_decl));
6396
6397 child_name.assign(
6398 superclass_interface_decl->getNameAsString());
6399
6400 clang::TypeInfo ivar_type_info =
6401 getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6402
6403 child_byte_size = ivar_type_info.Width / 8;
6404 child_byte_offset = 0;
6405 child_is_base_class = true;
6406
6407 return GetType(ivar_qual_type);
6408 }
6409
6410 ++child_idx;
6411 }
6412 } else
6413 ++child_idx;
6414 }
6415
6416 const uint32_t superclass_idx = child_idx;
6417
6418 if (idx < (child_idx + class_interface_decl->ivar_size())) {
6419 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6420 ivar_end = class_interface_decl->ivar_end();
6421
6422 for (ivar_pos = class_interface_decl->ivar_begin();
6423 ivar_pos != ivar_end; ++ivar_pos) {
6424 if (child_idx == idx) {
6425 clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6426
6427 clang::QualType ivar_qual_type(ivar_decl->getType());
6428
6429 child_name.assign(ivar_decl->getNameAsString());
6430
6431 clang::TypeInfo ivar_type_info =
6432 getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6433
6434 child_byte_size = ivar_type_info.Width / 8;
6435
6436 // Figure out the field offset within the current
6437 // struct/union/class type For ObjC objects, we can't trust the
6438 // bit offset we get from the Clang AST, since that doesn't
6439 // account for the space taken up by unbacked properties, or
6440 // from the changing size of base classes that are newer than
6441 // this class. So if we have a process around that we can ask
6442 // about this object, do so.
6443 child_byte_offset = LLDB_INVALID_IVAR_OFFSET(4294967295U);
6444 Process *process = nullptr;
6445 if (exe_ctx)
6446 process = exe_ctx->GetProcessPtr();
6447 if (process) {
6448 ObjCLanguageRuntime *objc_runtime =
6449 ObjCLanguageRuntime::Get(*process);
6450 if (objc_runtime != nullptr) {
6451 CompilerType parent_ast_type = GetType(parent_qual_type);
6452 child_byte_offset = objc_runtime->GetByteOffsetForIvar(
6453 parent_ast_type, ivar_decl->getNameAsString().c_str());
6454 }
6455 }
6456
6457 // Setting this to INT32_MAX to make sure we don't compute it
6458 // twice...
6459 bit_offset = INT32_MAX(2147483647);
6460
6461 if (child_byte_offset ==
6462 static_cast<int32_t>(LLDB_INVALID_IVAR_OFFSET(4294967295U))) {
6463 bit_offset = interface_layout.getFieldOffset(child_idx -
6464 superclass_idx);
6465 child_byte_offset = bit_offset / 8;
6466 }
6467
6468 // Note, the ObjC Ivar Byte offset is just that, it doesn't
6469 // account for the bit offset of a bitfield within its
6470 // containing object. So regardless of where we get the byte
6471 // offset from, we still need to get the bit offset for
6472 // bitfields from the layout.
6473
6474 if (FieldIsBitfield(ivar_decl, child_bitfield_bit_size)) {
6475 if (bit_offset == INT32_MAX(2147483647))
6476 bit_offset = interface_layout.getFieldOffset(
6477 child_idx - superclass_idx);
6478
6479 child_bitfield_bit_offset = bit_offset % 8;
6480 }
6481 return GetType(ivar_qual_type);
6482 }
6483 ++child_idx;
6484 }
6485 }
6486 }
6487 }
6488 }
6489 break;
6490
6491 case clang::Type::ObjCObjectPointer:
6492 if (idx_is_valid) {
6493 CompilerType pointee_clang_type(GetPointeeType(type));
6494
6495 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6496 child_is_deref_of_parent = false;
6497 bool tmp_child_is_deref_of_parent = false;
6498 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6499 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6500 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6501 child_bitfield_bit_size, child_bitfield_bit_offset,
6502 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6503 language_flags);
6504 } else {
6505 child_is_deref_of_parent = true;
6506 const char *parent_name =
6507 valobj ? valobj->GetName().GetCString() : nullptr;
6508 if (parent_name) {
6509 child_name.assign(1, '*');
6510 child_name += parent_name;
6511 }
6512
6513 // We have a pointer to an simple type
6514 if (idx == 0 && pointee_clang_type.GetCompleteType()) {
6515 if (std::optional<uint64_t> size =
6516 pointee_clang_type.GetByteSize(get_exe_scope())) {
6517 child_byte_size = *size;
6518 child_byte_offset = 0;
6519 return pointee_clang_type;
6520 }
6521 }
6522 }
6523 }
6524 break;
6525
6526 case clang::Type::Vector:
6527 case clang::Type::ExtVector:
6528 if (idx_is_valid) {
6529 const clang::VectorType *array =
6530 llvm::cast<clang::VectorType>(parent_qual_type.getTypePtr());
6531 if (array) {
6532 CompilerType element_type = GetType(array->getElementType());
6533 if (element_type.GetCompleteType()) {
6534 char element_name[64];
6535 ::snprintf(element_name, sizeof(element_name), "[%" PRIu64"l" "u" "]",
6536 static_cast<uint64_t>(idx));
6537 child_name.assign(element_name);
6538 if (std::optional<uint64_t> size =
6539 element_type.GetByteSize(get_exe_scope())) {
6540 child_byte_size = *size;
6541 child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6542 return element_type;
6543 }
6544 }
6545 }
6546 }
6547 break;
6548
6549 case clang::Type::ConstantArray:
6550 case clang::Type::IncompleteArray:
6551 if (ignore_array_bounds || idx_is_valid) {
6552 const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe();
6553 if (array) {
6554 CompilerType element_type = GetType(array->getElementType());
6555 if (element_type.GetCompleteType()) {
6556 child_name = std::string(llvm::formatv("[{0}]", idx));
6557 if (std::optional<uint64_t> size =
6558 element_type.GetByteSize(get_exe_scope())) {
6559 child_byte_size = *size;
6560 child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6561 return element_type;
6562 }
6563 }
6564 }
6565 }
6566 break;
6567
6568 case clang::Type::Pointer: {
6569 CompilerType pointee_clang_type(GetPointeeType(type));
6570
6571 // Don't dereference "void *" pointers
6572 if (pointee_clang_type.IsVoidType())
6573 return CompilerType();
6574
6575 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6576 child_is_deref_of_parent = false;
6577 bool tmp_child_is_deref_of_parent = false;
6578 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6579 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6580 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6581 child_bitfield_bit_size, child_bitfield_bit_offset,
6582 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6583 language_flags);
6584 } else {
6585 child_is_deref_of_parent = true;
6586
6587 const char *parent_name =
6588 valobj ? valobj->GetName().GetCString() : nullptr;
6589 if (parent_name) {
6590 child_name.assign(1, '*');
6591 child_name += parent_name;
6592 }
6593
6594 // We have a pointer to an simple type
6595 if (idx == 0) {
6596 if (std::optional<uint64_t> size =
6597 pointee_clang_type.GetByteSize(get_exe_scope())) {
6598 child_byte_size = *size;
6599 child_byte_offset = 0;
6600 return pointee_clang_type;
6601 }
6602 }
6603 }
6604 break;
6605 }
6606
6607 case clang::Type::LValueReference:
6608 case clang::Type::RValueReference:
6609 if (idx_is_valid) {
6610 const clang::ReferenceType *reference_type =
6611 llvm::cast<clang::ReferenceType>(
6612 RemoveWrappingTypes(GetQualType(type)).getTypePtr());
6613 CompilerType pointee_clang_type =
6614 GetType(reference_type->getPointeeType());
6615 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6616 child_is_deref_of_parent = false;
6617 bool tmp_child_is_deref_of_parent = false;
6618 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6619 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6620 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6621 child_bitfield_bit_size, child_bitfield_bit_offset,
6622 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6623 language_flags);
6624 } else {
6625 const char *parent_name =
6626 valobj ? valobj->GetName().GetCString() : nullptr;
6627 if (parent_name) {
6628 child_name.assign(1, '&');
6629 child_name += parent_name;
6630 }
6631
6632 // We have a pointer to an simple type
6633 if (idx == 0) {
6634 if (std::optional<uint64_t> size =
6635 pointee_clang_type.GetByteSize(get_exe_scope())) {
6636 child_byte_size = *size;
6637 child_byte_offset = 0;
6638 return pointee_clang_type;
6639 }
6640 }
6641 }
6642 }
6643 break;
6644
6645 default:
6646 break;
6647 }
6648 return CompilerType();
6649}
6650
6651uint32_t TypeSystemClang::GetIndexForRecordBase(
6652 const clang::RecordDecl *record_decl,
6653 const clang::CXXBaseSpecifier *base_spec,
6654 bool omit_empty_base_classes) {
6655 uint32_t child_idx = 0;
6656
6657 const clang::CXXRecordDecl *cxx_record_decl =
6658 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6659
6660 if (cxx_record_decl) {
6661 clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
6662 for (base_class = cxx_record_decl->bases_begin(),
6663 base_class_end = cxx_record_decl->bases_end();
6664 base_class != base_class_end; ++base_class) {
6665 if (omit_empty_base_classes) {
6666 if (BaseSpecifierIsEmpty(base_class))
6667 continue;
6668 }
6669
6670 if (base_class == base_spec)
6671 return child_idx;
6672 ++child_idx;
6673 }
6674 }
6675
6676 return UINT32_MAX(4294967295U);
6677}
6678
6679uint32_t TypeSystemClang::GetIndexForRecordChild(
6680 const clang::RecordDecl *record_decl, clang::NamedDecl *canonical_decl,
6681 bool omit_empty_base_classes) {
6682 uint32_t child_idx = TypeSystemClang::GetNumBaseClasses(
6683 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl),
6684 omit_empty_base_classes);
6685
6686 clang::RecordDecl::field_iterator field, field_end;
6687 for (field = record_decl->field_begin(), field_end = record_decl->field_end();
6688 field != field_end; ++field, ++child_idx) {
6689 if (field->getCanonicalDecl() == canonical_decl)
6690 return child_idx;
6691 }
6692
6693 return UINT32_MAX(4294967295U);
6694}
6695
6696// Look for a child member (doesn't include base classes, but it does include
6697// their members) in the type hierarchy. Returns an index path into
6698// "clang_type" on how to reach the appropriate member.
6699//
6700// class A
6701// {
6702// public:
6703// int m_a;
6704// int m_b;
6705// };
6706//
6707// class B
6708// {
6709// };
6710//
6711// class C :
6712// public B,
6713// public A
6714// {
6715// };
6716//
6717// If we have a clang type that describes "class C", and we wanted to looked
6718// "m_b" in it:
6719//
6720// With omit_empty_base_classes == false we would get an integer array back
6721// with: { 1, 1 } The first index 1 is the child index for "class A" within
6722// class C The second index 1 is the child index for "m_b" within class A
6723//
6724// With omit_empty_base_classes == true we would get an integer array back
6725// with: { 0, 1 } The first index 0 is the child index for "class A" within
6726// class C (since class B doesn't have any members it doesn't count) The second
6727// index 1 is the child index for "m_b" within class A
6728
6729size_t TypeSystemClang::GetIndexOfChildMemberWithName(
6730 lldb::opaque_compiler_type_t type, const char *name,
6731 bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) {
6732 if (type && name && name[0]) {
6733 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6734 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6735 switch (type_class) {
6736 case clang::Type::Record:
6737 if (GetCompleteType(type)) {
6738 const clang::RecordType *record_type =
6739 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6740 const clang::RecordDecl *record_decl = record_type->getDecl();
6741
6742 assert(record_decl)(static_cast <bool> (record_decl) ? void (0) : __assert_fail
("record_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 6742, __extension__ __PRETTY_FUNCTION__))
;
6743 uint32_t child_idx = 0;
6744
6745 const clang::CXXRecordDecl *cxx_record_decl =
6746 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6747
6748 // Try and find a field that matches NAME
6749 clang::RecordDecl::field_iterator field, field_end;
6750 llvm::StringRef name_sref(name);
6751 for (field = record_decl->field_begin(),
6752 field_end = record_decl->field_end();
6753 field != field_end; ++field, ++child_idx) {
6754 llvm::StringRef field_name = field->getName();
6755 if (field_name.empty()) {
6756 CompilerType field_type = GetType(field->getType());
6757 child_indexes.push_back(child_idx);
6758 if (field_type.GetIndexOfChildMemberWithName(
6759 name, omit_empty_base_classes, child_indexes))
6760 return child_indexes.size();
6761 child_indexes.pop_back();
6762
6763 } else if (field_name.equals(name_sref)) {
6764 // We have to add on the number of base classes to this index!
6765 child_indexes.push_back(
6766 child_idx + TypeSystemClang::GetNumBaseClasses(
6767 cxx_record_decl, omit_empty_base_classes));
6768 return child_indexes.size();
6769 }
6770 }
6771
6772 if (cxx_record_decl) {
6773 const clang::RecordDecl *parent_record_decl = cxx_record_decl;
6774
6775 // Didn't find things easily, lets let clang do its thang...
6776 clang::IdentifierInfo &ident_ref =
6777 getASTContext().Idents.get(name_sref);
6778 clang::DeclarationName decl_name(&ident_ref);
6779
6780 clang::CXXBasePaths paths;
6781 if (cxx_record_decl->lookupInBases(
6782 [decl_name](const clang::CXXBaseSpecifier *specifier,
6783 clang::CXXBasePath &path) {
6784 CXXRecordDecl *record =
6785 specifier->getType()->getAsCXXRecordDecl();
6786 auto r = record->lookup(decl_name);
6787 path.Decls = r.begin();
6788 return !r.empty();
6789 },
6790 paths)) {
6791 clang::CXXBasePaths::const_paths_iterator path,
6792 path_end = paths.end();
6793 for (path = paths.begin(); path != path_end; ++path) {
6794 const size_t num_path_elements = path->size();
6795 for (size_t e = 0; e < num_path_elements; ++e) {
6796 clang::CXXBasePathElement elem = (*path)[e];
6797
6798 child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base,
6799 omit_empty_base_classes);
6800 if (child_idx == UINT32_MAX(4294967295U)) {
6801 child_indexes.clear();
6802 return 0;
6803 } else {
6804 child_indexes.push_back(child_idx);
6805 parent_record_decl = llvm::cast<clang::RecordDecl>(
6806 elem.Base->getType()
6807 ->castAs<clang::RecordType>()
6808 ->getDecl());
6809 }
6810 }
6811 for (clang::DeclContext::lookup_iterator I = path->Decls, E;
6812 I != E; ++I) {
6813 child_idx = GetIndexForRecordChild(
6814 parent_record_decl, *I, omit_empty_base_classes);
6815 if (child_idx == UINT32_MAX(4294967295U)) {
6816 child_indexes.clear();
6817 return 0;
6818 } else {
6819 child_indexes.push_back(child_idx);
6820 }
6821 }
6822 }
6823 return child_indexes.size();
6824 }
6825 }
6826 }
6827 break;
6828
6829 case clang::Type::ObjCObject:
6830 case clang::Type::ObjCInterface:
6831 if (GetCompleteType(type)) {
6832 llvm::StringRef name_sref(name);
6833 const clang::ObjCObjectType *objc_class_type =
6834 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
6835 assert(objc_class_type)(static_cast <bool> (objc_class_type) ? void (0) : __assert_fail
("objc_class_type", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 6835, __extension__ __PRETTY_FUNCTION__))
;
6836 if (objc_class_type) {
6837 uint32_t child_idx = 0;
6838 clang::ObjCInterfaceDecl *class_interface_decl =
6839 objc_class_type->getInterface();
6840
6841 if (class_interface_decl) {
6842 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6843 ivar_end = class_interface_decl->ivar_end();
6844 clang::ObjCInterfaceDecl *superclass_interface_decl =
6845 class_interface_decl->getSuperClass();
6846
6847 for (ivar_pos = class_interface_decl->ivar_begin();
6848 ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
6849 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6850
6851 if (ivar_decl->getName().equals(name_sref)) {
6852 if ((!omit_empty_base_classes && superclass_interface_decl) ||
6853 (omit_empty_base_classes &&
6854 ObjCDeclHasIVars(superclass_interface_decl, true)))
6855 ++child_idx;
6856
6857 child_indexes.push_back(child_idx);
6858 return child_indexes.size();
6859 }
6860 }
6861
6862 if (superclass_interface_decl) {
6863 // The super class index is always zero for ObjC classes, so we
6864 // push it onto the child indexes in case we find an ivar in our
6865 // superclass...
6866 child_indexes.push_back(0);
6867
6868 CompilerType superclass_clang_type =
6869 GetType(getASTContext().getObjCInterfaceType(
6870 superclass_interface_decl));
6871 if (superclass_clang_type.GetIndexOfChildMemberWithName(
6872 name, omit_empty_base_classes, child_indexes)) {
6873 // We did find an ivar in a superclass so just return the
6874 // results!
6875 return child_indexes.size();
6876 }
6877
6878 // We didn't find an ivar matching "name" in our superclass, pop
6879 // the superclass zero index that we pushed on above.
6880 child_indexes.pop_back();
6881 }
6882 }
6883 }
6884 }
6885 break;
6886
6887 case clang::Type::ObjCObjectPointer: {
6888 CompilerType objc_object_clang_type = GetType(
6889 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
6890 ->getPointeeType());
6891 return objc_object_clang_type.GetIndexOfChildMemberWithName(
6892 name, omit_empty_base_classes, child_indexes);
6893 } break;
6894
6895 case clang::Type::ConstantArray: {
6896 // const clang::ConstantArrayType *array =
6897 // llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
6898 // const uint64_t element_count =
6899 // array->getSize().getLimitedValue();
6900 //
6901 // if (idx < element_count)
6902 // {
6903 // std::pair<uint64_t, unsigned> field_type_info =
6904 // ast->getTypeInfo(array->getElementType());
6905 //
6906 // char element_name[32];
6907 // ::snprintf (element_name, sizeof (element_name),
6908 // "%s[%u]", parent_name ? parent_name : "", idx);
6909 //
6910 // child_name.assign(element_name);
6911 // assert(field_type_info.first % 8 == 0);
6912 // child_byte_size = field_type_info.first / 8;
6913 // child_byte_offset = idx * child_byte_size;
6914 // return array->getElementType().getAsOpaquePtr();
6915 // }
6916 } break;
6917
6918 // case clang::Type::MemberPointerType:
6919 // {
6920 // MemberPointerType *mem_ptr_type =
6921 // llvm::cast<MemberPointerType>(qual_type.getTypePtr());
6922 // clang::QualType pointee_type =
6923 // mem_ptr_type->getPointeeType();
6924 //
6925 // if (TypeSystemClang::IsAggregateType
6926 // (pointee_type.getAsOpaquePtr()))
6927 // {
6928 // return GetIndexOfChildWithName (ast,
6929 // mem_ptr_type->getPointeeType().getAsOpaquePtr(),
6930 // name);
6931 // }
6932 // }
6933 // break;
6934 //
6935 case clang::Type::LValueReference:
6936 case clang::Type::RValueReference: {
6937 const clang::ReferenceType *reference_type =
6938 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
6939 clang::QualType pointee_type(reference_type->getPointeeType());
6940 CompilerType pointee_clang_type = GetType(pointee_type);
6941
6942 if (pointee_clang_type.IsAggregateType()) {
6943 return pointee_clang_type.GetIndexOfChildMemberWithName(
6944 name, omit_empty_base_classes, child_indexes);
6945 }
6946 } break;
6947
6948 case clang::Type::Pointer: {
6949 CompilerType pointee_clang_type(GetPointeeType(type));
6950
6951 if (pointee_clang_type.IsAggregateType()) {
6952 return pointee_clang_type.GetIndexOfChildMemberWithName(
6953 name, omit_empty_base_classes, child_indexes);
6954 }
6955 } break;
6956
6957 default:
6958 break;
6959 }
6960 }
6961 return 0;
6962}
6963
6964// Get the index of the child of "clang_type" whose name matches. This function
6965// doesn't descend into the children, but only looks one level deep and name
6966// matches can include base class names.
6967
6968uint32_t
6969TypeSystemClang::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
6970 const char *name,
6971 bool omit_empty_base_classes) {
6972 if (type && name && name[0]) {
6973 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6974
6975 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6976
6977 switch (type_class) {
6978 case clang::Type::Record:
6979 if (GetCompleteType(type)) {
6980 const clang::RecordType *record_type =
6981 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6982 const clang::RecordDecl *record_decl = record_type->getDecl();
6983
6984 assert(record_decl)(static_cast <bool> (record_decl) ? void (0) : __assert_fail
("record_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 6984, __extension__ __PRETTY_FUNCTION__))
;
6985 uint32_t child_idx = 0;
6986
6987 const clang::CXXRecordDecl *cxx_record_decl =
6988 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6989
6990 if (cxx_record_decl) {
6991 clang::CXXRecordDecl::base_class_const_iterator base_class,
6992 base_class_end;
6993 for (base_class = cxx_record_decl->bases_begin(),
6994 base_class_end = cxx_record_decl->bases_end();
6995 base_class != base_class_end; ++base_class) {
6996 // Skip empty base classes
6997 clang::CXXRecordDecl *base_class_decl =
6998 llvm::cast<clang::CXXRecordDecl>(
6999 base_class->getType()
7000 ->castAs<clang::RecordType>()
7001 ->getDecl());
7002 if (omit_empty_base_classes &&
7003 !TypeSystemClang::RecordHasFields(base_class_decl))
7004 continue;
7005
7006 CompilerType base_class_clang_type = GetType(base_class->getType());
7007 std::string base_class_type_name(
7008 base_class_clang_type.GetTypeName().AsCString(""));
7009 if (base_class_type_name == name)
7010 return child_idx;
7011 ++child_idx;
7012 }
7013 }
7014
7015 // Try and find a field that matches NAME
7016 clang::RecordDecl::field_iterator field, field_end;
7017 llvm::StringRef name_sref(name);
7018 for (field = record_decl->field_begin(),
7019 field_end = record_decl->field_end();
7020 field != field_end; ++field, ++child_idx) {
7021 if (field->getName().equals(name_sref))
7022 return child_idx;
7023 }
7024 }
7025 break;
7026
7027 case clang::Type::ObjCObject:
7028 case clang::Type::ObjCInterface:
7029 if (GetCompleteType(type)) {
7030 llvm::StringRef name_sref(name);
7031 const clang::ObjCObjectType *objc_class_type =
7032 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
7033 assert(objc_class_type)(static_cast <bool> (objc_class_type) ? void (0) : __assert_fail
("objc_class_type", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 7033, __extension__ __PRETTY_FUNCTION__))
;
7034 if (objc_class_type) {
7035 uint32_t child_idx = 0;
7036 clang::ObjCInterfaceDecl *class_interface_decl =
7037 objc_class_type->getInterface();
7038
7039 if (class_interface_decl) {
7040 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
7041 ivar_end = class_interface_decl->ivar_end();
7042 clang::ObjCInterfaceDecl *superclass_interface_decl =
7043 class_interface_decl->getSuperClass();
7044
7045 for (ivar_pos = class_interface_decl->ivar_begin();
7046 ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
7047 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
7048
7049 if (ivar_decl->getName().equals(name_sref)) {
7050 if ((!omit_empty_base_classes && superclass_interface_decl) ||
7051 (omit_empty_base_classes &&
7052 ObjCDeclHasIVars(superclass_interface_decl, true)))
7053 ++child_idx;
7054
7055 return child_idx;
7056 }
7057 }
7058
7059 if (superclass_interface_decl) {
7060 if (superclass_interface_decl->getName().equals(name_sref))
7061 return 0;
7062 }
7063 }
7064 }
7065 }
7066 break;
7067
7068 case clang::Type::ObjCObjectPointer: {
7069 CompilerType pointee_clang_type = GetType(
7070 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
7071 ->getPointeeType());
7072 return pointee_clang_type.GetIndexOfChildWithName(
7073 name, omit_empty_base_classes);
7074 } break;
7075
7076 case clang::Type::ConstantArray: {
7077 // const clang::ConstantArrayType *array =
7078 // llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
7079 // const uint64_t element_count =
7080 // array->getSize().getLimitedValue();
7081 //
7082 // if (idx < element_count)
7083 // {
7084 // std::pair<uint64_t, unsigned> field_type_info =
7085 // ast->getTypeInfo(array->getElementType());
7086 //
7087 // char element_name[32];
7088 // ::snprintf (element_name, sizeof (element_name),
7089 // "%s[%u]", parent_name ? parent_name : "", idx);
7090 //
7091 // child_name.assign(element_name);
7092 // assert(field_type_info.first % 8 == 0);
7093 // child_byte_size = field_type_info.first / 8;
7094 // child_byte_offset = idx * child_byte_size;
7095 // return array->getElementType().getAsOpaquePtr();
7096 // }
7097 } break;
7098
7099 // case clang::Type::MemberPointerType:
7100 // {
7101 // MemberPointerType *mem_ptr_type =
7102 // llvm::cast<MemberPointerType>(qual_type.getTypePtr());
7103 // clang::QualType pointee_type =
7104 // mem_ptr_type->getPointeeType();
7105 //
7106 // if (TypeSystemClang::IsAggregateType
7107 // (pointee_type.getAsOpaquePtr()))
7108 // {
7109 // return GetIndexOfChildWithName (ast,
7110 // mem_ptr_type->getPointeeType().getAsOpaquePtr(),
7111 // name);
7112 // }
7113 // }
7114 // break;
7115 //
7116 case clang::Type::LValueReference:
7117 case clang::Type::RValueReference: {
7118 const clang::ReferenceType *reference_type =
7119 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
7120 CompilerType pointee_type = GetType(reference_type->getPointeeType());
7121
7122 if (pointee_type.IsAggregateType()) {
7123 return pointee_type.GetIndexOfChildWithName(name,
7124 omit_empty_base_classes);
7125 }
7126 } break;
7127
7128 case clang::Type::Pointer: {
7129 const clang::PointerType *pointer_type =
7130 llvm::cast<clang::PointerType>(qual_type.getTypePtr());
7131 CompilerType pointee_type = GetType(pointer_type->getPointeeType());
7132
7133 if (pointee_type.IsAggregateType()) {
7134 return pointee_type.GetIndexOfChildWithName(name,
7135 omit_empty_base_classes);
7136 } else {
7137 // if (parent_name)
7138 // {
7139 // child_name.assign(1, '*');
7140 // child_name += parent_name;
7141 // }
7142 //
7143 // // We have a pointer to an simple type
7144 // if (idx == 0)
7145 // {
7146 // std::pair<uint64_t, unsigned> clang_type_info
7147 // = ast->getTypeInfo(pointee_type);
7148 // assert(clang_type_info.first % 8 == 0);
7149 // child_byte_size = clang_type_info.first / 8;
7150 // child_byte_offset = 0;
7151 // return pointee_type.getAsOpaquePtr();
7152 // }
7153 }
7154 } break;
7155
7156 default:
7157 break;
7158 }
7159 }
7160 return UINT32_MAX(4294967295U);
7161}
7162
7163bool TypeSystemClang::IsTemplateType(lldb::opaque_compiler_type_t type) {
7164 if (!type)
7165 return false;
7166 CompilerType ct(weak_from_this(), type);
7167 const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr();
7168 if (auto *cxx_record_decl = dyn_cast<clang::TagType>(clang_type))
7169 return isa<clang::ClassTemplateSpecializationDecl>(
7170 cxx_record_decl->getDecl());
7171 return false;
7172}
7173
7174size_t
7175TypeSystemClang::GetNumTemplateArguments(lldb::opaque_compiler_type_t type,
7176 bool expand_pack) {
7177 if (!type)
7178 return 0;
7179
7180 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
7181 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7182 switch (type_class) {
7183 case clang::Type::Record:
7184 if (GetCompleteType(type)) {
7185 const clang::CXXRecordDecl *cxx_record_decl =
7186 qual_type->getAsCXXRecordDecl();
7187 if (cxx_record_decl) {
7188 const clang::ClassTemplateSpecializationDecl *template_decl =
7189 llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7190 cxx_record_decl);
7191 if (template_decl) {
7192 const auto &template_arg_list = template_decl->getTemplateArgs();
7193 size_t num_args = template_arg_list.size();
7194 assert(num_args && "template specialization without any args")(static_cast <bool> (num_args && "template specialization without any args"
) ? void (0) : __assert_fail ("num_args && \"template specialization without any args\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7194, __extension__ __PRETTY_FUNCTION__))
;
7195 if (expand_pack && num_args) {
7196 const auto &pack = template_arg_list[num_args - 1];
7197 if (pack.getKind() == clang::TemplateArgument::Pack)
7198 num_args += pack.pack_size() - 1;
7199 }
7200 return num_args;
7201 }
7202 }
7203 }
7204 break;
7205
7206 default:
7207 break;
7208 }
7209
7210 return 0;
7211}
7212
7213const clang::ClassTemplateSpecializationDecl *
7214TypeSystemClang::GetAsTemplateSpecialization(
7215 lldb::opaque_compiler_type_t type) {
7216 if (!type)
7217 return nullptr;
7218
7219 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
7220 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7221 switch (type_class) {
7222 case clang::Type::Record: {
7223 if (! GetCompleteType(type))
7224 return nullptr;
7225 const clang::CXXRecordDecl *cxx_record_decl =
7226 qual_type->getAsCXXRecordDecl();
7227 if (!cxx_record_decl)
7228 return nullptr;
7229 return llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7230 cxx_record_decl);
7231 }
7232
7233 default:
7234 return nullptr;
7235 }
7236}
7237
7238const TemplateArgument *
7239GetNthTemplateArgument(const clang::ClassTemplateSpecializationDecl *decl,
7240 size_t idx, bool expand_pack) {
7241 const auto &args = decl->getTemplateArgs();
7242 const size_t args_size = args.size();
7243
7244 assert(args_size && "template specialization without any args")(static_cast <bool> (args_size && "template specialization without any args"
) ? void (0) : __assert_fail ("args_size && \"template specialization without any args\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7244, __extension__ __PRETTY_FUNCTION__))
;
7245 if (!args_size)
7246 return nullptr;
7247
7248 const size_t last_idx = args_size - 1;
7249
7250 // We're asked for a template argument that can't be a parameter pack, so
7251 // return it without worrying about 'expand_pack'.
7252 if (idx < last_idx)
7253 return &args[idx];
7254
7255 // We're asked for the last template argument but we don't want/need to
7256 // expand it.
7257 if (!expand_pack || args[last_idx].getKind() != clang::TemplateArgument::Pack)
7258 return idx >= args.size() ? nullptr : &args[idx];
7259
7260 // Index into the expanded pack.
7261 // Note that 'idx' counts from the beginning of all template arguments
7262 // (including the ones preceding the parameter pack).
7263 const auto &pack = args[last_idx];
7264 const size_t pack_idx = idx - last_idx;
7265 assert(pack_idx < pack.pack_size() && "parameter pack index out-of-bounds")(static_cast <bool> (pack_idx < pack.pack_size() &&
"parameter pack index out-of-bounds") ? void (0) : __assert_fail
("pack_idx < pack.pack_size() && \"parameter pack index out-of-bounds\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7265, __extension__ __PRETTY_FUNCTION__))
;
7266 return &pack.pack_elements()[pack_idx];
7267}
7268
7269lldb::TemplateArgumentKind
7270TypeSystemClang::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
7271 size_t arg_idx, bool expand_pack) {
7272 const clang::ClassTemplateSpecializationDecl *template_decl =
7273 GetAsTemplateSpecialization(type);
7274 if (!template_decl)
7275 return eTemplateArgumentKindNull;
7276
7277 const auto *arg = GetNthTemplateArgument(template_decl, arg_idx, expand_pack);
7278 if (!arg)
7279 return eTemplateArgumentKindNull;
7280
7281 switch (arg->getKind()) {
7282 case clang::TemplateArgument::Null:
7283 return eTemplateArgumentKindNull;
7284
7285 case clang::TemplateArgument::NullPtr:
7286 return eTemplateArgumentKindNullPtr;
7287
7288 case clang::TemplateArgument::Type:
7289 return eTemplateArgumentKindType;
7290
7291 case clang::TemplateArgument::Declaration:
7292 return eTemplateArgumentKindDeclaration;
7293
7294 case clang::TemplateArgument::Integral:
7295 return eTemplateArgumentKindIntegral;
7296
7297 case clang::TemplateArgument::Template:
7298 return eTemplateArgumentKindTemplate;
7299
7300 case clang::TemplateArgument::TemplateExpansion:
7301 return eTemplateArgumentKindTemplateExpansion;
7302
7303 case clang::TemplateArgument::Expression:
7304 return eTemplateArgumentKindExpression;
7305
7306 case clang::TemplateArgument::Pack:
7307 return eTemplateArgumentKindPack;
7308 }
7309 llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind")::llvm::llvm_unreachable_internal("Unhandled clang::TemplateArgument::ArgKind"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7309)
;
7310}
7311
7312CompilerType
7313TypeSystemClang::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
7314 size_t idx, bool expand_pack) {
7315 const clang::ClassTemplateSpecializationDecl *template_decl =
7316 GetAsTemplateSpecialization(type);
7317 if (!template_decl)
7318 return CompilerType();
7319
7320 const auto *arg = GetNthTemplateArgument(template_decl, idx, expand_pack);
7321 if (!arg || arg->getKind() != clang::TemplateArgument::Type)
7322 return CompilerType();
7323
7324 return GetType(arg->getAsType());
7325}
7326
7327std::optional<CompilerType::IntegralTemplateArgument>
7328TypeSystemClang::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
7329 size_t idx, bool expand_pack) {
7330 const clang::ClassTemplateSpecializationDecl *template_decl =
7331 GetAsTemplateSpecialization(type);
7332 if (!template_decl)
7333 return std::nullopt;
7334
7335 const auto *arg = GetNthTemplateArgument(template_decl, idx, expand_pack);
7336 if (!arg || arg->getKind() != clang::TemplateArgument::Integral)
7337 return std::nullopt;
7338
7339 return {{arg->getAsIntegral(), GetType(arg->getIntegralType())}};
7340}
7341
7342CompilerType TypeSystemClang::GetTypeForFormatters(void *type) {
7343 if (type)
7344 return ClangUtil::RemoveFastQualifiers(CompilerType(weak_from_this(), type));
7345 return CompilerType();
7346}
7347
7348clang::EnumDecl *TypeSystemClang::GetAsEnumDecl(const CompilerType &type) {
7349 const clang::EnumType *enutype =
7350 llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type));
7351 if (enutype)
7352 return enutype->getDecl();
7353 return nullptr;
7354}
7355
7356clang::RecordDecl *TypeSystemClang::GetAsRecordDecl(const CompilerType &type) {
7357 const clang::RecordType *record_type =
7358 llvm::dyn_cast<clang::RecordType>(ClangUtil::GetCanonicalQualType(type));
7359 if (record_type)
7360 return record_type->getDecl();
7361 return nullptr;
7362}
7363
7364clang::TagDecl *TypeSystemClang::GetAsTagDecl(const CompilerType &type) {
7365 return ClangUtil::GetAsTagDecl(type);
7366}
7367
7368clang::TypedefNameDecl *
7369TypeSystemClang::GetAsTypedefDecl(const CompilerType &type) {
7370 const clang::TypedefType *typedef_type =
7371 llvm::dyn_cast<clang::TypedefType>(ClangUtil::GetQualType(type));
7372 if (typedef_type)
7373 return typedef_type->getDecl();
7374 return nullptr;
7375}
7376
7377clang::CXXRecordDecl *
7378TypeSystemClang::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) {
7379 return GetCanonicalQualType(type)->getAsCXXRecordDecl();
7380}
7381
7382clang::ObjCInterfaceDecl *
7383TypeSystemClang::GetAsObjCInterfaceDecl(const CompilerType &type) {
7384 const clang::ObjCObjectType *objc_class_type =
7385 llvm::dyn_cast<clang::ObjCObjectType>(
7386 ClangUtil::GetCanonicalQualType(type));
7387 if (objc_class_type)
7388 return objc_class_type->getInterface();
7389 return nullptr;
7390}
7391
7392clang::FieldDecl *TypeSystemClang::AddFieldToRecordType(
7393 const CompilerType &type, llvm::StringRef name,
7394 const CompilerType &field_clang_type, AccessType access,
7395 uint32_t bitfield_bit_size) {
7396 if (!type.IsValid() || !field_clang_type.IsValid())
7397 return nullptr;
7398 auto ts = type.GetTypeSystem();
7399 auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7400 if (!ast)
7401 return nullptr;
7402 clang::ASTContext &clang_ast = ast->getASTContext();
7403 clang::IdentifierInfo *ident = nullptr;
7404 if (!name.empty())
7405 ident = &clang_ast.Idents.get(name);
7406
7407 clang::FieldDecl *field = nullptr;
7408
7409 clang::Expr *bit_width = nullptr;
7410 if (bitfield_bit_size != 0) {
7411 llvm::APInt bitfield_bit_size_apint(clang_ast.getTypeSize(clang_ast.IntTy),
7412 bitfield_bit_size);
7413 bit_width = new (clang_ast)
7414 clang::IntegerLiteral(clang_ast, bitfield_bit_size_apint,
7415 clang_ast.IntTy, clang::SourceLocation());
7416 }
7417
7418 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7419 if (record_decl) {
7420 field = clang::FieldDecl::CreateDeserialized(clang_ast, 0);
7421 field->setDeclContext(record_decl);
7422 field->setDeclName(ident);
7423 field->setType(ClangUtil::GetQualType(field_clang_type));
7424 if (bit_width)
7425 field->setBitWidth(bit_width);
7426 SetMemberOwningModule(field, record_decl);
7427
7428 if (name.empty()) {
7429 // Determine whether this field corresponds to an anonymous struct or
7430 // union.
7431 if (const clang::TagType *TagT =
7432 field->getType()->getAs<clang::TagType>()) {
7433 if (clang::RecordDecl *Rec =
7434 llvm::dyn_cast<clang::RecordDecl>(TagT->getDecl()))
7435 if (!Rec->getDeclName()) {
7436 Rec->setAnonymousStructOrUnion(true);
7437 field->setImplicit();
7438 }
7439 }
7440 }
7441
7442 if (field) {
7443 clang::AccessSpecifier access_specifier =
7444 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access);
7445 field->setAccess(access_specifier);
7446
7447 if (clang::CXXRecordDecl *cxx_record_decl =
7448 llvm::dyn_cast<CXXRecordDecl>(record_decl)) {
7449 AddAccessSpecifierDecl(cxx_record_decl, ast->getASTContext(),
7450 ast->GetCXXRecordDeclAccess(cxx_record_decl),
7451 access_specifier);
7452 ast->SetCXXRecordDeclAccess(cxx_record_decl, access_specifier);
7453 }
7454 record_decl->addDecl(field);
7455
7456 VerifyDecl(field);
7457 }
7458 } else {
7459 clang::ObjCInterfaceDecl *class_interface_decl =
7460 ast->GetAsObjCInterfaceDecl(type);
7461
7462 if (class_interface_decl) {
7463 const bool is_synthesized = false;
7464
7465 field_clang_type.GetCompleteType();
7466
7467 auto *ivar = clang::ObjCIvarDecl::CreateDeserialized(clang_ast, 0);
7468 ivar->setDeclContext(class_interface_decl);
7469 ivar->setDeclName(ident);
7470 ivar->setType(ClangUtil::GetQualType(field_clang_type));
7471 ivar->setAccessControl(ConvertAccessTypeToObjCIvarAccessControl(access));
7472 if (bit_width)
7473 ivar->setBitWidth(bit_width);
7474 ivar->setSynthesize(is_synthesized);
7475 field = ivar;
7476 SetMemberOwningModule(field, class_interface_decl);
7477
7478 if (field) {
7479 class_interface_decl->addDecl(field);
7480
7481 VerifyDecl(field);
7482 }
7483 }
7484 }
7485 return field;
7486}
7487
7488void TypeSystemClang::BuildIndirectFields(const CompilerType &type) {
7489 if (!type)
7490 return;
7491
7492 auto ts = type.GetTypeSystem();
7493 auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7494 if (!ast)
7495 return;
7496
7497 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7498
7499 if (!record_decl)
7500 return;
7501
7502 typedef llvm::SmallVector<clang::IndirectFieldDecl *, 1> IndirectFieldVector;
7503
7504 IndirectFieldVector indirect_fields;
7505 clang::RecordDecl::field_iterator field_pos;
7506 clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end();
7507 clang::RecordDecl::field_iterator last_field_pos = field_end_pos;
7508 for (field_pos = record_decl->field_begin(); field_pos != field_end_pos;
7509 last_field_pos = field_pos++) {
7510 if (field_pos->isAnonymousStructOrUnion()) {
7511 clang::QualType field_qual_type = field_pos->getType();
7512
7513 const clang::RecordType *field_record_type =
7514 field_qual_type->getAs<clang::RecordType>();
7515
7516 if (!field_record_type)
7517 continue;
7518
7519 clang::RecordDecl *field_record_decl = field_record_type->getDecl();
7520
7521 if (!field_record_decl)
7522 continue;
7523
7524 for (clang::RecordDecl::decl_iterator
7525 di = field_record_decl->decls_begin(),
7526 de = field_record_decl->decls_end();
7527 di != de; ++di) {
7528 if (clang::FieldDecl *nested_field_decl =
7529 llvm::dyn_cast<clang::FieldDecl>(*di)) {
7530 clang::NamedDecl **chain =
7531 new (ast->getASTContext()) clang::NamedDecl *[2];
7532 chain[0] = *field_pos;
7533 chain[1] = nested_field_decl;
7534 clang::IndirectFieldDecl *indirect_field =
7535 clang::IndirectFieldDecl::Create(
7536 ast->getASTContext(), record_decl, clang::SourceLocation(),
7537 nested_field_decl->getIdentifier(),
7538 nested_field_decl->getType(), {chain, 2});
7539 SetMemberOwningModule(indirect_field, record_decl);
7540
7541 indirect_field->setImplicit();
7542
7543 indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7544 field_pos->getAccess(), nested_field_decl->getAccess()));
7545
7546 indirect_fields.push_back(indirect_field);
7547 } else if (clang::IndirectFieldDecl *nested_indirect_field_decl =
7548 llvm::dyn_cast<clang::IndirectFieldDecl>(*di)) {
7549 size_t nested_chain_size =
7550 nested_indirect_field_decl->getChainingSize();
7551 clang::NamedDecl **chain = new (ast->getASTContext())
7552 clang::NamedDecl *[nested_chain_size + 1];
7553 chain[0] = *field_pos;
7554
7555 int chain_index = 1;
7556 for (clang::IndirectFieldDecl::chain_iterator
7557 nci = nested_indirect_field_decl->chain_begin(),
7558 nce = nested_indirect_field_decl->chain_end();
7559 nci < nce; ++nci) {
7560 chain[chain_index] = *nci;
7561 chain_index++;
7562 }
7563
7564 clang::IndirectFieldDecl *indirect_field =
7565 clang::IndirectFieldDecl::Create(
7566 ast->getASTContext(), record_decl, clang::SourceLocation(),
7567 nested_indirect_field_decl->getIdentifier(),
7568 nested_indirect_field_decl->getType(),
7569 {chain, nested_chain_size + 1});
7570 SetMemberOwningModule(indirect_field, record_decl);
7571
7572 indirect_field->setImplicit();
7573
7574 indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7575 field_pos->getAccess(), nested_indirect_field_decl->getAccess()));
7576
7577 indirect_fields.push_back(indirect_field);
7578 }
7579 }
7580 }
7581 }
7582
7583 // Check the last field to see if it has an incomplete array type as its last
7584 // member and if it does, the tell the record decl about it
7585 if (last_field_pos != field_end_pos) {
7586 if (last_field_pos->getType()->isIncompleteArrayType())
7587 record_decl->hasFlexibleArrayMember();
7588 }
7589
7590 for (IndirectFieldVector::iterator ifi = indirect_fields.begin(),
7591 ife = indirect_fields.end();
7592 ifi < ife; ++ifi) {
7593 record_decl->addDecl(*ifi);
7594 }
7595}
7596
7597void TypeSystemClang::SetIsPacked(const CompilerType &type) {
7598 if (type) {
7599 auto ts = type.GetTypeSystem();
7600 auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7601 if (ast) {
7602 clang::RecordDecl *record_decl = GetAsRecordDecl(type);
7603
7604 if (!record_decl)
7605 return;
7606
7607 record_decl->addAttr(
7608 clang::PackedAttr::CreateImplicit(ast->getASTContext()));
7609 }
7610 }
7611}
7612
7613clang::VarDecl *TypeSystemClang::AddVariableToRecordType(
7614 const CompilerType &type, llvm::StringRef name,
7615 const CompilerType &var_type, AccessType access) {
7616 if (!type.IsValid() || !var_type.IsValid())
7617 return nullptr;
7618
7619 auto ts = type.GetTypeSystem();
7620 auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7621 if (!ast)
7622 return nullptr;
7623
7624 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7625 if (!record_decl)
7626 return nullptr;
7627
7628 clang::VarDecl *var_decl = nullptr;
7629 clang::IdentifierInfo *ident = nullptr;
7630 if (!name.empty())
7631 ident = &ast->getASTContext().Idents.get(name);
7632
7633 var_decl = clang::VarDecl::CreateDeserialized(ast->getASTContext(), 0);
7634 var_decl->setDeclContext(record_decl);
7635 var_decl->setDeclName(ident);
7636 var_decl->setType(ClangUtil::GetQualType(var_type));
7637 var_decl->setStorageClass(clang::SC_Static);
7638 SetMemberOwningModule(var_decl, record_decl);
7639 if (!var_decl)
7640 return nullptr;
7641
7642 var_decl->setAccess(
7643 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access));
7644 record_decl->addDecl(var_decl);
7645
7646 VerifyDecl(var_decl);
7647
7648 return var_decl;
7649}
7650
7651void TypeSystemClang::SetIntegerInitializerForVariable(
7652 VarDecl *var, const llvm::APInt &init_value) {
7653 assert(!var->hasInit() && "variable already initialized")(static_cast <bool> (!var->hasInit() && "variable already initialized"
) ? void (0) : __assert_fail ("!var->hasInit() && \"variable already initialized\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7653, __extension__ __PRETTY_FUNCTION__))
;
7654
7655 clang::ASTContext &ast = var->getASTContext();
7656 QualType qt = var->getType();
7657 assert(qt->isIntegralOrEnumerationType() &&(static_cast <bool> (qt->isIntegralOrEnumerationType
() && "only integer or enum types supported") ? void (
0) : __assert_fail ("qt->isIntegralOrEnumerationType() && \"only integer or enum types supported\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7658, __extension__ __PRETTY_FUNCTION__))
7658 "only integer or enum types supported")(static_cast <bool> (qt->isIntegralOrEnumerationType
() && "only integer or enum types supported") ? void (
0) : __assert_fail ("qt->isIntegralOrEnumerationType() && \"only integer or enum types supported\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7658, __extension__ __PRETTY_FUNCTION__))
;
7659 // If the variable is an enum type, take the underlying integer type as
7660 // the type of the integer literal.
7661 if (const EnumType *enum_type = qt->getAs<EnumType>()) {
7662 const EnumDecl *enum_decl = enum_type->getDecl();
7663 qt = enum_decl->getIntegerType();
7664 }
7665 // Bools are handled separately because the clang AST printer handles bools
7666 // separately from other integral types.
7667 if (qt->isSpecificBuiltinType(BuiltinType::Bool)) {
7668 var->setInit(CXXBoolLiteralExpr::Create(
7669 ast, !init_value.isZero(), qt.getUnqualifiedType(), SourceLocation()));
7670 } else {
7671 var->setInit(IntegerLiteral::Create(
7672 ast, init_value, qt.getUnqualifiedType(), SourceLocation()));
7673 }
7674}
7675
7676void TypeSystemClang::SetFloatingInitializerForVariable(
7677 clang::VarDecl *var, const llvm::APFloat &init_value) {
7678 assert(!var->hasInit() && "variable already initialized")(static_cast <bool> (!var->hasInit() && "variable already initialized"
) ? void (0) : __assert_fail ("!var->hasInit() && \"variable already initialized\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7678, __extension__ __PRETTY_FUNCTION__))
;
7679
7680 clang::ASTContext &ast = var->getASTContext();
7681 QualType qt = var->getType();
7682 assert(qt->isFloatingType() && "only floating point types supported")(static_cast <bool> (qt->isFloatingType() &&
"only floating point types supported") ? void (0) : __assert_fail
("qt->isFloatingType() && \"only floating point types supported\""
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
7682, __extension__ __PRETTY_FUNCTION__))
;
7683 var->setInit(FloatingLiteral::Create(
7684 ast, init_value, true, qt.getUnqualifiedType(), SourceLocation()));
7685}
7686
7687clang::CXXMethodDecl *TypeSystemClang::AddMethodToCXXRecordType(
7688 lldb::opaque_compiler_type_t type, llvm::StringRef name,
7689 const char *mangled_name, const CompilerType &method_clang_type,
7690 lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline,
7691 bool is_explicit, bool is_attr_used, bool is_artificial) {
7692 if (!type || !method_clang_type.IsValid() || name.empty())
7693 return nullptr;
7694
7695 clang::QualType record_qual_type(GetCanonicalQualType(type));
7696
7697 clang::CXXRecordDecl *cxx_record_decl =
7698 record_qual_type->getAsCXXRecordDecl();
7699
7700 if (cxx_record_decl == nullptr)
7701 return nullptr;
7702
7703 clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
7704
7705 clang::CXXMethodDecl *cxx_method_decl = nullptr;
7706
7707 clang::DeclarationName decl_name(&getASTContext().Idents.get(name));
7708
7709 const clang::FunctionType *function_type =
7710 llvm::dyn_cast<clang::FunctionType>(method_qual_type.getTypePtr());
7711
7712 if (function_type == nullptr)
7713 return nullptr;
7714
7715 const clang::FunctionProtoType *method_function_prototype(
7716 llvm::dyn_cast<clang::FunctionProtoType>(function_type));
7717
7718 if (!method_function_prototype)
7719 return nullptr;
7720
7721 unsigned int num_params = method_function_prototype->getNumParams();
7722
7723 clang::CXXDestructorDecl *cxx_dtor_decl(nullptr);
7724 clang::CXXConstructorDecl *cxx_ctor_decl(nullptr);
7725
7726 if (is_artificial)
7727 return nullptr; // skip everything artificial
7728
7729 const clang::ExplicitSpecifier explicit_spec(
7730 nullptr /*expr*/, is_explicit ? clang::ExplicitSpecKind::ResolvedTrue
7731 : clang::ExplicitSpecKind::ResolvedFalse);
7732
7733 if (name.startswith("~")) {
7734 cxx_dtor_decl =
7735 clang::CXXDestructorDecl::CreateDeserialized(getASTContext(), 0);
7736 cxx_dtor_decl->setDeclContext(cxx_record_decl);
7737 cxx_dtor_decl->setDeclName(
7738 getASTContext().DeclarationNames.getCXXDestructorName(
7739 getASTContext().getCanonicalType(record_qual_type)));
7740 cxx_dtor_decl->setType(method_qual_type);
7741 cxx_dtor_decl->setImplicit(is_artificial);
7742 cxx_dtor_decl->setInlineSpecified(is_inline);
7743 cxx_dtor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7744 cxx_method_decl = cxx_dtor_decl;
7745 } else if (decl_name == cxx_record_decl->getDeclName()) {
7746 cxx_ctor_decl = clang::CXXConstructorDecl::CreateDeserialized(
7747 getASTContext(), 0, 0);
7748 cxx_ctor_decl->setDeclContext(cxx_record_decl);
7749 cxx_ctor_decl->setDeclName(
7750 getASTContext().DeclarationNames.getCXXConstructorName(
7751 getASTContext().getCanonicalType(record_qual_type)));
7752 cxx_ctor_decl->setType(method_qual_type);
7753 cxx_ctor_decl->setImplicit(is_artificial);
7754 cxx_ctor_decl->setInlineSpecified(is_inline);
7755 cxx_ctor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7756 cxx_ctor_decl->setNumCtorInitializers(0);
7757 cxx_ctor_decl->setExplicitSpecifier(explicit_spec);
7758 cxx_method_decl = cxx_ctor_decl;
7759 } else {
7760 clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None;
7761 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
7762
7763 if (IsOperator(name, op_kind)) {
7764 if (op_kind != clang::NUM_OVERLOADED_OPERATORS) {
7765 // Check the number of operator parameters. Sometimes we have seen bad
7766 // DWARF that doesn't correctly describe operators and if we try to
7767 // create a method and add it to the class, clang will assert and
7768 // crash, so we need to make sure things are acceptable.
7769 const bool is_method = true;
7770 if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
7771 is_method, op_kind, num_params))
7772 return nullptr;
7773 cxx_method_decl =
7774 clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0);
7775 cxx_method_decl->setDeclContext(cxx_record_decl);
7776 cxx_method_decl->setDeclName(
7777 getASTContext().DeclarationNames.getCXXOperatorName(op_kind));
7778 cxx_method_decl->setType(method_qual_type);
7779 cxx_method_decl->setStorageClass(SC);
7780 cxx_method_decl->setInlineSpecified(is_inline);
7781 cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7782 } else if (num_params == 0) {
7783 // Conversion operators don't take params...
7784 auto *cxx_conversion_decl =
7785 clang::CXXConversionDecl::CreateDeserialized(getASTContext(), 0);
7786 cxx_conversion_decl->setDeclContext(cxx_record_decl);
7787 cxx_conversion_decl->setDeclName(
7788 getASTContext().DeclarationNames.getCXXConversionFunctionName(
7789 getASTContext().getCanonicalType(
7790 function_type->getReturnType())));
7791 cxx_conversion_decl->setType(method_qual_type);
7792 cxx_conversion_decl->setInlineSpecified(is_inline);
7793 cxx_conversion_decl->setExplicitSpecifier(explicit_spec);
7794 cxx_conversion_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7795 cxx_method_decl = cxx_conversion_decl;
7796 }
7797 }
7798
7799 if (cxx_method_decl == nullptr) {
7800 cxx_method_decl =
7801 clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0);
7802 cxx_method_decl->setDeclContext(cxx_record_decl);
7803 cxx_method_decl->setDeclName(decl_name);
7804 cxx_method_decl->setType(method_qual_type);
7805 cxx_method_decl->setInlineSpecified(is_inline);
7806 cxx_method_decl->setStorageClass(SC);
7807 cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7808 }
7809 }
7810 SetMemberOwningModule(cxx_method_decl, cxx_record_decl);
7811
7812 clang::AccessSpecifier access_specifier =
7813 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access);
7814
7815 cxx_method_decl->setAccess(access_specifier);
7816 cxx_method_decl->setVirtualAsWritten(is_virtual);
7817
7818 if (is_attr_used)
7819 cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(getASTContext()));
7820
7821 if (mangled_name != nullptr) {
7822 cxx_method_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
7823 getASTContext(), mangled_name, /*literal=*/false));
7824 }
7825
7826 // Populate the method decl with parameter decls
7827
7828 llvm::SmallVector<clang::ParmVarDecl *, 12> params;
7829
7830 for (unsigned param_index = 0; param_index < num_params; ++param_index) {
7831 params.push_back(clang::ParmVarDecl::Create(
7832 getASTContext(), cxx_method_decl, clang::SourceLocation(),
7833 clang::SourceLocation(),
7834 nullptr, // anonymous
7835 method_function_prototype->getParamType(param_index), nullptr,
7836 clang::SC_None, nullptr));
7837 }
7838
7839 cxx_method_decl->setParams(llvm::ArrayRef<clang::ParmVarDecl *>(params));
7840
7841 AddAccessSpecifierDecl(cxx_record_decl, getASTContext(),
7842 GetCXXRecordDeclAccess(cxx_record_decl),
7843 access_specifier);
7844 SetCXXRecordDeclAccess(cxx_record_decl, access_specifier);
7845
7846 cxx_record_decl->addDecl(cxx_method_decl);
7847
7848 // Sometimes the debug info will mention a constructor (default/copy/move),
7849 // destructor, or assignment operator (copy/move) but there won't be any
7850 // version of this in the code. So we check if the function was artificially
7851 // generated and if it is trivial and this lets the compiler/backend know
7852 // that it can inline the IR for these when it needs to and we can avoid a
7853 // "missing function" error when running expressions.
7854
7855 if (is_artificial) {
7856 if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() &&
7857 cxx_record_decl->hasTrivialDefaultConstructor()) ||
7858 (cxx_ctor_decl->isCopyConstructor() &&
7859 cxx_record_decl->hasTrivialCopyConstructor()) ||
7860 (cxx_ctor_decl->isMoveConstructor() &&
7861 cxx_record_decl->hasTrivialMoveConstructor()))) {
7862 cxx_ctor_decl->setDefaulted();
7863 cxx_ctor_decl->setTrivial(true);
7864 } else if (cxx_dtor_decl) {
7865 if (cxx_record_decl->hasTrivialDestructor()) {
7866 cxx_dtor_decl->setDefaulted();
7867 cxx_dtor_decl->setTrivial(true);
7868 }
7869 } else if ((cxx_method_decl->isCopyAssignmentOperator() &&
7870 cxx_record_decl->hasTrivialCopyAssignment()) ||
7871 (cxx_method_decl->isMoveAssignmentOperator() &&
7872 cxx_record_decl->hasTrivialMoveAssignment())) {
7873 cxx_method_decl->setDefaulted();
7874 cxx_method_decl->setTrivial(true);
7875 }
7876 }
7877
7878 VerifyDecl(cxx_method_decl);
7879
7880 return cxx_method_decl;
7881}
7882
7883void TypeSystemClang::AddMethodOverridesForCXXRecordType(
7884 lldb::opaque_compiler_type_t type) {
7885 if (auto *record = GetAsCXXRecordDecl(type))
7886 for (auto *method : record->methods())
7887 addOverridesForMethod(method);
7888}
7889
7890#pragma mark C++ Base Classes
7891
7892std::unique_ptr<clang::CXXBaseSpecifier>
7893TypeSystemClang::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
7894 AccessType access, bool is_virtual,
7895 bool base_of_class) {
7896 if (!type)
7897 return nullptr;
7898
7899 return std::make_unique<clang::CXXBaseSpecifier>(
7900 clang::SourceRange(), is_virtual, base_of_class,
7901 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access),
7902 getASTContext().getTrivialTypeSourceInfo(GetQualType(type)),
7903 clang::SourceLocation());
7904}
7905
7906bool TypeSystemClang::TransferBaseClasses(
7907 lldb::opaque_compiler_type_t type,
7908 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases) {
7909 if (!type)
7910 return false;
7911 clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type);
7912 if (!cxx_record_decl)
7913 return false;
7914 std::vector<clang::CXXBaseSpecifier *> raw_bases;
7915 raw_bases.reserve(bases.size());
7916
7917 // Clang will make a copy of them, so it's ok that we pass pointers that we're
7918 // about to destroy.
7919 for (auto &b : bases)
7920 raw_bases.push_back(b.get());
7921 cxx_record_decl->setBases(raw_bases.data(), raw_bases.size());
7922 return true;
7923}
7924
7925bool TypeSystemClang::SetObjCSuperClass(
7926 const CompilerType &type, const CompilerType &superclass_clang_type) {
7927 auto ts = type.GetTypeSystem();
7928 auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7929 if (!ast)
7930 return false;
7931 clang::ASTContext &clang_ast = ast->getASTContext();
7932
7933 if (type && superclass_clang_type.IsValid() &&
7934 superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) {
7935 clang::ObjCInterfaceDecl *class_interface_decl =
7936 GetAsObjCInterfaceDecl(type);
7937 clang::ObjCInterfaceDecl *super_interface_decl =
7938 GetAsObjCInterfaceDecl(superclass_clang_type);
7939 if (class_interface_decl && super_interface_decl) {
7940 class_interface_decl->setSuperClass(clang_ast.getTrivialTypeSourceInfo(
7941 clang_ast.getObjCInterfaceType(super_interface_decl)));
7942 return true;
7943 }
7944 }
7945 return false;
7946}
7947
7948bool TypeSystemClang::AddObjCClassProperty(
7949 const CompilerType &type, const char *property_name,
7950 const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl,
7951 const char *property_setter_name, const char *property_getter_name,
7952 uint32_t property_attributes, ClangASTMetadata *metadata) {
7953 if (!type || !property_clang_type.IsValid() || property_name == nullptr ||
7954 property_name[0] == '\0')
7955 return false;
7956 auto ts = type.GetTypeSystem();
7957 auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7958 if (!ast)
7959 return false;
7960 clang::ASTContext &clang_ast = ast->getASTContext();
7961
7962 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7963 if (!class_interface_decl)
7964 return false;
7965
7966 CompilerType property_clang_type_to_access;
7967
7968 if (property_clang_type.IsValid())
7969 property_clang_type_to_access = property_clang_type;
7970 else if (ivar_decl)
7971 property_clang_type_to_access = ast->GetType(ivar_decl->getType());
7972
7973 if (!class_interface_decl || !property_clang_type_to_access.IsValid())
7974 return false;
7975
7976 clang::TypeSourceInfo *prop_type_source;
7977 if (ivar_decl)
7978 prop_type_source = clang_ast.getTrivialTypeSourceInfo(ivar_decl->getType());
7979 else
7980 prop_type_source = clang_ast.getTrivialTypeSourceInfo(
7981 ClangUtil::GetQualType(property_clang_type));
7982
7983 clang::ObjCPropertyDecl *property_decl =
7984 clang::ObjCPropertyDecl::CreateDeserialized(clang_ast, 0);
7985 property_decl->setDeclContext(class_interface_decl);
7986 property_decl->setDeclName(&clang_ast.Idents.get(property_name));
7987 property_decl->setType(ivar_decl
7988 ? ivar_decl->getType()
7989 : ClangUtil::GetQualType(property_clang_type),
7990 prop_type_source);
7991 SetMemberOwningModule(property_decl, class_interface_decl);
7992
7993 if (!property_decl)
7994 return false;
7995
7996 if (metadata)
7997 ast->SetMetadata(property_decl, *metadata);
7998
7999 class_interface_decl->addDecl(property_decl);
8000
8001 clang::Selector setter_sel, getter_sel;
8002
8003 if (property_setter_name) {
8004 std::string property_setter_no_colon(property_setter_name,
8005 strlen(property_setter_name) - 1);
8006 clang::IdentifierInfo *setter_ident =
8007 &clang_ast.Idents.get(property_setter_no_colon);
8008 setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
8009 } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) {
8010 std::string setter_sel_string("set");
8011 setter_sel_string.push_back(::toupper(property_name[0]));
8012 setter_sel_string.append(&property_name[1]);
8013 clang::IdentifierInfo *setter_ident =
8014 &clang_ast.Idents.get(setter_sel_string);
8015 setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
8016 }
8017 property_decl->setSetterName(setter_sel);
8018 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_setter);
8019
8020 if (property_getter_name != nullptr) {
8021 clang::IdentifierInfo *getter_ident =
8022 &clang_ast.Idents.get(property_getter_name);
8023 getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
8024 } else {
8025 clang::IdentifierInfo *getter_ident = &clang_ast.Idents.get(property_name);
8026 getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
8027 }
8028 property_decl->setGetterName(getter_sel);
8029 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_getter);
8030
8031 if (ivar_decl)
8032 property_decl->setPropertyIvarDecl(ivar_decl);
8033
8034 if (property_attributes & DW_APPLE_PROPERTY_readonly)
8035 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readonly);
8036 if (property_attributes & DW_APPLE_PROPERTY_readwrite)
8037 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite);
8038 if (property_attributes & DW_APPLE_PROPERTY_assign)
8039 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
8040 if (property_attributes & DW_APPLE_PROPERTY_retain)
8041 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_retain);
8042 if (property_attributes & DW_APPLE_PROPERTY_copy)
8043 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_copy);
8044 if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
8045 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic);
8046 if (property_attributes & ObjCPropertyAttribute::kind_nullability)
8047 property_decl->setPropertyAttributes(
8048 ObjCPropertyAttribute::kind_nullability);
8049 if (property_attributes & ObjCPropertyAttribute::kind_null_resettable)
8050 property_decl->setPropertyAttributes(
8051 ObjCPropertyAttribute::kind_null_resettable);
8052 if (property_attributes & ObjCPropertyAttribute::kind_class)
8053 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_class);
8054
8055 const bool isInstance =
8056 (property_attributes & ObjCPropertyAttribute::kind_class) == 0;
8057
8058 clang::ObjCMethodDecl *getter = nullptr;
8059 if (!getter_sel.isNull())
8060 getter = isInstance ? class_interface_decl->lookupInstanceMethod(getter_sel)
8061 : class_interface_decl->lookupClassMethod(getter_sel);
8062 if (!getter_sel.isNull() && !getter) {
8063 const bool isVariadic = false;
8064 const bool isPropertyAccessor = true;
8065 const bool isSynthesizedAccessorStub = false;
8066 const bool isImplicitlyDeclared = true;
8067 const bool isDefined = false;
8068 const clang::ObjCMethodDecl::ImplementationControl impControl =
8069 clang::ObjCMethodDecl::None;
8070 const bool HasRelatedResultType = false;
8071
8072 getter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0);
8073 getter->setDeclName(getter_sel);
8074 getter->setReturnType(ClangUtil::GetQualType(property_clang_type_to_access));
8075 getter->setDeclContext(class_interface_decl);
8076 getter->setInstanceMethod(isInstance);
8077 getter->setVariadic(isVariadic);
8078 getter->setPropertyAccessor(isPropertyAccessor);
8079 getter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8080 getter->setImplicit(isImplicitlyDeclared);
8081 getter->setDefined(isDefined);
8082 getter->setDeclImplementation(impControl);
8083 getter->setRelatedResultType(HasRelatedResultType);
8084 SetMemberOwningModule(getter, class_interface_decl);
8085
8086 if (getter) {
8087 if (metadata)
8088 ast->SetMetadata(getter, *metadata);
8089
8090 getter->setMethodParams(clang_ast, llvm::ArrayRef<clang::ParmVarDecl *>(),
8091 llvm::ArrayRef<clang::SourceLocation>());
8092 class_interface_decl->addDecl(getter);
8093 }
8094 }
8095 if (getter) {
8096 getter->setPropertyAccessor(true);
8097 property_decl->setGetterMethodDecl(getter);
8098 }
8099
8100 clang::ObjCMethodDecl *setter = nullptr;
8101 setter = isInstance ? class_interface_decl->lookupInstanceMethod(setter_sel)
8102 : class_interface_decl->lookupClassMethod(setter_sel);
8103 if (!setter_sel.isNull() && !setter) {
8104 clang::QualType result_type = clang_ast.VoidTy;
8105 const bool isVariadic = false;
8106 const bool isPropertyAccessor = true;
8107 const bool isSynthesizedAccessorStub = false;
8108 const bool isImplicitlyDeclared = true;
8109 const bool isDefined = false;
8110 const clang::ObjCMethodDecl::ImplementationControl impControl =
8111 clang::ObjCMethodDecl::None;
8112 const bool HasRelatedResultType = false;
8113
8114 setter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0);
8115 setter->setDeclName(setter_sel);
8116 setter->setReturnType(result_type);
8117 setter->setDeclContext(class_interface_decl);
8118 setter->setInstanceMethod(isInstance);
8119 setter->setVariadic(isVariadic);
8120 setter->setPropertyAccessor(isPropertyAccessor);
8121 setter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8122 setter->setImplicit(isImplicitlyDeclared);
8123 setter->setDefined(isDefined);
8124 setter->setDeclImplementation(impControl);
8125 setter->setRelatedResultType(HasRelatedResultType);
8126 SetMemberOwningModule(setter, class_interface_decl);
8127
8128 if (setter) {
8129 if (metadata)
8130 ast->SetMetadata(setter, *metadata);
8131
8132 llvm::SmallVector<clang::ParmVarDecl *, 1> params;
8133 params.push_back(clang::ParmVarDecl::Create(
8134 clang_ast, setter, clang::SourceLocation(), clang::SourceLocation(),
8135 nullptr, // anonymous
8136 ClangUtil::GetQualType(property_clang_type_to_access), nullptr,
8137 clang::SC_Auto, nullptr));
8138
8139 setter->setMethodParams(clang_ast,
8140 llvm::ArrayRef<clang::ParmVarDecl *>(params),
8141 llvm::ArrayRef<clang::SourceLocation>());
8142
8143 class_interface_decl->addDecl(setter);
8144 }
8145 }
8146 if (setter) {
8147 setter->setPropertyAccessor(true);
8148 property_decl->setSetterMethodDecl(setter);
8149 }
8150
8151 return true;
8152}
8153
8154bool TypeSystemClang::IsObjCClassTypeAndHasIVars(const CompilerType &type,
8155 bool check_superclass) {
8156 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8157 if (class_interface_decl)
8158 return ObjCDeclHasIVars(class_interface_decl, check_superclass);
8159 return false;
8160}
8161
8162clang::ObjCMethodDecl *TypeSystemClang::AddMethodToObjCObjectType(
8163 const CompilerType &type,
8164 const char *name, // the full symbol name as seen in the symbol table
8165 // (lldb::opaque_compiler_type_t type, "-[NString
8166 // stringWithCString:]")
8167 const CompilerType &method_clang_type, lldb::AccessType access,
8168 bool is_artificial, bool is_variadic, bool is_objc_direct_call) {
8169 if (!type || !method_clang_type.IsValid())
8170 return nullptr;
8171
8172 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8173
8174 if (class_interface_decl == nullptr)
8175 return nullptr;
8176 auto ts = type.GetTypeSystem();
8177 auto lldb_ast = ts.dyn_cast_or_null<TypeSystemClang>();
8178 if (lldb_ast == nullptr)
8179 return nullptr;
8180 clang::ASTContext &ast = lldb_ast->getASTContext();
8181
8182 const char *selector_start = ::strchr(name, ' ');
8183 if (selector_start == nullptr)
8184 return nullptr;
8185
8186 selector_start++;
8187 llvm::SmallVector<clang::IdentifierInfo *, 12> selector_idents;
8188
8189 size_t len = 0;
8190 const char *start;
8191
8192 unsigned num_selectors_with_args = 0;
8193 for (start = selector_start; start && *start != '\0' && *start != ']';
8194 start += len) {
8195 len = ::strcspn(start, ":]");
8196 bool has_arg = (start[len] == ':');
8197 if (has_arg)
8198 ++num_selectors_with_args;
8199 selector_idents.push_back(&ast.Idents.get(llvm::StringRef(start, len)));
8200 if (has_arg)
8201 len += 1;
8202 }
8203
8204 if (selector_idents.size() == 0)
8205 return nullptr;
8206
8207 clang::Selector method_selector = ast.Selectors.getSelector(
8208 num_selectors_with_args ? selector_idents.size() : 0,
8209 selector_idents.data());
8210
8211 clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
8212
8213 // Populate the method decl with parameter decls
8214 const clang::Type *method_type(method_qual_type.getTypePtr());
8215
8216 if (method_type == nullptr)
8217 return nullptr;
8218
8219 const clang::FunctionProtoType *method_function_prototype(
8220 llvm::dyn_cast<clang::FunctionProtoType>(method_type));
8221
8222 if (!method_function_prototype)
8223 return nullptr;
8224
8225 const bool isInstance = (name[0] == '-');
8226 const bool isVariadic = is_variadic;
8227 const bool isPropertyAccessor = false;
8228 const bool isSynthesizedAccessorStub = false;
8229 /// Force this to true because we don't have source locations.
8230 const bool isImplicitlyDeclared = true;
8231 const bool isDefined = false;
8232 const clang::ObjCMethodDecl::ImplementationControl impControl =
8233 clang::ObjCMethodDecl::None;
8234 const bool HasRelatedResultType = false;
8235
8236 const unsigned num_args = method_function_prototype->getNumParams();
8237
8238 if (num_args != num_selectors_with_args)
8239 return nullptr; // some debug information is corrupt. We are not going to
8240 // deal with it.
8241
8242 auto *objc_method_decl = clang::ObjCMethodDecl::CreateDeserialized(ast, 0);
8243 objc_method_decl->setDeclName(method_selector);
8244 objc_method_decl->setReturnType(method_function_prototype->getReturnType());
8245 objc_method_decl->setDeclContext(
8246 lldb_ast->GetDeclContextForType(ClangUtil::GetQualType(type)));
8247 objc_method_decl->setInstanceMethod(isInstance);
8248 objc_method_decl->setVariadic(isVariadic);
8249 objc_method_decl->setPropertyAccessor(isPropertyAccessor);
8250 objc_method_decl->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8251 objc_method_decl->setImplicit(isImplicitlyDeclared);
8252 objc_method_decl->setDefined(isDefined);
8253 objc_method_decl->setDeclImplementation(impControl);
8254 objc_method_decl->setRelatedResultType(HasRelatedResultType);
8255 SetMemberOwningModule(objc_method_decl, class_interface_decl);
8256
8257 if (objc_method_decl == nullptr)
8258 return nullptr;
8259
8260 if (num_args > 0) {
8261 llvm::SmallVector<clang::ParmVarDecl *, 12> params;
8262
8263 for (unsigned param_index = 0; param_index < num_args; ++param_index) {
8264 params.push_back(clang::ParmVarDecl::Create(
8265 ast, objc_method_decl, clang::SourceLocation(),
8266 clang::SourceLocation(),
8267 nullptr, // anonymous
8268 method_function_prototype->getParamType(param_index), nullptr,
8269 clang::SC_Auto, nullptr));
8270 }
8271
8272 objc_method_decl->setMethodParams(
8273 ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
8274 llvm::ArrayRef<clang::SourceLocation>());
8275 }
8276
8277 if (is_objc_direct_call) {
8278 // Add a the objc_direct attribute to the declaration we generate that
8279 // we generate a direct method call for this ObjCMethodDecl.
8280 objc_method_decl->addAttr(
8281 clang::ObjCDirectAttr::CreateImplicit(ast, SourceLocation()));
8282 // Usually Sema is creating implicit parameters (e.g., self) when it
8283 // parses the method. We don't have a parsing Sema when we build our own
8284 // AST here so we manually need to create these implicit parameters to
8285 // make the direct call code generation happy.
8286 objc_method_decl->createImplicitParams(ast, class_interface_decl);
8287 }
8288
8289 class_interface_decl->addDecl(objc_method_decl);
8290
8291 VerifyDecl(objc_method_decl);
8292
8293 return objc_method_decl;
8294}
8295
8296bool TypeSystemClang::SetHasExternalStorage(lldb::opaque_compiler_type_t type,
8297 bool has_extern) {
8298 if (!type)
8299 return false;
8300
8301 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
8302
8303 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8304 switch (type_class) {
8305 case clang::Type::Record: {
8306 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
8307 if (cxx_record_decl) {
8308 cxx_record_decl->setHasExternalLexicalStorage(has_extern);
8309 cxx_record_decl->setHasExternalVisibleStorage(has_extern);
8310 return true;
8311 }
8312 } break;
8313
8314 case clang::Type::Enum: {
8315 clang::EnumDecl *enum_decl =
8316 llvm::cast<clang::EnumType>(qual_type)->getDecl();
8317 if (enum_decl) {
8318 enum_decl->setHasExternalLexicalStorage(has_extern);
8319 enum_decl->setHasExternalVisibleStorage(has_extern);
8320 return true;
8321 }
8322 } break;
8323
8324 case clang::Type::ObjCObject:
8325 case clang::Type::ObjCInterface: {
8326 const clang::ObjCObjectType *objc_class_type =
8327 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8328 assert(objc_class_type)(static_cast <bool> (objc_class_type) ? void (0) : __assert_fail
("objc_class_type", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 8328, __extension__ __PRETTY_FUNCTION__))
;
8329 if (objc_class_type) {
8330 clang::ObjCInterfaceDecl *class_interface_decl =
8331 objc_class_type->getInterface();
8332
8333 if (class_interface_decl) {
8334 class_interface_decl->setHasExternalLexicalStorage(has_extern);
8335 class_interface_decl->setHasExternalVisibleStorage(has_extern);
8336 return true;
8337 }
8338 }
8339 } break;
8340
8341 default:
8342 break;
8343 }
8344 return false;
8345}
8346
8347#pragma mark TagDecl
8348
8349bool TypeSystemClang::StartTagDeclarationDefinition(const CompilerType &type) {
8350 clang::QualType qual_type(ClangUtil::GetQualType(type));
8351 if (!qual_type.isNull()) {
8352 const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8353 if (tag_type) {
8354 clang::TagDecl *tag_decl = tag_type->getDecl();
8355 if (tag_decl) {
8356 tag_decl->startDefinition();
8357 return true;
8358 }
8359 }
8360
8361 const clang::ObjCObjectType *object_type =
8362 qual_type->getAs<clang::ObjCObjectType>();
8363 if (object_type) {
8364 clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface();
8365 if (interface_decl) {
8366 interface_decl->startDefinition();
8367 return true;
8368 }
8369 }
8370 }
8371 return false;
8372}
8373
8374bool TypeSystemClang::CompleteTagDeclarationDefinition(
8375 const CompilerType &type) {
8376 clang::QualType qual_type(ClangUtil::GetQualType(type));
8377 if (qual_type.isNull())
8378 return false;
8379
8380 auto ts = type.GetTypeSystem();
8381 auto lldb_ast = ts.dyn_cast_or_null<TypeSystemClang>();
8382 if (lldb_ast == nullptr)
8383 return false;
8384
8385 // Make sure we use the same methodology as
8386 // TypeSystemClang::StartTagDeclarationDefinition() as to how we start/end
8387 // the definition.
8388 const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8389 if (tag_type) {
8390 clang::TagDecl *tag_decl = tag_type->getDecl();
8391
8392 if (auto *cxx_record_decl = llvm::dyn_cast<CXXRecordDecl>(tag_decl)) {
8393 // If we have a move constructor declared but no copy constructor we
8394 // need to explicitly mark it as deleted. Usually Sema would do this for
8395 // us in Sema::DeclareImplicitCopyConstructor but we don't have a Sema
8396 // when building an AST from debug information.
8397 // See also:
8398 // C++11 [class.copy]p7, p18:
8399 // If the class definition declares a move constructor or move assignment
8400 // operator, an implicitly declared copy constructor or copy assignment
8401 // operator is defined as deleted.
8402 if (cxx_record_decl->hasUserDeclaredMoveConstructor() ||
8403 cxx_record_decl->hasUserDeclaredMoveAssignment()) {
8404 if (cxx_record_decl->needsImplicitCopyConstructor())
8405 cxx_record_decl->setImplicitCopyConstructorIsDeleted();
8406 if (cxx_record_decl->needsImplicitCopyAssignment())
8407 cxx_record_decl->setImplicitCopyAssignmentIsDeleted();
8408 }
8409
8410 if (!cxx_record_decl->isCompleteDefinition())
8411 cxx_record_decl->completeDefinition();
8412 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
8413 cxx_record_decl->setHasExternalLexicalStorage(false);
8414 cxx_record_decl->setHasExternalVisibleStorage(false);
8415 lldb_ast->SetCXXRecordDeclAccess(cxx_record_decl,
8416 clang::AccessSpecifier::AS_none);
8417 return true;
8418 }
8419 }
8420
8421 const clang::EnumType *enutype = qual_type->getAs<clang::EnumType>();
8422
8423 if (!enutype)
8424 return false;
8425 clang::EnumDecl *enum_decl = enutype->getDecl();
8426
8427 if (enum_decl->isCompleteDefinition())
8428 return true;
8429
8430 clang::ASTContext &ast = lldb_ast->getASTContext();
8431
8432 /// TODO This really needs to be fixed.
8433
8434 QualType integer_type(enum_decl->getIntegerType());
8435 if (!integer_type.isNull()) {
8436 unsigned NumPositiveBits = 1;
8437 unsigned NumNegativeBits = 0;
8438
8439 clang::QualType promotion_qual_type;
8440 // If the enum integer type is less than an integer in bit width,
8441 // then we must promote it to an integer size.
8442 if (ast.getTypeSize(enum_decl->getIntegerType()) <
8443 ast.getTypeSize(ast.IntTy)) {
8444 if (enum_decl->getIntegerType()->isSignedIntegerType())
8445 promotion_qual_type = ast.IntTy;
8446 else
8447 promotion_qual_type = ast.UnsignedIntTy;
8448 } else
8449 promotion_qual_type = enum_decl->getIntegerType();
8450
8451 enum_decl->completeDefinition(enum_decl->getIntegerType(),
8452 promotion_qual_type, NumPositiveBits,
8453 NumNegativeBits);
8454 }
8455 return true;
8456}
8457
8458clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8459 const CompilerType &enum_type, const Declaration &decl, const char *name,
8460 const llvm::APSInt &value) {
8461
8462 if (!enum_type || ConstString(name).IsEmpty())
8463 return nullptr;
8464
8465 lldbassert(enum_type.GetTypeSystem().GetSharedPointer().get() ==lldb_private::lldb_assert(static_cast<bool>(enum_type.GetTypeSystem
().GetSharedPointer().get() == static_cast<TypeSystem *>
(this)), "enum_type.GetTypeSystem().GetSharedPointer().get() == static_cast<TypeSystem *>(this)"
, __FUNCTION__, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 8466)
8466 static_cast<TypeSystem *>(this))lldb_private::lldb_assert(static_cast<bool>(enum_type.GetTypeSystem
().GetSharedPointer().get() == static_cast<TypeSystem *>
(this)), "enum_type.GetTypeSystem().GetSharedPointer().get() == static_cast<TypeSystem *>(this)"
, __FUNCTION__, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 8466)
;
8467
8468 lldb::opaque_compiler_type_t enum_opaque_compiler_type =
8469 enum_type.GetOpaqueQualType();
8470
8471 if (!enum_opaque_compiler_type)
8472 return nullptr;
8473
8474 clang::QualType enum_qual_type(
8475 GetCanonicalQualType(enum_opaque_compiler_type));
8476
8477 const clang::Type *clang_type = enum_qual_type.getTypePtr();
8478
8479 if (!clang_type)
8480 return nullptr;
8481
8482 const clang::EnumType *enutype = llvm::dyn_cast<clang::EnumType>(clang_type);
8483
8484 if (!enutype)
8485 return nullptr;
8486
8487 clang::EnumConstantDecl *enumerator_decl =
8488 clang::EnumConstantDecl::CreateDeserialized(getASTContext(), 0);
8489 enumerator_decl->setDeclContext(enutype->getDecl());
8490 if (name && name[0])
8491 enumerator_decl->setDeclName(&getASTContext().Idents.get(name));
8492 enumerator_decl->setType(clang::QualType(enutype, 0));
8493 enumerator_decl->setInitVal(value);
8494 SetMemberOwningModule(enumerator_decl, enutype->getDecl());
8495
8496 if (!enumerator_decl)
8497 return nullptr;
8498
8499 enutype->getDecl()->addDecl(enumerator_decl);
8500
8501 VerifyDecl(enumerator_decl);
8502 return enumerator_decl;
8503}
8504
8505clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8506 const CompilerType &enum_type, const Declaration &decl, const char *name,
8507 int64_t enum_value, uint32_t enum_value_bit_size) {
8508 CompilerType underlying_type = GetEnumerationIntegerType(enum_type);
8509 bool is_signed = false;
8510 underlying_type.IsIntegerType(is_signed);
8511
8512 llvm::APSInt value(enum_value_bit_size, is_signed);
8513 value = enum_value;
8514
8515 return AddEnumerationValueToEnumerationType(enum_type, decl, name, value);
8516}
8517
8518CompilerType TypeSystemClang::GetEnumerationIntegerType(CompilerType type) {
8519 clang::QualType qt(ClangUtil::GetQualType(type));
8520 const clang::Type *clang_type = qt.getTypePtrOrNull();
8521 const auto *enum_type = llvm::dyn_cast_or_null<clang::EnumType>(clang_type);
8522 if (!enum_type)
8523 return CompilerType();
8524
8525 return GetType(enum_type->getDecl()->getIntegerType());
8526}
8527
8528CompilerType
8529TypeSystemClang::CreateMemberPointerType(const CompilerType &type,
8530 const CompilerType &pointee_type) {
8531 if (type && pointee_type.IsValid() &&
8532 type.GetTypeSystem() == pointee_type.GetTypeSystem()) {
8533 auto ts = type.GetTypeSystem();
8534 auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
8535 if (!ast)
8536 return CompilerType();
8537 return ast->GetType(ast->getASTContext().getMemberPointerType(
8538 ClangUtil::GetQualType(pointee_type),
8539 ClangUtil::GetQualType(type).getTypePtr()));
8540 }
8541 return CompilerType();
8542}
8543
8544// Dumping types
8545#define DEPTH_INCREMENT2 2
8546
8547#ifndef NDEBUG
8548LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void
8549TypeSystemClang::dump(lldb::opaque_compiler_type_t type) const {
8550 if (!type)
8551 return;
8552 clang::QualType qual_type(GetQualType(type));
8553 qual_type.dump();
8554}
8555#endif
8556
8557void TypeSystemClang::Dump(llvm::raw_ostream &output) {
8558 GetTranslationUnitDecl()->dump(output);
8559}
8560
8561void TypeSystemClang::DumpFromSymbolFile(Stream &s,
8562 llvm::StringRef symbol_name) {
8563 SymbolFile *symfile = GetSymbolFile();
8564
8565 if (!symfile)
8566 return;
8567
8568 lldb_private::TypeList type_list;
8569 symfile->GetTypes(nullptr, eTypeClassAny, type_list);
8570 size_t ntypes = type_list.GetSize();
8571
8572 for (size_t i = 0; i < ntypes; ++i) {
8573 TypeSP type = type_list.GetTypeAtIndex(i);
8574
8575 if (!symbol_name.empty())
8576 if (symbol_name != type->GetName().GetStringRef())
8577 continue;
8578
8579 s << type->GetName().AsCString() << "\n";
8580
8581 CompilerType full_type = type->GetFullCompilerType();
8582 if (clang::TagDecl *tag_decl = GetAsTagDecl(full_type)) {
8583 tag_decl->dump(s.AsRawOstream());
8584 continue;
8585 }
8586 if (clang::TypedefNameDecl *typedef_decl = GetAsTypedefDecl(full_type)) {
8587 typedef_decl->dump(s.AsRawOstream());
8588 continue;
8589 }
8590 if (auto *objc_obj = llvm::dyn_cast<clang::ObjCObjectType>(
8591 ClangUtil::GetQualType(full_type).getTypePtr())) {
8592 if (clang::ObjCInterfaceDecl *interface_decl = objc_obj->getInterface()) {
8593 interface_decl->dump(s.AsRawOstream());
8594 continue;
8595 }
8596 }
8597 GetCanonicalQualType(full_type.GetOpaqueQualType())
8598 .dump(s.AsRawOstream(), getASTContext());
8599 }
8600}
8601
8602void TypeSystemClang::DumpValue(
8603 lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s,
8604 lldb::Format format, const lldb_private::DataExtractor &data,
8605 lldb::offset_t data_byte_offset, size_t data_byte_size,
8606 uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool show_types,
8607 bool show_summary, bool verbose, uint32_t depth) {
8608 if (!type)
8609 return;
8610
8611 clang::QualType qual_type(GetQualType(type));
8612 switch (qual_type->getTypeClass()) {
8613 case clang::Type::Record:
8614 if (GetCompleteType(type)) {
8615 const clang::RecordType *record_type =
8616 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
8617 const clang::RecordDecl *record_decl = record_type->getDecl();
8618 assert(record_decl)(static_cast <bool> (record_decl) ? void (0) : __assert_fail
("record_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 8618, __extension__ __PRETTY_FUNCTION__))
;
8619 uint32_t field_bit_offset = 0;
8620 uint32_t field_byte_offset = 0;
8621 const clang::ASTRecordLayout &record_layout =
8622 getASTContext().getASTRecordLayout(record_decl);
8623 uint32_t child_idx = 0;
8624
8625 const clang::CXXRecordDecl *cxx_record_decl =
8626 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
8627 if (cxx_record_decl) {
8628 // We might have base classes to print out first
8629 clang::CXXRecordDecl::base_class_const_iterator base_class,
8630 base_class_end;
8631 for (base_class = cxx_record_decl->bases_begin(),
8632 base_class_end = cxx_record_decl->bases_end();
8633 base_class != base_class_end; ++base_class) {
8634 const clang::CXXRecordDecl *base_class_decl =
8635 llvm::cast<clang::CXXRecordDecl>(
8636 base_class->getType()->getAs<clang::RecordType>()->getDecl());
8637
8638 // Skip empty base classes
8639 if (!verbose && !TypeSystemClang::RecordHasFields(base_class_decl))
8640 continue;
8641
8642 if (base_class->isVirtual())
8643 field_bit_offset =
8644 record_layout.getVBaseClassOffset(base_class_decl)
8645 .getQuantity() *
8646 8;
8647 else
8648 field_bit_offset = record_layout.getBaseClassOffset(base_class_decl)
8649 .getQuantity() *
8650 8;
8651 field_byte_offset = field_bit_offset / 8;
8652 assert(field_bit_offset % 8 == 0)(static_cast <bool> (field_bit_offset % 8 == 0) ? void (
0) : __assert_fail ("field_bit_offset % 8 == 0", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 8652, __extension__ __PRETTY_FUNCTION__))
;
8653 if (child_idx == 0)
8654 s->PutChar('{');
8655 else
8656 s->PutChar(',');
8657
8658 clang::QualType base_class_qual_type = base_class->getType();
8659 std::string base_class_type_name(base_class_qual_type.getAsString());
8660
8661 // Indent and print the base class type name
8662 s->Format("\n{0}{1}", llvm::fmt_repeat(" ", depth + DEPTH_INCREMENT2),
8663 base_class_type_name);
8664
8665 clang::TypeInfo base_class_type_info =
8666 getASTContext().getTypeInfo(base_class_qual_type);
8667
8668 // Dump the value of the member
8669 CompilerType base_clang_type = GetType(base_class_qual_type);
8670 base_clang_type.DumpValue(
8671 exe_ctx,
8672 s, // Stream to dump to
8673 base_clang_type
8674 .GetFormat(), // The format with which to display the member
8675 data, // Data buffer containing all bytes for this type
8676 data_byte_offset + field_byte_offset, // Offset into "data" where
8677 // to grab value from
8678 base_class_type_info.Width / 8, // Size of this type in bytes
8679 0, // Bitfield bit size
8680 0, // Bitfield bit offset
8681 show_types, // Boolean indicating if we should show the variable
8682 // types
8683 show_summary, // Boolean indicating if we should show a summary
8684 // for the current type
8685 verbose, // Verbose output?
8686 depth + DEPTH_INCREMENT2); // Scope depth for any types that have
8687 // children
8688
8689 ++child_idx;
8690 }
8691 }
8692 uint32_t field_idx = 0;
8693 clang::RecordDecl::field_iterator field, field_end;
8694 for (field = record_decl->field_begin(),
8695 field_end = record_decl->field_end();
8696 field != field_end; ++field, ++field_idx, ++child_idx) {
8697 // Print the starting squiggly bracket (if this is the first member) or
8698 // comma (for member 2 and beyond) for the struct/union/class member.
8699 if (child_idx == 0)
8700 s->PutChar('{');
8701 else
8702 s->PutChar(',');
8703
8704 // Indent
8705 s->Printf("\n%*s", depth + DEPTH_INCREMENT2, "");
8706
8707 clang::QualType field_type = field->getType();
8708 // Print the member type if requested
8709 // Figure out the type byte size (field_type_info.first) and alignment
8710 // (field_type_info.second) from the AST context.
8711 clang::TypeInfo field_type_info =
8712 getASTContext().getTypeInfo(field_type);
8713 assert(field_idx < record_layout.getFieldCount())(static_cast <bool> (field_idx < record_layout.getFieldCount
()) ? void (0) : __assert_fail ("field_idx < record_layout.getFieldCount()"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
8713, __extension__ __PRETTY_FUNCTION__))
;
8714 // Figure out the field offset within the current struct/union/class
8715 // type
8716 field_bit_offset = record_layout.getFieldOffset(field_idx);
8717 field_byte_offset = field_bit_offset / 8;
8718 uint32_t field_bitfield_bit_size = 0;
8719 uint32_t field_bitfield_bit_offset = 0;
8720 if (FieldIsBitfield(*field, field_bitfield_bit_size))
8721 field_bitfield_bit_offset = field_bit_offset % 8;
8722
8723 if (show_types) {
8724 std::string field_type_name(field_type.getAsString());
8725 if (field_bitfield_bit_size > 0)
8726 s->Printf("(%s:%u) ", field_type_name.c_str(),
8727 field_bitfield_bit_size);
8728 else
8729 s->Printf("(%s) ", field_type_name.c_str());
8730 }
8731 // Print the member name and equal sign
8732 s->Printf("%s = ", field->getNameAsString().c_str());
8733
8734 // Dump the value of the member
8735 CompilerType field_clang_type = GetType(field_type);
8736 field_clang_type.DumpValue(
8737 exe_ctx,
8738 s, // Stream to dump to
8739 field_clang_type
8740 .GetFormat(), // The format with which to display the member
8741 data, // Data buffer containing all bytes for this type
8742 data_byte_offset + field_byte_offset, // Offset into "data" where to
8743 // grab value from
8744 field_type_info.Width / 8, // Size of this type in bytes
8745 field_bitfield_bit_size, // Bitfield bit size
8746 field_bitfield_bit_offset, // Bitfield bit offset
8747 show_types, // Boolean indicating if we should show the variable
8748 // types
8749 show_summary, // Boolean indicating if we should show a summary for
8750 // the current type
8751 verbose, // Verbose output?
8752 depth + DEPTH_INCREMENT2); // Scope depth for any types that have
8753 // children
8754 }
8755
8756 // Indent the trailing squiggly bracket
8757 if (child_idx > 0)
8758 s->Printf("\n%*s}", depth, "");
8759 }
8760 return;
8761
8762 case clang::Type::Enum:
8763 if (GetCompleteType(type)) {
8764 const clang::EnumType *enutype =
8765 llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8766 const clang::EnumDecl *enum_decl = enutype->getDecl();
8767 assert(enum_decl)(static_cast <bool> (enum_decl) ? void (0) : __assert_fail
("enum_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 8767, __extension__ __PRETTY_FUNCTION__))
;
8768 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
8769 lldb::offset_t offset = data_byte_offset;
8770 const int64_t enum_value = data.GetMaxU64Bitfield(
8771 &offset, data_byte_size, bitfield_bit_size, bitfield_bit_offset);
8772 for (enum_pos = enum_decl->enumerator_begin(),
8773 enum_end_pos = enum_decl->enumerator_end();
8774 enum_pos != enum_end_pos; ++enum_pos) {
8775 if (enum_pos->getInitVal() == enum_value) {
8776 s->Printf("%s", enum_pos->getNameAsString().c_str());
8777 return;
8778 }
8779 }
8780 // If we have gotten here we didn't get find the enumerator in the enum
8781 // decl, so just print the integer.
8782 s->Printf("%" PRIi64"l" "i", enum_value);
8783 }
8784 return;
8785
8786 case clang::Type::ConstantArray: {
8787 const clang::ConstantArrayType *array =
8788 llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr());
8789 bool is_array_of_characters = false;
8790 clang::QualType element_qual_type = array->getElementType();
8791
8792 const clang::Type *canonical_type =
8793 element_qual_type->getCanonicalTypeInternal().getTypePtr();
8794 if (canonical_type)
8795 is_array_of_characters = canonical_type->isCharType();
8796
8797 const uint64_t element_count = array->getSize().getLimitedValue();
8798
8799 clang::TypeInfo field_type_info =
8800 getASTContext().getTypeInfo(element_qual_type);
8801
8802 uint32_t element_idx = 0;
8803 uint32_t element_offset = 0;
8804 uint64_t element_byte_size = field_type_info.Width / 8;
8805 uint32_t element_stride = element_byte_size;
8806
8807 if (is_array_of_characters) {
8808 s->PutChar('"');
8809 DumpDataExtractor(data, s, data_byte_offset, lldb::eFormatChar,
8810 element_byte_size, element_count, UINT32_MAX(4294967295U),
8811 LLDB_INVALID_ADDRESS(18446744073709551615UL), 0, 0);
8812 s->PutChar('"');
8813 return;
8814 } else {
8815 CompilerType element_clang_type = GetType(element_qual_type);
8816 lldb::Format element_format = element_clang_type.GetFormat();
8817
8818 for (element_idx = 0; element_idx < element_count; ++element_idx) {
8819 // Print the starting squiggly bracket (if this is the first member) or
8820 // comman (for member 2 and beyong) for the struct/union/class member.
8821 if (element_idx == 0)
8822 s->PutChar('{');
8823 else
8824 s->PutChar(',');
8825
8826 // Indent and print the index
8827 s->Printf("\n%*s[%u] ", depth + DEPTH_INCREMENT2, "", element_idx);
8828
8829 // Figure out the field offset within the current struct/union/class
8830 // type
8831 element_offset = element_idx * element_stride;
8832
8833 // Dump the value of the member
8834 element_clang_type.DumpValue(
8835 exe_ctx,
8836 s, // Stream to dump to
8837 element_format, // The format with which to display the element
8838 data, // Data buffer containing all bytes for this type
8839 data_byte_offset +
8840 element_offset, // Offset into "data" where to grab value from
8841 element_byte_size, // Size of this type in bytes
8842 0, // Bitfield bit size
8843 0, // Bitfield bit offset
8844 show_types, // Boolean indicating if we should show the variable
8845 // types
8846 show_summary, // Boolean indicating if we should show a summary for
8847 // the current type
8848 verbose, // Verbose output?
8849 depth + DEPTH_INCREMENT2); // Scope depth for any types that have
8850 // children
8851 }
8852
8853 // Indent the trailing squiggly bracket
8854 if (element_idx > 0)
8855 s->Printf("\n%*s}", depth, "");
8856 }
8857 }
8858 return;
8859
8860 case clang::Type::Typedef: {
8861 clang::QualType typedef_qual_type =
8862 llvm::cast<clang::TypedefType>(qual_type)
8863 ->getDecl()
8864 ->getUnderlyingType();
8865
8866 CompilerType typedef_clang_type = GetType(typedef_qual_type);
8867 lldb::Format typedef_format = typedef_clang_type.GetFormat();
8868 clang::TypeInfo typedef_type_info =
8869 getASTContext().getTypeInfo(typedef_qual_type);
8870 uint64_t typedef_byte_size = typedef_type_info.Width / 8;
8871
8872 return typedef_clang_type.DumpValue(
8873 exe_ctx,
8874 s, // Stream to dump to
8875 typedef_format, // The format with which to display the element
8876 data, // Data buffer containing all bytes for this type
8877 data_byte_offset, // Offset into "data" where to grab value from
8878 typedef_byte_size, // Size of this type in bytes
8879 bitfield_bit_size, // Bitfield bit size
8880 bitfield_bit_offset, // Bitfield bit offset
8881 show_types, // Boolean indicating if we should show the variable types
8882 show_summary, // Boolean indicating if we should show a summary for the
8883 // current type
8884 verbose, // Verbose output?
8885 depth); // Scope depth for any types that have children
8886 } break;
8887
8888 case clang::Type::Auto: {
8889 clang::QualType elaborated_qual_type =
8890 llvm::cast<clang::AutoType>(qual_type)->getDeducedType();
8891 CompilerType elaborated_clang_type = GetType(elaborated_qual_type);
8892 lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
8893 clang::TypeInfo elaborated_type_info =
8894 getASTContext().getTypeInfo(elaborated_qual_type);
8895 uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
8896
8897 return elaborated_clang_type.DumpValue(
8898 exe_ctx,
8899 s, // Stream to dump to
8900 elaborated_format, // The format with which to display the element
8901 data, // Data buffer containing all bytes for this type
8902 data_byte_offset, // Offset into "data" where to grab value from
8903 elaborated_byte_size, // Size of this type in bytes
8904 bitfield_bit_size, // Bitfield bit size
8905 bitfield_bit_offset, // Bitfield bit offset
8906 show_types, // Boolean indicating if we should show the variable types
8907 show_summary, // Boolean indicating if we should show a summary for the
8908 // current type
8909 verbose, // Verbose output?
8910 depth); // Scope depth for any types that have children
8911 } break;
8912
8913 case clang::Type::Elaborated: {
8914 clang::QualType elaborated_qual_type =
8915 llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
8916 CompilerType elaborated_clang_type = GetType(elaborated_qual_type);
8917 lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
8918 clang::TypeInfo elaborated_type_info =
8919 getASTContext().getTypeInfo(elaborated_qual_type);
8920 uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
8921
8922 return elaborated_clang_type.DumpValue(
8923 exe_ctx,
8924 s, // Stream to dump to
8925 elaborated_format, // The format with which to display the element
8926 data, // Data buffer containing all bytes for this type
8927 data_byte_offset, // Offset into "data" where to grab value from
8928 elaborated_byte_size, // Size of this type in bytes
8929 bitfield_bit_size, // Bitfield bit size
8930 bitfield_bit_offset, // Bitfield bit offset
8931 show_types, // Boolean indicating if we should show the variable types
8932 show_summary, // Boolean indicating if we should show a summary for the
8933 // current type
8934 verbose, // Verbose output?
8935 depth); // Scope depth for any types that have children
8936 } break;
8937
8938 case clang::Type::Paren: {
8939 clang::QualType desugar_qual_type =
8940 llvm::cast<clang::ParenType>(qual_type)->desugar();
8941 CompilerType desugar_clang_type = GetType(desugar_qual_type);
8942
8943 lldb::Format desugar_format = desugar_clang_type.GetFormat();
8944 clang::TypeInfo desugar_type_info =
8945 getASTContext().getTypeInfo(desugar_qual_type);
8946 uint64_t desugar_byte_size = desugar_type_info.Width / 8;
8947
8948 return desugar_clang_type.DumpValue(
8949 exe_ctx,
8950 s, // Stream to dump to
8951 desugar_format, // The format with which to display the element
8952 data, // Data buffer containing all bytes for this type
8953 data_byte_offset, // Offset into "data" where to grab value from
8954 desugar_byte_size, // Size of this type in bytes
8955 bitfield_bit_size, // Bitfield bit size
8956 bitfield_bit_offset, // Bitfield bit offset
8957 show_types, // Boolean indicating if we should show the variable types
8958 show_summary, // Boolean indicating if we should show a summary for the
8959 // current type
8960 verbose, // Verbose output?
8961 depth); // Scope depth for any types that have children
8962 } break;
8963
8964 default:
8965 // We are down to a scalar type that we just need to display.
8966 DumpDataExtractor(data, s, data_byte_offset, format, data_byte_size, 1,
8967 UINT32_MAX(4294967295U), LLDB_INVALID_ADDRESS(18446744073709551615UL), bitfield_bit_size,
8968 bitfield_bit_offset);
8969
8970 if (show_summary)
8971 DumpSummary(type, exe_ctx, s, data, data_byte_offset, data_byte_size);
8972 break;
8973 }
8974}
8975
8976static bool DumpEnumValue(const clang::QualType &qual_type, Stream *s,
8977 const DataExtractor &data, lldb::offset_t byte_offset,
8978 size_t byte_size, uint32_t bitfield_bit_offset,
8979 uint32_t bitfield_bit_size) {
8980 const clang::EnumType *enutype =
8981 llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8982 const clang::EnumDecl *enum_decl = enutype->getDecl();
8983 assert(enum_decl)(static_cast <bool> (enum_decl) ? void (0) : __assert_fail
("enum_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 8983, __extension__ __PRETTY_FUNCTION__))
;
8984 lldb::offset_t offset = byte_offset;
8985 const uint64_t enum_svalue = data.GetMaxS64Bitfield(
8986 &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
8987 bool can_be_bitfield = true;
8988 uint64_t covered_bits = 0;
8989 int num_enumerators = 0;
8990
8991 // Try to find an exact match for the value.
8992 // At the same time, we're applying a heuristic to determine whether we want
8993 // to print this enum as a bitfield. We're likely dealing with a bitfield if
8994 // every enumerator is either a one bit value or a superset of the previous
8995 // enumerators. Also 0 doesn't make sense when the enumerators are used as
8996 // flags.
8997 for (auto *enumerator : enum_decl->enumerators()) {
8998 uint64_t val = enumerator->getInitVal().getSExtValue();
8999 val = llvm::SignExtend64(val, 8*byte_size);
9000 if (llvm::popcount(val) != 1 && (val & ~covered_bits) != 0)
9001 can_be_bitfield = false;
9002 covered_bits |= val;
9003 ++num_enumerators;
9004 if (val == enum_svalue) {
9005 // Found an exact match, that's all we need to do.
9006 s->PutCString(enumerator->getNameAsString());
9007 return true;
9008 }
9009 }
9010
9011 // Unsigned values make more sense for flags.
9012 offset = byte_offset;
9013 const uint64_t enum_uvalue = data.GetMaxU64Bitfield(
9014 &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
9015
9016 // No exact match, but we don't think this is a bitfield. Print the value as
9017 // decimal.
9018 if (!can_be_bitfield) {
9019 if (qual_type->isSignedIntegerOrEnumerationType())
9020 s->Printf("%" PRIi64"l" "i", enum_svalue);
9021 else
9022 s->Printf("%" PRIu64"l" "u", enum_uvalue);
9023 return true;
9024 }
9025
9026 uint64_t remaining_value = enum_uvalue;
9027 std::vector<std::pair<uint64_t, llvm::StringRef>> values;
9028 values.reserve(num_enumerators);
9029 for (auto *enumerator : enum_decl->enumerators())
9030 if (auto val = enumerator->getInitVal().getZExtValue())
9031 values.emplace_back(val, enumerator->getName());
9032
9033 // Sort in reverse order of the number of the population count, so that in
9034 // `enum {A, B, ALL = A|B }` we visit ALL first. Use a stable sort so that
9035 // A | C where A is declared before C is displayed in this order.
9036 std::stable_sort(values.begin(), values.end(),
9037 [](const auto &a, const auto &b) {
9038 return llvm::popcount(a.first) > llvm::popcount(b.first);
9039 });
9040
9041 for (const auto &val : values) {
9042 if ((remaining_value & val.first) != val.first)
9043 continue;
9044 remaining_value &= ~val.first;
9045 s->PutCString(val.second);
9046 if (remaining_value)
9047 s->PutCString(" | ");
9048 }
9049
9050 // If there is a remainder that is not covered by the value, print it as hex.
9051 if (remaining_value)
9052 s->Printf("0x%" PRIx64"l" "x", remaining_value);
9053
9054 return true;
9055}
9056
9057bool TypeSystemClang::DumpTypeValue(
9058 lldb::opaque_compiler_type_t type, Stream *s, lldb::Format format,
9059 const lldb_private::DataExtractor &data, lldb::offset_t byte_offset,
9060 size_t byte_size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
9061 ExecutionContextScope *exe_scope) {
9062 if (!type)
9063 return false;
9064 if (IsAggregateType(type)) {
9065 return false;
9066 } else {
9067 clang::QualType qual_type(GetQualType(type));
9068
9069 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9070
9071 if (type_class == clang::Type::Elaborated) {
9072 qual_type = llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
9073 return DumpTypeValue(qual_type.getAsOpaquePtr(), s, format, data, byte_offset, byte_size,
9074 bitfield_bit_size, bitfield_bit_offset, exe_scope);
9075 }
9076
9077 switch (type_class) {
9078 case clang::Type::Typedef: {
9079 clang::QualType typedef_qual_type =
9080 llvm::cast<clang::TypedefType>(qual_type)
9081 ->getDecl()
9082 ->getUnderlyingType();
9083 CompilerType typedef_clang_type = GetType(typedef_qual_type);
9084 if (format == eFormatDefault)
9085 format = typedef_clang_type.GetFormat();
9086 clang::TypeInfo typedef_type_info =
9087 getASTContext().getTypeInfo(typedef_qual_type);
9088 uint64_t typedef_byte_size = typedef_type_info.Width / 8;
9089
9090 return typedef_clang_type.DumpTypeValue(
9091 s,
9092 format, // The format with which to display the element
9093 data, // Data buffer containing all bytes for this type
9094 byte_offset, // Offset into "data" where to grab value from
9095 typedef_byte_size, // Size of this type in bytes
9096 bitfield_bit_size, // Size in bits of a bitfield value, if zero don't
9097 // treat as a bitfield
9098 bitfield_bit_offset, // Offset in bits of a bitfield value if
9099 // bitfield_bit_size != 0
9100 exe_scope);
9101 } break;
9102
9103 case clang::Type::Enum:
9104 // If our format is enum or default, show the enumeration value as its
9105 // enumeration string value, else just display it as requested.
9106 if ((format == eFormatEnum || format == eFormatDefault) &&
9107 GetCompleteType(type))
9108 return DumpEnumValue(qual_type, s, data, byte_offset, byte_size,
9109 bitfield_bit_offset, bitfield_bit_size);
9110 // format was not enum, just fall through and dump the value as
9111 // requested....
9112 [[fallthrough]];
9113
9114 default:
9115 // We are down to a scalar type that we just need to display.
9116 {
9117 uint32_t item_count = 1;
9118 // A few formats, we might need to modify our size and count for
9119 // depending
9120 // on how we are trying to display the value...
9121 switch (format) {
9122 default:
9123 case eFormatBoolean:
9124 case eFormatBinary:
9125 case eFormatComplex:
9126 case eFormatCString: // NULL terminated C strings
9127 case eFormatDecimal:
9128 case eFormatEnum:
9129 case eFormatHex:
9130 case eFormatHexUppercase:
9131 case eFormatFloat:
9132 case eFormatOctal:
9133 case eFormatOSType:
9134 case eFormatUnsigned:
9135 case eFormatPointer:
9136 case eFormatVectorOfChar:
9137 case eFormatVectorOfSInt8:
9138 case eFormatVectorOfUInt8:
9139 case eFormatVectorOfSInt16:
9140 case eFormatVectorOfUInt16:
9141 case eFormatVectorOfSInt32:
9142 case eFormatVectorOfUInt32:
9143 case eFormatVectorOfSInt64:
9144 case eFormatVectorOfUInt64:
9145 case eFormatVectorOfFloat32:
9146 case eFormatVectorOfFloat64:
9147 case eFormatVectorOfUInt128:
9148 break;
9149
9150 case eFormatChar:
9151 case eFormatCharPrintable:
9152 case eFormatCharArray:
9153 case eFormatBytes:
9154 case eFormatUnicode8:
9155 case eFormatBytesWithASCII:
9156 item_count = byte_size;
9157 byte_size = 1;
9158 break;
9159
9160 case eFormatUnicode16:
9161 item_count = byte_size / 2;
9162 byte_size = 2;
9163 break;
9164
9165 case eFormatUnicode32:
9166 item_count = byte_size / 4;
9167 byte_size = 4;
9168 break;
9169 }
9170 return DumpDataExtractor(data, s, byte_offset, format, byte_size,
9171 item_count, UINT32_MAX(4294967295U), LLDB_INVALID_ADDRESS(18446744073709551615UL),
9172 bitfield_bit_size, bitfield_bit_offset,
9173 exe_scope);
9174 }
9175 break;
9176 }
9177 }
9178 return false;
9179}
9180
9181void TypeSystemClang::DumpSummary(lldb::opaque_compiler_type_t type,
9182 ExecutionContext *exe_ctx, Stream *s,
9183 const lldb_private::DataExtractor &data,
9184 lldb::offset_t data_byte_offset,
9185 size_t data_byte_size) {
9186 uint32_t length = 0;
9187 if (IsCStringType(type, length)) {
9188 if (exe_ctx) {
9189 Process *process = exe_ctx->GetProcessPtr();
9190 if (process) {
9191 lldb::offset_t offset = data_byte_offset;
9192 lldb::addr_t pointer_address = data.GetMaxU64(&offset, data_byte_size);
9193 std::vector<uint8_t> buf;
9194 if (length > 0)
9195 buf.resize(length);
9196 else
9197 buf.resize(256);
9198
9199 DataExtractor cstr_data(&buf.front(), buf.size(),
9200 process->GetByteOrder(), 4);
9201 buf.back() = '\0';
9202 size_t bytes_read;
9203 size_t total_cstr_len = 0;
9204 Status error;
9205 while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(),
Although the value stored to 'bytes_read' is used in the enclosing expression, the value is never actually read from 'bytes_read'
9206 buf.size(), error)) > 0) {
9207 const size_t len = strlen((const char *)&buf.front());
9208 if (len == 0)
9209 break;
9210 if (total_cstr_len == 0)
9211 s->PutCString(" \"");
9212 DumpDataExtractor(cstr_data, s, 0, lldb::eFormatChar, 1, len,
9213 UINT32_MAX(4294967295U), LLDB_INVALID_ADDRESS(18446744073709551615UL), 0, 0);
9214 total_cstr_len += len;
9215 if (len < buf.size())
9216 break;
9217 pointer_address += total_cstr_len;
9218 }
9219 if (total_cstr_len > 0)
9220 s->PutChar('"');
9221 }
9222 }
9223 }
9224}
9225
9226void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
9227 lldb::DescriptionLevel level) {
9228 StreamFile s(stdoutstdout, false);
9229 DumpTypeDescription(type, &s, level);
9230
9231 CompilerType ct(weak_from_this(), type);
9232 const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr();
9233 ClangASTMetadata *metadata = GetMetadata(clang_type);
9234 if (metadata) {
9235 metadata->Dump(&s);
9236 }
9237}
9238
9239void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
9240 Stream *s,
9241 lldb::DescriptionLevel level) {
9242 if (type) {
9243 clang::QualType qual_type =
9244 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
9245
9246 llvm::SmallVector<char, 1024> buf;
9247 llvm::raw_svector_ostream llvm_ostrm(buf);
9248
9249 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9250 switch (type_class) {
9251 case clang::Type::ObjCObject:
9252 case clang::Type::ObjCInterface: {
9253 GetCompleteType(type);
9254
9255 auto *objc_class_type =
9256 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
9257 assert(objc_class_type)(static_cast <bool> (objc_class_type) ? void (0) : __assert_fail
("objc_class_type", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 9257, __extension__ __PRETTY_FUNCTION__))
;
9258 if (!objc_class_type)
9259 break;
9260 clang::ObjCInterfaceDecl *class_interface_decl =
9261 objc_class_type->getInterface();
9262 if (!class_interface_decl)
9263 break;
9264 if (level == eDescriptionLevelVerbose)
9265 class_interface_decl->dump(llvm_ostrm);
9266 else
9267 class_interface_decl->print(llvm_ostrm,
9268 getASTContext().getPrintingPolicy(),
9269 s->GetIndentLevel());
9270 } break;
9271
9272 case clang::Type::Typedef: {
9273 auto *typedef_type = qual_type->getAs<clang::TypedefType>();
9274 if (!typedef_type)
9275 break;
9276 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
9277 if (level == eDescriptionLevelVerbose)
9278 typedef_decl->dump(llvm_ostrm);
9279 else {
9280 std::string clang_typedef_name(GetTypeNameForDecl(typedef_decl));
9281 if (!clang_typedef_name.empty()) {
9282 s->PutCString("typedef ");
9283 s->PutCString(clang_typedef_name);
9284 }
9285 }
9286 } break;
9287
9288 case clang::Type::Record: {
9289 GetCompleteType(type);
9290
9291 auto *record_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr());
9292 const clang::RecordDecl *record_decl = record_type->getDecl();
9293 if (level == eDescriptionLevelVerbose)
9294 record_decl->dump(llvm_ostrm);
9295 else {
9296 record_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(),
9297 s->GetIndentLevel());
9298 }
9299 } break;
9300
9301 default: {
9302 if (auto *tag_type =
9303 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr())) {
9304 if (clang::TagDecl *tag_decl = tag_type->getDecl()) {
9305 if (level == eDescriptionLevelVerbose)
9306 tag_decl->dump(llvm_ostrm);
9307 else
9308 tag_decl->print(llvm_ostrm, 0);
9309 }
9310 } else {
9311 if (level == eDescriptionLevelVerbose)
9312 qual_type->dump(llvm_ostrm, getASTContext());
9313 else {
9314 std::string clang_type_name(qual_type.getAsString());
9315 if (!clang_type_name.empty())
9316 s->PutCString(clang_type_name);
9317 }
9318 }
9319 }
9320 }
9321
9322 if (buf.size() > 0) {
9323 s->Write(buf.data(), buf.size());
9324 }
9325}
9326}
9327
9328void TypeSystemClang::DumpTypeName(const CompilerType &type) {
9329 if (ClangUtil::IsClangType(type)) {
9330 clang::QualType qual_type(
9331 ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
9332
9333 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9334 switch (type_class) {
9335 case clang::Type::Record: {
9336 const clang::CXXRecordDecl *cxx_record_decl =
9337 qual_type->getAsCXXRecordDecl();
9338 if (cxx_record_decl)
9339 printf("class %s", cxx_record_decl->getName().str().c_str());
9340 } break;
9341
9342 case clang::Type::Enum: {
9343 clang::EnumDecl *enum_decl =
9344 llvm::cast<clang::EnumType>(qual_type)->getDecl();
9345 if (enum_decl) {
9346 printf("enum %s", enum_decl->getName().str().c_str());
9347 }
9348 } break;
9349
9350 case clang::Type::ObjCObject:
9351 case clang::Type::ObjCInterface: {
9352 const clang::ObjCObjectType *objc_class_type =
9353 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
9354 if (objc_class_type) {
9355 clang::ObjCInterfaceDecl *class_interface_decl =
9356 objc_class_type->getInterface();
9357 // We currently can't complete objective C types through the newly
9358 // added ASTContext because it only supports TagDecl objects right
9359 // now...
9360 if (class_interface_decl)
9361 printf("@class %s", class_interface_decl->getName().str().c_str());
9362 }
9363 } break;
9364
9365 case clang::Type::Typedef:
9366 printf("typedef %s", llvm::cast<clang::TypedefType>(qual_type)
9367 ->getDecl()
9368 ->getName()
9369 .str()
9370 .c_str());
9371 break;
9372
9373 case clang::Type::Auto:
9374 printf("auto ");
9375 return DumpTypeName(CompilerType(type.GetTypeSystem(),
9376 llvm::cast<clang::AutoType>(qual_type)
9377 ->getDeducedType()
9378 .getAsOpaquePtr()));
9379
9380 case clang::Type::Elaborated:
9381 printf("elaborated ");
9382 return DumpTypeName(CompilerType(
9383 type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
9384 ->getNamedType()
9385 .getAsOpaquePtr()));
9386
9387 case clang::Type::Paren:
9388 printf("paren ");
9389 return DumpTypeName(CompilerType(
9390 type.GetTypeSystem(),
9391 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
9392
9393 default:
9394 printf("TypeSystemClang::DumpTypeName() type_class = %u", type_class);
9395 break;
9396 }
9397 }
9398}
9399
9400clang::ClassTemplateDecl *TypeSystemClang::ParseClassTemplateDecl(
9401 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
9402 lldb::AccessType access_type, const char *parent_name, int tag_decl_kind,
9403 const TypeSystemClang::TemplateParameterInfos &template_param_infos) {
9404 if (template_param_infos.IsValid()) {
9405 std::string template_basename(parent_name);
9406 // With -gsimple-template-names we may omit template parameters in the name.
9407 if (auto i = template_basename.find('<'); i != std::string::npos)
9408 template_basename.erase(i);
9409
9410 return CreateClassTemplateDecl(decl_ctx, owning_module, access_type,
9411 template_basename.c_str(), tag_decl_kind,
9412 template_param_infos);
9413 }
9414 return nullptr;
9415}
9416
9417void TypeSystemClang::CompleteTagDecl(clang::TagDecl *decl) {
9418 SymbolFile *sym_file = GetSymbolFile();
9419 if (sym_file) {
9420 CompilerType clang_type = GetTypeForDecl(decl);
9421 if (clang_type)
9422 sym_file->CompleteType(clang_type);
9423 }
9424}
9425
9426void TypeSystemClang::CompleteObjCInterfaceDecl(
9427 clang::ObjCInterfaceDecl *decl) {
9428 SymbolFile *sym_file = GetSymbolFile();
9429 if (sym_file) {
9430 CompilerType clang_type = GetTypeForDecl(decl);
9431 if (clang_type)
9432 sym_file->CompleteType(clang_type);
9433 }
9434}
9435
9436DWARFASTParser *TypeSystemClang::GetDWARFParser() {
9437 if (!m_dwarf_ast_parser_up)
9438 m_dwarf_ast_parser_up = std::make_unique<DWARFASTParserClang>(*this);
9439 return m_dwarf_ast_parser_up.get();
9440}
9441
9442PDBASTParser *TypeSystemClang::GetPDBParser() {
9443 if (!m_pdb_ast_parser_up)
9444 m_pdb_ast_parser_up = std::make_unique<PDBASTParser>(*this);
9445 return m_pdb_ast_parser_up.get();
9446}
9447
9448npdb::PdbAstBuilder *TypeSystemClang::GetNativePDBParser() {
9449 if (!m_native_pdb_ast_parser_up)
9450 m_native_pdb_ast_parser_up = std::make_unique<npdb::PdbAstBuilder>(*this);
9451 return m_native_pdb_ast_parser_up.get();
9452}
9453
9454bool TypeSystemClang::LayoutRecordType(
9455 const clang::RecordDecl *record_decl, uint64_t &bit_size,
9456 uint64_t &alignment,
9457 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
9458 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9459 &base_offsets,
9460 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9461 &vbase_offsets) {
9462 lldb_private::ClangASTImporter *importer = nullptr;
9463 if (m_dwarf_ast_parser_up)
9464 importer = &m_dwarf_ast_parser_up->GetClangASTImporter();
9465 if (!importer && m_pdb_ast_parser_up)
9466 importer = &m_pdb_ast_parser_up->GetClangASTImporter();
9467 if (!importer && m_native_pdb_ast_parser_up)
9468 importer = &m_native_pdb_ast_parser_up->GetClangASTImporter();
9469 if (!importer)
9470 return false;
9471
9472 return importer->LayoutRecordType(record_decl, bit_size, alignment,
9473 field_offsets, base_offsets, vbase_offsets);
9474}
9475
9476// CompilerDecl override functions
9477
9478ConstString TypeSystemClang::DeclGetName(void *opaque_decl) {
9479 if (opaque_decl) {
9480 clang::NamedDecl *nd =
9481 llvm::dyn_cast<NamedDecl>((clang::Decl *)opaque_decl);
9482 if (nd != nullptr)
9483 return ConstString(nd->getDeclName().getAsString());
9484 }
9485 return ConstString();
9486}
9487
9488ConstString TypeSystemClang::DeclGetMangledName(void *opaque_decl) {
9489 if (opaque_decl) {
9490 clang::NamedDecl *nd =
9491 llvm::dyn_cast<clang::NamedDecl>((clang::Decl *)opaque_decl);
9492 if (nd != nullptr && !llvm::isa<clang::ObjCMethodDecl>(nd)) {
9493 clang::MangleContext *mc = getMangleContext();
9494 if (mc && mc->shouldMangleCXXName(nd)) {
9495 llvm::SmallVector<char, 1024> buf;
9496 llvm::raw_svector_ostream llvm_ostrm(buf);
9497 if (llvm::isa<clang::CXXConstructorDecl>(nd)) {
9498 mc->mangleName(
9499 clang::GlobalDecl(llvm::dyn_cast<clang::CXXConstructorDecl>(nd),
9500 Ctor_Complete),
9501 llvm_ostrm);
9502 } else if (llvm::isa<clang::CXXDestructorDecl>(nd)) {
9503 mc->mangleName(
9504 clang::GlobalDecl(llvm::dyn_cast<clang::CXXDestructorDecl>(nd),
9505 Dtor_Complete),
9506 llvm_ostrm);
9507 } else {
9508 mc->mangleName(nd, llvm_ostrm);
9509 }
9510 if (buf.size() > 0)
9511 return ConstString(buf.data(), buf.size());
9512 }
9513 }
9514 }
9515 return ConstString();
9516}
9517
9518CompilerDeclContext TypeSystemClang::DeclGetDeclContext(void *opaque_decl) {
9519 if (opaque_decl)
9520 return CreateDeclContext(((clang::Decl *)opaque_decl)->getDeclContext());
9521 return CompilerDeclContext();
9522}
9523
9524CompilerType TypeSystemClang::DeclGetFunctionReturnType(void *opaque_decl) {
9525 if (clang::FunctionDecl *func_decl =
9526 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9527 return GetType(func_decl->getReturnType());
9528 if (clang::ObjCMethodDecl *objc_method =
9529 llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9530 return GetType(objc_method->getReturnType());
9531 else
9532 return CompilerType();
9533}
9534
9535size_t TypeSystemClang::DeclGetFunctionNumArguments(void *opaque_decl) {
9536 if (clang::FunctionDecl *func_decl =
9537 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9538 return func_decl->param_size();
9539 if (clang::ObjCMethodDecl *objc_method =
9540 llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9541 return objc_method->param_size();
9542 else
9543 return 0;
9544}
9545
9546CompilerType TypeSystemClang::DeclGetFunctionArgumentType(void *opaque_decl,
9547 size_t idx) {
9548 if (clang::FunctionDecl *func_decl =
9549 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) {
9550 if (idx < func_decl->param_size()) {
9551 ParmVarDecl *var_decl = func_decl->getParamDecl(idx);
9552 if (var_decl)
9553 return GetType(var_decl->getOriginalType());
9554 }
9555 } else if (clang::ObjCMethodDecl *objc_method =
9556 llvm::dyn_cast<clang::ObjCMethodDecl>(
9557 (clang::Decl *)opaque_decl)) {
9558 if (idx < objc_method->param_size())
9559 return GetType(objc_method->parameters()[idx]->getOriginalType());
9560 }
9561 return CompilerType();
9562}
9563
9564// CompilerDeclContext functions
9565
9566std::vector<CompilerDecl> TypeSystemClang::DeclContextFindDeclByName(
9567 void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) {
9568 std::vector<CompilerDecl> found_decls;
9569 SymbolFile *symbol_file = GetSymbolFile();
9570 if (opaque_decl_ctx && symbol_file) {
9571 DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx;
9572 std::set<DeclContext *> searched;
9573 std::multimap<DeclContext *, DeclContext *> search_queue;
9574
9575 for (clang::DeclContext *decl_context = root_decl_ctx;
9576 decl_context != nullptr && found_decls.empty();
9577 decl_context = decl_context->getParent()) {
9578 search_queue.insert(std::make_pair(decl_context, decl_context));
9579
9580 for (auto it = search_queue.find(decl_context); it != search_queue.end();
9581 it++) {
9582 if (!searched.insert(it->second).second)
9583 continue;
9584 symbol_file->ParseDeclsForContext(
9585 CreateDeclContext(it->second));
9586
9587 for (clang::Decl *child : it->second->decls()) {
9588 if (clang::UsingDirectiveDecl *ud =
9589 llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9590 if (ignore_using_decls)
9591 continue;
9592 clang::DeclContext *from = ud->getCommonAncestor();
9593 if (searched.find(ud->getNominatedNamespace()) == searched.end())
9594 search_queue.insert(
9595 std::make_pair(from, ud->getNominatedNamespace()));
9596 } else if (clang::UsingDecl *ud =
9597 llvm::dyn_cast<clang::UsingDecl>(child)) {
9598 if (ignore_using_decls)
9599 continue;
9600 for (clang::UsingShadowDecl *usd : ud->shadows()) {
9601 clang::Decl *target = usd->getTargetDecl();
9602 if (clang::NamedDecl *nd =
9603 llvm::dyn_cast<clang::NamedDecl>(target)) {
9604 IdentifierInfo *ii = nd->getIdentifier();
9605 if (ii != nullptr &&
9606 ii->getName().equals(name.AsCString(nullptr)))
9607 found_decls.push_back(GetCompilerDecl(nd));
9608 }
9609 }
9610 } else if (clang::NamedDecl *nd =
9611 llvm::dyn_cast<clang::NamedDecl>(child)) {
9612 IdentifierInfo *ii = nd->getIdentifier();
9613 if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr)))
9614 found_decls.push_back(GetCompilerDecl(nd));
9615 }
9616 }
9617 }
9618 }
9619 }
9620 return found_decls;
9621}
9622
9623// Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents,
9624// and return the number of levels it took to find it, or
9625// LLDB_INVALID_DECL_LEVEL if not found. If the decl was imported via a using
9626// declaration, its name and/or type, if set, will be used to check that the
9627// decl found in the scope is a match.
9628//
9629// The optional name is required by languages (like C++) to handle using
9630// declarations like:
9631//
9632// void poo();
9633// namespace ns {
9634// void foo();
9635// void goo();
9636// }
9637// void bar() {
9638// using ns::foo;
9639// // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and
9640// // LLDB_INVALID_DECL_LEVEL for 'goo'.
9641// }
9642//
9643// The optional type is useful in the case that there's a specific overload
9644// that we're looking for that might otherwise be shadowed, like:
9645//
9646// void foo(int);
9647// namespace ns {
9648// void foo();
9649// }
9650// void bar() {
9651// using ns::foo;
9652// // CountDeclLevels returns 0 for { 'foo', void() },
9653// // 1 for { 'foo', void(int) }, and
9654// // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }.
9655// }
9656//
9657// NOTE: Because file statics are at the TranslationUnit along with globals, a
9658// function at file scope will return the same level as a function at global
9659// scope. Ideally we'd like to treat the file scope as an additional scope just
9660// below the global scope. More work needs to be done to recognise that, if
9661// the decl we're trying to look up is static, we should compare its source
9662// file with that of the current scope and return a lower number for it.
9663uint32_t TypeSystemClang::CountDeclLevels(clang::DeclContext *frame_decl_ctx,
9664 clang::DeclContext *child_decl_ctx,
9665 ConstString *child_name,
9666 CompilerType *child_type) {
9667 SymbolFile *symbol_file = GetSymbolFile();
9668 if (frame_decl_ctx && symbol_file) {
9669 std::set<DeclContext *> searched;
9670 std::multimap<DeclContext *, DeclContext *> search_queue;
9671
9672 // Get the lookup scope for the decl we're trying to find.
9673 clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent();
9674
9675 // Look for it in our scope's decl context and its parents.
9676 uint32_t level = 0;
9677 for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr;
9678 decl_ctx = decl_ctx->getParent()) {
9679 if (!decl_ctx->isLookupContext())
9680 continue;
9681 if (decl_ctx == parent_decl_ctx)
9682 // Found it!
9683 return level;
9684 search_queue.insert(std::make_pair(decl_ctx, decl_ctx));
9685 for (auto it = search_queue.find(decl_ctx); it != search_queue.end();
9686 it++) {
9687 if (searched.find(it->second) != searched.end())
9688 continue;
9689
9690 // Currently DWARF has one shared translation unit for all Decls at top
9691 // level, so this would erroneously find using statements anywhere. So
9692 // don't look at the top-level translation unit.
9693 // TODO fix this and add a testcase that depends on it.
9694
9695 if (llvm::isa<clang::TranslationUnitDecl>(it->second))
9696 continue;
9697
9698 searched.insert(it->second);
9699 symbol_file->ParseDeclsForContext(
9700 CreateDeclContext(it->second));
9701
9702 for (clang::Decl *child : it->second->decls()) {
9703 if (clang::UsingDirectiveDecl *ud =
9704 llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9705 clang::DeclContext *ns = ud->getNominatedNamespace();
9706 if (ns == parent_decl_ctx)
9707 // Found it!
9708 return level;
9709 clang::DeclContext *from = ud->getCommonAncestor();
9710 if (searched.find(ns) == searched.end())
9711 search_queue.insert(std::make_pair(from, ns));
9712 } else if (child_name) {
9713 if (clang::UsingDecl *ud =
9714 llvm::dyn_cast<clang::UsingDecl>(child)) {
9715 for (clang::UsingShadowDecl *usd : ud->shadows()) {
9716 clang::Decl *target = usd->getTargetDecl();
9717 clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(target);
9718 if (!nd)
9719 continue;
9720 // Check names.
9721 IdentifierInfo *ii = nd->getIdentifier();
9722 if (ii == nullptr ||
9723 !ii->getName().equals(child_name->AsCString(nullptr)))
9724 continue;
9725 // Check types, if one was provided.
9726 if (child_type) {
9727 CompilerType clang_type = GetTypeForDecl(nd);
9728 if (!AreTypesSame(clang_type, *child_type,
9729 /*ignore_qualifiers=*/true))
9730 continue;
9731 }
9732 // Found it!
9733 return level;
9734 }
9735 }
9736 }
9737 }
9738 }
9739 ++level;
9740 }
9741 }
9742 return LLDB_INVALID_DECL_LEVEL(4294967295U);
9743}
9744
9745ConstString TypeSystemClang::DeclContextGetName(void *opaque_decl_ctx) {
9746 if (opaque_decl_ctx) {
9747 clang::NamedDecl *named_decl =
9748 llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9749 if (named_decl)
9750 return ConstString(named_decl->getName());
9751 }
9752 return ConstString();
9753}
9754
9755ConstString
9756TypeSystemClang::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) {
9757 if (opaque_decl_ctx) {
9758 clang::NamedDecl *named_decl =
9759 llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9760 if (named_decl)
9761 return ConstString(GetTypeNameForDecl(named_decl));
9762 }
9763 return ConstString();
9764}
9765
9766bool TypeSystemClang::DeclContextIsClassMethod(void *opaque_decl_ctx) {
9767 if (!opaque_decl_ctx)
9768 return false;
9769
9770 clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9771 if (llvm::isa<clang::ObjCMethodDecl>(decl_ctx)) {
9772 return true;
9773 } else if (llvm::isa<clang::CXXMethodDecl>(decl_ctx)) {
9774 return true;
9775 } else if (clang::FunctionDecl *fun_decl =
9776 llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
9777 if (ClangASTMetadata *metadata = GetMetadata(fun_decl))
9778 return metadata->HasObjectPtr();
9779 }
9780
9781 return false;
9782}
9783
9784bool TypeSystemClang::DeclContextIsContainedInLookup(
9785 void *opaque_decl_ctx, void *other_opaque_decl_ctx) {
9786 auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9787 auto *other = (clang::DeclContext *)other_opaque_decl_ctx;
9788
9789 do {
9790 // A decl context always includes its own contents in its lookup.
9791 if (decl_ctx == other)
9792 return true;
9793
9794 // If we have an inline namespace, then the lookup of the parent context
9795 // also includes the inline namespace contents.
9796 } while (other->isInlineNamespace() && (other = other->getParent()));
9797
9798 return false;
9799}
9800
9801lldb::LanguageType
9802TypeSystemClang::DeclContextGetLanguage(void *opaque_decl_ctx) {
9803 if (!opaque_decl_ctx)
9804 return eLanguageTypeUnknown;
9805
9806 auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9807 if (llvm::isa<clang::ObjCMethodDecl>(decl_ctx)) {
9808 return eLanguageTypeObjC;
9809 } else if (llvm::isa<clang::CXXMethodDecl>(decl_ctx)) {
9810 return eLanguageTypeC_plus_plus;
9811 } else if (auto *fun_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
9812 if (ClangASTMetadata *metadata = GetMetadata(fun_decl))
9813 return metadata->GetObjectPtrLanguage();
9814 }
9815
9816 return eLanguageTypeUnknown;
9817}
9818
9819static bool IsClangDeclContext(const CompilerDeclContext &dc) {
9820 return dc.IsValid() && isa<TypeSystemClang>(dc.GetTypeSystem());
9821}
9822
9823clang::DeclContext *
9824TypeSystemClang::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) {
9825 if (IsClangDeclContext(dc))
9826 return (clang::DeclContext *)dc.GetOpaqueDeclContext();
9827 return nullptr;
9828}
9829
9830ObjCMethodDecl *
9831TypeSystemClang::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) {
9832 if (IsClangDeclContext(dc))
9833 return llvm::dyn_cast<clang::ObjCMethodDecl>(
9834 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9835 return nullptr;
9836}
9837
9838CXXMethodDecl *
9839TypeSystemClang::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) {
9840 if (IsClangDeclContext(dc))
9841 return llvm::dyn_cast<clang::CXXMethodDecl>(
9842 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9843 return nullptr;
9844}
9845
9846clang::FunctionDecl *
9847TypeSystemClang::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) {
9848 if (IsClangDeclContext(dc))
9849 return llvm::dyn_cast<clang::FunctionDecl>(
9850 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9851 return nullptr;
9852}
9853
9854clang::NamespaceDecl *
9855TypeSystemClang::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) {
9856 if (IsClangDeclContext(dc))
9857 return llvm::dyn_cast<clang::NamespaceDecl>(
9858 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9859 return nullptr;
9860}
9861
9862ClangASTMetadata *
9863TypeSystemClang::DeclContextGetMetaData(const CompilerDeclContext &dc,
9864 const Decl *object) {
9865 TypeSystemClang *ast = llvm::cast<TypeSystemClang>(dc.GetTypeSystem());
9866 return ast->GetMetadata(object);
9867}
9868
9869clang::ASTContext *
9870TypeSystemClang::DeclContextGetTypeSystemClang(const CompilerDeclContext &dc) {
9871 TypeSystemClang *ast =
9872 llvm::dyn_cast_or_null<TypeSystemClang>(dc.GetTypeSystem());
9873 if (ast)
9874 return &ast->getASTContext();
9875 return nullptr;
9876}
9877
9878void TypeSystemClang::RequireCompleteType(CompilerType type) {
9879 // Technically, enums can be incomplete too, but we don't handle those as they
9880 // are emitted even under -flimit-debug-info.
9881 if (!TypeSystemClang::IsCXXClassType(type))
9882 return;
9883
9884 if (type.GetCompleteType())
9885 return;
9886
9887 // No complete definition in this module. Mark the class as complete to
9888 // satisfy local ast invariants, but make a note of the fact that
9889 // it is not _really_ complete so we can later search for a definition in a
9890 // different module.
9891 // Since we provide layout assistance, layouts of types containing this class
9892 // will be correct even if we are not able to find the definition elsewhere.
9893 bool started = TypeSystemClang::StartTagDeclarationDefinition(type);
9894 lldbassert(started && "Unable to start a class type definition.")lldb_private::lldb_assert(static_cast<bool>(started &&
"Unable to start a class type definition."), "started && \"Unable to start a class type definition.\""
, __FUNCTION__, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 9894)
;
9895 TypeSystemClang::CompleteTagDeclarationDefinition(type);
9896 const clang::TagDecl *td = ClangUtil::GetAsTagDecl(type);
9897 auto ts = type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
9898 if (ts)
9899 ts->SetDeclIsForcefullyCompleted(td);
9900}
9901
9902namespace {
9903/// A specialized scratch AST used within ScratchTypeSystemClang.
9904/// These are the ASTs backing the different IsolatedASTKinds. They behave
9905/// like a normal ScratchTypeSystemClang but they don't own their own
9906/// persistent storage or target reference.
9907class SpecializedScratchAST : public TypeSystemClang {
9908public:
9909 /// \param name The display name of the TypeSystemClang instance.
9910 /// \param triple The triple used for the TypeSystemClang instance.
9911 /// \param ast_source The ClangASTSource that should be used to complete
9912 /// type information.
9913 SpecializedScratchAST(llvm::StringRef name, llvm::Triple triple,
9914 std::unique_ptr<ClangASTSource> ast_source)
9915 : TypeSystemClang(name, triple),
9916 m_scratch_ast_source_up(std::move(ast_source)) {
9917 // Setup the ClangASTSource to complete this AST.
9918 m_scratch_ast_source_up->InstallASTContext(*this);
9919 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9920 m_scratch_ast_source_up->CreateProxy());
9921 SetExternalSource(proxy_ast_source);
9922 }
9923
9924 /// The ExternalASTSource that performs lookups and completes types.
9925 std::unique_ptr<ClangASTSource> m_scratch_ast_source_up;
9926};
9927} // namespace
9928
9929char ScratchTypeSystemClang::ID;
9930const std::nullopt_t ScratchTypeSystemClang::DefaultAST = std::nullopt;
9931
9932ScratchTypeSystemClang::ScratchTypeSystemClang(Target &target,
9933 llvm::Triple triple)
9934 : TypeSystemClang("scratch ASTContext", triple), m_triple(triple),
9935 m_target_wp(target.shared_from_this()),
9936 m_persistent_variables(
9937 new ClangPersistentVariables(target.shared_from_this())) {
9938 m_scratch_ast_source_up = CreateASTSource();
9939 m_scratch_ast_source_up->InstallASTContext(*this);
9940 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9941 m_scratch_ast_source_up->CreateProxy());
9942 SetExternalSource(proxy_ast_source);
9943}
9944
9945void ScratchTypeSystemClang::Finalize() {
9946 TypeSystemClang::Finalize();
9947 m_scratch_ast_source_up.reset();
9948}
9949
9950TypeSystemClangSP
9951ScratchTypeSystemClang::GetForTarget(Target &target,
9952 std::optional<IsolatedASTKind> ast_kind,
9953 bool create_on_demand) {
9954 auto type_system_or_err = target.GetScratchTypeSystemForLanguage(
9955 lldb::eLanguageTypeC, create_on_demand);
9956 if (auto err = type_system_or_err.takeError()) {
9957 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),do { ::lldb_private::Log *log_private = (GetLog(LLDBLog::Target
)); ::llvm::Error error_private = (std::move(err)); if (log_private
&& error_private) { log_private->FormatError(::std
::move(error_private), "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "Couldn't get scratch TypeSystemClang"); } else ::
llvm::consumeError(::std::move(error_private)); } while (0)
9958 "Couldn't get scratch TypeSystemClang")do { ::lldb_private::Log *log_private = (GetLog(LLDBLog::Target
)); ::llvm::Error error_private = (std::move(err)); if (log_private
&& error_private) { log_private->FormatError(::std
::move(error_private), "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, __func__, "Couldn't get scratch TypeSystemClang"); } else ::
llvm::consumeError(::std::move(error_private)); } while (0)
;
9959 return nullptr;
9960 }
9961 auto ts_sp = *type_system_or_err;
9962 ScratchTypeSystemClang *scratch_ast =
9963 llvm::dyn_cast_or_null<ScratchTypeSystemClang>(ts_sp.get());
9964 if (!scratch_ast)
9965 return nullptr;
9966 // If no dedicated sub-AST was requested, just return the main AST.
9967 if (ast_kind == DefaultAST)
9968 return std::static_pointer_cast<TypeSystemClang>(ts_sp);
9969 // Search the sub-ASTs.
9970 return std::static_pointer_cast<TypeSystemClang>(
9971 scratch_ast->GetIsolatedAST(*ast_kind).shared_from_this());
9972}
9973
9974/// Returns a human-readable name that uniquely identifiers the sub-AST kind.
9975static llvm::StringRef
9976GetNameForIsolatedASTKind(ScratchTypeSystemClang::IsolatedASTKind kind) {
9977 switch (kind) {
9978 case ScratchTypeSystemClang::IsolatedASTKind::CppModules:
9979 return "C++ modules";
9980 }
9981 llvm_unreachable("Unimplemented IsolatedASTKind?")::llvm::llvm_unreachable_internal("Unimplemented IsolatedASTKind?"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
9981)
;
9982}
9983
9984void ScratchTypeSystemClang::Dump(llvm::raw_ostream &output) {
9985 // First dump the main scratch AST.
9986 output << "State of scratch Clang type system:\n";
9987 TypeSystemClang::Dump(output);
9988
9989 // Now sort the isolated sub-ASTs.
9990 typedef std::pair<IsolatedASTKey, TypeSystem *> KeyAndTS;
9991 std::vector<KeyAndTS> sorted_typesystems;
9992 for (const auto &a : m_isolated_asts)
9993 sorted_typesystems.emplace_back(a.first, a.second.get());
9994 llvm::stable_sort(sorted_typesystems, llvm::less_first());
9995
9996 // Dump each sub-AST too.
9997 for (const auto &a : sorted_typesystems) {
9998 IsolatedASTKind kind =
9999 static_cast<ScratchTypeSystemClang::IsolatedASTKind>(a.first);
10000 output << "State of scratch Clang type subsystem "
10001 << GetNameForIsolatedASTKind(kind) << ":\n";
10002 a.second->Dump(output);
10003 }
10004}
10005
10006UserExpression *ScratchTypeSystemClang::GetUserExpression(
10007 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
10008 Expression::ResultType desired_type,
10009 const EvaluateExpressionOptions &options, ValueObject *ctx_obj) {
10010 TargetSP target_sp = m_target_wp.lock();
10011 if (!target_sp)
10012 return nullptr;
10013
10014 return new ClangUserExpression(*target_sp.get(), expr, prefix, language,
10015 desired_type, options, ctx_obj);
10016}
10017
10018FunctionCaller *ScratchTypeSystemClang::GetFunctionCaller(
10019 const CompilerType &return_type, const Address &function_address,
10020 const ValueList &arg_value_list, const char *name) {
10021 TargetSP target_sp = m_target_wp.lock();
10022 if (!target_sp)
10023 return nullptr;
10024
10025 Process *process = target_sp->GetProcessSP().get();
10026 if (!process)
10027 return nullptr;
10028
10029 return new ClangFunctionCaller(*process, return_type, function_address,
10030 arg_value_list, name);
10031}
10032
10033std::unique_ptr<UtilityFunction>
10034ScratchTypeSystemClang::CreateUtilityFunction(std::string text,
10035 std::string name) {
10036 TargetSP target_sp = m_target_wp.lock();
10037 if (!target_sp)
10038 return {};
10039
10040 return std::make_unique<ClangUtilityFunction>(
10041 *target_sp.get(), std::move(text), std::move(name),
10042 target_sp->GetDebugUtilityExpression());
10043}
10044
10045PersistentExpressionState *
10046ScratchTypeSystemClang::GetPersistentExpressionState() {
10047 return m_persistent_variables.get();
10048}
10049
10050void ScratchTypeSystemClang::ForgetSource(ASTContext *src_ctx,
10051 ClangASTImporter &importer) {
10052 // Remove it as a source from the main AST.
10053 importer.ForgetSource(&getASTContext(), src_ctx);
10054 // Remove it as a source from all created sub-ASTs.
10055 for (const auto &a : m_isolated_asts)
10056 importer.ForgetSource(&a.second->getASTContext(), src_ctx);
10057}
10058
10059std::unique_ptr<ClangASTSource> ScratchTypeSystemClang::CreateASTSource() {
10060 return std::make_unique<ClangASTSource>(
10061 m_target_wp.lock()->shared_from_this(),
10062 m_persistent_variables->GetClangASTImporter());
10063}
10064
10065static llvm::StringRef
10066GetSpecializedASTName(ScratchTypeSystemClang::IsolatedASTKind feature) {
10067 switch (feature) {
10068 case ScratchTypeSystemClang::IsolatedASTKind::CppModules:
10069 return "scratch ASTContext for C++ module types";
10070 }
10071 llvm_unreachable("Unimplemented ASTFeature kind?")::llvm::llvm_unreachable_internal("Unimplemented ASTFeature kind?"
, "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp",
10071)
;
10072}
10073
10074TypeSystemClang &ScratchTypeSystemClang::GetIsolatedAST(
10075 ScratchTypeSystemClang::IsolatedASTKind feature) {
10076 auto found_ast = m_isolated_asts.find(feature);
10077 if (found_ast != m_isolated_asts.end())
10078 return *found_ast->second;
10079
10080 // Couldn't find the requested sub-AST, so create it now.
10081 std::shared_ptr<TypeSystemClang> new_ast_sp =
10082 std::make_shared<SpecializedScratchAST>(GetSpecializedASTName(feature),
10083 m_triple, CreateASTSource());
10084 m_isolated_asts.insert({feature, new_ast_sp});
10085 return *new_ast_sp;
10086}
10087
10088bool TypeSystemClang::IsForcefullyCompleted(lldb::opaque_compiler_type_t type) {
10089 if (type) {
10090 clang::QualType qual_type(GetQualType(type));
10091 const clang::RecordType *record_type =
10092 llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
10093 if (record_type) {
10094 const clang::RecordDecl *record_decl = record_type->getDecl();
10095 assert(record_decl)(static_cast <bool> (record_decl) ? void (0) : __assert_fail
("record_decl", "lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp"
, 10095, __extension__ __PRETTY_FUNCTION__))
;
10096 ClangASTMetadata *metadata = GetMetadata(record_decl);
10097 if (metadata)
10098 return metadata->IsForcefullyCompleted();
10099 }
10100 }
10101 return false;
10102}
10103
10104bool TypeSystemClang::SetDeclIsForcefullyCompleted(const clang::TagDecl *td) {
10105 if (td == nullptr)
10106 return false;
10107 ClangASTMetadata *metadata = GetMetadata(td);
10108 if (metadata == nullptr)
10109 return false;
10110 m_has_forcefully_completed_types = true;
10111 metadata->SetIsForcefullyCompleted();
10112 return true;
10113}