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