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