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