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