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