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