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