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