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