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