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