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