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