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