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