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