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