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