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