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