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