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