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