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