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 "llvm/Support/Casting.h"
14#include "llvm/Support/FormatAdapters.h"
15#include "llvm/Support/FormatVariadic.h"
16
17#include <mutex>
18#include <memory>
19#include <string>
20#include <vector>
21
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/ASTImporter.h"
24#include "clang/AST/Attr.h"
25#include "clang/AST/CXXInheritance.h"
26#include "clang/AST/DeclObjC.h"
27#include "clang/AST/DeclTemplate.h"
28#include "clang/AST/Mangle.h"
29#include "clang/AST/RecordLayout.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/VTableBuilder.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/Diagnostic.h"
34#include "clang/Basic/FileManager.h"
35#include "clang/Basic/FileSystemOptions.h"
36#include "clang/Basic/LangStandard.h"
37#include "clang/Basic/SourceManager.h"
38#include "clang/Basic/TargetInfo.h"
39#include "clang/Basic/TargetOptions.h"
40#include "clang/Frontend/FrontendOptions.h"
41#include "clang/Lex/HeaderSearch.h"
42#include "clang/Lex/HeaderSearchOptions.h"
43#include "clang/Lex/ModuleMap.h"
44#include "clang/Sema/Sema.h"
45
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/Threading.h"
48
58#include "lldb/Core/Module.h"
66#include "lldb/Target/Process.h"
67#include "lldb/Target/Target.h"
70#include "lldb/Utility/Flags.h"
74#include "lldb/Utility/Scalar.h"
76
81
82#include <cstdio>
83
84#include <mutex>
85#include <optional>
86
87using namespace lldb;
88using namespace lldb_private;
89using namespace lldb_private::dwarf;
90using namespace lldb_private::plugin::dwarf;
91using namespace clang;
92using llvm::StringSwitch;
93
95
96namespace {
97static void VerifyDecl(clang::Decl *decl) {
98 assert(decl && "VerifyDecl called with nullptr?");
99#ifndef NDEBUG
100 // We don't care about the actual access value here but only want to trigger
101 // that Clang calls its internal Decl::AccessDeclContextCheck validation.
102 decl->getAccess();
103#endif
104}
105
106static inline bool
107TypeSystemClangSupportsLanguage(lldb::LanguageType language) {
108 return language == eLanguageTypeUnknown || // Clang is the default type system
113 // Use Clang for Rust until there is a proper language plugin for it
114 language == eLanguageTypeRust ||
115 // Use Clang for D until there is a proper language plugin for it
116 language == eLanguageTypeD ||
117 // Open Dylan compiler debug info is designed to be Clang-compatible
118 language == eLanguageTypeDylan;
119}
120
121// Checks whether m1 is an overload of m2 (as opposed to an override). This is
122// called by addOverridesForMethod to distinguish overrides (which share a
123// vtable entry) from overloads (which require distinct entries).
124bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) {
125 // FIXME: This should detect covariant return types, but currently doesn't.
126 lldbassert(&m1->getASTContext() == &m2->getASTContext() &&
127 "Methods should have the same AST context");
128 clang::ASTContext &context = m1->getASTContext();
129
130 const auto *m1Type = llvm::cast<clang::FunctionProtoType>(
131 context.getCanonicalType(m1->getType()));
132
133 const auto *m2Type = llvm::cast<clang::FunctionProtoType>(
134 context.getCanonicalType(m2->getType()));
135
136 auto compareArgTypes = [&context](const clang::QualType &m1p,
137 const clang::QualType &m2p) {
138 return context.hasSameType(m1p.getUnqualifiedType(),
139 m2p.getUnqualifiedType());
140 };
141
142 // FIXME: In C++14 and later, we can just pass m2Type->param_type_end()
143 // as a fourth parameter to std::equal().
144 return (m1->getNumParams() != m2->getNumParams()) ||
145 !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(),
146 m2Type->param_type_begin(), compareArgTypes);
147}
148
149// If decl is a virtual method, walk the base classes looking for methods that
150// decl overrides. This table of overridden methods is used by IRGen to
151// determine the vtable layout for decl's parent class.
152void addOverridesForMethod(clang::CXXMethodDecl *decl) {
153 if (!decl->isVirtual())
154 return;
155
156 clang::CXXBasePaths paths;
157 llvm::SmallVector<clang::NamedDecl *, 4> decls;
158
159 auto find_overridden_methods =
160 [&decls, decl](const clang::CXXBaseSpecifier *specifier,
161 clang::CXXBasePath &path) {
162 if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>(
163 specifier->getType()->castAs<clang::RecordType>()->getDecl())) {
164
165 clang::DeclarationName name = decl->getDeclName();
166
167 // If this is a destructor, check whether the base class destructor is
168 // virtual.
169 if (name.getNameKind() == clang::DeclarationName::CXXDestructorName)
170 if (auto *baseDtorDecl = base_record->getDestructor()) {
171 if (baseDtorDecl->isVirtual()) {
172 decls.push_back(baseDtorDecl);
173 return true;
174 } else
175 return false;
176 }
177
178 // Otherwise, search for name in the base class.
179 for (path.Decls = base_record->lookup(name).begin();
180 path.Decls != path.Decls.end(); ++path.Decls) {
181 if (auto *method_decl =
182 llvm::dyn_cast<clang::CXXMethodDecl>(*path.Decls))
183 if (method_decl->isVirtual() && !isOverload(decl, method_decl)) {
184 decls.push_back(method_decl);
185 return true;
186 }
187 }
188 }
189
190 return false;
191 };
192
193 if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) {
194 for (auto *overridden_decl : decls)
195 decl->addOverriddenMethod(
196 llvm::cast<clang::CXXMethodDecl>(overridden_decl));
197 }
198}
199}
200
202 VTableContextBase &vtable_ctx,
203 ValueObject &valobj,
204 const ASTRecordLayout &record_layout) {
205 // Retrieve type info
206 CompilerType pointee_type;
207 CompilerType this_type(valobj.GetCompilerType());
208 uint32_t type_info = this_type.GetTypeInfo(&pointee_type);
209 if (!type_info)
211
212 // Check if it's a pointer or reference
213 bool ptr_or_ref = false;
214 if (type_info & (eTypeIsPointer | eTypeIsReference)) {
215 ptr_or_ref = true;
216 type_info = pointee_type.GetTypeInfo();
217 }
218
219 // We process only C++ classes
220 const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus;
221 if ((type_info & cpp_class) != cpp_class)
223
224 // Calculate offset to VTable pointer
225 lldb::offset_t vbtable_ptr_offset =
226 vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity()
227 : 0;
228
229 if (ptr_or_ref) {
230 // We have a pointer / ref to object, so read
231 // VTable pointer from process memory
232
235
236 auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
237 if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS)
239
240 vbtable_ptr_addr += vbtable_ptr_offset;
241
242 Status err;
243 return process.ReadPointerFromMemory(vbtable_ptr_addr, err);
244 }
245
246 // We have an object already read from process memory,
247 // so just extract VTable pointer from it
248
249 DataExtractor data;
250 Status err;
251 auto size = valobj.GetData(data, err);
252 if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size)
254
255 return data.GetAddress(&vbtable_ptr_offset);
256}
257
258static int64_t ReadVBaseOffsetFromVTable(Process &process,
259 VTableContextBase &vtable_ctx,
260 lldb::addr_t vtable_ptr,
261 const CXXRecordDecl *cxx_record_decl,
262 const CXXRecordDecl *base_class_decl) {
263 if (vtable_ctx.isMicrosoft()) {
264 clang::MicrosoftVTableContext &msoft_vtable_ctx =
265 static_cast<clang::MicrosoftVTableContext &>(vtable_ctx);
266
267 // Get the index into the virtual base table. The
268 // index is the index in uint32_t from vbtable_ptr
269 const unsigned vbtable_index =
270 msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl);
271 const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4;
272 Status err;
273 return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX,
274 err);
275 }
276
277 clang::ItaniumVTableContext &itanium_vtable_ctx =
278 static_cast<clang::ItaniumVTableContext &>(vtable_ctx);
279
280 clang::CharUnits base_offset_offset =
281 itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl,
282 base_class_decl);
283 const lldb::addr_t base_offset_addr =
284 vtable_ptr + base_offset_offset.getQuantity();
285 const uint32_t base_offset_size = process.GetAddressByteSize();
286 Status err;
287 return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size,
288 INT64_MAX, err);
289}
290
291static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx,
292 ValueObject &valobj,
293 const ASTRecordLayout &record_layout,
294 const CXXRecordDecl *cxx_record_decl,
295 const CXXRecordDecl *base_class_decl,
296 int32_t &bit_offset) {
298 Process *process = exe_ctx.GetProcessPtr();
299 if (!process)
300 return false;
301
302 lldb::addr_t vtable_ptr =
303 GetVTableAddress(*process, vtable_ctx, valobj, record_layout);
304 if (vtable_ptr == LLDB_INVALID_ADDRESS)
305 return false;
306
307 auto base_offset = ReadVBaseOffsetFromVTable(
308 *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl);
309 if (base_offset == INT64_MAX)
310 return false;
311
312 bit_offset = base_offset * 8;
313
314 return true;
315}
316
319
321 static ClangASTMap *g_map_ptr = nullptr;
322 static llvm::once_flag g_once_flag;
323 llvm::call_once(g_once_flag, []() {
324 g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
325 });
326 return *g_map_ptr;
327}
328
330 bool is_complete_objc_class)
331 : m_payload(owning_module.GetValue()) {
332 SetIsCompleteObjCClass(is_complete_objc_class);
333}
334
336 assert(id.GetValue() < ObjCClassBit);
337 bool is_complete = IsCompleteObjCClass();
338 m_payload = id.GetValue();
339 SetIsCompleteObjCClass(is_complete);
340}
341
342static void SetMemberOwningModule(clang::Decl *member,
343 const clang::Decl *parent) {
344 if (!member || !parent)
345 return;
346
347 OptionalClangModuleID id(parent->getOwningModuleID());
348 if (!id.HasValue())
349 return;
350
351 member->setFromASTFile();
352 member->setOwningModuleID(id.GetValue());
353 member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
354 if (llvm::isa<clang::NamedDecl>(member))
355 if (auto *dc = llvm::dyn_cast<clang::DeclContext>(parent)) {
356 dc->setHasExternalVisibleStorage(true);
357 // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be
358 // called when searching for members.
359 dc->setHasExternalLexicalStorage(true);
360 }
361}
362
364
365bool TypeSystemClang::IsOperator(llvm::StringRef name,
366 clang::OverloadedOperatorKind &op_kind) {
367 // All operators have to start with "operator".
368 if (!name.consume_front("operator"))
369 return false;
370
371 // Remember if there was a space after "operator". This is necessary to
372 // check for collisions with strangely named functions like "operatorint()".
373 bool space_after_operator = name.consume_front(" ");
374
375 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
376 .Case("+", clang::OO_Plus)
377 .Case("+=", clang::OO_PlusEqual)
378 .Case("++", clang::OO_PlusPlus)
379 .Case("-", clang::OO_Minus)
380 .Case("-=", clang::OO_MinusEqual)
381 .Case("--", clang::OO_MinusMinus)
382 .Case("->", clang::OO_Arrow)
383 .Case("->*", clang::OO_ArrowStar)
384 .Case("*", clang::OO_Star)
385 .Case("*=", clang::OO_StarEqual)
386 .Case("/", clang::OO_Slash)
387 .Case("/=", clang::OO_SlashEqual)
388 .Case("%", clang::OO_Percent)
389 .Case("%=", clang::OO_PercentEqual)
390 .Case("^", clang::OO_Caret)
391 .Case("^=", clang::OO_CaretEqual)
392 .Case("&", clang::OO_Amp)
393 .Case("&=", clang::OO_AmpEqual)
394 .Case("&&", clang::OO_AmpAmp)
395 .Case("|", clang::OO_Pipe)
396 .Case("|=", clang::OO_PipeEqual)
397 .Case("||", clang::OO_PipePipe)
398 .Case("~", clang::OO_Tilde)
399 .Case("!", clang::OO_Exclaim)
400 .Case("!=", clang::OO_ExclaimEqual)
401 .Case("=", clang::OO_Equal)
402 .Case("==", clang::OO_EqualEqual)
403 .Case("<", clang::OO_Less)
404 .Case("<=>", clang::OO_Spaceship)
405 .Case("<<", clang::OO_LessLess)
406 .Case("<<=", clang::OO_LessLessEqual)
407 .Case("<=", clang::OO_LessEqual)
408 .Case(">", clang::OO_Greater)
409 .Case(">>", clang::OO_GreaterGreater)
410 .Case(">>=", clang::OO_GreaterGreaterEqual)
411 .Case(">=", clang::OO_GreaterEqual)
412 .Case("()", clang::OO_Call)
413 .Case("[]", clang::OO_Subscript)
414 .Case(",", clang::OO_Comma)
415 .Default(clang::NUM_OVERLOADED_OPERATORS);
416
417 // We found a fitting operator, so we can exit now.
418 if (op_kind != clang::NUM_OVERLOADED_OPERATORS)
419 return true;
420
421 // After the "operator " or "operator" part is something unknown. This means
422 // it's either one of the named operators (new/delete), a conversion operator
423 // (e.g. operator bool) or a function which name starts with "operator"
424 // (e.g. void operatorbool).
425
426 // If it's a function that starts with operator it can't have a space after
427 // "operator" because identifiers can't contain spaces.
428 // E.g. "operator int" (conversion operator)
429 // vs. "operatorint" (function with colliding name).
430 if (!space_after_operator)
431 return false; // not an operator.
432
433 // Now the operator is either one of the named operators or a conversion
434 // operator.
435 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
436 .Case("new", clang::OO_New)
437 .Case("new[]", clang::OO_Array_New)
438 .Case("delete", clang::OO_Delete)
439 .Case("delete[]", clang::OO_Array_Delete)
440 // conversion operators hit this case.
441 .Default(clang::NUM_OVERLOADED_OPERATORS);
442
443 return true;
444}
445
446clang::AccessSpecifier
448 switch (access) {
449 default:
450 break;
451 case eAccessNone:
452 return AS_none;
453 case eAccessPublic:
454 return AS_public;
455 case eAccessPrivate:
456 return AS_private;
457 case eAccessProtected:
458 return AS_protected;
459 }
460 return AS_none;
461}
462
463static void ParseLangArgs(LangOptions &Opts, ArchSpec arch) {
464 // FIXME: Cleanup per-file based stuff.
465
466 std::vector<std::string> Includes;
467 LangOptions::setLangDefaults(Opts, clang::Language::ObjCXX, arch.GetTriple(),
468 Includes, clang::LangStandard::lang_gnucxx98);
469
470 Opts.setValueVisibilityMode(DefaultVisibility);
471
472 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
473 // specified, or -std is set to a conforming mode.
474 Opts.Trigraphs = !Opts.GNUMode;
475 Opts.CharIsSigned = arch.CharIsSignedByDefault();
476 Opts.OptimizeSize = 0;
477
478 // FIXME: Eliminate this dependency.
479 // unsigned Opt =
480 // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
481 // Opts.Optimize = Opt != 0;
482 unsigned Opt = 0;
483
484 // This is the __NO_INLINE__ define, which just depends on things like the
485 // optimization level and -fno-inline, not actually whether the backend has
486 // inlining enabled.
487 //
488 // FIXME: This is affected by other options (-fno-inline).
489 Opts.NoInlineDefine = !Opt;
490
491 // This is needed to allocate the extra space for the owning module
492 // on each decl.
493 Opts.ModulesLocalVisibility = 1;
494}
495
497 llvm::Triple target_triple) {
498 m_display_name = name.str();
499 if (!target_triple.str().empty())
500 SetTargetTriple(target_triple.str());
501 // The caller didn't pass an ASTContext so create a new one for this
502 // TypeSystemClang.
504
505 LogCreation();
506}
507
508TypeSystemClang::TypeSystemClang(llvm::StringRef name,
509 ASTContext &existing_ctxt) {
510 m_display_name = name.str();
511 SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str());
512
513 m_ast_up.reset(&existing_ctxt);
514 GetASTMap().Insert(&existing_ctxt, this);
515
516 LogCreation();
517}
518
519// Destructor
521
523 lldb_private::Module *module,
524 Target *target) {
525 if (!TypeSystemClangSupportsLanguage(language))
526 return lldb::TypeSystemSP();
527 ArchSpec arch;
528 if (module)
529 arch = module->GetArchitecture();
530 else if (target)
531 arch = target->GetArchitecture();
532
533 if (!arch.IsValid())
534 return lldb::TypeSystemSP();
535
536 llvm::Triple triple = arch.GetTriple();
537 // LLVM wants this to be set to iOS or MacOSX; if we're working on
538 // a bare-boards type image, change the triple for llvm's benefit.
539 if (triple.getVendor() == llvm::Triple::Apple &&
540 triple.getOS() == llvm::Triple::UnknownOS) {
541 if (triple.getArch() == llvm::Triple::arm ||
542 triple.getArch() == llvm::Triple::aarch64 ||
543 triple.getArch() == llvm::Triple::aarch64_32 ||
544 triple.getArch() == llvm::Triple::thumb) {
545 triple.setOS(llvm::Triple::IOS);
546 } else {
547 triple.setOS(llvm::Triple::MacOSX);
548 }
549 }
550
551 if (module) {
552 std::string ast_name =
553 "ASTContext for '" + module->GetFileSpec().GetPath() + "'";
554 return std::make_shared<TypeSystemClang>(ast_name, triple);
555 } else if (target && target->IsValid())
556 return std::make_shared<ScratchTypeSystemClang>(*target, triple);
557 return lldb::TypeSystemSP();
558}
559
561 LanguageSet languages;
563 languages.Insert(lldb::eLanguageTypeC);
575 return languages;
576}
577
579 LanguageSet languages;
587 return languages;
588}
589
592 GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance,
594}
595
598}
599
601 assert(m_ast_up);
602 GetASTMap().Erase(m_ast_up.get());
603 if (!m_ast_owned)
604 m_ast_up.release();
605
606 m_builtins_up.reset();
607 m_selector_table_up.reset();
608 m_identifier_table_up.reset();
609 m_target_info_up.reset();
610 m_target_options_rp.reset();
612 m_source_manager_up.reset();
613 m_language_options_up.reset();
614}
615
617 // Ensure that the new sema actually belongs to our ASTContext.
618 assert(s == nullptr || &s->getASTContext() == m_ast_up.get());
619 m_sema = s;
620}
621
623 return m_target_triple.c_str();
624}
625
626void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) {
627 m_target_triple = target_triple.str();
628}
629
631 llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
632 ASTContext &ast = getASTContext();
633 ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
634 ast.setExternalSource(ast_source_up);
635}
636
638 assert(m_ast_up);
639 return *m_ast_up;
640}
641
642class NullDiagnosticConsumer : public DiagnosticConsumer {
643public:
644 NullDiagnosticConsumer() { m_log = GetLog(LLDBLog::Expressions); }
645
646 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
647 const clang::Diagnostic &info) override {
648 if (m_log) {
649 llvm::SmallVector<char, 32> diag_str(10);
650 info.FormatDiagnostic(diag_str);
651 diag_str.push_back('\0');
652 LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data());
653 }
654 }
655
656 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
657 return new NullDiagnosticConsumer();
658 }
659
660private:
662};
663
665 assert(!m_ast_up);
666 m_ast_owned = true;
667
668 m_language_options_up = std::make_unique<LangOptions>();
670
672 std::make_unique<IdentifierTable>(*m_language_options_up, nullptr);
673 m_builtins_up = std::make_unique<Builtin::Context>();
674
675 m_selector_table_up = std::make_unique<SelectorTable>();
676
677 clang::FileSystemOptions file_system_options;
678 m_file_manager_up = std::make_unique<clang::FileManager>(
679 file_system_options, FileSystem::Instance().GetVirtualFileSystem());
680
681 llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
683 std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions());
684
685 m_source_manager_up = std::make_unique<clang::SourceManager>(
687 m_ast_up = std::make_unique<ASTContext>(
689 *m_selector_table_up, *m_builtins_up, TU_Complete);
690
691 m_diagnostic_consumer_up = std::make_unique<NullDiagnosticConsumer>();
692 m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), false);
693
694 // This can be NULL if we don't know anything about the architecture or if
695 // the target for an architecture isn't enabled in the llvm/clang that we
696 // built
697 TargetInfo *target_info = getTargetInfo();
698 if (target_info)
699 m_ast_up->InitBuiltinTypes(*target_info);
700
701 GetASTMap().Insert(m_ast_up.get(), this);
702
703 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
705 SetExternalSource(ast_source_up);
706}
707
709 TypeSystemClang *clang_ast = GetASTMap().Lookup(ast);
710 return clang_ast;
711}
712
713clang::MangleContext *TypeSystemClang::getMangleContext() {
714 if (m_mangle_ctx_up == nullptr)
715 m_mangle_ctx_up.reset(getASTContext().createMangleContext());
716 return m_mangle_ctx_up.get();
717}
718
719std::shared_ptr<clang::TargetOptions> &TypeSystemClang::getTargetOptions() {
720 if (m_target_options_rp == nullptr && !m_target_triple.empty()) {
721 m_target_options_rp = std::make_shared<clang::TargetOptions>();
722 if (m_target_options_rp != nullptr)
724 }
725 return m_target_options_rp;
726}
727
729 // target_triple should be something like "x86_64-apple-macosx"
730 if (m_target_info_up == nullptr && !m_target_triple.empty())
731 m_target_info_up.reset(TargetInfo::CreateTargetInfo(
732 getASTContext().getDiagnostics(), getTargetOptions()));
733 return m_target_info_up.get();
734}
735
736#pragma mark Basic Types
737
738static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
739 ASTContext &ast, QualType qual_type) {
740 uint64_t qual_type_bit_size = ast.getTypeSize(qual_type);
741 return qual_type_bit_size == bit_size;
742}
743
746 size_t bit_size) {
747 ASTContext &ast = getASTContext();
748 switch (encoding) {
749 case eEncodingInvalid:
750 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
751 return GetType(ast.VoidPtrTy);
752 break;
753
754 case eEncodingUint:
755 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
756 return GetType(ast.UnsignedCharTy);
757 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
758 return GetType(ast.UnsignedShortTy);
759 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
760 return GetType(ast.UnsignedIntTy);
761 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
762 return GetType(ast.UnsignedLongTy);
763 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
764 return GetType(ast.UnsignedLongLongTy);
765 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
766 return GetType(ast.UnsignedInt128Ty);
767 break;
768
769 case eEncodingSint:
770 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
771 return GetType(ast.SignedCharTy);
772 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
773 return GetType(ast.ShortTy);
774 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
775 return GetType(ast.IntTy);
776 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
777 return GetType(ast.LongTy);
778 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
779 return GetType(ast.LongLongTy);
780 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
781 return GetType(ast.Int128Ty);
782 break;
783
784 case eEncodingIEEE754:
785 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
786 return GetType(ast.FloatTy);
787 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
788 return GetType(ast.DoubleTy);
789 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
790 return GetType(ast.LongDoubleTy);
791 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
792 return GetType(ast.HalfTy);
793 break;
794
795 case eEncodingVector:
796 // Sanity check that bit_size is a multiple of 8's.
797 if (bit_size && !(bit_size & 0x7u))
798 return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8));
799 break;
800 }
801
802 return CompilerType();
803}
804
806 static const llvm::StringMap<lldb::BasicType> g_type_map = {
807 // "void"
808 {"void", eBasicTypeVoid},
809
810 // "char"
811 {"char", eBasicTypeChar},
812 {"signed char", eBasicTypeSignedChar},
813 {"unsigned char", eBasicTypeUnsignedChar},
814 {"wchar_t", eBasicTypeWChar},
815 {"signed wchar_t", eBasicTypeSignedWChar},
816 {"unsigned wchar_t", eBasicTypeUnsignedWChar},
817
818 // "short"
819 {"short", eBasicTypeShort},
820 {"short int", eBasicTypeShort},
821 {"unsigned short", eBasicTypeUnsignedShort},
822 {"unsigned short int", eBasicTypeUnsignedShort},
823
824 // "int"
825 {"int", eBasicTypeInt},
826 {"signed int", eBasicTypeInt},
827 {"unsigned int", eBasicTypeUnsignedInt},
828 {"unsigned", eBasicTypeUnsignedInt},
829
830 // "long"
831 {"long", eBasicTypeLong},
832 {"long int", eBasicTypeLong},
833 {"unsigned long", eBasicTypeUnsignedLong},
834 {"unsigned long int", eBasicTypeUnsignedLong},
835
836 // "long long"
837 {"long long", eBasicTypeLongLong},
838 {"long long int", eBasicTypeLongLong},
839 {"unsigned long long", eBasicTypeUnsignedLongLong},
840 {"unsigned long long int", eBasicTypeUnsignedLongLong},
841
842 // "int128"
843 {"__int128_t", eBasicTypeInt128},
844 {"__uint128_t", eBasicTypeUnsignedInt128},
845
846 // "bool"
847 {"bool", eBasicTypeBool},
848 {"_Bool", eBasicTypeBool},
849
850 // Miscellaneous
851 {"float", eBasicTypeFloat},
852 {"double", eBasicTypeDouble},
853 {"long double", eBasicTypeLongDouble},
854 {"id", eBasicTypeObjCID},
855 {"SEL", eBasicTypeObjCSel},
856 {"nullptr", eBasicTypeNullPtr},
857 };
858
859 auto iter = g_type_map.find(name);
860 if (iter == g_type_map.end())
861 return eBasicTypeInvalid;
862
863 return iter->second;
864}
865
867 if (m_pointer_byte_size == 0)
868 if (auto size = GetBasicType(lldb::eBasicTypeVoid)
870 .GetByteSize(nullptr))
871 m_pointer_byte_size = *size;
872 return m_pointer_byte_size;
873}
874
876 clang::ASTContext &ast = getASTContext();
877
879 GetOpaqueCompilerType(&ast, basic_type);
880
881 if (clang_type)
882 return CompilerType(weak_from_this(), clang_type);
883 return CompilerType();
884}
885
887 llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) {
888 ASTContext &ast = getASTContext();
889
890 switch (dw_ate) {
891 default:
892 break;
893
894 case DW_ATE_address:
895 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
896 return GetType(ast.VoidPtrTy);
897 break;
898
899 case DW_ATE_boolean:
900 if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy))
901 return GetType(ast.BoolTy);
902 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
903 return GetType(ast.UnsignedCharTy);
904 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
905 return GetType(ast.UnsignedShortTy);
906 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
907 return GetType(ast.UnsignedIntTy);
908 break;
909
910 case DW_ATE_lo_user:
911 // This has been seen to mean DW_AT_complex_integer
912 if (type_name.contains("complex")) {
913 CompilerType complex_int_clang_type =
914 GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
915 bit_size / 2);
916 return GetType(
917 ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type)));
918 }
919 break;
920
921 case DW_ATE_complex_float: {
922 CanQualType FloatComplexTy = ast.getComplexType(ast.FloatTy);
923 if (QualTypeMatchesBitSize(bit_size, ast, FloatComplexTy))
924 return GetType(FloatComplexTy);
925
926 CanQualType DoubleComplexTy = ast.getComplexType(ast.DoubleTy);
927 if (QualTypeMatchesBitSize(bit_size, ast, DoubleComplexTy))
928 return GetType(DoubleComplexTy);
929
930 CanQualType LongDoubleComplexTy = ast.getComplexType(ast.LongDoubleTy);
931 if (QualTypeMatchesBitSize(bit_size, ast, LongDoubleComplexTy))
932 return GetType(LongDoubleComplexTy);
933
934 CompilerType complex_float_clang_type =
935 GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
936 bit_size / 2);
937 return GetType(
938 ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type)));
939 }
940
941 case DW_ATE_float:
942 if (type_name == "float" &&
943 QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
944 return GetType(ast.FloatTy);
945 if (type_name == "double" &&
946 QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
947 return GetType(ast.DoubleTy);
948 if (type_name == "long double" &&
949 QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
950 return GetType(ast.LongDoubleTy);
951 // Fall back to not requiring a name match
952 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
953 return GetType(ast.FloatTy);
954 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
955 return GetType(ast.DoubleTy);
956 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
957 return GetType(ast.LongDoubleTy);
958 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
959 return GetType(ast.HalfTy);
960 break;
961
962 case DW_ATE_signed:
963 if (!type_name.empty()) {
964 if (type_name == "wchar_t" &&
965 QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) &&
966 (getTargetInfo() &&
967 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
968 return GetType(ast.WCharTy);
969 if (type_name == "void" &&
970 QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy))
971 return GetType(ast.VoidTy);
972 if (type_name.contains("long long") &&
973 QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
974 return GetType(ast.LongLongTy);
975 if (type_name.contains("long") &&
976 QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
977 return GetType(ast.LongTy);
978 if (type_name.contains("short") &&
979 QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
980 return GetType(ast.ShortTy);
981 if (type_name.contains("char")) {
982 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
983 return GetType(ast.CharTy);
984 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
985 return GetType(ast.SignedCharTy);
986 }
987 if (type_name.contains("int")) {
988 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
989 return GetType(ast.IntTy);
990 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
991 return GetType(ast.Int128Ty);
992 }
993 }
994 // We weren't able to match up a type name, just search by size
995 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
996 return GetType(ast.CharTy);
997 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
998 return GetType(ast.ShortTy);
999 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1000 return GetType(ast.IntTy);
1001 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1002 return GetType(ast.LongTy);
1003 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1004 return GetType(ast.LongLongTy);
1005 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1006 return GetType(ast.Int128Ty);
1007 break;
1008
1009 case DW_ATE_signed_char:
1010 if (type_name == "char") {
1011 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1012 return GetType(ast.CharTy);
1013 }
1014 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1015 return GetType(ast.SignedCharTy);
1016 break;
1017
1018 case DW_ATE_unsigned:
1019 if (!type_name.empty()) {
1020 if (type_name == "wchar_t") {
1021 if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) {
1022 if (!(getTargetInfo() &&
1023 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1024 return GetType(ast.WCharTy);
1025 }
1026 }
1027 if (type_name.contains("long long")) {
1028 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1029 return GetType(ast.UnsignedLongLongTy);
1030 } else if (type_name.contains("long")) {
1031 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1032 return GetType(ast.UnsignedLongTy);
1033 } else if (type_name.contains("short")) {
1034 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1035 return GetType(ast.UnsignedShortTy);
1036 } else if (type_name.contains("char")) {
1037 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1038 return GetType(ast.UnsignedCharTy);
1039 } else if (type_name.contains("int")) {
1040 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1041 return GetType(ast.UnsignedIntTy);
1042 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1043 return GetType(ast.UnsignedInt128Ty);
1044 }
1045 }
1046 // We weren't able to match up a type name, just search by size
1047 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1048 return GetType(ast.UnsignedCharTy);
1049 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1050 return GetType(ast.UnsignedShortTy);
1051 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1052 return GetType(ast.UnsignedIntTy);
1053 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1054 return GetType(ast.UnsignedLongTy);
1055 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1056 return GetType(ast.UnsignedLongLongTy);
1057 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1058 return GetType(ast.UnsignedInt128Ty);
1059 break;
1060
1061 case DW_ATE_unsigned_char:
1062 if (type_name == "char") {
1063 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1064 return GetType(ast.CharTy);
1065 }
1066 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1067 return GetType(ast.UnsignedCharTy);
1068 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1069 return GetType(ast.UnsignedShortTy);
1070 break;
1071
1072 case DW_ATE_imaginary_float:
1073 break;
1074
1075 case DW_ATE_UTF:
1076 switch (bit_size) {
1077 case 8:
1078 return GetType(ast.Char8Ty);
1079 case 16:
1080 return GetType(ast.Char16Ty);
1081 case 32:
1082 return GetType(ast.Char32Ty);
1083 default:
1084 if (!type_name.empty()) {
1085 if (type_name == "char16_t")
1086 return GetType(ast.Char16Ty);
1087 if (type_name == "char32_t")
1088 return GetType(ast.Char32Ty);
1089 if (type_name == "char8_t")
1090 return GetType(ast.Char8Ty);
1091 }
1092 }
1093 break;
1094 }
1095
1096 Log *log = GetLog(LLDBLog::Types);
1097 LLDB_LOG(log,
1098 "error: need to add support for DW_TAG_base_type '{0}' "
1099 "encoded with DW_ATE = {1:x}, bit_size = {2}",
1100 type_name, dw_ate, bit_size);
1101 return CompilerType();
1102}
1103
1105 ASTContext &ast = getASTContext();
1106 QualType char_type(ast.CharTy);
1107
1108 if (is_const)
1109 char_type.addConst();
1110
1111 return GetType(ast.getPointerType(char_type));
1112}
1113
1115 bool ignore_qualifiers) {
1116 auto ast = type1.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
1117 if (!ast || type1.GetTypeSystem() != type2.GetTypeSystem())
1118 return false;
1119
1120 if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1121 return true;
1122
1123 QualType type1_qual = ClangUtil::GetQualType(type1);
1124 QualType type2_qual = ClangUtil::GetQualType(type2);
1125
1126 if (ignore_qualifiers) {
1127 type1_qual = type1_qual.getUnqualifiedType();
1128 type2_qual = type2_qual.getUnqualifiedType();
1129 }
1130
1131 return ast->getASTContext().hasSameType(type1_qual, type2_qual);
1132}
1133
1135 if (!opaque_decl)
1136 return CompilerType();
1137
1138 clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl);
1139 if (auto *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl))
1140 return GetTypeForDecl(named_decl);
1141 return CompilerType();
1142}
1143
1145 // Check that the DeclContext actually belongs to this ASTContext.
1146 assert(&ctx->getParentASTContext() == &getASTContext());
1147 return CompilerDeclContext(this, ctx);
1148}
1149
1151 if (clang::ObjCInterfaceDecl *interface_decl =
1152 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1153 return GetTypeForDecl(interface_decl);
1154 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1155 return GetTypeForDecl(tag_decl);
1156 if (clang::ValueDecl *value_decl = llvm::dyn_cast<clang::ValueDecl>(decl))
1157 return GetTypeForDecl(value_decl);
1158 return CompilerType();
1159}
1160
1162 return GetType(getASTContext().getTagDeclType(decl));
1163}
1164
1165CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1166 return GetType(getASTContext().getObjCInterfaceType(decl));
1167}
1168
1169CompilerType TypeSystemClang::GetTypeForDecl(clang::ValueDecl *value_decl) {
1170 return GetType(value_decl->getType());
1171}
1172
1173#pragma mark Structure, Unions, Classes
1174
1176 OptionalClangModuleID owning_module) {
1177 if (!decl || !owning_module.HasValue())
1178 return;
1179
1180 decl->setFromASTFile();
1181 decl->setOwningModuleID(owning_module.GetValue());
1182 decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
1183}
1184
1187 OptionalClangModuleID parent,
1188 bool is_framework, bool is_explicit) {
1189 // Get the external AST source which holds the modules.
1190 auto *ast_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1191 getASTContext().getExternalSource());
1192 assert(ast_source && "external ast source was lost");
1193 if (!ast_source)
1194 return {};
1195
1196 // Lazily initialize the module map.
1197 if (!m_header_search_up) {
1198 auto HSOpts = std::make_shared<clang::HeaderSearchOptions>();
1199 m_header_search_up = std::make_unique<clang::HeaderSearch>(
1202 m_module_map_up = std::make_unique<clang::ModuleMap>(
1205 }
1206
1207 // Get or create the module context.
1208 bool created;
1209 clang::Module *module;
1210 auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue());
1211 std::tie(module, created) = m_module_map_up->findOrCreateModule(
1212 name, parent_desc ? parent_desc->getModuleOrNull() : nullptr,
1213 is_framework, is_explicit);
1214 if (!created)
1215 return ast_source->GetIDForModule(module);
1216
1217 return ast_source->RegisterModule(module);
1218}
1219
1221 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1222 AccessType access_type, llvm::StringRef name, int kind,
1223 LanguageType language, std::optional<ClangASTMetadata> metadata,
1224 bool exports_symbols) {
1225 ASTContext &ast = getASTContext();
1226
1227 if (decl_ctx == nullptr)
1228 decl_ctx = ast.getTranslationUnitDecl();
1229
1230 if (language == eLanguageTypeObjC ||
1231 language == eLanguageTypeObjC_plus_plus) {
1232 bool isInternal = false;
1233 return CreateObjCClass(name, decl_ctx, owning_module, isInternal, metadata);
1234 }
1235
1236 // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1237 // we will need to update this code. I was told to currently always use the
1238 // CXXRecordDecl class since we often don't know from debug information if
1239 // something is struct or a class, so we default to always use the more
1240 // complete definition just in case.
1241
1242 bool has_name = !name.empty();
1243 CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, GlobalDeclID());
1244 decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1245 decl->setDeclContext(decl_ctx);
1246 if (has_name)
1247 decl->setDeclName(&ast.Idents.get(name));
1248 SetOwningModule(decl, owning_module);
1249
1250 if (!has_name) {
1251 // In C++ a lambda is also represented as an unnamed class. This is
1252 // different from an *anonymous class* that the user wrote:
1253 //
1254 // struct A {
1255 // // anonymous class (GNU/MSVC extension)
1256 // struct {
1257 // int x;
1258 // };
1259 // // unnamed class within a class
1260 // struct {
1261 // int y;
1262 // } B;
1263 // };
1264 //
1265 // void f() {
1266 // // unammed class outside of a class
1267 // struct {
1268 // int z;
1269 // } C;
1270 // }
1271 //
1272 // Anonymous classes is a GNU/MSVC extension that clang supports. It
1273 // requires the anonymous class be embedded within a class. So the new
1274 // heuristic verifies this condition.
1275 if (isa<CXXRecordDecl>(decl_ctx) && exports_symbols)
1276 decl->setAnonymousStructOrUnion(true);
1277 }
1278
1279 if (metadata)
1280 SetMetadata(decl, *metadata);
1281
1282 if (access_type != eAccessNone)
1283 decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1284
1285 if (decl_ctx)
1286 decl_ctx->addDecl(decl);
1287
1288 return GetType(ast.getTagDeclType(decl));
1289}
1290
1291namespace {
1292/// Returns true iff the given TemplateArgument should be represented as an
1293/// NonTypeTemplateParmDecl in the AST.
1294bool IsValueParam(const clang::TemplateArgument &argument) {
1295 return argument.getKind() == TemplateArgument::Integral;
1296}
1297
1298void AddAccessSpecifierDecl(clang::CXXRecordDecl *cxx_record_decl,
1299 ASTContext &ct,
1300 clang::AccessSpecifier previous_access,
1301 clang::AccessSpecifier access_specifier) {
1302 if (!cxx_record_decl->isClass() && !cxx_record_decl->isStruct())
1303 return;
1304 if (previous_access != access_specifier) {
1305 // For struct, don't add AS_public if it's the first AccessSpecDecl.
1306 // For class, don't add AS_private if it's the first AccessSpecDecl.
1307 if ((cxx_record_decl->isStruct() &&
1308 previous_access == clang::AccessSpecifier::AS_none &&
1309 access_specifier == clang::AccessSpecifier::AS_public) ||
1310 (cxx_record_decl->isClass() &&
1311 previous_access == clang::AccessSpecifier::AS_none &&
1312 access_specifier == clang::AccessSpecifier::AS_private)) {
1313 return;
1314 }
1315 cxx_record_decl->addDecl(
1316 AccessSpecDecl::Create(ct, access_specifier, cxx_record_decl,
1317 SourceLocation(), SourceLocation()));
1318 }
1319}
1320} // namespace
1321
1322static TemplateParameterList *CreateTemplateParameterList(
1323 ASTContext &ast,
1324 const TypeSystemClang::TemplateParameterInfos &template_param_infos,
1325 llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1326 const bool parameter_pack = false;
1327 const bool is_typename = false;
1328 const unsigned depth = 0;
1329 const size_t num_template_params = template_param_infos.Size();
1330 DeclContext *const decl_context =
1331 ast.getTranslationUnitDecl(); // Is this the right decl context?,
1332
1333 auto const &args = template_param_infos.GetArgs();
1334 auto const &names = template_param_infos.GetNames();
1335 for (size_t i = 0; i < num_template_params; ++i) {
1336 const char *name = names[i];
1337
1338 IdentifierInfo *identifier_info = nullptr;
1339 if (name && name[0])
1340 identifier_info = &ast.Idents.get(name);
1341 TemplateArgument const &targ = args[i];
1342 if (IsValueParam(targ)) {
1343 QualType template_param_type = targ.getIntegralType();
1344 template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1345 ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1346 identifier_info, template_param_type, parameter_pack,
1347 ast.getTrivialTypeSourceInfo(template_param_type)));
1348 } else {
1349 template_param_decls.push_back(TemplateTypeParmDecl::Create(
1350 ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1351 identifier_info, is_typename, parameter_pack));
1352 }
1353 }
1354
1355 if (template_param_infos.hasParameterPack()) {
1356 IdentifierInfo *identifier_info = nullptr;
1357 if (template_param_infos.HasPackName())
1358 identifier_info = &ast.Idents.get(template_param_infos.GetPackName());
1359 const bool parameter_pack_true = true;
1360
1361 if (!template_param_infos.GetParameterPack().IsEmpty() &&
1362 IsValueParam(template_param_infos.GetParameterPack().Front())) {
1363 QualType template_param_type =
1364 template_param_infos.GetParameterPack().Front().getIntegralType();
1365 template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1366 ast, decl_context, SourceLocation(), SourceLocation(), depth,
1367 num_template_params, identifier_info, template_param_type,
1368 parameter_pack_true,
1369 ast.getTrivialTypeSourceInfo(template_param_type)));
1370 } else {
1371 template_param_decls.push_back(TemplateTypeParmDecl::Create(
1372 ast, decl_context, SourceLocation(), SourceLocation(), depth,
1373 num_template_params, identifier_info, is_typename,
1374 parameter_pack_true));
1375 }
1376 }
1377 clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1378 TemplateParameterList *template_param_list = TemplateParameterList::Create(
1379 ast, SourceLocation(), SourceLocation(), template_param_decls,
1380 SourceLocation(), requires_clause);
1381 return template_param_list;
1382}
1383
1385 const TemplateParameterInfos &template_param_infos) {
1386 llvm::SmallVector<NamedDecl *, 8> ignore;
1387 clang::TemplateParameterList *template_param_list =
1388 CreateTemplateParameterList(getASTContext(), template_param_infos,
1389 ignore);
1390 llvm::SmallVector<clang::TemplateArgument, 2> args(
1391 template_param_infos.GetArgs());
1392 if (template_param_infos.hasParameterPack()) {
1393 llvm::ArrayRef<TemplateArgument> pack_args =
1394 template_param_infos.GetParameterPackArgs();
1395 args.append(pack_args.begin(), pack_args.end());
1396 }
1397 std::string str;
1398 llvm::raw_string_ostream os(str);
1399 clang::printTemplateArgumentList(os, args, GetTypePrintingPolicy(),
1400 template_param_list);
1401 return str;
1402}
1403
1405 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1406 clang::FunctionDecl *func_decl,
1407 const TemplateParameterInfos &template_param_infos) {
1408 // /// Create a function template node.
1409 ASTContext &ast = getASTContext();
1410
1411 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1412 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1413 ast, template_param_infos, template_param_decls);
1414 FunctionTemplateDecl *func_tmpl_decl =
1415 FunctionTemplateDecl::CreateDeserialized(ast, GlobalDeclID());
1416 func_tmpl_decl->setDeclContext(decl_ctx);
1417 func_tmpl_decl->setLocation(func_decl->getLocation());
1418 func_tmpl_decl->setDeclName(func_decl->getDeclName());
1419 func_tmpl_decl->setTemplateParameters(template_param_list);
1420 func_tmpl_decl->init(func_decl);
1421 SetOwningModule(func_tmpl_decl, owning_module);
1422
1423 for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1424 i < template_param_decl_count; ++i) {
1425 // TODO: verify which decl context we should put template_param_decls into..
1426 template_param_decls[i]->setDeclContext(func_decl);
1427 }
1428 // Function templates inside a record need to have an access specifier.
1429 // It doesn't matter what access specifier we give the template as LLDB
1430 // anyway allows accessing everything inside a record.
1431 if (decl_ctx->isRecord())
1432 func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public);
1433
1434 return func_tmpl_decl;
1435}
1436
1438 FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1439 const TemplateParameterInfos &infos) {
1440 TemplateArgumentList *template_args_ptr = TemplateArgumentList::CreateCopy(
1441 func_decl->getASTContext(), infos.GetArgs());
1442
1443 func_decl->setFunctionTemplateSpecialization(func_tmpl_decl,
1444 template_args_ptr, nullptr);
1445}
1446
1447/// Returns true if the given template parameter can represent the given value.
1448/// For example, `typename T` can represent `int` but not integral values such
1449/// as `int I = 3`.
1450static bool TemplateParameterAllowsValue(NamedDecl *param,
1451 const TemplateArgument &value) {
1452 if (llvm::isa<TemplateTypeParmDecl>(param)) {
1453 // Compare the argument kind, i.e. ensure that <typename> != <int>.
1454 if (value.getKind() != TemplateArgument::Type)
1455 return false;
1456 } else if (auto *type_param =
1457 llvm::dyn_cast<NonTypeTemplateParmDecl>(param)) {
1458 // Compare the argument kind, i.e. ensure that <typename> != <int>.
1459 if (!IsValueParam(value))
1460 return false;
1461 // Compare the integral type, i.e. ensure that <int> != <char>.
1462 if (type_param->getType() != value.getIntegralType())
1463 return false;
1464 } else {
1465 // There is no way to create other parameter decls at the moment, so we
1466 // can't reach this case during normal LLDB usage. Log that this happened
1467 // and assert.
1469 LLDB_LOG(log,
1470 "Don't know how to compare template parameter to passed"
1471 " value. Decl kind of parameter is: {0}",
1472 param->getDeclKindName());
1473 lldbassert(false && "Can't compare this TemplateParmDecl subclass");
1474 // In release builds just fall back to marking the parameter as not
1475 // accepting the value so that we don't try to fit an instantiation to a
1476 // template that doesn't fit. E.g., avoid that `S<1>` is being connected to
1477 // `template<typename T> struct S;`.
1478 return false;
1479 }
1480 return true;
1481}
1482
1483/// Returns true if the given class template declaration could produce an
1484/// instantiation with the specified values.
1485/// For example, `<typename T>` allows the arguments `float`, but not for
1486/// example `bool, float` or `3` (as an integer parameter value).
1488 ClassTemplateDecl *class_template_decl,
1489 const TypeSystemClang::TemplateParameterInfos &instantiation_values) {
1490
1491 TemplateParameterList &params = *class_template_decl->getTemplateParameters();
1492
1493 // Save some work by iterating only once over the found parameters and
1494 // calculate the information related to parameter packs.
1495
1496 // Contains the first pack parameter (or non if there are none).
1497 std::optional<NamedDecl *> pack_parameter;
1498 // Contains the number of non-pack parameters.
1499 size_t non_pack_params = params.size();
1500 for (size_t i = 0; i < params.size(); ++i) {
1501 NamedDecl *param = params.getParam(i);
1502 if (param->isParameterPack()) {
1503 pack_parameter = param;
1504 non_pack_params = i;
1505 break;
1506 }
1507 }
1508
1509 // The found template needs to have compatible non-pack template arguments.
1510 // E.g., ensure that <typename, typename> != <typename>.
1511 // The pack parameters are compared later.
1512 if (non_pack_params != instantiation_values.Size())
1513 return false;
1514
1515 // Ensure that <typename...> != <typename>.
1516 if (pack_parameter.has_value() != instantiation_values.hasParameterPack())
1517 return false;
1518
1519 // Compare the first pack parameter that was found with the first pack
1520 // parameter value. The special case of having an empty parameter pack value
1521 // always fits to a pack parameter.
1522 // E.g., ensure that <int...> != <typename...>.
1523 if (pack_parameter && !instantiation_values.GetParameterPack().IsEmpty() &&
1525 *pack_parameter, instantiation_values.GetParameterPack().Front()))
1526 return false;
1527
1528 // Compare all the non-pack parameters now.
1529 // E.g., ensure that <int> != <long>.
1530 for (const auto pair :
1531 llvm::zip_first(instantiation_values.GetArgs(), params)) {
1532 const TemplateArgument &passed_arg = std::get<0>(pair);
1533 NamedDecl *found_param = std::get<1>(pair);
1534 if (!TemplateParameterAllowsValue(found_param, passed_arg))
1535 return false;
1536 }
1537
1538 return class_template_decl;
1539}
1540
1542 DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1543 lldb::AccessType access_type, llvm::StringRef class_name, int kind,
1544 const TemplateParameterInfos &template_param_infos) {
1545 ASTContext &ast = getASTContext();
1546
1547 ClassTemplateDecl *class_template_decl = nullptr;
1548 if (decl_ctx == nullptr)
1549 decl_ctx = ast.getTranslationUnitDecl();
1550
1551 IdentifierInfo &identifier_info = ast.Idents.get(class_name);
1552 DeclarationName decl_name(&identifier_info);
1553
1554 // Search the AST for an existing ClassTemplateDecl that could be reused.
1555 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1556 for (NamedDecl *decl : result) {
1557 class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1558 if (!class_template_decl)
1559 continue;
1560 // The class template has to be able to represents the instantiation
1561 // values we received. Without this we might end up putting an instantiation
1562 // with arguments such as <int, int> to a template such as:
1563 // template<typename T> struct S;
1564 // Connecting the instantiation to an incompatible template could cause
1565 // problems later on.
1566 if (!ClassTemplateAllowsToInstantiationArgs(class_template_decl,
1567 template_param_infos))
1568 continue;
1569 return class_template_decl;
1570 }
1571
1572 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1573
1574 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1575 ast, template_param_infos, template_param_decls);
1576
1577 CXXRecordDecl *template_cxx_decl =
1578 CXXRecordDecl::CreateDeserialized(ast, GlobalDeclID());
1579 template_cxx_decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1580 // What decl context do we use here? TU? The actual decl context?
1581 template_cxx_decl->setDeclContext(decl_ctx);
1582 template_cxx_decl->setDeclName(decl_name);
1583 SetOwningModule(template_cxx_decl, owning_module);
1584
1585 for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1586 i < template_param_decl_count; ++i) {
1587 template_param_decls[i]->setDeclContext(template_cxx_decl);
1588 }
1589
1590 // With templated classes, we say that a class is templated with
1591 // specializations, but that the bare class has no functions.
1592 // template_cxx_decl->startDefinition();
1593 // template_cxx_decl->completeDefinition();
1594
1595 class_template_decl =
1596 ClassTemplateDecl::CreateDeserialized(ast, GlobalDeclID());
1597 // What decl context do we use here? TU? The actual decl context?
1598 class_template_decl->setDeclContext(decl_ctx);
1599 class_template_decl->setDeclName(decl_name);
1600 class_template_decl->setTemplateParameters(template_param_list);
1601 class_template_decl->init(template_cxx_decl);
1602 template_cxx_decl->setDescribedClassTemplate(class_template_decl);
1603 SetOwningModule(class_template_decl, owning_module);
1604
1605 if (access_type != eAccessNone)
1606 class_template_decl->setAccess(
1608
1609 decl_ctx->addDecl(class_template_decl);
1610
1611 VerifyDecl(class_template_decl);
1612
1613 return class_template_decl;
1614}
1615
1616TemplateTemplateParmDecl *
1618 ASTContext &ast = getASTContext();
1619
1620 auto *decl_ctx = ast.getTranslationUnitDecl();
1621
1622 IdentifierInfo &identifier_info = ast.Idents.get(template_name);
1623 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1624
1625 TypeSystemClang::TemplateParameterInfos template_param_infos;
1626 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1627 ast, template_param_infos, template_param_decls);
1628
1629 // LLDB needs to create those decls only to be able to display a
1630 // type that includes a template template argument. Only the name matters for
1631 // this purpose, so we use dummy values for the other characteristics of the
1632 // type.
1633 return TemplateTemplateParmDecl::Create(ast, decl_ctx, SourceLocation(),
1634 /*Depth=*/0, /*Position=*/0,
1635 /*IsParameterPack=*/false,
1636 &identifier_info, /*Typename=*/false,
1637 template_param_list);
1638}
1639
1640ClassTemplateSpecializationDecl *
1642 DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1643 ClassTemplateDecl *class_template_decl, int kind,
1644 const TemplateParameterInfos &template_param_infos) {
1645 ASTContext &ast = getASTContext();
1646 llvm::SmallVector<clang::TemplateArgument, 2> args(
1647 template_param_infos.Size() +
1648 (template_param_infos.hasParameterPack() ? 1 : 0));
1649
1650 auto const &orig_args = template_param_infos.GetArgs();
1651 std::copy(orig_args.begin(), orig_args.end(), args.begin());
1652 if (template_param_infos.hasParameterPack()) {
1653 args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1654 ast, template_param_infos.GetParameterPackArgs());
1655 }
1656 ClassTemplateSpecializationDecl *class_template_specialization_decl =
1657 ClassTemplateSpecializationDecl::CreateDeserialized(ast, GlobalDeclID());
1658 class_template_specialization_decl->setTagKind(
1659 static_cast<TagDecl::TagKind>(kind));
1660 class_template_specialization_decl->setDeclContext(decl_ctx);
1661 class_template_specialization_decl->setInstantiationOf(class_template_decl);
1662 class_template_specialization_decl->setTemplateArgs(
1663 TemplateArgumentList::CreateCopy(ast, args));
1664 ast.getTypeDeclType(class_template_specialization_decl, nullptr);
1665 class_template_specialization_decl->setDeclName(
1666 class_template_decl->getDeclName());
1667 SetOwningModule(class_template_specialization_decl, owning_module);
1668 decl_ctx->addDecl(class_template_specialization_decl);
1669
1670 class_template_specialization_decl->setSpecializationKind(
1671 TSK_ExplicitSpecialization);
1672
1673 return class_template_specialization_decl;
1674}
1675
1677 ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1678 if (class_template_specialization_decl) {
1679 ASTContext &ast = getASTContext();
1680 return GetType(ast.getTagDeclType(class_template_specialization_decl));
1681 }
1682 return CompilerType();
1683}
1684
1685static inline bool check_op_param(bool is_method,
1686 clang::OverloadedOperatorKind op_kind,
1687 bool unary, bool binary,
1688 uint32_t num_params) {
1689 // Special-case call since it can take any number of operands
1690 if (op_kind == OO_Call)
1691 return true;
1692
1693 // The parameter count doesn't include "this"
1694 if (is_method)
1695 ++num_params;
1696 if (num_params == 1)
1697 return unary;
1698 if (num_params == 2)
1699 return binary;
1700 else
1701 return false;
1702}
1703
1705 bool is_method, clang::OverloadedOperatorKind op_kind,
1706 uint32_t num_params) {
1707 switch (op_kind) {
1708 default:
1709 break;
1710 // C++ standard allows any number of arguments to new/delete
1711 case OO_New:
1712 case OO_Array_New:
1713 case OO_Delete:
1714 case OO_Array_Delete:
1715 return true;
1716 }
1717
1718#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
1719 case OO_##Name: \
1720 return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1721 switch (op_kind) {
1722#include "clang/Basic/OperatorKinds.def"
1723 default:
1724 break;
1725 }
1726 return false;
1727}
1728
1729clang::AccessSpecifier
1731 clang::AccessSpecifier rhs) {
1732 // Make the access equal to the stricter of the field and the nested field's
1733 // access
1734 if (lhs == AS_none || rhs == AS_none)
1735 return AS_none;
1736 if (lhs == AS_private || rhs == AS_private)
1737 return AS_private;
1738 if (lhs == AS_protected || rhs == AS_protected)
1739 return AS_protected;
1740 return AS_public;
1741}
1742
1744 uint32_t &bitfield_bit_size) {
1745 ASTContext &ast = getASTContext();
1746 if (field == nullptr)
1747 return false;
1748
1749 if (field->isBitField()) {
1750 Expr *bit_width_expr = field->getBitWidth();
1751 if (bit_width_expr) {
1752 if (std::optional<llvm::APSInt> bit_width_apsint =
1753 bit_width_expr->getIntegerConstantExpr(ast)) {
1754 bitfield_bit_size = bit_width_apsint->getLimitedValue(UINT32_MAX);
1755 return true;
1756 }
1757 }
1758 }
1759 return false;
1760}
1761
1762bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) {
1763 if (record_decl == nullptr)
1764 return false;
1765
1766 if (!record_decl->field_empty())
1767 return true;
1768
1769 // No fields, lets check this is a CXX record and check the base classes
1770 const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1771 if (cxx_record_decl) {
1772 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1773 for (base_class = cxx_record_decl->bases_begin(),
1774 base_class_end = cxx_record_decl->bases_end();
1775 base_class != base_class_end; ++base_class) {
1776 const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1777 base_class->getType()->getAs<RecordType>()->getDecl());
1778 if (RecordHasFields(base_class_decl))
1779 return true;
1780 }
1781 }
1782
1783 // We always want forcefully completed types to show up so we can print a
1784 // message in the summary that indicates that the type is incomplete.
1785 // This will help users know when they are running into issues with
1786 // -flimit-debug-info instead of just seeing nothing if this is a base class
1787 // (since we were hiding empty base classes), or nothing when you turn open
1788 // an valiable whose type was incomplete.
1789 if (std::optional<ClangASTMetadata> meta_data = GetMetadata(record_decl);
1790 meta_data && meta_data->IsForcefullyCompleted())
1791 return true;
1792
1793 return false;
1794}
1795
1796#pragma mark Objective-C Classes
1797
1799 llvm::StringRef name, clang::DeclContext *decl_ctx,
1800 OptionalClangModuleID owning_module, bool isInternal,
1801 std::optional<ClangASTMetadata> metadata) {
1802 ASTContext &ast = getASTContext();
1803 assert(!name.empty());
1804 if (!decl_ctx)
1805 decl_ctx = ast.getTranslationUnitDecl();
1806
1807 ObjCInterfaceDecl *decl =
1808 ObjCInterfaceDecl::CreateDeserialized(ast, GlobalDeclID());
1809 decl->setDeclContext(decl_ctx);
1810 decl->setDeclName(&ast.Idents.get(name));
1811 decl->setImplicit(isInternal);
1812 SetOwningModule(decl, owning_module);
1813
1814 if (metadata)
1815 SetMetadata(decl, *metadata);
1816
1817 return GetType(ast.getObjCInterfaceType(decl));
1818}
1819
1820bool TypeSystemClang::BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1821 return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl());
1822}
1823
1824uint32_t
1825TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1826 bool omit_empty_base_classes) {
1827 uint32_t num_bases = 0;
1828 if (cxx_record_decl) {
1829 if (omit_empty_base_classes) {
1830 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1831 for (base_class = cxx_record_decl->bases_begin(),
1832 base_class_end = cxx_record_decl->bases_end();
1833 base_class != base_class_end; ++base_class) {
1834 // Skip empty base classes
1835 if (BaseSpecifierIsEmpty(base_class))
1836 continue;
1837 ++num_bases;
1838 }
1839 } else
1840 num_bases = cxx_record_decl->getNumBases();
1841 }
1842 return num_bases;
1843}
1844
1845#pragma mark Namespace Declarations
1846
1848 const char *name, clang::DeclContext *decl_ctx,
1849 OptionalClangModuleID owning_module, bool is_inline) {
1850 NamespaceDecl *namespace_decl = nullptr;
1851 ASTContext &ast = getASTContext();
1852 TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl();
1853 if (!decl_ctx)
1854 decl_ctx = translation_unit_decl;
1855
1856 if (name) {
1857 IdentifierInfo &identifier_info = ast.Idents.get(name);
1858 DeclarationName decl_name(&identifier_info);
1859 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1860 for (NamedDecl *decl : result) {
1861 namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1862 if (namespace_decl)
1863 return namespace_decl;
1864 }
1865
1866 namespace_decl = NamespaceDecl::Create(ast, decl_ctx, is_inline,
1867 SourceLocation(), SourceLocation(),
1868 &identifier_info, nullptr, false);
1869
1870 decl_ctx->addDecl(namespace_decl);
1871 } else {
1872 if (decl_ctx == translation_unit_decl) {
1873 namespace_decl = translation_unit_decl->getAnonymousNamespace();
1874 if (namespace_decl)
1875 return namespace_decl;
1876
1877 namespace_decl =
1878 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1879 SourceLocation(), nullptr, nullptr, false);
1880 translation_unit_decl->setAnonymousNamespace(namespace_decl);
1881 translation_unit_decl->addDecl(namespace_decl);
1882 assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
1883 } else {
1884 NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1885 if (parent_namespace_decl) {
1886 namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1887 if (namespace_decl)
1888 return namespace_decl;
1889 namespace_decl =
1890 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1891 SourceLocation(), nullptr, nullptr, false);
1892 parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1893 parent_namespace_decl->addDecl(namespace_decl);
1894 assert(namespace_decl ==
1895 parent_namespace_decl->getAnonymousNamespace());
1896 } else {
1897 assert(false && "GetUniqueNamespaceDeclaration called with no name and "
1898 "no namespace as decl_ctx");
1899 }
1900 }
1901 }
1902 // Note: namespaces can span multiple modules, so perhaps this isn't a good
1903 // idea.
1904 SetOwningModule(namespace_decl, owning_module);
1905
1906 VerifyDecl(namespace_decl);
1907 return namespace_decl;
1908}
1909
1910clang::BlockDecl *
1912 OptionalClangModuleID owning_module) {
1913 if (ctx) {
1914 clang::BlockDecl *decl =
1915 clang::BlockDecl::CreateDeserialized(getASTContext(), GlobalDeclID());
1916 decl->setDeclContext(ctx);
1917 ctx->addDecl(decl);
1918 SetOwningModule(decl, owning_module);
1919 return decl;
1920 }
1921 return nullptr;
1922}
1923
1924clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1925 clang::DeclContext *right,
1926 clang::DeclContext *root) {
1927 if (root == nullptr)
1928 return nullptr;
1929
1930 std::set<clang::DeclContext *> path_left;
1931 for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
1932 path_left.insert(d);
1933
1934 for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
1935 if (path_left.find(d) != path_left.end())
1936 return d;
1937
1938 return nullptr;
1939}
1940
1942 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1943 clang::NamespaceDecl *ns_decl) {
1944 if (decl_ctx && ns_decl) {
1945 auto *translation_unit = getASTContext().getTranslationUnitDecl();
1946 clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
1947 getASTContext(), decl_ctx, clang::SourceLocation(),
1948 clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
1949 clang::SourceLocation(), ns_decl,
1950 FindLCABetweenDecls(decl_ctx, ns_decl,
1951 translation_unit));
1952 decl_ctx->addDecl(using_decl);
1953 SetOwningModule(using_decl, owning_module);
1954 return using_decl;
1955 }
1956 return nullptr;
1957}
1958
1959clang::UsingDecl *
1960TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
1961 OptionalClangModuleID owning_module,
1962 clang::NamedDecl *target) {
1963 if (current_decl_ctx && target) {
1964 clang::UsingDecl *using_decl = clang::UsingDecl::Create(
1965 getASTContext(), current_decl_ctx, clang::SourceLocation(),
1966 clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
1967 SetOwningModule(using_decl, owning_module);
1968 clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
1969 getASTContext(), current_decl_ctx, clang::SourceLocation(),
1970 target->getDeclName(), using_decl, target);
1971 SetOwningModule(shadow_decl, owning_module);
1972 using_decl->addShadowDecl(shadow_decl);
1973 current_decl_ctx->addDecl(using_decl);
1974 return using_decl;
1975 }
1976 return nullptr;
1977}
1978
1980 clang::DeclContext *decl_context, OptionalClangModuleID owning_module,
1981 const char *name, clang::QualType type) {
1982 if (decl_context) {
1983 clang::VarDecl *var_decl =
1984 clang::VarDecl::CreateDeserialized(getASTContext(), GlobalDeclID());
1985 var_decl->setDeclContext(decl_context);
1986 if (name && name[0])
1987 var_decl->setDeclName(&getASTContext().Idents.getOwn(name));
1988 var_decl->setType(type);
1989 SetOwningModule(var_decl, owning_module);
1990 var_decl->setAccess(clang::AS_public);
1991 decl_context->addDecl(var_decl);
1992 return var_decl;
1993 }
1994 return nullptr;
1995}
1996
1999 lldb::BasicType basic_type) {
2000 switch (basic_type) {
2001 case eBasicTypeVoid:
2002 return ast->VoidTy.getAsOpaquePtr();
2003 case eBasicTypeChar:
2004 return ast->CharTy.getAsOpaquePtr();
2006 return ast->SignedCharTy.getAsOpaquePtr();
2008 return ast->UnsignedCharTy.getAsOpaquePtr();
2009 case eBasicTypeWChar:
2010 return ast->getWCharType().getAsOpaquePtr();
2012 return ast->getSignedWCharType().getAsOpaquePtr();
2014 return ast->getUnsignedWCharType().getAsOpaquePtr();
2015 case eBasicTypeChar8:
2016 return ast->Char8Ty.getAsOpaquePtr();
2017 case eBasicTypeChar16:
2018 return ast->Char16Ty.getAsOpaquePtr();
2019 case eBasicTypeChar32:
2020 return ast->Char32Ty.getAsOpaquePtr();
2021 case eBasicTypeShort:
2022 return ast->ShortTy.getAsOpaquePtr();
2024 return ast->UnsignedShortTy.getAsOpaquePtr();
2025 case eBasicTypeInt:
2026 return ast->IntTy.getAsOpaquePtr();
2028 return ast->UnsignedIntTy.getAsOpaquePtr();
2029 case eBasicTypeLong:
2030 return ast->LongTy.getAsOpaquePtr();
2032 return ast->UnsignedLongTy.getAsOpaquePtr();
2033 case eBasicTypeLongLong:
2034 return ast->LongLongTy.getAsOpaquePtr();
2036 return ast->UnsignedLongLongTy.getAsOpaquePtr();
2037 case eBasicTypeInt128:
2038 return ast->Int128Ty.getAsOpaquePtr();
2040 return ast->UnsignedInt128Ty.getAsOpaquePtr();
2041 case eBasicTypeBool:
2042 return ast->BoolTy.getAsOpaquePtr();
2043 case eBasicTypeHalf:
2044 return ast->HalfTy.getAsOpaquePtr();
2045 case eBasicTypeFloat:
2046 return ast->FloatTy.getAsOpaquePtr();
2047 case eBasicTypeDouble:
2048 return ast->DoubleTy.getAsOpaquePtr();
2050 return ast->LongDoubleTy.getAsOpaquePtr();
2052 return ast->getComplexType(ast->FloatTy).getAsOpaquePtr();
2054 return ast->getComplexType(ast->DoubleTy).getAsOpaquePtr();
2056 return ast->getComplexType(ast->LongDoubleTy).getAsOpaquePtr();
2057 case eBasicTypeObjCID:
2058 return ast->getObjCIdType().getAsOpaquePtr();
2060 return ast->getObjCClassType().getAsOpaquePtr();
2061 case eBasicTypeObjCSel:
2062 return ast->getObjCSelType().getAsOpaquePtr();
2063 case eBasicTypeNullPtr:
2064 return ast->NullPtrTy.getAsOpaquePtr();
2065 default:
2066 return nullptr;
2067 }
2068}
2069
2070#pragma mark Function Types
2071
2072clang::DeclarationName
2074 const CompilerType &function_clang_type) {
2075 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
2076 if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
2077 return DeclarationName(&getASTContext().Idents.get(
2078 name)); // Not operator, but a regular function.
2079
2080 // Check the number of operator parameters. Sometimes we have seen bad DWARF
2081 // that doesn't correctly describe operators and if we try to create a method
2082 // and add it to the class, clang will assert and crash, so we need to make
2083 // sure things are acceptable.
2084 clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
2085 const clang::FunctionProtoType *function_type =
2086 llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
2087 if (function_type == nullptr)
2088 return clang::DeclarationName();
2089
2090 const bool is_method = false;
2091 const unsigned int num_params = function_type->getNumParams();
2093 is_method, op_kind, num_params))
2094 return clang::DeclarationName();
2095
2096 return getASTContext().DeclarationNames.getCXXOperatorName(op_kind);
2097}
2098
2100 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
2101 printing_policy.SuppressTagKeyword = true;
2102 // Inline namespaces are important for some type formatters (e.g., libc++
2103 // and libstdc++ are differentiated by their inline namespaces).
2104 printing_policy.SuppressInlineNamespace = false;
2105 printing_policy.SuppressUnwrittenScope = false;
2106 // Default arguments are also always important for type formatters. Otherwise
2107 // we would need to always specify two type names for the setups where we do
2108 // know the default arguments and where we don't know default arguments.
2109 //
2110 // For example, without this we would need to have formatters for both:
2111 // std::basic_string<char>
2112 // and
2113 // std::basic_string<char, std::char_traits<char>, std::allocator<char> >
2114 // to support setups where LLDB was able to reconstruct default arguments
2115 // (and we then would have suppressed them from the type name) and also setups
2116 // where LLDB wasn't able to reconstruct the default arguments.
2117 printing_policy.SuppressDefaultTemplateArgs = false;
2118 return printing_policy;
2119}
2120
2121std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl,
2122 bool qualified) {
2123 clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
2124 std::string result;
2125 llvm::raw_string_ostream os(result);
2126 named_decl->getNameForDiagnostic(os, printing_policy, qualified);
2127 return result;
2128}
2129
2131 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2132 llvm::StringRef name, const CompilerType &function_clang_type,
2133 clang::StorageClass storage, bool is_inline) {
2134 FunctionDecl *func_decl = nullptr;
2135 ASTContext &ast = getASTContext();
2136 if (!decl_ctx)
2137 decl_ctx = ast.getTranslationUnitDecl();
2138
2139 const bool hasWrittenPrototype = true;
2140 const bool isConstexprSpecified = false;
2141
2142 clang::DeclarationName declarationName =
2143 GetDeclarationName(name, function_clang_type);
2144 func_decl = FunctionDecl::CreateDeserialized(ast, GlobalDeclID());
2145 func_decl->setDeclContext(decl_ctx);
2146 func_decl->setDeclName(declarationName);
2147 func_decl->setType(ClangUtil::GetQualType(function_clang_type));
2148 func_decl->setStorageClass(storage);
2149 func_decl->setInlineSpecified(is_inline);
2150 func_decl->setHasWrittenPrototype(hasWrittenPrototype);
2151 func_decl->setConstexprKind(isConstexprSpecified
2152 ? ConstexprSpecKind::Constexpr
2153 : ConstexprSpecKind::Unspecified);
2154 SetOwningModule(func_decl, owning_module);
2155 decl_ctx->addDecl(func_decl);
2156
2157 VerifyDecl(func_decl);
2158
2159 return func_decl;
2160}
2161
2163 const CompilerType &result_type, const CompilerType *args,
2164 unsigned num_args, bool is_variadic, unsigned type_quals,
2165 clang::CallingConv cc, clang::RefQualifierKind ref_qual) {
2166 if (!result_type || !ClangUtil::IsClangType(result_type))
2167 return CompilerType(); // invalid return type
2168
2169 std::vector<QualType> qual_type_args;
2170 if (num_args > 0 && args == nullptr)
2171 return CompilerType(); // invalid argument array passed in
2172
2173 // Verify that all arguments are valid and the right type
2174 for (unsigned i = 0; i < num_args; ++i) {
2175 if (args[i]) {
2176 // Make sure we have a clang type in args[i] and not a type from another
2177 // language whose name might match
2178 const bool is_clang_type = ClangUtil::IsClangType(args[i]);
2179 lldbassert(is_clang_type);
2180 if (is_clang_type)
2181 qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
2182 else
2183 return CompilerType(); // invalid argument type (must be a clang type)
2184 } else
2185 return CompilerType(); // invalid argument type (empty)
2186 }
2187
2188 // TODO: Detect calling convention in DWARF?
2189 FunctionProtoType::ExtProtoInfo proto_info;
2190 proto_info.ExtInfo = cc;
2191 proto_info.Variadic = is_variadic;
2192 proto_info.ExceptionSpec = EST_None;
2193 proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals);
2194 proto_info.RefQualifier = ref_qual;
2195
2196 return GetType(getASTContext().getFunctionType(
2197 ClangUtil::GetQualType(result_type), qual_type_args, proto_info));
2198}
2199
2201 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2202 const char *name, const CompilerType &param_type, int storage,
2203 bool add_decl) {
2204 ASTContext &ast = getASTContext();
2205 auto *decl = ParmVarDecl::CreateDeserialized(ast, GlobalDeclID());
2206 decl->setDeclContext(decl_ctx);
2207 if (name && name[0])
2208 decl->setDeclName(&ast.Idents.get(name));
2209 decl->setType(ClangUtil::GetQualType(param_type));
2210 decl->setStorageClass(static_cast<clang::StorageClass>(storage));
2211 SetOwningModule(decl, owning_module);
2212 if (add_decl)
2213 decl_ctx->addDecl(decl);
2214
2215 return decl;
2216}
2217
2219 FunctionDecl *function_decl, llvm::ArrayRef<ParmVarDecl *> params) {
2220 if (function_decl)
2221 function_decl->setParams(params);
2222}
2223
2226 QualType block_type = m_ast_up->getBlockPointerType(
2227 clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2228
2229 return GetType(block_type);
2230}
2231
2232#pragma mark Array Types
2233
2236 std::optional<size_t> element_count,
2237 bool is_vector) {
2238 if (!element_type.IsValid())
2239 return {};
2240
2241 ASTContext &ast = getASTContext();
2242
2243 // Unknown number of elements; this is an incomplete array
2244 // (e.g., variable length array with non-constant bounds, or
2245 // a flexible array member).
2246 if (!element_count)
2247 return GetType(
2248 ast.getIncompleteArrayType(ClangUtil::GetQualType(element_type),
2249 clang::ArraySizeModifier::Normal, 0));
2250
2251 if (is_vector)
2252 return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type),
2253 *element_count));
2254
2255 llvm::APInt ap_element_count(64, *element_count);
2256 return GetType(ast.getConstantArrayType(ClangUtil::GetQualType(element_type),
2257 ap_element_count, nullptr,
2258 clang::ArraySizeModifier::Normal, 0));
2259}
2260
2262 llvm::StringRef type_name,
2263 const std::initializer_list<std::pair<const char *, CompilerType>>
2264 &type_fields,
2265 bool packed) {
2266 CompilerType type;
2267 if (!type_name.empty() &&
2268 (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2269 .IsValid()) {
2270 lldbassert(0 && "Trying to create a type for an existing name");
2271 return type;
2272 }
2273
2274 type = CreateRecordType(
2275 nullptr, OptionalClangModuleID(), lldb::eAccessPublic, type_name,
2276 llvm::to_underlying(clang::TagTypeKind::Struct), lldb::eLanguageTypeC);
2278 for (const auto &field : type_fields)
2279 AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2280 0);
2281 if (packed)
2282 SetIsPacked(type);
2284 return type;
2285}
2286
2288 llvm::StringRef type_name,
2289 const std::initializer_list<std::pair<const char *, CompilerType>>
2290 &type_fields,
2291 bool packed) {
2292 CompilerType type;
2293 if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2294 return type;
2295
2296 return CreateStructForIdentifier(type_name, type_fields, packed);
2297}
2298
2299#pragma mark Enumeration Types
2300
2302 llvm::StringRef name, clang::DeclContext *decl_ctx,
2303 OptionalClangModuleID owning_module, const Declaration &decl,
2304 const CompilerType &integer_clang_type, bool is_scoped) {
2305 // TODO: Do something intelligent with the Declaration object passed in
2306 // like maybe filling in the SourceLocation with it...
2307 ASTContext &ast = getASTContext();
2308
2309 // TODO: ask about these...
2310 // const bool IsFixed = false;
2311 EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, GlobalDeclID());
2312 enum_decl->setDeclContext(decl_ctx);
2313 if (!name.empty())
2314 enum_decl->setDeclName(&ast.Idents.get(name));
2315 enum_decl->setScoped(is_scoped);
2316 enum_decl->setScopedUsingClassTag(is_scoped);
2317 enum_decl->setFixed(false);
2318 SetOwningModule(enum_decl, owning_module);
2319 if (decl_ctx)
2320 decl_ctx->addDecl(enum_decl);
2321
2322 // TODO: check if we should be setting the promotion type too?
2323 enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2324
2325 enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2326
2327 return GetType(ast.getTagDeclType(enum_decl));
2328}
2329
2331 bool is_signed) {
2332 clang::ASTContext &ast = getASTContext();
2333
2334 if (is_signed) {
2335 if (bit_size == ast.getTypeSize(ast.SignedCharTy))
2336 return GetType(ast.SignedCharTy);
2337
2338 if (bit_size == ast.getTypeSize(ast.ShortTy))
2339 return GetType(ast.ShortTy);
2340
2341 if (bit_size == ast.getTypeSize(ast.IntTy))
2342 return GetType(ast.IntTy);
2343
2344 if (bit_size == ast.getTypeSize(ast.LongTy))
2345 return GetType(ast.LongTy);
2346
2347 if (bit_size == ast.getTypeSize(ast.LongLongTy))
2348 return GetType(ast.LongLongTy);
2349
2350 if (bit_size == ast.getTypeSize(ast.Int128Ty))
2351 return GetType(ast.Int128Ty);
2352 } else {
2353 if (bit_size == ast.getTypeSize(ast.UnsignedCharTy))
2354 return GetType(ast.UnsignedCharTy);
2355
2356 if (bit_size == ast.getTypeSize(ast.UnsignedShortTy))
2357 return GetType(ast.UnsignedShortTy);
2358
2359 if (bit_size == ast.getTypeSize(ast.UnsignedIntTy))
2360 return GetType(ast.UnsignedIntTy);
2361
2362 if (bit_size == ast.getTypeSize(ast.UnsignedLongTy))
2363 return GetType(ast.UnsignedLongTy);
2364
2365 if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy))
2366 return GetType(ast.UnsignedLongLongTy);
2367
2368 if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty))
2369 return GetType(ast.UnsignedInt128Ty);
2370 }
2371 return CompilerType();
2372}
2373
2375 return GetIntTypeFromBitSize(
2376 getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed);
2377}
2378
2379void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2380 if (decl_ctx) {
2381 DumpDeclContextHiearchy(decl_ctx->getParent());
2382
2383 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2384 if (named_decl) {
2385 printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2386 named_decl->getDeclName().getAsString().c_str());
2387 } else {
2388 printf("%20s\n", decl_ctx->getDeclKindName());
2389 }
2390 }
2391}
2392
2393void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) {
2394 if (decl == nullptr)
2395 return;
2396 DumpDeclContextHiearchy(decl->getDeclContext());
2397
2398 clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2399 if (record_decl) {
2400 printf("%20s: %s%s\n", decl->getDeclKindName(),
2401 record_decl->getDeclName().getAsString().c_str(),
2402 record_decl->isInjectedClassName() ? " (injected class name)" : "");
2403
2404 } else {
2405 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2406 if (named_decl) {
2407 printf("%20s: %s\n", decl->getDeclKindName(),
2408 named_decl->getDeclName().getAsString().c_str());
2409 } else {
2410 printf("%20s\n", decl->getDeclKindName());
2411 }
2412 }
2413}
2414
2415bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast,
2416 clang::Decl *decl) {
2417 if (!decl)
2418 return false;
2419
2420 ExternalASTSource *ast_source = ast->getExternalSource();
2421
2422 if (!ast_source)
2423 return false;
2424
2425 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2426 if (tag_decl->isCompleteDefinition())
2427 return true;
2428
2429 if (!tag_decl->hasExternalLexicalStorage())
2430 return false;
2431
2432 ast_source->CompleteType(tag_decl);
2433
2434 return !tag_decl->getTypeForDecl()->isIncompleteType();
2435 } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2436 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2437 if (objc_interface_decl->getDefinition())
2438 return true;
2439
2440 if (!objc_interface_decl->hasExternalLexicalStorage())
2441 return false;
2442
2443 ast_source->CompleteType(objc_interface_decl);
2444
2445 return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2446 } else {
2447 return false;
2448 }
2449}
2450
2451void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl,
2452 user_id_t user_id) {
2453 ClangASTMetadata meta_data;
2454 meta_data.SetUserID(user_id);
2455 SetMetadata(decl, meta_data);
2456}
2457
2458void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type,
2459 user_id_t user_id) {
2460 ClangASTMetadata meta_data;
2461 meta_data.SetUserID(user_id);
2462 SetMetadata(type, meta_data);
2463}
2464
2465void TypeSystemClang::SetMetadata(const clang::Decl *object,
2466 ClangASTMetadata metadata) {
2467 m_decl_metadata[object] = metadata;
2468}
2469
2470void TypeSystemClang::SetMetadata(const clang::Type *object,
2471 ClangASTMetadata metadata) {
2472 m_type_metadata[object] = metadata;
2473}
2474
2475std::optional<ClangASTMetadata>
2476TypeSystemClang::GetMetadata(const clang::Decl *object) {
2477 auto It = m_decl_metadata.find(object);
2478 if (It != m_decl_metadata.end())
2479 return It->second;
2480
2481 return std::nullopt;
2482}
2483
2484std::optional<ClangASTMetadata>
2485TypeSystemClang::GetMetadata(const clang::Type *object) {
2486 auto It = m_type_metadata.find(object);
2487 if (It != m_type_metadata.end())
2488 return It->second;
2489
2490 return std::nullopt;
2491}
2492
2493void TypeSystemClang::SetCXXRecordDeclAccess(const clang::CXXRecordDecl *object,
2494 clang::AccessSpecifier access) {
2495 if (access == clang::AccessSpecifier::AS_none)
2496 m_cxx_record_decl_access.erase(object);
2497 else
2498 m_cxx_record_decl_access[object] = access;
2499}
2500
2501clang::AccessSpecifier
2502TypeSystemClang::GetCXXRecordDeclAccess(const clang::CXXRecordDecl *object) {
2503 auto It = m_cxx_record_decl_access.find(object);
2504 if (It != m_cxx_record_decl_access.end())
2505 return It->second;
2506 return clang::AccessSpecifier::AS_none;
2507}
2508
2509clang::DeclContext *
2512}
2513
2516 if (auto *decl_context = GetDeclContextForType(type))
2517 return CreateDeclContext(decl_context);
2518 return CompilerDeclContext();
2519}
2520
2521/// Aggressively desugar the provided type, skipping past various kinds of
2522/// syntactic sugar and other constructs one typically wants to ignore.
2523/// The \p mask argument allows one to skip certain kinds of simplifications,
2524/// when one wishes to handle a certain kind of type directly.
2525static QualType
2526RemoveWrappingTypes(QualType type, ArrayRef<clang::Type::TypeClass> mask = {}) {
2527 while (true) {
2528 if (find(mask, type->getTypeClass()) != mask.end())
2529 return type;
2530 switch (type->getTypeClass()) {
2531 // This is not fully correct as _Atomic is more than sugar, but it is
2532 // sufficient for the purposes we care about.
2533 case clang::Type::Atomic:
2534 type = cast<clang::AtomicType>(type)->getValueType();
2535 break;
2536 case clang::Type::Auto:
2537 case clang::Type::Decltype:
2538 case clang::Type::Elaborated:
2539 case clang::Type::Paren:
2540 case clang::Type::SubstTemplateTypeParm:
2541 case clang::Type::TemplateSpecialization:
2542 case clang::Type::Typedef:
2543 case clang::Type::TypeOf:
2544 case clang::Type::TypeOfExpr:
2545 case clang::Type::Using:
2546 type = type->getLocallyUnqualifiedSingleStepDesugaredType();
2547 break;
2548 default:
2549 return type;
2550 }
2551 }
2552}
2553
2554clang::DeclContext *
2556 if (type.isNull())
2557 return nullptr;
2558
2559 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
2560 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2561 switch (type_class) {
2562 case clang::Type::ObjCInterface:
2563 return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2564 ->getInterface();
2565 case clang::Type::ObjCObjectPointer:
2566 return GetDeclContextForType(
2567 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2568 ->getPointeeType());
2569 case clang::Type::Record:
2570 return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2571 case clang::Type::Enum:
2572 return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2573 default:
2574 break;
2575 }
2576 // No DeclContext in this type...
2577 return nullptr;
2578}
2579
2580/// Returns the clang::RecordType of the specified \ref qual_type. This
2581/// function will try to complete the type if necessary (and allowed
2582/// by the specified \ref allow_completion). If we fail to return a *complete*
2583/// type, returns nullptr.
2584static const clang::RecordType *GetCompleteRecordType(clang::ASTContext *ast,
2585 clang::QualType qual_type,
2586 bool allow_completion) {
2587 assert(qual_type->isRecordType());
2588
2589 const auto *tag_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr());
2590
2591 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2592
2593 // RecordType with no way of completing it, return the plain
2594 // TagType.
2595 if (!cxx_record_decl || !cxx_record_decl->hasExternalLexicalStorage())
2596 return tag_type;
2597
2598 const bool is_complete = cxx_record_decl->isCompleteDefinition();
2599 const bool fields_loaded =
2600 cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2601
2602 // Already completed this type, nothing to be done.
2603 if (is_complete && fields_loaded)
2604 return tag_type;
2605
2606 if (!allow_completion)
2607 return nullptr;
2608
2609 // Call the field_begin() accessor to for it to use the external source
2610 // to load the fields...
2611 //
2612 // TODO: if we need to complete the type but have no external source,
2613 // shouldn't we error out instead?
2614 clang::ExternalASTSource *external_ast_source = ast->getExternalSource();
2615 if (external_ast_source) {
2616 external_ast_source->CompleteType(cxx_record_decl);
2617 if (cxx_record_decl->isCompleteDefinition()) {
2618 cxx_record_decl->field_begin();
2619 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2620 }
2621 }
2622
2623 return tag_type;
2624}
2625
2626/// Returns the clang::EnumType of the specified \ref qual_type. This
2627/// function will try to complete the type if necessary (and allowed
2628/// by the specified \ref allow_completion). If we fail to return a *complete*
2629/// type, returns nullptr.
2630static const clang::EnumType *GetCompleteEnumType(clang::ASTContext *ast,
2631 clang::QualType qual_type,
2632 bool allow_completion) {
2633 assert(qual_type->isEnumeralType());
2634 assert(ast);
2635
2636 const clang::EnumType *enum_type =
2637 llvm::cast<clang::EnumType>(qual_type.getTypePtr());
2638
2639 auto *tag_decl = enum_type->getAsTagDecl();
2640 assert(tag_decl);
2641
2642 // Already completed, nothing to be done.
2643 if (tag_decl->getDefinition())
2644 return enum_type;
2645
2646 if (!allow_completion)
2647 return nullptr;
2648
2649 // No definition but can't complete it, error out.
2650 if (!tag_decl->hasExternalLexicalStorage())
2651 return nullptr;
2652
2653 // We can't complete the type without an external source.
2654 clang::ExternalASTSource *external_ast_source = ast->getExternalSource();
2655 if (!external_ast_source)
2656 return nullptr;
2657
2658 external_ast_source->CompleteType(tag_decl);
2659 return enum_type;
2660}
2661
2662/// Returns the clang::ObjCObjectType of the specified \ref qual_type. This
2663/// function will try to complete the type if necessary (and allowed
2664/// by the specified \ref allow_completion). If we fail to return a *complete*
2665/// type, returns nullptr.
2666static const clang::ObjCObjectType *
2667GetCompleteObjCObjectType(clang::ASTContext *ast, QualType qual_type,
2668 bool allow_completion) {
2669 assert(qual_type->isObjCObjectType());
2670 assert(ast);
2671
2672 const clang::ObjCObjectType *objc_class_type =
2673 llvm::cast<clang::ObjCObjectType>(qual_type);
2674
2675 clang::ObjCInterfaceDecl *class_interface_decl =
2676 objc_class_type->getInterface();
2677 // We currently can't complete objective C types through the newly added
2678 // ASTContext because it only supports TagDecl objects right now...
2679 if (!class_interface_decl)
2680 return objc_class_type;
2681
2682 // Already complete, nothing to be done.
2683 if (class_interface_decl->getDefinition())
2684 return objc_class_type;
2685
2686 if (!allow_completion)
2687 return nullptr;
2688
2689 // No definition but can't complete it, error out.
2690 if (!class_interface_decl->hasExternalLexicalStorage())
2691 return nullptr;
2692
2693 // We can't complete the type without an external source.
2694 clang::ExternalASTSource *external_ast_source = ast->getExternalSource();
2695 if (!external_ast_source)
2696 return nullptr;
2697
2698 external_ast_source->CompleteType(class_interface_decl);
2699 return objc_class_type;
2700}
2701
2702static bool GetCompleteQualType(clang::ASTContext *ast,
2703 clang::QualType qual_type,
2704 bool allow_completion = true) {
2705 qual_type = RemoveWrappingTypes(qual_type);
2706 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2707 switch (type_class) {
2708 case clang::Type::ConstantArray:
2709 case clang::Type::IncompleteArray:
2710 case clang::Type::VariableArray: {
2711 const clang::ArrayType *array_type =
2712 llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2713
2714 if (array_type)
2715 return GetCompleteQualType(ast, array_type->getElementType(),
2716 allow_completion);
2717 } break;
2718 case clang::Type::Record: {
2719 if (const auto *RT =
2720 GetCompleteRecordType(ast, qual_type, allow_completion))
2721 return !RT->isIncompleteType();
2722
2723 return false;
2724 } break;
2725
2726 case clang::Type::Enum: {
2727 if (const auto *ET = GetCompleteEnumType(ast, qual_type, allow_completion))
2728 return !ET->isIncompleteType();
2729
2730 return false;
2731 } break;
2732 case clang::Type::ObjCObject:
2733 case clang::Type::ObjCInterface: {
2734 if (const auto *OT =
2735 GetCompleteObjCObjectType(ast, qual_type, allow_completion))
2736 return !OT->isIncompleteType();
2737
2738 return false;
2739 } break;
2740
2741 case clang::Type::Attributed:
2742 return GetCompleteQualType(
2743 ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2744 allow_completion);
2745
2746 default:
2747 break;
2748 }
2749
2750 return true;
2751}
2752
2753static clang::ObjCIvarDecl::AccessControl
2755 switch (access) {
2756 case eAccessNone:
2757 return clang::ObjCIvarDecl::None;
2758 case eAccessPublic:
2759 return clang::ObjCIvarDecl::Public;
2760 case eAccessPrivate:
2761 return clang::ObjCIvarDecl::Private;
2762 case eAccessProtected:
2763 return clang::ObjCIvarDecl::Protected;
2764 case eAccessPackage:
2765 return clang::ObjCIvarDecl::Package;
2766 }
2767 return clang::ObjCIvarDecl::None;
2768}
2769
2770// Tests
2771
2772#ifndef NDEBUG
2774 return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr());
2775}
2776#endif
2777
2779 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2780
2781 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2782 switch (type_class) {
2783 case clang::Type::IncompleteArray:
2784 case clang::Type::VariableArray:
2785 case clang::Type::ConstantArray:
2786 case clang::Type::ExtVector:
2787 case clang::Type::Vector:
2788 case clang::Type::Record:
2789 case clang::Type::ObjCObject:
2790 case clang::Type::ObjCInterface:
2791 return true;
2792 default:
2793 break;
2794 }
2795 // The clang type does have a value
2796 return false;
2797}
2798
2800 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2801
2802 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2803 switch (type_class) {
2804 case clang::Type::Record: {
2805 if (const clang::RecordType *record_type =
2806 llvm::dyn_cast_or_null<clang::RecordType>(
2807 qual_type.getTypePtrOrNull())) {
2808 if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2809 return record_decl->isAnonymousStructOrUnion();
2810 }
2811 }
2812 break;
2813 }
2814 default:
2815 break;
2816 }
2817 // The clang type does have a value
2818 return false;
2819}
2820
2822 CompilerType *element_type_ptr,
2823 uint64_t *size, bool *is_incomplete) {
2824 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2825
2826 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2827 switch (type_class) {
2828 default:
2829 break;
2830
2831 case clang::Type::ConstantArray:
2832 if (element_type_ptr)
2833 element_type_ptr->SetCompilerType(
2834 weak_from_this(), llvm::cast<clang::ConstantArrayType>(qual_type)
2835 ->getElementType()
2836 .getAsOpaquePtr());
2837 if (size)
2838 *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2839 ->getSize()
2840 .getLimitedValue(ULLONG_MAX);
2841 if (is_incomplete)
2842 *is_incomplete = false;
2843 return true;
2844
2845 case clang::Type::IncompleteArray:
2846 if (element_type_ptr)
2847 element_type_ptr->SetCompilerType(
2848 weak_from_this(), llvm::cast<clang::IncompleteArrayType>(qual_type)
2849 ->getElementType()
2850 .getAsOpaquePtr());
2851 if (size)
2852 *size = 0;
2853 if (is_incomplete)
2854 *is_incomplete = true;
2855 return true;
2856
2857 case clang::Type::VariableArray:
2858 if (element_type_ptr)
2859 element_type_ptr->SetCompilerType(
2860 weak_from_this(), llvm::cast<clang::VariableArrayType>(qual_type)
2861 ->getElementType()
2862 .getAsOpaquePtr());
2863 if (size)
2864 *size = 0;
2865 if (is_incomplete)
2866 *is_incomplete = false;
2867 return true;
2868
2869 case clang::Type::DependentSizedArray:
2870 if (element_type_ptr)
2871 element_type_ptr->SetCompilerType(
2872 weak_from_this(),
2873 llvm::cast<clang::DependentSizedArrayType>(qual_type)
2874 ->getElementType()
2875 .getAsOpaquePtr());
2876 if (size)
2877 *size = 0;
2878 if (is_incomplete)
2879 *is_incomplete = false;
2880 return true;
2881 }
2882 if (element_type_ptr)
2883 element_type_ptr->Clear();
2884 if (size)
2885 *size = 0;
2886 if (is_incomplete)
2887 *is_incomplete = false;
2888 return false;
2889}
2890
2892 CompilerType *element_type, uint64_t *size) {
2893 clang::QualType qual_type(GetCanonicalQualType(type));
2894
2895 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2896 switch (type_class) {
2897 case clang::Type::Vector: {
2898 const clang::VectorType *vector_type =
2899 qual_type->getAs<clang::VectorType>();
2900 if (vector_type) {
2901 if (size)
2902 *size = vector_type->getNumElements();
2903 if (element_type)
2904 *element_type = GetType(vector_type->getElementType());
2905 }
2906 return true;
2907 } break;
2908 case clang::Type::ExtVector: {
2909 const clang::ExtVectorType *ext_vector_type =
2910 qual_type->getAs<clang::ExtVectorType>();
2911 if (ext_vector_type) {
2912 if (size)
2913 *size = ext_vector_type->getNumElements();
2914 if (element_type)
2915 *element_type =
2916 CompilerType(weak_from_this(),
2917 ext_vector_type->getElementType().getAsOpaquePtr());
2918 }
2919 return true;
2920 }
2921 default:
2922 break;
2923 }
2924 return false;
2925}
2926
2929 clang::DeclContext *decl_ctx = GetDeclContextForType(GetQualType(type));
2930 if (!decl_ctx)
2931 return false;
2932
2933 if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
2934 return false;
2935
2936 clang::ObjCInterfaceDecl *result_iface_decl =
2937 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
2938
2939 std::optional<ClangASTMetadata> ast_metadata = GetMetadata(result_iface_decl);
2940 if (!ast_metadata)
2941 return false;
2942
2943 return (ast_metadata->GetISAPtr() != 0);
2944}
2945
2947 return GetQualType(type).getUnqualifiedType()->isCharType();
2948}
2949
2951 // If the type hasn't been lazily completed yet, complete it now so that we
2952 // can give the caller an accurate answer whether the type actually has a
2953 // definition. Without completing the type now we would just tell the user
2954 // the current (internal) completeness state of the type and most users don't
2955 // care (or even know) about this behavior.
2956 const bool allow_completion = true;
2958 allow_completion);
2959}
2960
2962 return GetQualType(type).isConstQualified();
2963}
2964
2966 uint32_t &length) {
2967 CompilerType pointee_or_element_clang_type;
2968 length = 0;
2969 Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
2970
2971 if (!pointee_or_element_clang_type.IsValid())
2972 return false;
2973
2974 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
2975 if (pointee_or_element_clang_type.IsCharType()) {
2976 if (type_flags.Test(eTypeIsArray)) {
2977 // We know the size of the array and it could be a C string since it is
2978 // an array of characters
2979 length = llvm::cast<clang::ConstantArrayType>(
2980 GetCanonicalQualType(type).getTypePtr())
2981 ->getSize()
2982 .getLimitedValue();
2983 }
2984 return true;
2985 }
2986 }
2987 return false;
2988}
2989
2991 if (type) {
2992 clang::QualType qual_type(GetCanonicalQualType(type));
2993 if (auto pointer_auth = qual_type.getPointerAuth())
2994 return pointer_auth.getKey();
2995 }
2996 return 0;
2997}
2998
2999unsigned
3001 if (type) {
3002 clang::QualType qual_type(GetCanonicalQualType(type));
3003 if (auto pointer_auth = qual_type.getPointerAuth())
3004 return pointer_auth.getExtraDiscriminator();
3005 }
3006 return 0;
3007}
3008
3011 if (type) {
3012 clang::QualType qual_type(GetCanonicalQualType(type));
3013 if (auto pointer_auth = qual_type.getPointerAuth())
3014 return pointer_auth.isAddressDiscriminated();
3015 }
3016 return false;
3017}
3018
3020 auto isFunctionType = [&](clang::QualType qual_type) {
3021 return qual_type->isFunctionType();
3022 };
3023
3024 return IsTypeImpl(type, isFunctionType);
3025}
3026
3027// Used to detect "Homogeneous Floating-point Aggregates"
3028uint32_t
3030 CompilerType *base_type_ptr) {
3031 if (!type)
3032 return 0;
3033
3034 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
3035 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3036 switch (type_class) {
3037 case clang::Type::Record:
3038 if (GetCompleteType(type)) {
3039 const clang::CXXRecordDecl *cxx_record_decl =
3040 qual_type->getAsCXXRecordDecl();
3041 if (cxx_record_decl) {
3042 if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
3043 return 0;
3044 }
3045 const clang::RecordType *record_type =
3046 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3047 if (record_type) {
3048 const clang::RecordDecl *record_decl = record_type->getDecl();
3049 if (record_decl) {
3050 // We are looking for a structure that contains only floating point
3051 // types
3052 clang::RecordDecl::field_iterator field_pos,
3053 field_end = record_decl->field_end();
3054 uint32_t num_fields = 0;
3055 bool is_hva = false;
3056 bool is_hfa = false;
3057 clang::QualType base_qual_type;
3058 uint64_t base_bitwidth = 0;
3059 for (field_pos = record_decl->field_begin(); field_pos != field_end;
3060 ++field_pos) {
3061 clang::QualType field_qual_type = field_pos->getType();
3062 uint64_t field_bitwidth = getASTContext().getTypeSize(qual_type);
3063 if (field_qual_type->isFloatingType()) {
3064 if (field_qual_type->isComplexType())
3065 return 0;
3066 else {
3067 if (num_fields == 0)
3068 base_qual_type = field_qual_type;
3069 else {
3070 if (is_hva)
3071 return 0;
3072 is_hfa = true;
3073 if (field_qual_type.getTypePtr() !=
3074 base_qual_type.getTypePtr())
3075 return 0;
3076 }
3077 }
3078 } else if (field_qual_type->isVectorType() ||
3079 field_qual_type->isExtVectorType()) {
3080 if (num_fields == 0) {
3081 base_qual_type = field_qual_type;
3082 base_bitwidth = field_bitwidth;
3083 } else {
3084 if (is_hfa)
3085 return 0;
3086 is_hva = true;
3087 if (base_bitwidth != field_bitwidth)
3088 return 0;
3089 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3090 return 0;
3091 }
3092 } else
3093 return 0;
3094 ++num_fields;
3095 }
3096 if (base_type_ptr)
3097 *base_type_ptr =
3098 CompilerType(weak_from_this(), base_qual_type.getAsOpaquePtr());
3099 return num_fields;
3100 }
3101 }
3102 }
3103 break;
3104
3105 default:
3106 break;
3107 }
3108 return 0;
3109}
3110
3113 if (type) {
3114 clang::QualType qual_type(GetCanonicalQualType(type));
3115 const clang::FunctionProtoType *func =
3116 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3117 if (func)
3118 return func->getNumParams();
3119 }
3120 return 0;
3121}
3122
3125 const size_t index) {
3126 if (type) {
3127 clang::QualType qual_type(GetQualType(type));
3128 const clang::FunctionProtoType *func =
3129 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3130 if (func) {
3131 if (index < func->getNumParams())
3132 return CompilerType(weak_from_this(), func->getParamType(index).getAsOpaquePtr());
3133 }
3134 }
3135 return CompilerType();
3136}
3137
3140 llvm::function_ref<bool(clang::QualType)> predicate) const {
3141 if (type) {
3142 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3143
3144 if (predicate(qual_type))
3145 return true;
3146
3147 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3148 switch (type_class) {
3149 default:
3150 break;
3151
3152 case clang::Type::LValueReference:
3153 case clang::Type::RValueReference: {
3154 const clang::ReferenceType *reference_type =
3155 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3156 if (reference_type)
3157 return IsTypeImpl(reference_type->getPointeeType().getAsOpaquePtr(), predicate);
3158 } break;
3159 }
3160 }
3161 return false;
3162}
3163
3166 auto isMemberFunctionPointerType = [](clang::QualType qual_type) {
3167 return qual_type->isMemberFunctionPointerType();
3168 };
3169
3170 return IsTypeImpl(type, isMemberFunctionPointerType);
3171}
3172
3174 auto isFunctionPointerType = [](clang::QualType qual_type) {
3175 return qual_type->isFunctionPointerType();
3176 };
3177
3178 return IsTypeImpl(type, isFunctionPointerType);
3179}
3180
3183 CompilerType *function_pointer_type_ptr) {
3184 auto isBlockPointerType = [&](clang::QualType qual_type) {
3185 if (qual_type->isBlockPointerType()) {
3186 if (function_pointer_type_ptr) {
3187 const clang::BlockPointerType *block_pointer_type =
3188 qual_type->castAs<clang::BlockPointerType>();
3189 QualType pointee_type = block_pointer_type->getPointeeType();
3190 QualType function_pointer_type = m_ast_up->getPointerType(pointee_type);
3191 *function_pointer_type_ptr = CompilerType(
3192 weak_from_this(), function_pointer_type.getAsOpaquePtr());
3193 }
3194 return true;
3195 }
3196
3197 return false;
3198 };
3199
3200 return IsTypeImpl(type, isBlockPointerType);
3201}
3202
3204 bool &is_signed) {
3205 if (!type)
3206 return false;
3207
3208 clang::QualType qual_type(GetCanonicalQualType(type));
3209 const clang::BuiltinType *builtin_type =
3210 llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3211
3212 if (builtin_type) {
3213 if (builtin_type->isInteger()) {
3214 is_signed = builtin_type->isSignedInteger();
3215 return true;
3216 }
3217 }
3218
3219 return false;
3220}
3221
3223 bool &is_signed) {
3224 if (type) {
3225 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3226 GetCanonicalQualType(type)->getCanonicalTypeInternal());
3227
3228 if (enum_type) {
3229 IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3230 is_signed);
3231 return true;
3232 }
3233 }
3234
3235 return false;
3236}
3237
3240 if (type) {
3241 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3242 GetCanonicalQualType(type)->getCanonicalTypeInternal());
3243
3244 if (enum_type) {
3245 return enum_type->isScopedEnumeralType();
3246 }
3247 }
3248
3249 return false;
3250}
3251
3253 CompilerType *pointee_type) {
3254 if (type) {
3255 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3256 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3257 switch (type_class) {
3258 case clang::Type::Builtin:
3259 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3260 default:
3261 break;
3262 case clang::BuiltinType::ObjCId:
3263 case clang::BuiltinType::ObjCClass:
3264 return true;
3265 }
3266 return false;
3267 case clang::Type::ObjCObjectPointer:
3268 if (pointee_type)
3269 pointee_type->SetCompilerType(
3270 weak_from_this(),
3271 llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3272 ->getPointeeType()
3273 .getAsOpaquePtr());
3274 return true;
3275 case clang::Type::BlockPointer:
3276 if (pointee_type)
3277 pointee_type->SetCompilerType(
3278 weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type)
3279 ->getPointeeType()
3280 .getAsOpaquePtr());
3281 return true;
3282 case clang::Type::Pointer:
3283 if (pointee_type)
3284 pointee_type->SetCompilerType(weak_from_this(),
3285 llvm::cast<clang::PointerType>(qual_type)
3286 ->getPointeeType()
3287 .getAsOpaquePtr());
3288 return true;
3289 case clang::Type::MemberPointer:
3290 if (pointee_type)
3291 pointee_type->SetCompilerType(
3292 weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type)
3293 ->getPointeeType()
3294 .getAsOpaquePtr());
3295 return true;
3296 default:
3297 break;
3298 }
3299 }
3300 if (pointee_type)
3301 pointee_type->Clear();
3302 return false;
3303}
3304
3306 lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3307 if (type) {
3308 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3309 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3310 switch (type_class) {
3311 case clang::Type::Builtin:
3312 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3313 default:
3314 break;
3315 case clang::BuiltinType::ObjCId:
3316 case clang::BuiltinType::ObjCClass:
3317 return true;
3318 }
3319 return false;
3320 case clang::Type::ObjCObjectPointer:
3321 if (pointee_type)
3322 pointee_type->SetCompilerType(
3323 weak_from_this(),
3324 llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3325 ->getPointeeType()
3326 .getAsOpaquePtr());
3327 return true;
3328 case clang::Type::BlockPointer:
3329 if (pointee_type)
3330 pointee_type->SetCompilerType(
3331 weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type)
3332 ->getPointeeType()
3333 .getAsOpaquePtr());
3334 return true;
3335 case clang::Type::Pointer:
3336 if (pointee_type)
3337 pointee_type->SetCompilerType(weak_from_this(),
3338 llvm::cast<clang::PointerType>(qual_type)
3339 ->getPointeeType()
3340 .getAsOpaquePtr());
3341 return true;
3342 case clang::Type::MemberPointer:
3343 if (pointee_type)
3344 pointee_type->SetCompilerType(
3345 weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type)
3346 ->getPointeeType()
3347 .getAsOpaquePtr());
3348 return true;
3349 case clang::Type::LValueReference:
3350 if (pointee_type)
3351 pointee_type->SetCompilerType(
3352 weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type)
3353 ->desugar()
3354 .getAsOpaquePtr());
3355 return true;
3356 case clang::Type::RValueReference:
3357 if (pointee_type)
3358 pointee_type->SetCompilerType(
3359 weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type)
3360 ->desugar()
3361 .getAsOpaquePtr());
3362 return true;
3363 default:
3364 break;
3365 }
3366 }
3367 if (pointee_type)
3368 pointee_type->Clear();
3369 return false;
3370}
3371
3373 CompilerType *pointee_type,
3374 bool *is_rvalue) {
3375 if (type) {
3376 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3377 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3378
3379 switch (type_class) {
3380 case clang::Type::LValueReference:
3381 if (pointee_type)
3382 pointee_type->SetCompilerType(
3383 weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type)
3384 ->desugar()
3385 .getAsOpaquePtr());
3386 if (is_rvalue)
3387 *is_rvalue = false;
3388 return true;
3389 case clang::Type::RValueReference:
3390 if (pointee_type)
3391 pointee_type->SetCompilerType(
3392 weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type)
3393 ->desugar()
3394 .getAsOpaquePtr());
3395 if (is_rvalue)
3396 *is_rvalue = true;
3397 return true;
3398
3399 default:
3400 break;
3401 }
3402 }
3403 if (pointee_type)
3404 pointee_type->Clear();
3405 return false;
3406}
3407
3409 uint32_t &count, bool &is_complex) {
3410 if (type) {
3411 clang::QualType qual_type(GetCanonicalQualType(type));
3412
3413 if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3414 qual_type->getCanonicalTypeInternal())) {
3415 clang::BuiltinType::Kind kind = BT->getKind();
3416 if (kind >= clang::BuiltinType::Float &&
3417 kind <= clang::BuiltinType::LongDouble) {
3418 count = 1;
3419 is_complex = false;
3420 return true;
3421 }
3422 } else if (const clang::ComplexType *CT =
3423 llvm::dyn_cast<clang::ComplexType>(
3424 qual_type->getCanonicalTypeInternal())) {
3425 if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3426 is_complex)) {
3427 count = 2;
3428 is_complex = true;
3429 return true;
3430 }
3431 } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3432 qual_type->getCanonicalTypeInternal())) {
3433 if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3434 is_complex)) {
3435 count = VT->getNumElements();
3436 is_complex = false;
3437 return true;
3438 }
3439 }
3440 }
3441 count = 0;
3442 is_complex = false;
3443 return false;
3444}
3445
3447 if (!type)
3448 return false;
3449
3450 clang::QualType qual_type(GetQualType(type));
3451 const clang::TagType *tag_type =
3452 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3453 if (tag_type) {
3454 clang::TagDecl *tag_decl = tag_type->getDecl();
3455 if (tag_decl)
3456 return tag_decl->isCompleteDefinition();
3457 return false;
3458 } else {
3459 const clang::ObjCObjectType *objc_class_type =
3460 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3461 if (objc_class_type) {
3462 clang::ObjCInterfaceDecl *class_interface_decl =
3463 objc_class_type->getInterface();
3464 if (class_interface_decl)
3465 return class_interface_decl->getDefinition() != nullptr;
3466 return false;
3467 }
3468 }
3469 return true;
3470}
3471
3473 if (ClangUtil::IsClangType(type)) {
3474 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3475
3476 const clang::ObjCObjectPointerType *obj_pointer_type =
3477 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3478
3479 if (obj_pointer_type)
3480 return obj_pointer_type->isObjCClassType();
3481 }
3482 return false;
3483}
3484
3486 if (ClangUtil::IsClangType(type))
3487 return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3488 return false;
3489}
3490
3492 if (!type)
3493 return false;
3494 clang::QualType qual_type(GetCanonicalQualType(type));
3495 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3496 return (type_class == clang::Type::Record);
3497}
3498
3500 if (!type)
3501 return false;
3502 clang::QualType qual_type(GetCanonicalQualType(type));
3503 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3504 return (type_class == clang::Type::Enum);
3505}
3506
3508 if (type) {
3509 clang::QualType qual_type(GetCanonicalQualType(type));
3510 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3511 switch (type_class) {
3512 case clang::Type::Record:
3513 if (GetCompleteType(type)) {
3514 const clang::RecordType *record_type =
3515 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3516 const clang::RecordDecl *record_decl = record_type->getDecl();
3517 if (record_decl) {
3518 const clang::CXXRecordDecl *cxx_record_decl =
3519 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3520 if (cxx_record_decl) {
3521 // We can't just call is isPolymorphic() here because that just
3522 // means the current class has virtual functions, it doesn't check
3523 // if any inherited classes have virtual functions. The doc string
3524 // in SBType::IsPolymorphicClass() says it is looking for both
3525 // if the class has virtual methods or if any bases do, so this
3526 // should be more correct.
3527 return cxx_record_decl->isDynamicClass();
3528 }
3529 }
3530 }
3531 break;
3532
3533 default:
3534 break;
3535 }
3536 }
3537 return false;
3538}
3539
3541 CompilerType *dynamic_pointee_type,
3542 bool check_cplusplus,
3543 bool check_objc) {
3544 clang::QualType pointee_qual_type;
3545 if (type) {
3546 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3547 bool success = false;
3548 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3549 switch (type_class) {
3550 case clang::Type::Builtin:
3551 if (check_objc &&
3552 llvm::cast<clang::BuiltinType>(qual_type)->getKind() ==
3553 clang::BuiltinType::ObjCId) {
3554 if (dynamic_pointee_type)
3555 dynamic_pointee_type->SetCompilerType(weak_from_this(), type);
3556 return true;
3557 }
3558 break;
3559
3560 case clang::Type::ObjCObjectPointer:
3561 if (check_objc) {
3562 if (const auto *objc_pointee_type =
3563 qual_type->getPointeeType().getTypePtrOrNull()) {
3564 if (const auto *objc_object_type =
3565 llvm::dyn_cast_or_null<clang::ObjCObjectType>(
3566 objc_pointee_type)) {
3567 if (objc_object_type->isObjCClass())
3568 return false;
3569 }
3570 }
3571 if (dynamic_pointee_type)
3572 dynamic_pointee_type->SetCompilerType(
3573 weak_from_this(),
3574 llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3575 ->getPointeeType()
3576 .getAsOpaquePtr());
3577 return true;
3578 }
3579 break;
3580
3581 case clang::Type::Pointer:
3582 pointee_qual_type =
3583 llvm::cast<clang::PointerType>(qual_type)->getPointeeType();
3584 success = true;
3585 break;
3586
3587 case clang::Type::LValueReference:
3588 case clang::Type::RValueReference:
3589 pointee_qual_type =
3590 llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType();
3591 success = true;
3592 break;
3593
3594 default:
3595 break;
3596 }
3597
3598 if (success) {
3599 // Check to make sure what we are pointing too is a possible dynamic C++
3600 // type We currently accept any "void *" (in case we have a class that
3601 // has been watered down to an opaque pointer) and virtual C++ classes.
3602 const clang::Type::TypeClass pointee_type_class =
3603 pointee_qual_type.getCanonicalType()->getTypeClass();
3604 switch (pointee_type_class) {
3605 case clang::Type::Builtin:
3606 switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) {
3607 case clang::BuiltinType::UnknownAny:
3608 case clang::BuiltinType::Void:
3609 if (dynamic_pointee_type)
3610 dynamic_pointee_type->SetCompilerType(
3611 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3612 return true;
3613 default:
3614 break;
3615 }
3616 break;
3617
3618 case clang::Type::Record:
3619 if (check_cplusplus) {
3620 clang::CXXRecordDecl *cxx_record_decl =
3621 pointee_qual_type->getAsCXXRecordDecl();
3622 if (cxx_record_decl) {
3623 bool is_complete = cxx_record_decl->isCompleteDefinition();
3624
3625 if (is_complete)
3626 success = cxx_record_decl->isDynamicClass();
3627 else {
3628 if (std::optional<ClangASTMetadata> metadata =
3629 GetMetadata(cxx_record_decl))
3630 success = metadata->GetIsDynamicCXXType();
3631 else {
3632 is_complete = GetType(pointee_qual_type).GetCompleteType();
3633 if (is_complete)
3634 success = cxx_record_decl->isDynamicClass();
3635 else
3636 success = false;
3637 }
3638 }
3639
3640 if (success) {
3641 if (dynamic_pointee_type)
3642 dynamic_pointee_type->SetCompilerType(
3643 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3644 return true;
3645 }
3646 }
3647 }
3648 break;
3649
3650 case clang::Type::ObjCObject:
3651 case clang::Type::ObjCInterface:
3652 if (check_objc) {
3653 if (dynamic_pointee_type)
3654 dynamic_pointee_type->SetCompilerType(
3655 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3656 return true;
3657 }
3658 break;
3659
3660 default:
3661 break;
3662 }
3663 }
3664 }
3665 if (dynamic_pointee_type)
3666 dynamic_pointee_type->Clear();
3667 return false;
3668}
3669
3671 if (!type)
3672 return false;
3673
3674 return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3675}
3676
3678 if (!type)
3679 return false;
3680 return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})
3681 ->getTypeClass() == clang::Type::Typedef;
3682}
3683
3685 if (!type)
3686 return false;
3687 return GetCanonicalQualType(type)->isVoidType();
3688}
3689
3691 if (auto *record_decl =
3693 return record_decl->canPassInRegisters();
3694 }
3695 return false;
3696}
3697
3699 return TypeSystemClangSupportsLanguage(language);
3700}
3701
3702std::optional<std::string>
3704 if (!type)
3705 return std::nullopt;
3706
3707 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3708 if (qual_type.isNull())
3709 return std::nullopt;
3710
3711 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3712 if (!cxx_record_decl)
3713 return std::nullopt;
3714
3715 return std::string(cxx_record_decl->getIdentifier()->getNameStart());
3716}
3717
3719 if (!type)
3720 return false;
3721
3722 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3723 return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr;
3724}
3725
3727 if (!type)
3728 return false;
3729 clang::QualType qual_type(GetCanonicalQualType(type));
3730 const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type);
3731 if (tag_type)
3732 return tag_type->isBeingDefined();
3733 return false;
3734}
3735
3737 CompilerType *class_type_ptr) {
3738 if (!ClangUtil::IsClangType(type))
3739 return false;
3740
3741 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3742
3743 if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) {
3744 if (class_type_ptr) {
3745 if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) {
3746 const clang::ObjCObjectPointerType *obj_pointer_type =
3747 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3748 if (obj_pointer_type == nullptr)
3749 class_type_ptr->Clear();
3750 else
3751 class_type_ptr->SetCompilerType(
3752 type.GetTypeSystem(),
3753 clang::QualType(obj_pointer_type->getInterfaceType(), 0)
3754 .getAsOpaquePtr());
3755 }
3756 }
3757 return true;
3758 }
3759 if (class_type_ptr)
3760 class_type_ptr->Clear();
3761 return false;
3762}
3763
3764// Type Completion
3765
3767 if (!type)
3768 return false;
3769 const bool allow_completion = true;
3771 allow_completion);
3772}
3773
3775 bool base_only) {
3776 if (!type)
3777 return ConstString();
3778
3779 clang::QualType qual_type(GetQualType(type));
3780
3781 // Remove certain type sugar from the name. Sugar such as elaborated types
3782 // or template types which only serve to improve diagnostics shouldn't
3783 // act as their own types from the user's perspective (e.g., formatter
3784 // shouldn't format a variable differently depending on how the ser has
3785 // specified the type. '::Type' and 'Type' should behave the same).
3786 // Typedefs and atomic derived types are not removed as they are actually
3787 // useful for identifiying specific types.
3788 qual_type = RemoveWrappingTypes(qual_type,
3789 {clang::Type::Typedef, clang::Type::Atomic});
3790
3791 // For a typedef just return the qualified name.
3792 if (const auto *typedef_type = qual_type->getAs<clang::TypedefType>()) {
3793 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
3794 return ConstString(GetTypeNameForDecl(typedef_decl));
3795 }
3796
3797 // For consistency, this follows the same code path that clang uses to emit
3798 // debug info. This also handles when we don't want any scopes preceding the
3799 // name.
3800 if (auto *named_decl = qual_type->getAsTagDecl())
3801 return ConstString(GetTypeNameForDecl(named_decl, !base_only));
3802
3803 return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
3804}
3805
3808 if (!type)
3809 return ConstString();
3810
3811 clang::QualType qual_type(GetQualType(type));
3812 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
3813 printing_policy.SuppressTagKeyword = true;
3814 printing_policy.SuppressScope = false;
3815 printing_policy.SuppressUnwrittenScope = true;
3816 printing_policy.SuppressInlineNamespace = true;
3817 return ConstString(qual_type.getAsString(printing_policy));
3818}
3819
3820uint32_t
3822 CompilerType *pointee_or_element_clang_type) {
3823 if (!type)
3824 return 0;
3825
3826 if (pointee_or_element_clang_type)
3827 pointee_or_element_clang_type->Clear();
3828
3829 clang::QualType qual_type =
3830 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
3831
3832 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3833 switch (type_class) {
3834 case clang::Type::Attributed:
3835 return GetTypeInfo(qual_type->castAs<clang::AttributedType>()
3836 ->getModifiedType()
3837 .getAsOpaquePtr(),
3838 pointee_or_element_clang_type);
3839 case clang::Type::Builtin: {
3840 const clang::BuiltinType *builtin_type =
3841 llvm::cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3842
3843 uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
3844 switch (builtin_type->getKind()) {
3845 case clang::BuiltinType::ObjCId:
3846 case clang::BuiltinType::ObjCClass:
3847 if (pointee_or_element_clang_type)
3848 pointee_or_element_clang_type->SetCompilerType(
3849 weak_from_this(),
3850 getASTContext().ObjCBuiltinClassTy.getAsOpaquePtr());
3851 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3852 break;
3853
3854 case clang::BuiltinType::ObjCSel:
3855 if (pointee_or_element_clang_type)
3856 pointee_or_element_clang_type->SetCompilerType(
3857 weak_from_this(), getASTContext().CharTy.getAsOpaquePtr());
3858 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3859 break;
3860
3861 case clang::BuiltinType::Bool:
3862 case clang::BuiltinType::Char_U:
3863 case clang::BuiltinType::UChar:
3864 case clang::BuiltinType::WChar_U:
3865 case clang::BuiltinType::Char16:
3866 case clang::BuiltinType::Char32:
3867 case clang::BuiltinType::UShort:
3868 case clang::BuiltinType::UInt:
3869 case clang::BuiltinType::ULong:
3870 case clang::BuiltinType::ULongLong:
3871 case clang::BuiltinType::UInt128:
3872 case clang::BuiltinType::Char_S:
3873 case clang::BuiltinType::SChar:
3874 case clang::BuiltinType::WChar_S:
3875 case clang::BuiltinType::Short:
3876 case clang::BuiltinType::Int:
3877 case clang::BuiltinType::Long:
3878 case clang::BuiltinType::LongLong:
3879 case clang::BuiltinType::Int128:
3880 case clang::BuiltinType::Float:
3881 case clang::BuiltinType::Double:
3882 case clang::BuiltinType::LongDouble:
3883 builtin_type_flags |= eTypeIsScalar;
3884 if (builtin_type->isInteger()) {
3885 builtin_type_flags |= eTypeIsInteger;
3886 if (builtin_type->isSignedInteger())
3887 builtin_type_flags |= eTypeIsSigned;
3888 } else if (builtin_type->isFloatingPoint())
3889 builtin_type_flags |= eTypeIsFloat;
3890 break;
3891 default:
3892 break;
3893 }
3894 return builtin_type_flags;
3895 }
3896
3897 case clang::Type::BlockPointer:
3898 if (pointee_or_element_clang_type)
3899 pointee_or_element_clang_type->SetCompilerType(
3900 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
3901 return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
3902
3903 case clang::Type::Complex: {
3904 uint32_t complex_type_flags =
3905 eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
3906 const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>(
3907 qual_type->getCanonicalTypeInternal());
3908 if (complex_type) {
3909 clang::QualType complex_element_type(complex_type->getElementType());
3910 if (complex_element_type->isIntegerType())
3911 complex_type_flags |= eTypeIsFloat;
3912 else if (complex_element_type->isFloatingType())
3913 complex_type_flags |= eTypeIsInteger;
3914 }
3915 return complex_type_flags;
3916 } break;
3917
3918 case clang::Type::ConstantArray:
3919 case clang::Type::DependentSizedArray:
3920 case clang::Type::IncompleteArray:
3921 case clang::Type::VariableArray:
3922 if (pointee_or_element_clang_type)
3923 pointee_or_element_clang_type->SetCompilerType(
3924 weak_from_this(), llvm::cast<clang::ArrayType>(qual_type.getTypePtr())
3925 ->getElementType()
3926 .getAsOpaquePtr());
3927 return eTypeHasChildren | eTypeIsArray;
3928
3929 case clang::Type::DependentName:
3930 return 0;
3931 case clang::Type::DependentSizedExtVector:
3932 return eTypeHasChildren | eTypeIsVector;
3933 case clang::Type::DependentTemplateSpecialization:
3934 return eTypeIsTemplate;
3935
3936 case clang::Type::Enum:
3937 if (pointee_or_element_clang_type)
3938 pointee_or_element_clang_type->SetCompilerType(
3939 weak_from_this(), llvm::cast<clang::EnumType>(qual_type)
3940 ->getDecl()
3941 ->getIntegerType()
3942 .getAsOpaquePtr());
3943 return eTypeIsEnumeration | eTypeHasValue;
3944
3945 case clang::Type::FunctionProto:
3946 return eTypeIsFuncPrototype | eTypeHasValue;
3947 case clang::Type::FunctionNoProto:
3948 return eTypeIsFuncPrototype | eTypeHasValue;
3949 case clang::Type::InjectedClassName:
3950 return 0;
3951
3952 case clang::Type::LValueReference:
3953 case clang::Type::RValueReference:
3954 if (pointee_or_element_clang_type)
3955 pointee_or_element_clang_type->SetCompilerType(
3956 weak_from_this(),
3957 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr())
3958 ->getPointeeType()
3959 .getAsOpaquePtr());
3960 return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
3961
3962 case clang::Type::MemberPointer:
3963 return eTypeIsPointer | eTypeIsMember | eTypeHasValue;
3964
3965 case clang::Type::ObjCObjectPointer:
3966 if (pointee_or_element_clang_type)
3967 pointee_or_element_clang_type->SetCompilerType(
3968 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
3969 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer |
3970 eTypeHasValue;
3971
3972 case clang::Type::ObjCObject:
3973 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3974 case clang::Type::ObjCInterface:
3975 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3976
3977 case clang::Type::Pointer:
3978 if (pointee_or_element_clang_type)
3979 pointee_or_element_clang_type->SetCompilerType(
3980 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
3981 return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
3982
3983 case clang::Type::Record:
3984 if (qual_type->getAsCXXRecordDecl())
3985 return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
3986 else
3987 return eTypeHasChildren | eTypeIsStructUnion;
3988 break;
3989 case clang::Type::SubstTemplateTypeParm:
3990 return eTypeIsTemplate;
3991 case clang::Type::TemplateTypeParm:
3992 return eTypeIsTemplate;
3993 case clang::Type::TemplateSpecialization:
3994 return eTypeIsTemplate;
3995
3996 case clang::Type::Typedef:
3997 return eTypeIsTypedef | GetType(llvm::cast<clang::TypedefType>(qual_type)
3998 ->getDecl()
3999 ->getUnderlyingType())
4000 .GetTypeInfo(pointee_or_element_clang_type);
4001 case clang::Type::UnresolvedUsing:
4002 return 0;
4003
4004 case clang::Type::ExtVector:
4005 case clang::Type::Vector: {
4006 uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
4007 const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>(
4008 qual_type->getCanonicalTypeInternal());
4009 if (vector_type) {
4010 if (vector_type->isIntegerType())
4011 vector_type_flags |= eTypeIsFloat;
4012 else if (vector_type->isFloatingType())
4013 vector_type_flags |= eTypeIsInteger;
4014 }
4015 return vector_type_flags;
4016 }
4017 default:
4018 return 0;
4019 }
4020 return 0;
4021}
4022
4025 if (!type)
4026 return lldb::eLanguageTypeC;
4027
4028 // If the type is a reference, then resolve it to what it refers to first:
4029 clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType());
4030 if (qual_type->isAnyPointerType()) {
4031 if (qual_type->isObjCObjectPointerType())
4033 if (qual_type->getPointeeCXXRecordDecl())
4035
4036 clang::QualType pointee_type(qual_type->getPointeeType());
4037 if (pointee_type->getPointeeCXXRecordDecl())
4039 if (pointee_type->isObjCObjectOrInterfaceType())
4041 if (pointee_type->isObjCClassType())
4043 if (pointee_type.getTypePtr() ==
4044 getASTContext().ObjCBuiltinIdTy.getTypePtr())
4046 } else {
4047 if (qual_type->isObjCObjectOrInterfaceType())
4049 if (qual_type->getAsCXXRecordDecl())
4051 switch (qual_type->getTypeClass()) {
4052 default:
4053 break;
4054 case clang::Type::Builtin:
4055 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4056 default:
4057 case clang::BuiltinType::Void:
4058 case clang::BuiltinType::Bool:
4059 case clang::BuiltinType::Char_U:
4060 case clang::BuiltinType::UChar:
4061 case clang::BuiltinType::WChar_U:
4062 case clang::BuiltinType::Char16:
4063 case clang::BuiltinType::Char32:
4064 case clang::BuiltinType::UShort:
4065 case clang::BuiltinType::UInt:
4066 case clang::BuiltinType::ULong:
4067 case clang::BuiltinType::ULongLong:
4068 case clang::BuiltinType::UInt128:
4069 case clang::BuiltinType::Char_S:
4070 case clang::BuiltinType::SChar:
4071 case clang::BuiltinType::WChar_S:
4072 case clang::BuiltinType::Short:
4073 case clang::BuiltinType::Int:
4074 case clang::BuiltinType::Long:
4075 case clang::BuiltinType::LongLong:
4076 case clang::BuiltinType::Int128:
4077 case clang::BuiltinType::Float:
4078 case clang::BuiltinType::Double:
4079 case clang::BuiltinType::LongDouble:
4080 break;
4081
4082 case clang::BuiltinType::NullPtr:
4084
4085 case clang::BuiltinType::ObjCId:
4086 case clang::BuiltinType::ObjCClass:
4087 case clang::BuiltinType::ObjCSel:
4088 return eLanguageTypeObjC;
4089
4090 case clang::BuiltinType::Dependent:
4091 case clang::BuiltinType::Overload:
4092 case clang::BuiltinType::BoundMember:
4093 case clang::BuiltinType::UnknownAny:
4094 break;
4095 }
4096 break;
4097 case clang::Type::Typedef:
4098 return GetType(llvm::cast<clang::TypedefType>(qual_type)
4099 ->getDecl()
4100 ->getUnderlyingType())
4102 }
4103 }
4104 return lldb::eLanguageTypeC;
4105}
4106
4107lldb::TypeClass
4109 if (!type)
4110 return lldb::eTypeClassInvalid;
4111
4112 clang::QualType qual_type =
4113 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
4114
4115 switch (qual_type->getTypeClass()) {
4116 case clang::Type::Atomic:
4117 case clang::Type::Auto:
4118 case clang::Type::CountAttributed:
4119 case clang::Type::Decltype:
4120 case clang::Type::Elaborated:
4121 case clang::Type::Paren:
4122 case clang::Type::TypeOf:
4123 case clang::Type::TypeOfExpr:
4124 case clang::Type::Using:
4125 llvm_unreachable("Handled in RemoveWrappingTypes!");
4126 case clang::Type::UnaryTransform:
4127 break;
4128 case clang::Type::FunctionNoProto:
4129 return lldb::eTypeClassFunction;
4130 case clang::Type::FunctionProto:
4131 return lldb::eTypeClassFunction;
4132 case clang::Type::IncompleteArray:
4133 return lldb::eTypeClassArray;
4134 case clang::Type::VariableArray:
4135 return lldb::eTypeClassArray;
4136 case clang::Type::ConstantArray:
4137 return lldb::eTypeClassArray;
4138 case clang::Type::DependentSizedArray:
4139 return lldb::eTypeClassArray;
4140 case clang::Type::ArrayParameter:
4141 return lldb::eTypeClassArray;
4142 case clang::Type::DependentSizedExtVector:
4143 return lldb::eTypeClassVector;
4144 case clang::Type::DependentVector:
4145 return lldb::eTypeClassVector;
4146 case clang::Type::ExtVector:
4147 return lldb::eTypeClassVector;
4148 case clang::Type::Vector:
4149 return lldb::eTypeClassVector;
4150 case clang::Type::Builtin:
4151 // Ext-Int is just an integer type.
4152 case clang::Type::BitInt:
4153 case clang::Type::DependentBitInt:
4154 return lldb::eTypeClassBuiltin;
4155 case clang::Type::ObjCObjectPointer:
4156 return lldb::eTypeClassObjCObjectPointer;
4157 case clang::Type::BlockPointer:
4158 return lldb::eTypeClassBlockPointer;
4159 case clang::Type::Pointer:
4160 return lldb::eTypeClassPointer;
4161 case clang::Type::LValueReference:
4162 return lldb::eTypeClassReference;
4163 case clang::Type::RValueReference:
4164 return lldb::eTypeClassReference;
4165 case clang::Type::MemberPointer:
4166 return lldb::eTypeClassMemberPointer;
4167 case clang::Type::Complex:
4168 if (qual_type->isComplexType())
4169 return lldb::eTypeClassComplexFloat;
4170 else
4171 return lldb::eTypeClassComplexInteger;
4172 case clang::Type::ObjCObject:
4173 return lldb::eTypeClassObjCObject;
4174 case clang::Type::ObjCInterface:
4175 return lldb::eTypeClassObjCInterface;
4176 case clang::Type::Record: {
4177 const clang::RecordType *record_type =
4178 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4179 const clang::RecordDecl *record_decl = record_type->getDecl();
4180 if (record_decl->isUnion())
4181 return lldb::eTypeClassUnion;
4182 else if (record_decl->isStruct())
4183 return lldb::eTypeClassStruct;
4184 else
4185 return lldb::eTypeClassClass;
4186 } break;
4187 case clang::Type::Enum:
4188 return lldb::eTypeClassEnumeration;
4189 case clang::Type::Typedef:
4190 return lldb::eTypeClassTypedef;
4191 case clang::Type::UnresolvedUsing:
4192 break;
4193
4194 case clang::Type::Attributed:
4195 case clang::Type::BTFTagAttributed:
4196 break;
4197 case clang::Type::TemplateTypeParm:
4198 break;
4199 case clang::Type::SubstTemplateTypeParm:
4200 break;
4201 case clang::Type::SubstTemplateTypeParmPack:
4202 break;
4203 case clang::Type::InjectedClassName:
4204 break;
4205 case clang::Type::DependentName:
4206 break;
4207 case clang::Type::DependentTemplateSpecialization:
4208 break;
4209 case clang::Type::PackExpansion:
4210 break;
4211
4212 case clang::Type::TemplateSpecialization:
4213 break;
4214 case clang::Type::DeducedTemplateSpecialization:
4215 break;
4216 case clang::Type::Pipe:
4217 break;
4218
4219 // pointer type decayed from an array or function type.
4220 case clang::Type::Decayed:
4221 break;
4222 case clang::Type::Adjusted:
4223 break;
4224 case clang::Type::ObjCTypeParam:
4225 break;
4226
4227 case clang::Type::DependentAddressSpace:
4228 break;
4229 case clang::Type::MacroQualified:
4230 break;
4231
4232 // Matrix types that we're not sure how to display at the moment.
4233 case clang::Type::ConstantMatrix:
4234 case clang::Type::DependentSizedMatrix:
4235 break;
4236
4237 // We don't handle pack indexing yet
4238 case clang::Type::PackIndexing:
4239 break;
4240 }
4241 // We don't know hot to display this type...
4242 return lldb::eTypeClassOther;
4243}
4244
4246 if (type)
4247 return GetQualType(type).getQualifiers().getCVRQualifiers();
4248 return 0;
4249}
4250
4251// Creating related types
4252
4255 ExecutionContextScope *exe_scope) {
4256 if (type) {
4257 clang::QualType qual_type(GetQualType(type));
4258
4259 const clang::Type *array_eletype =
4260 qual_type.getTypePtr()->getArrayElementTypeNoTypeQual();
4261
4262 if (!array_eletype)
4263 return CompilerType();
4264
4265 return GetType(clang::QualType(array_eletype, 0));
4266 }
4267 return CompilerType();
4268}
4269
4271 uint64_t size) {
4272 if (type) {
4273 clang::QualType qual_type(GetCanonicalQualType(type));
4274 clang::ASTContext &ast_ctx = getASTContext();
4275 if (size != 0)
4276 return GetType(ast_ctx.getConstantArrayType(
4277 qual_type, llvm::APInt(64, size), nullptr,
4278 clang::ArraySizeModifier::Normal, 0));
4279 else
4280 return GetType(ast_ctx.getIncompleteArrayType(
4281 qual_type, clang::ArraySizeModifier::Normal, 0));
4282 }
4283
4284 return CompilerType();
4285}
4286
4289 if (type)
4290 return GetType(GetCanonicalQualType(type));
4291 return CompilerType();
4292}
4293
4294static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast,
4295 clang::QualType qual_type) {
4296 if (qual_type->isPointerType())
4297 qual_type = ast->getPointerType(
4298 GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType()));
4299 else if (const ConstantArrayType *arr =
4300 ast->getAsConstantArrayType(qual_type)) {
4301 qual_type = ast->getConstantArrayType(
4302 GetFullyUnqualifiedType_Impl(ast, arr->getElementType()),
4303 arr->getSize(), arr->getSizeExpr(), arr->getSizeModifier(),
4304 arr->getIndexTypeQualifiers().getAsOpaqueValue());
4305 } else
4306 qual_type = qual_type.getUnqualifiedType();
4307 qual_type.removeLocalConst();
4308 qual_type.removeLocalRestrict();
4309 qual_type.removeLocalVolatile();
4310 return qual_type;
4311}
4312
4315 if (type)
4316 return GetType(
4318 return CompilerType();
4319}
4320
4323 if (type)
4325 return CompilerType();
4326}
4327
4330 if (type) {
4331 const clang::FunctionProtoType *func =
4332 llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type));
4333 if (func)
4334 return func->getNumParams();
4335 }
4336 return -1;
4337}
4338
4340 lldb::opaque_compiler_type_t type, size_t idx) {
4341 if (type) {
4342 const clang::FunctionProtoType *func =
4343 llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type));
4344 if (func) {
4345 const uint32_t num_args = func->getNumParams();
4346 if (idx < num_args)
4347 return GetType(func->getParamType(idx));
4348 }
4349 }
4350 return CompilerType();
4351}
4352
4355 if (type) {
4356 clang::QualType qual_type(GetQualType(type));
4357 const clang::FunctionProtoType *func =
4358 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
4359 if (func)
4360 return GetType(func->getReturnType());
4361 }
4362 return CompilerType();
4363}
4364
4365size_t
4367 size_t num_functions = 0;
4368 if (type) {
4369 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4370 switch (qual_type->getTypeClass()) {
4371 case clang::Type::Record:
4372 if (GetCompleteQualType(&getASTContext(), qual_type)) {
4373 const clang::RecordType *record_type =
4374 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4375 const clang::RecordDecl *record_decl = record_type->getDecl();
4376 assert(record_decl);
4377 const clang::CXXRecordDecl *cxx_record_decl =
4378 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4379 if (cxx_record_decl)
4380 num_functions = std::distance(cxx_record_decl->method_begin(),
4381 cxx_record_decl->method_end());
4382 }
4383 break;
4384
4385 case clang::Type::ObjCObjectPointer: {
4386 const clang::ObjCObjectPointerType *objc_class_type =
4387 qual_type->castAs<clang::ObjCObjectPointerType>();
4388 const clang::ObjCInterfaceType *objc_interface_type =
4389 objc_class_type->getInterfaceType();
4390 if (objc_interface_type &&
4392 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4393 clang::ObjCInterfaceDecl *class_interface_decl =
4394 objc_interface_type->getDecl();
4395 if (class_interface_decl) {
4396 num_functions = std::distance(class_interface_decl->meth_begin(),
4397 class_interface_decl->meth_end());
4398 }
4399 }
4400 break;
4401 }
4402
4403 case clang::Type::ObjCObject:
4404 case clang::Type::ObjCInterface:
4405 if (GetCompleteType(type)) {
4406 const clang::ObjCObjectType *objc_class_type =
4407 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4408 if (objc_class_type) {
4409 clang::ObjCInterfaceDecl *class_interface_decl =
4410 objc_class_type->getInterface();
4411 if (class_interface_decl)
4412 num_functions = std::distance(class_interface_decl->meth_begin(),
4413 class_interface_decl->meth_end());
4414 }
4415 }
4416 break;
4417
4418 default:
4419 break;
4420 }
4421 }
4422 return num_functions;
4423}
4424
4427 size_t idx) {
4428 std::string name;
4429 MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
4430 CompilerType clang_type;
4431 CompilerDecl clang_decl;
4432 if (type) {
4433 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4434 switch (qual_type->getTypeClass()) {
4435 case clang::Type::Record:
4436 if (GetCompleteQualType(&getASTContext(), qual_type)) {
4437 const clang::RecordType *record_type =
4438 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4439 const clang::RecordDecl *record_decl = record_type->getDecl();
4440 assert(record_decl);
4441 const clang::CXXRecordDecl *cxx_record_decl =
4442 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4443 if (cxx_record_decl) {
4444 auto method_iter = cxx_record_decl->method_begin();
4445 auto method_end = cxx_record_decl->method_end();
4446 if (idx <
4447 static_cast<size_t>(std::distance(method_iter, method_end))) {
4448 std::advance(method_iter, idx);
4449 clang::CXXMethodDecl *cxx_method_decl =
4450 method_iter->getCanonicalDecl();
4451 if (cxx_method_decl) {
4452 name = cxx_method_decl->getDeclName().getAsString();
4453 if (cxx_method_decl->isStatic())
4455 else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4457 else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4459 else
4461 clang_type = GetType(cxx_method_decl->getType());
4462 clang_decl = GetCompilerDecl(cxx_method_decl);
4463 }
4464 }
4465 }
4466 }
4467 break;
4468
4469 case clang::Type::ObjCObjectPointer: {
4470 const clang::ObjCObjectPointerType *objc_class_type =
4471 qual_type->castAs<clang::ObjCObjectPointerType>();
4472 const clang::ObjCInterfaceType *objc_interface_type =
4473 objc_class_type->getInterfaceType();
4474 if (objc_interface_type &&
4476 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4477 clang::ObjCInterfaceDecl *class_interface_decl =
4478 objc_interface_type->getDecl();
4479 if (class_interface_decl) {
4480 auto method_iter = class_interface_decl->meth_begin();
4481 auto method_end = class_interface_decl->meth_end();
4482 if (idx <
4483 static_cast<size_t>(std::distance(method_iter, method_end))) {
4484 std::advance(method_iter, idx);
4485 clang::ObjCMethodDecl *objc_method_decl =
4486 method_iter->getCanonicalDecl();
4487 if (objc_method_decl) {
4488 clang_decl = GetCompilerDecl(objc_method_decl);
4489 name = objc_method_decl->getSelector().getAsString();
4490 if (objc_method_decl->isClassMethod())
4492 else
4494 }
4495 }
4496 }
4497 }
4498 break;
4499 }
4500
4501 case clang::Type::ObjCObject:
4502 case clang::Type::ObjCInterface:
4503 if (GetCompleteType(type)) {
4504 const clang::ObjCObjectType *objc_class_type =
4505 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4506 if (objc_class_type) {
4507 clang::ObjCInterfaceDecl *class_interface_decl =
4508 objc_class_type->getInterface();
4509 if (class_interface_decl) {
4510 auto method_iter = class_interface_decl->meth_begin();
4511 auto method_end = class_interface_decl->meth_end();
4512 if (idx <
4513 static_cast<size_t>(std::distance(method_iter, method_end))) {
4514 std::advance(method_iter, idx);
4515 clang::ObjCMethodDecl *objc_method_decl =
4516 method_iter->getCanonicalDecl();
4517 if (objc_method_decl) {
4518 clang_decl = GetCompilerDecl(objc_method_decl);
4519 name = objc_method_decl->getSelector().getAsString();
4520 if (objc_method_decl->isClassMethod())
4522 else
4524 }
4525 }
4526 }
4527 }
4528 }
4529 break;
4530
4531 default:
4532 break;
4533 }
4534 }
4535
4536 if (kind == eMemberFunctionKindUnknown)
4537 return TypeMemberFunctionImpl();
4538 else
4539 return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind);
4540}
4541
4544 if (type)
4545 return GetType(GetQualType(type).getNonReferenceType());
4546 return CompilerType();
4547}
4548
4551 if (type) {
4552 clang::QualType qual_type(GetQualType(type));
4553 return GetType(qual_type.getTypePtr()->getPointeeType());
4554 }
4555 return CompilerType();
4556}
4557
4560 if (type) {
4561 clang::QualType qual_type(GetQualType(type));
4562
4563 switch (qual_type.getDesugaredType(getASTContext())->getTypeClass()) {
4564 case clang::Type::ObjCObject:
4565 case clang::Type::ObjCInterface:
4566 return GetType(getASTContext().getObjCObjectPointerType(qual_type));
4567
4568 default:
4569 return GetType(getASTContext().getPointerType(qual_type));
4570 }
4571 }
4572 return CompilerType();
4573}
4574
4577 if (type)
4578 return GetType(getASTContext().getLValueReferenceType(GetQualType(type)));
4579 else
4580 return CompilerType();
4581}
4582
4585 if (type)
4586 return GetType(getASTContext().getRValueReferenceType(GetQualType(type)));
4587 else
4588 return CompilerType();
4589}
4590
4592 if (!type)
4593 return CompilerType();
4594 return GetType(getASTContext().getAtomicType(GetQualType(type)));
4595}
4596
4599 if (type) {
4600 clang::QualType result(GetQualType(type));
4601 result.addConst();
4602 return GetType(result);
4603 }
4604 return CompilerType();
4605}
4606
4609 uint32_t payload) {
4610 if (type) {
4611 clang::ASTContext &clang_ast = getASTContext();
4612 auto pauth = PointerAuthQualifier::fromOpaqueValue(payload);
4613 clang::QualType result =
4614 clang_ast.getPointerAuthType(GetQualType(type), pauth);
4615 return GetType(result);
4616 }
4617 return CompilerType();
4618}
4619
4622 if (type) {
4623 clang::QualType result(GetQualType(type));
4624 result.addVolatile();
4625 return GetType(result);
4626 }
4627 return CompilerType();
4628}
4629
4632 if (type) {
4633 clang::QualType result(GetQualType(type));
4634 result.addRestrict();
4635 return GetType(result);
4636 }
4637 return CompilerType();
4638}
4639
4641 lldb::opaque_compiler_type_t type, const char *typedef_name,
4642 const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) {
4643 if (type && typedef_name && typedef_name[0]) {
4644 clang::ASTContext &clang_ast = getASTContext();
4645 clang::QualType qual_type(GetQualType(type));
4646
4647 clang::DeclContext *decl_ctx =
4649 if (!decl_ctx)
4650 decl_ctx = getASTContext().getTranslationUnitDecl();
4651
4652 clang::TypedefDecl *decl =
4653 clang::TypedefDecl::CreateDeserialized(clang_ast, GlobalDeclID());
4654 decl->setDeclContext(decl_ctx);
4655 decl->setDeclName(&clang_ast.Idents.get(typedef_name));
4656 decl->setTypeSourceInfo(clang_ast.getTrivialTypeSourceInfo(qual_type));
4657 decl_ctx->addDecl(decl);
4658 SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule());
4659
4660 clang::TagDecl *tdecl = nullptr;
4661 if (!qual_type.isNull()) {
4662 if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>())
4663 tdecl = rt->getDecl();
4664 if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>())
4665 tdecl = et->getDecl();
4666 }
4667
4668 // Check whether this declaration is an anonymous struct, union, or enum,
4669 // hidden behind a typedef. If so, we try to check whether we have a
4670 // typedef tag to attach to the original record declaration
4671 if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl())
4672 tdecl->setTypedefNameForAnonDecl(decl);
4673
4674 decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4675
4676 // Get a uniqued clang::QualType for the typedef decl type
4677 return GetType(clang_ast.getTypedefType(decl));
4678 }
4679 return CompilerType();
4680}
4681
4684 if (type) {
4685 const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(
4686 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}));
4687 if (typedef_type)
4688 return GetType(typedef_type->getDecl()->getUnderlyingType());
4689 }
4690 return CompilerType();
4691}
4692
4693// Create related types using the current type's AST
4694
4696 return TypeSystemClang::GetBasicType(basic_type);
4697}
4698
4700 clang::ASTContext &ast = getASTContext();
4701 const FunctionType::ExtInfo generic_ext_info(
4702 /*noReturn=*/false,
4703 /*hasRegParm=*/false,
4704 /*regParm=*/0,
4705 CallingConv::CC_C,
4706 /*producesResult=*/false,
4707 /*noCallerSavedRegs=*/false,
4708 /*NoCfCheck=*/false,
4709 /*cmseNSCall=*/false);
4710 QualType func_type = ast.getFunctionNoProtoType(ast.VoidTy, generic_ext_info);
4711 return GetType(func_type);
4712}
4713// Exploring the type
4714
4715const llvm::fltSemantics &
4717 clang::ASTContext &ast = getASTContext();
4718 const size_t bit_size = byte_size * 8;
4719 if (bit_size == ast.getTypeSize(ast.FloatTy))
4720 return ast.getFloatTypeSemantics(ast.FloatTy);
4721 else if (bit_size == ast.getTypeSize(ast.DoubleTy))
4722 return ast.getFloatTypeSemantics(ast.DoubleTy);
4723 else if (bit_size == ast.getTypeSize(ast.LongDoubleTy) ||
4724 bit_size == llvm::APFloat::semanticsSizeInBits(
4725 ast.getFloatTypeSemantics(ast.LongDoubleTy)))
4726 return ast.getFloatTypeSemantics(ast.LongDoubleTy);
4727 else if (bit_size == ast.getTypeSize(ast.HalfTy))
4728 return ast.getFloatTypeSemantics(ast.HalfTy);
4729 return llvm::APFloatBase::Bogus();
4730}
4731
4732std::optional<uint64_t>
4734 ExecutionContextScope *exe_scope) {
4735 assert(qual_type->isObjCObjectOrInterfaceType());
4736 ExecutionContext exe_ctx(exe_scope);
4737 if (Process *process = exe_ctx.GetProcessPtr()) {
4738 if (ObjCLanguageRuntime *objc_runtime =
4739 ObjCLanguageRuntime::Get(*process)) {
4740 if (std::optional<uint64_t> bit_size =
4741 objc_runtime->GetTypeBitSize(GetType(qual_type)))
4742 return *bit_size;
4743 }
4744 } else {
4745 static bool g_printed = false;
4746 if (!g_printed) {
4747 StreamString s;
4748 DumpTypeDescription(qual_type.getAsOpaquePtr(), s);
4749
4750 llvm::outs() << "warning: trying to determine the size of type ";
4751 llvm::outs() << s.GetString() << "\n";
4752 llvm::outs() << "without a valid ExecutionContext. this is not "
4753 "reliable. please file a bug against LLDB.\n";
4754 llvm::outs() << "backtrace:\n";
4755 llvm::sys::PrintStackTrace(llvm::outs());
4756 llvm::outs() << "\n";
4757 g_printed = true;
4758 }
4759 }
4760
4761 return getASTContext().getTypeSize(qual_type) +
4762 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy);
4763}
4764
4765std::optional<uint64_t>
4767 ExecutionContextScope *exe_scope) {
4768 if (!GetCompleteType(type))
4769 return std::nullopt;
4770
4771 clang::QualType qual_type(GetCanonicalQualType(type));
4772 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4773 switch (type_class) {
4774 case clang::Type::ConstantArray:
4775 case clang::Type::FunctionProto:
4776 case clang::Type::Record:
4777 return getASTContext().getTypeSize(qual_type);
4778 case clang::Type::ObjCInterface:
4779 case clang::Type::ObjCObject:
4780 return GetObjCBitSize(qual_type, exe_scope);
4781 case clang::Type::IncompleteArray: {
4782 const uint64_t bit_size = getASTContext().getTypeSize(qual_type);
4783 if (bit_size == 0)
4784 return getASTContext().getTypeSize(
4785 qual_type->getArrayElementTypeNoTypeQual()
4786 ->getCanonicalTypeUnqualified());
4787
4788 return bit_size;
4789 }
4790 default:
4791 if (const uint64_t bit_size = getASTContext().getTypeSize(qual_type))
4792 return bit_size;
4793 }
4794
4795 return std::nullopt;
4796}
4797
4798std::optional<size_t>
4800 ExecutionContextScope *exe_scope) {
4801 if (GetCompleteType(type))
4802 return getASTContext().getTypeAlign(GetQualType(type));
4803 return {};
4804}
4805
4807 uint64_t &count) {
4808 if (!type)
4810
4811 count = 1;
4812 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4813
4814 switch (qual_type->getTypeClass()) {
4815 case clang::Type::Atomic:
4816 case clang::Type::Auto:
4817 case clang::Type::CountAttributed:
4818 case clang::Type::Decltype:
4819 case clang::Type::Elaborated:
4820 case clang::Type::Paren:
4821 case clang::Type::Typedef:
4822 case clang::Type::TypeOf:
4823 case clang::Type::TypeOfExpr:
4824 case clang::Type::Using:
4825 llvm_unreachable("Handled in RemoveWrappingTypes!");
4826
4827 case clang::Type::UnaryTransform:
4828 break;
4829
4830 case clang::Type::FunctionNoProto:
4831 case clang::Type::FunctionProto:
4832 return lldb::eEncodingUint;
4833
4834 case clang::Type::IncompleteArray:
4835 case clang::Type::VariableArray:
4836 case clang::Type::ArrayParameter:
4837 break;
4838
4839 case clang::Type::ConstantArray:
4840 break;
4841
4842 case clang::Type::DependentVector:
4843 case clang::Type::ExtVector:
4844 case clang::Type::Vector:
4845 // TODO: Set this to more than one???
4846 break;
4847
4848 case clang::Type::BitInt:
4849 case clang::Type::DependentBitInt:
4850 return qual_type->isUnsignedIntegerType() ? lldb::eEncodingUint
4852
4853 case clang::Type::Builtin:
4854 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4855 case clang::BuiltinType::Void:
4856 break;
4857
4858 case clang::BuiltinType::Char_S:
4859 case clang::BuiltinType::SChar:
4860 case clang::BuiltinType::WChar_S:
4861 case clang::BuiltinType::Short:
4862 case clang::BuiltinType::Int:
4863 case clang::BuiltinType::Long:
4864 case clang::BuiltinType::LongLong:
4865 case clang::BuiltinType::Int128:
4866 return lldb::eEncodingSint;
4867
4868 case clang::BuiltinType::Bool:
4869 case clang::BuiltinType::Char_U:
4870 case clang::BuiltinType::UChar:
4871 case clang::BuiltinType::WChar_U:
4872 case clang::BuiltinType::Char8:
4873 case clang::BuiltinType::Char16:
4874 case clang::BuiltinType::Char32:
4875 case clang::BuiltinType::UShort:
4876 case clang::BuiltinType::UInt:
4877 case clang::BuiltinType::ULong:
4878 case clang::BuiltinType::ULongLong:
4879 case clang::BuiltinType::UInt128:
4880 return lldb::eEncodingUint;
4881
4882 // Fixed point types. Note that they are currently ignored.
4883 case clang::BuiltinType::ShortAccum:
4884 case clang::BuiltinType::Accum:
4885 case clang::BuiltinType::LongAccum:
4886 case clang::BuiltinType::UShortAccum:
4887 case clang::BuiltinType::UAccum:
4888 case clang::BuiltinType::ULongAccum:
4889 case clang::BuiltinType::ShortFract:
4890 case clang::BuiltinType::Fract:
4891 case clang::BuiltinType::LongFract:
4892 case clang::BuiltinType::UShortFract:
4893 case clang::BuiltinType::UFract:
4894 case clang::BuiltinType::ULongFract:
4895 case clang::BuiltinType::SatShortAccum:
4896 case clang::BuiltinType::SatAccum:
4897 case clang::BuiltinType::SatLongAccum:
4898 case clang::BuiltinType::SatUShortAccum:
4899 case clang::BuiltinType::SatUAccum:
4900 case clang::BuiltinType::SatULongAccum:
4901 case clang::BuiltinType::SatShortFract:
4902 case clang::BuiltinType::SatFract:
4903 case clang::BuiltinType::SatLongFract:
4904 case clang::BuiltinType::SatUShortFract:
4905 case clang::BuiltinType::SatUFract:
4906 case clang::BuiltinType::SatULongFract:
4907 break;
4908
4909 case clang::BuiltinType::Half:
4910 case clang::BuiltinType::Float:
4911 case clang::BuiltinType::Float16:
4912 case clang::BuiltinType::Float128:
4913 case clang::BuiltinType::Double:
4914 case clang::BuiltinType::LongDouble:
4915 case clang::BuiltinType::BFloat16:
4916 case clang::BuiltinType::Ibm128:
4918
4919 case clang::BuiltinType::ObjCClass:
4920 case clang::BuiltinType::ObjCId:
4921 case clang::BuiltinType::ObjCSel:
4922 return lldb::eEncodingUint;
4923
4924 case clang::BuiltinType::NullPtr:
4925 return lldb::eEncodingUint;
4926
4927 case clang::BuiltinType::Kind::ARCUnbridgedCast:
4928 case clang::BuiltinType::Kind::BoundMember:
4929 case clang::BuiltinType::Kind::BuiltinFn:
4930 case clang::BuiltinType::Kind::Dependent:
4931 case clang::BuiltinType::Kind::OCLClkEvent:
4932 case clang::BuiltinType::Kind::OCLEvent:
4933 case clang::BuiltinType::Kind::OCLImage1dRO:
4934 case clang::BuiltinType::Kind::OCLImage1dWO:
4935 case clang::BuiltinType::Kind::OCLImage1dRW:
4936 case clang::BuiltinType::Kind::OCLImage1dArrayRO:
4937 case clang::BuiltinType::Kind::OCLImage1dArrayWO:
4938 case clang::BuiltinType::Kind::OCLImage1dArrayRW:
4939 case clang::BuiltinType::Kind::OCLImage1dBufferRO:
4940 case clang::BuiltinType::Kind::OCLImage1dBufferWO:
4941 case clang::BuiltinType::Kind::OCLImage1dBufferRW:
4942 case clang::BuiltinType::Kind::OCLImage2dRO:
4943 case clang::BuiltinType::Kind::OCLImage2dWO:
4944 case clang::BuiltinType::Kind::OCLImage2dRW:
4945 case clang::BuiltinType::Kind::OCLImage2dArrayRO:
4946 case clang::BuiltinType::Kind::OCLImage2dArrayWO:
4947 case clang::BuiltinType::Kind::OCLImage2dArrayRW:
4948 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO:
4949 case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO:
4950 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW:
4951 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO:
4952 case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO:
4953 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW:
4954 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO:
4955 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO:
4956 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW:
4957 case clang::BuiltinType::Kind::OCLImage2dDepthRO:
4958 case clang::BuiltinType::Kind::OCLImage2dDepthWO:
4959 case clang::BuiltinType::Kind::OCLImage2dDepthRW:
4960 case clang::BuiltinType::Kind::OCLImage2dMSAARO:
4961 case clang::BuiltinType::Kind::OCLImage2dMSAAWO:
4962 case clang::BuiltinType::Kind::OCLImage2dMSAARW:
4963 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO:
4964 case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO:
4965 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW:
4966 case clang::BuiltinType::Kind::OCLImage3dRO:
4967 case clang::BuiltinType::Kind::OCLImage3dWO:
4968 case clang::BuiltinType::Kind::OCLImage3dRW:
4969 case clang::BuiltinType::Kind::OCLQueue:
4970 case clang::BuiltinType::Kind::OCLReserveID:
4971 case clang::BuiltinType::Kind::OCLSampler:
4972 case clang::BuiltinType::Kind::HLSLResource:
4973 case clang::BuiltinType::Kind::ArraySection:
4974 case clang::BuiltinType::Kind::OMPArrayShaping:
4975 case clang::BuiltinType::Kind::OMPIterator:
4976 case clang::BuiltinType::Kind::Overload:
4977 case clang::BuiltinType::Kind::PseudoObject:
4978 case clang::BuiltinType::Kind::UnknownAny:
4979 break;
4980
4981 case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
4982 case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
4983 case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
4984 case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
4985 case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
4986 case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
4987 case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
4988 case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
4989 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleReferenceStreamout:
4990 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualReferenceStreamout:
4991 case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleReferenceStreamin:
4992 case clang::BuiltinType::OCLIntelSubgroupAVCImeDualReferenceStreamin:
4993 break;
4994
4995 // PowerPC -- Matrix Multiply Assist
4996 case clang::BuiltinType::VectorPair:
4997 case clang::BuiltinType::VectorQuad:
4998 break;
4999
5000 // ARM -- Scalable Vector Extension
5001 case clang::BuiltinType::SveBool:
5002 case clang::BuiltinType::SveBoolx2:
5003 case clang::BuiltinType::SveBoolx4:
5004 case clang::BuiltinType::SveCount:
5005 case clang::BuiltinType::SveInt8:
5006 case clang::BuiltinType::SveInt8x2:
5007 case clang::BuiltinType::SveInt8x3:
5008 case clang::BuiltinType::SveInt8x4:
5009 case clang::BuiltinType::SveInt16:
5010 case clang::BuiltinType::SveInt16x2:
5011 case clang::BuiltinType::SveInt16x3:
5012 case clang::BuiltinType::SveInt16x4:
5013 case clang::BuiltinType::SveInt32:
5014 case clang::BuiltinType::SveInt32x2:
5015 case clang::BuiltinType::SveInt32x3:
5016 case clang::BuiltinType::SveInt32x4:
5017 case clang::BuiltinType::SveInt64:
5018 case clang::BuiltinType::SveInt64x2:
5019 case clang::BuiltinType::SveInt64x3:
5020 case clang::BuiltinType::SveInt64x4:
5021 case clang::BuiltinType::SveUint8:
5022 case clang::BuiltinType::SveUint8x2:
5023 case clang::BuiltinType::SveUint8x3:
5024 case clang::BuiltinType::SveUint8x4:
5025 case clang::BuiltinType::SveUint16:
5026 case clang::BuiltinType::SveUint16x2:
5027 case clang::BuiltinType::SveUint16x3:
5028 case clang::BuiltinType::SveUint16x4:
5029 case clang::BuiltinType::SveUint32:
5030 case clang::BuiltinType::SveUint32x2:
5031 case clang::BuiltinType::SveUint32x3:
5032 case clang::BuiltinType::SveUint32x4:
5033 case clang::BuiltinType::SveUint64:
5034 case clang::BuiltinType::SveUint64x2:
5035 case clang::BuiltinType::SveUint64x3:
5036 case clang::BuiltinType::SveUint64x4:
5037 case clang::BuiltinType::SveFloat16:
5038 case clang::BuiltinType::SveBFloat16:
5039 case clang::BuiltinType::SveBFloat16x2:
5040 case clang::BuiltinType::SveBFloat16x3:
5041 case clang::BuiltinType::SveBFloat16x4:
5042 case clang::BuiltinType::SveFloat16x2:
5043 case clang::BuiltinType::SveFloat16x3:
5044 case clang::BuiltinType::SveFloat16x4:
5045 case clang::BuiltinType::SveFloat32:
5046 case clang::BuiltinType::SveFloat32x2:
5047 case clang::BuiltinType::SveFloat32x3:
5048 case clang::BuiltinType::SveFloat32x4:
5049 case clang::BuiltinType::SveFloat64:
5050 case clang::BuiltinType::SveFloat64x2:
5051 case clang::BuiltinType::SveFloat64x3:
5052 case clang::BuiltinType::SveFloat64x4:
5053 break;
5054
5055 // RISC-V V builtin types.
5056#define RVV_TYPE(Name, Id, SingletonId) case clang::BuiltinType::Id:
5057#include "clang/Basic/RISCVVTypes.def"
5058 break;
5059
5060 // WebAssembly builtin types.
5061 case clang::BuiltinType::WasmExternRef:
5062 break;
5063
5064 case clang::BuiltinType::IncompleteMatrixIdx:
5065 break;
5066
5067 case clang::BuiltinType::UnresolvedTemplate:
5068 break;
5069
5070 // AMD GPU builtin types.
5071#define AMDGPU_TYPE(Name, Id, SingletonId) case clang::BuiltinType::Id:
5072#include "clang/Basic/AMDGPUTypes.def"
5073 break;
5074 }
5075 break;
5076 // All pointer types are represented as unsigned integer encodings. We may
5077 // nee to add a eEncodingPointer if we ever need to know the difference
5078 case clang::Type::ObjCObjectPointer:
5079 case clang::Type::BlockPointer:
5080 case clang::Type::Pointer:
5081 case clang::Type::LValueReference:
5082 case clang::Type::RValueReference:
5083 case clang::Type::MemberPointer:
5084 return lldb::eEncodingUint;
5085 case clang::Type::Complex: {
5087 if (qual_type->isComplexType())
5088 encoding = lldb::eEncodingIEEE754;
5089 else {
5090 const clang::ComplexType *complex_type =
5091 qual_type->getAsComplexIntegerType();
5092 if (complex_type)
5093 encoding = GetType(complex_type->getElementType()).GetEncoding(count);
5094 else
5095 encoding = lldb::eEncodingSint;
5096 }
5097 count = 2;
5098 return encoding;
5099 }
5100
5101 case clang::Type::ObjCInterface:
5102 break;
5103 case clang::Type::Record:
5104 break;
5105 case clang::Type::Enum:
5106 return qual_type->isUnsignedIntegerOrEnumerationType()
5109 case clang::Type::DependentSizedArray:
5110 case clang::Type::DependentSizedExtVector:
5111 case clang::Type::UnresolvedUsing:
5112 case clang::Type::Attributed:
5113 case clang::Type::BTFTagAttributed:
5114 case clang::Type::TemplateTypeParm:
5115 case clang::Type::SubstTemplateTypeParm:
5116 case clang::Type::SubstTemplateTypeParmPack:
5117 case clang::Type::InjectedClassName:
5118 case clang::Type::DependentName:
5119 case clang::Type::DependentTemplateSpecialization:
5120 case clang::Type::PackExpansion:
5121 case clang::Type::ObjCObject:
5122
5123 case clang::Type::TemplateSpecialization:
5124 case clang::Type::DeducedTemplateSpecialization:
5125 case clang::Type::Adjusted:
5126 case clang::Type::Pipe:
5127 break;
5128
5129 // pointer type decayed from an array or function type.
5130 case clang::Type::Decayed:
5131 break;
5132 case clang::Type::ObjCTypeParam:
5133 break;
5134
5135 case clang::Type::DependentAddressSpace:
5136 break;
5137 case clang::Type::MacroQualified:
5138 break;
5139
5140 case clang::Type::ConstantMatrix:
5141 case clang::Type::DependentSizedMatrix:
5142 break;
5143
5144 // We don't handle pack indexing yet
5145 case clang::Type::PackIndexing:
5146 break;
5147 }
5148 count = 0;
5150}
5151
5153 if (!type)
5154 return lldb::eFormatDefault;
5155
5156 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5157
5158 switch (qual_type->getTypeClass()) {
5159 case clang::Type::Atomic:
5160 case clang::Type::Auto:
5161 case clang::Type::CountAttributed:
5162 case clang::Type::Decltype:
5163 case clang::Type::Elaborated:
5164 case clang::Type::Paren:
5165 case clang::Type::Typedef:
5166 case clang::Type::TypeOf:
5167 case clang::Type::TypeOfExpr:
5168 case clang::Type::Using:
5169 llvm_unreachable("Handled in RemoveWrappingTypes!");
5170 case clang::Type::UnaryTransform:
5171 break;
5172
5173 case clang::Type::FunctionNoProto:
5174 case clang::Type::FunctionProto:
5175 break;
5176
5177 case clang::Type::IncompleteArray:
5178 case clang::Type::VariableArray:
5179 case clang::Type::ArrayParameter:
5180 break;
5181
5182 case clang::Type::ConstantArray:
5183 return lldb::eFormatVoid; // no value
5184
5185 case clang::Type::DependentVector:
5186 case clang::Type::ExtVector:
5187 case clang::Type::Vector:
5188 break;
5189
5190 case clang::Type::BitInt:
5191 case clang::Type::DependentBitInt:
5192 return qual_type->isUnsignedIntegerType() ? lldb::eFormatUnsigned
5194
5195 case clang::Type::Builtin:
5196 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5197 case clang::BuiltinType::UnknownAny:
5198 case clang::BuiltinType::Void:
5199 case clang::BuiltinType::BoundMember:
5200 break;
5201
5202 case clang::BuiltinType::Bool:
5203 return lldb::eFormatBoolean;
5204 case clang::BuiltinType::Char_S:
5205 case clang::BuiltinType::SChar:
5206 case clang::BuiltinType::WChar_S:
5207 case clang::BuiltinType::Char_U:
5208 case clang::BuiltinType::UChar:
5209 case clang::BuiltinType::WChar_U:
5210 return lldb::eFormatChar;
5211 case clang::BuiltinType::Char8:
5212 return lldb::eFormatUnicode8;
5213 case clang::BuiltinType::Char16:
5215 case clang::BuiltinType::Char32:
5217 case clang::BuiltinType::UShort:
5218 return lldb::eFormatUnsigned;
5219 case clang::BuiltinType::Short:
5220 return lldb::eFormatDecimal;
5221 case clang::BuiltinType::UInt:
5222 return lldb::eFormatUnsigned;
5223 case clang::BuiltinType::Int:
5224 return lldb::eFormatDecimal;
5225 case clang::BuiltinType::ULong:
5226 return lldb::eFormatUnsigned;
5227 case clang::BuiltinType::Long:
5228 return lldb::eFormatDecimal;
5229 case clang::BuiltinType::ULongLong:
5230 return lldb::eFormatUnsigned;
5231 case clang::BuiltinType::LongLong:
5232 return lldb::eFormatDecimal;
5233 case clang::BuiltinType::UInt128:
5234 return lldb::eFormatUnsigned;
5235 case clang::BuiltinType::Int128:
5236 return lldb::eFormatDecimal;
5237 case clang::BuiltinType::Half:
5238 case clang::BuiltinType::Float:
5239 case clang::BuiltinType::Double:
5240 case clang::BuiltinType::LongDouble:
5241 return lldb::eFormatFloat;
5242 default:
5243 return lldb::eFormatHex;
5244 }
5245 break;
5246 case clang::Type::ObjCObjectPointer:
5247 return lldb::eFormatHex;
5248 case clang::Type::BlockPointer:
5249 return lldb::eFormatHex;
5250 case clang::Type::Pointer:
5251 return lldb::eFormatHex;
5252 case clang::Type::LValueReference:
5253 case clang::Type::RValueReference:
5254 return lldb::eFormatHex;
5255 case clang::Type::MemberPointer:
5256 return lldb::eFormatHex;
5257 case clang::Type::Complex: {
5258 if (qual_type->isComplexType())
5259 return lldb::eFormatComplex;
5260 else
5262 }
5263 case clang::Type::ObjCInterface:
5264 break;
5265 case clang::Type::Record:
5266 break;
5267 case clang::Type::Enum:
5268 return lldb::eFormatEnum;
5269 case clang::Type::DependentSizedArray:
5270 case clang::Type::DependentSizedExtVector:
5271 case clang::Type::UnresolvedUsing:
5272 case clang::Type::Attributed:
5273 case clang::Type::BTFTagAttributed:
5274 case clang::Type::TemplateTypeParm:
5275 case clang::Type::SubstTemplateTypeParm:
5276 case clang::Type::SubstTemplateTypeParmPack:
5277 case clang::Type::InjectedClassName:
5278 case clang::Type::DependentName:
5279 case clang::Type::DependentTemplateSpecialization:
5280 case clang::Type::PackExpansion:
5281 case clang::Type::ObjCObject:
5282
5283 case clang::Type::TemplateSpecialization:
5284 case clang::Type::DeducedTemplateSpecialization:
5285 case clang::Type::Adjusted:
5286 case clang::Type::Pipe:
5287 break;
5288
5289 // pointer type decayed from an array or function type.
5290 case clang::Type::Decayed:
5291 break;
5292 case clang::Type::ObjCTypeParam:
5293 break;
5294
5295 case clang::Type::DependentAddressSpace:
5296 break;
5297 case clang::Type::MacroQualified:
5298 break;
5299
5300 // Matrix types we're not sure how to display yet.
5301 case clang::Type::ConstantMatrix:
5302 case clang::Type::DependentSizedMatrix:
5303 break;
5304
5305 // We don't handle pack indexing yet
5306 case clang::Type::PackIndexing:
5307 break;
5308 }
5309 // We don't know hot to display this type...
5310 return lldb::eFormatBytes;
5311}
5312
5313static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl,
5314 bool check_superclass) {
5315 while (class_interface_decl) {
5316 if (class_interface_decl->ivar_size() > 0)
5317 return true;
5318
5319 if (check_superclass)
5320 class_interface_decl = class_interface_decl->getSuperClass();
5321 else
5322 break;
5323 }
5324 return false;
5325}
5326
5327static std::optional<SymbolFile::ArrayInfo>
5329 clang::QualType qual_type,
5330 const ExecutionContext *exe_ctx) {
5331 if (qual_type->isIncompleteArrayType())
5332 if (std::optional<ClangASTMetadata> metadata =
5333 ast.GetMetadata(qual_type.getTypePtr()))
5334 return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(),
5335 exe_ctx);
5336 return std::nullopt;
5337}
5338
5339llvm::Expected<uint32_t>
5341 bool omit_empty_base_classes,
5342 const ExecutionContext *exe_ctx) {
5343 if (!type)
5344 return llvm::createStringError("invalid clang type");
5345
5346 uint32_t num_children = 0;
5347 clang::QualType qual_type(RemoveWrappingTypes(GetQualType(type)));
5348 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5349 switch (type_class) {
5350 case clang::Type::Builtin:
5351 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5352 case clang::BuiltinType::ObjCId: // child is Class
5353 case clang::BuiltinType::ObjCClass: // child is Class
5354 num_children = 1;
5355 break;
5356
5357 default:
5358 break;
5359 }
5360 break;
5361
5362 case clang::Type::Complex:
5363 return 0;
5364 case clang::Type::Record:
5365 if (GetCompleteQualType(&getASTContext(), qual_type)) {
5366 const clang::RecordType *record_type =
5367 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5368 const clang::RecordDecl *record_decl = record_type->getDecl();
5369 assert(record_decl);
5370 const clang::CXXRecordDecl *cxx_record_decl =
5371 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
5372 if (cxx_record_decl) {
5373 if (omit_empty_base_classes) {
5374 // Check each base classes to see if it or any of its base classes
5375 // contain any fields. This can help limit the noise in variable
5376 // views by not having to show base classes that contain no members.
5377 clang::CXXRecordDecl::base_class_const_iterator base_class,
5378 base_class_end;
5379 for (base_class = cxx_record_decl->bases_begin(),
5380 base_class_end = cxx_record_decl->bases_end();
5381 base_class != base_class_end; ++base_class) {
5382 const clang::CXXRecordDecl *base_class_decl =
5383 llvm::cast<clang::CXXRecordDecl>(
5384 base_class->getType()
5385 ->getAs<clang::RecordType>()
5386 ->getDecl());
5387
5388 // Skip empty base classes
5389 if (!TypeSystemClang::RecordHasFields(base_class_decl))
5390 continue;
5391
5392 num_children++;
5393 }
5394 } else {
5395 // Include all base classes
5396 num_children += cxx_record_decl->getNumBases();
5397 }
5398 }
5399 num_children += std::distance(record_decl->field_begin(),
5400 record_decl->field_end());
5401 } else
5402 return llvm::createStringError(
5403 "incomplete type \"" + GetDisplayTypeName(type).GetString() + "\"");
5404 break;
5405 case clang::Type::ObjCObject:
5406 case clang::Type::ObjCInterface:
5407 if (GetCompleteQualType(&getASTContext(), qual_type)) {
5408 const clang::ObjCObjectType *objc_class_type =
5409 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5410 assert(objc_class_type);
5411 if (objc_class_type) {
5412 clang::ObjCInterfaceDecl *class_interface_decl =
5413 objc_class_type->getInterface();
5414
5415 if (class_interface_decl) {
5416
5417 clang::ObjCInterfaceDecl *superclass_interface_decl =
5418 class_interface_decl->getSuperClass();
5419 if (superclass_interface_decl) {
5420 if (omit_empty_base_classes) {
5421 if (ObjCDeclHasIVars(superclass_interface_decl, true))
5422 ++num_children;
5423 } else
5424 ++num_children;
5425 }
5426
5427 num_children += class_interface_decl->ivar_size();
5428 }
5429 }
5430 }
5431 break;
5432
5433 case clang::Type::LValueReference:
5434 case clang::Type::RValueReference:
5435 case clang::Type::ObjCObjectPointer: {
5436 CompilerType pointee_clang_type(GetPointeeType(type));
5437
5438 uint32_t num_pointee_children = 0;
5439 if (pointee_clang_type.IsAggregateType()) {
5440 auto num_children_or_err =
5441 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5442 if (!num_children_or_err)
5443 return num_children_or_err;
5444 num_pointee_children = *num_children_or_err;
5445 }
5446 // If this type points to a simple type, then it has 1 child
5447 if (num_pointee_children == 0)
5448 num_children = 1;
5449 else
5450 num_children = num_pointee_children;
5451 } break;
5452
5453 case clang::Type::Vector:
5454 case clang::Type::ExtVector:
5455 num_children =
5456 llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements();
5457 break;
5458
5459 case clang::Type::ConstantArray:
5460 num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr())
5461 ->getSize()
5462 .getLimitedValue();
5463 break;
5464 case clang::Type::IncompleteArray:
5465 if (auto array_info =
5466 GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx))
5467 // FIXME: Only 1-dimensional arrays are supported.
5468 num_children = array_info->element_orders.size()
5469 ? array_info->element_orders.back().value_or(0)
5470 : 0;
5471 break;
5472
5473 case clang::Type::Pointer: {
5474 const clang::PointerType *pointer_type =
5475 llvm::cast<clang::PointerType>(qual_type.getTypePtr());
5476 clang::QualType pointee_type(pointer_type->getPointeeType());
5477 CompilerType pointee_clang_type(GetType(pointee_type));
5478 uint32_t num_pointee_children = 0;
5479 if (pointee_clang_type.IsAggregateType()) {
5480 auto num_children_or_err =
5481 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5482 if (!num_children_or_err)
5483 return num_children_or_err;
5484 num_pointee_children = *num_children_or_err;
5485 }
5486 if (num_pointee_children == 0) {
5487 // We have a pointer to a pointee type that claims it has no children. We
5488 // will want to look at
5489 num_children = GetNumPointeeChildren(pointee_type);
5490 } else
5491 num_children = num_pointee_children;
5492 } break;
5493
5494 default:
5495 break;
5496 }
5497 return num_children;
5498}
5499
5502}
5503
5506 if (type) {
5507 clang::QualType qual_type(GetQualType(type));
5508 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5509 if (type_class == clang::Type::Builtin) {
5510 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5511 case clang::BuiltinType::Void:
5512 return eBasicTypeVoid;
5513 case clang::BuiltinType::Bool:
5514 return eBasicTypeBool;
5515 case clang::BuiltinType::Char_S:
5516 return eBasicTypeSignedChar;
5517 case clang::BuiltinType::Char_U:
5519 case clang::BuiltinType::Char8:
5520 return eBasicTypeChar8;
5521 case clang::BuiltinType::Char16:
5522 return eBasicTypeChar16;
5523 case clang::BuiltinType::Char32:
5524 return eBasicTypeChar32;
5525 case clang::BuiltinType::UChar:
5527 case clang::BuiltinType::SChar:
5528 return eBasicTypeSignedChar;
5529 case clang::BuiltinType::WChar_S:
5530 return eBasicTypeSignedWChar;
5531 case clang::BuiltinType::WChar_U:
5533 case clang::BuiltinType::Short:
5534 return eBasicTypeShort;
5535 case clang::BuiltinType::UShort:
5537 case clang::BuiltinType::Int:
5538 return eBasicTypeInt;
5539 case clang::BuiltinType::UInt:
5540 return eBasicTypeUnsignedInt;
5541 case clang::BuiltinType::Long:
5542 return eBasicTypeLong;
5543 case clang::BuiltinType::ULong:
5545 case clang::BuiltinType::LongLong:
5546 return eBasicTypeLongLong;
5547 case clang::BuiltinType::ULongLong:
5549 case clang::BuiltinType::Int128:
5550 return eBasicTypeInt128;
5551 case clang::BuiltinType::UInt128:
5553
5554 case clang::BuiltinType::Half:
5555 return eBasicTypeHalf;
5556 case clang::BuiltinType::Float:
5557 return eBasicTypeFloat;
5558 case clang::BuiltinType::Double:
5559 return eBasicTypeDouble;
5560 case clang::BuiltinType::LongDouble:
5561 return eBasicTypeLongDouble;
5562
5563 case clang::BuiltinType::NullPtr:
5564 return eBasicTypeNullPtr;
5565 case clang::BuiltinType::ObjCId:
5566 return eBasicTypeObjCID;
5567 case clang::BuiltinType::ObjCClass:
5568 return eBasicTypeObjCClass;
5569 case clang::BuiltinType::ObjCSel:
5570 return eBasicTypeObjCSel;
5571 default:
5572 return eBasicTypeOther;
5573 }
5574 }
5575 }
5576 return eBasicTypeInvalid;
5577}
5578
5581 std::function<bool(const CompilerType &integer_type,
5582 ConstString name,
5583 const llvm::APSInt &value)> const &callback) {
5584 const clang::EnumType *enum_type =
5585 llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type));
5586 if (enum_type) {
5587 const clang::EnumDecl *enum_decl = enum_type->getDecl();
5588 if (enum_decl) {
5589 CompilerType integer_type = GetType(enum_decl->getIntegerType());
5590
5591 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
5592 for (enum_pos = enum_decl->enumerator_begin(),
5593 enum_end_pos = enum_decl->enumerator_end();
5594 enum_pos != enum_end_pos; ++enum_pos) {
5595 ConstString name(enum_pos->getNameAsString().c_str());
5596 if (!callback(integer_type, name, enum_pos->getInitVal()))
5597 break;
5598 }
5599 }
5600 }
5601}
5602
5603#pragma mark Aggregate Types
5604
5606 if (!type)
5607 return 0;
5608
5609 uint32_t count = 0;
5610 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5611 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5612 switch (type_class) {
5613 case clang::Type::Record:
5614 if (GetCompleteType(type)) {
5615 const clang::RecordType *record_type =
5616 llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
5617 if (record_type) {
5618 clang::RecordDecl *record_decl = record_type->getDecl();
5619 if (record_decl) {
5620 count = std::distance(record_decl->field_begin(),
5621 record_decl->field_end());
5622 }
5623 }
5624 }
5625 break;
5626
5627 case clang::Type::ObjCObjectPointer: {
5628 const clang::ObjCObjectPointerType *objc_class_type =
5629 qual_type->castAs<clang::ObjCObjectPointerType>();
5630 const clang::ObjCInterfaceType *objc_interface_type =
5631 objc_class_type->getInterfaceType();
5632 if (objc_interface_type &&
5634 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5635 clang::ObjCInterfaceDecl *class_interface_decl =
5636 objc_interface_type->getDecl();
5637 if (class_interface_decl) {
5638 count = class_interface_decl->ivar_size();
5639 }
5640 }
5641 break;
5642 }
5643
5644 case clang::Type::ObjCObject:
5645 case clang::Type::ObjCInterface:
5646 if (GetCompleteType(type)) {
5647 const clang::ObjCObjectType *objc_class_type =
5648 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5649 if (objc_class_type) {
5650 clang::ObjCInterfaceDecl *class_interface_decl =
5651 objc_class_type->getInterface();
5652
5653 if (class_interface_decl)
5654 count = class_interface_decl->ivar_size();
5655 }
5656 }
5657 break;
5658
5659 default:
5660 break;
5661 }
5662 return count;
5663}
5664
5666GetObjCFieldAtIndex(clang::ASTContext *ast,
5667 clang::ObjCInterfaceDecl *class_interface_decl, size_t idx,
5668 std::string &name, uint64_t *bit_offset_ptr,
5669 uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) {
5670 if (class_interface_decl) {
5671 if (idx < (class_interface_decl->ivar_size())) {
5672 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
5673 ivar_end = class_interface_decl->ivar_end();
5674 uint32_t ivar_idx = 0;
5675
5676 for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end;
5677 ++ivar_pos, ++ivar_idx) {
5678 if (ivar_idx == idx) {
5679 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
5680
5681 clang::QualType ivar_qual_type(ivar_decl->getType());
5682
5683 name.assign(ivar_decl->getNameAsString());
5684
5685 if (bit_offset_ptr) {
5686 const clang::ASTRecordLayout &interface_layout =
5687 ast->getASTObjCInterfaceLayout(class_interface_decl);
5688 *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx);
5689 }
5690
5691 const bool is_bitfield = ivar_pos->isBitField();
5692
5693 if (bitfield_bit_size_ptr) {
5694 *bitfield_bit_size_ptr = 0;
5695
5696 if (is_bitfield && ast) {
5697 clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
5698 clang::Expr::EvalResult result;
5699 if (bitfield_bit_size_expr &&
5700 bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) {
5701 llvm::APSInt bitfield_apsint = result.Val.getInt();
5702 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5703 }
5704 }
5705 }
5706 if (is_bitfield_ptr)
5707 *is_bitfield_ptr = is_bitfield;
5708
5709 return ivar_qual_type.getAsOpaquePtr();
5710 }
5711 }
5712 }
5713 }
5714 return nullptr;
5715}
5716
5718 size_t idx, std::string &name,
5719 uint64_t *bit_offset_ptr,
5720 uint32_t *bitfield_bit_size_ptr,
5721 bool *is_bitfield_ptr) {
5722 if (!type)
5723 return CompilerType();
5724
5725 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5726 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5727 switch (type_class) {
5728 case clang::Type::Record:
5729 if (GetCompleteType(type)) {
5730 const clang::RecordType *record_type =
5731 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5732 const clang::RecordDecl *record_decl = record_type->getDecl();
5733 uint32_t field_idx = 0;
5734 clang::RecordDecl::field_iterator field, field_end;
5735 for (field = record_decl->field_begin(),
5736 field_end = record_decl->field_end();
5737 field != field_end; ++field, ++field_idx) {
5738 if (idx == field_idx) {
5739 // Print the member type if requested
5740 // Print the member name and equal sign
5741 name.assign(field->getNameAsString());
5742
5743 // Figure out the type byte size (field_type_info.first) and
5744 // alignment (field_type_info.second) from the AST context.
5745 if (bit_offset_ptr) {
5746 const clang::ASTRecordLayout &record_layout =
5747 getASTContext().getASTRecordLayout(record_decl);
5748 *bit_offset_ptr = record_layout.getFieldOffset(field_idx);
5749 }
5750
5751 const bool is_bitfield = field->isBitField();
5752
5753 if (bitfield_bit_size_ptr) {
5754 *bitfield_bit_size_ptr = 0;
5755
5756 if (is_bitfield) {
5757 clang::Expr *bitfield_bit_size_expr = field->getBitWidth();
5758 clang::Expr::EvalResult result;
5759 if (bitfield_bit_size_expr &&
5760 bitfield_bit_size_expr->EvaluateAsInt(result,
5761 getASTContext())) {
5762 llvm::APSInt bitfield_apsint = result.Val.getInt();
5763 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5764 }
5765 }
5766 }
5767 if (is_bitfield_ptr)
5768 *is_bitfield_ptr = is_bitfield;
5769
5770 return GetType(field->getType());
5771 }
5772 }
5773 }
5774 break;
5775
5776 case clang::Type::ObjCObjectPointer: {
5777 const clang::ObjCObjectPointerType *objc_class_type =
5778 qual_type->castAs<clang::ObjCObjectPointerType>();
5779 const clang::ObjCInterfaceType *objc_interface_type =
5780 objc_class_type->getInterfaceType();
5781 if (objc_interface_type &&
5783 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5784 clang::ObjCInterfaceDecl *class_interface_decl =
5785 objc_interface_type->getDecl();
5786 if (class_interface_decl) {
5787 return CompilerType(
5788 weak_from_this(),
5789 GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx,
5790 name, bit_offset_ptr, bitfield_bit_size_ptr,
5791 is_bitfield_ptr));
5792 }
5793 }
5794 break;
5795 }
5796