1//===-- DWARFASTParserClang.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 <cstdlib>
10
11#include "DWARFASTParser.h"
12#include "DWARFASTParserClang.h"
13#include "DWARFDebugInfo.h"
14#include "DWARFDeclContext.h"
15#include "DWARFDefines.h"
16#include "SymbolFileDWARF.h"
17#include "SymbolFileDWARFDebugMap.h"
18#include "SymbolFileDWARFDwo.h"
19#include "UniqueDWARFASTType.h"
20
21#include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
22#include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
23#include "Plugins/ExpressionParser/Clang/ClangUtil.h"
24#include "Plugins/Language/ObjC/ObjCLanguage.h"
25#include "lldb/Core/Module.h"
26#include "lldb/Core/Value.h"
27#include "lldb/Host/Host.h"
28#include "lldb/Symbol/CompileUnit.h"
29#include "lldb/Symbol/Function.h"
30#include "lldb/Symbol/ObjectFile.h"
31#include "lldb/Symbol/SymbolFile.h"
32#include "lldb/Symbol/TypeList.h"
33#include "lldb/Symbol/TypeMap.h"
34#include "lldb/Symbol/VariableList.h"
35#include "lldb/Target/Language.h"
36#include "lldb/Utility/LLDBAssert.h"
37#include "lldb/Utility/Log.h"
38#include "lldb/Utility/StreamString.h"
39
40#include "clang/AST/CXXInheritance.h"
41#include "clang/AST/DeclCXX.h"
42#include "clang/AST/DeclObjC.h"
43#include "clang/AST/DeclTemplate.h"
44#include "clang/AST/Type.h"
45#include "llvm/Demangle/Demangle.h"
46
47#include <map>
48#include <memory>
49#include <optional>
50#include <vector>
51
52//#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
53
54#ifdef ENABLE_DEBUG_PRINTF
55#include <cstdio>
56#define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
57#else
58#define DEBUG_PRINTF(fmt, ...)
59#endif
60
61using namespace lldb;
62using namespace lldb_private;
63using namespace lldb_private::dwarf;
64using namespace lldb_private::plugin::dwarf;
65
66DWARFASTParserClang::DWARFASTParserClang(TypeSystemClang &ast)
67 : DWARFASTParser(Kind::DWARFASTParserClang), m_ast(ast),
68 m_die_to_decl_ctx(), m_decl_ctx_to_die() {}
69
70DWARFASTParserClang::~DWARFASTParserClang() = default;
71
72static bool DeclKindIsCXXClass(clang::Decl::Kind decl_kind) {
73 switch (decl_kind) {
74 case clang::Decl::CXXRecord:
75 case clang::Decl::ClassTemplateSpecialization:
76 return true;
77 default:
78 break;
79 }
80 return false;
81}
82
83
84ClangASTImporter &DWARFASTParserClang::GetClangASTImporter() {
85 if (!m_clang_ast_importer_up) {
86 m_clang_ast_importer_up = std::make_unique<ClangASTImporter>();
87 }
88 return *m_clang_ast_importer_up;
89}
90
91/// Detect a forward declaration that is nested in a DW_TAG_module.
92static bool IsClangModuleFwdDecl(const DWARFDIE &Die) {
93 if (!Die.GetAttributeValueAsUnsigned(attr: DW_AT_declaration, fail_value: 0))
94 return false;
95 auto Parent = Die.GetParent();
96 while (Parent.IsValid()) {
97 if (Parent.Tag() == DW_TAG_module)
98 return true;
99 Parent = Parent.GetParent();
100 }
101 return false;
102}
103
104static DWARFDIE GetContainingClangModuleDIE(const DWARFDIE &die) {
105 if (die.IsValid()) {
106 DWARFDIE top_module_die;
107 // Now make sure this DIE is scoped in a DW_TAG_module tag and return true
108 // if so
109 for (DWARFDIE parent = die.GetParent(); parent.IsValid();
110 parent = parent.GetParent()) {
111 const dw_tag_t tag = parent.Tag();
112 if (tag == DW_TAG_module)
113 top_module_die = parent;
114 else if (tag == DW_TAG_compile_unit || tag == DW_TAG_partial_unit)
115 break;
116 }
117
118 return top_module_die;
119 }
120 return DWARFDIE();
121}
122
123static lldb::ModuleSP GetContainingClangModule(const DWARFDIE &die) {
124 if (die.IsValid()) {
125 DWARFDIE clang_module_die = GetContainingClangModuleDIE(die);
126
127 if (clang_module_die) {
128 const char *module_name = clang_module_die.GetName();
129 if (module_name)
130 return die.GetDWARF()->GetExternalModule(
131 name: lldb_private::ConstString(module_name));
132 }
133 }
134 return lldb::ModuleSP();
135}
136
137// Returns true if the given artificial field name should be ignored when
138// parsing the DWARF.
139static bool ShouldIgnoreArtificialField(llvm::StringRef FieldName) {
140 return FieldName.starts_with(Prefix: "_vptr$")
141 // gdb emit vtable pointer as "_vptr.classname"
142 || FieldName.starts_with(Prefix: "_vptr.");
143}
144
145/// Returns true for C++ constructs represented by clang::CXXRecordDecl
146static bool TagIsRecordType(dw_tag_t tag) {
147 switch (tag) {
148 case DW_TAG_class_type:
149 case DW_TAG_structure_type:
150 case DW_TAG_union_type:
151 return true;
152 default:
153 return false;
154 }
155}
156
157TypeSP DWARFASTParserClang::ParseTypeFromClangModule(const SymbolContext &sc,
158 const DWARFDIE &die,
159 Log *log) {
160 ModuleSP clang_module_sp = GetContainingClangModule(die);
161 if (!clang_module_sp)
162 return TypeSP();
163
164 // If this type comes from a Clang module, recursively look in the
165 // DWARF section of the .pcm file in the module cache. Clang
166 // generates DWO skeleton units as breadcrumbs to find them.
167 std::vector<lldb_private::CompilerContext> die_context = die.GetDeclContext();
168 TypeQuery query(die_context, TypeQueryOptions::e_module_search |
169 TypeQueryOptions::e_find_one);
170 TypeResults results;
171
172 // The type in the Clang module must have the same language as the current CU.
173 query.AddLanguage(language: SymbolFileDWARF::GetLanguageFamily(unit&: *die.GetCU()));
174 clang_module_sp->FindTypes(query, results);
175 TypeSP pcm_type_sp = results.GetTypeMap().FirstType();
176 if (!pcm_type_sp) {
177 // Since this type is defined in one of the Clang modules imported
178 // by this symbol file, search all of them. Instead of calling
179 // sym_file->FindTypes(), which would return this again, go straight
180 // to the imported modules.
181 auto &sym_file = die.GetCU()->GetSymbolFileDWARF();
182
183 // Well-formed clang modules never form cycles; guard against corrupted
184 // ones by inserting the current file.
185 results.AlreadySearched(sym_file: &sym_file);
186 sym_file.ForEachExternalModule(
187 *sc.comp_unit, results.GetSearchedSymbolFiles(), [&](Module &module) {
188 module.FindTypes(query, results);
189 pcm_type_sp = results.GetTypeMap().FirstType();
190 return (bool)pcm_type_sp;
191 });
192 }
193
194 if (!pcm_type_sp)
195 return TypeSP();
196
197 // We found a real definition for this type in the Clang module, so lets use
198 // it and cache the fact that we found a complete type for this die.
199 lldb_private::CompilerType pcm_type = pcm_type_sp->GetForwardCompilerType();
200 lldb_private::CompilerType type =
201 GetClangASTImporter().CopyType(dst&: m_ast, src_type: pcm_type);
202
203 if (!type)
204 return TypeSP();
205
206 // Under normal operation pcm_type is a shallow forward declaration
207 // that gets completed later. This is necessary to support cyclic
208 // data structures. If, however, pcm_type is already complete (for
209 // example, because it was loaded for a different target before),
210 // the definition needs to be imported right away, too.
211 // Type::ResolveClangType() effectively ignores the ResolveState
212 // inside type_sp and only looks at IsDefined(), so it never calls
213 // ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo(),
214 // which does extra work for Objective-C classes. This would result
215 // in only the forward declaration to be visible.
216 if (pcm_type.IsDefined())
217 GetClangASTImporter().RequireCompleteType(type: ClangUtil::GetQualType(ct: type));
218
219 SymbolFileDWARF *dwarf = die.GetDWARF();
220 auto type_sp = dwarf->MakeType(
221 uid: die.GetID(), name: pcm_type_sp->GetName(), byte_size: pcm_type_sp->GetByteSize(exe_scope: nullptr),
222 context: nullptr, LLDB_INVALID_UID, encoding_uid_type: Type::eEncodingInvalid,
223 decl: &pcm_type_sp->GetDeclaration(), compiler_qual_type: type, compiler_type_resolve_state: Type::ResolveState::Forward,
224 opaque_payload: TypePayloadClang(GetOwningClangModule(die)));
225 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
226 clang::TagDecl *tag_decl = TypeSystemClang::GetAsTagDecl(type);
227 if (tag_decl) {
228 LinkDeclContextToDIE(tag_decl, die);
229 } else {
230 clang::DeclContext *defn_decl_ctx = GetCachedClangDeclContextForDIE(die);
231 if (defn_decl_ctx)
232 LinkDeclContextToDIE(decl_ctx: defn_decl_ctx, die);
233 }
234
235 return type_sp;
236}
237
238static void ForcefullyCompleteType(CompilerType type) {
239 bool started = TypeSystemClang::StartTagDeclarationDefinition(type);
240 lldbassert(started && "Unable to start a class type definition.");
241 TypeSystemClang::CompleteTagDeclarationDefinition(type);
242 const clang::TagDecl *td = ClangUtil::GetAsTagDecl(type);
243 auto ts_sp = type.GetTypeSystem();
244 auto ts = ts_sp.dyn_cast_or_null<TypeSystemClang>();
245 if (ts)
246 ts->SetDeclIsForcefullyCompleted(td);
247}
248
249/// This function serves a similar purpose as RequireCompleteType above, but it
250/// avoids completing the type if it is not immediately necessary. It only
251/// ensures we _can_ complete the type later.
252static void PrepareContextToReceiveMembers(TypeSystemClang &ast,
253 ClangASTImporter &ast_importer,
254 clang::DeclContext *decl_ctx,
255 DWARFDIE die,
256 const char *type_name_cstr) {
257 auto *tag_decl_ctx = clang::dyn_cast<clang::TagDecl>(Val: decl_ctx);
258 if (!tag_decl_ctx)
259 return; // Non-tag context are always ready.
260
261 // We have already completed the type, or we have found its definition and are
262 // ready to complete it later (cf. ParseStructureLikeDIE).
263 if (tag_decl_ctx->isCompleteDefinition() || tag_decl_ctx->isBeingDefined())
264 return;
265
266 // We reach this point of the tag was present in the debug info as a
267 // declaration only. If it was imported from another AST context (in the
268 // gmodules case), we can complete the type by doing a full import.
269
270 // If this type was not imported from an external AST, there's nothing to do.
271 CompilerType type = ast.GetTypeForDecl(decl: tag_decl_ctx);
272 if (type && ast_importer.CanImport(type)) {
273 auto qual_type = ClangUtil::GetQualType(ct: type);
274 if (ast_importer.RequireCompleteType(type: qual_type))
275 return;
276 die.GetDWARF()->GetObjectFile()->GetModule()->ReportError(
277 format: "Unable to complete the Decl context for DIE {0} at offset "
278 "{1:x16}.\nPlease file a bug report.",
279 args: type_name_cstr ? type_name_cstr : "", args: die.GetOffset());
280 }
281
282 // We don't have a type definition and/or the import failed. We must
283 // forcefully complete the type to avoid crashes.
284 ForcefullyCompleteType(type);
285}
286
287ParsedDWARFTypeAttributes::ParsedDWARFTypeAttributes(const DWARFDIE &die) {
288 DWARFAttributes attributes = die.GetAttributes();
289 for (size_t i = 0; i < attributes.Size(); ++i) {
290 dw_attr_t attr = attributes.AttributeAtIndex(i);
291 DWARFFormValue form_value;
292 if (!attributes.ExtractFormValueAtIndex(i, form_value))
293 continue;
294 switch (attr) {
295 default:
296 break;
297 case DW_AT_abstract_origin:
298 abstract_origin = form_value;
299 break;
300
301 case DW_AT_accessibility:
302 accessibility =
303 DWARFASTParser::GetAccessTypeFromDWARF(dwarf_accessibility: form_value.Unsigned());
304 break;
305
306 case DW_AT_artificial:
307 is_artificial = form_value.Boolean();
308 break;
309
310 case DW_AT_bit_stride:
311 bit_stride = form_value.Unsigned();
312 break;
313
314 case DW_AT_byte_size:
315 byte_size = form_value.Unsigned();
316 break;
317
318 case DW_AT_alignment:
319 alignment = form_value.Unsigned();
320 break;
321
322 case DW_AT_byte_stride:
323 byte_stride = form_value.Unsigned();
324 break;
325
326 case DW_AT_calling_convention:
327 calling_convention = form_value.Unsigned();
328 break;
329
330 case DW_AT_containing_type:
331 containing_type = form_value;
332 break;
333
334 case DW_AT_decl_file:
335 // die.GetCU() can differ if DW_AT_specification uses DW_FORM_ref_addr.
336 decl.SetFile(
337 attributes.CompileUnitAtIndex(i)->GetFile(file_idx: form_value.Unsigned()));
338 break;
339 case DW_AT_decl_line:
340 decl.SetLine(form_value.Unsigned());
341 break;
342 case DW_AT_decl_column:
343 decl.SetColumn(form_value.Unsigned());
344 break;
345
346 case DW_AT_declaration:
347 is_forward_declaration = form_value.Boolean();
348 break;
349
350 case DW_AT_encoding:
351 encoding = form_value.Unsigned();
352 break;
353
354 case DW_AT_enum_class:
355 is_scoped_enum = form_value.Boolean();
356 break;
357
358 case DW_AT_explicit:
359 is_explicit = form_value.Boolean();
360 break;
361
362 case DW_AT_external:
363 if (form_value.Unsigned())
364 storage = clang::SC_Extern;
365 break;
366
367 case DW_AT_inline:
368 is_inline = form_value.Boolean();
369 break;
370
371 case DW_AT_linkage_name:
372 case DW_AT_MIPS_linkage_name:
373 mangled_name = form_value.AsCString();
374 break;
375
376 case DW_AT_name:
377 name.SetCString(form_value.AsCString());
378 break;
379
380 case DW_AT_object_pointer:
381 object_pointer = form_value.Reference();
382 break;
383
384 case DW_AT_signature:
385 signature = form_value;
386 break;
387
388 case DW_AT_specification:
389 specification = form_value;
390 break;
391
392 case DW_AT_type:
393 type = form_value;
394 break;
395
396 case DW_AT_virtuality:
397 is_virtual = form_value.Boolean();
398 break;
399
400 case DW_AT_APPLE_objc_complete_type:
401 is_complete_objc_class = form_value.Signed();
402 break;
403
404 case DW_AT_APPLE_objc_direct:
405 is_objc_direct_call = true;
406 break;
407
408 case DW_AT_APPLE_runtime_class:
409 class_language = (LanguageType)form_value.Signed();
410 break;
411
412 case DW_AT_GNU_vector:
413 is_vector = form_value.Boolean();
414 break;
415 case DW_AT_export_symbols:
416 exports_symbols = form_value.Boolean();
417 break;
418 case DW_AT_rvalue_reference:
419 ref_qual = clang::RQ_RValue;
420 break;
421 case DW_AT_reference:
422 ref_qual = clang::RQ_LValue;
423 break;
424 }
425 }
426}
427
428static std::string GetUnitName(const DWARFDIE &die) {
429 if (DWARFUnit *unit = die.GetCU())
430 return unit->GetAbsolutePath().GetPath();
431 return "<missing DWARF unit path>";
432}
433
434TypeSP DWARFASTParserClang::ParseTypeFromDWARF(const SymbolContext &sc,
435 const DWARFDIE &die,
436 bool *type_is_new_ptr) {
437 if (type_is_new_ptr)
438 *type_is_new_ptr = false;
439
440 if (!die)
441 return nullptr;
442
443 Log *log = GetLog(mask: DWARFLog::TypeCompletion | DWARFLog::Lookups);
444
445 SymbolFileDWARF *dwarf = die.GetDWARF();
446 if (log) {
447 DWARFDIE context_die;
448 clang::DeclContext *context =
449 GetClangDeclContextContainingDIE(die, decl_ctx_die: &context_die);
450
451 dwarf->GetObjectFile()->GetModule()->LogMessage(
452 log,
453 format: "DWARFASTParserClang::ParseTypeFromDWARF "
454 "(die = {0:x16}, decl_ctx = {1:p} (die "
455 "{2:x16})) {3} name = '{4}')",
456 args: die.GetOffset(), args: static_cast<void *>(context), args: context_die.GetOffset(),
457 args: die.GetTagAsCString(), args: die.GetName());
458 }
459
460 Type *type_ptr = dwarf->GetDIEToType().lookup(Val: die.GetDIE());
461 if (type_ptr == DIE_IS_BEING_PARSED)
462 return nullptr;
463 if (type_ptr)
464 return type_ptr->shared_from_this();
465 // Set a bit that lets us know that we are currently parsing this
466 dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
467
468 ParsedDWARFTypeAttributes attrs(die);
469
470 if (DWARFDIE signature_die = attrs.signature.Reference()) {
471 if (TypeSP type_sp =
472 ParseTypeFromDWARF(sc, die: signature_die, type_is_new_ptr)) {
473 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
474 if (clang::DeclContext *decl_ctx =
475 GetCachedClangDeclContextForDIE(die: signature_die))
476 LinkDeclContextToDIE(decl_ctx, die);
477 return type_sp;
478 }
479 return nullptr;
480 }
481
482 if (type_is_new_ptr)
483 *type_is_new_ptr = true;
484
485 const dw_tag_t tag = die.Tag();
486
487 TypeSP type_sp;
488
489 switch (tag) {
490 case DW_TAG_typedef:
491 case DW_TAG_base_type:
492 case DW_TAG_pointer_type:
493 case DW_TAG_reference_type:
494 case DW_TAG_rvalue_reference_type:
495 case DW_TAG_const_type:
496 case DW_TAG_restrict_type:
497 case DW_TAG_volatile_type:
498 case DW_TAG_atomic_type:
499 case DW_TAG_unspecified_type: {
500 type_sp = ParseTypeModifier(sc, die, attrs);
501 break;
502 }
503
504 case DW_TAG_structure_type:
505 case DW_TAG_union_type:
506 case DW_TAG_class_type: {
507 type_sp = ParseStructureLikeDIE(sc, die, attrs);
508 break;
509 }
510
511 case DW_TAG_enumeration_type: {
512 type_sp = ParseEnum(sc, die, attrs);
513 break;
514 }
515
516 case DW_TAG_inlined_subroutine:
517 case DW_TAG_subprogram:
518 case DW_TAG_subroutine_type: {
519 type_sp = ParseSubroutine(die, attrs);
520 break;
521 }
522 case DW_TAG_array_type: {
523 type_sp = ParseArrayType(die, attrs);
524 break;
525 }
526 case DW_TAG_ptr_to_member_type: {
527 type_sp = ParsePointerToMemberType(die, attrs);
528 break;
529 }
530 default:
531 dwarf->GetObjectFile()->GetModule()->ReportError(
532 format: "[{0:x16}]: unhandled type tag {1:x4} ({2}), "
533 "please file a bug and "
534 "attach the file at the start of this error message",
535 args: die.GetOffset(), args: tag, args: DW_TAG_value_to_name(val: tag));
536 break;
537 }
538
539 // TODO: We should consider making the switch above exhaustive to simplify
540 // control flow in ParseTypeFromDWARF. Then, we could simply replace this
541 // return statement with a call to llvm_unreachable.
542 return UpdateSymbolContextScopeForType(sc, die, type_sp);
543}
544
545static std::optional<uint32_t>
546ExtractDataMemberLocation(DWARFDIE const &die, DWARFFormValue const &form_value,
547 ModuleSP module_sp) {
548 // With DWARF 3 and later, if the value is an integer constant,
549 // this form value is the offset in bytes from the beginning of
550 // the containing entity.
551 if (!form_value.BlockData())
552 return form_value.Unsigned();
553
554 Value initialValue(0);
555 Value memberOffset(0);
556 const DWARFDataExtractor &debug_info_data = die.GetData();
557 uint32_t block_length = form_value.Unsigned();
558 uint32_t block_offset =
559 form_value.BlockData() - debug_info_data.GetDataStart();
560 if (!DWARFExpression::Evaluate(
561 exe_ctx: nullptr, // ExecutionContext *
562 reg_ctx: nullptr, // RegisterContext *
563 module_sp, opcodes: DataExtractor(debug_info_data, block_offset, block_length),
564 dwarf_cu: die.GetCU(), reg_set: eRegisterKindDWARF, initial_value_ptr: &initialValue, object_address_ptr: nullptr, result&: memberOffset,
565 error_ptr: nullptr)) {
566 return {};
567 }
568
569 return memberOffset.ResolveValue(exe_ctx: nullptr).UInt();
570}
571
572lldb::TypeSP
573DWARFASTParserClang::ParseTypeModifier(const SymbolContext &sc,
574 const DWARFDIE &die,
575 ParsedDWARFTypeAttributes &attrs) {
576 Log *log = GetLog(mask: DWARFLog::TypeCompletion | DWARFLog::Lookups);
577 SymbolFileDWARF *dwarf = die.GetDWARF();
578 const dw_tag_t tag = die.Tag();
579 LanguageType cu_language = SymbolFileDWARF::GetLanguage(unit&: *die.GetCU());
580 Type::ResolveState resolve_state = Type::ResolveState::Unresolved;
581 Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
582 TypeSP type_sp;
583 CompilerType clang_type;
584
585 if (tag == DW_TAG_typedef) {
586 // DeclContext will be populated when the clang type is materialized in
587 // Type::ResolveCompilerType.
588 PrepareContextToReceiveMembers(
589 ast&: m_ast, ast_importer&: GetClangASTImporter(),
590 decl_ctx: GetClangDeclContextContainingDIE(die, decl_ctx_die: nullptr), die,
591 type_name_cstr: attrs.name.GetCString());
592
593 if (attrs.type.IsValid()) {
594 // Try to parse a typedef from the (DWARF embedded in the) Clang
595 // module file first as modules can contain typedef'ed
596 // structures that have no names like:
597 //
598 // typedef struct { int a; } Foo;
599 //
600 // In this case we will have a structure with no name and a
601 // typedef named "Foo" that points to this unnamed
602 // structure. The name in the typedef is the only identifier for
603 // the struct, so always try to get typedefs from Clang modules
604 // if possible.
605 //
606 // The type_sp returned will be empty if the typedef doesn't
607 // exist in a module file, so it is cheap to call this function
608 // just to check.
609 //
610 // If we don't do this we end up creating a TypeSP that says
611 // this is a typedef to type 0x123 (the DW_AT_type value would
612 // be 0x123 in the DW_TAG_typedef), and this is the unnamed
613 // structure type. We will have a hard time tracking down an
614 // unnammed structure type in the module debug info, so we make
615 // sure we don't get into this situation by always resolving
616 // typedefs from the module.
617 const DWARFDIE encoding_die = attrs.type.Reference();
618
619 // First make sure that the die that this is typedef'ed to _is_
620 // just a declaration (DW_AT_declaration == 1), not a full
621 // definition since template types can't be represented in
622 // modules since only concrete instances of templates are ever
623 // emitted and modules won't contain those
624 if (encoding_die &&
625 encoding_die.GetAttributeValueAsUnsigned(attr: DW_AT_declaration, fail_value: 0) == 1) {
626 type_sp = ParseTypeFromClangModule(sc, die, log);
627 if (type_sp)
628 return type_sp;
629 }
630 }
631 }
632
633 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n", die.GetID(),
634 DW_TAG_value_to_name(tag), type_name_cstr,
635 encoding_uid.Reference());
636
637 switch (tag) {
638 default:
639 break;
640
641 case DW_TAG_unspecified_type:
642 if (attrs.name == "nullptr_t" || attrs.name == "decltype(nullptr)") {
643 resolve_state = Type::ResolveState::Full;
644 clang_type = m_ast.GetBasicType(type: eBasicTypeNullPtr);
645 break;
646 }
647 // Fall through to base type below in case we can handle the type
648 // there...
649 [[fallthrough]];
650
651 case DW_TAG_base_type:
652 resolve_state = Type::ResolveState::Full;
653 clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
654 type_name: attrs.name.GetStringRef(), dw_ate: attrs.encoding,
655 bit_size: attrs.byte_size.value_or(u: 0) * 8);
656 break;
657
658 case DW_TAG_pointer_type:
659 encoding_data_type = Type::eEncodingIsPointerUID;
660 break;
661 case DW_TAG_reference_type:
662 encoding_data_type = Type::eEncodingIsLValueReferenceUID;
663 break;
664 case DW_TAG_rvalue_reference_type:
665 encoding_data_type = Type::eEncodingIsRValueReferenceUID;
666 break;
667 case DW_TAG_typedef:
668 encoding_data_type = Type::eEncodingIsTypedefUID;
669 break;
670 case DW_TAG_const_type:
671 encoding_data_type = Type::eEncodingIsConstUID;
672 break;
673 case DW_TAG_restrict_type:
674 encoding_data_type = Type::eEncodingIsRestrictUID;
675 break;
676 case DW_TAG_volatile_type:
677 encoding_data_type = Type::eEncodingIsVolatileUID;
678 break;
679 case DW_TAG_atomic_type:
680 encoding_data_type = Type::eEncodingIsAtomicUID;
681 break;
682 }
683
684 if (!clang_type && (encoding_data_type == Type::eEncodingIsPointerUID ||
685 encoding_data_type == Type::eEncodingIsTypedefUID)) {
686 if (tag == DW_TAG_pointer_type) {
687 DWARFDIE target_die = die.GetReferencedDIE(attr: DW_AT_type);
688
689 if (target_die.GetAttributeValueAsUnsigned(attr: DW_AT_APPLE_block, fail_value: 0)) {
690 // Blocks have a __FuncPtr inside them which is a pointer to a
691 // function of the proper type.
692
693 for (DWARFDIE child_die : target_die.children()) {
694 if (!strcmp(s1: child_die.GetAttributeValueAsString(attr: DW_AT_name, fail_value: ""),
695 s2: "__FuncPtr")) {
696 DWARFDIE function_pointer_type =
697 child_die.GetReferencedDIE(attr: DW_AT_type);
698
699 if (function_pointer_type) {
700 DWARFDIE function_type =
701 function_pointer_type.GetReferencedDIE(attr: DW_AT_type);
702
703 bool function_type_is_new_pointer;
704 TypeSP lldb_function_type_sp = ParseTypeFromDWARF(
705 sc, die: function_type, type_is_new_ptr: &function_type_is_new_pointer);
706
707 if (lldb_function_type_sp) {
708 clang_type = m_ast.CreateBlockPointerType(
709 function_type: lldb_function_type_sp->GetForwardCompilerType());
710 encoding_data_type = Type::eEncodingIsUID;
711 attrs.type.Clear();
712 resolve_state = Type::ResolveState::Full;
713 }
714 }
715
716 break;
717 }
718 }
719 }
720 }
721
722 if (cu_language == eLanguageTypeObjC ||
723 cu_language == eLanguageTypeObjC_plus_plus) {
724 if (attrs.name) {
725 if (attrs.name == "id") {
726 if (log)
727 dwarf->GetObjectFile()->GetModule()->LogMessage(
728 log,
729 format: "SymbolFileDWARF::ParseType (die = {0:x16}) {1} '{2}' "
730 "is Objective-C 'id' built-in type.",
731 args: die.GetOffset(), args: die.GetTagAsCString(), args: die.GetName());
732 clang_type = m_ast.GetBasicType(type: eBasicTypeObjCID);
733 encoding_data_type = Type::eEncodingIsUID;
734 attrs.type.Clear();
735 resolve_state = Type::ResolveState::Full;
736 } else if (attrs.name == "Class") {
737 if (log)
738 dwarf->GetObjectFile()->GetModule()->LogMessage(
739 log,
740 format: "SymbolFileDWARF::ParseType (die = {0:x16}) {1} '{2}' "
741 "is Objective-C 'Class' built-in type.",
742 args: die.GetOffset(), args: die.GetTagAsCString(), args: die.GetName());
743 clang_type = m_ast.GetBasicType(type: eBasicTypeObjCClass);
744 encoding_data_type = Type::eEncodingIsUID;
745 attrs.type.Clear();
746 resolve_state = Type::ResolveState::Full;
747 } else if (attrs.name == "SEL") {
748 if (log)
749 dwarf->GetObjectFile()->GetModule()->LogMessage(
750 log,
751 format: "SymbolFileDWARF::ParseType (die = {0:x16}) {1} '{2}' "
752 "is Objective-C 'selector' built-in type.",
753 args: die.GetOffset(), args: die.GetTagAsCString(), args: die.GetName());
754 clang_type = m_ast.GetBasicType(type: eBasicTypeObjCSel);
755 encoding_data_type = Type::eEncodingIsUID;
756 attrs.type.Clear();
757 resolve_state = Type::ResolveState::Full;
758 }
759 } else if (encoding_data_type == Type::eEncodingIsPointerUID &&
760 attrs.type.IsValid()) {
761 // Clang sometimes erroneously emits id as objc_object*. In that
762 // case we fix up the type to "id".
763
764 const DWARFDIE encoding_die = attrs.type.Reference();
765
766 if (encoding_die && encoding_die.Tag() == DW_TAG_structure_type) {
767 llvm::StringRef struct_name = encoding_die.GetName();
768 if (struct_name == "objc_object") {
769 if (log)
770 dwarf->GetObjectFile()->GetModule()->LogMessage(
771 log,
772 format: "SymbolFileDWARF::ParseType (die = {0:x16}) {1} "
773 "'{2}' is 'objc_object*', which we overrode to "
774 "'id'.",
775 args: die.GetOffset(), args: die.GetTagAsCString(), args: die.GetName());
776 clang_type = m_ast.GetBasicType(type: eBasicTypeObjCID);
777 encoding_data_type = Type::eEncodingIsUID;
778 attrs.type.Clear();
779 resolve_state = Type::ResolveState::Full;
780 }
781 }
782 }
783 }
784 }
785
786 type_sp = dwarf->MakeType(uid: die.GetID(), name: attrs.name, byte_size: attrs.byte_size, context: nullptr,
787 encoding_uid: attrs.type.Reference().GetID(), encoding_uid_type: encoding_data_type,
788 decl: &attrs.decl, compiler_qual_type: clang_type, compiler_type_resolve_state: resolve_state,
789 opaque_payload: TypePayloadClang(GetOwningClangModule(die)));
790
791 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
792 return type_sp;
793}
794
795ConstString
796DWARFASTParserClang::GetDIEClassTemplateParams(const DWARFDIE &die) {
797 if (llvm::StringRef(die.GetName()).contains(Other: "<"))
798 return ConstString();
799
800 TypeSystemClang::TemplateParameterInfos template_param_infos;
801 if (ParseTemplateParameterInfos(parent_die: die, template_param_infos)) {
802 return ConstString(m_ast.PrintTemplateParams(template_param_infos));
803 }
804 return ConstString();
805}
806
807TypeSP DWARFASTParserClang::ParseEnum(const SymbolContext &sc,
808 const DWARFDIE &die,
809 ParsedDWARFTypeAttributes &attrs) {
810 Log *log = GetLog(mask: DWARFLog::TypeCompletion | DWARFLog::Lookups);
811 SymbolFileDWARF *dwarf = die.GetDWARF();
812 const dw_tag_t tag = die.Tag();
813 TypeSP type_sp;
814
815 if (attrs.is_forward_declaration) {
816 type_sp = ParseTypeFromClangModule(sc, die, log);
817 if (type_sp)
818 return type_sp;
819
820 type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die);
821
822 if (!type_sp) {
823 SymbolFileDWARFDebugMap *debug_map_symfile = dwarf->GetDebugMapSymfile();
824 if (debug_map_symfile) {
825 // We weren't able to find a full declaration in this DWARF,
826 // see if we have a declaration anywhere else...
827 type_sp = debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(die);
828 }
829 }
830
831 if (type_sp) {
832 if (log) {
833 dwarf->GetObjectFile()->GetModule()->LogMessage(
834 log,
835 format: "SymbolFileDWARF({0:p}) - {1:x16}}: {2} type \"{3}\" is a "
836 "forward declaration, complete type is {4:x8}",
837 args: static_cast<void *>(this), args: die.GetOffset(),
838 args: DW_TAG_value_to_name(val: tag), args: attrs.name.GetCString(),
839 args: type_sp->GetID());
840 }
841
842 // We found a real definition for this type elsewhere so lets use
843 // it and cache the fact that we found a complete type for this
844 // die
845 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
846 clang::DeclContext *defn_decl_ctx =
847 GetCachedClangDeclContextForDIE(die: dwarf->GetDIE(uid: type_sp->GetID()));
848 if (defn_decl_ctx)
849 LinkDeclContextToDIE(decl_ctx: defn_decl_ctx, die);
850 return type_sp;
851 }
852 }
853 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
854 DW_TAG_value_to_name(tag), type_name_cstr);
855
856 CompilerType enumerator_clang_type;
857 if (attrs.type.IsValid()) {
858 Type *enumerator_type = dwarf->ResolveTypeUID(die: attrs.type.Reference(), assert_not_being_parsed: true);
859 if (enumerator_type)
860 enumerator_clang_type = enumerator_type->GetFullCompilerType();
861 }
862
863 if (!enumerator_clang_type) {
864 if (attrs.byte_size) {
865 enumerator_clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
866 type_name: "", dw_ate: DW_ATE_signed, bit_size: *attrs.byte_size * 8);
867 } else {
868 enumerator_clang_type = m_ast.GetBasicType(type: eBasicTypeInt);
869 }
870 }
871
872 CompilerType clang_type = m_ast.CreateEnumerationType(
873 name: attrs.name.GetStringRef(), decl_ctx: GetClangDeclContextContainingDIE(die, decl_ctx_die: nullptr),
874 owning_module: GetOwningClangModule(die), decl: attrs.decl, integer_qual_type: enumerator_clang_type,
875 is_scoped: attrs.is_scoped_enum);
876
877 LinkDeclContextToDIE(decl_ctx: TypeSystemClang::GetDeclContextForType(type: clang_type), die);
878
879 type_sp =
880 dwarf->MakeType(uid: die.GetID(), name: attrs.name, byte_size: attrs.byte_size, context: nullptr,
881 encoding_uid: attrs.type.Reference().GetID(), encoding_uid_type: Type::eEncodingIsUID,
882 decl: &attrs.decl, compiler_qual_type: clang_type, compiler_type_resolve_state: Type::ResolveState::Forward,
883 opaque_payload: TypePayloadClang(GetOwningClangModule(die)));
884
885 if (TypeSystemClang::StartTagDeclarationDefinition(type: clang_type)) {
886 if (die.HasChildren()) {
887 bool is_signed = false;
888 enumerator_clang_type.IsIntegerType(is_signed);
889 ParseChildEnumerators(compiler_type&: clang_type, is_signed,
890 enumerator_byte_size: type_sp->GetByteSize(exe_scope: nullptr).value_or(u: 0), parent_die: die);
891 }
892 TypeSystemClang::CompleteTagDeclarationDefinition(type: clang_type);
893 } else {
894 dwarf->GetObjectFile()->GetModule()->ReportError(
895 format: "DWARF DIE at {0:x16} named \"{1}\" was not able to start its "
896 "definition.\nPlease file a bug and attach the file at the "
897 "start of this error message",
898 args: die.GetOffset(), args: attrs.name.GetCString());
899 }
900 return type_sp;
901}
902
903static clang::CallingConv
904ConvertDWARFCallingConventionToClang(const ParsedDWARFTypeAttributes &attrs) {
905 switch (attrs.calling_convention) {
906 case llvm::dwarf::DW_CC_normal:
907 return clang::CC_C;
908 case llvm::dwarf::DW_CC_BORLAND_stdcall:
909 return clang::CC_X86StdCall;
910 case llvm::dwarf::DW_CC_BORLAND_msfastcall:
911 return clang::CC_X86FastCall;
912 case llvm::dwarf::DW_CC_LLVM_vectorcall:
913 return clang::CC_X86VectorCall;
914 case llvm::dwarf::DW_CC_BORLAND_pascal:
915 return clang::CC_X86Pascal;
916 case llvm::dwarf::DW_CC_LLVM_Win64:
917 return clang::CC_Win64;
918 case llvm::dwarf::DW_CC_LLVM_X86_64SysV:
919 return clang::CC_X86_64SysV;
920 case llvm::dwarf::DW_CC_LLVM_X86RegCall:
921 return clang::CC_X86RegCall;
922 default:
923 break;
924 }
925
926 Log *log = GetLog(mask: DWARFLog::TypeCompletion | DWARFLog::Lookups);
927 LLDB_LOG(log, "Unsupported DW_AT_calling_convention value: {0}",
928 attrs.calling_convention);
929 // Use the default calling convention as a fallback.
930 return clang::CC_C;
931}
932
933TypeSP
934DWARFASTParserClang::ParseSubroutine(const DWARFDIE &die,
935 const ParsedDWARFTypeAttributes &attrs) {
936 Log *log = GetLog(mask: DWARFLog::TypeCompletion | DWARFLog::Lookups);
937
938 SymbolFileDWARF *dwarf = die.GetDWARF();
939 const dw_tag_t tag = die.Tag();
940
941 bool is_variadic = false;
942 bool is_static = false;
943 bool has_template_params = false;
944
945 unsigned type_quals = 0;
946
947 std::string object_pointer_name;
948 if (attrs.object_pointer) {
949 const char *object_pointer_name_cstr = attrs.object_pointer.GetName();
950 if (object_pointer_name_cstr)
951 object_pointer_name = object_pointer_name_cstr;
952 }
953
954 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
955 DW_TAG_value_to_name(tag), type_name_cstr);
956
957 CompilerType return_clang_type;
958 Type *func_type = nullptr;
959
960 if (attrs.type.IsValid())
961 func_type = dwarf->ResolveTypeUID(die: attrs.type.Reference(), assert_not_being_parsed: true);
962
963 if (func_type)
964 return_clang_type = func_type->GetForwardCompilerType();
965 else
966 return_clang_type = m_ast.GetBasicType(type: eBasicTypeVoid);
967
968 std::vector<CompilerType> function_param_types;
969 std::vector<clang::ParmVarDecl *> function_param_decls;
970
971 // Parse the function children for the parameters
972
973 DWARFDIE decl_ctx_die;
974 clang::DeclContext *containing_decl_ctx =
975 GetClangDeclContextContainingDIE(die, decl_ctx_die: &decl_ctx_die);
976 const clang::Decl::Kind containing_decl_kind =
977 containing_decl_ctx->getDeclKind();
978
979 bool is_cxx_method = DeclKindIsCXXClass(decl_kind: containing_decl_kind);
980 // Start off static. This will be set to false in
981 // ParseChildParameters(...) if we find a "this" parameters as the
982 // first parameter
983 if (is_cxx_method) {
984 is_static = true;
985 }
986
987 if (die.HasChildren()) {
988 bool skip_artificial = true;
989 ParseChildParameters(containing_decl_ctx, parent_die: die, skip_artificial, is_static,
990 is_variadic, has_template_params,
991 function_args&: function_param_types, function_param_decls,
992 type_quals);
993 }
994
995 bool ignore_containing_context = false;
996 // Check for templatized class member functions. If we had any
997 // DW_TAG_template_type_parameter or DW_TAG_template_value_parameter
998 // the DW_TAG_subprogram DIE, then we can't let this become a method in
999 // a class. Why? Because templatized functions are only emitted if one
1000 // of the templatized methods is used in the current compile unit and
1001 // we will end up with classes that may or may not include these member
1002 // functions and this means one class won't match another class
1003 // definition and it affects our ability to use a class in the clang
1004 // expression parser. So for the greater good, we currently must not
1005 // allow any template member functions in a class definition.
1006 if (is_cxx_method && has_template_params) {
1007 ignore_containing_context = true;
1008 is_cxx_method = false;
1009 }
1010
1011 clang::CallingConv calling_convention =
1012 ConvertDWARFCallingConventionToClang(attrs);
1013
1014 // clang_type will get the function prototype clang type after this
1015 // call
1016 CompilerType clang_type =
1017 m_ast.CreateFunctionType(result_type: return_clang_type, args: function_param_types.data(),
1018 num_args: function_param_types.size(), is_variadic,
1019 type_quals, cc: calling_convention, ref_qual: attrs.ref_qual);
1020
1021 if (attrs.name) {
1022 bool type_handled = false;
1023 if (tag == DW_TAG_subprogram || tag == DW_TAG_inlined_subroutine) {
1024 std::optional<const ObjCLanguage::MethodName> objc_method =
1025 ObjCLanguage::MethodName::Create(name: attrs.name.GetStringRef(), strict: true);
1026 if (objc_method) {
1027 CompilerType class_opaque_type;
1028 ConstString class_name(objc_method->GetClassName());
1029 if (class_name) {
1030 TypeSP complete_objc_class_type_sp(
1031 dwarf->FindCompleteObjCDefinitionTypeForDIE(die: DWARFDIE(),
1032 type_name: class_name, must_be_implementation: false));
1033
1034 if (complete_objc_class_type_sp) {
1035 CompilerType type_clang_forward_type =
1036 complete_objc_class_type_sp->GetForwardCompilerType();
1037 if (TypeSystemClang::IsObjCObjectOrInterfaceType(
1038 type: type_clang_forward_type))
1039 class_opaque_type = type_clang_forward_type;
1040 }
1041 }
1042
1043 if (class_opaque_type) {
1044 clang::ObjCMethodDecl *objc_method_decl =
1045 m_ast.AddMethodToObjCObjectType(
1046 type: class_opaque_type, name: attrs.name.GetCString(), method_compiler_type: clang_type,
1047 is_artificial: attrs.is_artificial, is_variadic, is_objc_direct_call: attrs.is_objc_direct_call);
1048 type_handled = objc_method_decl != nullptr;
1049 if (type_handled) {
1050 LinkDeclContextToDIE(objc_method_decl, die);
1051 m_ast.SetMetadataAsUserID(objc_method_decl, die.GetID());
1052 } else {
1053 dwarf->GetObjectFile()->GetModule()->ReportError(
1054 format: "[{0:x16}]: invalid Objective-C method {1:x4} ({2}), "
1055 "please file a bug and attach the file at the start of "
1056 "this error message",
1057 args: die.GetOffset(), args: tag, args: DW_TAG_value_to_name(val: tag));
1058 }
1059 }
1060 } else if (is_cxx_method) {
1061 // Look at the parent of this DIE and see if it is a class or
1062 // struct and see if this is actually a C++ method
1063 Type *class_type = dwarf->ResolveType(die: decl_ctx_die);
1064 if (class_type) {
1065 if (class_type->GetID() != decl_ctx_die.GetID() ||
1066 IsClangModuleFwdDecl(Die: decl_ctx_die)) {
1067
1068 // We uniqued the parent class of this function to another
1069 // class so we now need to associate all dies under
1070 // "decl_ctx_die" to DIEs in the DIE for "class_type"...
1071 DWARFDIE class_type_die = dwarf->GetDIE(uid: class_type->GetID());
1072
1073 if (class_type_die) {
1074 std::vector<DWARFDIE> failures;
1075
1076 CopyUniqueClassMethodTypes(src_class_die: decl_ctx_die, dst_class_die: class_type_die,
1077 class_type, failures);
1078
1079 // FIXME do something with these failures that's
1080 // smarter than just dropping them on the ground.
1081 // Unfortunately classes don't like having stuff added
1082 // to them after their definitions are complete...
1083
1084 Type *type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1085 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1086 return type_ptr->shared_from_this();
1087 }
1088 }
1089 }
1090
1091 if (attrs.specification.IsValid()) {
1092 // We have a specification which we are going to base our
1093 // function prototype off of, so we need this type to be
1094 // completed so that the m_die_to_decl_ctx for the method in
1095 // the specification has a valid clang decl context.
1096 class_type->GetForwardCompilerType();
1097 // If we have a specification, then the function type should
1098 // have been made with the specification and not with this
1099 // die.
1100 DWARFDIE spec_die = attrs.specification.Reference();
1101 clang::DeclContext *spec_clang_decl_ctx =
1102 GetClangDeclContextForDIE(die: spec_die);
1103 if (spec_clang_decl_ctx) {
1104 LinkDeclContextToDIE(decl_ctx: spec_clang_decl_ctx, die);
1105 } else {
1106 dwarf->GetObjectFile()->GetModule()->ReportWarning(
1107 format: "{0:x8}: DW_AT_specification({1:x16}"
1108 ") has no decl\n",
1109 args: die.GetID(), args: spec_die.GetOffset());
1110 }
1111 type_handled = true;
1112 } else if (attrs.abstract_origin.IsValid()) {
1113 // We have a specification which we are going to base our
1114 // function prototype off of, so we need this type to be
1115 // completed so that the m_die_to_decl_ctx for the method in
1116 // the abstract origin has a valid clang decl context.
1117 class_type->GetForwardCompilerType();
1118
1119 DWARFDIE abs_die = attrs.abstract_origin.Reference();
1120 clang::DeclContext *abs_clang_decl_ctx =
1121 GetClangDeclContextForDIE(die: abs_die);
1122 if (abs_clang_decl_ctx) {
1123 LinkDeclContextToDIE(decl_ctx: abs_clang_decl_ctx, die);
1124 } else {
1125 dwarf->GetObjectFile()->GetModule()->ReportWarning(
1126 format: "{0:x8}: DW_AT_abstract_origin({1:x16}"
1127 ") has no decl\n",
1128 args: die.GetID(), args: abs_die.GetOffset());
1129 }
1130 type_handled = true;
1131 } else {
1132 CompilerType class_opaque_type =
1133 class_type->GetForwardCompilerType();
1134 if (TypeSystemClang::IsCXXClassType(type: class_opaque_type)) {
1135 if (class_opaque_type.IsBeingDefined()) {
1136 if (!is_static && !die.HasChildren()) {
1137 // We have a C++ member function with no children (this
1138 // pointer!) and clang will get mad if we try and make
1139 // a function that isn't well formed in the DWARF, so
1140 // we will just skip it...
1141 type_handled = true;
1142 } else {
1143 llvm::PrettyStackTraceFormat stack_trace(
1144 "SymbolFileDWARF::ParseType() is adding a method "
1145 "%s to class %s in DIE 0x%8.8" PRIx64 " from %s",
1146 attrs.name.GetCString(),
1147 class_type->GetName().GetCString(), die.GetID(),
1148 dwarf->GetObjectFile()->GetFileSpec().GetPath().c_str());
1149
1150 const bool is_attr_used = false;
1151 // Neither GCC 4.2 nor clang++ currently set a valid
1152 // accessibility in the DWARF for C++ methods...
1153 // Default to public for now...
1154 const auto accessibility = attrs.accessibility == eAccessNone
1155 ? eAccessPublic
1156 : attrs.accessibility;
1157
1158 clang::CXXMethodDecl *cxx_method_decl =
1159 m_ast.AddMethodToCXXRecordType(
1160 type: class_opaque_type.GetOpaqueQualType(),
1161 name: attrs.name.GetCString(), mangled_name: attrs.mangled_name,
1162 method_type: clang_type, access: accessibility, is_virtual: attrs.is_virtual,
1163 is_static, is_inline: attrs.is_inline, is_explicit: attrs.is_explicit,
1164 is_attr_used, is_artificial: attrs.is_artificial);
1165
1166 type_handled = cxx_method_decl != nullptr;
1167 // Artificial methods are always handled even when we
1168 // don't create a new declaration for them.
1169 type_handled |= attrs.is_artificial;
1170
1171 if (cxx_method_decl) {
1172 LinkDeclContextToDIE(cxx_method_decl, die);
1173
1174 ClangASTMetadata metadata;
1175 metadata.SetUserID(die.GetID());
1176
1177 if (!object_pointer_name.empty()) {
1178 metadata.SetObjectPtrName(object_pointer_name.c_str());
1179 LLDB_LOGF(log,
1180 "Setting object pointer name: %s on method "
1181 "object %p.\n",
1182 object_pointer_name.c_str(),
1183 static_cast<void *>(cxx_method_decl));
1184 }
1185 m_ast.SetMetadata(cxx_method_decl, metadata);
1186 } else {
1187 ignore_containing_context = true;
1188 }
1189 }
1190 } else {
1191 // We were asked to parse the type for a method in a
1192 // class, yet the class hasn't been asked to complete
1193 // itself through the clang::ExternalASTSource protocol,
1194 // so we need to just have the class complete itself and
1195 // do things the right way, then our
1196 // DIE should then have an entry in the
1197 // dwarf->GetDIEToType() map. First
1198 // we need to modify the dwarf->GetDIEToType() so it
1199 // doesn't think we are trying to parse this DIE
1200 // anymore...
1201 dwarf->GetDIEToType()[die.GetDIE()] = NULL;
1202
1203 // Now we get the full type to force our class type to
1204 // complete itself using the clang::ExternalASTSource
1205 // protocol which will parse all base classes and all
1206 // methods (including the method for this DIE).
1207 class_type->GetFullCompilerType();
1208
1209 // The type for this DIE should have been filled in the
1210 // function call above.
1211 Type *type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1212 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1213 return type_ptr->shared_from_this();
1214 }
1215
1216 // The previous comment isn't actually true if the class wasn't
1217 // resolved using the current method's parent DIE as source
1218 // data. We need to ensure that we look up the method correctly
1219 // in the class and then link the method's DIE to the unique
1220 // CXXMethodDecl appropriately.
1221 type_handled = true;
1222 }
1223 }
1224 }
1225 }
1226 }
1227 }
1228
1229 if (!type_handled) {
1230 clang::FunctionDecl *function_decl = nullptr;
1231 clang::FunctionDecl *template_function_decl = nullptr;
1232
1233 if (attrs.abstract_origin.IsValid()) {
1234 DWARFDIE abs_die = attrs.abstract_origin.Reference();
1235
1236 if (dwarf->ResolveType(die: abs_die)) {
1237 function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>(
1238 Val: GetCachedClangDeclContextForDIE(die: abs_die));
1239
1240 if (function_decl) {
1241 LinkDeclContextToDIE(function_decl, die);
1242 }
1243 }
1244 }
1245
1246 if (!function_decl) {
1247 char *name_buf = nullptr;
1248 llvm::StringRef name = attrs.name.GetStringRef();
1249
1250 // We currently generate function templates with template parameters in
1251 // their name. In order to get closer to the AST that clang generates
1252 // we want to strip these from the name when creating the AST.
1253 if (attrs.mangled_name) {
1254 llvm::ItaniumPartialDemangler D;
1255 if (!D.partialDemangle(MangledName: attrs.mangled_name)) {
1256 name_buf = D.getFunctionBaseName(Buf: nullptr, N: nullptr);
1257 name = name_buf;
1258 }
1259 }
1260
1261 // We just have a function that isn't part of a class
1262 function_decl = m_ast.CreateFunctionDeclaration(
1263 decl_ctx: ignore_containing_context ? m_ast.GetTranslationUnitDecl()
1264 : containing_decl_ctx,
1265 owning_module: GetOwningClangModule(die), name, function_Type: clang_type, storage: attrs.storage,
1266 is_inline: attrs.is_inline);
1267 std::free(ptr: name_buf);
1268
1269 if (has_template_params) {
1270 TypeSystemClang::TemplateParameterInfos template_param_infos;
1271 ParseTemplateParameterInfos(parent_die: die, template_param_infos);
1272 template_function_decl = m_ast.CreateFunctionDeclaration(
1273 decl_ctx: ignore_containing_context ? m_ast.GetTranslationUnitDecl()
1274 : containing_decl_ctx,
1275 owning_module: GetOwningClangModule(die), name: attrs.name.GetStringRef(), function_Type: clang_type,
1276 storage: attrs.storage, is_inline: attrs.is_inline);
1277 clang::FunctionTemplateDecl *func_template_decl =
1278 m_ast.CreateFunctionTemplateDecl(
1279 decl_ctx: containing_decl_ctx, owning_module: GetOwningClangModule(die),
1280 func_decl: template_function_decl, infos: template_param_infos);
1281 m_ast.CreateFunctionTemplateSpecializationInfo(
1282 func_decl: template_function_decl, Template: func_template_decl, infos: template_param_infos);
1283 }
1284
1285 lldbassert(function_decl);
1286
1287 if (function_decl) {
1288 // Attach an asm(<mangled_name>) label to the FunctionDecl.
1289 // This ensures that clang::CodeGen emits function calls
1290 // using symbols that are mangled according to the DW_AT_linkage_name.
1291 // If we didn't do this, the external symbols wouldn't exactly
1292 // match the mangled name LLDB knows about and the IRExecutionUnit
1293 // would have to fall back to searching object files for
1294 // approximately matching function names. The motivating
1295 // example is generating calls to ABI-tagged template functions.
1296 // This is done separately for member functions in
1297 // AddMethodToCXXRecordType.
1298 if (attrs.mangled_name)
1299 function_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
1300 m_ast.getASTContext(), attrs.mangled_name, /*literal=*/false));
1301
1302 LinkDeclContextToDIE(function_decl, die);
1303
1304 if (!function_param_decls.empty()) {
1305 m_ast.SetFunctionParameters(function_decl, params: function_param_decls);
1306 if (template_function_decl)
1307 m_ast.SetFunctionParameters(function_decl: template_function_decl,
1308 params: function_param_decls);
1309 }
1310
1311 ClangASTMetadata metadata;
1312 metadata.SetUserID(die.GetID());
1313
1314 if (!object_pointer_name.empty()) {
1315 metadata.SetObjectPtrName(object_pointer_name.c_str());
1316 LLDB_LOGF(log,
1317 "Setting object pointer name: %s on function "
1318 "object %p.",
1319 object_pointer_name.c_str(),
1320 static_cast<void *>(function_decl));
1321 }
1322 m_ast.SetMetadata(function_decl, metadata);
1323 }
1324 }
1325 }
1326 }
1327 return dwarf->MakeType(
1328 uid: die.GetID(), name: attrs.name, byte_size: std::nullopt, context: nullptr, LLDB_INVALID_UID,
1329 encoding_uid_type: Type::eEncodingIsUID, decl: &attrs.decl, compiler_qual_type: clang_type, compiler_type_resolve_state: Type::ResolveState::Full);
1330}
1331
1332TypeSP
1333DWARFASTParserClang::ParseArrayType(const DWARFDIE &die,
1334 const ParsedDWARFTypeAttributes &attrs) {
1335 SymbolFileDWARF *dwarf = die.GetDWARF();
1336
1337 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1338 DW_TAG_value_to_name(tag), type_name_cstr);
1339
1340 DWARFDIE type_die = attrs.type.Reference();
1341 Type *element_type = dwarf->ResolveTypeUID(die: type_die, assert_not_being_parsed: true);
1342
1343 if (!element_type)
1344 return nullptr;
1345
1346 std::optional<SymbolFile::ArrayInfo> array_info = ParseChildArrayInfo(parent_die: die);
1347 uint32_t byte_stride = attrs.byte_stride;
1348 uint32_t bit_stride = attrs.bit_stride;
1349 if (array_info) {
1350 byte_stride = array_info->byte_stride;
1351 bit_stride = array_info->bit_stride;
1352 }
1353 if (byte_stride == 0 && bit_stride == 0)
1354 byte_stride = element_type->GetByteSize(exe_scope: nullptr).value_or(u: 0);
1355 CompilerType array_element_type = element_type->GetForwardCompilerType();
1356 TypeSystemClang::RequireCompleteType(type: array_element_type);
1357
1358 uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
1359 CompilerType clang_type;
1360 if (array_info && array_info->element_orders.size() > 0) {
1361 uint64_t num_elements = 0;
1362 auto end = array_info->element_orders.rend();
1363 for (auto pos = array_info->element_orders.rbegin(); pos != end; ++pos) {
1364 num_elements = *pos;
1365 clang_type = m_ast.CreateArrayType(element_type: array_element_type, element_count: num_elements,
1366 is_vector: attrs.is_vector);
1367 array_element_type = clang_type;
1368 array_element_bit_stride = num_elements
1369 ? array_element_bit_stride * num_elements
1370 : array_element_bit_stride;
1371 }
1372 } else {
1373 clang_type =
1374 m_ast.CreateArrayType(element_type: array_element_type, element_count: 0, is_vector: attrs.is_vector);
1375 }
1376 ConstString empty_name;
1377 TypeSP type_sp =
1378 dwarf->MakeType(uid: die.GetID(), name: empty_name, byte_size: array_element_bit_stride / 8,
1379 context: nullptr, encoding_uid: type_die.GetID(), encoding_uid_type: Type::eEncodingIsUID,
1380 decl: &attrs.decl, compiler_qual_type: clang_type, compiler_type_resolve_state: Type::ResolveState::Full);
1381 type_sp->SetEncodingType(element_type);
1382 const clang::Type *type = ClangUtil::GetQualType(ct: clang_type).getTypePtr();
1383 m_ast.SetMetadataAsUserID(type, user_id: die.GetID());
1384 return type_sp;
1385}
1386
1387TypeSP DWARFASTParserClang::ParsePointerToMemberType(
1388 const DWARFDIE &die, const ParsedDWARFTypeAttributes &attrs) {
1389 SymbolFileDWARF *dwarf = die.GetDWARF();
1390 Type *pointee_type = dwarf->ResolveTypeUID(die: attrs.type.Reference(), assert_not_being_parsed: true);
1391 Type *class_type =
1392 dwarf->ResolveTypeUID(die: attrs.containing_type.Reference(), assert_not_being_parsed: true);
1393
1394 // Check to make sure pointers are not NULL before attempting to
1395 // dereference them.
1396 if ((class_type == nullptr) || (pointee_type == nullptr))
1397 return nullptr;
1398
1399 CompilerType pointee_clang_type = pointee_type->GetForwardCompilerType();
1400 CompilerType class_clang_type = class_type->GetForwardCompilerType();
1401
1402 CompilerType clang_type = TypeSystemClang::CreateMemberPointerType(
1403 type: class_clang_type, pointee_type: pointee_clang_type);
1404
1405 if (std::optional<uint64_t> clang_type_size =
1406 clang_type.GetByteSize(exe_scope: nullptr)) {
1407 return dwarf->MakeType(uid: die.GetID(), name: attrs.name, byte_size: *clang_type_size, context: nullptr,
1408 LLDB_INVALID_UID, encoding_uid_type: Type::eEncodingIsUID, decl: nullptr,
1409 compiler_qual_type: clang_type, compiler_type_resolve_state: Type::ResolveState::Forward);
1410 }
1411 return nullptr;
1412}
1413
1414void DWARFASTParserClang::ParseInheritance(
1415 const DWARFDIE &die, const DWARFDIE &parent_die,
1416 const CompilerType class_clang_type, const AccessType default_accessibility,
1417 const lldb::ModuleSP &module_sp,
1418 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes,
1419 ClangASTImporter::LayoutInfo &layout_info) {
1420 auto ast =
1421 class_clang_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
1422 if (ast == nullptr)
1423 return;
1424
1425 // TODO: implement DW_TAG_inheritance type parsing.
1426 DWARFAttributes attributes = die.GetAttributes();
1427 if (attributes.Size() == 0)
1428 return;
1429
1430 DWARFFormValue encoding_form;
1431 AccessType accessibility = default_accessibility;
1432 bool is_virtual = false;
1433 bool is_base_of_class = true;
1434 off_t member_byte_offset = 0;
1435
1436 for (uint32_t i = 0; i < attributes.Size(); ++i) {
1437 const dw_attr_t attr = attributes.AttributeAtIndex(i);
1438 DWARFFormValue form_value;
1439 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1440 switch (attr) {
1441 case DW_AT_type:
1442 encoding_form = form_value;
1443 break;
1444 case DW_AT_data_member_location:
1445 if (auto maybe_offset =
1446 ExtractDataMemberLocation(die, form_value, module_sp))
1447 member_byte_offset = *maybe_offset;
1448 break;
1449
1450 case DW_AT_accessibility:
1451 accessibility =
1452 DWARFASTParser::GetAccessTypeFromDWARF(dwarf_accessibility: form_value.Unsigned());
1453 break;
1454
1455 case DW_AT_virtuality:
1456 is_virtual = form_value.Boolean();
1457 break;
1458
1459 default:
1460 break;
1461 }
1462 }
1463 }
1464
1465 Type *base_class_type = die.ResolveTypeUID(die: encoding_form.Reference());
1466 if (base_class_type == nullptr) {
1467 module_sp->ReportError(format: "{0:x16}: DW_TAG_inheritance failed to "
1468 "resolve the base class at {1:x16}"
1469 " from enclosing type {2:x16}. \nPlease file "
1470 "a bug and attach the file at the start of "
1471 "this error message",
1472 args: die.GetOffset(),
1473 args: encoding_form.Reference().GetOffset(),
1474 args: parent_die.GetOffset());
1475 return;
1476 }
1477
1478 CompilerType base_class_clang_type = base_class_type->GetFullCompilerType();
1479 assert(base_class_clang_type);
1480 if (TypeSystemClang::IsObjCObjectOrInterfaceType(type: class_clang_type)) {
1481 ast->SetObjCSuperClass(type: class_clang_type, superclass_compiler_type: base_class_clang_type);
1482 return;
1483 }
1484 std::unique_ptr<clang::CXXBaseSpecifier> result =
1485 ast->CreateBaseClassSpecifier(type: base_class_clang_type.GetOpaqueQualType(),
1486 access: accessibility, is_virtual,
1487 base_of_class: is_base_of_class);
1488 if (!result)
1489 return;
1490
1491 base_classes.push_back(x: std::move(result));
1492
1493 if (is_virtual) {
1494 // Do not specify any offset for virtual inheritance. The DWARF
1495 // produced by clang doesn't give us a constant offset, but gives
1496 // us a DWARF expressions that requires an actual object in memory.
1497 // the DW_AT_data_member_location for a virtual base class looks
1498 // like:
1499 // DW_AT_data_member_location( DW_OP_dup, DW_OP_deref,
1500 // DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref,
1501 // DW_OP_plus )
1502 // Given this, there is really no valid response we can give to
1503 // clang for virtual base class offsets, and this should eventually
1504 // be removed from LayoutRecordType() in the external
1505 // AST source in clang.
1506 } else {
1507 layout_info.base_offsets.insert(KV: std::make_pair(
1508 x: ast->GetAsCXXRecordDecl(type: base_class_clang_type.GetOpaqueQualType()),
1509 y: clang::CharUnits::fromQuantity(Quantity: member_byte_offset)));
1510 }
1511}
1512
1513TypeSP DWARFASTParserClang::UpdateSymbolContextScopeForType(
1514 const SymbolContext &sc, const DWARFDIE &die, TypeSP type_sp) {
1515 if (!type_sp)
1516 return type_sp;
1517
1518 SymbolFileDWARF *dwarf = die.GetDWARF();
1519 DWARFDIE sc_parent_die = SymbolFileDWARF::GetParentSymbolContextDIE(die);
1520 dw_tag_t sc_parent_tag = sc_parent_die.Tag();
1521
1522 SymbolContextScope *symbol_context_scope = nullptr;
1523 if (sc_parent_tag == DW_TAG_compile_unit ||
1524 sc_parent_tag == DW_TAG_partial_unit) {
1525 symbol_context_scope = sc.comp_unit;
1526 } else if (sc.function != nullptr && sc_parent_die) {
1527 symbol_context_scope =
1528 sc.function->GetBlock(can_create: true).FindBlockByID(block_id: sc_parent_die.GetID());
1529 if (symbol_context_scope == nullptr)
1530 symbol_context_scope = sc.function;
1531 } else {
1532 symbol_context_scope = sc.module_sp.get();
1533 }
1534
1535 if (symbol_context_scope != nullptr)
1536 type_sp->SetSymbolContextScope(symbol_context_scope);
1537
1538 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1539 return type_sp;
1540}
1541
1542std::string
1543DWARFASTParserClang::GetCPlusPlusQualifiedName(const DWARFDIE &die) {
1544 if (!die.IsValid())
1545 return "";
1546 const char *name = die.GetName();
1547 if (!name)
1548 return "";
1549 std::string qualified_name;
1550 DWARFDIE parent_decl_ctx_die = die.GetParentDeclContextDIE();
1551 // TODO: change this to get the correct decl context parent....
1552 while (parent_decl_ctx_die) {
1553 // The name may not contain template parameters due to
1554 // -gsimple-template-names; we must reconstruct the full name from child
1555 // template parameter dies via GetDIEClassTemplateParams().
1556 const dw_tag_t parent_tag = parent_decl_ctx_die.Tag();
1557 switch (parent_tag) {
1558 case DW_TAG_namespace: {
1559 if (const char *namespace_name = parent_decl_ctx_die.GetName()) {
1560 qualified_name.insert(pos: 0, s: "::");
1561 qualified_name.insert(pos: 0, s: namespace_name);
1562 } else {
1563 qualified_name.insert(pos: 0, s: "(anonymous namespace)::");
1564 }
1565 parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE();
1566 break;
1567 }
1568
1569 case DW_TAG_class_type:
1570 case DW_TAG_structure_type:
1571 case DW_TAG_union_type: {
1572 if (const char *class_union_struct_name = parent_decl_ctx_die.GetName()) {
1573 qualified_name.insert(
1574 pos: 0, s: GetDIEClassTemplateParams(die: parent_decl_ctx_die).AsCString(value_if_empty: ""));
1575 qualified_name.insert(pos: 0, s: "::");
1576 qualified_name.insert(pos: 0, s: class_union_struct_name);
1577 }
1578 parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE();
1579 break;
1580 }
1581
1582 default:
1583 parent_decl_ctx_die.Clear();
1584 break;
1585 }
1586 }
1587
1588 if (qualified_name.empty())
1589 qualified_name.append(s: "::");
1590
1591 qualified_name.append(s: name);
1592 qualified_name.append(s: GetDIEClassTemplateParams(die).AsCString(value_if_empty: ""));
1593
1594 return qualified_name;
1595}
1596
1597TypeSP
1598DWARFASTParserClang::ParseStructureLikeDIE(const SymbolContext &sc,
1599 const DWARFDIE &die,
1600 ParsedDWARFTypeAttributes &attrs) {
1601 TypeSP type_sp;
1602 CompilerType clang_type;
1603 const dw_tag_t tag = die.Tag();
1604 SymbolFileDWARF *dwarf = die.GetDWARF();
1605 LanguageType cu_language = SymbolFileDWARF::GetLanguage(unit&: *die.GetCU());
1606 Log *log = GetLog(mask: DWARFLog::TypeCompletion | DWARFLog::Lookups);
1607
1608 // UniqueDWARFASTType is large, so don't create a local variables on the
1609 // stack, put it on the heap. This function is often called recursively and
1610 // clang isn't good at sharing the stack space for variables in different
1611 // blocks.
1612 auto unique_ast_entry_up = std::make_unique<UniqueDWARFASTType>();
1613
1614 ConstString unique_typename(attrs.name);
1615 Declaration unique_decl(attrs.decl);
1616
1617 if (attrs.name) {
1618 if (Language::LanguageIsCPlusPlus(language: cu_language)) {
1619 // For C++, we rely solely upon the one definition rule that says
1620 // only one thing can exist at a given decl context. We ignore the
1621 // file and line that things are declared on.
1622 std::string qualified_name = GetCPlusPlusQualifiedName(die);
1623 if (!qualified_name.empty())
1624 unique_typename = ConstString(qualified_name);
1625 unique_decl.Clear();
1626 }
1627
1628 if (dwarf->GetUniqueDWARFASTTypeMap().Find(
1629 name: unique_typename, die, decl: unique_decl, byte_size: attrs.byte_size.value_or(u: -1),
1630 entry&: *unique_ast_entry_up)) {
1631 type_sp = unique_ast_entry_up->m_type_sp;
1632 if (type_sp) {
1633 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1634 LinkDeclContextToDIE(
1635 decl_ctx: GetCachedClangDeclContextForDIE(die: unique_ast_entry_up->m_die), die);
1636 return type_sp;
1637 }
1638 }
1639 }
1640
1641 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1642 DW_TAG_value_to_name(tag), type_name_cstr);
1643
1644 int tag_decl_kind = -1;
1645 AccessType default_accessibility = eAccessNone;
1646 if (tag == DW_TAG_structure_type) {
1647 tag_decl_kind = llvm::to_underlying(E: clang::TagTypeKind::Struct);
1648 default_accessibility = eAccessPublic;
1649 } else if (tag == DW_TAG_union_type) {
1650 tag_decl_kind = llvm::to_underlying(E: clang::TagTypeKind::Union);
1651 default_accessibility = eAccessPublic;
1652 } else if (tag == DW_TAG_class_type) {
1653 tag_decl_kind = llvm::to_underlying(E: clang::TagTypeKind::Class);
1654 default_accessibility = eAccessPrivate;
1655 }
1656
1657 if (attrs.byte_size && *attrs.byte_size == 0 && attrs.name &&
1658 !die.HasChildren() && cu_language == eLanguageTypeObjC) {
1659 // Work around an issue with clang at the moment where forward
1660 // declarations for objective C classes are emitted as:
1661 // DW_TAG_structure_type [2]
1662 // DW_AT_name( "ForwardObjcClass" )
1663 // DW_AT_byte_size( 0x00 )
1664 // DW_AT_decl_file( "..." )
1665 // DW_AT_decl_line( 1 )
1666 //
1667 // Note that there is no DW_AT_declaration and there are no children,
1668 // and the byte size is zero.
1669 attrs.is_forward_declaration = true;
1670 }
1671
1672 if (attrs.class_language == eLanguageTypeObjC ||
1673 attrs.class_language == eLanguageTypeObjC_plus_plus) {
1674 if (!attrs.is_complete_objc_class &&
1675 die.Supports_DW_AT_APPLE_objc_complete_type()) {
1676 // We have a valid eSymbolTypeObjCClass class symbol whose name
1677 // matches the current objective C class that we are trying to find
1678 // and this DIE isn't the complete definition (we checked
1679 // is_complete_objc_class above and know it is false), so the real
1680 // definition is in here somewhere
1681 type_sp =
1682 dwarf->FindCompleteObjCDefinitionTypeForDIE(die, type_name: attrs.name, must_be_implementation: true);
1683
1684 if (!type_sp) {
1685 SymbolFileDWARFDebugMap *debug_map_symfile =
1686 dwarf->GetDebugMapSymfile();
1687 if (debug_map_symfile) {
1688 // We weren't able to find a full declaration in this DWARF,
1689 // see if we have a declaration anywhere else...
1690 type_sp = debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE(
1691 die, type_name: attrs.name, must_be_implementation: true);
1692 }
1693 }
1694
1695 if (type_sp) {
1696 if (log) {
1697 dwarf->GetObjectFile()->GetModule()->LogMessage(
1698 log,
1699 format: "SymbolFileDWARF({0:p}) - {1:x16}: {2} type "
1700 "\"{3}\" is an "
1701 "incomplete objc type, complete type is {4:x8}",
1702 args: static_cast<void *>(this), args: die.GetOffset(),
1703 args: DW_TAG_value_to_name(val: tag), args: attrs.name.GetCString(),
1704 args: type_sp->GetID());
1705 }
1706
1707 // We found a real definition for this type elsewhere so lets use
1708 // it and cache the fact that we found a complete type for this
1709 // die
1710 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1711 return type_sp;
1712 }
1713 }
1714 }
1715
1716 if (attrs.is_forward_declaration) {
1717 // We have a forward declaration to a type and we need to try and
1718 // find a full declaration. We look in the current type index just in
1719 // case we have a forward declaration followed by an actual
1720 // declarations in the DWARF. If this fails, we need to look
1721 // elsewhere...
1722 if (log) {
1723 dwarf->GetObjectFile()->GetModule()->LogMessage(
1724 log,
1725 format: "SymbolFileDWARF({0:p}) - {1:x16}: {2} type \"{3}\" is a "
1726 "forward declaration, trying to find complete type",
1727 args: static_cast<void *>(this), args: die.GetOffset(), args: DW_TAG_value_to_name(val: tag),
1728 args: attrs.name.GetCString());
1729 }
1730
1731 // See if the type comes from a Clang module and if so, track down
1732 // that type.
1733 type_sp = ParseTypeFromClangModule(sc, die, log);
1734 if (type_sp)
1735 return type_sp;
1736
1737 // type_sp = FindDefinitionTypeForDIE (dwarf_cu, die,
1738 // type_name_const_str);
1739 type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die);
1740
1741 if (!type_sp) {
1742 SymbolFileDWARFDebugMap *debug_map_symfile = dwarf->GetDebugMapSymfile();
1743 if (debug_map_symfile) {
1744 // We weren't able to find a full declaration in this DWARF, see
1745 // if we have a declaration anywhere else...
1746 type_sp = debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(die);
1747 }
1748 }
1749
1750 if (type_sp) {
1751 if (log) {
1752 dwarf->GetObjectFile()->GetModule()->LogMessage(
1753 log,
1754 format: "SymbolFileDWARF({0:p}) - {1:x16}: {2} type \"{3}\" is a "
1755 "forward declaration, complete type is {4:x8}",
1756 args: static_cast<void *>(this), args: die.GetOffset(),
1757 args: DW_TAG_value_to_name(val: tag), args: attrs.name.GetCString(),
1758 args: type_sp->GetID());
1759 }
1760
1761 // We found a real definition for this type elsewhere so lets use
1762 // it and cache the fact that we found a complete type for this die
1763 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1764 clang::DeclContext *defn_decl_ctx =
1765 GetCachedClangDeclContextForDIE(die: dwarf->GetDIE(uid: type_sp->GetID()));
1766 if (defn_decl_ctx)
1767 LinkDeclContextToDIE(decl_ctx: defn_decl_ctx, die);
1768 return type_sp;
1769 }
1770 }
1771 assert(tag_decl_kind != -1);
1772 UNUSED_IF_ASSERT_DISABLED(tag_decl_kind);
1773 bool clang_type_was_created = false;
1774 clang::DeclContext *decl_ctx = GetClangDeclContextContainingDIE(die, decl_ctx_die: nullptr);
1775
1776 PrepareContextToReceiveMembers(ast&: m_ast, ast_importer&: GetClangASTImporter(), decl_ctx, die,
1777 type_name_cstr: attrs.name.GetCString());
1778
1779 if (attrs.accessibility == eAccessNone && decl_ctx) {
1780 // Check the decl context that contains this class/struct/union. If
1781 // it is a class we must give it an accessibility.
1782 const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind();
1783 if (DeclKindIsCXXClass(decl_kind: containing_decl_kind))
1784 attrs.accessibility = default_accessibility;
1785 }
1786
1787 ClangASTMetadata metadata;
1788 metadata.SetUserID(die.GetID());
1789 metadata.SetIsDynamicCXXType(dwarf->ClassOrStructIsVirtual(die));
1790
1791 TypeSystemClang::TemplateParameterInfos template_param_infos;
1792 if (ParseTemplateParameterInfos(parent_die: die, template_param_infos)) {
1793 clang::ClassTemplateDecl *class_template_decl =
1794 m_ast.ParseClassTemplateDecl(
1795 decl_ctx, owning_module: GetOwningClangModule(die), access_type: attrs.accessibility,
1796 parent_name: attrs.name.GetCString(), tag_decl_kind, template_param_infos);
1797 if (!class_template_decl) {
1798 if (log) {
1799 dwarf->GetObjectFile()->GetModule()->LogMessage(
1800 log,
1801 format: "SymbolFileDWARF({0:p}) - {1:x16}: {2} type \"{3}\" "
1802 "clang::ClassTemplateDecl failed to return a decl.",
1803 args: static_cast<void *>(this), args: die.GetOffset(),
1804 args: DW_TAG_value_to_name(val: tag), args: attrs.name.GetCString());
1805 }
1806 return TypeSP();
1807 }
1808
1809 clang::ClassTemplateSpecializationDecl *class_specialization_decl =
1810 m_ast.CreateClassTemplateSpecializationDecl(
1811 decl_ctx, owning_module: GetOwningClangModule(die), class_template_decl,
1812 kind: tag_decl_kind, infos: template_param_infos);
1813 clang_type =
1814 m_ast.CreateClassTemplateSpecializationType(class_template_specialization_decl: class_specialization_decl);
1815 clang_type_was_created = true;
1816
1817 m_ast.SetMetadata(class_template_decl, metadata);
1818 m_ast.SetMetadata(class_specialization_decl, metadata);
1819 }
1820
1821 if (!clang_type_was_created) {
1822 clang_type_was_created = true;
1823 clang_type = m_ast.CreateRecordType(
1824 decl_ctx, owning_module: GetOwningClangModule(die), access_type: attrs.accessibility,
1825 name: attrs.name.GetCString(), kind: tag_decl_kind, language: attrs.class_language, metadata: &metadata,
1826 exports_symbols: attrs.exports_symbols);
1827 }
1828
1829 // Store a forward declaration to this class type in case any
1830 // parameters in any class methods need it for the clang types for
1831 // function prototypes.
1832 LinkDeclContextToDIE(decl_ctx: m_ast.GetDeclContextForType(type: clang_type), die);
1833 type_sp = dwarf->MakeType(
1834 uid: die.GetID(), name: attrs.name, byte_size: attrs.byte_size, context: nullptr, LLDB_INVALID_UID,
1835 encoding_uid_type: Type::eEncodingIsUID, decl: &attrs.decl, compiler_qual_type: clang_type,
1836 compiler_type_resolve_state: Type::ResolveState::Forward,
1837 opaque_payload: TypePayloadClang(OptionalClangModuleID(), attrs.is_complete_objc_class));
1838
1839 // Add our type to the unique type map so we don't end up creating many
1840 // copies of the same type over and over in the ASTContext for our
1841 // module
1842 unique_ast_entry_up->m_type_sp = type_sp;
1843 unique_ast_entry_up->m_die = die;
1844 unique_ast_entry_up->m_declaration = unique_decl;
1845 unique_ast_entry_up->m_byte_size = attrs.byte_size.value_or(u: 0);
1846 dwarf->GetUniqueDWARFASTTypeMap().Insert(name: unique_typename,
1847 entry: *unique_ast_entry_up);
1848
1849 if (!attrs.is_forward_declaration) {
1850 // Always start the definition for a class type so that if the class
1851 // has child classes or types that require the class to be created
1852 // for use as their decl contexts the class will be ready to accept
1853 // these child definitions.
1854 if (!die.HasChildren()) {
1855 // No children for this struct/union/class, lets finish it
1856 if (TypeSystemClang::StartTagDeclarationDefinition(type: clang_type)) {
1857 TypeSystemClang::CompleteTagDeclarationDefinition(type: clang_type);
1858 } else {
1859 dwarf->GetObjectFile()->GetModule()->ReportError(
1860
1861 format: "DWARF DIE at {0:x16} named \"{1}\" was not able to start "
1862 "its "
1863 "definition.\nPlease file a bug and attach the file at the "
1864 "start of this error message",
1865 args: die.GetOffset(), args: attrs.name.GetCString());
1866 }
1867
1868 // Setting authority byte size and alignment for empty structures.
1869 //
1870 // If the byte size or alignmenet of the record is specified then
1871 // overwrite the ones that would be computed by Clang.
1872 // This is only needed as LLDB's TypeSystemClang is always in C++ mode,
1873 // but some compilers such as GCC and Clang give empty structs a size of 0
1874 // in C mode (in contrast to the size of 1 for empty structs that would be
1875 // computed in C++ mode).
1876 if (attrs.byte_size || attrs.alignment) {
1877 clang::RecordDecl *record_decl =
1878 TypeSystemClang::GetAsRecordDecl(type: clang_type);
1879 if (record_decl) {
1880 ClangASTImporter::LayoutInfo layout;
1881 layout.bit_size = attrs.byte_size.value_or(u: 0) * 8;
1882 layout.alignment = attrs.alignment.value_or(u: 0) * 8;
1883 GetClangASTImporter().SetRecordLayout(decl: record_decl, layout);
1884 }
1885 }
1886 } else if (clang_type_was_created) {
1887 // Start the definition if the class is not objective C since the
1888 // underlying decls respond to isCompleteDefinition(). Objective
1889 // C decls don't respond to isCompleteDefinition() so we can't
1890 // start the declaration definition right away. For C++
1891 // class/union/structs we want to start the definition in case the
1892 // class is needed as the declaration context for a contained class
1893 // or type without the need to complete that type..
1894
1895 if (attrs.class_language != eLanguageTypeObjC &&
1896 attrs.class_language != eLanguageTypeObjC_plus_plus)
1897 TypeSystemClang::StartTagDeclarationDefinition(type: clang_type);
1898
1899 // Leave this as a forward declaration until we need to know the
1900 // details of the type. lldb_private::Type will automatically call
1901 // the SymbolFile virtual function
1902 // "SymbolFileDWARF::CompleteType(Type *)" When the definition
1903 // needs to be defined.
1904 assert(!dwarf->GetForwardDeclCompilerTypeToDIE().count(
1905 ClangUtil::RemoveFastQualifiers(clang_type)
1906 .GetOpaqueQualType()) &&
1907 "Type already in the forward declaration map!");
1908 // Can't assume m_ast.GetSymbolFile() is actually a
1909 // SymbolFileDWARF, it can be a SymbolFileDWARFDebugMap for Apple
1910 // binaries.
1911 dwarf->GetForwardDeclCompilerTypeToDIE().try_emplace(
1912 Key: ClangUtil::RemoveFastQualifiers(ct: clang_type).GetOpaqueQualType(),
1913 Args: *die.GetDIERef());
1914 m_ast.SetHasExternalStorage(type: clang_type.GetOpaqueQualType(), has_extern: true);
1915 }
1916 }
1917
1918 // If we made a clang type, set the trivial abi if applicable: We only
1919 // do this for pass by value - which implies the Trivial ABI. There
1920 // isn't a way to assert that something that would normally be pass by
1921 // value is pass by reference, so we ignore that attribute if set.
1922 if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_value) {
1923 clang::CXXRecordDecl *record_decl =
1924 m_ast.GetAsCXXRecordDecl(type: clang_type.GetOpaqueQualType());
1925 if (record_decl && record_decl->getDefinition()) {
1926 record_decl->setHasTrivialSpecialMemberForCall();
1927 }
1928 }
1929
1930 if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_reference) {
1931 clang::CXXRecordDecl *record_decl =
1932 m_ast.GetAsCXXRecordDecl(type: clang_type.GetOpaqueQualType());
1933 if (record_decl)
1934 record_decl->setArgPassingRestrictions(
1935 clang::RecordArgPassingKind::CannotPassInRegs);
1936 }
1937 return type_sp;
1938}
1939
1940// DWARF parsing functions
1941
1942class DWARFASTParserClang::DelayedAddObjCClassProperty {
1943public:
1944 DelayedAddObjCClassProperty(
1945 const CompilerType &class_opaque_type, const char *property_name,
1946 const CompilerType &property_opaque_type, // The property type is only
1947 // required if you don't have an
1948 // ivar decl
1949 const char *property_setter_name, const char *property_getter_name,
1950 uint32_t property_attributes, const ClangASTMetadata *metadata)
1951 : m_class_opaque_type(class_opaque_type), m_property_name(property_name),
1952 m_property_opaque_type(property_opaque_type),
1953 m_property_setter_name(property_setter_name),
1954 m_property_getter_name(property_getter_name),
1955 m_property_attributes(property_attributes) {
1956 if (metadata != nullptr) {
1957 m_metadata_up = std::make_unique<ClangASTMetadata>();
1958 *m_metadata_up = *metadata;
1959 }
1960 }
1961
1962 DelayedAddObjCClassProperty(const DelayedAddObjCClassProperty &rhs) {
1963 *this = rhs;
1964 }
1965
1966 DelayedAddObjCClassProperty &
1967 operator=(const DelayedAddObjCClassProperty &rhs) {
1968 m_class_opaque_type = rhs.m_class_opaque_type;
1969 m_property_name = rhs.m_property_name;
1970 m_property_opaque_type = rhs.m_property_opaque_type;
1971 m_property_setter_name = rhs.m_property_setter_name;
1972 m_property_getter_name = rhs.m_property_getter_name;
1973 m_property_attributes = rhs.m_property_attributes;
1974
1975 if (rhs.m_metadata_up) {
1976 m_metadata_up = std::make_unique<ClangASTMetadata>();
1977 *m_metadata_up = *rhs.m_metadata_up;
1978 }
1979 return *this;
1980 }
1981
1982 bool Finalize() {
1983 return TypeSystemClang::AddObjCClassProperty(
1984 type: m_class_opaque_type, property_name: m_property_name, property_compiler_type: m_property_opaque_type,
1985 /*ivar_decl=*/nullptr, property_setter_name: m_property_setter_name, property_getter_name: m_property_getter_name,
1986 property_attributes: m_property_attributes, metadata: m_metadata_up.get());
1987 }
1988
1989private:
1990 CompilerType m_class_opaque_type;
1991 const char *m_property_name;
1992 CompilerType m_property_opaque_type;
1993 const char *m_property_setter_name;
1994 const char *m_property_getter_name;
1995 uint32_t m_property_attributes;
1996 std::unique_ptr<ClangASTMetadata> m_metadata_up;
1997};
1998
1999bool DWARFASTParserClang::ParseTemplateDIE(
2000 const DWARFDIE &die,
2001 TypeSystemClang::TemplateParameterInfos &template_param_infos) {
2002 const dw_tag_t tag = die.Tag();
2003 bool is_template_template_argument = false;
2004
2005 switch (tag) {
2006 case DW_TAG_GNU_template_parameter_pack: {
2007 template_param_infos.SetParameterPack(
2008 std::make_unique<TypeSystemClang::TemplateParameterInfos>());
2009 for (DWARFDIE child_die : die.children()) {
2010 if (!ParseTemplateDIE(die: child_die, template_param_infos&: template_param_infos.GetParameterPack()))
2011 return false;
2012 }
2013 if (const char *name = die.GetName()) {
2014 template_param_infos.SetPackName(name);
2015 }
2016 return true;
2017 }
2018 case DW_TAG_GNU_template_template_param:
2019 is_template_template_argument = true;
2020 [[fallthrough]];
2021 case DW_TAG_template_type_parameter:
2022 case DW_TAG_template_value_parameter: {
2023 DWARFAttributes attributes = die.GetAttributes();
2024 if (attributes.Size() == 0)
2025 return true;
2026
2027 const char *name = nullptr;
2028 const char *template_name = nullptr;
2029 CompilerType clang_type;
2030 uint64_t uval64 = 0;
2031 bool uval64_valid = false;
2032 bool is_default_template_arg = false;
2033 DWARFFormValue form_value;
2034 for (size_t i = 0; i < attributes.Size(); ++i) {
2035 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2036
2037 switch (attr) {
2038 case DW_AT_name:
2039 if (attributes.ExtractFormValueAtIndex(i, form_value))
2040 name = form_value.AsCString();
2041 break;
2042
2043 case DW_AT_GNU_template_name:
2044 if (attributes.ExtractFormValueAtIndex(i, form_value))
2045 template_name = form_value.AsCString();
2046 break;
2047
2048 case DW_AT_type:
2049 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2050 Type *lldb_type = die.ResolveTypeUID(die: form_value.Reference());
2051 if (lldb_type)
2052 clang_type = lldb_type->GetForwardCompilerType();
2053 }
2054 break;
2055
2056 case DW_AT_const_value:
2057 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2058 uval64_valid = true;
2059 uval64 = form_value.Unsigned();
2060 }
2061 break;
2062 case DW_AT_default_value:
2063 if (attributes.ExtractFormValueAtIndex(i, form_value))
2064 is_default_template_arg = form_value.Boolean();
2065 break;
2066 default:
2067 break;
2068 }
2069 }
2070
2071 clang::ASTContext &ast = m_ast.getASTContext();
2072 if (!clang_type)
2073 clang_type = m_ast.GetBasicType(type: eBasicTypeVoid);
2074
2075 if (!is_template_template_argument) {
2076 bool is_signed = false;
2077 // Get the signed value for any integer or enumeration if available
2078 clang_type.IsIntegerOrEnumerationType(is_signed);
2079
2080 if (name && !name[0])
2081 name = nullptr;
2082
2083 if (tag == DW_TAG_template_value_parameter && uval64_valid) {
2084 std::optional<uint64_t> size = clang_type.GetBitSize(exe_scope: nullptr);
2085 if (!size)
2086 return false;
2087 llvm::APInt apint(*size, uval64, is_signed);
2088 template_param_infos.InsertArg(
2089 name, arg: clang::TemplateArgument(ast, llvm::APSInt(apint, !is_signed),
2090 ClangUtil::GetQualType(ct: clang_type),
2091 is_default_template_arg));
2092 } else {
2093 template_param_infos.InsertArg(
2094 name, arg: clang::TemplateArgument(ClangUtil::GetQualType(ct: clang_type),
2095 /*isNullPtr*/ false,
2096 is_default_template_arg));
2097 }
2098 } else {
2099 auto *tplt_type = m_ast.CreateTemplateTemplateParmDecl(template_name);
2100 template_param_infos.InsertArg(
2101 name, arg: clang::TemplateArgument(clang::TemplateName(tplt_type),
2102 is_default_template_arg));
2103 }
2104 }
2105 return true;
2106
2107 default:
2108 break;
2109 }
2110 return false;
2111}
2112
2113bool DWARFASTParserClang::ParseTemplateParameterInfos(
2114 const DWARFDIE &parent_die,
2115 TypeSystemClang::TemplateParameterInfos &template_param_infos) {
2116
2117 if (!parent_die)
2118 return false;
2119
2120 for (DWARFDIE die : parent_die.children()) {
2121 const dw_tag_t tag = die.Tag();
2122
2123 switch (tag) {
2124 case DW_TAG_template_type_parameter:
2125 case DW_TAG_template_value_parameter:
2126 case DW_TAG_GNU_template_parameter_pack:
2127 case DW_TAG_GNU_template_template_param:
2128 ParseTemplateDIE(die, template_param_infos);
2129 break;
2130
2131 default:
2132 break;
2133 }
2134 }
2135
2136 return !template_param_infos.IsEmpty() ||
2137 template_param_infos.hasParameterPack();
2138}
2139
2140bool DWARFASTParserClang::CompleteRecordType(const DWARFDIE &die,
2141 lldb_private::Type *type,
2142 CompilerType &clang_type) {
2143 const dw_tag_t tag = die.Tag();
2144 SymbolFileDWARF *dwarf = die.GetDWARF();
2145
2146 ClangASTImporter::LayoutInfo layout_info;
2147 std::vector<DWARFDIE> contained_type_dies;
2148
2149 if (die.HasChildren()) {
2150 const bool type_is_objc_object_or_interface =
2151 TypeSystemClang::IsObjCObjectOrInterfaceType(type: clang_type);
2152 if (type_is_objc_object_or_interface) {
2153 // For objective C we don't start the definition when the class is
2154 // created.
2155 TypeSystemClang::StartTagDeclarationDefinition(type: clang_type);
2156 }
2157
2158 AccessType default_accessibility = eAccessNone;
2159 if (tag == DW_TAG_structure_type) {
2160 default_accessibility = eAccessPublic;
2161 } else if (tag == DW_TAG_union_type) {
2162 default_accessibility = eAccessPublic;
2163 } else if (tag == DW_TAG_class_type) {
2164 default_accessibility = eAccessPrivate;
2165 }
2166
2167 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases;
2168 // Parse members and base classes first
2169 std::vector<DWARFDIE> member_function_dies;
2170
2171 DelayedPropertyList delayed_properties;
2172 ParseChildMembers(die, class_compiler_type&: clang_type, base_classes&: bases, member_function_dies,
2173 contained_type_dies, delayed_properties,
2174 default_accessibility, layout_info);
2175
2176 // Now parse any methods if there were any...
2177 for (const DWARFDIE &die : member_function_dies)
2178 dwarf->ResolveType(die);
2179
2180 if (type_is_objc_object_or_interface) {
2181 ConstString class_name(clang_type.GetTypeName());
2182 if (class_name) {
2183 dwarf->GetObjCMethods(class_name, callback: [&](DWARFDIE method_die) {
2184 method_die.ResolveType();
2185 return true;
2186 });
2187
2188 for (DelayedAddObjCClassProperty &property : delayed_properties)
2189 property.Finalize();
2190 }
2191 }
2192
2193 if (!bases.empty()) {
2194 // Make sure all base classes refer to complete types and not forward
2195 // declarations. If we don't do this, clang will crash with an
2196 // assertion in the call to clang_type.TransferBaseClasses()
2197 for (const auto &base_class : bases) {
2198 clang::TypeSourceInfo *type_source_info =
2199 base_class->getTypeSourceInfo();
2200 if (type_source_info)
2201 TypeSystemClang::RequireCompleteType(
2202 type: m_ast.GetType(qt: type_source_info->getType()));
2203 }
2204
2205 m_ast.TransferBaseClasses(type: clang_type.GetOpaqueQualType(),
2206 bases: std::move(bases));
2207 }
2208 }
2209
2210 m_ast.AddMethodOverridesForCXXRecordType(type: clang_type.GetOpaqueQualType());
2211 TypeSystemClang::BuildIndirectFields(type: clang_type);
2212 TypeSystemClang::CompleteTagDeclarationDefinition(type: clang_type);
2213
2214 if (!layout_info.field_offsets.empty() || !layout_info.base_offsets.empty() ||
2215 !layout_info.vbase_offsets.empty()) {
2216 if (type)
2217 layout_info.bit_size = type->GetByteSize(exe_scope: nullptr).value_or(u: 0) * 8;
2218 if (layout_info.bit_size == 0)
2219 layout_info.bit_size =
2220 die.GetAttributeValueAsUnsigned(attr: DW_AT_byte_size, fail_value: 0) * 8;
2221 if (layout_info.alignment == 0)
2222 layout_info.alignment =
2223 die.GetAttributeValueAsUnsigned(attr: llvm::dwarf::DW_AT_alignment, fail_value: 0) * 8;
2224
2225 clang::CXXRecordDecl *record_decl =
2226 m_ast.GetAsCXXRecordDecl(type: clang_type.GetOpaqueQualType());
2227 if (record_decl)
2228 GetClangASTImporter().SetRecordLayout(record_decl, layout_info);
2229 }
2230 // Now parse all contained types inside of the class. We make forward
2231 // declarations to all classes, but we need the CXXRecordDecl to have decls
2232 // for all contained types because we don't get asked for them via the
2233 // external AST support.
2234 for (const DWARFDIE &die : contained_type_dies)
2235 dwarf->ResolveType(die);
2236
2237 return (bool)clang_type;
2238}
2239
2240bool DWARFASTParserClang::CompleteEnumType(const DWARFDIE &die,
2241 lldb_private::Type *type,
2242 CompilerType &clang_type) {
2243 if (TypeSystemClang::StartTagDeclarationDefinition(type: clang_type)) {
2244 if (die.HasChildren()) {
2245 bool is_signed = false;
2246 clang_type.IsIntegerType(is_signed);
2247 ParseChildEnumerators(compiler_type&: clang_type, is_signed,
2248 enumerator_byte_size: type->GetByteSize(exe_scope: nullptr).value_or(u: 0), parent_die: die);
2249 }
2250 TypeSystemClang::CompleteTagDeclarationDefinition(type: clang_type);
2251 }
2252 return (bool)clang_type;
2253}
2254
2255bool DWARFASTParserClang::CompleteTypeFromDWARF(const DWARFDIE &die,
2256 lldb_private::Type *type,
2257 CompilerType &clang_type) {
2258 SymbolFileDWARF *dwarf = die.GetDWARF();
2259
2260 std::lock_guard<std::recursive_mutex> guard(
2261 dwarf->GetObjectFile()->GetModule()->GetMutex());
2262
2263 // Disable external storage for this type so we don't get anymore
2264 // clang::ExternalASTSource queries for this type.
2265 m_ast.SetHasExternalStorage(type: clang_type.GetOpaqueQualType(), has_extern: false);
2266
2267 if (!die)
2268 return false;
2269
2270 const dw_tag_t tag = die.Tag();
2271
2272 assert(clang_type);
2273 switch (tag) {
2274 case DW_TAG_structure_type:
2275 case DW_TAG_union_type:
2276 case DW_TAG_class_type:
2277 return CompleteRecordType(die, type, clang_type);
2278 case DW_TAG_enumeration_type:
2279 return CompleteEnumType(die, type, clang_type);
2280 default:
2281 assert(false && "not a forward clang type decl!");
2282 break;
2283 }
2284
2285 return false;
2286}
2287
2288void DWARFASTParserClang::EnsureAllDIEsInDeclContextHaveBeenParsed(
2289 lldb_private::CompilerDeclContext decl_context) {
2290 auto opaque_decl_ctx =
2291 (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
2292 for (auto it = m_decl_ctx_to_die.find(x: opaque_decl_ctx);
2293 it != m_decl_ctx_to_die.end() && it->first == opaque_decl_ctx;
2294 it = m_decl_ctx_to_die.erase(position: it))
2295 for (DWARFDIE decl : it->second.children())
2296 GetClangDeclForDIE(die: decl);
2297}
2298
2299CompilerDecl DWARFASTParserClang::GetDeclForUIDFromDWARF(const DWARFDIE &die) {
2300 clang::Decl *clang_decl = GetClangDeclForDIE(die);
2301 if (clang_decl != nullptr)
2302 return m_ast.GetCompilerDecl(decl: clang_decl);
2303 return {};
2304}
2305
2306CompilerDeclContext
2307DWARFASTParserClang::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {
2308 clang::DeclContext *clang_decl_ctx = GetClangDeclContextForDIE(die);
2309 if (clang_decl_ctx)
2310 return m_ast.CreateDeclContext(ctx: clang_decl_ctx);
2311 return {};
2312}
2313
2314CompilerDeclContext
2315DWARFASTParserClang::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {
2316 clang::DeclContext *clang_decl_ctx =
2317 GetClangDeclContextContainingDIE(die, decl_ctx_die: nullptr);
2318 if (clang_decl_ctx)
2319 return m_ast.CreateDeclContext(ctx: clang_decl_ctx);
2320 return {};
2321}
2322
2323size_t DWARFASTParserClang::ParseChildEnumerators(
2324 lldb_private::CompilerType &clang_type, bool is_signed,
2325 uint32_t enumerator_byte_size, const DWARFDIE &parent_die) {
2326 if (!parent_die)
2327 return 0;
2328
2329 size_t enumerators_added = 0;
2330
2331 for (DWARFDIE die : parent_die.children()) {
2332 const dw_tag_t tag = die.Tag();
2333 if (tag != DW_TAG_enumerator)
2334 continue;
2335
2336 DWARFAttributes attributes = die.GetAttributes();
2337 if (attributes.Size() == 0)
2338 continue;
2339
2340 const char *name = nullptr;
2341 bool got_value = false;
2342 int64_t enum_value = 0;
2343 Declaration decl;
2344
2345 for (size_t i = 0; i < attributes.Size(); ++i) {
2346 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2347 DWARFFormValue form_value;
2348 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2349 switch (attr) {
2350 case DW_AT_const_value:
2351 got_value = true;
2352 if (is_signed)
2353 enum_value = form_value.Signed();
2354 else
2355 enum_value = form_value.Unsigned();
2356 break;
2357
2358 case DW_AT_name:
2359 name = form_value.AsCString();
2360 break;
2361
2362 case DW_AT_description:
2363 default:
2364 case DW_AT_decl_file:
2365 decl.SetFile(
2366 attributes.CompileUnitAtIndex(i)->GetFile(file_idx: form_value.Unsigned()));
2367 break;
2368 case DW_AT_decl_line:
2369 decl.SetLine(form_value.Unsigned());
2370 break;
2371 case DW_AT_decl_column:
2372 decl.SetColumn(form_value.Unsigned());
2373 break;
2374 case DW_AT_sibling:
2375 break;
2376 }
2377 }
2378 }
2379
2380 if (name && name[0] && got_value) {
2381 m_ast.AddEnumerationValueToEnumerationType(
2382 enum_type: clang_type, decl, name, enum_value, enum_value_bit_size: enumerator_byte_size * 8);
2383 ++enumerators_added;
2384 }
2385 }
2386 return enumerators_added;
2387}
2388
2389ConstString
2390DWARFASTParserClang::ConstructDemangledNameFromDWARF(const DWARFDIE &die) {
2391 bool is_static = false;
2392 bool is_variadic = false;
2393 bool has_template_params = false;
2394 unsigned type_quals = 0;
2395 std::vector<CompilerType> param_types;
2396 std::vector<clang::ParmVarDecl *> param_decls;
2397 StreamString sstr;
2398
2399 DWARFDeclContext decl_ctx = SymbolFileDWARF::GetDWARFDeclContext(die);
2400 sstr << decl_ctx.GetQualifiedName();
2401
2402 clang::DeclContext *containing_decl_ctx =
2403 GetClangDeclContextContainingDIE(die, decl_ctx_die: nullptr);
2404 ParseChildParameters(containing_decl_ctx, parent_die: die, skip_artificial: true, is_static, is_variadic,
2405 has_template_params, function_args&: param_types, function_param_decls&: param_decls,
2406 type_quals);
2407 sstr << "(";
2408 for (size_t i = 0; i < param_types.size(); i++) {
2409 if (i > 0)
2410 sstr << ", ";
2411 sstr << param_types[i].GetTypeName();
2412 }
2413 if (is_variadic)
2414 sstr << ", ...";
2415 sstr << ")";
2416 if (type_quals & clang::Qualifiers::Const)
2417 sstr << " const";
2418
2419 return ConstString(sstr.GetString());
2420}
2421
2422Function *
2423DWARFASTParserClang::ParseFunctionFromDWARF(CompileUnit &comp_unit,
2424 const DWARFDIE &die,
2425 const AddressRange &func_range) {
2426 assert(func_range.GetBaseAddress().IsValid());
2427 DWARFRangeList func_ranges;
2428 const char *name = nullptr;
2429 const char *mangled = nullptr;
2430 std::optional<int> decl_file;
2431 std::optional<int> decl_line;
2432 std::optional<int> decl_column;
2433 std::optional<int> call_file;
2434 std::optional<int> call_line;
2435 std::optional<int> call_column;
2436 DWARFExpressionList frame_base;
2437
2438 const dw_tag_t tag = die.Tag();
2439
2440 if (tag != DW_TAG_subprogram)
2441 return nullptr;
2442
2443 if (die.GetDIENamesAndRanges(name, mangled, ranges&: func_ranges, decl_file, decl_line,
2444 decl_column, call_file, call_line, call_column,
2445 frame_base: &frame_base)) {
2446 Mangled func_name;
2447 if (mangled)
2448 func_name.SetValue(ConstString(mangled));
2449 else if ((die.GetParent().Tag() == DW_TAG_compile_unit ||
2450 die.GetParent().Tag() == DW_TAG_partial_unit) &&
2451 Language::LanguageIsCPlusPlus(
2452 language: SymbolFileDWARF::GetLanguage(unit&: *die.GetCU())) &&
2453 !Language::LanguageIsObjC(
2454 language: SymbolFileDWARF::GetLanguage(unit&: *die.GetCU())) &&
2455 name && strcmp(s1: name, s2: "main") != 0) {
2456 // If the mangled name is not present in the DWARF, generate the
2457 // demangled name using the decl context. We skip if the function is
2458 // "main" as its name is never mangled.
2459 func_name.SetValue(ConstructDemangledNameFromDWARF(die));
2460 } else
2461 func_name.SetValue(ConstString(name));
2462
2463 FunctionSP func_sp;
2464 std::unique_ptr<Declaration> decl_up;
2465 if (decl_file || decl_line || decl_column)
2466 decl_up = std::make_unique<Declaration>(
2467 args: die.GetCU()->GetFile(file_idx: decl_file ? *decl_file : 0),
2468 args: decl_line ? *decl_line : 0, args: decl_column ? *decl_column : 0);
2469
2470 SymbolFileDWARF *dwarf = die.GetDWARF();
2471 // Supply the type _only_ if it has already been parsed
2472 Type *func_type = dwarf->GetDIEToType().lookup(Val: die.GetDIE());
2473
2474 assert(func_type == nullptr || func_type != DIE_IS_BEING_PARSED);
2475
2476 const user_id_t func_user_id = die.GetID();
2477 func_sp =
2478 std::make_shared<Function>(args: &comp_unit,
2479 args: func_user_id, // UserID is the DIE offset
2480 args: func_user_id, args&: func_name, args&: func_type,
2481 args: func_range); // first address range
2482
2483 if (func_sp.get() != nullptr) {
2484 if (frame_base.IsValid())
2485 func_sp->GetFrameBaseExpression() = frame_base;
2486 comp_unit.AddFunction(function_sp&: func_sp);
2487 return func_sp.get();
2488 }
2489 }
2490 return nullptr;
2491}
2492
2493namespace {
2494/// Parsed form of all attributes that are relevant for parsing Objective-C
2495/// properties.
2496struct PropertyAttributes {
2497 explicit PropertyAttributes(const DWARFDIE &die);
2498 const char *prop_name = nullptr;
2499 const char *prop_getter_name = nullptr;
2500 const char *prop_setter_name = nullptr;
2501 /// \see clang::ObjCPropertyAttribute
2502 uint32_t prop_attributes = 0;
2503};
2504
2505struct DiscriminantValue {
2506 explicit DiscriminantValue(const DWARFDIE &die, ModuleSP module_sp);
2507
2508 uint32_t byte_offset;
2509 uint32_t byte_size;
2510 DWARFFormValue type_ref;
2511};
2512
2513struct VariantMember {
2514 explicit VariantMember(DWARFDIE &die, ModuleSP module_sp);
2515 bool IsDefault() const;
2516
2517 std::optional<uint32_t> discr_value;
2518 DWARFFormValue type_ref;
2519 ConstString variant_name;
2520 uint32_t byte_offset;
2521 ConstString GetName() const;
2522};
2523
2524struct VariantPart {
2525 explicit VariantPart(const DWARFDIE &die, const DWARFDIE &parent_die,
2526 ModuleSP module_sp);
2527
2528 std::vector<VariantMember> &members();
2529
2530 DiscriminantValue &discriminant();
2531
2532private:
2533 std::vector<VariantMember> _members;
2534 DiscriminantValue _discriminant;
2535};
2536
2537} // namespace
2538
2539ConstString VariantMember::GetName() const { return this->variant_name; }
2540
2541bool VariantMember::IsDefault() const { return !discr_value; }
2542
2543VariantMember::VariantMember(DWARFDIE &die, lldb::ModuleSP module_sp) {
2544 assert(die.Tag() == llvm::dwarf::DW_TAG_variant);
2545 this->discr_value =
2546 die.GetAttributeValueAsOptionalUnsigned(attr: DW_AT_discr_value);
2547
2548 for (auto child_die : die.children()) {
2549 switch (child_die.Tag()) {
2550 case llvm::dwarf::DW_TAG_member: {
2551 DWARFAttributes attributes = child_die.GetAttributes();
2552 for (std::size_t i = 0; i < attributes.Size(); ++i) {
2553 DWARFFormValue form_value;
2554 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2555 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2556 switch (attr) {
2557 case DW_AT_name:
2558 variant_name = ConstString(form_value.AsCString());
2559 break;
2560 case DW_AT_type:
2561 type_ref = form_value;
2562 break;
2563
2564 case DW_AT_data_member_location:
2565 if (auto maybe_offset =
2566 ExtractDataMemberLocation(die, form_value, module_sp))
2567 byte_offset = *maybe_offset;
2568 break;
2569
2570 default:
2571 break;
2572 }
2573 }
2574 }
2575 break;
2576 }
2577 default:
2578 break;
2579 }
2580 break;
2581 }
2582}
2583
2584DiscriminantValue::DiscriminantValue(const DWARFDIE &die, ModuleSP module_sp) {
2585 auto referenced_die = die.GetReferencedDIE(attr: DW_AT_discr);
2586 DWARFAttributes attributes = referenced_die.GetAttributes();
2587 for (std::size_t i = 0; i < attributes.Size(); ++i) {
2588 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2589 DWARFFormValue form_value;
2590 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2591 switch (attr) {
2592 case DW_AT_type:
2593 type_ref = form_value;
2594 break;
2595 case DW_AT_data_member_location:
2596 if (auto maybe_offset =
2597 ExtractDataMemberLocation(die, form_value, module_sp))
2598 byte_offset = *maybe_offset;
2599 break;
2600 default:
2601 break;
2602 }
2603 }
2604 }
2605}
2606
2607VariantPart::VariantPart(const DWARFDIE &die, const DWARFDIE &parent_die,
2608 lldb::ModuleSP module_sp)
2609 : _members(), _discriminant(die, module_sp) {
2610
2611 for (auto child : die.children()) {
2612 if (child.Tag() == llvm::dwarf::DW_TAG_variant) {
2613 _members.push_back(x: VariantMember(child, module_sp));
2614 }
2615 }
2616}
2617
2618std::vector<VariantMember> &VariantPart::members() { return this->_members; }
2619
2620DiscriminantValue &VariantPart::discriminant() { return this->_discriminant; }
2621
2622DWARFASTParserClang::MemberAttributes::MemberAttributes(
2623 const DWARFDIE &die, const DWARFDIE &parent_die, ModuleSP module_sp) {
2624 DWARFAttributes attributes = die.GetAttributes();
2625 for (size_t i = 0; i < attributes.Size(); ++i) {
2626 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2627 DWARFFormValue form_value;
2628 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2629 switch (attr) {
2630 case DW_AT_name:
2631 name = form_value.AsCString();
2632 break;
2633 case DW_AT_type:
2634 encoding_form = form_value;
2635 break;
2636 case DW_AT_bit_offset:
2637 bit_offset = form_value.Signed();
2638 break;
2639 case DW_AT_bit_size:
2640 bit_size = form_value.Unsigned();
2641 break;
2642 case DW_AT_byte_size:
2643 byte_size = form_value.Unsigned();
2644 break;
2645 case DW_AT_const_value:
2646 const_value_form = form_value;
2647 break;
2648 case DW_AT_data_bit_offset:
2649 data_bit_offset = form_value.Unsigned();
2650 break;
2651 case DW_AT_data_member_location:
2652 if (auto maybe_offset =
2653 ExtractDataMemberLocation(die, form_value, module_sp))
2654 member_byte_offset = *maybe_offset;
2655 break;
2656
2657 case DW_AT_accessibility:
2658 accessibility =
2659 DWARFASTParser::GetAccessTypeFromDWARF(dwarf_accessibility: form_value.Unsigned());
2660 break;
2661 case DW_AT_artificial:
2662 is_artificial = form_value.Boolean();
2663 break;
2664 case DW_AT_declaration:
2665 is_declaration = form_value.Boolean();
2666 break;
2667 default:
2668 break;
2669 }
2670 }
2671 }
2672
2673 // Clang has a DWARF generation bug where sometimes it represents
2674 // fields that are references with bad byte size and bit size/offset
2675 // information such as:
2676 //
2677 // DW_AT_byte_size( 0x00 )
2678 // DW_AT_bit_size( 0x40 )
2679 // DW_AT_bit_offset( 0xffffffffffffffc0 )
2680 //
2681 // So check the bit offset to make sure it is sane, and if the values
2682 // are not sane, remove them. If we don't do this then we will end up
2683 // with a crash if we try to use this type in an expression when clang
2684 // becomes unhappy with its recycled debug info.
2685 if (byte_size.value_or(u: 0) == 0 && bit_offset < 0) {
2686 bit_size = 0;
2687 bit_offset = 0;
2688 }
2689}
2690
2691PropertyAttributes::PropertyAttributes(const DWARFDIE &die) {
2692
2693 DWARFAttributes attributes = die.GetAttributes();
2694 for (size_t i = 0; i < attributes.Size(); ++i) {
2695 const dw_attr_t attr = attributes.AttributeAtIndex(i);
2696 DWARFFormValue form_value;
2697 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2698 switch (attr) {
2699 case DW_AT_APPLE_property_name:
2700 prop_name = form_value.AsCString();
2701 break;
2702 case DW_AT_APPLE_property_getter:
2703 prop_getter_name = form_value.AsCString();
2704 break;
2705 case DW_AT_APPLE_property_setter:
2706 prop_setter_name = form_value.AsCString();
2707 break;
2708 case DW_AT_APPLE_property_attribute:
2709 prop_attributes = form_value.Unsigned();
2710 break;
2711 default:
2712 break;
2713 }
2714 }
2715 }
2716
2717 if (!prop_name)
2718 return;
2719 ConstString fixed_setter;
2720
2721 // Check if the property getter/setter were provided as full names.
2722 // We want basenames, so we extract them.
2723 if (prop_getter_name && prop_getter_name[0] == '-') {
2724 std::optional<const ObjCLanguage::MethodName> prop_getter_method =
2725 ObjCLanguage::MethodName::Create(name: prop_getter_name, strict: true);
2726 if (prop_getter_method)
2727 prop_getter_name =
2728 ConstString(prop_getter_method->GetSelector()).GetCString();
2729 }
2730
2731 if (prop_setter_name && prop_setter_name[0] == '-') {
2732 std::optional<const ObjCLanguage::MethodName> prop_setter_method =
2733 ObjCLanguage::MethodName::Create(name: prop_setter_name, strict: true);
2734 if (prop_setter_method)
2735 prop_setter_name =
2736 ConstString(prop_setter_method->GetSelector()).GetCString();
2737 }
2738
2739 // If the names haven't been provided, they need to be filled in.
2740 if (!prop_getter_name)
2741 prop_getter_name = prop_name;
2742 if (!prop_setter_name && prop_name[0] &&
2743 !(prop_attributes & DW_APPLE_PROPERTY_readonly)) {
2744 StreamString ss;
2745
2746 ss.Printf(format: "set%c%s:", toupper(c: prop_name[0]), &prop_name[1]);
2747
2748 fixed_setter.SetString(ss.GetString());
2749 prop_setter_name = fixed_setter.GetCString();
2750 }
2751}
2752
2753void DWARFASTParserClang::ParseObjCProperty(
2754 const DWARFDIE &die, const DWARFDIE &parent_die,
2755 const lldb_private::CompilerType &class_clang_type,
2756 DelayedPropertyList &delayed_properties) {
2757 // This function can only parse DW_TAG_APPLE_property.
2758 assert(die.Tag() == DW_TAG_APPLE_property);
2759
2760 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2761
2762 const MemberAttributes attrs(die, parent_die, module_sp);
2763 const PropertyAttributes propAttrs(die);
2764
2765 if (!propAttrs.prop_name) {
2766 module_sp->ReportError(format: "{0:x8}: DW_TAG_APPLE_property has no name.",
2767 args: die.GetID());
2768 return;
2769 }
2770
2771 Type *member_type = die.ResolveTypeUID(die: attrs.encoding_form.Reference());
2772 if (!member_type) {
2773 module_sp->ReportError(
2774 format: "{0:x8}: DW_TAG_APPLE_property '{1}' refers to type {2:x16}"
2775 " which was unable to be parsed",
2776 args: die.GetID(), args: propAttrs.prop_name,
2777 args: attrs.encoding_form.Reference().GetOffset());
2778 return;
2779 }
2780
2781 ClangASTMetadata metadata;
2782 metadata.SetUserID(die.GetID());
2783 delayed_properties.push_back(x: DelayedAddObjCClassProperty(
2784 class_clang_type, propAttrs.prop_name,
2785 member_type->GetLayoutCompilerType(), propAttrs.prop_setter_name,
2786 propAttrs.prop_getter_name, propAttrs.prop_attributes, &metadata));
2787}
2788
2789llvm::Expected<llvm::APInt> DWARFASTParserClang::ExtractIntFromFormValue(
2790 const CompilerType &int_type, const DWARFFormValue &form_value) const {
2791 clang::QualType qt = ClangUtil::GetQualType(ct: int_type);
2792 assert(qt->isIntegralOrEnumerationType());
2793 auto ts_ptr = int_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
2794 if (!ts_ptr)
2795 return llvm::createStringError(EC: llvm::inconvertibleErrorCode(),
2796 Msg: "TypeSystem not clang");
2797 TypeSystemClang &ts = *ts_ptr;
2798 clang::ASTContext &ast = ts.getASTContext();
2799
2800 const unsigned type_bits = ast.getIntWidth(T: qt);
2801 const bool is_unsigned = qt->isUnsignedIntegerType();
2802
2803 // The maximum int size supported at the moment by this function. Limited
2804 // by the uint64_t return type of DWARFFormValue::Signed/Unsigned.
2805 constexpr std::size_t max_bit_size = 64;
2806
2807 // For values bigger than 64 bit (e.g. __int128_t values),
2808 // DWARFFormValue's Signed/Unsigned functions will return wrong results so
2809 // emit an error for now.
2810 if (type_bits > max_bit_size) {
2811 auto msg = llvm::formatv(Fmt: "Can only parse integers with up to {0} bits, but "
2812 "given integer has {1} bits.",
2813 Vals: max_bit_size, Vals: type_bits);
2814 return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), S: msg.str());
2815 }
2816
2817 // Construct an APInt with the maximum bit size and the given integer.
2818 llvm::APInt result(max_bit_size, form_value.Unsigned(), !is_unsigned);
2819
2820 // Calculate how many bits are required to represent the input value.
2821 // For unsigned types, take the number of active bits in the APInt.
2822 // For signed types, ask APInt how many bits are required to represent the
2823 // signed integer.
2824 const unsigned required_bits =
2825 is_unsigned ? result.getActiveBits() : result.getSignificantBits();
2826
2827 // If the input value doesn't fit into the integer type, return an error.
2828 if (required_bits > type_bits) {
2829 std::string value_as_str = is_unsigned
2830 ? std::to_string(val: form_value.Unsigned())
2831 : std::to_string(val: form_value.Signed());
2832 auto msg = llvm::formatv(Fmt: "Can't store {0} value {1} in integer with {2} "
2833 "bits.",
2834 Vals: (is_unsigned ? "unsigned" : "signed"),
2835 Vals&: value_as_str, Vals: type_bits);
2836 return llvm::createStringError(EC: llvm::inconvertibleErrorCode(), S: msg.str());
2837 }
2838
2839 // Trim the result to the bit width our the int type.
2840 if (result.getBitWidth() > type_bits)
2841 result = result.trunc(width: type_bits);
2842 return result;
2843}
2844
2845void DWARFASTParserClang::CreateStaticMemberVariable(
2846 const DWARFDIE &die, const MemberAttributes &attrs,
2847 const lldb_private::CompilerType &class_clang_type) {
2848 Log *log = GetLog(mask: DWARFLog::TypeCompletion | DWARFLog::Lookups);
2849 assert(die.Tag() == DW_TAG_member || die.Tag() == DW_TAG_variable);
2850
2851 Type *var_type = die.ResolveTypeUID(die: attrs.encoding_form.Reference());
2852
2853 if (!var_type)
2854 return;
2855
2856 auto accessibility =
2857 attrs.accessibility == eAccessNone ? eAccessPublic : attrs.accessibility;
2858
2859 CompilerType ct = var_type->GetForwardCompilerType();
2860 clang::VarDecl *v = TypeSystemClang::AddVariableToRecordType(
2861 type: class_clang_type, name: attrs.name, var_type: ct, access: accessibility);
2862 if (!v) {
2863 LLDB_LOG(log, "Failed to add variable to the record type");
2864 return;
2865 }
2866
2867 bool unused;
2868 // TODO: Support float/double static members as well.
2869 if (!ct.IsIntegerOrEnumerationType(is_signed&: unused) || !attrs.const_value_form)
2870 return;
2871
2872 llvm::Expected<llvm::APInt> const_value_or_err =
2873 ExtractIntFromFormValue(int_type: ct, form_value: *attrs.const_value_form);
2874 if (!const_value_or_err) {
2875 LLDB_LOG_ERROR(log, const_value_or_err.takeError(),
2876 "Failed to add const value to variable {1}: {0}",
2877 v->getQualifiedNameAsString());
2878 return;
2879 }
2880
2881 TypeSystemClang::SetIntegerInitializerForVariable(var: v, init_value: *const_value_or_err);
2882}
2883
2884void DWARFASTParserClang::ParseSingleMember(
2885 const DWARFDIE &die, const DWARFDIE &parent_die,
2886 const lldb_private::CompilerType &class_clang_type,
2887 lldb::AccessType default_accessibility,
2888 lldb_private::ClangASTImporter::LayoutInfo &layout_info,
2889 FieldInfo &last_field_info) {
2890 // This function can only parse DW_TAG_member.
2891 assert(die.Tag() == DW_TAG_member);
2892
2893 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2894 const dw_tag_t tag = die.Tag();
2895 // Get the parent byte size so we can verify any members will fit
2896 const uint64_t parent_byte_size =
2897 parent_die.GetAttributeValueAsUnsigned(attr: DW_AT_byte_size, UINT64_MAX);
2898 const uint64_t parent_bit_size =
2899 parent_byte_size == UINT64_MAX ? UINT64_MAX : parent_byte_size * 8;
2900
2901 const MemberAttributes attrs(die, parent_die, module_sp);
2902
2903 // Handle static members, which are typically members without
2904 // locations. However, GCC doesn't emit DW_AT_data_member_location
2905 // for any union members (regardless of linkage).
2906 // Non-normative text pre-DWARFv5 recommends marking static
2907 // data members with an DW_AT_external flag. Clang emits this consistently
2908 // whereas GCC emits it only for static data members if not part of an
2909 // anonymous namespace. The flag that is consistently emitted for static
2910 // data members is DW_AT_declaration, so we check it instead.
2911 // The following block is only necessary to support DWARFv4 and earlier.
2912 // Starting with DWARFv5, static data members are marked DW_AT_variable so we
2913 // can consistently detect them on both GCC and Clang without below heuristic.
2914 if (attrs.member_byte_offset == UINT32_MAX &&
2915 attrs.data_bit_offset == UINT64_MAX && attrs.is_declaration) {
2916 CreateStaticMemberVariable(die, attrs, class_clang_type);
2917 return;
2918 }
2919
2920 Type *member_type = die.ResolveTypeUID(die: attrs.encoding_form.Reference());
2921 if (!member_type) {
2922 if (attrs.name)
2923 module_sp->ReportError(
2924 format: "{0:x8}: DW_TAG_member '{1}' refers to type {2:x16}"
2925 " which was unable to be parsed",
2926 args: die.GetID(), args: attrs.name, args: attrs.encoding_form.Reference().GetOffset());
2927 else
2928 module_sp->ReportError(format: "{0:x8}: DW_TAG_member refers to type {1:x16}"
2929 " which was unable to be parsed",
2930 args: die.GetID(),
2931 args: attrs.encoding_form.Reference().GetOffset());
2932 return;
2933 }
2934
2935 const uint64_t character_width = 8;
2936 const uint64_t word_width = 32;
2937 CompilerType member_clang_type = member_type->GetLayoutCompilerType();
2938
2939 const auto accessibility = attrs.accessibility == eAccessNone
2940 ? default_accessibility
2941 : attrs.accessibility;
2942
2943 uint64_t field_bit_offset = (attrs.member_byte_offset == UINT32_MAX
2944 ? 0
2945 : (attrs.member_byte_offset * 8ULL));
2946
2947 if (attrs.bit_size > 0) {
2948 FieldInfo this_field_info;
2949 this_field_info.bit_offset = field_bit_offset;
2950 this_field_info.bit_size = attrs.bit_size;
2951
2952 if (attrs.data_bit_offset != UINT64_MAX) {
2953 this_field_info.bit_offset = attrs.data_bit_offset;
2954 } else {
2955 auto byte_size = attrs.byte_size;
2956 if (!byte_size)
2957 byte_size = member_type->GetByteSize(exe_scope: nullptr);
2958
2959 ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2960 if (objfile->GetByteOrder() == eByteOrderLittle) {
2961 this_field_info.bit_offset += byte_size.value_or(u: 0) * 8;
2962 this_field_info.bit_offset -= (attrs.bit_offset + attrs.bit_size);
2963 } else {
2964 this_field_info.bit_offset += attrs.bit_offset;
2965 }
2966 }
2967
2968 // The ObjC runtime knows the byte offset but we still need to provide
2969 // the bit-offset in the layout. It just means something different then
2970 // what it does in C and C++. So we skip this check for ObjC types.
2971 //
2972 // We also skip this for fields of a union since they will all have a
2973 // zero offset.
2974 if (!TypeSystemClang::IsObjCObjectOrInterfaceType(type: class_clang_type) &&
2975 !(parent_die.Tag() == DW_TAG_union_type &&
2976 this_field_info.bit_offset == 0) &&
2977 ((this_field_info.bit_offset >= parent_bit_size) ||
2978 (last_field_info.IsBitfield() &&
2979 !last_field_info.NextBitfieldOffsetIsValid(
2980 next_bit_offset: this_field_info.bit_offset)))) {
2981 ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2982 objfile->GetModule()->ReportWarning(
2983 format: "{0:x16}: {1} bitfield named \"{2}\" has invalid "
2984 "bit offset ({3:x8}) member will be ignored. Please file a bug "
2985 "against the "
2986 "compiler and include the preprocessed output for {4}\n",
2987 args: die.GetID(), args: DW_TAG_value_to_name(val: tag), args: attrs.name,
2988 args&: this_field_info.bit_offset, args: GetUnitName(die: parent_die).c_str());
2989 return;
2990 }
2991
2992 // Update the field bit offset we will report for layout
2993 field_bit_offset = this_field_info.bit_offset;
2994
2995 // Objective-C has invalid DW_AT_bit_offset values in older
2996 // versions of clang, so we have to be careful and only insert
2997 // unnamed bitfields if we have a new enough clang.
2998 bool detect_unnamed_bitfields = true;
2999
3000 if (TypeSystemClang::IsObjCObjectOrInterfaceType(type: class_clang_type))
3001 detect_unnamed_bitfields =
3002 die.GetCU()->Supports_unnamed_objc_bitfields();
3003
3004 if (detect_unnamed_bitfields) {
3005 std::optional<FieldInfo> unnamed_field_info;
3006 uint64_t last_field_end =
3007 last_field_info.bit_offset + last_field_info.bit_size;
3008
3009 if (!last_field_info.IsBitfield()) {
3010 // The last field was not a bit-field...
3011 // but if it did take up the entire word then we need to extend
3012 // last_field_end so the bit-field does not step into the last
3013 // fields padding.
3014 if (last_field_end != 0 && ((last_field_end % word_width) != 0))
3015 last_field_end += word_width - (last_field_end % word_width);
3016 }
3017
3018 if (ShouldCreateUnnamedBitfield(last_field_info, last_field_end,
3019 this_field_info, layout_info)) {
3020 unnamed_field_info = FieldInfo{};
3021 unnamed_field_info->bit_size =
3022 this_field_info.bit_offset - last_field_end;
3023 unnamed_field_info->bit_offset = last_field_end;
3024 }
3025
3026 if (unnamed_field_info) {
3027 clang::FieldDecl *unnamed_bitfield_decl =
3028 TypeSystemClang::AddFieldToRecordType(
3029 type: class_clang_type, name: llvm::StringRef(),
3030 field_type: m_ast.GetBuiltinTypeForEncodingAndBitSize(encoding: eEncodingSint,
3031 bit_size: word_width),
3032 access: accessibility, bitfield_bit_size: unnamed_field_info->bit_size);
3033
3034 layout_info.field_offsets.insert(KV: std::make_pair(
3035 x&: unnamed_bitfield_decl, y&: unnamed_field_info->bit_offset));
3036 }
3037 }
3038
3039 last_field_info = this_field_info;
3040 last_field_info.SetIsBitfield(true);
3041 } else {
3042 last_field_info.bit_offset = field_bit_offset;
3043
3044 if (std::optional<uint64_t> clang_type_size =
3045 member_type->GetByteSize(exe_scope: nullptr)) {
3046 last_field_info.bit_size = *clang_type_size * character_width;
3047 }
3048
3049 last_field_info.SetIsBitfield(false);
3050 }
3051
3052 // Don't turn artificial members such as vtable pointers into real FieldDecls
3053 // in our AST. Clang will re-create those articial members and they would
3054 // otherwise just overlap in the layout with the FieldDecls we add here.
3055 // This needs to be done after updating FieldInfo which keeps track of where
3056 // field start/end so we don't later try to fill the space of this
3057 // artificial member with (unnamed bitfield) padding.
3058 if (attrs.is_artificial && ShouldIgnoreArtificialField(FieldName: attrs.name)) {
3059 last_field_info.SetIsArtificial(true);
3060 return;
3061 }
3062
3063 if (!member_clang_type.IsCompleteType())
3064 member_clang_type.GetCompleteType();
3065
3066 {
3067 // Older versions of clang emit the same DWARF for array[0] and array[1]. If
3068 // the current field is at the end of the structure, then there is
3069 // definitely no room for extra elements and we override the type to
3070 // array[0]. This was fixed by f454dfb6b5af.
3071 CompilerType member_array_element_type;
3072 uint64_t member_array_size;
3073 bool member_array_is_incomplete;
3074
3075 if (member_clang_type.IsArrayType(element_type: &member_array_element_type,
3076 size: &member_array_size,
3077 is_incomplete: &member_array_is_incomplete) &&
3078 !member_array_is_incomplete) {
3079 uint64_t parent_byte_size =
3080 parent_die.GetAttributeValueAsUnsigned(attr: DW_AT_byte_size, UINT64_MAX);
3081
3082 if (attrs.member_byte_offset >= parent_byte_size) {
3083 if (member_array_size != 1 &&
3084 (member_array_size != 0 ||
3085 attrs.member_byte_offset > parent_byte_size)) {
3086 module_sp->ReportError(
3087 format: "{0:x8}: DW_TAG_member '{1}' refers to type {2:x16}"
3088 " which extends beyond the bounds of {3:x8}",
3089 args: die.GetID(), args: attrs.name,
3090 args: attrs.encoding_form.Reference().GetOffset(), args: parent_die.GetID());
3091 }
3092
3093 member_clang_type =
3094 m_ast.CreateArrayType(element_type: member_array_element_type, element_count: 0, is_vector: false);
3095 }
3096 }
3097 }
3098
3099 TypeSystemClang::RequireCompleteType(type: member_clang_type);
3100
3101 clang::FieldDecl *field_decl = TypeSystemClang::AddFieldToRecordType(
3102 type: class_clang_type, name: attrs.name, field_type: member_clang_type, access: accessibility,
3103 bitfield_bit_size: attrs.bit_size);
3104
3105 m_ast.SetMetadataAsUserID(field_decl, die.GetID());
3106
3107 layout_info.field_offsets.insert(
3108 KV: std::make_pair(x&: field_decl, y&: field_bit_offset));
3109}
3110
3111bool DWARFASTParserClang::ParseChildMembers(
3112 const DWARFDIE &parent_die, CompilerType &class_clang_type,
3113 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes,
3114 std::vector<DWARFDIE> &member_function_dies,
3115 std::vector<DWARFDIE> &contained_type_dies,
3116 DelayedPropertyList &delayed_properties,
3117 const AccessType default_accessibility,
3118 ClangASTImporter::LayoutInfo &layout_info) {
3119 if (!parent_die)
3120 return false;
3121
3122 FieldInfo last_field_info;
3123
3124 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
3125 auto ts = class_clang_type.GetTypeSystem();
3126 auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
3127 if (ast == nullptr)
3128 return false;
3129
3130 for (DWARFDIE die : parent_die.children()) {
3131 dw_tag_t tag = die.Tag();
3132
3133 switch (tag) {
3134 case DW_TAG_APPLE_property:
3135 ParseObjCProperty(die, parent_die, class_clang_type, delayed_properties);
3136 break;
3137
3138 case DW_TAG_variant_part:
3139 if (die.GetCU()->GetDWARFLanguageType() == eLanguageTypeRust) {
3140 ParseRustVariantPart(die, parent_die, class_clang_type,
3141 default_accesibility: default_accessibility, layout_info);
3142 }
3143 break;
3144
3145 case DW_TAG_variable: {
3146 const MemberAttributes attrs(die, parent_die, module_sp);
3147 CreateStaticMemberVariable(die, attrs, class_clang_type);
3148 } break;
3149 case DW_TAG_member:
3150 ParseSingleMember(die, parent_die, class_clang_type,
3151 default_accessibility, layout_info, last_field_info);
3152 break;
3153
3154 case DW_TAG_subprogram:
3155 // Let the type parsing code handle this one for us.
3156 member_function_dies.push_back(x: die);
3157 break;
3158
3159 case DW_TAG_inheritance:
3160 ParseInheritance(die, parent_die, class_clang_type, default_accessibility,
3161 module_sp, base_classes, layout_info);
3162 break;
3163
3164 default:
3165 if (llvm::dwarf::isType(T: tag))
3166 contained_type_dies.push_back(x: die);
3167 break;
3168 }
3169 }
3170
3171 return true;
3172}
3173
3174size_t DWARFASTParserClang::ParseChildParameters(
3175 clang::DeclContext *containing_decl_ctx, const DWARFDIE &parent_die,
3176 bool skip_artificial, bool &is_static, bool &is_variadic,
3177 bool &has_template_params, std::vector<CompilerType> &function_param_types,
3178 std::vector<clang::ParmVarDecl *> &function_param_decls,
3179 unsigned &type_quals) {
3180 if (!parent_die)
3181 return 0;
3182
3183 size_t arg_idx = 0;
3184 for (DWARFDIE die : parent_die.children()) {
3185 const dw_tag_t tag = die.Tag();
3186 switch (tag) {
3187 case DW_TAG_formal_parameter: {
3188 DWARFAttributes attributes = die.GetAttributes();
3189 if (attributes.Size() == 0) {
3190 arg_idx++;
3191 break;
3192 }
3193
3194 const char *name = nullptr;
3195 DWARFFormValue param_type_die_form;
3196 bool is_artificial = false;
3197 // one of None, Auto, Register, Extern, Static, PrivateExtern
3198
3199 clang::StorageClass storage = clang::SC_None;
3200 uint32_t i;
3201 for (i = 0; i < attributes.Size(); ++i) {
3202 const dw_attr_t attr = attributes.AttributeAtIndex(i);
3203 DWARFFormValue form_value;
3204 if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3205 switch (attr) {
3206 case DW_AT_name:
3207 name = form_value.AsCString();
3208 break;
3209 case DW_AT_type:
3210 param_type_die_form = form_value;
3211 break;
3212 case DW_AT_artificial:
3213 is_artificial = form_value.Boolean();
3214 break;
3215 case DW_AT_location:
3216 case DW_AT_const_value:
3217 case DW_AT_default_value:
3218 case DW_AT_description:
3219 case DW_AT_endianity:
3220 case DW_AT_is_optional:
3221 case DW_AT_segment:
3222 case DW_AT_variable_parameter:
3223 default:
3224 case DW_AT_abstract_origin:
3225 case DW_AT_sibling:
3226 break;
3227 }
3228 }
3229 }
3230
3231 bool skip = false;
3232 if (skip_artificial && is_artificial) {
3233 // In order to determine if a C++ member function is "const" we
3234 // have to look at the const-ness of "this"...
3235 if (arg_idx == 0 &&
3236 DeclKindIsCXXClass(decl_kind: containing_decl_ctx->getDeclKind()) &&
3237 // Often times compilers omit the "this" name for the
3238 // specification DIEs, so we can't rely upon the name being in
3239 // the formal parameter DIE...
3240 (name == nullptr || ::strcmp(s1: name, s2: "this") == 0)) {
3241 Type *this_type = die.ResolveTypeUID(die: param_type_die_form.Reference());
3242 if (this_type) {
3243 uint32_t encoding_mask = this_type->GetEncodingMask();
3244 if (encoding_mask & Type::eEncodingIsPointerUID) {
3245 is_static = false;
3246
3247 if (encoding_mask & (1u << Type::eEncodingIsConstUID))
3248 type_quals |= clang::Qualifiers::Const;
3249 if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
3250 type_quals |= clang::Qualifiers::Volatile;
3251 }
3252 }
3253 }
3254 skip = true;
3255 }
3256
3257 if (!skip) {
3258 Type *type = die.ResolveTypeUID(die: param_type_die_form.Reference());
3259 if (type) {
3260 function_param_types.push_back(x: type->GetForwardCompilerType());
3261
3262 clang::ParmVarDecl *param_var_decl = m_ast.CreateParameterDeclaration(
3263 decl_ctx: containing_decl_ctx, owning_module: GetOwningClangModule(die), name,
3264 param_type: type->GetForwardCompilerType(), storage);
3265 assert(param_var_decl);
3266 function_param_decls.push_back(x: param_var_decl);
3267
3268 m_ast.SetMetadataAsUserID(param_var_decl, die.GetID());
3269 }
3270 }
3271 arg_idx++;
3272 } break;
3273
3274 case DW_TAG_unspecified_parameters:
3275 is_variadic = true;
3276 break;
3277
3278 case DW_TAG_template_type_parameter:
3279 case DW_TAG_template_value_parameter:
3280 case DW_TAG_GNU_template_parameter_pack:
3281 // The one caller of this was never using the template_param_infos, and
3282 // the local variable was taking up a large amount of stack space in
3283 // SymbolFileDWARF::ParseType() so this was removed. If we ever need the
3284 // template params back, we can add them back.
3285 // ParseTemplateDIE (dwarf_cu, die, template_param_infos);
3286 has_template_params = true;
3287 break;
3288
3289 default:
3290 break;
3291 }
3292 }
3293 return arg_idx;
3294}
3295
3296clang::Decl *DWARFASTParserClang::GetClangDeclForDIE(const DWARFDIE &die) {
3297 if (!die)
3298 return nullptr;
3299
3300 switch (die.Tag()) {
3301 case DW_TAG_constant:
3302 case DW_TAG_formal_parameter:
3303 case DW_TAG_imported_declaration:
3304 case DW_TAG_imported_module:
3305 break;
3306 case DW_TAG_variable:
3307 // This means 'die' is a C++ static data member.
3308 // We don't want to create decls for such members
3309 // here.
3310 if (auto parent = die.GetParent();
3311 parent.IsValid() && TagIsRecordType(tag: parent.Tag()))
3312 return nullptr;
3313 break;
3314 default:
3315 return nullptr;
3316 }
3317
3318 DIEToDeclMap::iterator cache_pos = m_die_to_decl.find(Val: die.GetDIE());
3319 if (cache_pos != m_die_to_decl.end())
3320 return cache_pos->second;
3321
3322 if (DWARFDIE spec_die = die.GetReferencedDIE(attr: DW_AT_specification)) {
3323 clang::Decl *decl = GetClangDeclForDIE(die: spec_die);
3324 m_die_to_decl[die.GetDIE()] = decl;
3325 return decl;
3326 }
3327
3328 if (DWARFDIE abstract_origin_die =
3329 die.GetReferencedDIE(attr: DW_AT_abstract_origin)) {
3330 clang::Decl *decl = GetClangDeclForDIE(die: abstract_origin_die);
3331 m_die_to_decl[die.GetDIE()] = decl;
3332 return decl;
3333 }
3334
3335 clang::Decl *decl = nullptr;
3336 switch (die.Tag()) {
3337 case DW_TAG_variable:
3338 case DW_TAG_constant:
3339 case DW_TAG_formal_parameter: {
3340 SymbolFileDWARF *dwarf = die.GetDWARF();
3341 Type *type = GetTypeForDIE(die);
3342 if (dwarf && type) {
3343 const char *name = die.GetName();
3344 clang::DeclContext *decl_context =
3345 TypeSystemClang::DeclContextGetAsDeclContext(
3346 dc: dwarf->GetDeclContextContainingUID(uid: die.GetID()));
3347 decl = m_ast.CreateVariableDeclaration(
3348 decl_context, owning_module: GetOwningClangModule(die), name,
3349 type: ClangUtil::GetQualType(ct: type->GetForwardCompilerType()));
3350 }
3351 break;
3352 }
3353 case DW_TAG_imported_declaration: {
3354 SymbolFileDWARF *dwarf = die.GetDWARF();
3355 DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(attr: DW_AT_import);
3356 if (imported_uid) {
3357 CompilerDecl imported_decl = SymbolFileDWARF::GetDecl(die: imported_uid);
3358 if (imported_decl) {
3359 clang::DeclContext *decl_context =
3360 TypeSystemClang::DeclContextGetAsDeclContext(
3361 dc: dwarf->GetDeclContextContainingUID(uid: die.GetID()));
3362 if (clang::NamedDecl *clang_imported_decl =
3363 llvm::dyn_cast<clang::NamedDecl>(
3364 Val: (clang::Decl *)imported_decl.GetOpaqueDecl()))
3365 decl = m_ast.CreateUsingDeclaration(
3366 current_decl_ctx: decl_context, owning_module: OptionalClangModuleID(), target: clang_imported_decl);
3367 }
3368 }
3369 break;
3370 }
3371 case DW_TAG_imported_module: {
3372 SymbolFileDWARF *dwarf = die.GetDWARF();
3373 DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(attr: DW_AT_import);
3374
3375 if (imported_uid) {
3376 CompilerDeclContext imported_decl_ctx =
3377 SymbolFileDWARF::GetDeclContext(die: imported_uid);
3378 if (imported_decl_ctx) {
3379 clang::DeclContext *decl_context =
3380 TypeSystemClang::DeclContextGetAsDeclContext(
3381 dc: dwarf->GetDeclContextContainingUID(uid: die.GetID()));
3382 if (clang::NamespaceDecl *ns_decl =
3383 TypeSystemClang::DeclContextGetAsNamespaceDecl(
3384 dc: imported_decl_ctx))
3385 decl = m_ast.CreateUsingDirectiveDeclaration(
3386 decl_ctx: decl_context, owning_module: OptionalClangModuleID(), ns_decl);
3387 }
3388 }
3389 break;
3390 }
3391 default:
3392 break;
3393 }
3394
3395 m_die_to_decl[die.GetDIE()] = decl;
3396
3397 return decl;
3398}
3399
3400clang::DeclContext *
3401DWARFASTParserClang::GetClangDeclContextForDIE(const DWARFDIE &die) {
3402 if (die) {
3403 clang::DeclContext *decl_ctx = GetCachedClangDeclContextForDIE(die);
3404 if (decl_ctx)
3405 return decl_ctx;
3406
3407 bool try_parsing_type = true;
3408 switch (die.Tag()) {
3409 case DW_TAG_compile_unit:
3410 case DW_TAG_partial_unit:
3411 decl_ctx = m_ast.GetTranslationUnitDecl();
3412 try_parsing_type = false;
3413 break;
3414
3415 case DW_TAG_namespace:
3416 decl_ctx = ResolveNamespaceDIE(die);
3417 try_parsing_type = false;
3418 break;
3419
3420 case DW_TAG_imported_declaration:
3421 decl_ctx = ResolveImportedDeclarationDIE(die);
3422 try_parsing_type = false;
3423 break;
3424
3425 case DW_TAG_lexical_block:
3426 decl_ctx = GetDeclContextForBlock(die);
3427 try_parsing_type = false;
3428 break;
3429
3430 default:
3431 break;
3432 }
3433
3434 if (decl_ctx == nullptr && try_parsing_type) {
3435 Type *type = die.GetDWARF()->ResolveType(die);
3436 if (type)
3437 decl_ctx = GetCachedClangDeclContextForDIE(die);
3438 }
3439
3440 if (decl_ctx) {
3441 LinkDeclContextToDIE(decl_ctx, die);
3442 return decl_ctx;
3443 }
3444 }
3445 return nullptr;
3446}
3447
3448OptionalClangModuleID
3449DWARFASTParserClang::GetOwningClangModule(const DWARFDIE &die) {
3450 if (!die.IsValid())
3451 return {};
3452
3453 for (DWARFDIE parent = die.GetParent(); parent.IsValid();
3454 parent = parent.GetParent()) {
3455 const dw_tag_t tag = parent.Tag();
3456 if (tag == DW_TAG_module) {
3457 DWARFDIE module_die = parent;
3458 auto it = m_die_to_module.find(Val: module_die.GetDIE());
3459 if (it != m_die_to_module.end())
3460 return it->second;
3461 const char *name =
3462 module_die.GetAttributeValueAsString(attr: DW_AT_name, fail_value: nullptr);
3463 if (!name)
3464 return {};
3465
3466 OptionalClangModuleID id =
3467 m_ast.GetOrCreateClangModule(name, parent: GetOwningClangModule(die: module_die));
3468 m_die_to_module.insert(KV: {module_die.GetDIE(), id});
3469 return id;
3470 }
3471 }
3472 return {};
3473}
3474
3475static bool IsSubroutine(const DWARFDIE &die) {
3476 switch (die.Tag()) {
3477 case DW_TAG_subprogram:
3478 case DW_TAG_inlined_subroutine:
3479 return true;
3480 default:
3481 return false;
3482 }
3483}
3484
3485static DWARFDIE GetContainingFunctionWithAbstractOrigin(const DWARFDIE &die) {
3486 for (DWARFDIE candidate = die; candidate; candidate = candidate.GetParent()) {
3487 if (IsSubroutine(die: candidate)) {
3488 if (candidate.GetReferencedDIE(attr: DW_AT_abstract_origin)) {
3489 return candidate;
3490 } else {
3491 return DWARFDIE();
3492 }
3493 }
3494 }
3495 assert(0 && "Shouldn't call GetContainingFunctionWithAbstractOrigin on "
3496 "something not in a function");
3497 return DWARFDIE();
3498}
3499
3500static DWARFDIE FindAnyChildWithAbstractOrigin(const DWARFDIE &context) {
3501 for (DWARFDIE candidate : context.children()) {
3502 if (candidate.GetReferencedDIE(attr: DW_AT_abstract_origin)) {
3503 return candidate;
3504 }
3505 }
3506 return DWARFDIE();
3507}
3508
3509static DWARFDIE FindFirstChildWithAbstractOrigin(const DWARFDIE &block,
3510 const DWARFDIE &function) {
3511 assert(IsSubroutine(function));
3512 for (DWARFDIE context = block; context != function.GetParent();
3513 context = context.GetParent()) {
3514 assert(!IsSubroutine(context) || context == function);
3515 if (DWARFDIE child = FindAnyChildWithAbstractOrigin(context)) {
3516 return child;
3517 }
3518 }
3519 return DWARFDIE();
3520}
3521
3522clang::DeclContext *
3523DWARFASTParserClang::GetDeclContextForBlock(const DWARFDIE &die) {
3524 assert(die.Tag() == DW_TAG_lexical_block);
3525 DWARFDIE containing_function_with_abstract_origin =
3526 GetContainingFunctionWithAbstractOrigin(die);
3527 if (!containing_function_with_abstract_origin) {
3528 return (clang::DeclContext *)ResolveBlockDIE(die);
3529 }
3530 DWARFDIE child = FindFirstChildWithAbstractOrigin(
3531 block: die, function: containing_function_with_abstract_origin);
3532 CompilerDeclContext decl_context =
3533 GetDeclContextContainingUIDFromDWARF(die: child);
3534 return (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
3535}
3536
3537clang::BlockDecl *DWARFASTParserClang::ResolveBlockDIE(const DWARFDIE &die) {
3538 if (die && die.Tag() == DW_TAG_lexical_block) {
3539 clang::BlockDecl *decl =
3540 llvm::cast_or_null<clang::BlockDecl>(Val: m_die_to_decl_ctx[die.GetDIE()]);
3541
3542 if (!decl) {
3543 DWARFDIE decl_context_die;
3544 clang::DeclContext *decl_context =
3545 GetClangDeclContextContainingDIE(die, decl_ctx_die: &decl_context_die);
3546 decl =
3547 m_ast.CreateBlockDeclaration(ctx: decl_context, owning_module: GetOwningClangModule(die));
3548
3549 if (decl)
3550 LinkDeclContextToDIE(decl_ctx: (clang::DeclContext *)decl, die);
3551 }
3552
3553 return decl;
3554 }
3555 return nullptr;
3556}
3557
3558clang::NamespaceDecl *
3559DWARFASTParserClang::ResolveNamespaceDIE(const DWARFDIE &die) {
3560 if (die && die.Tag() == DW_TAG_namespace) {
3561 // See if we already parsed this namespace DIE and associated it with a
3562 // uniqued namespace declaration
3563 clang::NamespaceDecl *namespace_decl =
3564 static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die.GetDIE()]);
3565 if (namespace_decl)
3566 return namespace_decl;
3567 else {
3568 const char *namespace_name = die.GetName();
3569 clang::DeclContext *containing_decl_ctx =
3570 GetClangDeclContextContainingDIE(die, decl_ctx_die: nullptr);
3571 bool is_inline =
3572 die.GetAttributeValueAsUnsigned(attr: DW_AT_export_symbols, fail_value: 0) != 0;
3573
3574 namespace_decl = m_ast.GetUniqueNamespaceDeclaration(
3575 name: namespace_name, decl_ctx: containing_decl_ctx, owning_module: GetOwningClangModule(die),
3576 is_inline);
3577
3578 if (namespace_decl)
3579 LinkDeclContextToDIE(decl_ctx: (clang::DeclContext *)namespace_decl, die);
3580 return namespace_decl;
3581 }
3582 }
3583 return nullptr;
3584}
3585
3586clang::NamespaceDecl *
3587DWARFASTParserClang::ResolveImportedDeclarationDIE(const DWARFDIE &die) {
3588 assert(die && die.Tag() == DW_TAG_imported_declaration);
3589
3590 // See if we cached a NamespaceDecl for this imported declaration
3591 // already
3592 auto it = m_die_to_decl_ctx.find(Val: die.GetDIE());
3593 if (it != m_die_to_decl_ctx.end())
3594 return static_cast<clang::NamespaceDecl *>(it->getSecond());
3595
3596 clang::NamespaceDecl *namespace_decl = nullptr;
3597
3598 const DWARFDIE imported_uid =
3599 die.GetAttributeValueAsReferenceDIE(attr: DW_AT_import);
3600 if (!imported_uid)
3601 return nullptr;
3602
3603 switch (imported_uid.Tag()) {
3604 case DW_TAG_imported_declaration:
3605 namespace_decl = ResolveImportedDeclarationDIE(die: imported_uid);
3606 break;
3607 case DW_TAG_namespace:
3608 namespace_decl = ResolveNamespaceDIE(die: imported_uid);
3609 break;
3610 default:
3611 return nullptr;
3612 }
3613
3614 if (!namespace_decl)
3615 return nullptr;
3616
3617 LinkDeclContextToDIE(namespace_decl, die);
3618
3619 return namespace_decl;
3620}
3621
3622clang::DeclContext *DWARFASTParserClang::GetClangDeclContextContainingDIE(
3623 const DWARFDIE &die, DWARFDIE *decl_ctx_die_copy) {
3624 SymbolFileDWARF *dwarf = die.GetDWARF();
3625
3626 DWARFDIE decl_ctx_die = dwarf->GetDeclContextDIEContainingDIE(die);
3627
3628 if (decl_ctx_die_copy)
3629 *decl_ctx_die_copy = decl_ctx_die;
3630
3631 if (decl_ctx_die) {
3632 clang::DeclContext *clang_decl_ctx =
3633 GetClangDeclContextForDIE(die: decl_ctx_die);
3634 if (clang_decl_ctx)
3635 return clang_decl_ctx;
3636 }
3637 return m_ast.GetTranslationUnitDecl();
3638}
3639
3640clang::DeclContext *
3641DWARFASTParserClang::GetCachedClangDeclContextForDIE(const DWARFDIE &die) {
3642 if (die) {
3643 DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find(Val: die.GetDIE());
3644 if (pos != m_die_to_decl_ctx.end())
3645 return pos->second;
3646 }
3647 return nullptr;
3648}
3649
3650void DWARFASTParserClang::LinkDeclContextToDIE(clang::DeclContext *decl_ctx,
3651 const DWARFDIE &die) {
3652 m_die_to_decl_ctx[die.GetDIE()] = decl_ctx;
3653 // There can be many DIEs for a single decl context
3654 // m_decl_ctx_to_die[decl_ctx].insert(die.GetDIE());
3655 m_decl_ctx_to_die.insert(x: std::make_pair(x&: decl_ctx, y: die));
3656}
3657
3658bool DWARFASTParserClang::CopyUniqueClassMethodTypes(
3659 const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die,
3660 lldb_private::Type *class_type, std::vector<DWARFDIE> &failures) {
3661 if (!class_type || !src_class_die || !dst_class_die)
3662 return false;
3663 if (src_class_die.Tag() != dst_class_die.Tag())
3664 return false;
3665
3666 // We need to complete the class type so we can get all of the method types
3667 // parsed so we can then unique those types to their equivalent counterparts
3668 // in "dst_cu" and "dst_class_die"
3669 class_type->GetFullCompilerType();
3670
3671 auto gather = [](DWARFDIE die, UniqueCStringMap<DWARFDIE> &map,
3672 UniqueCStringMap<DWARFDIE> &map_artificial) {
3673 if (die.Tag() != DW_TAG_subprogram)
3674 return;
3675 // Make sure this is a declaration and not a concrete instance by looking
3676 // for DW_AT_declaration set to 1. Sometimes concrete function instances are
3677 // placed inside the class definitions and shouldn't be included in the list
3678 // of things that are tracking here.
3679 if (die.GetAttributeValueAsUnsigned(attr: DW_AT_declaration, fail_value: 0) != 1)
3680 return;
3681
3682 if (const char *name = die.GetMangledName()) {
3683 ConstString const_name(name);
3684 if (die.GetAttributeValueAsUnsigned(attr: DW_AT_artificial, fail_value: 0))
3685 map_artificial.Append(unique_cstr: const_name, value: die);
3686 else
3687 map.Append(unique_cstr: const_name, value: die);
3688 }
3689 };
3690
3691 UniqueCStringMap<DWARFDIE> src_name_to_die;
3692 UniqueCStringMap<DWARFDIE> dst_name_to_die;
3693 UniqueCStringMap<DWARFDIE> src_name_to_die_artificial;
3694 UniqueCStringMap<DWARFDIE> dst_name_to_die_artificial;
3695 for (DWARFDIE src_die = src_class_die.GetFirstChild(); src_die.IsValid();
3696 src_die = src_die.GetSibling()) {
3697 gather(src_die, src_name_to_die, src_name_to_die_artificial);
3698 }
3699 for (DWARFDIE dst_die = dst_class_die.GetFirstChild(); dst_die.IsValid();
3700 dst_die = dst_die.GetSibling()) {
3701 gather(dst_die, dst_name_to_die, dst_name_to_die_artificial);
3702 }
3703 const uint32_t src_size = src_name_to_die.GetSize();
3704 const uint32_t dst_size = dst_name_to_die.GetSize();
3705
3706 // Is everything kosher so we can go through the members at top speed?
3707 bool fast_path = true;
3708
3709 if (src_size != dst_size)
3710 fast_path = false;
3711
3712 uint32_t idx;
3713
3714 if (fast_path) {
3715 for (idx = 0; idx < src_size; ++idx) {
3716 DWARFDIE src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
3717 DWARFDIE dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3718
3719 if (src_die.Tag() != dst_die.Tag())
3720 fast_path = false;
3721
3722 const char *src_name = src_die.GetMangledName();
3723 const char *dst_name = dst_die.GetMangledName();
3724
3725 // Make sure the names match
3726 if (src_name == dst_name || (strcmp(s1: src_name, s2: dst_name) == 0))
3727 continue;
3728
3729 fast_path = false;
3730 }
3731 }
3732
3733 DWARFASTParserClang *src_dwarf_ast_parser =
3734 static_cast<DWARFASTParserClang *>(
3735 SymbolFileDWARF::GetDWARFParser(unit&: *src_class_die.GetCU()));
3736 DWARFASTParserClang *dst_dwarf_ast_parser =
3737 static_cast<DWARFASTParserClang *>(
3738 SymbolFileDWARF::GetDWARFParser(unit&: *dst_class_die.GetCU()));
3739 auto link = [&](DWARFDIE src, DWARFDIE dst) {
3740 SymbolFileDWARF::DIEToTypePtr &die_to_type =
3741 dst_class_die.GetDWARF()->GetDIEToType();
3742 clang::DeclContext *dst_decl_ctx =
3743 dst_dwarf_ast_parser->m_die_to_decl_ctx[dst.GetDIE()];
3744 if (dst_decl_ctx)
3745 src_dwarf_ast_parser->LinkDeclContextToDIE(decl_ctx: dst_decl_ctx, die: src);
3746
3747 if (Type *src_child_type = die_to_type[src.GetDIE()])
3748 die_to_type[dst.GetDIE()] = src_child_type;
3749 };
3750
3751 // Now do the work of linking the DeclContexts and Types.
3752 if (fast_path) {
3753 // We can do this quickly. Just run across the tables index-for-index
3754 // since we know each node has matching names and tags.
3755 for (idx = 0; idx < src_size; ++idx) {
3756 link(src_name_to_die.GetValueAtIndexUnchecked(idx),
3757 dst_name_to_die.GetValueAtIndexUnchecked(idx));
3758 }
3759 } else {
3760 // We must do this slowly. For each member of the destination, look up a
3761 // member in the source with the same name, check its tag, and unique them
3762 // if everything matches up. Report failures.
3763
3764 if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty()) {
3765 src_name_to_die.Sort();
3766
3767 for (idx = 0; idx < dst_size; ++idx) {
3768 ConstString dst_name = dst_name_to_die.GetCStringAtIndex(idx);
3769 DWARFDIE dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3770 DWARFDIE src_die = src_name_to_die.Find(unique_cstr: dst_name, fail_value: DWARFDIE());
3771
3772 if (src_die && (src_die.Tag() == dst_die.Tag()))
3773 link(src_die, dst_die);
3774 else
3775 failures.push_back(x: dst_die);
3776 }
3777 }
3778 }
3779
3780 const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize();
3781 const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize();
3782
3783 if (src_size_artificial && dst_size_artificial) {
3784 dst_name_to_die_artificial.Sort();
3785
3786 for (idx = 0; idx < src_size_artificial; ++idx) {
3787 ConstString src_name_artificial =
3788 src_name_to_die_artificial.GetCStringAtIndex(idx);
3789 DWARFDIE src_die =
3790 src_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
3791 DWARFDIE dst_die =
3792 dst_name_to_die_artificial.Find(unique_cstr: src_name_artificial, fail_value: DWARFDIE());
3793
3794 // Both classes have the artificial types, link them
3795 if (dst_die)
3796 link(src_die, dst_die);
3797 }
3798 }
3799
3800 if (dst_size_artificial) {
3801 for (idx = 0; idx < dst_size_artificial; ++idx) {
3802 failures.push_back(
3803 x: dst_name_to_die_artificial.GetValueAtIndexUnchecked(idx));
3804 }
3805 }
3806
3807 return !failures.empty();
3808}
3809
3810bool DWARFASTParserClang::ShouldCreateUnnamedBitfield(
3811 FieldInfo const &last_field_info, uint64_t last_field_end,
3812 FieldInfo const &this_field_info,
3813 lldb_private::ClangASTImporter::LayoutInfo const &layout_info) const {
3814 // If we have a gap between the last_field_end and the current
3815 // field we have an unnamed bit-field.
3816 if (this_field_info.bit_offset <= last_field_end)
3817 return false;
3818
3819 // If we have a base class, we assume there is no unnamed
3820 // bit-field if either of the following is true:
3821 // (a) this is the first field since the gap can be
3822 // attributed to the members from the base class.
3823 // FIXME: This assumption is not correct if the first field of
3824 // the derived class is indeed an unnamed bit-field. We currently
3825 // do not have the machinary to track the offset of the last field
3826 // of classes we have seen before, so we are not handling this case.
3827 // (b) Or, the first member of the derived class was a vtable pointer.
3828 // In this case we don't want to create an unnamed bitfield either
3829 // since those will be inserted by clang later.
3830 const bool have_base = layout_info.base_offsets.size() != 0;
3831 const bool this_is_first_field =
3832 last_field_info.bit_offset == 0 && last_field_info.bit_size == 0;
3833 const bool first_field_is_vptr =
3834 last_field_info.bit_offset == 0 && last_field_info.IsArtificial();
3835
3836 if (have_base && (this_is_first_field || first_field_is_vptr))
3837 return false;
3838
3839 return true;
3840}
3841
3842void DWARFASTParserClang::ParseRustVariantPart(
3843 DWARFDIE &die, const DWARFDIE &parent_die, CompilerType &class_clang_type,
3844 const lldb::AccessType default_accesibility,
3845 ClangASTImporter::LayoutInfo &layout_info) {
3846 assert(die.Tag() == llvm::dwarf::DW_TAG_variant_part);
3847 assert(SymbolFileDWARF::GetLanguage(*die.GetCU()) ==
3848 LanguageType::eLanguageTypeRust);
3849
3850 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
3851
3852 VariantPart variants(die, parent_die, module_sp);
3853
3854 auto discriminant_type =
3855 die.ResolveTypeUID(die: variants.discriminant().type_ref.Reference());
3856
3857 auto decl_context = m_ast.GetDeclContextForType(type: class_clang_type);
3858
3859 auto inner_holder = m_ast.CreateRecordType(
3860 decl_ctx: decl_context, owning_module: OptionalClangModuleID(), access_type: lldb::eAccessPublic,
3861 name: std::string(
3862 llvm::formatv(Fmt: "{0}$Inner", Vals: class_clang_type.GetTypeName(BaseOnly: false))),
3863 kind: llvm::to_underlying(E: clang::TagTypeKind::Union), language: lldb::eLanguageTypeRust);
3864 m_ast.StartTagDeclarationDefinition(type: inner_holder);
3865 m_ast.SetIsPacked(inner_holder);
3866
3867 for (auto member : variants.members()) {
3868
3869 auto has_discriminant = !member.IsDefault();
3870
3871 auto member_type = die.ResolveTypeUID(die: member.type_ref.Reference());
3872
3873 auto field_type = m_ast.CreateRecordType(
3874 decl_ctx: m_ast.GetDeclContextForType(type: inner_holder), owning_module: OptionalClangModuleID(),
3875 access_type: lldb::eAccessPublic,
3876 name: std::string(llvm::formatv(Fmt: "{0}$Variant", Vals: member.GetName())),
3877 kind: llvm::to_underlying(E: clang::TagTypeKind::Struct),
3878 language: lldb::eLanguageTypeRust);
3879
3880 m_ast.StartTagDeclarationDefinition(type: field_type);
3881 auto offset = member.byte_offset;
3882
3883 if (has_discriminant) {
3884 m_ast.AddFieldToRecordType(
3885 type: field_type, name: "$discr$", field_type: discriminant_type->GetFullCompilerType(),
3886 access: lldb::eAccessPublic, bitfield_bit_size: variants.discriminant().byte_offset);
3887 offset += discriminant_type->GetByteSize(exe_scope: nullptr).value_or(u: 0);
3888 }
3889
3890 m_ast.AddFieldToRecordType(type: field_type, name: "value",
3891 field_type: member_type->GetFullCompilerType(),
3892 access: lldb::eAccessPublic, bitfield_bit_size: offset * 8);
3893
3894 m_ast.CompleteTagDeclarationDefinition(type: field_type);
3895
3896 auto name = has_discriminant
3897 ? llvm::formatv(Fmt: "$variant${0}", Vals&: member.discr_value.value())
3898 : std::string("$variant$");
3899
3900 auto variant_decl =
3901 m_ast.AddFieldToRecordType(type: inner_holder, name: llvm::StringRef(name),
3902 field_type, access: default_accesibility, bitfield_bit_size: 0);
3903
3904 layout_info.field_offsets.insert(KV: {variant_decl, 0});
3905 }
3906
3907 auto inner_field = m_ast.AddFieldToRecordType(type: class_clang_type,
3908 name: llvm::StringRef("$variants$"),
3909 field_type: inner_holder, access: eAccessPublic, bitfield_bit_size: 0);
3910
3911 m_ast.CompleteTagDeclarationDefinition(type: inner_holder);
3912
3913 layout_info.field_offsets.insert(KV: {inner_field, 0});
3914}
3915

source code of lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp