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