1 //===-- SymbolFileDWARF.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 "SymbolFileDWARF.h"
11 
12 // Other libraries and framework includes
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclGroup.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Basic/Builtins.h"
20 #include "clang/Basic/IdentifierTable.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Basic/Specifiers.h"
25 #include "clang/Sema/DeclSpec.h"
26 
27 #include "llvm/Support/Casting.h"
28 
29 #include "lldb/Core/Module.h"
30 #include "lldb/Core/PluginManager.h"
31 #include "lldb/Core/RegularExpression.h"
32 #include "lldb/Core/Scalar.h"
33 #include "lldb/Core/Section.h"
34 #include "lldb/Core/StreamFile.h"
35 #include "lldb/Core/StreamString.h"
36 #include "lldb/Core/Timer.h"
37 #include "lldb/Core/Value.h"
38 
39 #include "lldb/Host/Host.h"
40 
41 #include "lldb/Symbol/Block.h"
42 #include "lldb/Symbol/ClangExternalASTSourceCallbacks.h"
43 #include "lldb/Symbol/CompileUnit.h"
44 #include "lldb/Symbol/LineTable.h"
45 #include "lldb/Symbol/ObjectFile.h"
46 #include "lldb/Symbol/SymbolVendor.h"
47 #include "lldb/Symbol/VariableList.h"
48 
49 #include "lldb/Target/ObjCLanguageRuntime.h"
50 #include "lldb/Target/CPPLanguageRuntime.h"
51 
52 #include "DWARFCompileUnit.h"
53 #include "DWARFDebugAbbrev.h"
54 #include "DWARFDebugAranges.h"
55 #include "DWARFDebugInfo.h"
56 #include "DWARFDebugInfoEntry.h"
57 #include "DWARFDebugLine.h"
58 #include "DWARFDebugPubnames.h"
59 #include "DWARFDebugRanges.h"
60 #include "DWARFDeclContext.h"
61 #include "DWARFDIECollection.h"
62 #include "DWARFFormValue.h"
63 #include "DWARFLocationList.h"
64 #include "LogChannelDWARF.h"
65 #include "SymbolFileDWARFDebugMap.h"
66 
67 #include <map>
68 
69 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
70 
71 #ifdef ENABLE_DEBUG_PRINTF
72 #include <stdio.h>
73 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
74 #else
75 #define DEBUG_PRINTF(fmt, ...)
76 #endif
77 
78 #define DIE_IS_BEING_PARSED ((lldb_private::Type*)1)
79 
80 using namespace lldb;
81 using namespace lldb_private;
82 
83 //static inline bool
84 //child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
85 //{
86 //    switch (tag)
87 //    {
88 //    default:
89 //        break;
90 //    case DW_TAG_subprogram:
91 //    case DW_TAG_inlined_subroutine:
92 //    case DW_TAG_class_type:
93 //    case DW_TAG_structure_type:
94 //    case DW_TAG_union_type:
95 //        return true;
96 //    }
97 //    return false;
98 //}
99 //
100 static AccessType
101 DW_ACCESS_to_AccessType (uint32_t dwarf_accessibility)
102 {
103     switch (dwarf_accessibility)
104     {
105         case DW_ACCESS_public:      return eAccessPublic;
106         case DW_ACCESS_private:     return eAccessPrivate;
107         case DW_ACCESS_protected:   return eAccessProtected;
108         default:                    break;
109     }
110     return eAccessNone;
111 }
112 
113 #if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
114 
115 class DIEStack
116 {
117 public:
118 
119     void Push (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
120     {
121         m_dies.push_back (DIEInfo(cu, die));
122     }
123 
124 
125     void LogDIEs (Log *log, SymbolFileDWARF *dwarf)
126     {
127         StreamString log_strm;
128         const size_t n = m_dies.size();
129         log_strm.Printf("DIEStack[%" PRIu64 "]:\n", (uint64_t)n);
130         for (size_t i=0; i<n; i++)
131         {
132             DWARFCompileUnit *cu = m_dies[i].cu;
133             const DWARFDebugInfoEntry *die = m_dies[i].die;
134             std::string qualified_name;
135             die->GetQualifiedName(dwarf, cu, qualified_name);
136             log_strm.Printf ("[%" PRIu64 "] 0x%8.8x: %s name='%s'\n",
137                              (uint64_t)i,
138                              die->GetOffset(),
139                              DW_TAG_value_to_name(die->Tag()),
140                              qualified_name.c_str());
141         }
142         log->PutCString(log_strm.GetData());
143     }
144     void Pop ()
145     {
146         m_dies.pop_back();
147     }
148 
149     class ScopedPopper
150     {
151     public:
152         ScopedPopper (DIEStack &die_stack) :
153             m_die_stack (die_stack),
154             m_valid (false)
155         {
156         }
157 
158         void
159         Push (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
160         {
161             m_valid = true;
162             m_die_stack.Push (cu, die);
163         }
164 
165         ~ScopedPopper ()
166         {
167             if (m_valid)
168                 m_die_stack.Pop();
169         }
170 
171 
172 
173     protected:
174         DIEStack &m_die_stack;
175         bool m_valid;
176     };
177 
178 protected:
179     struct DIEInfo {
180         DIEInfo (DWARFCompileUnit *c, const DWARFDebugInfoEntry *d) :
181             cu(c),
182             die(d)
183         {
184         }
185         DWARFCompileUnit *cu;
186         const DWARFDebugInfoEntry *die;
187     };
188     typedef std::vector<DIEInfo> Stack;
189     Stack m_dies;
190 };
191 #endif
192 
193 void
194 SymbolFileDWARF::Initialize()
195 {
196     LogChannelDWARF::Initialize();
197     PluginManager::RegisterPlugin (GetPluginNameStatic(),
198                                    GetPluginDescriptionStatic(),
199                                    CreateInstance);
200 }
201 
202 void
203 SymbolFileDWARF::Terminate()
204 {
205     PluginManager::UnregisterPlugin (CreateInstance);
206     LogChannelDWARF::Initialize();
207 }
208 
209 
210 lldb_private::ConstString
211 SymbolFileDWARF::GetPluginNameStatic()
212 {
213     static ConstString g_name("dwarf");
214     return g_name;
215 }
216 
217 const char *
218 SymbolFileDWARF::GetPluginDescriptionStatic()
219 {
220     return "DWARF and DWARF3 debug symbol file reader.";
221 }
222 
223 
224 SymbolFile*
225 SymbolFileDWARF::CreateInstance (ObjectFile* obj_file)
226 {
227     return new SymbolFileDWARF(obj_file);
228 }
229 
230 TypeList *
231 SymbolFileDWARF::GetTypeList ()
232 {
233     if (GetDebugMapSymfile ())
234         return m_debug_map_symfile->GetTypeList();
235     return m_obj_file->GetModule()->GetTypeList();
236 
237 }
238 void
239 SymbolFileDWARF::GetTypes (DWARFCompileUnit* cu,
240                            const DWARFDebugInfoEntry *die,
241                            dw_offset_t min_die_offset,
242                            dw_offset_t max_die_offset,
243                            uint32_t type_mask,
244                            TypeSet &type_set)
245 {
246     if (cu)
247     {
248         if (die)
249         {
250             const dw_offset_t die_offset = die->GetOffset();
251 
252             if (die_offset >= max_die_offset)
253                 return;
254 
255             if (die_offset >= min_die_offset)
256             {
257                 const dw_tag_t tag = die->Tag();
258 
259                 bool add_type = false;
260 
261                 switch (tag)
262                 {
263                     case DW_TAG_array_type:         add_type = (type_mask & eTypeClassArray         ) != 0; break;
264                     case DW_TAG_unspecified_type:
265                     case DW_TAG_base_type:          add_type = (type_mask & eTypeClassBuiltin       ) != 0; break;
266                     case DW_TAG_class_type:         add_type = (type_mask & eTypeClassClass         ) != 0; break;
267                     case DW_TAG_structure_type:     add_type = (type_mask & eTypeClassStruct        ) != 0; break;
268                     case DW_TAG_union_type:         add_type = (type_mask & eTypeClassUnion         ) != 0; break;
269                     case DW_TAG_enumeration_type:   add_type = (type_mask & eTypeClassEnumeration   ) != 0; break;
270                     case DW_TAG_subroutine_type:
271                     case DW_TAG_subprogram:
272                     case DW_TAG_inlined_subroutine: add_type = (type_mask & eTypeClassFunction      ) != 0; break;
273                     case DW_TAG_pointer_type:       add_type = (type_mask & eTypeClassPointer       ) != 0; break;
274                     case DW_TAG_rvalue_reference_type:
275                     case DW_TAG_reference_type:     add_type = (type_mask & eTypeClassReference     ) != 0; break;
276                     case DW_TAG_typedef:            add_type = (type_mask & eTypeClassTypedef       ) != 0; break;
277                     case DW_TAG_ptr_to_member_type: add_type = (type_mask & eTypeClassMemberPointer ) != 0; break;
278                 }
279 
280                 if (add_type)
281                 {
282                     const bool assert_not_being_parsed = true;
283                     Type *type = ResolveTypeUID (cu, die, assert_not_being_parsed);
284                     if (type)
285                     {
286                         if (type_set.find(type) == type_set.end())
287                             type_set.insert(type);
288                     }
289                 }
290             }
291 
292             for (const DWARFDebugInfoEntry *child_die = die->GetFirstChild();
293                  child_die != NULL;
294                  child_die = child_die->GetSibling())
295             {
296                 GetTypes (cu, child_die, min_die_offset, max_die_offset, type_mask, type_set);
297             }
298         }
299     }
300 }
301 
302 size_t
303 SymbolFileDWARF::GetTypes (SymbolContextScope *sc_scope,
304                            uint32_t type_mask,
305                            TypeList &type_list)
306 
307 {
308     TypeSet type_set;
309 
310     CompileUnit *comp_unit = NULL;
311     DWARFCompileUnit* dwarf_cu = NULL;
312     if (sc_scope)
313         comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
314 
315     if (comp_unit)
316     {
317         dwarf_cu = GetDWARFCompileUnit(comp_unit);
318         if (dwarf_cu == 0)
319             return 0;
320         GetTypes (dwarf_cu,
321                   dwarf_cu->DIE(),
322                   dwarf_cu->GetOffset(),
323                   dwarf_cu->GetNextCompileUnitOffset(),
324                   type_mask,
325                   type_set);
326     }
327     else
328     {
329         DWARFDebugInfo* info = DebugInfo();
330         if (info)
331         {
332             const size_t num_cus = info->GetNumCompileUnits();
333             for (size_t cu_idx=0; cu_idx<num_cus; ++cu_idx)
334             {
335                 dwarf_cu = info->GetCompileUnitAtIndex(cu_idx);
336                 if (dwarf_cu)
337                 {
338                     GetTypes (dwarf_cu,
339                               dwarf_cu->DIE(),
340                               0,
341                               UINT32_MAX,
342                               type_mask,
343                               type_set);
344                 }
345             }
346         }
347     }
348 //    if (m_using_apple_tables)
349 //    {
350 //        DWARFMappedHash::MemoryTable *apple_types = m_apple_types_ap.get();
351 //        if (apple_types)
352 //        {
353 //            apple_types->ForEach([this, &type_set, apple_types, type_mask](const DWARFMappedHash::DIEInfoArray &die_info_array) -> bool {
354 //
355 //                for (auto die_info: die_info_array)
356 //                {
357 //                    bool add_type = TagMatchesTypeMask (type_mask, 0);
358 //                    if (!add_type)
359 //                    {
360 //                        dw_tag_t tag = die_info.tag;
361 //                        if (tag == 0)
362 //                        {
363 //                            const DWARFDebugInfoEntry *die = DebugInfo()->GetDIEPtr(die_info.offset, NULL);
364 //                            tag = die->Tag();
365 //                        }
366 //                        add_type = TagMatchesTypeMask (type_mask, tag);
367 //                    }
368 //                    if (add_type)
369 //                    {
370 //                        Type *type = ResolveTypeUID(die_info.offset);
371 //
372 //                        if (type_set.find(type) == type_set.end())
373 //                            type_set.insert(type);
374 //                    }
375 //                }
376 //                return true; // Keep iterating
377 //            });
378 //        }
379 //    }
380 //    else
381 //    {
382 //        if (!m_indexed)
383 //            Index ();
384 //
385 //        m_type_index.ForEach([this, &type_set, type_mask](const char *name, uint32_t die_offset) -> bool {
386 //
387 //            bool add_type = TagMatchesTypeMask (type_mask, 0);
388 //
389 //            if (!add_type)
390 //            {
391 //                const DWARFDebugInfoEntry *die = DebugInfo()->GetDIEPtr(die_offset, NULL);
392 //                if (die)
393 //                {
394 //                    const dw_tag_t tag = die->Tag();
395 //                    add_type = TagMatchesTypeMask (type_mask, tag);
396 //                }
397 //            }
398 //
399 //            if (add_type)
400 //            {
401 //                Type *type = ResolveTypeUID(die_offset);
402 //
403 //                if (type_set.find(type) == type_set.end())
404 //                    type_set.insert(type);
405 //            }
406 //            return true; // Keep iterating
407 //        });
408 //    }
409 
410     std::set<ClangASTType> clang_type_set;
411     size_t num_types_added = 0;
412     for (Type *type : type_set)
413     {
414         ClangASTType clang_type = type->GetClangForwardType();
415         if (clang_type_set.find(clang_type) == clang_type_set.end())
416         {
417             clang_type_set.insert(clang_type);
418             type_list.Insert (type->shared_from_this());
419             ++num_types_added;
420         }
421     }
422     return num_types_added;
423 }
424 
425 
426 //----------------------------------------------------------------------
427 // Gets the first parent that is a lexical block, function or inlined
428 // subroutine, or compile unit.
429 //----------------------------------------------------------------------
430 static const DWARFDebugInfoEntry *
431 GetParentSymbolContextDIE(const DWARFDebugInfoEntry *child_die)
432 {
433     const DWARFDebugInfoEntry *die;
434     for (die = child_die->GetParent(); die != NULL; die = die->GetParent())
435     {
436         dw_tag_t tag = die->Tag();
437 
438         switch (tag)
439         {
440         case DW_TAG_compile_unit:
441         case DW_TAG_subprogram:
442         case DW_TAG_inlined_subroutine:
443         case DW_TAG_lexical_block:
444             return die;
445         }
446     }
447     return NULL;
448 }
449 
450 
451 SymbolFileDWARF::SymbolFileDWARF(ObjectFile* objfile) :
452     SymbolFile (objfile),
453     UserID (0),  // Used by SymbolFileDWARFDebugMap to when this class parses .o files to contain the .o file index/ID
454     m_debug_map_module_wp (),
455     m_debug_map_symfile (NULL),
456     m_clang_tu_decl (NULL),
457     m_flags(),
458     m_data_debug_abbrev (),
459     m_data_debug_aranges (),
460     m_data_debug_frame (),
461     m_data_debug_info (),
462     m_data_debug_line (),
463     m_data_debug_loc (),
464     m_data_debug_ranges (),
465     m_data_debug_str (),
466     m_data_apple_names (),
467     m_data_apple_types (),
468     m_data_apple_namespaces (),
469     m_abbr(),
470     m_info(),
471     m_line(),
472     m_apple_names_ap (),
473     m_apple_types_ap (),
474     m_apple_namespaces_ap (),
475     m_apple_objc_ap (),
476     m_function_basename_index(),
477     m_function_fullname_index(),
478     m_function_method_index(),
479     m_function_selector_index(),
480     m_objc_class_selectors_index(),
481     m_global_index(),
482     m_type_index(),
483     m_namespace_index(),
484     m_indexed (false),
485     m_is_external_ast_source (false),
486     m_using_apple_tables (false),
487     m_supports_DW_AT_APPLE_objc_complete_type (eLazyBoolCalculate),
488     m_ranges(),
489     m_unique_ast_type_map ()
490 {
491 }
492 
493 SymbolFileDWARF::~SymbolFileDWARF()
494 {
495     if (m_is_external_ast_source)
496     {
497         ModuleSP module_sp (m_obj_file->GetModule());
498         if (module_sp)
499             module_sp->GetClangASTContext().RemoveExternalSource ();
500     }
501 }
502 
503 static const ConstString &
504 GetDWARFMachOSegmentName ()
505 {
506     static ConstString g_dwarf_section_name ("__DWARF");
507     return g_dwarf_section_name;
508 }
509 
510 UniqueDWARFASTTypeMap &
511 SymbolFileDWARF::GetUniqueDWARFASTTypeMap ()
512 {
513     if (GetDebugMapSymfile ())
514         return m_debug_map_symfile->GetUniqueDWARFASTTypeMap ();
515     return m_unique_ast_type_map;
516 }
517 
518 ClangASTContext &
519 SymbolFileDWARF::GetClangASTContext ()
520 {
521     if (GetDebugMapSymfile ())
522         return m_debug_map_symfile->GetClangASTContext ();
523 
524     ClangASTContext &ast = m_obj_file->GetModule()->GetClangASTContext();
525     if (!m_is_external_ast_source)
526     {
527         m_is_external_ast_source = true;
528         llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_ap (
529             new ClangExternalASTSourceCallbacks (SymbolFileDWARF::CompleteTagDecl,
530                                                  SymbolFileDWARF::CompleteObjCInterfaceDecl,
531                                                  SymbolFileDWARF::FindExternalVisibleDeclsByName,
532                                                  SymbolFileDWARF::LayoutRecordType,
533                                                  this));
534         ast.SetExternalSource (ast_source_ap);
535     }
536     return ast;
537 }
538 
539 void
540 SymbolFileDWARF::InitializeObject()
541 {
542     // Install our external AST source callbacks so we can complete Clang types.
543     ModuleSP module_sp (m_obj_file->GetModule());
544     if (module_sp)
545     {
546         const SectionList *section_list = module_sp->GetSectionList();
547 
548         const Section* section = section_list->FindSectionByName(GetDWARFMachOSegmentName ()).get();
549 
550         // Memory map the DWARF mach-o segment so we have everything mmap'ed
551         // to keep our heap memory usage down.
552         if (section)
553             m_obj_file->MemoryMapSectionData(section, m_dwarf_data);
554     }
555     get_apple_names_data();
556     if (m_data_apple_names.GetByteSize() > 0)
557     {
558         m_apple_names_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_names, get_debug_str_data(), ".apple_names"));
559         if (m_apple_names_ap->IsValid())
560             m_using_apple_tables = true;
561         else
562             m_apple_names_ap.reset();
563     }
564     get_apple_types_data();
565     if (m_data_apple_types.GetByteSize() > 0)
566     {
567         m_apple_types_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_types, get_debug_str_data(), ".apple_types"));
568         if (m_apple_types_ap->IsValid())
569             m_using_apple_tables = true;
570         else
571             m_apple_types_ap.reset();
572     }
573 
574     get_apple_namespaces_data();
575     if (m_data_apple_namespaces.GetByteSize() > 0)
576     {
577         m_apple_namespaces_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_namespaces, get_debug_str_data(), ".apple_namespaces"));
578         if (m_apple_namespaces_ap->IsValid())
579             m_using_apple_tables = true;
580         else
581             m_apple_namespaces_ap.reset();
582     }
583 
584     get_apple_objc_data();
585     if (m_data_apple_objc.GetByteSize() > 0)
586     {
587         m_apple_objc_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_objc, get_debug_str_data(), ".apple_objc"));
588         if (m_apple_objc_ap->IsValid())
589             m_using_apple_tables = true;
590         else
591             m_apple_objc_ap.reset();
592     }
593 }
594 
595 bool
596 SymbolFileDWARF::SupportedVersion(uint16_t version)
597 {
598     return version == 2 || version == 3 || version == 4;
599 }
600 
601 uint32_t
602 SymbolFileDWARF::CalculateAbilities ()
603 {
604     uint32_t abilities = 0;
605     if (m_obj_file != NULL)
606     {
607         const Section* section = NULL;
608         const SectionList *section_list = m_obj_file->GetSectionList();
609         if (section_list == NULL)
610             return 0;
611 
612         uint64_t debug_abbrev_file_size = 0;
613         uint64_t debug_info_file_size = 0;
614         uint64_t debug_line_file_size = 0;
615 
616         section = section_list->FindSectionByName(GetDWARFMachOSegmentName ()).get();
617 
618         if (section)
619             section_list = &section->GetChildren ();
620 
621         section = section_list->FindSectionByType (eSectionTypeDWARFDebugInfo, true).get();
622         if (section != NULL)
623         {
624             debug_info_file_size = section->GetFileSize();
625 
626             section = section_list->FindSectionByType (eSectionTypeDWARFDebugAbbrev, true).get();
627             if (section)
628                 debug_abbrev_file_size = section->GetFileSize();
629             else
630                 m_flags.Set (flagsGotDebugAbbrevData);
631 
632             section = section_list->FindSectionByType (eSectionTypeDWARFDebugAranges, true).get();
633             if (!section)
634                 m_flags.Set (flagsGotDebugArangesData);
635 
636             section = section_list->FindSectionByType (eSectionTypeDWARFDebugFrame, true).get();
637             if (!section)
638                 m_flags.Set (flagsGotDebugFrameData);
639 
640             section = section_list->FindSectionByType (eSectionTypeDWARFDebugLine, true).get();
641             if (section)
642                 debug_line_file_size = section->GetFileSize();
643             else
644                 m_flags.Set (flagsGotDebugLineData);
645 
646             section = section_list->FindSectionByType (eSectionTypeDWARFDebugLoc, true).get();
647             if (!section)
648                 m_flags.Set (flagsGotDebugLocData);
649 
650             section = section_list->FindSectionByType (eSectionTypeDWARFDebugMacInfo, true).get();
651             if (!section)
652                 m_flags.Set (flagsGotDebugMacInfoData);
653 
654             section = section_list->FindSectionByType (eSectionTypeDWARFDebugPubNames, true).get();
655             if (!section)
656                 m_flags.Set (flagsGotDebugPubNamesData);
657 
658             section = section_list->FindSectionByType (eSectionTypeDWARFDebugPubTypes, true).get();
659             if (!section)
660                 m_flags.Set (flagsGotDebugPubTypesData);
661 
662             section = section_list->FindSectionByType (eSectionTypeDWARFDebugRanges, true).get();
663             if (!section)
664                 m_flags.Set (flagsGotDebugRangesData);
665 
666             section = section_list->FindSectionByType (eSectionTypeDWARFDebugStr, true).get();
667             if (!section)
668                 m_flags.Set (flagsGotDebugStrData);
669         }
670         else
671         {
672             const char *symfile_dir_cstr = m_obj_file->GetFileSpec().GetDirectory().GetCString();
673             if (symfile_dir_cstr)
674             {
675                 if (strcasestr(symfile_dir_cstr, ".dsym"))
676                 {
677                     if (m_obj_file->GetType() == ObjectFile::eTypeDebugInfo)
678                     {
679                         // We have a dSYM file that didn't have a any debug info.
680                         // If the string table has a size of 1, then it was made from
681                         // an executable with no debug info, or from an executable that
682                         // was stripped.
683                         section = section_list->FindSectionByType (eSectionTypeDWARFDebugStr, true).get();
684                         if (section && section->GetFileSize() == 1)
685                         {
686                             m_obj_file->GetModule()->ReportWarning ("empty dSYM file detected, dSYM was created with an executable with no debug info.");
687                         }
688                     }
689                 }
690             }
691         }
692 
693         if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
694             abilities |= CompileUnits | Functions | Blocks | GlobalVariables | LocalVariables | VariableTypes;
695 
696         if (debug_line_file_size > 0)
697             abilities |= LineTables;
698     }
699     return abilities;
700 }
701 
702 const DWARFDataExtractor&
703 SymbolFileDWARF::GetCachedSectionData (uint32_t got_flag, SectionType sect_type, DWARFDataExtractor &data)
704 {
705     if (m_flags.IsClear (got_flag))
706     {
707         ModuleSP module_sp (m_obj_file->GetModule());
708         m_flags.Set (got_flag);
709         const SectionList *section_list = module_sp->GetSectionList();
710         if (section_list)
711         {
712             SectionSP section_sp (section_list->FindSectionByType(sect_type, true));
713             if (section_sp)
714             {
715                 // See if we memory mapped the DWARF segment?
716                 if (m_dwarf_data.GetByteSize())
717                 {
718                     data.SetData(m_dwarf_data, section_sp->GetOffset (), section_sp->GetFileSize());
719                 }
720                 else
721                 {
722                     if (m_obj_file->ReadSectionData (section_sp.get(), data) == 0)
723                         data.Clear();
724                 }
725             }
726         }
727     }
728     return data;
729 }
730 
731 const DWARFDataExtractor&
732 SymbolFileDWARF::get_debug_abbrev_data()
733 {
734     return GetCachedSectionData (flagsGotDebugAbbrevData, eSectionTypeDWARFDebugAbbrev, m_data_debug_abbrev);
735 }
736 
737 const DWARFDataExtractor&
738 SymbolFileDWARF::get_debug_aranges_data()
739 {
740     return GetCachedSectionData (flagsGotDebugArangesData, eSectionTypeDWARFDebugAranges, m_data_debug_aranges);
741 }
742 
743 const DWARFDataExtractor&
744 SymbolFileDWARF::get_debug_frame_data()
745 {
746     return GetCachedSectionData (flagsGotDebugFrameData, eSectionTypeDWARFDebugFrame, m_data_debug_frame);
747 }
748 
749 const DWARFDataExtractor&
750 SymbolFileDWARF::get_debug_info_data()
751 {
752     return GetCachedSectionData (flagsGotDebugInfoData, eSectionTypeDWARFDebugInfo, m_data_debug_info);
753 }
754 
755 const DWARFDataExtractor&
756 SymbolFileDWARF::get_debug_line_data()
757 {
758     return GetCachedSectionData (flagsGotDebugLineData, eSectionTypeDWARFDebugLine, m_data_debug_line);
759 }
760 
761 const DWARFDataExtractor&
762 SymbolFileDWARF::get_debug_loc_data()
763 {
764     return GetCachedSectionData (flagsGotDebugLocData, eSectionTypeDWARFDebugLoc, m_data_debug_loc);
765 }
766 
767 const DWARFDataExtractor&
768 SymbolFileDWARF::get_debug_ranges_data()
769 {
770     return GetCachedSectionData (flagsGotDebugRangesData, eSectionTypeDWARFDebugRanges, m_data_debug_ranges);
771 }
772 
773 const DWARFDataExtractor&
774 SymbolFileDWARF::get_debug_str_data()
775 {
776     return GetCachedSectionData (flagsGotDebugStrData, eSectionTypeDWARFDebugStr, m_data_debug_str);
777 }
778 
779 const DWARFDataExtractor&
780 SymbolFileDWARF::get_apple_names_data()
781 {
782     return GetCachedSectionData (flagsGotAppleNamesData, eSectionTypeDWARFAppleNames, m_data_apple_names);
783 }
784 
785 const DWARFDataExtractor&
786 SymbolFileDWARF::get_apple_types_data()
787 {
788     return GetCachedSectionData (flagsGotAppleTypesData, eSectionTypeDWARFAppleTypes, m_data_apple_types);
789 }
790 
791 const DWARFDataExtractor&
792 SymbolFileDWARF::get_apple_namespaces_data()
793 {
794     return GetCachedSectionData (flagsGotAppleNamespacesData, eSectionTypeDWARFAppleNamespaces, m_data_apple_namespaces);
795 }
796 
797 const DWARFDataExtractor&
798 SymbolFileDWARF::get_apple_objc_data()
799 {
800     return GetCachedSectionData (flagsGotAppleObjCData, eSectionTypeDWARFAppleObjC, m_data_apple_objc);
801 }
802 
803 
804 DWARFDebugAbbrev*
805 SymbolFileDWARF::DebugAbbrev()
806 {
807     if (m_abbr.get() == NULL)
808     {
809         const DWARFDataExtractor &debug_abbrev_data = get_debug_abbrev_data();
810         if (debug_abbrev_data.GetByteSize() > 0)
811         {
812             m_abbr.reset(new DWARFDebugAbbrev());
813             if (m_abbr.get())
814                 m_abbr->Parse(debug_abbrev_data);
815         }
816     }
817     return m_abbr.get();
818 }
819 
820 const DWARFDebugAbbrev*
821 SymbolFileDWARF::DebugAbbrev() const
822 {
823     return m_abbr.get();
824 }
825 
826 
827 DWARFDebugInfo*
828 SymbolFileDWARF::DebugInfo()
829 {
830     if (m_info.get() == NULL)
831     {
832         Timer scoped_timer(__PRETTY_FUNCTION__, "%s this = %p",
833                            __PRETTY_FUNCTION__, static_cast<void*>(this));
834         if (get_debug_info_data().GetByteSize() > 0)
835         {
836             m_info.reset(new DWARFDebugInfo());
837             if (m_info.get())
838             {
839                 m_info->SetDwarfData(this);
840             }
841         }
842     }
843     return m_info.get();
844 }
845 
846 const DWARFDebugInfo*
847 SymbolFileDWARF::DebugInfo() const
848 {
849     return m_info.get();
850 }
851 
852 DWARFCompileUnit*
853 SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit)
854 {
855     DWARFDebugInfo* info = DebugInfo();
856     if (info)
857     {
858         if (GetDebugMapSymfile ())
859         {
860             // The debug map symbol file made the compile units for this DWARF
861             // file which is .o file with DWARF in it, and we should have
862             // only 1 compile unit which is at offset zero in the DWARF.
863             // TODO: modify to support LTO .o files where each .o file might
864             // have multiple DW_TAG_compile_unit tags.
865             return info->GetCompileUnit(0).get();
866         }
867         else
868         {
869             // Just a normal DWARF file whose user ID for the compile unit is
870             // the DWARF offset itself
871             return info->GetCompileUnit((dw_offset_t)comp_unit->GetID()).get();
872         }
873     }
874     return NULL;
875 }
876 
877 
878 DWARFDebugRanges*
879 SymbolFileDWARF::DebugRanges()
880 {
881     if (m_ranges.get() == NULL)
882     {
883         Timer scoped_timer(__PRETTY_FUNCTION__, "%s this = %p",
884                            __PRETTY_FUNCTION__, static_cast<void*>(this));
885         if (get_debug_ranges_data().GetByteSize() > 0)
886         {
887             m_ranges.reset(new DWARFDebugRanges());
888             if (m_ranges.get())
889                 m_ranges->Extract(this);
890         }
891     }
892     return m_ranges.get();
893 }
894 
895 const DWARFDebugRanges*
896 SymbolFileDWARF::DebugRanges() const
897 {
898     return m_ranges.get();
899 }
900 
901 lldb::CompUnitSP
902 SymbolFileDWARF::ParseCompileUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
903 {
904     CompUnitSP cu_sp;
905     if (dwarf_cu)
906     {
907         CompileUnit *comp_unit = (CompileUnit*)dwarf_cu->GetUserData();
908         if (comp_unit)
909         {
910             // We already parsed this compile unit, had out a shared pointer to it
911             cu_sp = comp_unit->shared_from_this();
912         }
913         else
914         {
915             if (GetDebugMapSymfile ())
916             {
917                 // Let the debug map create the compile unit
918                 cu_sp = m_debug_map_symfile->GetCompileUnit(this);
919                 dwarf_cu->SetUserData(cu_sp.get());
920             }
921             else
922             {
923                 ModuleSP module_sp (m_obj_file->GetModule());
924                 if (module_sp)
925                 {
926                     const DWARFDebugInfoEntry * cu_die = dwarf_cu->GetCompileUnitDIEOnly ();
927                     if (cu_die)
928                     {
929                         const char * cu_die_name = cu_die->GetName(this, dwarf_cu);
930                         const char * cu_comp_dir = cu_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_comp_dir, NULL);
931                         LanguageType cu_language = (LanguageType)cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_language, 0);
932                         if (cu_die_name)
933                         {
934                             std::string ramapped_file;
935                             FileSpec cu_file_spec;
936 
937                             if (cu_die_name[0] == '/' || cu_comp_dir == NULL || cu_comp_dir[0] == '\0')
938                             {
939                                 // If we have a full path to the compile unit, we don't need to resolve
940                                 // the file.  This can be expensive e.g. when the source files are NFS mounted.
941                                 if (module_sp->RemapSourceFile(cu_die_name, ramapped_file))
942                                     cu_file_spec.SetFile (ramapped_file.c_str(), false);
943                                 else
944                                     cu_file_spec.SetFile (cu_die_name, false);
945                             }
946                             else
947                             {
948                                 std::string fullpath(cu_comp_dir);
949                                 if (*fullpath.rbegin() != '/')
950                                     fullpath += '/';
951                                 fullpath += cu_die_name;
952                                 if (module_sp->RemapSourceFile (fullpath.c_str(), ramapped_file))
953                                     cu_file_spec.SetFile (ramapped_file.c_str(), false);
954                                 else
955                                     cu_file_spec.SetFile (fullpath.c_str(), false);
956                             }
957 
958                             cu_sp.reset(new CompileUnit (module_sp,
959                                                          dwarf_cu,
960                                                          cu_file_spec,
961                                                          MakeUserID(dwarf_cu->GetOffset()),
962                                                          cu_language));
963                             if (cu_sp)
964                             {
965                                 dwarf_cu->SetUserData(cu_sp.get());
966 
967                                 // Figure out the compile unit index if we weren't given one
968                                 if (cu_idx == UINT32_MAX)
969                                     DebugInfo()->GetCompileUnit(dwarf_cu->GetOffset(), &cu_idx);
970 
971                                 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cu_idx, cu_sp);
972                             }
973                         }
974                     }
975                 }
976             }
977         }
978     }
979     return cu_sp;
980 }
981 
982 uint32_t
983 SymbolFileDWARF::GetNumCompileUnits()
984 {
985     DWARFDebugInfo* info = DebugInfo();
986     if (info)
987         return info->GetNumCompileUnits();
988     return 0;
989 }
990 
991 CompUnitSP
992 SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx)
993 {
994     CompUnitSP cu_sp;
995     DWARFDebugInfo* info = DebugInfo();
996     if (info)
997     {
998         DWARFCompileUnit* dwarf_cu = info->GetCompileUnitAtIndex(cu_idx);
999         if (dwarf_cu)
1000             cu_sp = ParseCompileUnit(dwarf_cu, cu_idx);
1001     }
1002     return cu_sp;
1003 }
1004 
1005 static void
1006 AddRangesToBlock (Block& block,
1007                   DWARFDebugRanges::RangeList& ranges,
1008                   addr_t block_base_addr)
1009 {
1010     const size_t num_ranges = ranges.GetSize();
1011     for (size_t i = 0; i<num_ranges; ++i)
1012     {
1013         const DWARFDebugRanges::Range &range = ranges.GetEntryRef (i);
1014         const addr_t range_base = range.GetRangeBase();
1015         assert (range_base >= block_base_addr);
1016         block.AddRange(Block::Range (range_base - block_base_addr, range.GetByteSize()));;
1017     }
1018     block.FinalizeRanges ();
1019 }
1020 
1021 
1022 Function *
1023 SymbolFileDWARF::ParseCompileUnitFunction (const SymbolContext& sc, DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry *die)
1024 {
1025     DWARFDebugRanges::RangeList func_ranges;
1026     const char *name = NULL;
1027     const char *mangled = NULL;
1028     int decl_file = 0;
1029     int decl_line = 0;
1030     int decl_column = 0;
1031     int call_file = 0;
1032     int call_line = 0;
1033     int call_column = 0;
1034     DWARFExpression frame_base;
1035 
1036     assert (die->Tag() == DW_TAG_subprogram);
1037 
1038     if (die->Tag() != DW_TAG_subprogram)
1039         return NULL;
1040 
1041     if (die->GetDIENamesAndRanges (this,
1042                                    dwarf_cu,
1043                                    name,
1044                                    mangled,
1045                                    func_ranges,
1046                                    decl_file,
1047                                    decl_line,
1048                                    decl_column,
1049                                    call_file,
1050                                    call_line,
1051                                    call_column,
1052                                    &frame_base))
1053     {
1054         // Union of all ranges in the function DIE (if the function is discontiguous)
1055         AddressRange func_range;
1056         lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase (0);
1057         lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd (0);
1058         if (lowest_func_addr != LLDB_INVALID_ADDRESS && lowest_func_addr <= highest_func_addr)
1059         {
1060             ModuleSP module_sp (m_obj_file->GetModule());
1061             func_range.GetBaseAddress().ResolveAddressUsingFileSections (lowest_func_addr, module_sp->GetSectionList());
1062             if (func_range.GetBaseAddress().IsValid())
1063                 func_range.SetByteSize(highest_func_addr - lowest_func_addr);
1064         }
1065 
1066         if (func_range.GetBaseAddress().IsValid())
1067         {
1068             Mangled func_name;
1069             if (mangled)
1070                 func_name.SetValue(ConstString(mangled), true);
1071             else if (name)
1072                 func_name.SetValue(ConstString(name), false);
1073 
1074             FunctionSP func_sp;
1075             std::unique_ptr<Declaration> decl_ap;
1076             if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1077                 decl_ap.reset(new Declaration (sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
1078                                                decl_line,
1079                                                decl_column));
1080 
1081             // Supply the type _only_ if it has already been parsed
1082             Type *func_type = m_die_to_type.lookup (die);
1083 
1084             assert(func_type == NULL || func_type != DIE_IS_BEING_PARSED);
1085 
1086             if (FixupAddress (func_range.GetBaseAddress()))
1087             {
1088                 const user_id_t func_user_id = MakeUserID(die->GetOffset());
1089                 func_sp.reset(new Function (sc.comp_unit,
1090                                             MakeUserID(func_user_id),       // UserID is the DIE offset
1091                                             MakeUserID(func_user_id),
1092                                             func_name,
1093                                             func_type,
1094                                             func_range));           // first address range
1095 
1096                 if (func_sp.get() != NULL)
1097                 {
1098                     if (frame_base.IsValid())
1099                         func_sp->GetFrameBaseExpression() = frame_base;
1100                     sc.comp_unit->AddFunction(func_sp);
1101                     return func_sp.get();
1102                 }
1103             }
1104         }
1105     }
1106     return NULL;
1107 }
1108 
1109 bool
1110 SymbolFileDWARF::FixupAddress (Address &addr)
1111 {
1112     SymbolFileDWARFDebugMap * debug_map_symfile = GetDebugMapSymfile ();
1113     if (debug_map_symfile)
1114     {
1115         return debug_map_symfile->LinkOSOAddress(addr);
1116     }
1117     // This is a normal DWARF file, no address fixups need to happen
1118     return true;
1119 }
1120 lldb::LanguageType
1121 SymbolFileDWARF::ParseCompileUnitLanguage (const SymbolContext& sc)
1122 {
1123     assert (sc.comp_unit);
1124     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1125     if (dwarf_cu)
1126     {
1127         const DWARFDebugInfoEntry *die = dwarf_cu->GetCompileUnitDIEOnly();
1128         if (die)
1129         {
1130             const uint32_t language = die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_language, 0);
1131             if (language)
1132                 return (lldb::LanguageType)language;
1133         }
1134     }
1135     return eLanguageTypeUnknown;
1136 }
1137 
1138 size_t
1139 SymbolFileDWARF::ParseCompileUnitFunctions(const SymbolContext &sc)
1140 {
1141     assert (sc.comp_unit);
1142     size_t functions_added = 0;
1143     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1144     if (dwarf_cu)
1145     {
1146         DWARFDIECollection function_dies;
1147         const size_t num_functions = dwarf_cu->AppendDIEsWithTag (DW_TAG_subprogram, function_dies);
1148         size_t func_idx;
1149         for (func_idx = 0; func_idx < num_functions; ++func_idx)
1150         {
1151             const DWARFDebugInfoEntry *die = function_dies.GetDIEPtrAtIndex(func_idx);
1152             if (sc.comp_unit->FindFunctionByUID (MakeUserID(die->GetOffset())).get() == NULL)
1153             {
1154                 if (ParseCompileUnitFunction(sc, dwarf_cu, die))
1155                     ++functions_added;
1156             }
1157         }
1158         //FixupTypes();
1159     }
1160     return functions_added;
1161 }
1162 
1163 bool
1164 SymbolFileDWARF::ParseCompileUnitSupportFiles (const SymbolContext& sc, FileSpecList& support_files)
1165 {
1166     assert (sc.comp_unit);
1167     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1168     if (dwarf_cu)
1169     {
1170         const DWARFDebugInfoEntry * cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1171 
1172         if (cu_die)
1173         {
1174             const char * cu_comp_dir = cu_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_comp_dir, NULL);
1175             dw_offset_t stmt_list = cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_stmt_list, DW_INVALID_OFFSET);
1176 
1177             // All file indexes in DWARF are one based and a file of index zero is
1178             // supposed to be the compile unit itself.
1179             support_files.Append (*sc.comp_unit);
1180 
1181             return DWARFDebugLine::ParseSupportFiles(sc.comp_unit->GetModule(), get_debug_line_data(), cu_comp_dir, stmt_list, support_files);
1182         }
1183     }
1184     return false;
1185 }
1186 
1187 struct ParseDWARFLineTableCallbackInfo
1188 {
1189     LineTable* line_table;
1190     std::unique_ptr<LineSequence> sequence_ap;
1191 };
1192 
1193 //----------------------------------------------------------------------
1194 // ParseStatementTableCallback
1195 //----------------------------------------------------------------------
1196 static void
1197 ParseDWARFLineTableCallback(dw_offset_t offset, const DWARFDebugLine::State& state, void* userData)
1198 {
1199     if (state.row == DWARFDebugLine::State::StartParsingLineTable)
1200     {
1201         // Just started parsing the line table
1202     }
1203     else if (state.row == DWARFDebugLine::State::DoneParsingLineTable)
1204     {
1205         // Done parsing line table, nothing to do for the cleanup
1206     }
1207     else
1208     {
1209         ParseDWARFLineTableCallbackInfo* info = (ParseDWARFLineTableCallbackInfo*)userData;
1210         LineTable* line_table = info->line_table;
1211 
1212         // If this is our first time here, we need to create a
1213         // sequence container.
1214         if (!info->sequence_ap.get())
1215         {
1216             info->sequence_ap.reset(line_table->CreateLineSequenceContainer());
1217             assert(info->sequence_ap.get());
1218         }
1219         line_table->AppendLineEntryToSequence (info->sequence_ap.get(),
1220                                                state.address,
1221                                                state.line,
1222                                                state.column,
1223                                                state.file,
1224                                                state.is_stmt,
1225                                                state.basic_block,
1226                                                state.prologue_end,
1227                                                state.epilogue_begin,
1228                                                state.end_sequence);
1229         if (state.end_sequence)
1230         {
1231             // First, put the current sequence into the line table.
1232             line_table->InsertSequence(info->sequence_ap.get());
1233             // Then, empty it to prepare for the next sequence.
1234             info->sequence_ap->Clear();
1235         }
1236     }
1237 }
1238 
1239 bool
1240 SymbolFileDWARF::ParseCompileUnitLineTable (const SymbolContext &sc)
1241 {
1242     assert (sc.comp_unit);
1243     if (sc.comp_unit->GetLineTable() != NULL)
1244         return true;
1245 
1246     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1247     if (dwarf_cu)
1248     {
1249         const DWARFDebugInfoEntry *dwarf_cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1250         if (dwarf_cu_die)
1251         {
1252             const dw_offset_t cu_line_offset = dwarf_cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_stmt_list, DW_INVALID_OFFSET);
1253             if (cu_line_offset != DW_INVALID_OFFSET)
1254             {
1255                 std::unique_ptr<LineTable> line_table_ap(new LineTable(sc.comp_unit));
1256                 if (line_table_ap.get())
1257                 {
1258                     ParseDWARFLineTableCallbackInfo info;
1259                     info.line_table = line_table_ap.get();
1260                     lldb::offset_t offset = cu_line_offset;
1261                     DWARFDebugLine::ParseStatementTable(get_debug_line_data(), &offset, ParseDWARFLineTableCallback, &info);
1262                     if (m_debug_map_symfile)
1263                     {
1264                         // We have an object file that has a line table with addresses
1265                         // that are not linked. We need to link the line table and convert
1266                         // the addresses that are relative to the .o file into addresses
1267                         // for the main executable.
1268                         sc.comp_unit->SetLineTable (m_debug_map_symfile->LinkOSOLineTable (this, line_table_ap.get()));
1269                     }
1270                     else
1271                     {
1272                         sc.comp_unit->SetLineTable(line_table_ap.release());
1273                         return true;
1274                     }
1275                 }
1276             }
1277         }
1278     }
1279     return false;
1280 }
1281 
1282 size_t
1283 SymbolFileDWARF::ParseFunctionBlocks
1284 (
1285     const SymbolContext& sc,
1286     Block *parent_block,
1287     DWARFCompileUnit* dwarf_cu,
1288     const DWARFDebugInfoEntry *die,
1289     addr_t subprogram_low_pc,
1290     uint32_t depth
1291 )
1292 {
1293     size_t blocks_added = 0;
1294     while (die != NULL)
1295     {
1296         dw_tag_t tag = die->Tag();
1297 
1298         switch (tag)
1299         {
1300         case DW_TAG_inlined_subroutine:
1301         case DW_TAG_subprogram:
1302         case DW_TAG_lexical_block:
1303             {
1304                 Block *block = NULL;
1305                 if (tag == DW_TAG_subprogram)
1306                 {
1307                     // Skip any DW_TAG_subprogram DIEs that are inside
1308                     // of a normal or inlined functions. These will be
1309                     // parsed on their own as separate entities.
1310 
1311                     if (depth > 0)
1312                         break;
1313 
1314                     block = parent_block;
1315                 }
1316                 else
1317                 {
1318                     BlockSP block_sp(new Block (MakeUserID(die->GetOffset())));
1319                     parent_block->AddChild(block_sp);
1320                     block = block_sp.get();
1321                 }
1322                 DWARFDebugRanges::RangeList ranges;
1323                 const char *name = NULL;
1324                 const char *mangled_name = NULL;
1325 
1326                 int decl_file = 0;
1327                 int decl_line = 0;
1328                 int decl_column = 0;
1329                 int call_file = 0;
1330                 int call_line = 0;
1331                 int call_column = 0;
1332                 if (die->GetDIENamesAndRanges (this,
1333                                                dwarf_cu,
1334                                                name,
1335                                                mangled_name,
1336                                                ranges,
1337                                                decl_file, decl_line, decl_column,
1338                                                call_file, call_line, call_column))
1339                 {
1340                     if (tag == DW_TAG_subprogram)
1341                     {
1342                         assert (subprogram_low_pc == LLDB_INVALID_ADDRESS);
1343                         subprogram_low_pc = ranges.GetMinRangeBase(0);
1344                     }
1345                     else if (tag == DW_TAG_inlined_subroutine)
1346                     {
1347                         // We get called here for inlined subroutines in two ways.
1348                         // The first time is when we are making the Function object
1349                         // for this inlined concrete instance.  Since we're creating a top level block at
1350                         // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we need to
1351                         // adjust the containing address.
1352                         // The second time is when we are parsing the blocks inside the function that contains
1353                         // the inlined concrete instance.  Since these will be blocks inside the containing "real"
1354                         // function the offset will be for that function.
1355                         if (subprogram_low_pc == LLDB_INVALID_ADDRESS)
1356                         {
1357                             subprogram_low_pc = ranges.GetMinRangeBase(0);
1358                         }
1359                     }
1360 
1361                     AddRangesToBlock (*block, ranges, subprogram_low_pc);
1362 
1363                     if (tag != DW_TAG_subprogram && (name != NULL || mangled_name != NULL))
1364                     {
1365                         std::unique_ptr<Declaration> decl_ap;
1366                         if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1367                             decl_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
1368                                                           decl_line, decl_column));
1369 
1370                         std::unique_ptr<Declaration> call_ap;
1371                         if (call_file != 0 || call_line != 0 || call_column != 0)
1372                             call_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(call_file),
1373                                                           call_line, call_column));
1374 
1375                         block->SetInlinedFunctionInfo (name, mangled_name, decl_ap.get(), call_ap.get());
1376                     }
1377 
1378                     ++blocks_added;
1379 
1380                     if (die->HasChildren())
1381                     {
1382                         blocks_added += ParseFunctionBlocks (sc,
1383                                                              block,
1384                                                              dwarf_cu,
1385                                                              die->GetFirstChild(),
1386                                                              subprogram_low_pc,
1387                                                              depth + 1);
1388                     }
1389                 }
1390             }
1391             break;
1392         default:
1393             break;
1394         }
1395 
1396         // Only parse siblings of the block if we are not at depth zero. A depth
1397         // of zero indicates we are currently parsing the top level
1398         // DW_TAG_subprogram DIE
1399 
1400         if (depth == 0)
1401             die = NULL;
1402         else
1403             die = die->GetSibling();
1404     }
1405     return blocks_added;
1406 }
1407 
1408 bool
1409 SymbolFileDWARF::ParseTemplateDIE (DWARFCompileUnit* dwarf_cu,
1410                                    const DWARFDebugInfoEntry *die,
1411                                    ClangASTContext::TemplateParameterInfos &template_param_infos)
1412 {
1413     const dw_tag_t tag = die->Tag();
1414 
1415     switch (tag)
1416     {
1417     case DW_TAG_template_type_parameter:
1418     case DW_TAG_template_value_parameter:
1419         {
1420             const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
1421 
1422             DWARFDebugInfoEntry::Attributes attributes;
1423             const size_t num_attributes = die->GetAttributes (this,
1424                                                               dwarf_cu,
1425                                                               fixed_form_sizes,
1426                                                               attributes);
1427             const char *name = NULL;
1428             Type *lldb_type = NULL;
1429             ClangASTType clang_type;
1430             uint64_t uval64 = 0;
1431             bool uval64_valid = false;
1432             if (num_attributes > 0)
1433             {
1434                 DWARFFormValue form_value;
1435                 for (size_t i=0; i<num_attributes; ++i)
1436                 {
1437                     const dw_attr_t attr = attributes.AttributeAtIndex(i);
1438 
1439                     switch (attr)
1440                     {
1441                         case DW_AT_name:
1442                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1443                                 name = form_value.AsCString(&get_debug_str_data());
1444                             break;
1445 
1446                         case DW_AT_type:
1447                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1448                             {
1449                                 const dw_offset_t type_die_offset = form_value.Reference(dwarf_cu);
1450                                 lldb_type = ResolveTypeUID(type_die_offset);
1451                                 if (lldb_type)
1452                                     clang_type = lldb_type->GetClangForwardType();
1453                             }
1454                             break;
1455 
1456                         case DW_AT_const_value:
1457                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1458                             {
1459                                 uval64_valid = true;
1460                                 uval64 = form_value.Unsigned();
1461                             }
1462                             break;
1463                         default:
1464                             break;
1465                     }
1466                 }
1467 
1468                 clang::ASTContext *ast = GetClangASTContext().getASTContext();
1469                 if (!clang_type)
1470                     clang_type = GetClangASTContext().GetBasicType(eBasicTypeVoid);
1471 
1472                 if (clang_type)
1473                 {
1474                     bool is_signed = false;
1475                     if (name && name[0])
1476                         template_param_infos.names.push_back(name);
1477                     else
1478                         template_param_infos.names.push_back(NULL);
1479 
1480                     if (tag == DW_TAG_template_value_parameter &&
1481                         lldb_type != NULL &&
1482                         clang_type.IsIntegerType (is_signed) &&
1483                         uval64_valid)
1484                     {
1485                         llvm::APInt apint (lldb_type->GetByteSize() * 8, uval64, is_signed);
1486                         template_param_infos.args.push_back (clang::TemplateArgument (*ast,
1487                                                                                       llvm::APSInt(apint),
1488                                                                                       clang_type.GetQualType()));
1489                     }
1490                     else
1491                     {
1492                         template_param_infos.args.push_back (clang::TemplateArgument (clang_type.GetQualType()));
1493                     }
1494                 }
1495                 else
1496                 {
1497                     return false;
1498                 }
1499 
1500             }
1501         }
1502         return true;
1503 
1504     default:
1505         break;
1506     }
1507     return false;
1508 }
1509 
1510 bool
1511 SymbolFileDWARF::ParseTemplateParameterInfos (DWARFCompileUnit* dwarf_cu,
1512                                               const DWARFDebugInfoEntry *parent_die,
1513                                               ClangASTContext::TemplateParameterInfos &template_param_infos)
1514 {
1515 
1516     if (parent_die == NULL)
1517         return false;
1518 
1519     Args template_parameter_names;
1520     for (const DWARFDebugInfoEntry *die = parent_die->GetFirstChild();
1521          die != NULL;
1522          die = die->GetSibling())
1523     {
1524         const dw_tag_t tag = die->Tag();
1525 
1526         switch (tag)
1527         {
1528             case DW_TAG_template_type_parameter:
1529             case DW_TAG_template_value_parameter:
1530                 ParseTemplateDIE (dwarf_cu, die, template_param_infos);
1531             break;
1532 
1533         default:
1534             break;
1535         }
1536     }
1537     if (template_param_infos.args.empty())
1538         return false;
1539     return template_param_infos.args.size() == template_param_infos.names.size();
1540 }
1541 
1542 clang::ClassTemplateDecl *
1543 SymbolFileDWARF::ParseClassTemplateDecl (clang::DeclContext *decl_ctx,
1544                                          lldb::AccessType access_type,
1545                                          const char *parent_name,
1546                                          int tag_decl_kind,
1547                                          const ClangASTContext::TemplateParameterInfos &template_param_infos)
1548 {
1549     if (template_param_infos.IsValid())
1550     {
1551         std::string template_basename(parent_name);
1552         template_basename.erase (template_basename.find('<'));
1553         ClangASTContext &ast = GetClangASTContext();
1554 
1555         return ast.CreateClassTemplateDecl (decl_ctx,
1556                                             access_type,
1557                                             template_basename.c_str(),
1558                                             tag_decl_kind,
1559                                             template_param_infos);
1560     }
1561     return NULL;
1562 }
1563 
1564 class SymbolFileDWARF::DelayedAddObjCClassProperty
1565 {
1566 public:
1567     DelayedAddObjCClassProperty
1568     (
1569         const ClangASTType     &class_opaque_type,
1570         const char             *property_name,
1571         const ClangASTType     &property_opaque_type,  // The property type is only required if you don't have an ivar decl
1572         clang::ObjCIvarDecl    *ivar_decl,
1573         const char             *property_setter_name,
1574         const char             *property_getter_name,
1575         uint32_t                property_attributes,
1576         const ClangASTMetadata *metadata
1577     ) :
1578         m_class_opaque_type     (class_opaque_type),
1579         m_property_name         (property_name),
1580         m_property_opaque_type  (property_opaque_type),
1581         m_ivar_decl             (ivar_decl),
1582         m_property_setter_name  (property_setter_name),
1583         m_property_getter_name  (property_getter_name),
1584         m_property_attributes   (property_attributes)
1585     {
1586         if (metadata != NULL)
1587         {
1588             m_metadata_ap.reset(new ClangASTMetadata());
1589             *m_metadata_ap = *metadata;
1590         }
1591     }
1592 
1593     DelayedAddObjCClassProperty (const DelayedAddObjCClassProperty &rhs)
1594     {
1595         *this = rhs;
1596     }
1597 
1598     DelayedAddObjCClassProperty& operator= (const DelayedAddObjCClassProperty &rhs)
1599     {
1600         m_class_opaque_type    = rhs.m_class_opaque_type;
1601         m_property_name        = rhs.m_property_name;
1602         m_property_opaque_type = rhs.m_property_opaque_type;
1603         m_ivar_decl            = rhs.m_ivar_decl;
1604         m_property_setter_name = rhs.m_property_setter_name;
1605         m_property_getter_name = rhs.m_property_getter_name;
1606         m_property_attributes  = rhs.m_property_attributes;
1607 
1608         if (rhs.m_metadata_ap.get())
1609         {
1610             m_metadata_ap.reset (new ClangASTMetadata());
1611             *m_metadata_ap = *rhs.m_metadata_ap;
1612         }
1613         return *this;
1614     }
1615 
1616     bool
1617     Finalize()
1618     {
1619         return m_class_opaque_type.AddObjCClassProperty (m_property_name,
1620                                                          m_property_opaque_type,
1621                                                          m_ivar_decl,
1622                                                          m_property_setter_name,
1623                                                          m_property_getter_name,
1624                                                          m_property_attributes,
1625                                                          m_metadata_ap.get());
1626     }
1627 private:
1628     ClangASTType            m_class_opaque_type;
1629     const char             *m_property_name;
1630     ClangASTType            m_property_opaque_type;
1631     clang::ObjCIvarDecl    *m_ivar_decl;
1632     const char             *m_property_setter_name;
1633     const char             *m_property_getter_name;
1634     uint32_t                m_property_attributes;
1635     std::unique_ptr<ClangASTMetadata> m_metadata_ap;
1636 };
1637 
1638 struct BitfieldInfo
1639 {
1640     uint64_t bit_size;
1641     uint64_t bit_offset;
1642 
1643     BitfieldInfo () :
1644         bit_size (LLDB_INVALID_ADDRESS),
1645         bit_offset (LLDB_INVALID_ADDRESS)
1646     {
1647     }
1648 
1649     void
1650     Clear()
1651     {
1652         bit_size = LLDB_INVALID_ADDRESS;
1653         bit_offset = LLDB_INVALID_ADDRESS;
1654     }
1655 
1656     bool IsValid ()
1657     {
1658         return (bit_size != LLDB_INVALID_ADDRESS) &&
1659                (bit_offset != LLDB_INVALID_ADDRESS);
1660     }
1661 };
1662 
1663 
1664 bool
1665 SymbolFileDWARF::ClassOrStructIsVirtual (DWARFCompileUnit* dwarf_cu,
1666                                          const DWARFDebugInfoEntry *parent_die)
1667 {
1668     if (parent_die)
1669     {
1670         for (const DWARFDebugInfoEntry *die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
1671         {
1672             dw_tag_t tag = die->Tag();
1673             bool check_virtuality = false;
1674             switch (tag)
1675             {
1676                 case DW_TAG_inheritance:
1677                 case DW_TAG_subprogram:
1678                     check_virtuality = true;
1679                     break;
1680                 default:
1681                     break;
1682             }
1683             if (check_virtuality)
1684             {
1685                 if (die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_virtuality, 0) != 0)
1686                     return true;
1687             }
1688         }
1689     }
1690     return false;
1691 }
1692 
1693 size_t
1694 SymbolFileDWARF::ParseChildMembers
1695 (
1696     const SymbolContext& sc,
1697     DWARFCompileUnit* dwarf_cu,
1698     const DWARFDebugInfoEntry *parent_die,
1699     ClangASTType &class_clang_type,
1700     const LanguageType class_language,
1701     std::vector<clang::CXXBaseSpecifier *>& base_classes,
1702     std::vector<int>& member_accessibilities,
1703     DWARFDIECollection& member_function_dies,
1704     DelayedPropertyList& delayed_properties,
1705     AccessType& default_accessibility,
1706     bool &is_a_class,
1707     LayoutInfo &layout_info
1708 )
1709 {
1710     if (parent_die == NULL)
1711         return 0;
1712 
1713     size_t count = 0;
1714     const DWARFDebugInfoEntry *die;
1715     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
1716     uint32_t member_idx = 0;
1717     BitfieldInfo last_field_info;
1718     ModuleSP module = GetObjectFile()->GetModule();
1719 
1720     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
1721     {
1722         dw_tag_t tag = die->Tag();
1723 
1724         switch (tag)
1725         {
1726         case DW_TAG_member:
1727         case DW_TAG_APPLE_property:
1728             {
1729                 DWARFDebugInfoEntry::Attributes attributes;
1730                 const size_t num_attributes = die->GetAttributes (this,
1731                                                                   dwarf_cu,
1732                                                                   fixed_form_sizes,
1733                                                                   attributes);
1734                 if (num_attributes > 0)
1735                 {
1736                     Declaration decl;
1737                     //DWARFExpression location;
1738                     const char *name = NULL;
1739                     const char *prop_name = NULL;
1740                     const char *prop_getter_name = NULL;
1741                     const char *prop_setter_name = NULL;
1742                     uint32_t prop_attributes = 0;
1743 
1744 
1745                     bool is_artificial = false;
1746                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
1747                     AccessType accessibility = eAccessNone;
1748                     uint32_t member_byte_offset = UINT32_MAX;
1749                     size_t byte_size = 0;
1750                     size_t bit_offset = 0;
1751                     size_t bit_size = 0;
1752                     bool is_external = false; // On DW_TAG_members, this means the member is static
1753                     uint32_t i;
1754                     for (i=0; i<num_attributes && !is_artificial; ++i)
1755                     {
1756                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
1757                         DWARFFormValue form_value;
1758                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1759                         {
1760                             switch (attr)
1761                             {
1762                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
1763                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
1764                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
1765                             case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
1766                             case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
1767                             case DW_AT_bit_offset:  bit_offset = form_value.Unsigned(); break;
1768                             case DW_AT_bit_size:    bit_size = form_value.Unsigned(); break;
1769                             case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
1770                             case DW_AT_data_member_location:
1771                                 if (form_value.BlockData())
1772                                 {
1773                                     Value initialValue(0);
1774                                     Value memberOffset(0);
1775                                     const DWARFDataExtractor& debug_info_data = get_debug_info_data();
1776                                     uint32_t block_length = form_value.Unsigned();
1777                                     uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
1778                                     if (DWARFExpression::Evaluate(NULL, // ExecutionContext *
1779                                                                   NULL, // ClangExpressionVariableList *
1780                                                                   NULL, // ClangExpressionDeclMap *
1781                                                                   NULL, // RegisterContext *
1782                                                                   module,
1783                                                                   debug_info_data,
1784                                                                   block_offset,
1785                                                                   block_length,
1786                                                                   eRegisterKindDWARF,
1787                                                                   &initialValue,
1788                                                                   memberOffset,
1789                                                                   NULL))
1790                                     {
1791                                         member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
1792                                     }
1793                                 }
1794                                 else
1795                                 {
1796                                     // With DWARF 3 and later, if the value is an integer constant,
1797                                     // this form value is the offset in bytes from the beginning
1798                                     // of the containing entity.
1799                                     member_byte_offset = form_value.Unsigned();
1800                                 }
1801                                 break;
1802 
1803                             case DW_AT_accessibility: accessibility = DW_ACCESS_to_AccessType (form_value.Unsigned()); break;
1804                             case DW_AT_artificial: is_artificial = form_value.Boolean(); break;
1805                             case DW_AT_APPLE_property_name:      prop_name = form_value.AsCString(&get_debug_str_data()); break;
1806                             case DW_AT_APPLE_property_getter:    prop_getter_name = form_value.AsCString(&get_debug_str_data()); break;
1807                             case DW_AT_APPLE_property_setter:    prop_setter_name = form_value.AsCString(&get_debug_str_data()); break;
1808                             case DW_AT_APPLE_property_attribute: prop_attributes = form_value.Unsigned(); break;
1809                             case DW_AT_external:                 is_external = form_value.Boolean(); break;
1810 
1811                             default:
1812                             case DW_AT_declaration:
1813                             case DW_AT_description:
1814                             case DW_AT_mutable:
1815                             case DW_AT_visibility:
1816                             case DW_AT_sibling:
1817                                 break;
1818                             }
1819                         }
1820                     }
1821 
1822                     if (prop_name)
1823                     {
1824                         ConstString fixed_getter;
1825                         ConstString fixed_setter;
1826 
1827                         // Check if the property getter/setter were provided as full
1828                         // names.  We want basenames, so we extract them.
1829 
1830                         if (prop_getter_name && prop_getter_name[0] == '-')
1831                         {
1832                             ObjCLanguageRuntime::MethodName prop_getter_method(prop_getter_name, true);
1833                             prop_getter_name = prop_getter_method.GetSelector().GetCString();
1834                         }
1835 
1836                         if (prop_setter_name && prop_setter_name[0] == '-')
1837                         {
1838                             ObjCLanguageRuntime::MethodName prop_setter_method(prop_setter_name, true);
1839                             prop_setter_name = prop_setter_method.GetSelector().GetCString();
1840                         }
1841 
1842                         // If the names haven't been provided, they need to be
1843                         // filled in.
1844 
1845                         if (!prop_getter_name)
1846                         {
1847                             prop_getter_name = prop_name;
1848                         }
1849                         if (!prop_setter_name && prop_name[0] && !(prop_attributes & DW_APPLE_PROPERTY_readonly))
1850                         {
1851                             StreamString ss;
1852 
1853                             ss.Printf("set%c%s:",
1854                                       toupper(prop_name[0]),
1855                                       &prop_name[1]);
1856 
1857                             fixed_setter.SetCString(ss.GetData());
1858                             prop_setter_name = fixed_setter.GetCString();
1859                         }
1860                     }
1861 
1862                     // Clang has a DWARF generation bug where sometimes it
1863                     // represents fields that are references with bad byte size
1864                     // and bit size/offset information such as:
1865                     //
1866                     //  DW_AT_byte_size( 0x00 )
1867                     //  DW_AT_bit_size( 0x40 )
1868                     //  DW_AT_bit_offset( 0xffffffffffffffc0 )
1869                     //
1870                     // So check the bit offset to make sure it is sane, and if
1871                     // the values are not sane, remove them. If we don't do this
1872                     // then we will end up with a crash if we try to use this
1873                     // type in an expression when clang becomes unhappy with its
1874                     // recycled debug info.
1875 
1876                     if (bit_offset > 128)
1877                     {
1878                         bit_size = 0;
1879                         bit_offset = 0;
1880                     }
1881 
1882                     // FIXME: Make Clang ignore Objective-C accessibility for expressions
1883                     if (class_language == eLanguageTypeObjC ||
1884                         class_language == eLanguageTypeObjC_plus_plus)
1885                         accessibility = eAccessNone;
1886 
1887                     if (member_idx == 0 && !is_artificial && name && (strstr (name, "_vptr$") == name))
1888                     {
1889                         // Not all compilers will mark the vtable pointer
1890                         // member as artificial (llvm-gcc). We can't have
1891                         // the virtual members in our classes otherwise it
1892                         // throws off all child offsets since we end up
1893                         // having and extra pointer sized member in our
1894                         // class layouts.
1895                         is_artificial = true;
1896                     }
1897 
1898                     // Handle static members
1899                     if (is_external && member_byte_offset == UINT32_MAX)
1900                     {
1901                         Type *var_type = ResolveTypeUID(encoding_uid);
1902 
1903                         if (var_type)
1904                         {
1905                             if (accessibility == eAccessNone)
1906                                 accessibility = eAccessPublic;
1907                             class_clang_type.AddVariableToRecordType (name,
1908                                                                       var_type->GetClangLayoutType(),
1909                                                                       accessibility);
1910                         }
1911                         break;
1912                     }
1913 
1914                     if (is_artificial == false)
1915                     {
1916                         Type *member_type = ResolveTypeUID(encoding_uid);
1917 
1918                         clang::FieldDecl *field_decl = NULL;
1919                         if (tag == DW_TAG_member)
1920                         {
1921                             if (member_type)
1922                             {
1923                                 if (accessibility == eAccessNone)
1924                                     accessibility = default_accessibility;
1925                                 member_accessibilities.push_back(accessibility);
1926 
1927                                 uint64_t field_bit_offset = (member_byte_offset == UINT32_MAX ? 0 : (member_byte_offset * 8));
1928                                 if (bit_size > 0)
1929                                 {
1930 
1931                                     BitfieldInfo this_field_info;
1932                                     this_field_info.bit_offset = field_bit_offset;
1933                                     this_field_info.bit_size = bit_size;
1934 
1935                                     /////////////////////////////////////////////////////////////
1936                                     // How to locate a field given the DWARF debug information
1937                                     //
1938                                     // AT_byte_size indicates the size of the word in which the
1939                                     // bit offset must be interpreted.
1940                                     //
1941                                     // AT_data_member_location indicates the byte offset of the
1942                                     // word from the base address of the structure.
1943                                     //
1944                                     // AT_bit_offset indicates how many bits into the word
1945                                     // (according to the host endianness) the low-order bit of
1946                                     // the field starts.  AT_bit_offset can be negative.
1947                                     //
1948                                     // AT_bit_size indicates the size of the field in bits.
1949                                     /////////////////////////////////////////////////////////////
1950 
1951                                     if (byte_size == 0)
1952                                         byte_size = member_type->GetByteSize();
1953 
1954                                     if (GetObjectFile()->GetByteOrder() == eByteOrderLittle)
1955                                     {
1956                                         this_field_info.bit_offset += byte_size * 8;
1957                                         this_field_info.bit_offset -= (bit_offset + bit_size);
1958                                     }
1959                                     else
1960                                     {
1961                                         this_field_info.bit_offset += bit_offset;
1962                                     }
1963 
1964                                     // Update the field bit offset we will report for layout
1965                                     field_bit_offset = this_field_info.bit_offset;
1966 
1967                                     // If the member to be emitted did not start on a character boundary and there is
1968                                     // empty space between the last field and this one, then we need to emit an
1969                                     // anonymous member filling up the space up to its start.  There are three cases
1970                                     // here:
1971                                     //
1972                                     // 1 If the previous member ended on a character boundary, then we can emit an
1973                                     //   anonymous member starting at the most recent character boundary.
1974                                     //
1975                                     // 2 If the previous member did not end on a character boundary and the distance
1976                                     //   from the end of the previous member to the current member is less than a
1977                                     //   word width, then we can emit an anonymous member starting right after the
1978                                     //   previous member and right before this member.
1979                                     //
1980                                     // 3 If the previous member did not end on a character boundary and the distance
1981                                     //   from the end of the previous member to the current member is greater than
1982                                     //   or equal a word width, then we act as in Case 1.
1983 
1984                                     const uint64_t character_width = 8;
1985                                     const uint64_t word_width = 32;
1986 
1987                                     // Objective-C has invalid DW_AT_bit_offset values in older versions
1988                                     // of clang, so we have to be careful and only insert unnammed bitfields
1989                                     // if we have a new enough clang.
1990                                     bool detect_unnamed_bitfields = true;
1991 
1992                                     if (class_language == eLanguageTypeObjC || class_language == eLanguageTypeObjC_plus_plus)
1993                                         detect_unnamed_bitfields = dwarf_cu->Supports_unnamed_objc_bitfields ();
1994 
1995                                     if (detect_unnamed_bitfields)
1996                                     {
1997                                         BitfieldInfo anon_field_info;
1998 
1999                                         if ((this_field_info.bit_offset % character_width) != 0) // not char aligned
2000                                         {
2001                                             uint64_t last_field_end = 0;
2002 
2003                                             if (last_field_info.IsValid())
2004                                                 last_field_end = last_field_info.bit_offset + last_field_info.bit_size;
2005 
2006                                             if (this_field_info.bit_offset != last_field_end)
2007                                             {
2008                                                 if (((last_field_end % character_width) == 0) ||                    // case 1
2009                                                     (this_field_info.bit_offset - last_field_end >= word_width))    // case 3
2010                                                 {
2011                                                     anon_field_info.bit_size = this_field_info.bit_offset % character_width;
2012                                                     anon_field_info.bit_offset = this_field_info.bit_offset - anon_field_info.bit_size;
2013                                                 }
2014                                                 else                                                                // case 2
2015                                                 {
2016                                                     anon_field_info.bit_size = this_field_info.bit_offset - last_field_end;
2017                                                     anon_field_info.bit_offset = last_field_end;
2018                                                 }
2019                                             }
2020                                         }
2021 
2022                                         if (anon_field_info.IsValid())
2023                                         {
2024                                             clang::FieldDecl *unnamed_bitfield_decl = class_clang_type.AddFieldToRecordType (NULL,
2025                                                                                                                              GetClangASTContext().GetBuiltinTypeForEncodingAndBitSize(eEncodingSint, word_width),
2026                                                                                                                              accessibility,
2027                                                                                                                              anon_field_info.bit_size);
2028 
2029                                             layout_info.field_offsets.insert(std::make_pair(unnamed_bitfield_decl, anon_field_info.bit_offset));
2030                                         }
2031                                     }
2032                                     last_field_info = this_field_info;
2033                                 }
2034                                 else
2035                                 {
2036                                     last_field_info.Clear();
2037                                 }
2038 
2039                                 ClangASTType member_clang_type = member_type->GetClangLayoutType();
2040 
2041                                 {
2042                                     // Older versions of clang emit array[0] and array[1] in the same way (<rdar://problem/12566646>).
2043                                     // If the current field is at the end of the structure, then there is definitely no room for extra
2044                                     // elements and we override the type to array[0].
2045 
2046                                     ClangASTType member_array_element_type;
2047                                     uint64_t member_array_size;
2048                                     bool member_array_is_incomplete;
2049 
2050                                     if (member_clang_type.IsArrayType(&member_array_element_type,
2051                                                                       &member_array_size,
2052                                                                       &member_array_is_incomplete) &&
2053                                         !member_array_is_incomplete)
2054                                     {
2055                                         uint64_t parent_byte_size = parent_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_byte_size, UINT64_MAX);
2056 
2057                                         if (member_byte_offset >= parent_byte_size)
2058                                         {
2059                                             if (member_array_size != 1)
2060                                             {
2061                                                 GetObjectFile()->GetModule()->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,
2062                                                                                            MakeUserID(die->GetOffset()),
2063                                                                                            name,
2064                                                                                            encoding_uid,
2065                                                                                            MakeUserID(parent_die->GetOffset()));
2066                                             }
2067 
2068                                             member_clang_type = GetClangASTContext().CreateArrayType(member_array_element_type, 0, false);
2069                                         }
2070                                     }
2071                                 }
2072 
2073                                 field_decl = class_clang_type.AddFieldToRecordType (name,
2074                                                                                     member_clang_type,
2075                                                                                     accessibility,
2076                                                                                     bit_size);
2077 
2078                                 GetClangASTContext().SetMetadataAsUserID (field_decl, MakeUserID(die->GetOffset()));
2079 
2080                                 layout_info.field_offsets.insert(std::make_pair(field_decl, field_bit_offset));
2081 
2082                             }
2083                             else
2084                             {
2085                                 if (name)
2086                                     GetObjectFile()->GetModule()->ReportError ("0x%8.8" PRIx64 ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64 " which was unable to be parsed",
2087                                                                                MakeUserID(die->GetOffset()),
2088                                                                                name,
2089                                                                                encoding_uid);
2090                                 else
2091                                     GetObjectFile()->GetModule()->ReportError ("0x%8.8" PRIx64 ": DW_TAG_member refers to type 0x%8.8" PRIx64 " which was unable to be parsed",
2092                                                                                MakeUserID(die->GetOffset()),
2093                                                                                encoding_uid);
2094                             }
2095                         }
2096 
2097                         if (prop_name != NULL)
2098                         {
2099                             clang::ObjCIvarDecl *ivar_decl = NULL;
2100 
2101                             if (field_decl)
2102                             {
2103                                 ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl);
2104                                 assert (ivar_decl != NULL);
2105                             }
2106 
2107                             ClangASTMetadata metadata;
2108                             metadata.SetUserID (MakeUserID(die->GetOffset()));
2109                             delayed_properties.push_back(DelayedAddObjCClassProperty(class_clang_type,
2110                                                                                      prop_name,
2111                                                                                      member_type->GetClangLayoutType(),
2112                                                                                      ivar_decl,
2113                                                                                      prop_setter_name,
2114                                                                                      prop_getter_name,
2115                                                                                      prop_attributes,
2116                                                                                      &metadata));
2117 
2118                             if (ivar_decl)
2119                                 GetClangASTContext().SetMetadataAsUserID (ivar_decl, MakeUserID(die->GetOffset()));
2120                         }
2121                     }
2122                 }
2123                 ++member_idx;
2124             }
2125             break;
2126 
2127         case DW_TAG_subprogram:
2128             // Let the type parsing code handle this one for us.
2129             member_function_dies.Append (die);
2130             break;
2131 
2132         case DW_TAG_inheritance:
2133             {
2134                 is_a_class = true;
2135                 if (default_accessibility == eAccessNone)
2136                     default_accessibility = eAccessPrivate;
2137                 // TODO: implement DW_TAG_inheritance type parsing
2138                 DWARFDebugInfoEntry::Attributes attributes;
2139                 const size_t num_attributes = die->GetAttributes (this,
2140                                                                   dwarf_cu,
2141                                                                   fixed_form_sizes,
2142                                                                   attributes);
2143                 if (num_attributes > 0)
2144                 {
2145                     Declaration decl;
2146                     DWARFExpression location;
2147                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
2148                     AccessType accessibility = default_accessibility;
2149                     bool is_virtual = false;
2150                     bool is_base_of_class = true;
2151                     off_t member_byte_offset = 0;
2152                     uint32_t i;
2153                     for (i=0; i<num_attributes; ++i)
2154                     {
2155                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
2156                         DWARFFormValue form_value;
2157                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
2158                         {
2159                             switch (attr)
2160                             {
2161                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
2162                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
2163                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
2164                             case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
2165                             case DW_AT_data_member_location:
2166                                 if (form_value.BlockData())
2167                                 {
2168                                     Value initialValue(0);
2169                                     Value memberOffset(0);
2170                                     const DWARFDataExtractor& debug_info_data = get_debug_info_data();
2171                                     uint32_t block_length = form_value.Unsigned();
2172                                     uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
2173                                     if (DWARFExpression::Evaluate (NULL,
2174                                                                    NULL,
2175                                                                    NULL,
2176                                                                    NULL,
2177                                                                    module,
2178                                                                    debug_info_data,
2179                                                                    block_offset,
2180                                                                    block_length,
2181                                                                    eRegisterKindDWARF,
2182                                                                    &initialValue,
2183                                                                    memberOffset,
2184                                                                    NULL))
2185                                     {
2186                                         member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
2187                                     }
2188                                 }
2189                                 else
2190                                 {
2191                                     // With DWARF 3 and later, if the value is an integer constant,
2192                                     // this form value is the offset in bytes from the beginning
2193                                     // of the containing entity.
2194                                     member_byte_offset = form_value.Unsigned();
2195                                 }
2196                                 break;
2197 
2198                             case DW_AT_accessibility:
2199                                 accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
2200                                 break;
2201 
2202                             case DW_AT_virtuality:
2203                                 is_virtual = form_value.Boolean();
2204                                 break;
2205 
2206                             case DW_AT_sibling:
2207                                 break;
2208 
2209                             default:
2210                                 break;
2211                             }
2212                         }
2213                     }
2214 
2215                     Type *base_class_type = ResolveTypeUID(encoding_uid);
2216                     assert(base_class_type);
2217 
2218                     ClangASTType base_class_clang_type = base_class_type->GetClangFullType();
2219                     assert (base_class_clang_type);
2220                     if (class_language == eLanguageTypeObjC)
2221                     {
2222                         class_clang_type.SetObjCSuperClass(base_class_clang_type);
2223                     }
2224                     else
2225                     {
2226                         base_classes.push_back (base_class_clang_type.CreateBaseClassSpecifier (accessibility,
2227                                                                                                is_virtual,
2228                                                                                                is_base_of_class));
2229 
2230                         if (is_virtual)
2231                         {
2232                             // Do not specify any offset for virtual inheritance. The DWARF produced by clang doesn't
2233                             // give us a constant offset, but gives us a DWARF expressions that requires an actual object
2234                             // in memory. the DW_AT_data_member_location for a virtual base class looks like:
2235                             //      DW_AT_data_member_location( DW_OP_dup, DW_OP_deref, DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref, DW_OP_plus )
2236                             // Given this, there is really no valid response we can give to clang for virtual base
2237                             // class offsets, and this should eventually be removed from LayoutRecordType() in the external
2238                             // AST source in clang.
2239                         }
2240                         else
2241                         {
2242                             layout_info.base_offsets.insert(std::make_pair(base_class_clang_type.GetAsCXXRecordDecl(),
2243                                                                            clang::CharUnits::fromQuantity(member_byte_offset)));
2244                         }
2245                     }
2246                 }
2247             }
2248             break;
2249 
2250         default:
2251             break;
2252         }
2253     }
2254 
2255     return count;
2256 }
2257 
2258 
2259 clang::DeclContext*
2260 SymbolFileDWARF::GetClangDeclContextContainingTypeUID (lldb::user_id_t type_uid)
2261 {
2262     DWARFDebugInfo* debug_info = DebugInfo();
2263     if (debug_info && UserIDMatches(type_uid))
2264     {
2265         DWARFCompileUnitSP cu_sp;
2266         const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(type_uid, &cu_sp);
2267         if (die)
2268             return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
2269     }
2270     return NULL;
2271 }
2272 
2273 clang::DeclContext*
2274 SymbolFileDWARF::GetClangDeclContextForTypeUID (const lldb_private::SymbolContext &sc, lldb::user_id_t type_uid)
2275 {
2276     if (UserIDMatches(type_uid))
2277         return GetClangDeclContextForDIEOffset (sc, type_uid);
2278     return NULL;
2279 }
2280 
2281 Type*
2282 SymbolFileDWARF::ResolveTypeUID (lldb::user_id_t type_uid)
2283 {
2284     if (UserIDMatches(type_uid))
2285     {
2286         DWARFDebugInfo* debug_info = DebugInfo();
2287         if (debug_info)
2288         {
2289             DWARFCompileUnitSP cu_sp;
2290             const DWARFDebugInfoEntry* type_die = debug_info->GetDIEPtr(type_uid, &cu_sp);
2291             const bool assert_not_being_parsed = true;
2292             return ResolveTypeUID (cu_sp.get(), type_die, assert_not_being_parsed);
2293         }
2294     }
2295     return NULL;
2296 }
2297 
2298 Type*
2299 SymbolFileDWARF::ResolveTypeUID (DWARFCompileUnit* cu, const DWARFDebugInfoEntry* die, bool assert_not_being_parsed)
2300 {
2301     if (die != NULL)
2302     {
2303         Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
2304         if (log)
2305             GetObjectFile()->GetModule()->LogMessage (log,
2306                                                       "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
2307                                                       die->GetOffset(),
2308                                                       DW_TAG_value_to_name(die->Tag()),
2309                                                       die->GetName(this, cu));
2310 
2311         // We might be coming in in the middle of a type tree (a class
2312         // withing a class, an enum within a class), so parse any needed
2313         // parent DIEs before we get to this one...
2314         const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
2315         switch (decl_ctx_die->Tag())
2316         {
2317             case DW_TAG_structure_type:
2318             case DW_TAG_union_type:
2319             case DW_TAG_class_type:
2320             {
2321                 // Get the type, which could be a forward declaration
2322                 if (log)
2323                     GetObjectFile()->GetModule()->LogMessage (log,
2324                                                               "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent forward type for 0x%8.8x",
2325                                                               die->GetOffset(),
2326                                                               DW_TAG_value_to_name(die->Tag()),
2327                                                               die->GetName(this, cu),
2328                                                               decl_ctx_die->GetOffset());
2329 //
2330 //                Type *parent_type = ResolveTypeUID (cu, decl_ctx_die, assert_not_being_parsed);
2331 //                if (child_requires_parent_class_union_or_struct_to_be_completed(die->Tag()))
2332 //                {
2333 //                    if (log)
2334 //                        GetObjectFile()->GetModule()->LogMessage (log,
2335 //                                                                  "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent full type for 0x%8.8x since die is a function",
2336 //                                                                  die->GetOffset(),
2337 //                                                                  DW_TAG_value_to_name(die->Tag()),
2338 //                                                                  die->GetName(this, cu),
2339 //                                                                  decl_ctx_die->GetOffset());
2340 //                    // Ask the type to complete itself if it already hasn't since if we
2341 //                    // want a function (method or static) from a class, the class must
2342 //                    // create itself and add it's own methods and class functions.
2343 //                    if (parent_type)
2344 //                        parent_type->GetClangFullType();
2345 //                }
2346             }
2347             break;
2348 
2349             default:
2350                 break;
2351         }
2352         return ResolveType (cu, die);
2353     }
2354     return NULL;
2355 }
2356 
2357 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
2358 // SymbolFileDWARF objects to detect if this DWARF file is the one that
2359 // can resolve a clang_type.
2360 bool
2361 SymbolFileDWARF::HasForwardDeclForClangType (const ClangASTType &clang_type)
2362 {
2363     ClangASTType clang_type_no_qualifiers = clang_type.RemoveFastQualifiers();
2364     const DWARFDebugInfoEntry* die = m_forward_decl_clang_type_to_die.lookup (clang_type_no_qualifiers.GetOpaqueQualType());
2365     return die != NULL;
2366 }
2367 
2368 
2369 bool
2370 SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (ClangASTType &clang_type)
2371 {
2372     // We have a struct/union/class/enum that needs to be fully resolved.
2373     ClangASTType clang_type_no_qualifiers = clang_type.RemoveFastQualifiers();
2374     const DWARFDebugInfoEntry* die = m_forward_decl_clang_type_to_die.lookup (clang_type_no_qualifiers.GetOpaqueQualType());
2375     if (die == NULL)
2376     {
2377         // We have already resolved this type...
2378         return true;
2379     }
2380     // Once we start resolving this type, remove it from the forward declaration
2381     // map in case anyone child members or other types require this type to get resolved.
2382     // The type will get resolved when all of the calls to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition
2383     // are done.
2384     m_forward_decl_clang_type_to_die.erase (clang_type_no_qualifiers.GetOpaqueQualType());
2385 
2386     // Disable external storage for this type so we don't get anymore
2387     // clang::ExternalASTSource queries for this type.
2388     clang_type.SetHasExternalStorage (false);
2389 
2390     DWARFDebugInfo* debug_info = DebugInfo();
2391 
2392     DWARFCompileUnit *dwarf_cu = debug_info->GetCompileUnitContainingDIE (die->GetOffset()).get();
2393     Type *type = m_die_to_type.lookup (die);
2394 
2395     const dw_tag_t tag = die->Tag();
2396 
2397     Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
2398     if (log)
2399         GetObjectFile()->GetModule()->LogMessageVerboseBacktrace (log,
2400                                                                   "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
2401                                                                   MakeUserID(die->GetOffset()),
2402                                                                   DW_TAG_value_to_name(tag),
2403                                                                   type->GetName().AsCString());
2404     assert (clang_type);
2405     DWARFDebugInfoEntry::Attributes attributes;
2406 
2407     switch (tag)
2408     {
2409     case DW_TAG_structure_type:
2410     case DW_TAG_union_type:
2411     case DW_TAG_class_type:
2412         {
2413             LayoutInfo layout_info;
2414 
2415             {
2416                 if (die->HasChildren())
2417                 {
2418                     LanguageType class_language = eLanguageTypeUnknown;
2419                     if (clang_type.IsObjCObjectOrInterfaceType())
2420                     {
2421                         class_language = eLanguageTypeObjC;
2422                         // For objective C we don't start the definition when
2423                         // the class is created.
2424                         clang_type.StartTagDeclarationDefinition ();
2425                     }
2426 
2427                     int tag_decl_kind = -1;
2428                     AccessType default_accessibility = eAccessNone;
2429                     if (tag == DW_TAG_structure_type)
2430                     {
2431                         tag_decl_kind = clang::TTK_Struct;
2432                         default_accessibility = eAccessPublic;
2433                     }
2434                     else if (tag == DW_TAG_union_type)
2435                     {
2436                         tag_decl_kind = clang::TTK_Union;
2437                         default_accessibility = eAccessPublic;
2438                     }
2439                     else if (tag == DW_TAG_class_type)
2440                     {
2441                         tag_decl_kind = clang::TTK_Class;
2442                         default_accessibility = eAccessPrivate;
2443                     }
2444 
2445                     SymbolContext sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
2446                     std::vector<clang::CXXBaseSpecifier *> base_classes;
2447                     std::vector<int> member_accessibilities;
2448                     bool is_a_class = false;
2449                     // Parse members and base classes first
2450                     DWARFDIECollection member_function_dies;
2451 
2452                     DelayedPropertyList delayed_properties;
2453                     ParseChildMembers (sc,
2454                                        dwarf_cu,
2455                                        die,
2456                                        clang_type,
2457                                        class_language,
2458                                        base_classes,
2459                                        member_accessibilities,
2460                                        member_function_dies,
2461                                        delayed_properties,
2462                                        default_accessibility,
2463                                        is_a_class,
2464                                        layout_info);
2465 
2466                     // Now parse any methods if there were any...
2467                     size_t num_functions = member_function_dies.Size();
2468                     if (num_functions > 0)
2469                     {
2470                         for (size_t i=0; i<num_functions; ++i)
2471                         {
2472                             ResolveType(dwarf_cu, member_function_dies.GetDIEPtrAtIndex(i));
2473                         }
2474                     }
2475 
2476                     if (class_language == eLanguageTypeObjC)
2477                     {
2478                         ConstString class_name (clang_type.GetTypeName());
2479                         if (class_name)
2480                         {
2481                             DIEArray method_die_offsets;
2482                             if (m_using_apple_tables)
2483                             {
2484                                 if (m_apple_objc_ap.get())
2485                                     m_apple_objc_ap->FindByName(class_name.GetCString(), method_die_offsets);
2486                             }
2487                             else
2488                             {
2489                                 if (!m_indexed)
2490                                     Index ();
2491 
2492                                 m_objc_class_selectors_index.Find (class_name, method_die_offsets);
2493                             }
2494 
2495                             if (!method_die_offsets.empty())
2496                             {
2497                                 DWARFDebugInfo* debug_info = DebugInfo();
2498 
2499                                 DWARFCompileUnit* method_cu = NULL;
2500                                 const size_t num_matches = method_die_offsets.size();
2501                                 for (size_t i=0; i<num_matches; ++i)
2502                                 {
2503                                     const dw_offset_t die_offset = method_die_offsets[i];
2504                                     DWARFDebugInfoEntry *method_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &method_cu);
2505 
2506                                     if (method_die)
2507                                         ResolveType (method_cu, method_die);
2508                                     else
2509                                     {
2510                                         if (m_using_apple_tables)
2511                                         {
2512                                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_objc accelerator table had bad die 0x%8.8x for '%s')\n",
2513                                                                                                        die_offset, class_name.GetCString());
2514                                         }
2515                                     }
2516                                 }
2517                             }
2518 
2519                             for (DelayedPropertyList::iterator pi = delayed_properties.begin(), pe = delayed_properties.end();
2520                                  pi != pe;
2521                                  ++pi)
2522                                 pi->Finalize();
2523                         }
2524                     }
2525 
2526                     // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we
2527                     // need to tell the clang type it is actually a class.
2528                     if (class_language != eLanguageTypeObjC)
2529                     {
2530                         if (is_a_class && tag_decl_kind != clang::TTK_Class)
2531                             clang_type.SetTagTypeKind (clang::TTK_Class);
2532                     }
2533 
2534                     // Since DW_TAG_structure_type gets used for both classes
2535                     // and structures, we may need to set any DW_TAG_member
2536                     // fields to have a "private" access if none was specified.
2537                     // When we parsed the child members we tracked that actual
2538                     // accessibility value for each DW_TAG_member in the
2539                     // "member_accessibilities" array. If the value for the
2540                     // member is zero, then it was set to the "default_accessibility"
2541                     // which for structs was "public". Below we correct this
2542                     // by setting any fields to "private" that weren't correctly
2543                     // set.
2544                     if (is_a_class && !member_accessibilities.empty())
2545                     {
2546                         // This is a class and all members that didn't have
2547                         // their access specified are private.
2548                         clang_type.SetDefaultAccessForRecordFields (eAccessPrivate,
2549                                                                     &member_accessibilities.front(),
2550                                                                     member_accessibilities.size());
2551                     }
2552 
2553                     if (!base_classes.empty())
2554                     {
2555                         // Make sure all base classes refer to complete types and not
2556                         // forward declarations. If we don't do this, clang will crash
2557                         // with an assertion in the call to clang_type.SetBaseClassesForClassType()
2558                         bool base_class_error = false;
2559                         for (auto &base_class : base_classes)
2560                         {
2561                             clang::TypeSourceInfo *type_source_info = base_class->getTypeSourceInfo();
2562                             if (type_source_info)
2563                             {
2564                                 ClangASTType base_class_type (GetClangASTContext().getASTContext(), type_source_info->getType());
2565                                 if (base_class_type.GetCompleteType() == false)
2566                                 {
2567                                     if (!base_class_error)
2568                                     {
2569                                         GetObjectFile()->GetModule()->ReportError ("DWARF DIE at 0x%8.8x for class '%s' has a base class '%s' that is a forward declaration, not a complete definition.\nPlease file a bug against the compiler and include the preprocessed output for %s",
2570                                                                                    die->GetOffset(),
2571                                                                                    die->GetName(this, dwarf_cu),
2572                                                                                    base_class_type.GetTypeName().GetCString(),
2573                                                                                    sc.comp_unit ? sc.comp_unit->GetPath().c_str() : "the source file");
2574                                     }
2575                                     // We have no choice other than to pretend that the base class
2576                                     // is complete. If we don't do this, clang will crash when we
2577                                     // call setBases() inside of "clang_type.SetBaseClassesForClassType()"
2578                                     // below. Since we provide layout assistance, all ivars in this
2579                                     // class and other classe will be fine, this is the best we can do
2580                                     // short of crashing.
2581                                     base_class_type.StartTagDeclarationDefinition ();
2582                                     base_class_type.CompleteTagDeclarationDefinition ();
2583                                 }
2584                             }
2585                         }
2586                         clang_type.SetBaseClassesForClassType (&base_classes.front(),
2587                                                                base_classes.size());
2588 
2589                         // Clang will copy each CXXBaseSpecifier in "base_classes"
2590                         // so we have to free them all.
2591                         ClangASTType::DeleteBaseClassSpecifiers (&base_classes.front(),
2592                                                                  base_classes.size());
2593                     }
2594                 }
2595             }
2596 
2597             clang_type.BuildIndirectFields ();
2598             clang_type.CompleteTagDeclarationDefinition ();
2599 
2600             if (!layout_info.field_offsets.empty() ||
2601                 !layout_info.base_offsets.empty()  ||
2602                 !layout_info.vbase_offsets.empty() )
2603             {
2604                 if (type)
2605                     layout_info.bit_size = type->GetByteSize() * 8;
2606                 if (layout_info.bit_size == 0)
2607                     layout_info.bit_size = die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_byte_size, 0) * 8;
2608 
2609                 clang::CXXRecordDecl *record_decl = clang_type.GetAsCXXRecordDecl();
2610                 if (record_decl)
2611                 {
2612                     if (log)
2613                     {
2614                         GetObjectFile()->GetModule()->LogMessage (log,
2615                                                                   "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) caching layout info for record_decl = %p, bit_size = %" PRIu64 ", alignment = %" PRIu64 ", field_offsets[%u], base_offsets[%u], vbase_offsets[%u])",
2616                                                                   static_cast<void*>(clang_type.GetOpaqueQualType()),
2617                                                                   static_cast<void*>(record_decl),
2618                                                                   layout_info.bit_size,
2619                                                                   layout_info.alignment,
2620                                                                   static_cast<uint32_t>(layout_info.field_offsets.size()),
2621                                                                   static_cast<uint32_t>(layout_info.base_offsets.size()),
2622                                                                   static_cast<uint32_t>(layout_info.vbase_offsets.size()));
2623 
2624                         uint32_t idx;
2625                         {
2626                         llvm::DenseMap <const clang::FieldDecl *, uint64_t>::const_iterator pos, end = layout_info.field_offsets.end();
2627                         for (idx = 0, pos = layout_info.field_offsets.begin(); pos != end; ++pos, ++idx)
2628                         {
2629                             GetObjectFile()->GetModule()->LogMessage (log,
2630                                                                       "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) field[%u] = { bit_offset=%u, name='%s' }",
2631                                                                       static_cast<void*>(clang_type.GetOpaqueQualType()),
2632                                                                       idx,
2633                                                                       static_cast<uint32_t>(pos->second),
2634                                                                       pos->first->getNameAsString().c_str());
2635                         }
2636                         }
2637 
2638                         {
2639                         llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits>::const_iterator base_pos, base_end = layout_info.base_offsets.end();
2640                         for (idx = 0, base_pos = layout_info.base_offsets.begin(); base_pos != base_end; ++base_pos, ++idx)
2641                         {
2642                             GetObjectFile()->GetModule()->LogMessage (log,
2643                                                                       "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) base[%u] = { byte_offset=%u, name='%s' }",
2644                                                                       clang_type.GetOpaqueQualType(),
2645                                                                       idx,
2646                                                                       (uint32_t)base_pos->second.getQuantity(),
2647                                                                       base_pos->first->getNameAsString().c_str());
2648                         }
2649                         }
2650                         {
2651                         llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits>::const_iterator vbase_pos, vbase_end = layout_info.vbase_offsets.end();
2652                         for (idx = 0, vbase_pos = layout_info.vbase_offsets.begin(); vbase_pos != vbase_end; ++vbase_pos, ++idx)
2653                         {
2654                             GetObjectFile()->GetModule()->LogMessage (log,
2655                                                                       "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) vbase[%u] = { byte_offset=%u, name='%s' }",
2656                                                                       static_cast<void*>(clang_type.GetOpaqueQualType()),
2657                                                                       idx,
2658                                                                       static_cast<uint32_t>(vbase_pos->second.getQuantity()),
2659                                                                       vbase_pos->first->getNameAsString().c_str());
2660                         }
2661                         }
2662                     }
2663                     m_record_decl_to_layout_map.insert(std::make_pair(record_decl, layout_info));
2664                 }
2665             }
2666         }
2667 
2668         return (bool)clang_type;
2669 
2670     case DW_TAG_enumeration_type:
2671         clang_type.StartTagDeclarationDefinition ();
2672         if (die->HasChildren())
2673         {
2674             SymbolContext sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
2675             bool is_signed = false;
2676             clang_type.IsIntegerType(is_signed);
2677             ParseChildEnumerators(sc, clang_type, is_signed, type->GetByteSize(), dwarf_cu, die);
2678         }
2679         clang_type.CompleteTagDeclarationDefinition ();
2680         return (bool)clang_type;
2681 
2682     default:
2683         assert(false && "not a forward clang type decl!");
2684         break;
2685     }
2686     return false;
2687 }
2688 
2689 Type*
2690 SymbolFileDWARF::ResolveType (DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry* type_die, bool assert_not_being_parsed)
2691 {
2692     if (type_die != NULL)
2693     {
2694         Type *type = m_die_to_type.lookup (type_die);
2695 
2696         if (type == NULL)
2697             type = GetTypeForDIE (dwarf_cu, type_die).get();
2698 
2699         if (assert_not_being_parsed)
2700         {
2701             if (type != DIE_IS_BEING_PARSED)
2702                 return type;
2703 
2704             GetObjectFile()->GetModule()->ReportError ("Parsing a die that is being parsed die: 0x%8.8x: %s %s",
2705                                                        type_die->GetOffset(),
2706                                                        DW_TAG_value_to_name(type_die->Tag()),
2707                                                        type_die->GetName(this, dwarf_cu));
2708 
2709         }
2710         else
2711             return type;
2712     }
2713     return NULL;
2714 }
2715 
2716 CompileUnit*
2717 SymbolFileDWARF::GetCompUnitForDWARFCompUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
2718 {
2719     // Check if the symbol vendor already knows about this compile unit?
2720     if (dwarf_cu->GetUserData() == NULL)
2721     {
2722         // The symbol vendor doesn't know about this compile unit, we
2723         // need to parse and add it to the symbol vendor object.
2724         return ParseCompileUnit(dwarf_cu, cu_idx).get();
2725     }
2726     return (CompileUnit*)dwarf_cu->GetUserData();
2727 }
2728 
2729 bool
2730 SymbolFileDWARF::GetFunction (DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry* func_die, SymbolContext& sc)
2731 {
2732     sc.Clear(false);
2733     // Check if the symbol vendor already knows about this compile unit?
2734     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
2735 
2736     sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(func_die->GetOffset())).get();
2737     if (sc.function == NULL)
2738         sc.function = ParseCompileUnitFunction(sc, dwarf_cu, func_die);
2739 
2740     if (sc.function)
2741     {
2742         sc.module_sp = sc.function->CalculateSymbolContextModule();
2743         return true;
2744     }
2745 
2746     return false;
2747 }
2748 
2749 uint32_t
2750 SymbolFileDWARF::ResolveSymbolContext (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
2751 {
2752     Timer scoped_timer(__PRETTY_FUNCTION__,
2753                        "SymbolFileDWARF::ResolveSymbolContext (so_addr = { section = %p, offset = 0x%" PRIx64 " }, resolve_scope = 0x%8.8x)",
2754                        static_cast<void*>(so_addr.GetSection().get()),
2755                        so_addr.GetOffset(), resolve_scope);
2756     uint32_t resolved = 0;
2757     if (resolve_scope & (   eSymbolContextCompUnit |
2758                             eSymbolContextFunction |
2759                             eSymbolContextBlock |
2760                             eSymbolContextLineEntry))
2761     {
2762         lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
2763 
2764         DWARFDebugInfo* debug_info = DebugInfo();
2765         if (debug_info)
2766         {
2767             const dw_offset_t cu_offset = debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr);
2768             if (cu_offset != DW_INVALID_OFFSET)
2769             {
2770                 uint32_t cu_idx = DW_INVALID_INDEX;
2771                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnit(cu_offset, &cu_idx).get();
2772                 if (dwarf_cu)
2773                 {
2774                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2775                     if (sc.comp_unit)
2776                     {
2777                         resolved |= eSymbolContextCompUnit;
2778 
2779                         bool force_check_line_table = false;
2780                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2781                         {
2782                             DWARFDebugInfoEntry *function_die = NULL;
2783                             DWARFDebugInfoEntry *block_die = NULL;
2784                             if (resolve_scope & eSymbolContextBlock)
2785                             {
2786                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, &block_die);
2787                             }
2788                             else
2789                             {
2790                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, NULL);
2791                             }
2792 
2793                             if (function_die != NULL)
2794                             {
2795                                 sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(function_die->GetOffset())).get();
2796                                 if (sc.function == NULL)
2797                                     sc.function = ParseCompileUnitFunction(sc, dwarf_cu, function_die);
2798                             }
2799                             else
2800                             {
2801                                 // We might have had a compile unit that had discontiguous
2802                                 // address ranges where the gaps are symbols that don't have
2803                                 // any debug info. Discontiguous compile unit address ranges
2804                                 // should only happen when there aren't other functions from
2805                                 // other compile units in these gaps. This helps keep the size
2806                                 // of the aranges down.
2807                                 force_check_line_table = true;
2808                             }
2809 
2810                             if (sc.function != NULL)
2811                             {
2812                                 resolved |= eSymbolContextFunction;
2813 
2814                                 if (resolve_scope & eSymbolContextBlock)
2815                                 {
2816                                     Block& block = sc.function->GetBlock (true);
2817 
2818                                     if (block_die != NULL)
2819                                         sc.block = block.FindBlockByID (MakeUserID(block_die->GetOffset()));
2820                                     else
2821                                         sc.block = block.FindBlockByID (MakeUserID(function_die->GetOffset()));
2822                                     if (sc.block)
2823                                         resolved |= eSymbolContextBlock;
2824                                 }
2825                             }
2826                         }
2827 
2828                         if ((resolve_scope & eSymbolContextLineEntry) || force_check_line_table)
2829                         {
2830                             LineTable *line_table = sc.comp_unit->GetLineTable();
2831                             if (line_table != NULL)
2832                             {
2833                                 // And address that makes it into this function should be in terms
2834                                 // of this debug file if there is no debug map, or it will be an
2835                                 // address in the .o file which needs to be fixed up to be in terms
2836                                 // of the debug map executable. Either way, calling FixupAddress()
2837                                 // will work for us.
2838                                 Address exe_so_addr (so_addr);
2839                                 if (FixupAddress(exe_so_addr))
2840                                 {
2841                                     if (line_table->FindLineEntryByAddress (exe_so_addr, sc.line_entry))
2842                                     {
2843                                         resolved |= eSymbolContextLineEntry;
2844                                     }
2845                                 }
2846                             }
2847                         }
2848 
2849                         if (force_check_line_table && !(resolved & eSymbolContextLineEntry))
2850                         {
2851                             // We might have had a compile unit that had discontiguous
2852                             // address ranges where the gaps are symbols that don't have
2853                             // any debug info. Discontiguous compile unit address ranges
2854                             // should only happen when there aren't other functions from
2855                             // other compile units in these gaps. This helps keep the size
2856                             // of the aranges down.
2857                             sc.comp_unit = NULL;
2858                             resolved &= ~eSymbolContextCompUnit;
2859                         }
2860                     }
2861                     else
2862                     {
2863                         GetObjectFile()->GetModule()->ReportWarning ("0x%8.8x: compile unit %u failed to create a valid lldb_private::CompileUnit class.",
2864                                                                      cu_offset,
2865                                                                      cu_idx);
2866                     }
2867                 }
2868             }
2869         }
2870     }
2871     return resolved;
2872 }
2873 
2874 
2875 
2876 uint32_t
2877 SymbolFileDWARF::ResolveSymbolContext(const FileSpec& file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
2878 {
2879     const uint32_t prev_size = sc_list.GetSize();
2880     if (resolve_scope & eSymbolContextCompUnit)
2881     {
2882         DWARFDebugInfo* debug_info = DebugInfo();
2883         if (debug_info)
2884         {
2885             uint32_t cu_idx;
2886             DWARFCompileUnit* dwarf_cu = NULL;
2887 
2888             for (cu_idx = 0; (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL; ++cu_idx)
2889             {
2890                 CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2891                 const bool full_match = (bool)file_spec.GetDirectory();
2892                 bool file_spec_matches_cu_file_spec = dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match);
2893                 if (check_inlines || file_spec_matches_cu_file_spec)
2894                 {
2895                     SymbolContext sc (m_obj_file->GetModule());
2896                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2897                     if (sc.comp_unit)
2898                     {
2899                         uint32_t file_idx = UINT32_MAX;
2900 
2901                         // If we are looking for inline functions only and we don't
2902                         // find it in the support files, we are done.
2903                         if (check_inlines)
2904                         {
2905                             file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2906                             if (file_idx == UINT32_MAX)
2907                                 continue;
2908                         }
2909 
2910                         if (line != 0)
2911                         {
2912                             LineTable *line_table = sc.comp_unit->GetLineTable();
2913 
2914                             if (line_table != NULL && line != 0)
2915                             {
2916                                 // We will have already looked up the file index if
2917                                 // we are searching for inline entries.
2918                                 if (!check_inlines)
2919                                     file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2920 
2921                                 if (file_idx != UINT32_MAX)
2922                                 {
2923                                     uint32_t found_line;
2924                                     uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex (0, file_idx, line, false, &sc.line_entry);
2925                                     found_line = sc.line_entry.line;
2926 
2927                                     while (line_idx != UINT32_MAX)
2928                                     {
2929                                         sc.function = NULL;
2930                                         sc.block = NULL;
2931                                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2932                                         {
2933                                             const lldb::addr_t file_vm_addr = sc.line_entry.range.GetBaseAddress().GetFileAddress();
2934                                             if (file_vm_addr != LLDB_INVALID_ADDRESS)
2935                                             {
2936                                                 DWARFDebugInfoEntry *function_die = NULL;
2937                                                 DWARFDebugInfoEntry *block_die = NULL;
2938                                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, resolve_scope & eSymbolContextBlock ? &block_die : NULL);
2939 
2940                                                 if (function_die != NULL)
2941                                                 {
2942                                                     sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(function_die->GetOffset())).get();
2943                                                     if (sc.function == NULL)
2944                                                         sc.function = ParseCompileUnitFunction(sc, dwarf_cu, function_die);
2945                                                 }
2946 
2947                                                 if (sc.function != NULL)
2948                                                 {
2949                                                     Block& block = sc.function->GetBlock (true);
2950 
2951                                                     if (block_die != NULL)
2952                                                         sc.block = block.FindBlockByID (MakeUserID(block_die->GetOffset()));
2953                                                     else
2954                                                         sc.block = block.FindBlockByID (MakeUserID(function_die->GetOffset()));
2955                                                 }
2956                                             }
2957                                         }
2958 
2959                                         sc_list.Append(sc);
2960                                         line_idx = line_table->FindLineEntryIndexByFileIndex (line_idx + 1, file_idx, found_line, true, &sc.line_entry);
2961                                     }
2962                                 }
2963                             }
2964                             else if (file_spec_matches_cu_file_spec && !check_inlines)
2965                             {
2966                                 // only append the context if we aren't looking for inline call sites
2967                                 // by file and line and if the file spec matches that of the compile unit
2968                                 sc_list.Append(sc);
2969                             }
2970                         }
2971                         else if (file_spec_matches_cu_file_spec && !check_inlines)
2972                         {
2973                             // only append the context if we aren't looking for inline call sites
2974                             // by file and line and if the file spec matches that of the compile unit
2975                             sc_list.Append(sc);
2976                         }
2977 
2978                         if (!check_inlines)
2979                             break;
2980                     }
2981                 }
2982             }
2983         }
2984     }
2985     return sc_list.GetSize() - prev_size;
2986 }
2987 
2988 void
2989 SymbolFileDWARF::Index ()
2990 {
2991     if (m_indexed)
2992         return;
2993     m_indexed = true;
2994     Timer scoped_timer (__PRETTY_FUNCTION__,
2995                         "SymbolFileDWARF::Index (%s)",
2996                         GetObjectFile()->GetFileSpec().GetFilename().AsCString());
2997 
2998     DWARFDebugInfo* debug_info = DebugInfo();
2999     if (debug_info)
3000     {
3001         uint32_t cu_idx = 0;
3002         const uint32_t num_compile_units = GetNumCompileUnits();
3003         for (cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
3004         {
3005             DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
3006 
3007             bool clear_dies = dwarf_cu->ExtractDIEsIfNeeded (false) > 1;
3008 
3009             dwarf_cu->Index (cu_idx,
3010                              m_function_basename_index,
3011                              m_function_fullname_index,
3012                              m_function_method_index,
3013                              m_function_selector_index,
3014                              m_objc_class_selectors_index,
3015                              m_global_index,
3016                              m_type_index,
3017                              m_namespace_index);
3018 
3019             // Keep memory down by clearing DIEs if this generate function
3020             // caused them to be parsed
3021             if (clear_dies)
3022                 dwarf_cu->ClearDIEs (true);
3023         }
3024 
3025         m_function_basename_index.Finalize();
3026         m_function_fullname_index.Finalize();
3027         m_function_method_index.Finalize();
3028         m_function_selector_index.Finalize();
3029         m_objc_class_selectors_index.Finalize();
3030         m_global_index.Finalize();
3031         m_type_index.Finalize();
3032         m_namespace_index.Finalize();
3033 
3034 #if defined (ENABLE_DEBUG_PRINTF)
3035         StreamFile s(stdout, false);
3036         s.Printf ("DWARF index for '%s':",
3037                   GetObjectFile()->GetFileSpec().GetPath().c_str());
3038         s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
3039         s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
3040         s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
3041         s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
3042         s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
3043         s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
3044         s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
3045         s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
3046 #endif
3047     }
3048 }
3049 
3050 bool
3051 SymbolFileDWARF::NamespaceDeclMatchesThisSymbolFile (const ClangNamespaceDecl *namespace_decl)
3052 {
3053     if (namespace_decl == NULL)
3054     {
3055         // Invalid namespace decl which means we aren't matching only things
3056         // in this symbol file, so return true to indicate it matches this
3057         // symbol file.
3058         return true;
3059     }
3060 
3061     clang::ASTContext *namespace_ast = namespace_decl->GetASTContext();
3062 
3063     if (namespace_ast == NULL)
3064         return true;    // No AST in the "namespace_decl", return true since it
3065                         // could then match any symbol file, including this one
3066 
3067     if (namespace_ast == GetClangASTContext().getASTContext())
3068         return true;    // The ASTs match, return true
3069 
3070     // The namespace AST was valid, and it does not match...
3071     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3072 
3073     if (log)
3074         GetObjectFile()->GetModule()->LogMessage(log, "Valid namespace does not match symbol file");
3075 
3076     return false;
3077 }
3078 
3079 bool
3080 SymbolFileDWARF::DIEIsInNamespace (const ClangNamespaceDecl *namespace_decl,
3081                                    DWARFCompileUnit* cu,
3082                                    const DWARFDebugInfoEntry* die)
3083 {
3084     // No namespace specified, so the answesr i
3085     if (namespace_decl == NULL)
3086         return true;
3087 
3088     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3089 
3090     const DWARFDebugInfoEntry *decl_ctx_die = NULL;
3091     clang::DeclContext *die_clang_decl_ctx = GetClangDeclContextContainingDIE (cu, die, &decl_ctx_die);
3092     if (decl_ctx_die)
3093     {
3094         clang::NamespaceDecl *clang_namespace_decl = namespace_decl->GetNamespaceDecl();
3095 
3096         if (clang_namespace_decl)
3097         {
3098             if (decl_ctx_die->Tag() != DW_TAG_namespace)
3099             {
3100                 if (log)
3101                     GetObjectFile()->GetModule()->LogMessage(log, "Found a match, but its parent is not a namespace");
3102                 return false;
3103             }
3104 
3105             if (clang_namespace_decl == die_clang_decl_ctx)
3106                 return true;
3107             else
3108                 return false;
3109         }
3110         else
3111         {
3112             // We have a namespace_decl that was not NULL but it contained
3113             // a NULL "clang::NamespaceDecl", so this means the global namespace
3114             // So as long the the contained decl context DIE isn't a namespace
3115             // we should be ok.
3116             if (decl_ctx_die->Tag() != DW_TAG_namespace)
3117                 return true;
3118         }
3119     }
3120 
3121     if (log)
3122         GetObjectFile()->GetModule()->LogMessage(log, "Found a match, but its parent doesn't exist");
3123 
3124     return false;
3125 }
3126 uint32_t
3127 SymbolFileDWARF::FindGlobalVariables (const ConstString &name, const lldb_private::ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, VariableList& variables)
3128 {
3129     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3130 
3131     if (log)
3132         GetObjectFile()->GetModule()->LogMessage (log,
3133                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", namespace_decl=%p, append=%u, max_matches=%u, variables)",
3134                                                   name.GetCString(),
3135                                                   static_cast<const void*>(namespace_decl),
3136                                                   append, max_matches);
3137 
3138     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3139         return 0;
3140 
3141     DWARFDebugInfo* info = DebugInfo();
3142     if (info == NULL)
3143         return 0;
3144 
3145     // If we aren't appending the results to this list, then clear the list
3146     if (!append)
3147         variables.Clear();
3148 
3149     // Remember how many variables are in the list before we search in case
3150     // we are appending the results to a variable list.
3151     const uint32_t original_size = variables.GetSize();
3152 
3153     DIEArray die_offsets;
3154 
3155     if (m_using_apple_tables)
3156     {
3157         if (m_apple_names_ap.get())
3158         {
3159             const char *name_cstr = name.GetCString();
3160             const char *base_name_start;
3161             const char *base_name_end = NULL;
3162 
3163             if (!CPPLanguageRuntime::StripNamespacesFromVariableName(name_cstr, base_name_start, base_name_end))
3164                 base_name_start = name_cstr;
3165 
3166             m_apple_names_ap->FindByName (base_name_start, die_offsets);
3167         }
3168     }
3169     else
3170     {
3171         // Index the DWARF if we haven't already
3172         if (!m_indexed)
3173             Index ();
3174 
3175         m_global_index.Find (name, die_offsets);
3176     }
3177 
3178     const size_t num_die_matches = die_offsets.size();
3179     if (num_die_matches)
3180     {
3181         SymbolContext sc;
3182         sc.module_sp = m_obj_file->GetModule();
3183         assert (sc.module_sp);
3184 
3185         DWARFDebugInfo* debug_info = DebugInfo();
3186         DWARFCompileUnit* dwarf_cu = NULL;
3187         const DWARFDebugInfoEntry* die = NULL;
3188         bool done = false;
3189         for (size_t i=0; i<num_die_matches && !done; ++i)
3190         {
3191             const dw_offset_t die_offset = die_offsets[i];
3192             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3193 
3194             if (die)
3195             {
3196                 switch (die->Tag())
3197                 {
3198                     default:
3199                     case DW_TAG_subprogram:
3200                     case DW_TAG_inlined_subroutine:
3201                     case DW_TAG_try_block:
3202                     case DW_TAG_catch_block:
3203                         break;
3204 
3205                     case DW_TAG_variable:
3206                         {
3207                             sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
3208 
3209                             if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3210                                 continue;
3211 
3212                             ParseVariables(sc, dwarf_cu, LLDB_INVALID_ADDRESS, die, false, false, &variables);
3213 
3214                             if (variables.GetSize() - original_size >= max_matches)
3215                                 done = true;
3216                         }
3217                         break;
3218                 }
3219             }
3220             else
3221             {
3222                 if (m_using_apple_tables)
3223                 {
3224                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')\n",
3225                                                                                die_offset, name.GetCString());
3226                 }
3227             }
3228         }
3229     }
3230 
3231     // Return the number of variable that were appended to the list
3232     const uint32_t num_matches = variables.GetSize() - original_size;
3233     if (log && num_matches > 0)
3234     {
3235         GetObjectFile()->GetModule()->LogMessage (log,
3236                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", namespace_decl=%p, append=%u, max_matches=%u, variables) => %u",
3237                                                   name.GetCString(),
3238                                                   static_cast<const void*>(namespace_decl),
3239                                                   append, max_matches,
3240                                                   num_matches);
3241     }
3242     return num_matches;
3243 }
3244 
3245 uint32_t
3246 SymbolFileDWARF::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
3247 {
3248     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3249 
3250     if (log)
3251     {
3252         GetObjectFile()->GetModule()->LogMessage (log,
3253                                                   "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", append=%u, max_matches=%u, variables)",
3254                                                   regex.GetText(), append,
3255                                                   max_matches);
3256     }
3257 
3258     DWARFDebugInfo* info = DebugInfo();
3259     if (info == NULL)
3260         return 0;
3261 
3262     // If we aren't appending the results to this list, then clear the list
3263     if (!append)
3264         variables.Clear();
3265 
3266     // Remember how many variables are in the list before we search in case
3267     // we are appending the results to a variable list.
3268     const uint32_t original_size = variables.GetSize();
3269 
3270     DIEArray die_offsets;
3271 
3272     if (m_using_apple_tables)
3273     {
3274         if (m_apple_names_ap.get())
3275         {
3276             DWARFMappedHash::DIEInfoArray hash_data_array;
3277             if (m_apple_names_ap->AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
3278                 DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
3279         }
3280     }
3281     else
3282     {
3283         // Index the DWARF if we haven't already
3284         if (!m_indexed)
3285             Index ();
3286 
3287         m_global_index.Find (regex, die_offsets);
3288     }
3289 
3290     SymbolContext sc;
3291     sc.module_sp = m_obj_file->GetModule();
3292     assert (sc.module_sp);
3293 
3294     DWARFCompileUnit* dwarf_cu = NULL;
3295     const DWARFDebugInfoEntry* die = NULL;
3296     const size_t num_matches = die_offsets.size();
3297     if (num_matches)
3298     {
3299         DWARFDebugInfo* debug_info = DebugInfo();
3300         for (size_t i=0; i<num_matches; ++i)
3301         {
3302             const dw_offset_t die_offset = die_offsets[i];
3303             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3304 
3305             if (die)
3306             {
3307                 sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
3308 
3309                 ParseVariables(sc, dwarf_cu, LLDB_INVALID_ADDRESS, die, false, false, &variables);
3310 
3311                 if (variables.GetSize() - original_size >= max_matches)
3312                     break;
3313             }
3314             else
3315             {
3316                 if (m_using_apple_tables)
3317                 {
3318                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for regex '%s')\n",
3319                                                                                die_offset, regex.GetText());
3320                 }
3321             }
3322         }
3323     }
3324 
3325     // Return the number of variable that were appended to the list
3326     return variables.GetSize() - original_size;
3327 }
3328 
3329 
3330 bool
3331 SymbolFileDWARF::ResolveFunction (dw_offset_t die_offset,
3332                                   DWARFCompileUnit *&dwarf_cu,
3333                                   SymbolContextList& sc_list)
3334 {
3335     const DWARFDebugInfoEntry *die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3336     return ResolveFunction (dwarf_cu, die, sc_list);
3337 }
3338 
3339 
3340 bool
3341 SymbolFileDWARF::ResolveFunction (DWARFCompileUnit *cu,
3342                                   const DWARFDebugInfoEntry *die,
3343                                   SymbolContextList& sc_list)
3344 {
3345     SymbolContext sc;
3346 
3347     if (die == NULL)
3348         return false;
3349 
3350     // If we were passed a die that is not a function, just return false...
3351     if (die->Tag() != DW_TAG_subprogram && die->Tag() != DW_TAG_inlined_subroutine)
3352         return false;
3353 
3354     const DWARFDebugInfoEntry* inlined_die = NULL;
3355     if (die->Tag() == DW_TAG_inlined_subroutine)
3356     {
3357         inlined_die = die;
3358 
3359         while ((die = die->GetParent()) != NULL)
3360         {
3361             if (die->Tag() == DW_TAG_subprogram)
3362                 break;
3363         }
3364     }
3365     assert (die->Tag() == DW_TAG_subprogram);
3366     if (GetFunction (cu, die, sc))
3367     {
3368         Address addr;
3369         // Parse all blocks if needed
3370         if (inlined_die)
3371         {
3372             sc.block = sc.function->GetBlock (true).FindBlockByID (MakeUserID(inlined_die->GetOffset()));
3373             assert (sc.block != NULL);
3374             if (sc.block->GetStartAddress (addr) == false)
3375                 addr.Clear();
3376         }
3377         else
3378         {
3379             sc.block = NULL;
3380             addr = sc.function->GetAddressRange().GetBaseAddress();
3381         }
3382 
3383         if (addr.IsValid())
3384         {
3385             sc_list.Append(sc);
3386             return true;
3387         }
3388     }
3389 
3390     return false;
3391 }
3392 
3393 void
3394 SymbolFileDWARF::FindFunctions (const ConstString &name,
3395                                 const NameToDIE &name_to_die,
3396                                 SymbolContextList& sc_list)
3397 {
3398     DIEArray die_offsets;
3399     if (name_to_die.Find (name, die_offsets))
3400     {
3401         ParseFunctions (die_offsets, sc_list);
3402     }
3403 }
3404 
3405 
3406 void
3407 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
3408                                 const NameToDIE &name_to_die,
3409                                 SymbolContextList& sc_list)
3410 {
3411     DIEArray die_offsets;
3412     if (name_to_die.Find (regex, die_offsets))
3413     {
3414         ParseFunctions (die_offsets, sc_list);
3415     }
3416 }
3417 
3418 
3419 void
3420 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
3421                                 const DWARFMappedHash::MemoryTable &memory_table,
3422                                 SymbolContextList& sc_list)
3423 {
3424     DIEArray die_offsets;
3425     DWARFMappedHash::DIEInfoArray hash_data_array;
3426     if (memory_table.AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
3427     {
3428         DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
3429         ParseFunctions (die_offsets, sc_list);
3430     }
3431 }
3432 
3433 void
3434 SymbolFileDWARF::ParseFunctions (const DIEArray &die_offsets,
3435                                  SymbolContextList& sc_list)
3436 {
3437     const size_t num_matches = die_offsets.size();
3438     if (num_matches)
3439     {
3440         SymbolContext sc;
3441 
3442         DWARFCompileUnit* dwarf_cu = NULL;
3443         for (size_t i=0; i<num_matches; ++i)
3444         {
3445             const dw_offset_t die_offset = die_offsets[i];
3446             ResolveFunction (die_offset, dwarf_cu, sc_list);
3447         }
3448     }
3449 }
3450 
3451 bool
3452 SymbolFileDWARF::FunctionDieMatchesPartialName (const DWARFDebugInfoEntry* die,
3453                                                 const DWARFCompileUnit *dwarf_cu,
3454                                                 uint32_t name_type_mask,
3455                                                 const char *partial_name,
3456                                                 const char *base_name_start,
3457                                                 const char *base_name_end)
3458 {
3459     // If we are looking only for methods, throw away all the ones that are or aren't in C++ classes:
3460     if (name_type_mask == eFunctionNameTypeMethod || name_type_mask == eFunctionNameTypeBase)
3461     {
3462         clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIEOffset(die->GetOffset());
3463         if (!containing_decl_ctx)
3464             return false;
3465 
3466         bool is_cxx_method = DeclKindIsCXXClass(containing_decl_ctx->getDeclKind());
3467 
3468         if (name_type_mask == eFunctionNameTypeMethod)
3469         {
3470             if (is_cxx_method == false)
3471                 return false;
3472         }
3473 
3474         if (name_type_mask == eFunctionNameTypeBase)
3475         {
3476             if (is_cxx_method == true)
3477                 return false;
3478         }
3479     }
3480 
3481     // Now we need to check whether the name we got back for this type matches the extra specifications
3482     // that were in the name we're looking up:
3483     if (base_name_start != partial_name || *base_name_end != '\0')
3484     {
3485         // First see if the stuff to the left matches the full name.  To do that let's see if
3486         // we can pull out the mips linkage name attribute:
3487 
3488         Mangled best_name;
3489         DWARFDebugInfoEntry::Attributes attributes;
3490         DWARFFormValue form_value;
3491         die->GetAttributes(this, dwarf_cu, NULL, attributes);
3492         uint32_t idx = attributes.FindAttributeIndex(DW_AT_MIPS_linkage_name);
3493         if (idx == UINT32_MAX)
3494             idx = attributes.FindAttributeIndex(DW_AT_linkage_name);
3495         if (idx != UINT32_MAX)
3496         {
3497             if (attributes.ExtractFormValueAtIndex(this, idx, form_value))
3498             {
3499                 const char *mangled_name = form_value.AsCString(&get_debug_str_data());
3500                 if (mangled_name)
3501                     best_name.SetValue (ConstString(mangled_name), true);
3502             }
3503         }
3504 
3505         if (!best_name)
3506         {
3507             idx = attributes.FindAttributeIndex(DW_AT_name);
3508             if (idx != UINT32_MAX && attributes.ExtractFormValueAtIndex(this, idx, form_value))
3509             {
3510                 const char *name = form_value.AsCString(&get_debug_str_data());
3511                 best_name.SetValue (ConstString(name), false);
3512             }
3513         }
3514 
3515         if (best_name.GetDemangledName())
3516         {
3517             const char *demangled = best_name.GetDemangledName().GetCString();
3518             if (demangled)
3519             {
3520                 std::string name_no_parens(partial_name, base_name_end - partial_name);
3521                 const char *partial_in_demangled = strstr (demangled, name_no_parens.c_str());
3522                 if (partial_in_demangled == NULL)
3523                     return false;
3524                 else
3525                 {
3526                     // Sort out the case where our name is something like "Process::Destroy" and the match is
3527                     // "SBProcess::Destroy" - that shouldn't be a match.  We should really always match on
3528                     // namespace boundaries...
3529 
3530                     if (partial_name[0] == ':'  && partial_name[1] == ':')
3531                     {
3532                         // The partial name was already on a namespace boundary so all matches are good.
3533                         return true;
3534                     }
3535                     else if (partial_in_demangled == demangled)
3536                     {
3537                         // They both start the same, so this is an good match.
3538                         return true;
3539                     }
3540                     else
3541                     {
3542                         if (partial_in_demangled - demangled == 1)
3543                         {
3544                             // Only one character difference, can't be a namespace boundary...
3545                             return false;
3546                         }
3547                         else if (*(partial_in_demangled - 1) == ':' && *(partial_in_demangled - 2) == ':')
3548                         {
3549                             // We are on a namespace boundary, so this is also good.
3550                             return true;
3551                         }
3552                         else
3553                             return false;
3554                     }
3555                 }
3556             }
3557         }
3558     }
3559 
3560     return true;
3561 }
3562 
3563 uint32_t
3564 SymbolFileDWARF::FindFunctions (const ConstString &name,
3565                                 const lldb_private::ClangNamespaceDecl *namespace_decl,
3566                                 uint32_t name_type_mask,
3567                                 bool include_inlines,
3568                                 bool append,
3569                                 SymbolContextList& sc_list)
3570 {
3571     Timer scoped_timer (__PRETTY_FUNCTION__,
3572                         "SymbolFileDWARF::FindFunctions (name = '%s')",
3573                         name.AsCString());
3574 
3575     // eFunctionNameTypeAuto should be pre-resolved by a call to Module::PrepareForFunctionNameLookup()
3576     assert ((name_type_mask & eFunctionNameTypeAuto) == 0);
3577 
3578     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3579 
3580     if (log)
3581     {
3582         GetObjectFile()->GetModule()->LogMessage (log,
3583                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list)",
3584                                                   name.GetCString(),
3585                                                   name_type_mask,
3586                                                   append);
3587     }
3588 
3589     // If we aren't appending the results to this list, then clear the list
3590     if (!append)
3591         sc_list.Clear();
3592 
3593     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3594         return 0;
3595 
3596     // If name is empty then we won't find anything.
3597     if (name.IsEmpty())
3598         return 0;
3599 
3600     // Remember how many sc_list are in the list before we search in case
3601     // we are appending the results to a variable list.
3602 
3603     const char *name_cstr = name.GetCString();
3604 
3605     const uint32_t original_size = sc_list.GetSize();
3606 
3607     DWARFDebugInfo* info = DebugInfo();
3608     if (info == NULL)
3609         return 0;
3610 
3611     DWARFCompileUnit *dwarf_cu = NULL;
3612     std::set<const DWARFDebugInfoEntry *> resolved_dies;
3613     if (m_using_apple_tables)
3614     {
3615         if (m_apple_names_ap.get())
3616         {
3617 
3618             DIEArray die_offsets;
3619 
3620             uint32_t num_matches = 0;
3621 
3622             if (name_type_mask & eFunctionNameTypeFull)
3623             {
3624                 // If they asked for the full name, match what they typed.  At some point we may
3625                 // want to canonicalize this (strip double spaces, etc.  For now, we just add all the
3626                 // dies that we find by exact match.
3627                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3628                 for (uint32_t i = 0; i < num_matches; i++)
3629                 {
3630                     const dw_offset_t die_offset = die_offsets[i];
3631                     const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3632                     if (die)
3633                     {
3634                         if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3635                             continue;
3636 
3637                         if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3638                             continue;
3639 
3640                         if (resolved_dies.find(die) == resolved_dies.end())
3641                         {
3642                             if (ResolveFunction (dwarf_cu, die, sc_list))
3643                                 resolved_dies.insert(die);
3644                         }
3645                     }
3646                     else
3647                     {
3648                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3649                                                                                    die_offset, name_cstr);
3650                     }
3651                 }
3652             }
3653 
3654             if (name_type_mask & eFunctionNameTypeSelector)
3655             {
3656                 if (namespace_decl && *namespace_decl)
3657                     return 0; // no selectors in namespaces
3658 
3659                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3660                 // Now make sure these are actually ObjC methods.  In this case we can simply look up the name,
3661                 // and if it is an ObjC method name, we're good.
3662 
3663                 for (uint32_t i = 0; i < num_matches; i++)
3664                 {
3665                     const dw_offset_t die_offset = die_offsets[i];
3666                     const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3667                     if (die)
3668                     {
3669                         const char *die_name = die->GetName(this, dwarf_cu);
3670                         if (ObjCLanguageRuntime::IsPossibleObjCMethodName(die_name))
3671                         {
3672                             if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3673                                 continue;
3674 
3675                             if (resolved_dies.find(die) == resolved_dies.end())
3676                             {
3677                                 if (ResolveFunction (dwarf_cu, die, sc_list))
3678                                     resolved_dies.insert(die);
3679                             }
3680                         }
3681                     }
3682                     else
3683                     {
3684                         GetObjectFile()->GetModule()->ReportError ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3685                                                                    die_offset, name_cstr);
3686                     }
3687                 }
3688                 die_offsets.clear();
3689             }
3690 
3691             if (((name_type_mask & eFunctionNameTypeMethod) && !namespace_decl) || name_type_mask & eFunctionNameTypeBase)
3692             {
3693                 // The apple_names table stores just the "base name" of C++ methods in the table.  So we have to
3694                 // extract the base name, look that up, and if there is any other information in the name we were
3695                 // passed in we have to post-filter based on that.
3696 
3697                 // FIXME: Arrange the logic above so that we don't calculate the base name twice:
3698                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3699 
3700                 for (uint32_t i = 0; i < num_matches; i++)
3701                 {
3702                     const dw_offset_t die_offset = die_offsets[i];
3703                     const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3704                     if (die)
3705                     {
3706                         if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3707                             continue;
3708 
3709                         if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3710                             continue;
3711 
3712                         // If we get to here, the die is good, and we should add it:
3713                         if (resolved_dies.find(die) == resolved_dies.end())
3714                         if (ResolveFunction (dwarf_cu, die, sc_list))
3715                         {
3716                             bool keep_die = true;
3717                             if ((name_type_mask & (eFunctionNameTypeBase|eFunctionNameTypeMethod)) != (eFunctionNameTypeBase|eFunctionNameTypeMethod))
3718                             {
3719                                 // We are looking for either basenames or methods, so we need to
3720                                 // trim out the ones we won't want by looking at the type
3721                                 SymbolContext sc;
3722                                 if (sc_list.GetLastContext(sc))
3723                                 {
3724                                     if (sc.block)
3725                                     {
3726                                         // We have an inlined function
3727                                     }
3728                                     else if (sc.function)
3729                                     {
3730                                         Type *type = sc.function->GetType();
3731 
3732                                         if (type)
3733                                         {
3734                                             clang::DeclContext* decl_ctx = GetClangDeclContextContainingTypeUID (type->GetID());
3735                                             if (decl_ctx->isRecord())
3736                                             {
3737                                                 if (name_type_mask & eFunctionNameTypeBase)
3738                                                 {
3739                                                     sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
3740                                                     keep_die = false;
3741                                                 }
3742                                             }
3743                                             else
3744                                             {
3745                                                 if (name_type_mask & eFunctionNameTypeMethod)
3746                                                 {
3747                                                     sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
3748                                                     keep_die = false;
3749                                                 }
3750                                             }
3751                                         }
3752                                         else
3753                                         {
3754                                             GetObjectFile()->GetModule()->ReportWarning ("function at die offset 0x%8.8x had no function type",
3755                                                                                          die_offset);
3756                                         }
3757                                     }
3758                                 }
3759                             }
3760                             if (keep_die)
3761                                 resolved_dies.insert(die);
3762                         }
3763                     }
3764                     else
3765                     {
3766                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3767                                                                                    die_offset, name_cstr);
3768                     }
3769                 }
3770                 die_offsets.clear();
3771             }
3772         }
3773     }
3774     else
3775     {
3776 
3777         // Index the DWARF if we haven't already
3778         if (!m_indexed)
3779             Index ();
3780 
3781         if (name_type_mask & eFunctionNameTypeFull)
3782         {
3783             FindFunctions (name, m_function_fullname_index, sc_list);
3784 
3785             // FIXME Temporary workaround for global/anonymous namespace
3786             // functions on FreeBSD and Linux
3787 #if defined (__FreeBSD__) || defined (__linux__)
3788             // If we didn't find any functions in the global namespace try
3789             // looking in the basename index but ignore any returned
3790             // functions that have a namespace (ie. mangled names starting with
3791             // '_ZN') but keep functions which have an anonymous namespace
3792             if (sc_list.GetSize() == 0)
3793             {
3794                 SymbolContextList temp_sc_list;
3795                 FindFunctions (name, m_function_basename_index, temp_sc_list);
3796                 if (!namespace_decl)
3797                 {
3798                     SymbolContext sc;
3799                     for (uint32_t i = 0; i < temp_sc_list.GetSize(); i++)
3800                     {
3801                         if (temp_sc_list.GetContextAtIndex(i, sc))
3802                         {
3803                             ConstString mangled_name = sc.GetFunctionName(Mangled::ePreferMangled);
3804                             ConstString demangled_name = sc.GetFunctionName(Mangled::ePreferDemangled);
3805                             if (strncmp(mangled_name.GetCString(), "_ZN", 3) ||
3806                                 !strncmp(demangled_name.GetCString(), "(anonymous namespace)", 21))
3807                             {
3808                                 sc_list.Append(sc);
3809                             }
3810                         }
3811                     }
3812                 }
3813             }
3814 #endif
3815         }
3816         DIEArray die_offsets;
3817         DWARFCompileUnit *dwarf_cu = NULL;
3818 
3819         if (name_type_mask & eFunctionNameTypeBase)
3820         {
3821             uint32_t num_base = m_function_basename_index.Find(name, die_offsets);
3822             for (uint32_t i = 0; i < num_base; i++)
3823             {
3824                 const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3825                 if (die)
3826                 {
3827                     if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3828                         continue;
3829 
3830                     if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3831                         continue;
3832 
3833                     // If we get to here, the die is good, and we should add it:
3834                     if (resolved_dies.find(die) == resolved_dies.end())
3835                     {
3836                         if (ResolveFunction (dwarf_cu, die, sc_list))
3837                             resolved_dies.insert(die);
3838                     }
3839                 }
3840             }
3841             die_offsets.clear();
3842         }
3843 
3844         if (name_type_mask & eFunctionNameTypeMethod)
3845         {
3846             if (namespace_decl && *namespace_decl)
3847                 return 0; // no methods in namespaces
3848 
3849             uint32_t num_base = m_function_method_index.Find(name, die_offsets);
3850             {
3851                 for (uint32_t i = 0; i < num_base; i++)
3852                 {
3853                     const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3854                     if (die)
3855                     {
3856                         if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3857                             continue;
3858 
3859                         // If we get to here, the die is good, and we should add it:
3860                         if (resolved_dies.find(die) == resolved_dies.end())
3861                         {
3862                             if (ResolveFunction (dwarf_cu, die, sc_list))
3863                                 resolved_dies.insert(die);
3864                         }
3865                     }
3866                 }
3867             }
3868             die_offsets.clear();
3869         }
3870 
3871         if ((name_type_mask & eFunctionNameTypeSelector) && (!namespace_decl || !*namespace_decl))
3872         {
3873             FindFunctions (name, m_function_selector_index, sc_list);
3874         }
3875 
3876     }
3877 
3878     // Return the number of variable that were appended to the list
3879     const uint32_t num_matches = sc_list.GetSize() - original_size;
3880 
3881     if (log && num_matches > 0)
3882     {
3883         GetObjectFile()->GetModule()->LogMessage (log,
3884                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list) => %u",
3885                                                   name.GetCString(),
3886                                                   name_type_mask,
3887                                                   append,
3888                                                   num_matches);
3889     }
3890     return num_matches;
3891 }
3892 
3893 uint32_t
3894 SymbolFileDWARF::FindFunctions(const RegularExpression& regex, bool include_inlines, bool append, SymbolContextList& sc_list)
3895 {
3896     Timer scoped_timer (__PRETTY_FUNCTION__,
3897                         "SymbolFileDWARF::FindFunctions (regex = '%s')",
3898                         regex.GetText());
3899 
3900     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3901 
3902     if (log)
3903     {
3904         GetObjectFile()->GetModule()->LogMessage (log,
3905                                                   "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
3906                                                   regex.GetText(),
3907                                                   append);
3908     }
3909 
3910 
3911     // If we aren't appending the results to this list, then clear the list
3912     if (!append)
3913         sc_list.Clear();
3914 
3915     // Remember how many sc_list are in the list before we search in case
3916     // we are appending the results to a variable list.
3917     uint32_t original_size = sc_list.GetSize();
3918 
3919     if (m_using_apple_tables)
3920     {
3921         if (m_apple_names_ap.get())
3922             FindFunctions (regex, *m_apple_names_ap, sc_list);
3923     }
3924     else
3925     {
3926         // Index the DWARF if we haven't already
3927         if (!m_indexed)
3928             Index ();
3929 
3930         FindFunctions (regex, m_function_basename_index, sc_list);
3931 
3932         FindFunctions (regex, m_function_fullname_index, sc_list);
3933     }
3934 
3935     // Return the number of variable that were appended to the list
3936     return sc_list.GetSize() - original_size;
3937 }
3938 
3939 uint32_t
3940 SymbolFileDWARF::FindTypes (const SymbolContext& sc,
3941                             const ConstString &name,
3942                             const lldb_private::ClangNamespaceDecl *namespace_decl,
3943                             bool append,
3944                             uint32_t max_matches,
3945                             TypeList& types)
3946 {
3947     DWARFDebugInfo* info = DebugInfo();
3948     if (info == NULL)
3949         return 0;
3950 
3951     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3952 
3953     if (log)
3954     {
3955         if (namespace_decl)
3956             GetObjectFile()->GetModule()->LogMessage (log,
3957                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list)",
3958                                                       name.GetCString(),
3959                                                       static_cast<void*>(namespace_decl->GetNamespaceDecl()),
3960                                                       namespace_decl->GetQualifiedName().c_str(),
3961                                                       append, max_matches);
3962         else
3963             GetObjectFile()->GetModule()->LogMessage (log,
3964                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list)",
3965                                                       name.GetCString(), append,
3966                                                       max_matches);
3967     }
3968 
3969     // If we aren't appending the results to this list, then clear the list
3970     if (!append)
3971         types.Clear();
3972 
3973     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3974         return 0;
3975 
3976     DIEArray die_offsets;
3977 
3978     if (m_using_apple_tables)
3979     {
3980         if (m_apple_types_ap.get())
3981         {
3982             const char *name_cstr = name.GetCString();
3983             m_apple_types_ap->FindByName (name_cstr, die_offsets);
3984         }
3985     }
3986     else
3987     {
3988         if (!m_indexed)
3989             Index ();
3990 
3991         m_type_index.Find (name, die_offsets);
3992     }
3993 
3994     const size_t num_die_matches = die_offsets.size();
3995 
3996     if (num_die_matches)
3997     {
3998         const uint32_t initial_types_size = types.GetSize();
3999         DWARFCompileUnit* dwarf_cu = NULL;
4000         const DWARFDebugInfoEntry* die = NULL;
4001         DWARFDebugInfo* debug_info = DebugInfo();
4002         for (size_t i=0; i<num_die_matches; ++i)
4003         {
4004             const dw_offset_t die_offset = die_offsets[i];
4005             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
4006 
4007             if (die)
4008             {
4009                 if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
4010                     continue;
4011 
4012                 Type *matching_type = ResolveType (dwarf_cu, die);
4013                 if (matching_type)
4014                 {
4015                     // We found a type pointer, now find the shared pointer form our type list
4016                     types.InsertUnique (matching_type->shared_from_this());
4017                     if (types.GetSize() >= max_matches)
4018                         break;
4019                 }
4020             }
4021             else
4022             {
4023                 if (m_using_apple_tables)
4024                 {
4025                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4026                                                                                die_offset, name.GetCString());
4027                 }
4028             }
4029 
4030         }
4031         const uint32_t num_matches = types.GetSize() - initial_types_size;
4032         if (log && num_matches)
4033         {
4034             if (namespace_decl)
4035             {
4036                 GetObjectFile()->GetModule()->LogMessage (log,
4037                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list) => %u",
4038                                                           name.GetCString(),
4039                                                           static_cast<void*>(namespace_decl->GetNamespaceDecl()),
4040                                                           namespace_decl->GetQualifiedName().c_str(),
4041                                                           append, max_matches,
4042                                                           num_matches);
4043             }
4044             else
4045             {
4046                 GetObjectFile()->GetModule()->LogMessage (log,
4047                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list) => %u",
4048                                                           name.GetCString(),
4049                                                           append, max_matches,
4050                                                           num_matches);
4051             }
4052         }
4053         return num_matches;
4054     }
4055     return 0;
4056 }
4057 
4058 
4059 ClangNamespaceDecl
4060 SymbolFileDWARF::FindNamespace (const SymbolContext& sc,
4061                                 const ConstString &name,
4062                                 const lldb_private::ClangNamespaceDecl *parent_namespace_decl)
4063 {
4064     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
4065 
4066     if (log)
4067     {
4068         GetObjectFile()->GetModule()->LogMessage (log,
4069                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
4070                                                   name.GetCString());
4071     }
4072 
4073     if (!NamespaceDeclMatchesThisSymbolFile(parent_namespace_decl))
4074         return ClangNamespaceDecl();
4075 
4076     ClangNamespaceDecl namespace_decl;
4077     DWARFDebugInfo* info = DebugInfo();
4078     if (info)
4079     {
4080         DIEArray die_offsets;
4081 
4082         // Index if we already haven't to make sure the compile units
4083         // get indexed and make their global DIE index list
4084         if (m_using_apple_tables)
4085         {
4086             if (m_apple_namespaces_ap.get())
4087             {
4088                 const char *name_cstr = name.GetCString();
4089                 m_apple_namespaces_ap->FindByName (name_cstr, die_offsets);
4090             }
4091         }
4092         else
4093         {
4094             if (!m_indexed)
4095                 Index ();
4096 
4097             m_namespace_index.Find (name, die_offsets);
4098         }
4099 
4100         DWARFCompileUnit* dwarf_cu = NULL;
4101         const DWARFDebugInfoEntry* die = NULL;
4102         const size_t num_matches = die_offsets.size();
4103         if (num_matches)
4104         {
4105             DWARFDebugInfo* debug_info = DebugInfo();
4106             for (size_t i=0; i<num_matches; ++i)
4107             {
4108                 const dw_offset_t die_offset = die_offsets[i];
4109                 die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
4110 
4111                 if (die)
4112                 {
4113                     if (parent_namespace_decl && !DIEIsInNamespace (parent_namespace_decl, dwarf_cu, die))
4114                         continue;
4115 
4116                     clang::NamespaceDecl *clang_namespace_decl = ResolveNamespaceDIE (dwarf_cu, die);
4117                     if (clang_namespace_decl)
4118                     {
4119                         namespace_decl.SetASTContext (GetClangASTContext().getASTContext());
4120                         namespace_decl.SetNamespaceDecl (clang_namespace_decl);
4121                         break;
4122                     }
4123                 }
4124                 else
4125                 {
4126                     if (m_using_apple_tables)
4127                     {
4128                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_namespaces accelerator table had bad die 0x%8.8x for '%s')\n",
4129                                                                    die_offset, name.GetCString());
4130                     }
4131                 }
4132 
4133             }
4134         }
4135     }
4136     if (log && namespace_decl.GetNamespaceDecl())
4137     {
4138         GetObjectFile()->GetModule()->LogMessage (log,
4139                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => clang::NamespaceDecl(%p) \"%s\"",
4140                                                   name.GetCString(),
4141                                                   static_cast<const void*>(namespace_decl.GetNamespaceDecl()),
4142                                                   namespace_decl.GetQualifiedName().c_str());
4143     }
4144 
4145     return namespace_decl;
4146 }
4147 
4148 uint32_t
4149 SymbolFileDWARF::FindTypes(std::vector<dw_offset_t> die_offsets, uint32_t max_matches, TypeList& types)
4150 {
4151     // Remember how many sc_list are in the list before we search in case
4152     // we are appending the results to a variable list.
4153     uint32_t original_size = types.GetSize();
4154 
4155     const uint32_t num_die_offsets = die_offsets.size();
4156     // Parse all of the types we found from the pubtypes matches
4157     uint32_t i;
4158     uint32_t num_matches = 0;
4159     for (i = 0; i < num_die_offsets; ++i)
4160     {
4161         Type *matching_type = ResolveTypeUID (die_offsets[i]);
4162         if (matching_type)
4163         {
4164             // We found a type pointer, now find the shared pointer form our type list
4165             types.InsertUnique (matching_type->shared_from_this());
4166             ++num_matches;
4167             if (num_matches >= max_matches)
4168                 break;
4169         }
4170     }
4171 
4172     // Return the number of variable that were appended to the list
4173     return types.GetSize() - original_size;
4174 }
4175 
4176 
4177 size_t
4178 SymbolFileDWARF::ParseChildParameters (const SymbolContext& sc,
4179                                        clang::DeclContext *containing_decl_ctx,
4180                                        DWARFCompileUnit* dwarf_cu,
4181                                        const DWARFDebugInfoEntry *parent_die,
4182                                        bool skip_artificial,
4183                                        bool &is_static,
4184                                        bool &is_variadic,
4185                                        TypeList* type_list,
4186                                        std::vector<ClangASTType>& function_param_types,
4187                                        std::vector<clang::ParmVarDecl*>& function_param_decls,
4188                                        unsigned &type_quals) // ,
4189                                        // ClangASTContext::TemplateParameterInfos &template_param_infos))
4190 {
4191     if (parent_die == NULL)
4192         return 0;
4193 
4194     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4195 
4196     size_t arg_idx = 0;
4197     const DWARFDebugInfoEntry *die;
4198     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4199     {
4200         dw_tag_t tag = die->Tag();
4201         switch (tag)
4202         {
4203         case DW_TAG_formal_parameter:
4204             {
4205                 DWARFDebugInfoEntry::Attributes attributes;
4206                 const size_t num_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4207                 if (num_attributes > 0)
4208                 {
4209                     const char *name = NULL;
4210                     Declaration decl;
4211                     dw_offset_t param_type_die_offset = DW_INVALID_OFFSET;
4212                     bool is_artificial = false;
4213                     // one of None, Auto, Register, Extern, Static, PrivateExtern
4214 
4215                     clang::StorageClass storage = clang::SC_None;
4216                     uint32_t i;
4217                     for (i=0; i<num_attributes; ++i)
4218                     {
4219                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
4220                         DWARFFormValue form_value;
4221                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4222                         {
4223                             switch (attr)
4224                             {
4225                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4226                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4227                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4228                             case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
4229                             case DW_AT_type:        param_type_die_offset = form_value.Reference(dwarf_cu); break;
4230                             case DW_AT_artificial:  is_artificial = form_value.Boolean(); break;
4231                             case DW_AT_location:
4232     //                          if (form_value.BlockData())
4233     //                          {
4234     //                              const DWARFDataExtractor& debug_info_data = debug_info();
4235     //                              uint32_t block_length = form_value.Unsigned();
4236     //                              DWARFDataExtractor location(debug_info_data, form_value.BlockData() - debug_info_data.GetDataStart(), block_length);
4237     //                          }
4238     //                          else
4239     //                          {
4240     //                          }
4241     //                          break;
4242                             case DW_AT_const_value:
4243                             case DW_AT_default_value:
4244                             case DW_AT_description:
4245                             case DW_AT_endianity:
4246                             case DW_AT_is_optional:
4247                             case DW_AT_segment:
4248                             case DW_AT_variable_parameter:
4249                             default:
4250                             case DW_AT_abstract_origin:
4251                             case DW_AT_sibling:
4252                                 break;
4253                             }
4254                         }
4255                     }
4256 
4257                     bool skip = false;
4258                     if (skip_artificial)
4259                     {
4260                         if (is_artificial)
4261                         {
4262                             // In order to determine if a C++ member function is
4263                             // "const" we have to look at the const-ness of "this"...
4264                             // Ugly, but that
4265                             if (arg_idx == 0)
4266                             {
4267                                 if (DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()))
4268                                 {
4269                                     // Often times compilers omit the "this" name for the
4270                                     // specification DIEs, so we can't rely upon the name
4271                                     // being in the formal parameter DIE...
4272                                     if (name == NULL || ::strcmp(name, "this")==0)
4273                                     {
4274                                         Type *this_type = ResolveTypeUID (param_type_die_offset);
4275                                         if (this_type)
4276                                         {
4277                                             uint32_t encoding_mask = this_type->GetEncodingMask();
4278                                             if (encoding_mask & Type::eEncodingIsPointerUID)
4279                                             {
4280                                                 is_static = false;
4281 
4282                                                 if (encoding_mask & (1u << Type::eEncodingIsConstUID))
4283                                                     type_quals |= clang::Qualifiers::Const;
4284                                                 if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
4285                                                     type_quals |= clang::Qualifiers::Volatile;
4286                                             }
4287                                         }
4288                                     }
4289                                 }
4290                             }
4291                             skip = true;
4292                         }
4293                         else
4294                         {
4295 
4296                             // HACK: Objective C formal parameters "self" and "_cmd"
4297                             // are not marked as artificial in the DWARF...
4298                             CompileUnit *comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
4299                             if (comp_unit)
4300                             {
4301                                 switch (comp_unit->GetLanguage())
4302                                 {
4303                                     case eLanguageTypeObjC:
4304                                     case eLanguageTypeObjC_plus_plus:
4305                                         if (name && name[0] && (strcmp (name, "self") == 0 || strcmp (name, "_cmd") == 0))
4306                                             skip = true;
4307                                         break;
4308                                     default:
4309                                         break;
4310                                 }
4311                             }
4312                         }
4313                     }
4314 
4315                     if (!skip)
4316                     {
4317                         Type *type = ResolveTypeUID(param_type_die_offset);
4318                         if (type)
4319                         {
4320                             function_param_types.push_back (type->GetClangForwardType());
4321 
4322                             clang::ParmVarDecl *param_var_decl = GetClangASTContext().CreateParameterDeclaration (name,
4323                                                                                                                   type->GetClangForwardType(),
4324                                                                                                                   storage);
4325                             assert(param_var_decl);
4326                             function_param_decls.push_back(param_var_decl);
4327 
4328                             GetClangASTContext().SetMetadataAsUserID (param_var_decl, MakeUserID(die->GetOffset()));
4329                         }
4330                     }
4331                 }
4332                 arg_idx++;
4333             }
4334             break;
4335 
4336         case DW_TAG_unspecified_parameters:
4337             is_variadic = true;
4338             break;
4339 
4340         case DW_TAG_template_type_parameter:
4341         case DW_TAG_template_value_parameter:
4342             // The one caller of this was never using the template_param_infos,
4343             // and the local variable was taking up a large amount of stack space
4344             // in SymbolFileDWARF::ParseType() so this was removed. If we ever need
4345             // the template params back, we can add them back.
4346             // ParseTemplateDIE (dwarf_cu, die, template_param_infos);
4347             break;
4348 
4349         default:
4350             break;
4351         }
4352     }
4353     return arg_idx;
4354 }
4355 
4356 size_t
4357 SymbolFileDWARF::ParseChildEnumerators
4358 (
4359     const SymbolContext& sc,
4360     lldb_private::ClangASTType &clang_type,
4361     bool is_signed,
4362     uint32_t enumerator_byte_size,
4363     DWARFCompileUnit* dwarf_cu,
4364     const DWARFDebugInfoEntry *parent_die
4365 )
4366 {
4367     if (parent_die == NULL)
4368         return 0;
4369 
4370     size_t enumerators_added = 0;
4371     const DWARFDebugInfoEntry *die;
4372     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4373 
4374     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4375     {
4376         const dw_tag_t tag = die->Tag();
4377         if (tag == DW_TAG_enumerator)
4378         {
4379             DWARFDebugInfoEntry::Attributes attributes;
4380             const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4381             if (num_child_attributes > 0)
4382             {
4383                 const char *name = NULL;
4384                 bool got_value = false;
4385                 int64_t enum_value = 0;
4386                 Declaration decl;
4387 
4388                 uint32_t i;
4389                 for (i=0; i<num_child_attributes; ++i)
4390                 {
4391                     const dw_attr_t attr = attributes.AttributeAtIndex(i);
4392                     DWARFFormValue form_value;
4393                     if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4394                     {
4395                         switch (attr)
4396                         {
4397                         case DW_AT_const_value:
4398                             got_value = true;
4399                             if (is_signed)
4400                                 enum_value = form_value.Signed();
4401                             else
4402                                 enum_value = form_value.Unsigned();
4403                             break;
4404 
4405                         case DW_AT_name:
4406                             name = form_value.AsCString(&get_debug_str_data());
4407                             break;
4408 
4409                         case DW_AT_description:
4410                         default:
4411                         case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4412                         case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4413                         case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4414                         case DW_AT_sibling:
4415                             break;
4416                         }
4417                     }
4418                 }
4419 
4420                 if (name && name[0] && got_value)
4421                 {
4422                     clang_type.AddEnumerationValueToEnumerationType (clang_type.GetEnumerationIntegerType(),
4423                                                                      decl,
4424                                                                      name,
4425                                                                      enum_value,
4426                                                                      enumerator_byte_size * 8);
4427                     ++enumerators_added;
4428                 }
4429             }
4430         }
4431     }
4432     return enumerators_added;
4433 }
4434 
4435 void
4436 SymbolFileDWARF::ParseChildArrayInfo
4437 (
4438     const SymbolContext& sc,
4439     DWARFCompileUnit* dwarf_cu,
4440     const DWARFDebugInfoEntry *parent_die,
4441     int64_t& first_index,
4442     std::vector<uint64_t>& element_orders,
4443     uint32_t& byte_stride,
4444     uint32_t& bit_stride
4445 )
4446 {
4447     if (parent_die == NULL)
4448         return;
4449 
4450     const DWARFDebugInfoEntry *die;
4451     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4452     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4453     {
4454         const dw_tag_t tag = die->Tag();
4455         switch (tag)
4456         {
4457         case DW_TAG_subrange_type:
4458             {
4459                 DWARFDebugInfoEntry::Attributes attributes;
4460                 const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4461                 if (num_child_attributes > 0)
4462                 {
4463                     uint64_t num_elements = 0;
4464                     uint64_t lower_bound = 0;
4465                     uint64_t upper_bound = 0;
4466                     bool upper_bound_valid = false;
4467                     uint32_t i;
4468                     for (i=0; i<num_child_attributes; ++i)
4469                     {
4470                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
4471                         DWARFFormValue form_value;
4472                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4473                         {
4474                             switch (attr)
4475                             {
4476                             case DW_AT_name:
4477                                 break;
4478 
4479                             case DW_AT_count:
4480                                 num_elements = form_value.Unsigned();
4481                                 break;
4482 
4483                             case DW_AT_bit_stride:
4484                                 bit_stride = form_value.Unsigned();
4485                                 break;
4486 
4487                             case DW_AT_byte_stride:
4488                                 byte_stride = form_value.Unsigned();
4489                                 break;
4490 
4491                             case DW_AT_lower_bound:
4492                                 lower_bound = form_value.Unsigned();
4493                                 break;
4494 
4495                             case DW_AT_upper_bound:
4496                                 upper_bound_valid = true;
4497                                 upper_bound = form_value.Unsigned();
4498                                 break;
4499 
4500                             default:
4501                             case DW_AT_abstract_origin:
4502                             case DW_AT_accessibility:
4503                             case DW_AT_allocated:
4504                             case DW_AT_associated:
4505                             case DW_AT_data_location:
4506                             case DW_AT_declaration:
4507                             case DW_AT_description:
4508                             case DW_AT_sibling:
4509                             case DW_AT_threads_scaled:
4510                             case DW_AT_type:
4511                             case DW_AT_visibility:
4512                                 break;
4513                             }
4514                         }
4515                     }
4516 
4517                     if (num_elements == 0)
4518                     {
4519                         if (upper_bound_valid && upper_bound >= lower_bound)
4520                             num_elements = upper_bound - lower_bound + 1;
4521                     }
4522 
4523                     element_orders.push_back (num_elements);
4524                 }
4525             }
4526             break;
4527         }
4528     }
4529 }
4530 
4531 TypeSP
4532 SymbolFileDWARF::GetTypeForDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry* die)
4533 {
4534     TypeSP type_sp;
4535     if (die != NULL)
4536     {
4537         assert(dwarf_cu != NULL);
4538         Type *type_ptr = m_die_to_type.lookup (die);
4539         if (type_ptr == NULL)
4540         {
4541             CompileUnit* lldb_cu = GetCompUnitForDWARFCompUnit(dwarf_cu);
4542             assert (lldb_cu);
4543             SymbolContext sc(lldb_cu);
4544             type_sp = ParseType(sc, dwarf_cu, die, NULL);
4545         }
4546         else if (type_ptr != DIE_IS_BEING_PARSED)
4547         {
4548             // Grab the existing type from the master types lists
4549             type_sp = type_ptr->shared_from_this();
4550         }
4551 
4552     }
4553     return type_sp;
4554 }
4555 
4556 clang::DeclContext *
4557 SymbolFileDWARF::GetClangDeclContextContainingDIEOffset (dw_offset_t die_offset)
4558 {
4559     if (die_offset != DW_INVALID_OFFSET)
4560     {
4561         DWARFCompileUnitSP cu_sp;
4562         const DWARFDebugInfoEntry* die = DebugInfo()->GetDIEPtr(die_offset, &cu_sp);
4563         return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
4564     }
4565     return NULL;
4566 }
4567 
4568 clang::DeclContext *
4569 SymbolFileDWARF::GetClangDeclContextForDIEOffset (const SymbolContext &sc, dw_offset_t die_offset)
4570 {
4571     if (die_offset != DW_INVALID_OFFSET)
4572     {
4573         DWARFDebugInfo* debug_info = DebugInfo();
4574         if (debug_info)
4575         {
4576             DWARFCompileUnitSP cu_sp;
4577             const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(die_offset, &cu_sp);
4578             if (die)
4579                 return GetClangDeclContextForDIE (sc, cu_sp.get(), die);
4580         }
4581     }
4582     return NULL;
4583 }
4584 
4585 clang::NamespaceDecl *
4586 SymbolFileDWARF::ResolveNamespaceDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry *die)
4587 {
4588     if (die && die->Tag() == DW_TAG_namespace)
4589     {
4590         // See if we already parsed this namespace DIE and associated it with a
4591         // uniqued namespace declaration
4592         clang::NamespaceDecl *namespace_decl = static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die]);
4593         if (namespace_decl)
4594             return namespace_decl;
4595         else
4596         {
4597             const char *namespace_name = die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_name, NULL);
4598             clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, NULL);
4599             namespace_decl = GetClangASTContext().GetUniqueNamespaceDeclaration (namespace_name, containing_decl_ctx);
4600             Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4601             if (log)
4602             {
4603                 if (namespace_name)
4604                 {
4605                     GetObjectFile()->GetModule()->LogMessage (log,
4606                                                               "ASTContext => %p: 0x%8.8" PRIx64 ": DW_TAG_namespace with DW_AT_name(\"%s\") => clang::NamespaceDecl *%p (original = %p)",
4607                                                               static_cast<void*>(GetClangASTContext().getASTContext()),
4608                                                               MakeUserID(die->GetOffset()),
4609                                                               namespace_name,
4610                                                               static_cast<void*>(namespace_decl),
4611                                                               static_cast<void*>(namespace_decl->getOriginalNamespace()));
4612                 }
4613                 else
4614                 {
4615                     GetObjectFile()->GetModule()->LogMessage (log,
4616                                                               "ASTContext => %p: 0x%8.8" PRIx64 ": DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p (original = %p)",
4617                                                               static_cast<void*>(GetClangASTContext().getASTContext()),
4618                                                               MakeUserID(die->GetOffset()),
4619                                                               static_cast<void*>(namespace_decl),
4620                                                               static_cast<void*>(namespace_decl->getOriginalNamespace()));
4621                 }
4622             }
4623 
4624             if (namespace_decl)
4625                 LinkDeclContextToDIE((clang::DeclContext*)namespace_decl, die);
4626             return namespace_decl;
4627         }
4628     }
4629     return NULL;
4630 }
4631 
4632 clang::DeclContext *
4633 SymbolFileDWARF::GetClangDeclContextForDIE (const SymbolContext &sc, DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4634 {
4635     clang::DeclContext *clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4636     if (clang_decl_ctx)
4637         return clang_decl_ctx;
4638     // If this DIE has a specification, or an abstract origin, then trace to those.
4639 
4640     dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4641     if (die_offset != DW_INVALID_OFFSET)
4642         return GetClangDeclContextForDIEOffset (sc, die_offset);
4643 
4644     die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4645     if (die_offset != DW_INVALID_OFFSET)
4646         return GetClangDeclContextForDIEOffset (sc, die_offset);
4647 
4648     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4649     if (log)
4650         GetObjectFile()->GetModule()->LogMessage(log, "SymbolFileDWARF::GetClangDeclContextForDIE (die = 0x%8.8x) %s '%s'", die->GetOffset(), DW_TAG_value_to_name(die->Tag()), die->GetName(this, cu));
4651     // This is the DIE we want.  Parse it, then query our map.
4652     bool assert_not_being_parsed = true;
4653     ResolveTypeUID (cu, die, assert_not_being_parsed);
4654 
4655     clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4656 
4657     return clang_decl_ctx;
4658 }
4659 
4660 clang::DeclContext *
4661 SymbolFileDWARF::GetClangDeclContextContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die, const DWARFDebugInfoEntry **decl_ctx_die_copy)
4662 {
4663     if (m_clang_tu_decl == NULL)
4664         m_clang_tu_decl = GetClangASTContext().getASTContext()->getTranslationUnitDecl();
4665 
4666     const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
4667 
4668     if (decl_ctx_die_copy)
4669         *decl_ctx_die_copy = decl_ctx_die;
4670 
4671     if (decl_ctx_die)
4672     {
4673 
4674         DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find (decl_ctx_die);
4675         if (pos != m_die_to_decl_ctx.end())
4676             return pos->second;
4677 
4678         switch (decl_ctx_die->Tag())
4679         {
4680         case DW_TAG_compile_unit:
4681             return m_clang_tu_decl;
4682 
4683         case DW_TAG_namespace:
4684             return ResolveNamespaceDIE (cu, decl_ctx_die);
4685             break;
4686 
4687         case DW_TAG_structure_type:
4688         case DW_TAG_union_type:
4689         case DW_TAG_class_type:
4690             {
4691                 Type* type = ResolveType (cu, decl_ctx_die);
4692                 if (type)
4693                 {
4694                     clang::DeclContext *decl_ctx = type->GetClangForwardType().GetDeclContextForType ();
4695                     if (decl_ctx)
4696                     {
4697                         LinkDeclContextToDIE (decl_ctx, decl_ctx_die);
4698                         if (decl_ctx)
4699                             return decl_ctx;
4700                     }
4701                 }
4702             }
4703             break;
4704 
4705         default:
4706             break;
4707         }
4708     }
4709     return m_clang_tu_decl;
4710 }
4711 
4712 
4713 const DWARFDebugInfoEntry *
4714 SymbolFileDWARF::GetDeclContextDIEContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4715 {
4716     if (cu && die)
4717     {
4718         const DWARFDebugInfoEntry * const decl_die = die;
4719 
4720         while (die != NULL)
4721         {
4722             // If this is the original DIE that we are searching for a declaration
4723             // for, then don't look in the cache as we don't want our own decl
4724             // context to be our decl context...
4725             if (decl_die != die)
4726             {
4727                 switch (die->Tag())
4728                 {
4729                     case DW_TAG_compile_unit:
4730                     case DW_TAG_namespace:
4731                     case DW_TAG_structure_type:
4732                     case DW_TAG_union_type:
4733                     case DW_TAG_class_type:
4734                         return die;
4735 
4736                     default:
4737                         break;
4738                 }
4739             }
4740 
4741             dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4742             if (die_offset != DW_INVALID_OFFSET)
4743             {
4744                 DWARFCompileUnit *spec_cu = cu;
4745                 const DWARFDebugInfoEntry *spec_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &spec_cu);
4746                 const DWARFDebugInfoEntry *spec_die_decl_ctx_die = GetDeclContextDIEContainingDIE (spec_cu, spec_die);
4747                 if (spec_die_decl_ctx_die)
4748                     return spec_die_decl_ctx_die;
4749             }
4750 
4751             die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4752             if (die_offset != DW_INVALID_OFFSET)
4753             {
4754                 DWARFCompileUnit *abs_cu = cu;
4755                 const DWARFDebugInfoEntry *abs_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &abs_cu);
4756                 const DWARFDebugInfoEntry *abs_die_decl_ctx_die = GetDeclContextDIEContainingDIE (abs_cu, abs_die);
4757                 if (abs_die_decl_ctx_die)
4758                     return abs_die_decl_ctx_die;
4759             }
4760 
4761             die = die->GetParent();
4762         }
4763     }
4764     return NULL;
4765 }
4766 
4767 
4768 Symbol *
4769 SymbolFileDWARF::GetObjCClassSymbol (const ConstString &objc_class_name)
4770 {
4771     Symbol *objc_class_symbol = NULL;
4772     if (m_obj_file)
4773     {
4774         Symtab *symtab = m_obj_file->GetSymtab ();
4775         if (symtab)
4776         {
4777             objc_class_symbol = symtab->FindFirstSymbolWithNameAndType (objc_class_name,
4778                                                                         eSymbolTypeObjCClass,
4779                                                                         Symtab::eDebugNo,
4780                                                                         Symtab::eVisibilityAny);
4781         }
4782     }
4783     return objc_class_symbol;
4784 }
4785 
4786 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If they don't
4787 // then we can end up looking through all class types for a complete type and never find
4788 // the full definition. We need to know if this attribute is supported, so we determine
4789 // this here and cache th result. We also need to worry about the debug map DWARF file
4790 // if we are doing darwin DWARF in .o file debugging.
4791 bool
4792 SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type (DWARFCompileUnit *cu)
4793 {
4794     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate)
4795     {
4796         m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
4797         if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
4798             m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4799         else
4800         {
4801             DWARFDebugInfo* debug_info = DebugInfo();
4802             const uint32_t num_compile_units = GetNumCompileUnits();
4803             for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
4804             {
4805                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
4806                 if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type())
4807                 {
4808                     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4809                     break;
4810                 }
4811             }
4812         }
4813         if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && GetDebugMapSymfile ())
4814             return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type (this);
4815     }
4816     return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
4817 }
4818 
4819 // This function can be used when a DIE is found that is a forward declaration
4820 // DIE and we want to try and find a type that has the complete definition.
4821 TypeSP
4822 SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE (const DWARFDebugInfoEntry *die,
4823                                                        const ConstString &type_name,
4824                                                        bool must_be_implementation)
4825 {
4826 
4827     TypeSP type_sp;
4828 
4829     if (!type_name || (must_be_implementation && !GetObjCClassSymbol (type_name)))
4830         return type_sp;
4831 
4832     DIEArray die_offsets;
4833 
4834     if (m_using_apple_tables)
4835     {
4836         if (m_apple_types_ap.get())
4837         {
4838             const char *name_cstr = type_name.GetCString();
4839             m_apple_types_ap->FindCompleteObjCClassByName (name_cstr, die_offsets, must_be_implementation);
4840         }
4841     }
4842     else
4843     {
4844         if (!m_indexed)
4845             Index ();
4846 
4847         m_type_index.Find (type_name, die_offsets);
4848     }
4849 
4850     const size_t num_matches = die_offsets.size();
4851 
4852     DWARFCompileUnit* type_cu = NULL;
4853     const DWARFDebugInfoEntry* type_die = NULL;
4854     if (num_matches)
4855     {
4856         DWARFDebugInfo* debug_info = DebugInfo();
4857         for (size_t i=0; i<num_matches; ++i)
4858         {
4859             const dw_offset_t die_offset = die_offsets[i];
4860             type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
4861 
4862             if (type_die)
4863             {
4864                 bool try_resolving_type = false;
4865 
4866                 // Don't try and resolve the DIE we are looking for with the DIE itself!
4867                 if (type_die != die)
4868                 {
4869                     switch (type_die->Tag())
4870                     {
4871                         case DW_TAG_class_type:
4872                         case DW_TAG_structure_type:
4873                             try_resolving_type = true;
4874                             break;
4875                         default:
4876                             break;
4877                     }
4878                 }
4879 
4880                 if (try_resolving_type)
4881                 {
4882                     if (must_be_implementation && type_cu->Supports_DW_AT_APPLE_objc_complete_type())
4883                         try_resolving_type = type_die->GetAttributeValueAsUnsigned (this, type_cu, DW_AT_APPLE_objc_complete_type, 0);
4884 
4885                     if (try_resolving_type)
4886                     {
4887                         Type *resolved_type = ResolveType (type_cu, type_die, false);
4888                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
4889                         {
4890                             DEBUG_PRINTF ("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ")\n",
4891                                           MakeUserID(die->GetOffset()),
4892                                           m_obj_file->GetFileSpec().GetFilename().AsCString(),
4893                                           MakeUserID(type_die->GetOffset()),
4894                                           MakeUserID(type_cu->GetOffset()));
4895 
4896                             if (die)
4897                                 m_die_to_type[die] = resolved_type;
4898                             type_sp = resolved_type->shared_from_this();
4899                             break;
4900                         }
4901                     }
4902                 }
4903             }
4904             else
4905             {
4906                 if (m_using_apple_tables)
4907                 {
4908                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4909                                                                die_offset, type_name.GetCString());
4910                 }
4911             }
4912 
4913         }
4914     }
4915     return type_sp;
4916 }
4917 
4918 
4919 //----------------------------------------------------------------------
4920 // This function helps to ensure that the declaration contexts match for
4921 // two different DIEs. Often times debug information will refer to a
4922 // forward declaration of a type (the equivalent of "struct my_struct;".
4923 // There will often be a declaration of that type elsewhere that has the
4924 // full definition. When we go looking for the full type "my_struct", we
4925 // will find one or more matches in the accelerator tables and we will
4926 // then need to make sure the type was in the same declaration context
4927 // as the original DIE. This function can efficiently compare two DIEs
4928 // and will return true when the declaration context matches, and false
4929 // when they don't.
4930 //----------------------------------------------------------------------
4931 bool
4932 SymbolFileDWARF::DIEDeclContextsMatch (DWARFCompileUnit* cu1, const DWARFDebugInfoEntry *die1,
4933                                        DWARFCompileUnit* cu2, const DWARFDebugInfoEntry *die2)
4934 {
4935     if (die1 == die2)
4936         return true;
4937 
4938 #if defined (LLDB_CONFIGURATION_DEBUG)
4939     // You can't and shouldn't call this function with a compile unit from
4940     // two different SymbolFileDWARF instances.
4941     assert (DebugInfo()->ContainsCompileUnit (cu1));
4942     assert (DebugInfo()->ContainsCompileUnit (cu2));
4943 #endif
4944 
4945     DWARFDIECollection decl_ctx_1;
4946     DWARFDIECollection decl_ctx_2;
4947     //The declaration DIE stack is a stack of the declaration context
4948     // DIEs all the way back to the compile unit. If a type "T" is
4949     // declared inside a class "B", and class "B" is declared inside
4950     // a class "A" and class "A" is in a namespace "lldb", and the
4951     // namespace is in a compile unit, there will be a stack of DIEs:
4952     //
4953     //   [0] DW_TAG_class_type for "B"
4954     //   [1] DW_TAG_class_type for "A"
4955     //   [2] DW_TAG_namespace  for "lldb"
4956     //   [3] DW_TAG_compile_unit for the source file.
4957     //
4958     // We grab both contexts and make sure that everything matches
4959     // all the way back to the compiler unit.
4960 
4961     // First lets grab the decl contexts for both DIEs
4962     die1->GetDeclContextDIEs (this, cu1, decl_ctx_1);
4963     die2->GetDeclContextDIEs (this, cu2, decl_ctx_2);
4964     // Make sure the context arrays have the same size, otherwise
4965     // we are done
4966     const size_t count1 = decl_ctx_1.Size();
4967     const size_t count2 = decl_ctx_2.Size();
4968     if (count1 != count2)
4969         return false;
4970 
4971     // Make sure the DW_TAG values match all the way back up the the
4972     // compile unit. If they don't, then we are done.
4973     const DWARFDebugInfoEntry *decl_ctx_die1;
4974     const DWARFDebugInfoEntry *decl_ctx_die2;
4975     size_t i;
4976     for (i=0; i<count1; i++)
4977     {
4978         decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
4979         decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
4980         if (decl_ctx_die1->Tag() != decl_ctx_die2->Tag())
4981             return false;
4982     }
4983 #if defined LLDB_CONFIGURATION_DEBUG
4984 
4985     // Make sure the top item in the decl context die array is always
4986     // DW_TAG_compile_unit. If it isn't then something went wrong in
4987     // the DWARFDebugInfoEntry::GetDeclContextDIEs() function...
4988     assert (decl_ctx_1.GetDIEPtrAtIndex (count1 - 1)->Tag() == DW_TAG_compile_unit);
4989 
4990 #endif
4991     // Always skip the compile unit when comparing by only iterating up to
4992     // "count - 1". Here we compare the names as we go.
4993     for (i=0; i<count1 - 1; i++)
4994     {
4995         decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
4996         decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
4997         const char *name1 = decl_ctx_die1->GetName(this, cu1);
4998         const char *name2 = decl_ctx_die2->GetName(this, cu2);
4999         // If the string was from a DW_FORM_strp, then the pointer will often
5000         // be the same!
5001         if (name1 == name2)
5002             continue;
5003 
5004         // Name pointers are not equal, so only compare the strings
5005         // if both are not NULL.
5006         if (name1 && name2)
5007         {
5008             // If the strings don't compare, we are done...
5009             if (strcmp(name1, name2) != 0)
5010                 return false;
5011         }
5012         else
5013         {
5014             // One name was NULL while the other wasn't
5015             return false;
5016         }
5017     }
5018     // We made it through all of the checks and the declaration contexts
5019     // are equal.
5020     return true;
5021 }
5022 
5023 // This function can be used when a DIE is found that is a forward declaration
5024 // DIE and we want to try and find a type that has the complete definition.
5025 // "cu" and "die" must be from this SymbolFileDWARF
5026 TypeSP
5027 SymbolFileDWARF::FindDefinitionTypeForDIE (DWARFCompileUnit* cu,
5028                                            const DWARFDebugInfoEntry *die,
5029                                            const ConstString &type_name)
5030 {
5031     TypeSP type_sp;
5032 
5033 #if defined (LLDB_CONFIGURATION_DEBUG)
5034     // You can't and shouldn't call this function with a compile unit from
5035     // another SymbolFileDWARF instance.
5036     assert (DebugInfo()->ContainsCompileUnit (cu));
5037 #endif
5038 
5039     if (cu == NULL || die == NULL || !type_name)
5040         return type_sp;
5041 
5042     std::string qualified_name;
5043 
5044     Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
5045     if (log)
5046     {
5047         die->GetQualifiedName(this, cu, qualified_name);
5048         GetObjectFile()->GetModule()->LogMessage (log,
5049                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x (%s), name='%s')",
5050                                                   die->GetOffset(),
5051                                                   qualified_name.c_str(),
5052                                                   type_name.GetCString());
5053     }
5054 
5055     DIEArray die_offsets;
5056 
5057     if (m_using_apple_tables)
5058     {
5059         if (m_apple_types_ap.get())
5060         {
5061             const bool has_tag = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeTag);
5062             const bool has_qualified_name_hash = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeQualNameHash);
5063             if (has_tag && has_qualified_name_hash)
5064             {
5065                 if (qualified_name.empty())
5066                     die->GetQualifiedName(this, cu, qualified_name);
5067 
5068                 const uint32_t qualified_name_hash = MappedHash::HashStringUsingDJB (qualified_name.c_str());
5069                 if (log)
5070                     GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTagAndQualifiedNameHash()");
5071                 m_apple_types_ap->FindByNameAndTagAndQualifiedNameHash (type_name.GetCString(), die->Tag(), qualified_name_hash, die_offsets);
5072             }
5073             else if (has_tag)
5074             {
5075                 if (log)
5076                     GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTag()");
5077                 m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), die->Tag(), die_offsets);
5078             }
5079             else
5080             {
5081                 m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
5082             }
5083         }
5084     }
5085     else
5086     {
5087         if (!m_indexed)
5088             Index ();
5089 
5090         m_type_index.Find (type_name, die_offsets);
5091     }
5092 
5093     const size_t num_matches = die_offsets.size();
5094 
5095     const dw_tag_t die_tag = die->Tag();
5096 
5097     DWARFCompileUnit* type_cu = NULL;
5098     const DWARFDebugInfoEntry* type_die = NULL;
5099     if (num_matches)
5100     {
5101         DWARFDebugInfo* debug_info = DebugInfo();
5102         for (size_t i=0; i<num_matches; ++i)
5103         {
5104             const dw_offset_t die_offset = die_offsets[i];
5105             type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
5106 
5107             if (type_die)
5108             {
5109                 bool try_resolving_type = false;
5110 
5111                 // Don't try and resolve the DIE we are looking for with the DIE itself!
5112                 if (type_die != die)
5113                 {
5114                     const dw_tag_t type_die_tag = type_die->Tag();
5115                     // Make sure the tags match
5116                     if (type_die_tag == die_tag)
5117                     {
5118                         // The tags match, lets try resolving this type
5119                         try_resolving_type = true;
5120                     }
5121                     else
5122                     {
5123                         // The tags don't match, but we need to watch our for a
5124                         // forward declaration for a struct and ("struct foo")
5125                         // ends up being a class ("class foo { ... };") or
5126                         // vice versa.
5127                         switch (type_die_tag)
5128                         {
5129                         case DW_TAG_class_type:
5130                             // We had a "class foo", see if we ended up with a "struct foo { ... };"
5131                             try_resolving_type = (die_tag == DW_TAG_structure_type);
5132                             break;
5133                         case DW_TAG_structure_type:
5134                             // We had a "struct foo", see if we ended up with a "class foo { ... };"
5135                             try_resolving_type = (die_tag == DW_TAG_class_type);
5136                             break;
5137                         default:
5138                             // Tags don't match, don't event try to resolve
5139                             // using this type whose name matches....
5140                             break;
5141                         }
5142                     }
5143                 }
5144 
5145                 if (try_resolving_type)
5146                 {
5147                     if (log)
5148                     {
5149                         std::string qualified_name;
5150                         type_die->GetQualifiedName(this, cu, qualified_name);
5151                         GetObjectFile()->GetModule()->LogMessage (log,
5152                                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x, name='%s') trying die=0x%8.8x (%s)",
5153                                                                   die->GetOffset(),
5154                                                                   type_name.GetCString(),
5155                                                                   type_die->GetOffset(),
5156                                                                   qualified_name.c_str());
5157                     }
5158 
5159                     // Make sure the decl contexts match all the way up
5160                     if (DIEDeclContextsMatch(cu, die, type_cu, type_die))
5161                     {
5162                         Type *resolved_type = ResolveType (type_cu, type_die, false);
5163                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
5164                         {
5165                             DEBUG_PRINTF ("resolved 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ") from %s to 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ")\n",
5166                                           MakeUserID(die->GetOffset()),
5167                                           MakeUserID(cu->GetOffset()),
5168                                           m_obj_file->GetFileSpec().GetFilename().AsCString(),
5169                                           MakeUserID(type_die->GetOffset()),
5170                                           MakeUserID(type_cu->GetOffset()));
5171 
5172                             m_die_to_type[die] = resolved_type;
5173                             type_sp = resolved_type->shared_from_this();
5174                             break;
5175                         }
5176                     }
5177                 }
5178                 else
5179                 {
5180                     if (log)
5181                     {
5182                         std::string qualified_name;
5183                         type_die->GetQualifiedName(this, cu, qualified_name);
5184                         GetObjectFile()->GetModule()->LogMessage (log,
5185                                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x, name='%s') ignoring die=0x%8.8x (%s)",
5186                                                                   die->GetOffset(),
5187                                                                   type_name.GetCString(),
5188                                                                   type_die->GetOffset(),
5189                                                                   qualified_name.c_str());
5190                     }
5191                 }
5192             }
5193             else
5194             {
5195                 if (m_using_apple_tables)
5196                 {
5197                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
5198                                                                                die_offset, type_name.GetCString());
5199                 }
5200             }
5201 
5202         }
5203     }
5204     return type_sp;
5205 }
5206 
5207 TypeSP
5208 SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext (const DWARFDeclContext &dwarf_decl_ctx)
5209 {
5210     TypeSP type_sp;
5211 
5212     const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
5213     if (dwarf_decl_ctx_count > 0)
5214     {
5215         const ConstString type_name(dwarf_decl_ctx[0].name);
5216         const dw_tag_t tag = dwarf_decl_ctx[0].tag;
5217 
5218         if (type_name)
5219         {
5220             Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
5221             if (log)
5222             {
5223                 GetObjectFile()->GetModule()->LogMessage (log,
5224                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s')",
5225                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5226                                                           dwarf_decl_ctx.GetQualifiedName());
5227             }
5228 
5229             DIEArray die_offsets;
5230 
5231             if (m_using_apple_tables)
5232             {
5233                 if (m_apple_types_ap.get())
5234                 {
5235                     const bool has_tag = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeTag);
5236                     const bool has_qualified_name_hash = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeQualNameHash);
5237                     if (has_tag && has_qualified_name_hash)
5238                     {
5239                         const char *qualified_name = dwarf_decl_ctx.GetQualifiedName();
5240                         const uint32_t qualified_name_hash = MappedHash::HashStringUsingDJB (qualified_name);
5241                         if (log)
5242                             GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTagAndQualifiedNameHash()");
5243                         m_apple_types_ap->FindByNameAndTagAndQualifiedNameHash (type_name.GetCString(), tag, qualified_name_hash, die_offsets);
5244                     }
5245                     else if (has_tag)
5246                     {
5247                         if (log)
5248                             GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTag()");
5249                         m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), tag, die_offsets);
5250                     }
5251                     else
5252                     {
5253                         m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
5254                     }
5255                 }
5256             }
5257             else
5258             {
5259                 if (!m_indexed)
5260                     Index ();
5261 
5262                 m_type_index.Find (type_name, die_offsets);
5263             }
5264 
5265             const size_t num_matches = die_offsets.size();
5266 
5267 
5268             DWARFCompileUnit* type_cu = NULL;
5269             const DWARFDebugInfoEntry* type_die = NULL;
5270             if (num_matches)
5271             {
5272                 DWARFDebugInfo* debug_info = DebugInfo();
5273                 for (size_t i=0; i<num_matches; ++i)
5274                 {
5275                     const dw_offset_t die_offset = die_offsets[i];
5276                     type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
5277 
5278                     if (type_die)
5279                     {
5280                         bool try_resolving_type = false;
5281 
5282                         // Don't try and resolve the DIE we are looking for with the DIE itself!
5283                         const dw_tag_t type_tag = type_die->Tag();
5284                         // Make sure the tags match
5285                         if (type_tag == tag)
5286                         {
5287                             // The tags match, lets try resolving this type
5288                             try_resolving_type = true;
5289                         }
5290                         else
5291                         {
5292                             // The tags don't match, but we need to watch our for a
5293                             // forward declaration for a struct and ("struct foo")
5294                             // ends up being a class ("class foo { ... };") or
5295                             // vice versa.
5296                             switch (type_tag)
5297                             {
5298                                 case DW_TAG_class_type:
5299                                     // We had a "class foo", see if we ended up with a "struct foo { ... };"
5300                                     try_resolving_type = (tag == DW_TAG_structure_type);
5301                                     break;
5302                                 case DW_TAG_structure_type:
5303                                     // We had a "struct foo", see if we ended up with a "class foo { ... };"
5304                                     try_resolving_type = (tag == DW_TAG_class_type);
5305                                     break;
5306                                 default:
5307                                     // Tags don't match, don't event try to resolve
5308                                     // using this type whose name matches....
5309                                     break;
5310                             }
5311                         }
5312 
5313                         if (try_resolving_type)
5314                         {
5315                             DWARFDeclContext type_dwarf_decl_ctx;
5316                             type_die->GetDWARFDeclContext (this, type_cu, type_dwarf_decl_ctx);
5317 
5318                             if (log)
5319                             {
5320                                 GetObjectFile()->GetModule()->LogMessage (log,
5321                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') trying die=0x%8.8x (%s)",
5322                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5323                                                                           dwarf_decl_ctx.GetQualifiedName(),
5324                                                                           type_die->GetOffset(),
5325                                                                           type_dwarf_decl_ctx.GetQualifiedName());
5326                             }
5327 
5328                             // Make sure the decl contexts match all the way up
5329                             if (dwarf_decl_ctx == type_dwarf_decl_ctx)
5330                             {
5331                                 Type *resolved_type = ResolveType (type_cu, type_die, false);
5332                                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
5333                                 {
5334                                     type_sp = resolved_type->shared_from_this();
5335                                     break;
5336                                 }
5337                             }
5338                         }
5339                         else
5340                         {
5341                             if (log)
5342                             {
5343                                 std::string qualified_name;
5344                                 type_die->GetQualifiedName(this, type_cu, qualified_name);
5345                                 GetObjectFile()->GetModule()->LogMessage (log,
5346                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') ignoring die=0x%8.8x (%s)",
5347                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5348                                                                           dwarf_decl_ctx.GetQualifiedName(),
5349                                                                           type_die->GetOffset(),
5350                                                                           qualified_name.c_str());
5351                             }
5352                         }
5353                     }
5354                     else
5355                     {
5356                         if (m_using_apple_tables)
5357                         {
5358                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
5359                                                                                        die_offset, type_name.GetCString());
5360                         }
5361                     }
5362 
5363                 }
5364             }
5365         }
5366     }
5367     return type_sp;
5368 }
5369 
5370 bool
5371 SymbolFileDWARF::CopyUniqueClassMethodTypes (SymbolFileDWARF *src_symfile,
5372                                              Type *class_type,
5373                                              DWARFCompileUnit* src_cu,
5374                                              const DWARFDebugInfoEntry *src_class_die,
5375                                              DWARFCompileUnit* dst_cu,
5376                                              const DWARFDebugInfoEntry *dst_class_die,
5377                                              DWARFDIECollection &failures)
5378 {
5379     if (!class_type || !src_cu || !src_class_die || !dst_cu || !dst_class_die)
5380         return false;
5381     if (src_class_die->Tag() != dst_class_die->Tag())
5382         return false;
5383 
5384     // We need to complete the class type so we can get all of the method types
5385     // parsed so we can then unique those types to their equivalent counterparts
5386     // in "dst_cu" and "dst_class_die"
5387     class_type->GetClangFullType();
5388 
5389     const DWARFDebugInfoEntry *src_die;
5390     const DWARFDebugInfoEntry *dst_die;
5391     UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die;
5392     UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die;
5393     UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die_artificial;
5394     UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die_artificial;
5395     for (src_die = src_class_die->GetFirstChild(); src_die != NULL; src_die = src_die->GetSibling())
5396     {
5397         if (src_die->Tag() == DW_TAG_subprogram)
5398         {
5399             // Make sure this is a declaration and not a concrete instance by looking
5400             // for DW_AT_declaration set to 1. Sometimes concrete function instances
5401             // are placed inside the class definitions and shouldn't be included in
5402             // the list of things are are tracking here.
5403             if (src_die->GetAttributeValueAsUnsigned(src_symfile, src_cu, DW_AT_declaration, 0) == 1)
5404             {
5405                 const char *src_name = src_die->GetMangledName (src_symfile, src_cu);
5406                 if (src_name)
5407                 {
5408                     ConstString src_const_name(src_name);
5409                     if (src_die->GetAttributeValueAsUnsigned(src_symfile, src_cu, DW_AT_artificial, 0))
5410                         src_name_to_die_artificial.Append(src_const_name.GetCString(), src_die);
5411                     else
5412                         src_name_to_die.Append(src_const_name.GetCString(), src_die);
5413                 }
5414             }
5415         }
5416     }
5417     for (dst_die = dst_class_die->GetFirstChild(); dst_die != NULL; dst_die = dst_die->GetSibling())
5418     {
5419         if (dst_die->Tag() == DW_TAG_subprogram)
5420         {
5421             // Make sure this is a declaration and not a concrete instance by looking
5422             // for DW_AT_declaration set to 1. Sometimes concrete function instances
5423             // are placed inside the class definitions and shouldn't be included in
5424             // the list of things are are tracking here.
5425             if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_declaration, 0) == 1)
5426             {
5427                 const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5428                 if (dst_name)
5429                 {
5430                     ConstString dst_const_name(dst_name);
5431                     if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_artificial, 0))
5432                         dst_name_to_die_artificial.Append(dst_const_name.GetCString(), dst_die);
5433                     else
5434                         dst_name_to_die.Append(dst_const_name.GetCString(), dst_die);
5435                 }
5436             }
5437         }
5438     }
5439     const uint32_t src_size = src_name_to_die.GetSize ();
5440     const uint32_t dst_size = dst_name_to_die.GetSize ();
5441     Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | DWARF_LOG_TYPE_COMPLETION));
5442 
5443     // Is everything kosher so we can go through the members at top speed?
5444     bool fast_path = true;
5445 
5446     if (src_size != dst_size)
5447     {
5448         if (src_size != 0 && dst_size != 0)
5449         {
5450             if (log)
5451                 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)",
5452                             src_class_die->GetOffset(),
5453                             dst_class_die->GetOffset(),
5454                             src_size,
5455                             dst_size);
5456         }
5457 
5458         fast_path = false;
5459     }
5460 
5461     uint32_t idx;
5462 
5463     if (fast_path)
5464     {
5465         for (idx = 0; idx < src_size; ++idx)
5466         {
5467             src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5468             dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5469 
5470             if (src_die->Tag() != dst_die->Tag())
5471             {
5472                 if (log)
5473                     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)",
5474                                 src_class_die->GetOffset(),
5475                                 dst_class_die->GetOffset(),
5476                                 src_die->GetOffset(),
5477                                 DW_TAG_value_to_name(src_die->Tag()),
5478                                 dst_die->GetOffset(),
5479                                 DW_TAG_value_to_name(src_die->Tag()));
5480                 fast_path = false;
5481             }
5482 
5483             const char *src_name = src_die->GetMangledName (src_symfile, src_cu);
5484             const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5485 
5486             // Make sure the names match
5487             if (src_name == dst_name || (strcmp (src_name, dst_name) == 0))
5488                 continue;
5489 
5490             if (log)
5491                 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)",
5492                             src_class_die->GetOffset(),
5493                             dst_class_die->GetOffset(),
5494                             src_die->GetOffset(),
5495                             src_name,
5496                             dst_die->GetOffset(),
5497                             dst_name);
5498 
5499             fast_path = false;
5500         }
5501     }
5502 
5503     // Now do the work of linking the DeclContexts and Types.
5504     if (fast_path)
5505     {
5506         // We can do this quickly.  Just run across the tables index-for-index since
5507         // we know each node has matching names and tags.
5508         for (idx = 0; idx < src_size; ++idx)
5509         {
5510             src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5511             dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5512 
5513             clang::DeclContext *src_decl_ctx = src_symfile->m_die_to_decl_ctx[src_die];
5514             if (src_decl_ctx)
5515             {
5516                 if (log)
5517                     log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
5518                                  static_cast<void*>(src_decl_ctx),
5519                                  src_die->GetOffset(), dst_die->GetOffset());
5520                 LinkDeclContextToDIE (src_decl_ctx, dst_die);
5521             }
5522             else
5523             {
5524                 if (log)
5525                     log->Printf ("warning: tried to unique decl context from 0x%8.8x for 0x%8.8x, but none was found",
5526                                  src_die->GetOffset(), dst_die->GetOffset());
5527             }
5528 
5529             Type *src_child_type = m_die_to_type[src_die];
5530             if (src_child_type)
5531             {
5532                 if (log)
5533                     log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
5534                                  static_cast<void*>(src_child_type),
5535                                  src_child_type->GetID(),
5536                                  src_die->GetOffset(), dst_die->GetOffset());
5537                 m_die_to_type[dst_die] = src_child_type;
5538             }
5539             else
5540             {
5541                 if (log)
5542                     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());
5543             }
5544         }
5545     }
5546     else
5547     {
5548         // We must do this slowly.  For each member of the destination, look
5549         // up a member in the source with the same name, check its tag, and
5550         // unique them if everything matches up.  Report failures.
5551 
5552         if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty())
5553         {
5554             src_name_to_die.Sort();
5555 
5556             for (idx = 0; idx < dst_size; ++idx)
5557             {
5558                 const char *dst_name = dst_name_to_die.GetCStringAtIndex(idx);
5559                 dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
5560                 src_die = src_name_to_die.Find(dst_name, NULL);
5561 
5562                 if (src_die && (src_die->Tag() == dst_die->Tag()))
5563                 {
5564                     clang::DeclContext *src_decl_ctx = src_symfile->m_die_to_decl_ctx[src_die];
5565                     if (src_decl_ctx)
5566                     {
5567                         if (log)
5568                             log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
5569                                          static_cast<void*>(src_decl_ctx),
5570                                          src_die->GetOffset(),
5571                                          dst_die->GetOffset());
5572                         LinkDeclContextToDIE (src_decl_ctx, dst_die);
5573                     }
5574                     else
5575                     {
5576                         if (log)
5577                             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());
5578                     }
5579 
5580                     Type *src_child_type = m_die_to_type[src_die];
5581                     if (src_child_type)
5582                     {
5583                         if (log)
5584                             log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
5585                                          static_cast<void*>(src_child_type),
5586                                          src_child_type->GetID(),
5587                                          src_die->GetOffset(),
5588                                          dst_die->GetOffset());
5589                         m_die_to_type[dst_die] = src_child_type;
5590                     }
5591                     else
5592                     {
5593                         if (log)
5594                             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());
5595                     }
5596                 }
5597                 else
5598                 {
5599                     if (log)
5600                         log->Printf ("warning: couldn't find a match for 0x%8.8x", dst_die->GetOffset());
5601 
5602                     failures.Append(dst_die);
5603                 }
5604             }
5605         }
5606     }
5607 
5608     const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize ();
5609     const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize ();
5610 
5611     UniqueCStringMap<const DWARFDebugInfoEntry *> name_to_die_artificial_not_in_src;
5612 
5613     if (src_size_artificial && dst_size_artificial)
5614     {
5615         dst_name_to_die_artificial.Sort();
5616 
5617         for (idx = 0; idx < src_size_artificial; ++idx)
5618         {
5619             const char *src_name_artificial = src_name_to_die_artificial.GetCStringAtIndex(idx);
5620             src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5621             dst_die = dst_name_to_die_artificial.Find(src_name_artificial, NULL);
5622 
5623             if (dst_die)
5624             {
5625                 // Both classes have the artificial types, link them
5626                 clang::DeclContext *src_decl_ctx = m_die_to_decl_ctx[src_die];
5627                 if (src_decl_ctx)
5628                 {
5629                     if (log)
5630                         log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
5631                                      static_cast<void*>(src_decl_ctx),
5632                                      src_die->GetOffset(), dst_die->GetOffset());
5633                     LinkDeclContextToDIE (src_decl_ctx, dst_die);
5634                 }
5635                 else
5636                 {
5637                     if (log)
5638                         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());
5639                 }
5640 
5641                 Type *src_child_type = m_die_to_type[src_die];
5642                 if (src_child_type)
5643                 {
5644                     if (log)
5645                         log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
5646                                      static_cast<void*>(src_child_type),
5647                                      src_child_type->GetID(),
5648                                      src_die->GetOffset(), dst_die->GetOffset());
5649                     m_die_to_type[dst_die] = src_child_type;
5650                 }
5651                 else
5652                 {
5653                     if (log)
5654                         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());
5655                 }
5656             }
5657         }
5658     }
5659 
5660     if (dst_size_artificial)
5661     {
5662         for (idx = 0; idx < dst_size_artificial; ++idx)
5663         {
5664             const char *dst_name_artificial = dst_name_to_die_artificial.GetCStringAtIndex(idx);
5665             dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5666             if (log)
5667                 log->Printf ("warning: need to create artificial method for 0x%8.8x for method '%s'", dst_die->GetOffset(), dst_name_artificial);
5668 
5669             failures.Append(dst_die);
5670         }
5671     }
5672 
5673     return (failures.Size() != 0);
5674 }
5675 
5676 TypeSP
5677 SymbolFileDWARF::ParseType (const SymbolContext& sc, DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry *die, bool *type_is_new_ptr)
5678 {
5679     TypeSP type_sp;
5680 
5681     if (type_is_new_ptr)
5682         *type_is_new_ptr = false;
5683 
5684 #if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
5685     static DIEStack g_die_stack;
5686     DIEStack::ScopedPopper scoped_die_logger(g_die_stack);
5687 #endif
5688 
5689     AccessType accessibility = eAccessNone;
5690     if (die != NULL)
5691     {
5692         Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5693         if (log)
5694         {
5695             const DWARFDebugInfoEntry *context_die;
5696             clang::DeclContext *context = GetClangDeclContextContainingDIE (dwarf_cu, die, &context_die);
5697 
5698             GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die 0x%8.8x)) %s name = '%s')",
5699                                                       die->GetOffset(),
5700                                                       static_cast<void*>(context),
5701                                                       context_die->GetOffset(),
5702                                                       DW_TAG_value_to_name(die->Tag()),
5703                                                       die->GetName(this, dwarf_cu));
5704 
5705 #if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
5706             scoped_die_logger.Push (dwarf_cu, die);
5707             g_die_stack.LogDIEs(log, this);
5708 #endif
5709         }
5710 //
5711 //        Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5712 //        if (log && dwarf_cu)
5713 //        {
5714 //            StreamString s;
5715 //            die->DumpLocation (this, dwarf_cu, s);
5716 //            GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDwarf::%s %s", __FUNCTION__, s.GetData());
5717 //
5718 //        }
5719 
5720         Type *type_ptr = m_die_to_type.lookup (die);
5721         TypeList* type_list = GetTypeList();
5722         if (type_ptr == NULL)
5723         {
5724             ClangASTContext &ast = GetClangASTContext();
5725             if (type_is_new_ptr)
5726                 *type_is_new_ptr = true;
5727 
5728             const dw_tag_t tag = die->Tag();
5729 
5730             bool is_forward_declaration = false;
5731             DWARFDebugInfoEntry::Attributes attributes;
5732             const char *type_name_cstr = NULL;
5733             ConstString type_name_const_str;
5734             Type::ResolveState resolve_state = Type::eResolveStateUnresolved;
5735             uint64_t byte_size = 0;
5736             Declaration decl;
5737 
5738             Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
5739             ClangASTType clang_type;
5740             DWARFFormValue form_value;
5741 
5742             dw_attr_t attr;
5743 
5744             switch (tag)
5745             {
5746             case DW_TAG_base_type:
5747             case DW_TAG_pointer_type:
5748             case DW_TAG_reference_type:
5749             case DW_TAG_rvalue_reference_type:
5750             case DW_TAG_typedef:
5751             case DW_TAG_const_type:
5752             case DW_TAG_restrict_type:
5753             case DW_TAG_volatile_type:
5754             case DW_TAG_unspecified_type:
5755                 {
5756                     // Set a bit that lets us know that we are currently parsing this
5757                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5758 
5759                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5760                     uint32_t encoding = 0;
5761                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
5762 
5763                     if (num_attributes > 0)
5764                     {
5765                         uint32_t i;
5766                         for (i=0; i<num_attributes; ++i)
5767                         {
5768                             attr = attributes.AttributeAtIndex(i);
5769                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5770                             {
5771                                 switch (attr)
5772                                 {
5773                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
5774                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
5775                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
5776                                 case DW_AT_name:
5777 
5778                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5779                                     // Work around a bug in llvm-gcc where they give a name to a reference type which doesn't
5780                                     // include the "&"...
5781                                     if (tag == DW_TAG_reference_type)
5782                                     {
5783                                         if (strchr (type_name_cstr, '&') == NULL)
5784                                             type_name_cstr = NULL;
5785                                     }
5786                                     if (type_name_cstr)
5787                                         type_name_const_str.SetCString(type_name_cstr);
5788                                     break;
5789                                 case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
5790                                 case DW_AT_encoding:    encoding = form_value.Unsigned(); break;
5791                                 case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
5792                                 default:
5793                                 case DW_AT_sibling:
5794                                     break;
5795                                 }
5796                             }
5797                         }
5798                     }
5799 
5800                     DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr, encoding_uid);
5801 
5802                     switch (tag)
5803                     {
5804                     default:
5805                         break;
5806 
5807                     case DW_TAG_unspecified_type:
5808                         if (strcmp(type_name_cstr, "nullptr_t") == 0 ||
5809                             strcmp(type_name_cstr, "decltype(nullptr)") == 0 )
5810                         {
5811                             resolve_state = Type::eResolveStateFull;
5812                             clang_type = ast.GetBasicType(eBasicTypeNullPtr);
5813                             break;
5814                         }
5815                         // Fall through to base type below in case we can handle the type there...
5816 
5817                     case DW_TAG_base_type:
5818                         resolve_state = Type::eResolveStateFull;
5819                         clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (type_name_cstr,
5820                                                                                    encoding,
5821                                                                                    byte_size * 8);
5822                         break;
5823 
5824                     case DW_TAG_pointer_type:           encoding_data_type = Type::eEncodingIsPointerUID;           break;
5825                     case DW_TAG_reference_type:         encoding_data_type = Type::eEncodingIsLValueReferenceUID;   break;
5826                     case DW_TAG_rvalue_reference_type:  encoding_data_type = Type::eEncodingIsRValueReferenceUID;   break;
5827                     case DW_TAG_typedef:                encoding_data_type = Type::eEncodingIsTypedefUID;           break;
5828                     case DW_TAG_const_type:             encoding_data_type = Type::eEncodingIsConstUID;             break;
5829                     case DW_TAG_restrict_type:          encoding_data_type = Type::eEncodingIsRestrictUID;          break;
5830                     case DW_TAG_volatile_type:          encoding_data_type = Type::eEncodingIsVolatileUID;          break;
5831                     }
5832 
5833                     if (!clang_type && (encoding_data_type == Type::eEncodingIsPointerUID || encoding_data_type == Type::eEncodingIsTypedefUID) && sc.comp_unit != NULL)
5834                     {
5835                         bool translation_unit_is_objc = (sc.comp_unit->GetLanguage() == eLanguageTypeObjC || sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus);
5836 
5837                         if (translation_unit_is_objc)
5838                         {
5839                             if (type_name_cstr != NULL)
5840                             {
5841                                 static ConstString g_objc_type_name_id("id");
5842                                 static ConstString g_objc_type_name_Class("Class");
5843                                 static ConstString g_objc_type_name_selector("SEL");
5844 
5845                                 if (type_name_const_str == g_objc_type_name_id)
5846                                 {
5847                                     if (log)
5848                                         GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'id' built-in type.",
5849                                                                                   die->GetOffset(),
5850                                                                                   DW_TAG_value_to_name(die->Tag()),
5851                                                                                   die->GetName(this, dwarf_cu));
5852                                     clang_type = ast.GetBasicType(eBasicTypeObjCID);
5853                                     encoding_data_type = Type::eEncodingIsUID;
5854                                     encoding_uid = LLDB_INVALID_UID;
5855                                     resolve_state = Type::eResolveStateFull;
5856 
5857                                 }
5858                                 else if (type_name_const_str == g_objc_type_name_Class)
5859                                 {
5860                                     if (log)
5861                                         GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'Class' built-in type.",
5862                                                                                   die->GetOffset(),
5863                                                                                   DW_TAG_value_to_name(die->Tag()),
5864                                                                                   die->GetName(this, dwarf_cu));
5865                                     clang_type = ast.GetBasicType(eBasicTypeObjCClass);
5866                                     encoding_data_type = Type::eEncodingIsUID;
5867                                     encoding_uid = LLDB_INVALID_UID;
5868                                     resolve_state = Type::eResolveStateFull;
5869                                 }
5870                                 else if (type_name_const_str == g_objc_type_name_selector)
5871                                 {
5872                                     if (log)
5873                                         GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'selector' built-in type.",
5874                                                                                   die->GetOffset(),
5875                                                                                   DW_TAG_value_to_name(die->Tag()),
5876                                                                                   die->GetName(this, dwarf_cu));
5877                                     clang_type = ast.GetBasicType(eBasicTypeObjCSel);
5878                                     encoding_data_type = Type::eEncodingIsUID;
5879                                     encoding_uid = LLDB_INVALID_UID;
5880                                     resolve_state = Type::eResolveStateFull;
5881                                 }
5882                             }
5883                             else if (encoding_data_type == Type::eEncodingIsPointerUID && encoding_uid != LLDB_INVALID_UID)
5884                             {
5885                                 // Clang sometimes erroneously emits id as objc_object*.  In that case we fix up the type to "id".
5886 
5887                                 DWARFDebugInfoEntry* encoding_die = dwarf_cu->GetDIEPtr(encoding_uid);
5888 
5889                                 if (encoding_die && encoding_die->Tag() == DW_TAG_structure_type)
5890                                 {
5891                                     if (const char *struct_name = encoding_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_name, NULL))
5892                                     {
5893                                         if (!strcmp(struct_name, "objc_object"))
5894                                         {
5895                                             if (log)
5896                                                 GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is 'objc_object*', which we overrode to 'id'.",
5897                                                                                           die->GetOffset(),
5898                                                                                           DW_TAG_value_to_name(die->Tag()),
5899                                                                                           die->GetName(this, dwarf_cu));
5900                                             clang_type = ast.GetBasicType(eBasicTypeObjCID);
5901                                             encoding_data_type = Type::eEncodingIsUID;
5902                                             encoding_uid = LLDB_INVALID_UID;
5903                                             resolve_state = Type::eResolveStateFull;
5904                                         }
5905                                     }
5906                                 }
5907                             }
5908                         }
5909                     }
5910 
5911                     type_sp.reset( new Type (MakeUserID(die->GetOffset()),
5912                                              this,
5913                                              type_name_const_str,
5914                                              byte_size,
5915                                              NULL,
5916                                              encoding_uid,
5917                                              encoding_data_type,
5918                                              &decl,
5919                                              clang_type,
5920                                              resolve_state));
5921 
5922                     m_die_to_type[die] = type_sp.get();
5923 
5924 //                  Type* encoding_type = GetUniquedTypeForDIEOffset(encoding_uid, type_sp, NULL, 0, 0, false);
5925 //                  if (encoding_type != NULL)
5926 //                  {
5927 //                      if (encoding_type != DIE_IS_BEING_PARSED)
5928 //                          type_sp->SetEncodingType(encoding_type);
5929 //                      else
5930 //                          m_indirect_fixups.push_back(type_sp.get());
5931 //                  }
5932                 }
5933                 break;
5934 
5935             case DW_TAG_structure_type:
5936             case DW_TAG_union_type:
5937             case DW_TAG_class_type:
5938                 {
5939                     // Set a bit that lets us know that we are currently parsing this
5940                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5941                     bool byte_size_valid = false;
5942 
5943                     LanguageType class_language = eLanguageTypeUnknown;
5944                     bool is_complete_objc_class = false;
5945                     //bool struct_is_class = false;
5946                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5947                     if (num_attributes > 0)
5948                     {
5949                         uint32_t i;
5950                         for (i=0; i<num_attributes; ++i)
5951                         {
5952                             attr = attributes.AttributeAtIndex(i);
5953                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5954                             {
5955                                 switch (attr)
5956                                 {
5957                                 case DW_AT_decl_file:
5958                                     if (dwarf_cu->DW_AT_decl_file_attributes_are_invalid())
5959                                     {
5960                                         // llvm-gcc outputs invalid DW_AT_decl_file attributes that always
5961                                         // point to the compile unit file, so we clear this invalid value
5962                                         // so that we can still unique types efficiently.
5963                                         decl.SetFile(FileSpec ("<invalid>", false));
5964                                     }
5965                                     else
5966                                         decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned()));
5967                                     break;
5968 
5969                                 case DW_AT_decl_line:
5970                                     decl.SetLine(form_value.Unsigned());
5971                                     break;
5972 
5973                                 case DW_AT_decl_column:
5974                                     decl.SetColumn(form_value.Unsigned());
5975                                     break;
5976 
5977                                 case DW_AT_name:
5978                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5979                                     type_name_const_str.SetCString(type_name_cstr);
5980                                     break;
5981 
5982                                 case DW_AT_byte_size:
5983                                     byte_size = form_value.Unsigned();
5984                                     byte_size_valid = true;
5985                                     break;
5986 
5987                                 case DW_AT_accessibility:
5988                                     accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
5989                                     break;
5990 
5991                                 case DW_AT_declaration:
5992                                     is_forward_declaration = form_value.Boolean();
5993                                     break;
5994 
5995                                 case DW_AT_APPLE_runtime_class:
5996                                     class_language = (LanguageType)form_value.Signed();
5997                                     break;
5998 
5999                                 case DW_AT_APPLE_objc_complete_type:
6000                                     is_complete_objc_class = form_value.Signed();
6001                                     break;
6002 
6003                                 case DW_AT_allocated:
6004                                 case DW_AT_associated:
6005                                 case DW_AT_data_location:
6006                                 case DW_AT_description:
6007                                 case DW_AT_start_scope:
6008                                 case DW_AT_visibility:
6009                                 default:
6010                                 case DW_AT_sibling:
6011                                     break;
6012                                 }
6013                             }
6014                         }
6015                     }
6016 
6017                     // UniqueDWARFASTType is large, so don't create a local variables on the
6018                     // stack, put it on the heap. This function is often called recursively
6019                     // and clang isn't good and sharing the stack space for variables in different blocks.
6020                     std::unique_ptr<UniqueDWARFASTType> unique_ast_entry_ap(new UniqueDWARFASTType());
6021 
6022                     // Only try and unique the type if it has a name.
6023                     if (type_name_const_str &&
6024                         GetUniqueDWARFASTTypeMap().Find (type_name_const_str,
6025                                                          this,
6026                                                          dwarf_cu,
6027                                                          die,
6028                                                          decl,
6029                                                          byte_size_valid ? byte_size : -1,
6030                                                          *unique_ast_entry_ap))
6031                     {
6032                         // We have already parsed this type or from another
6033                         // compile unit. GCC loves to use the "one definition
6034                         // rule" which can result in multiple definitions
6035                         // of the same class over and over in each compile
6036                         // unit.
6037                         type_sp = unique_ast_entry_ap->m_type_sp;
6038                         if (type_sp)
6039                         {
6040                             m_die_to_type[die] = type_sp.get();
6041                             return type_sp;
6042                         }
6043                     }
6044 
6045                     DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6046 
6047                     int tag_decl_kind = -1;
6048                     AccessType default_accessibility = eAccessNone;
6049                     if (tag == DW_TAG_structure_type)
6050                     {
6051                         tag_decl_kind = clang::TTK_Struct;
6052                         default_accessibility = eAccessPublic;
6053                     }
6054                     else if (tag == DW_TAG_union_type)
6055                     {
6056                         tag_decl_kind = clang::TTK_Union;
6057                         default_accessibility = eAccessPublic;
6058                     }
6059                     else if (tag == DW_TAG_class_type)
6060                     {
6061                         tag_decl_kind = clang::TTK_Class;
6062                         default_accessibility = eAccessPrivate;
6063                     }
6064 
6065                     if (byte_size_valid && byte_size == 0 && type_name_cstr &&
6066                         die->HasChildren() == false &&
6067                         sc.comp_unit->GetLanguage() == eLanguageTypeObjC)
6068                     {
6069                         // Work around an issue with clang at the moment where
6070                         // forward declarations for objective C classes are emitted
6071                         // as:
6072                         //  DW_TAG_structure_type [2]
6073                         //  DW_AT_name( "ForwardObjcClass" )
6074                         //  DW_AT_byte_size( 0x00 )
6075                         //  DW_AT_decl_file( "..." )
6076                         //  DW_AT_decl_line( 1 )
6077                         //
6078                         // Note that there is no DW_AT_declaration and there are
6079                         // no children, and the byte size is zero.
6080                         is_forward_declaration = true;
6081                     }
6082 
6083                     if (class_language == eLanguageTypeObjC ||
6084                         class_language == eLanguageTypeObjC_plus_plus)
6085                     {
6086                         if (!is_complete_objc_class && Supports_DW_AT_APPLE_objc_complete_type(dwarf_cu))
6087                         {
6088                             // We have a valid eSymbolTypeObjCClass class symbol whose
6089                             // name matches the current objective C class that we
6090                             // are trying to find and this DIE isn't the complete
6091                             // definition (we checked is_complete_objc_class above and
6092                             // know it is false), so the real definition is in here somewhere
6093                             type_sp = FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
6094 
6095                             if (!type_sp && GetDebugMapSymfile ())
6096                             {
6097                                 // We weren't able to find a full declaration in
6098                                 // this DWARF, see if we have a declaration anywhere
6099                                 // else...
6100                                 type_sp = m_debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
6101                             }
6102 
6103                             if (type_sp)
6104                             {
6105                                 if (log)
6106                                 {
6107                                     GetObjectFile()->GetModule()->LogMessage (log,
6108                                                                               "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an incomplete objc type, complete type is 0x%8.8" PRIx64,
6109                                                                               static_cast<void*>(this),
6110                                                                               die->GetOffset(),
6111                                                                               DW_TAG_value_to_name(tag),
6112                                                                               type_name_cstr,
6113                                                                               type_sp->GetID());
6114                                 }
6115 
6116                                 // We found a real definition for this type elsewhere
6117                                 // so lets use it and cache the fact that we found
6118                                 // a complete type for this die
6119                                 m_die_to_type[die] = type_sp.get();
6120                                 return type_sp;
6121                             }
6122                         }
6123                     }
6124 
6125 
6126                     if (is_forward_declaration)
6127                     {
6128                         // We have a forward declaration to a type and we need
6129                         // to try and find a full declaration. We look in the
6130                         // current type index just in case we have a forward
6131                         // declaration followed by an actual declarations in the
6132                         // DWARF. If this fails, we need to look elsewhere...
6133                         if (log)
6134                         {
6135                             GetObjectFile()->GetModule()->LogMessage (log,
6136                                                                       "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, trying to find complete type",
6137                                                                       static_cast<void*>(this),
6138                                                                       die->GetOffset(),
6139                                                                       DW_TAG_value_to_name(tag),
6140                                                                       type_name_cstr);
6141                         }
6142 
6143                         DWARFDeclContext die_decl_ctx;
6144                         die->GetDWARFDeclContext(this, dwarf_cu, die_decl_ctx);
6145 
6146                         //type_sp = FindDefinitionTypeForDIE (dwarf_cu, die, type_name_const_str);
6147                         type_sp = FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
6148 
6149                         if (!type_sp && GetDebugMapSymfile ())
6150                         {
6151                             // We weren't able to find a full declaration in
6152                             // this DWARF, see if we have a declaration anywhere
6153                             // else...
6154                             type_sp = m_debug_map_symfile->FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
6155                         }
6156 
6157                         if (type_sp)
6158                         {
6159                             if (log)
6160                             {
6161                                 GetObjectFile()->GetModule()->LogMessage (log,
6162                                                                           "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, complete type is 0x%8.8" PRIx64,
6163                                                                           static_cast<void*>(this),
6164                                                                           die->GetOffset(),
6165                                                                           DW_TAG_value_to_name(tag),
6166                                                                           type_name_cstr,
6167                                                                           type_sp->GetID());
6168                             }
6169 
6170                             // We found a real definition for this type elsewhere
6171                             // so lets use it and cache the fact that we found
6172                             // a complete type for this die
6173                             m_die_to_type[die] = type_sp.get();
6174                             return type_sp;
6175                         }
6176                     }
6177                     assert (tag_decl_kind != -1);
6178                     bool clang_type_was_created = false;
6179                     clang_type.SetClangType(ast.getASTContext(), m_forward_decl_die_to_clang_type.lookup (die));
6180                     if (!clang_type)
6181                     {
6182                         const DWARFDebugInfoEntry *decl_ctx_die;
6183 
6184                         clang::DeclContext *decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
6185                         if (accessibility == eAccessNone && decl_ctx)
6186                         {
6187                             // Check the decl context that contains this class/struct/union.
6188                             // If it is a class we must give it an accessability.
6189                             const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind();
6190                             if (DeclKindIsCXXClass (containing_decl_kind))
6191                                 accessibility = default_accessibility;
6192                         }
6193 
6194                         ClangASTMetadata metadata;
6195                         metadata.SetUserID(MakeUserID(die->GetOffset()));
6196                         metadata.SetIsDynamicCXXType(ClassOrStructIsVirtual (dwarf_cu, die));
6197 
6198                         if (type_name_cstr && strchr (type_name_cstr, '<'))
6199                         {
6200                             ClangASTContext::TemplateParameterInfos template_param_infos;
6201                             if (ParseTemplateParameterInfos (dwarf_cu, die, template_param_infos))
6202                             {
6203                                 clang::ClassTemplateDecl *class_template_decl = ParseClassTemplateDecl (decl_ctx,
6204                                                                                                         accessibility,
6205                                                                                                         type_name_cstr,
6206                                                                                                         tag_decl_kind,
6207                                                                                                         template_param_infos);
6208 
6209                                 clang::ClassTemplateSpecializationDecl *class_specialization_decl = ast.CreateClassTemplateSpecializationDecl (decl_ctx,
6210                                                                                                                                                class_template_decl,
6211                                                                                                                                                tag_decl_kind,
6212                                                                                                                                                template_param_infos);
6213                                 clang_type = ast.CreateClassTemplateSpecializationType (class_specialization_decl);
6214                                 clang_type_was_created = true;
6215 
6216                                 GetClangASTContext().SetMetadata (class_template_decl, metadata);
6217                                 GetClangASTContext().SetMetadata (class_specialization_decl, metadata);
6218                             }
6219                         }
6220 
6221                         if (!clang_type_was_created)
6222                         {
6223                             clang_type_was_created = true;
6224                             clang_type = ast.CreateRecordType (decl_ctx,
6225                                                                accessibility,
6226                                                                type_name_cstr,
6227                                                                tag_decl_kind,
6228                                                                class_language,
6229                                                                &metadata);
6230                         }
6231                     }
6232 
6233                     // Store a forward declaration to this class type in case any
6234                     // parameters in any class methods need it for the clang
6235                     // types for function prototypes.
6236                     LinkDeclContextToDIE(clang_type.GetDeclContextForType(), die);
6237                     type_sp.reset (new Type (MakeUserID(die->GetOffset()),
6238                                              this,
6239                                              type_name_const_str,
6240                                              byte_size,
6241                                              NULL,
6242                                              LLDB_INVALID_UID,
6243                                              Type::eEncodingIsUID,
6244                                              &decl,
6245                                              clang_type,
6246                                              Type::eResolveStateForward));
6247 
6248                     type_sp->SetIsCompleteObjCClass(is_complete_objc_class);
6249 
6250 
6251                     // Add our type to the unique type map so we don't
6252                     // end up creating many copies of the same type over
6253                     // and over in the ASTContext for our module
6254                     unique_ast_entry_ap->m_type_sp = type_sp;
6255                     unique_ast_entry_ap->m_symfile = this;
6256                     unique_ast_entry_ap->m_cu = dwarf_cu;
6257                     unique_ast_entry_ap->m_die = die;
6258                     unique_ast_entry_ap->m_declaration = decl;
6259                     unique_ast_entry_ap->m_byte_size = byte_size;
6260                     GetUniqueDWARFASTTypeMap().Insert (type_name_const_str,
6261                                                        *unique_ast_entry_ap);
6262 
6263                     if (is_forward_declaration && die->HasChildren())
6264                     {
6265                         // Check to see if the DIE actually has a definition, some version of GCC will
6266                         // emit DIEs with DW_AT_declaration set to true, but yet still have subprogram,
6267                         // members, or inheritance, so we can't trust it
6268                         const DWARFDebugInfoEntry *child_die = die->GetFirstChild();
6269                         while (child_die)
6270                         {
6271                             switch (child_die->Tag())
6272                             {
6273                                 case DW_TAG_inheritance:
6274                                 case DW_TAG_subprogram:
6275                                 case DW_TAG_member:
6276                                 case DW_TAG_APPLE_property:
6277                                 case DW_TAG_class_type:
6278                                 case DW_TAG_structure_type:
6279                                 case DW_TAG_enumeration_type:
6280                                 case DW_TAG_typedef:
6281                                 case DW_TAG_union_type:
6282                                     child_die = NULL;
6283                                     is_forward_declaration = false;
6284                                     break;
6285                                 default:
6286                                     child_die = child_die->GetSibling();
6287                                     break;
6288                             }
6289                         }
6290                     }
6291 
6292                     if (!is_forward_declaration)
6293                     {
6294                         // Always start the definition for a class type so that
6295                         // if the class has child classes or types that require
6296                         // the class to be created for use as their decl contexts
6297                         // the class will be ready to accept these child definitions.
6298                         if (die->HasChildren() == false)
6299                         {
6300                             // No children for this struct/union/class, lets finish it
6301                             clang_type.StartTagDeclarationDefinition ();
6302                             clang_type.CompleteTagDeclarationDefinition ();
6303 
6304                             if (tag == DW_TAG_structure_type) // this only applies in C
6305                             {
6306                                 clang::RecordDecl *record_decl = clang_type.GetAsRecordDecl();
6307 
6308                                 if (record_decl)
6309                                     m_record_decl_to_layout_map.insert(std::make_pair(record_decl, LayoutInfo()));
6310                             }
6311                         }
6312                         else if (clang_type_was_created)
6313                         {
6314                             // Start the definition if the class is not objective C since
6315                             // the underlying decls respond to isCompleteDefinition(). Objective
6316                             // C decls dont' respond to isCompleteDefinition() so we can't
6317                             // start the declaration definition right away. For C++ classs/union/structs
6318                             // we want to start the definition in case the class is needed as the
6319                             // declaration context for a contained class or type without the need
6320                             // to complete that type..
6321 
6322                             if (class_language != eLanguageTypeObjC &&
6323                                 class_language != eLanguageTypeObjC_plus_plus)
6324                                 clang_type.StartTagDeclarationDefinition ();
6325 
6326                             // Leave this as a forward declaration until we need
6327                             // to know the details of the type. lldb_private::Type
6328                             // will automatically call the SymbolFile virtual function
6329                             // "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition(Type *)"
6330                             // When the definition needs to be defined.
6331                             m_forward_decl_die_to_clang_type[die] = clang_type.GetOpaqueQualType();
6332                             m_forward_decl_clang_type_to_die[clang_type.RemoveFastQualifiers().GetOpaqueQualType()] = die;
6333                             clang_type.SetHasExternalStorage (true);
6334                         }
6335                     }
6336 
6337                 }
6338                 break;
6339 
6340             case DW_TAG_enumeration_type:
6341                 {
6342                     // Set a bit that lets us know that we are currently parsing this
6343                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6344 
6345                     lldb::user_id_t encoding_uid = DW_INVALID_OFFSET;
6346 
6347                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6348                     if (num_attributes > 0)
6349                     {
6350                         uint32_t i;
6351 
6352                         for (i=0; i<num_attributes; ++i)
6353                         {
6354                             attr = attributes.AttributeAtIndex(i);
6355                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6356                             {
6357                                 switch (attr)
6358                                 {
6359                                 case DW_AT_decl_file:       decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6360                                 case DW_AT_decl_line:       decl.SetLine(form_value.Unsigned()); break;
6361                                 case DW_AT_decl_column:     decl.SetColumn(form_value.Unsigned()); break;
6362                                 case DW_AT_name:
6363                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6364                                     type_name_const_str.SetCString(type_name_cstr);
6365                                     break;
6366                                 case DW_AT_type:            encoding_uid = form_value.Reference(dwarf_cu); break;
6367                                 case DW_AT_byte_size:       byte_size = form_value.Unsigned(); break;
6368                                 case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6369                                 case DW_AT_declaration:     break; //is_forward_declaration = form_value.Boolean(); break;
6370                                 case DW_AT_allocated:
6371                                 case DW_AT_associated:
6372                                 case DW_AT_bit_stride:
6373                                 case DW_AT_byte_stride:
6374                                 case DW_AT_data_location:
6375                                 case DW_AT_description:
6376                                 case DW_AT_start_scope:
6377                                 case DW_AT_visibility:
6378                                 case DW_AT_specification:
6379                                 case DW_AT_abstract_origin:
6380                                 case DW_AT_sibling:
6381                                     break;
6382                                 }
6383                             }
6384                         }
6385 
6386                         DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6387 
6388                         ClangASTType enumerator_clang_type;
6389                         clang_type.SetClangType (ast.getASTContext(), m_forward_decl_die_to_clang_type.lookup (die));
6390                         if (!clang_type)
6391                         {
6392                             if (encoding_uid != DW_INVALID_OFFSET)
6393                             {
6394                                 Type *enumerator_type = ResolveTypeUID(encoding_uid);
6395                                 if (enumerator_type)
6396                                     enumerator_clang_type = enumerator_type->GetClangFullType();
6397                             }
6398 
6399                             if (!enumerator_clang_type)
6400                                 enumerator_clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (NULL,
6401                                                                                                       DW_ATE_signed,
6402                                                                                                       byte_size * 8);
6403 
6404                             clang_type = ast.CreateEnumerationType (type_name_cstr,
6405                                                                     GetClangDeclContextContainingDIE (dwarf_cu, die, NULL),
6406                                                                     decl,
6407                                                                     enumerator_clang_type);
6408                         }
6409                         else
6410                         {
6411                             enumerator_clang_type = clang_type.GetEnumerationIntegerType ();
6412                         }
6413 
6414                         LinkDeclContextToDIE(clang_type.GetDeclContextForType(), die);
6415 
6416                         type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6417                                                  this,
6418                                                  type_name_const_str,
6419                                                  byte_size,
6420                                                  NULL,
6421                                                  encoding_uid,
6422                                                  Type::eEncodingIsUID,
6423                                                  &decl,
6424                                                  clang_type,
6425                                                  Type::eResolveStateForward));
6426 
6427                         clang_type.StartTagDeclarationDefinition ();
6428                         if (die->HasChildren())
6429                         {
6430                             SymbolContext cu_sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
6431                             bool is_signed = false;
6432                             enumerator_clang_type.IsIntegerType(is_signed);
6433                             ParseChildEnumerators(cu_sc, clang_type, is_signed, type_sp->GetByteSize(), dwarf_cu, die);
6434                         }
6435                         clang_type.CompleteTagDeclarationDefinition ();
6436                     }
6437                 }
6438                 break;
6439 
6440             case DW_TAG_inlined_subroutine:
6441             case DW_TAG_subprogram:
6442             case DW_TAG_subroutine_type:
6443                 {
6444                     // Set a bit that lets us know that we are currently parsing this
6445                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6446 
6447                     //const char *mangled = NULL;
6448                     dw_offset_t type_die_offset = DW_INVALID_OFFSET;
6449                     bool is_variadic = false;
6450                     bool is_inline = false;
6451                     bool is_static = false;
6452                     bool is_virtual = false;
6453                     bool is_explicit = false;
6454                     bool is_artificial = false;
6455                     dw_offset_t specification_die_offset = DW_INVALID_OFFSET;
6456                     dw_offset_t abstract_origin_die_offset = DW_INVALID_OFFSET;
6457                     dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET;
6458 
6459                     unsigned type_quals = 0;
6460                     clang::StorageClass storage = clang::SC_None;//, Extern, Static, PrivateExtern
6461 
6462 
6463                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6464                     if (num_attributes > 0)
6465                     {
6466                         uint32_t i;
6467                         for (i=0; i<num_attributes; ++i)
6468                         {
6469                             attr = attributes.AttributeAtIndex(i);
6470                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6471                             {
6472                                 switch (attr)
6473                                 {
6474                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6475                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6476                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6477                                 case DW_AT_name:
6478                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6479                                     type_name_const_str.SetCString(type_name_cstr);
6480                                     break;
6481 
6482                                 case DW_AT_linkage_name:
6483                                 case DW_AT_MIPS_linkage_name:   break; // mangled = form_value.AsCString(&get_debug_str_data()); break;
6484                                 case DW_AT_type:                type_die_offset = form_value.Reference(dwarf_cu); break;
6485                                 case DW_AT_accessibility:       accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6486                                 case DW_AT_declaration:         break; // is_forward_declaration = form_value.Boolean(); break;
6487                                 case DW_AT_inline:              is_inline = form_value.Boolean(); break;
6488                                 case DW_AT_virtuality:          is_virtual = form_value.Boolean();  break;
6489                                 case DW_AT_explicit:            is_explicit = form_value.Boolean();  break;
6490                                 case DW_AT_artificial:          is_artificial = form_value.Boolean();  break;
6491 
6492 
6493                                 case DW_AT_external:
6494                                     if (form_value.Unsigned())
6495                                     {
6496                                         if (storage == clang::SC_None)
6497                                             storage = clang::SC_Extern;
6498                                         else
6499                                             storage = clang::SC_PrivateExtern;
6500                                     }
6501                                     break;
6502 
6503                                 case DW_AT_specification:
6504                                     specification_die_offset = form_value.Reference(dwarf_cu);
6505                                     break;
6506 
6507                                 case DW_AT_abstract_origin:
6508                                     abstract_origin_die_offset = form_value.Reference(dwarf_cu);
6509                                     break;
6510 
6511                                 case DW_AT_object_pointer:
6512                                     object_pointer_die_offset = form_value.Reference(dwarf_cu);
6513                                     break;
6514 
6515                                 case DW_AT_allocated:
6516                                 case DW_AT_associated:
6517                                 case DW_AT_address_class:
6518                                 case DW_AT_calling_convention:
6519                                 case DW_AT_data_location:
6520                                 case DW_AT_elemental:
6521                                 case DW_AT_entry_pc:
6522                                 case DW_AT_frame_base:
6523                                 case DW_AT_high_pc:
6524                                 case DW_AT_low_pc:
6525                                 case DW_AT_prototyped:
6526                                 case DW_AT_pure:
6527                                 case DW_AT_ranges:
6528                                 case DW_AT_recursive:
6529                                 case DW_AT_return_addr:
6530                                 case DW_AT_segment:
6531                                 case DW_AT_start_scope:
6532                                 case DW_AT_static_link:
6533                                 case DW_AT_trampoline:
6534                                 case DW_AT_visibility:
6535                                 case DW_AT_vtable_elem_location:
6536                                 case DW_AT_description:
6537                                 case DW_AT_sibling:
6538                                     break;
6539                                 }
6540                             }
6541                         }
6542                     }
6543 
6544                     std::string object_pointer_name;
6545                     if (object_pointer_die_offset != DW_INVALID_OFFSET)
6546                     {
6547                         // Get the name from the object pointer die
6548                         StreamString s;
6549                         if (DWARFDebugInfoEntry::GetName (this, dwarf_cu, object_pointer_die_offset, s))
6550                         {
6551                             object_pointer_name.assign(s.GetData());
6552                         }
6553                     }
6554 
6555                     DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6556 
6557                     ClangASTType return_clang_type;
6558                     Type *func_type = NULL;
6559 
6560                     if (type_die_offset != DW_INVALID_OFFSET)
6561                         func_type = ResolveTypeUID(type_die_offset);
6562 
6563                     if (func_type)
6564                         return_clang_type = func_type->GetClangForwardType();
6565                     else
6566                         return_clang_type = ast.GetBasicType(eBasicTypeVoid);
6567 
6568 
6569                     std::vector<ClangASTType> function_param_types;
6570                     std::vector<clang::ParmVarDecl*> function_param_decls;
6571 
6572                     // Parse the function children for the parameters
6573 
6574                     const DWARFDebugInfoEntry *decl_ctx_die = NULL;
6575                     clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
6576                     const clang::Decl::Kind containing_decl_kind = containing_decl_ctx->getDeclKind();
6577 
6578                     const bool is_cxx_method = DeclKindIsCXXClass (containing_decl_kind);
6579                     // Start off static. This will be set to false in ParseChildParameters(...)
6580                     // if we find a "this" paramters as the first parameter
6581                     if (is_cxx_method)
6582                         is_static = true;
6583 
6584                     if (die->HasChildren())
6585                     {
6586                         bool skip_artificial = true;
6587                         ParseChildParameters (sc,
6588                                               containing_decl_ctx,
6589                                               dwarf_cu,
6590                                               die,
6591                                               skip_artificial,
6592                                               is_static,
6593                                               is_variadic,
6594                                               type_list,
6595                                               function_param_types,
6596                                               function_param_decls,
6597                                               type_quals);
6598                     }
6599 
6600                     // clang_type will get the function prototype clang type after this call
6601                     clang_type = ast.CreateFunctionType (return_clang_type,
6602                                                          function_param_types.data(),
6603                                                          function_param_types.size(),
6604                                                          is_variadic,
6605                                                          type_quals);
6606 
6607                     bool ignore_containing_context = false;
6608 
6609                     if (type_name_cstr)
6610                     {
6611                         bool type_handled = false;
6612                         if (tag == DW_TAG_subprogram)
6613                         {
6614                             ObjCLanguageRuntime::MethodName objc_method (type_name_cstr, true);
6615                             if (objc_method.IsValid(true))
6616                             {
6617                                 ClangASTType class_opaque_type;
6618                                 ConstString class_name(objc_method.GetClassName());
6619                                 if (class_name)
6620                                 {
6621                                     TypeSP complete_objc_class_type_sp (FindCompleteObjCDefinitionTypeForDIE (NULL, class_name, false));
6622 
6623                                     if (complete_objc_class_type_sp)
6624                                     {
6625                                         ClangASTType type_clang_forward_type = complete_objc_class_type_sp->GetClangForwardType();
6626                                         if (type_clang_forward_type.IsObjCObjectOrInterfaceType ())
6627                                             class_opaque_type = type_clang_forward_type;
6628                                     }
6629                                 }
6630 
6631                                 if (class_opaque_type)
6632                                 {
6633                                     // If accessibility isn't set to anything valid, assume public for
6634                                     // now...
6635                                     if (accessibility == eAccessNone)
6636                                         accessibility = eAccessPublic;
6637 
6638                                     clang::ObjCMethodDecl *objc_method_decl = class_opaque_type.AddMethodToObjCObjectType (type_name_cstr,
6639                                                                                                                            clang_type,
6640                                                                                                                            accessibility,
6641                                                                                                                            is_artificial);
6642                                     type_handled = objc_method_decl != NULL;
6643                                     if (type_handled)
6644                                     {
6645                                         LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(objc_method_decl), die);
6646                                         GetClangASTContext().SetMetadataAsUserID (objc_method_decl, MakeUserID(die->GetOffset()));
6647                                     }
6648                                     else
6649                                     {
6650                                         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",
6651                                                                                    die->GetOffset(),
6652                                                                                    tag,
6653                                                                                    DW_TAG_value_to_name(tag));
6654                                     }
6655                                 }
6656                             }
6657                             else if (is_cxx_method)
6658                             {
6659                                 // Look at the parent of this DIE and see if is is
6660                                 // a class or struct and see if this is actually a
6661                                 // C++ method
6662                                 Type *class_type = ResolveType (dwarf_cu, decl_ctx_die);
6663                                 if (class_type)
6664                                 {
6665                                     if (class_type->GetID() != MakeUserID(decl_ctx_die->GetOffset()))
6666                                     {
6667                                         // We uniqued the parent class of this function to another class
6668                                         // so we now need to associate all dies under "decl_ctx_die" to
6669                                         // DIEs in the DIE for "class_type"...
6670                                         SymbolFileDWARF *class_symfile = NULL;
6671                                         DWARFCompileUnitSP class_type_cu_sp;
6672                                         const DWARFDebugInfoEntry *class_type_die = NULL;
6673 
6674                                         SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
6675                                         if (debug_map_symfile)
6676                                         {
6677                                             class_symfile = debug_map_symfile->GetSymbolFileByOSOIndex(SymbolFileDWARFDebugMap::GetOSOIndexFromUserID(class_type->GetID()));
6678                                             class_type_die = class_symfile->DebugInfo()->GetDIEPtr(class_type->GetID(), &class_type_cu_sp);
6679                                         }
6680                                         else
6681                                         {
6682                                             class_symfile = this;
6683                                             class_type_die = DebugInfo()->GetDIEPtr(class_type->GetID(), &class_type_cu_sp);
6684                                         }
6685                                         if (class_type_die)
6686                                         {
6687                                             DWARFDIECollection failures;
6688 
6689                                             CopyUniqueClassMethodTypes (class_symfile,
6690                                                                         class_type,
6691                                                                         class_type_cu_sp.get(),
6692                                                                         class_type_die,
6693                                                                         dwarf_cu,
6694                                                                         decl_ctx_die,
6695                                                                         failures);
6696 
6697                                             // FIXME do something with these failures that's smarter than
6698                                             // just dropping them on the ground.  Unfortunately classes don't
6699                                             // like having stuff added to them after their definitions are
6700                                             // complete...
6701 
6702                                             type_ptr = m_die_to_type[die];
6703                                             if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6704                                             {
6705                                                 type_sp = type_ptr->shared_from_this();
6706                                                 break;
6707                                             }
6708                                         }
6709                                     }
6710 
6711                                     if (specification_die_offset != DW_INVALID_OFFSET)
6712                                     {
6713                                         // We have a specification which we are going to base our function
6714                                         // prototype off of, so we need this type to be completed so that the
6715                                         // m_die_to_decl_ctx for the method in the specification has a valid
6716                                         // clang decl context.
6717                                         class_type->GetClangForwardType();
6718                                         // If we have a specification, then the function type should have been
6719                                         // made with the specification and not with this die.
6720                                         DWARFCompileUnitSP spec_cu_sp;
6721                                         const DWARFDebugInfoEntry* spec_die = DebugInfo()->GetDIEPtr(specification_die_offset, &spec_cu_sp);
6722                                         clang::DeclContext *spec_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, spec_die);
6723                                         if (spec_clang_decl_ctx)
6724                                         {
6725                                             LinkDeclContextToDIE(spec_clang_decl_ctx, die);
6726                                         }
6727                                         else
6728                                         {
6729                                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8x) has no decl\n",
6730                                                                                          MakeUserID(die->GetOffset()),
6731                                                                                          specification_die_offset);
6732                                         }
6733                                         type_handled = true;
6734                                     }
6735                                     else if (abstract_origin_die_offset != DW_INVALID_OFFSET)
6736                                     {
6737                                         // We have a specification which we are going to base our function
6738                                         // prototype off of, so we need this type to be completed so that the
6739                                         // m_die_to_decl_ctx for the method in the abstract origin has a valid
6740                                         // clang decl context.
6741                                         class_type->GetClangForwardType();
6742 
6743                                         DWARFCompileUnitSP abs_cu_sp;
6744                                         const DWARFDebugInfoEntry* abs_die = DebugInfo()->GetDIEPtr(abstract_origin_die_offset, &abs_cu_sp);
6745                                         clang::DeclContext *abs_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, abs_die);
6746                                         if (abs_clang_decl_ctx)
6747                                         {
6748                                             LinkDeclContextToDIE (abs_clang_decl_ctx, die);
6749                                         }
6750                                         else
6751                                         {
6752                                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8x) has no decl\n",
6753                                                                                          MakeUserID(die->GetOffset()),
6754                                                                                          abstract_origin_die_offset);
6755                                         }
6756                                         type_handled = true;
6757                                     }
6758                                     else
6759                                     {
6760                                         ClangASTType class_opaque_type = class_type->GetClangForwardType();
6761                                         if (class_opaque_type.IsCXXClassType ())
6762                                         {
6763                                             if (class_opaque_type.IsBeingDefined ())
6764                                             {
6765                                                 // Neither GCC 4.2 nor clang++ currently set a valid accessibility
6766                                                 // in the DWARF for C++ methods... Default to public for now...
6767                                                 if (accessibility == eAccessNone)
6768                                                     accessibility = eAccessPublic;
6769 
6770                                                 if (!is_static && !die->HasChildren())
6771                                                 {
6772                                                     // We have a C++ member function with no children (this pointer!)
6773                                                     // and clang will get mad if we try and make a function that isn't
6774                                                     // well formed in the DWARF, so we will just skip it...
6775                                                     type_handled = true;
6776                                                 }
6777                                                 else
6778                                                 {
6779                                                     clang::CXXMethodDecl *cxx_method_decl;
6780                                                     // REMOVE THE CRASH DESCRIPTION BELOW
6781                                                     Host::SetCrashDescriptionWithFormat ("SymbolFileDWARF::ParseType() is adding a method %s to class %s in DIE 0x%8.8" PRIx64 " from %s",
6782                                                                                          type_name_cstr,
6783                                                                                          class_type->GetName().GetCString(),
6784                                                                                          MakeUserID(die->GetOffset()),
6785                                                                                          m_obj_file->GetFileSpec().GetPath().c_str());
6786 
6787                                                     const bool is_attr_used = false;
6788 
6789                                                     cxx_method_decl = class_opaque_type.AddMethodToCXXRecordType (type_name_cstr,
6790                                                                                                                   clang_type,
6791                                                                                                                   accessibility,
6792                                                                                                                   is_virtual,
6793                                                                                                                   is_static,
6794                                                                                                                   is_inline,
6795                                                                                                                   is_explicit,
6796                                                                                                                   is_attr_used,
6797                                                                                                                   is_artificial);
6798 
6799                                                     type_handled = cxx_method_decl != NULL;
6800 
6801                                                     if (type_handled)
6802                                                     {
6803                                                         LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(cxx_method_decl), die);
6804 
6805                                                         Host::SetCrashDescription (NULL);
6806 
6807 
6808                                                         ClangASTMetadata metadata;
6809                                                         metadata.SetUserID(MakeUserID(die->GetOffset()));
6810 
6811                                                         if (!object_pointer_name.empty())
6812                                                         {
6813                                                             metadata.SetObjectPtrName(object_pointer_name.c_str());
6814                                                             if (log)
6815                                                                 log->Printf ("Setting object pointer name: %s on method object %p.\n",
6816                                                                              object_pointer_name.c_str(),
6817                                                                              static_cast<void*>(cxx_method_decl));
6818                                                         }
6819                                                         GetClangASTContext().SetMetadata (cxx_method_decl, metadata);
6820                                                     }
6821                                                     else
6822                                                     {
6823                                                         ignore_containing_context = true;
6824                                                     }
6825                                                 }
6826                                             }
6827                                             else
6828                                             {
6829                                                 // We were asked to parse the type for a method in a class, yet the
6830                                                 // class hasn't been asked to complete itself through the
6831                                                 // clang::ExternalASTSource protocol, so we need to just have the
6832                                                 // class complete itself and do things the right way, then our
6833                                                 // DIE should then have an entry in the m_die_to_type map. First
6834                                                 // we need to modify the m_die_to_type so it doesn't think we are
6835                                                 // trying to parse this DIE anymore...
6836                                                 m_die_to_type[die] = NULL;
6837 
6838                                                 // Now we get the full type to force our class type to complete itself
6839                                                 // using the clang::ExternalASTSource protocol which will parse all
6840                                                 // base classes and all methods (including the method for this DIE).
6841                                                 class_type->GetClangFullType();
6842 
6843                                                 // The type for this DIE should have been filled in the function call above
6844                                                 type_ptr = m_die_to_type[die];
6845                                                 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6846                                                 {
6847                                                     type_sp = type_ptr->shared_from_this();
6848                                                     break;
6849                                                 }
6850 
6851                                                 // FIXME This is fixing some even uglier behavior but we really need to
6852                                                 // uniq the methods of each class as well as the class itself.
6853                                                 // <rdar://problem/11240464>
6854                                                 type_handled = true;
6855                                             }
6856                                         }
6857                                     }
6858                                 }
6859                             }
6860                         }
6861 
6862                         if (!type_handled)
6863                         {
6864                             // We just have a function that isn't part of a class
6865                             clang::FunctionDecl *function_decl = ast.CreateFunctionDeclaration (ignore_containing_context ? GetClangASTContext().GetTranslationUnitDecl() : containing_decl_ctx,
6866                                                                                                 type_name_cstr,
6867                                                                                                 clang_type,
6868                                                                                                 storage,
6869                                                                                                 is_inline);
6870 
6871 //                            if (template_param_infos.GetSize() > 0)
6872 //                            {
6873 //                                clang::FunctionTemplateDecl *func_template_decl = ast.CreateFunctionTemplateDecl (containing_decl_ctx,
6874 //                                                                                                                  function_decl,
6875 //                                                                                                                  type_name_cstr,
6876 //                                                                                                                  template_param_infos);
6877 //
6878 //                                ast.CreateFunctionTemplateSpecializationInfo (function_decl,
6879 //                                                                              func_template_decl,
6880 //                                                                              template_param_infos);
6881 //                            }
6882                             // Add the decl to our DIE to decl context map
6883                             assert (function_decl);
6884                             LinkDeclContextToDIE(function_decl, die);
6885                             if (!function_param_decls.empty())
6886                                 ast.SetFunctionParameters (function_decl,
6887                                                            &function_param_decls.front(),
6888                                                            function_param_decls.size());
6889 
6890                             ClangASTMetadata metadata;
6891                             metadata.SetUserID(MakeUserID(die->GetOffset()));
6892 
6893                             if (!object_pointer_name.empty())
6894                             {
6895                                 metadata.SetObjectPtrName(object_pointer_name.c_str());
6896                                 if (log)
6897                                     log->Printf ("Setting object pointer name: %s on function object %p.",
6898                                                  object_pointer_name.c_str(),
6899                                                  static_cast<void*>(function_decl));
6900                             }
6901                             GetClangASTContext().SetMetadata (function_decl, metadata);
6902                         }
6903                     }
6904                     type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6905                                              this,
6906                                              type_name_const_str,
6907                                              0,
6908                                              NULL,
6909                                              LLDB_INVALID_UID,
6910                                              Type::eEncodingIsUID,
6911                                              &decl,
6912                                              clang_type,
6913                                              Type::eResolveStateFull));
6914                     assert(type_sp.get());
6915                 }
6916                 break;
6917 
6918             case DW_TAG_array_type:
6919                 {
6920                     // Set a bit that lets us know that we are currently parsing this
6921                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6922 
6923                     lldb::user_id_t type_die_offset = DW_INVALID_OFFSET;
6924                     int64_t first_index = 0;
6925                     uint32_t byte_stride = 0;
6926                     uint32_t bit_stride = 0;
6927                     bool is_vector = false;
6928                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6929 
6930                     if (num_attributes > 0)
6931                     {
6932                         uint32_t i;
6933                         for (i=0; i<num_attributes; ++i)
6934                         {
6935                             attr = attributes.AttributeAtIndex(i);
6936                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6937                             {
6938                                 switch (attr)
6939                                 {
6940                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6941                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6942                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6943                                 case DW_AT_name:
6944                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6945                                     type_name_const_str.SetCString(type_name_cstr);
6946                                     break;
6947 
6948                                 case DW_AT_type:            type_die_offset = form_value.Reference(dwarf_cu); break;
6949                                 case DW_AT_byte_size:       break; // byte_size = form_value.Unsigned(); break;
6950                                 case DW_AT_byte_stride:     byte_stride = form_value.Unsigned(); break;
6951                                 case DW_AT_bit_stride:      bit_stride = form_value.Unsigned(); break;
6952                                 case DW_AT_GNU_vector:      is_vector = form_value.Boolean(); break;
6953                                 case DW_AT_accessibility:   break; // accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6954                                 case DW_AT_declaration:     break; // is_forward_declaration = form_value.Boolean(); break;
6955                                 case DW_AT_allocated:
6956                                 case DW_AT_associated:
6957                                 case DW_AT_data_location:
6958                                 case DW_AT_description:
6959                                 case DW_AT_ordering:
6960                                 case DW_AT_start_scope:
6961                                 case DW_AT_visibility:
6962                                 case DW_AT_specification:
6963                                 case DW_AT_abstract_origin:
6964                                 case DW_AT_sibling:
6965                                     break;
6966                                 }
6967                             }
6968                         }
6969 
6970                         DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6971 
6972                         Type *element_type = ResolveTypeUID(type_die_offset);
6973 
6974                         if (element_type)
6975                         {
6976                             std::vector<uint64_t> element_orders;
6977                             ParseChildArrayInfo(sc, dwarf_cu, die, first_index, element_orders, byte_stride, bit_stride);
6978                             if (byte_stride == 0 && bit_stride == 0)
6979                                 byte_stride = element_type->GetByteSize();
6980                             ClangASTType array_element_type = element_type->GetClangForwardType();
6981                             uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
6982                             uint64_t num_elements = 0;
6983                             std::vector<uint64_t>::const_reverse_iterator pos;
6984                             std::vector<uint64_t>::const_reverse_iterator end = element_orders.rend();
6985                             for (pos = element_orders.rbegin(); pos != end; ++pos)
6986                             {
6987                                 num_elements = *pos;
6988                                 clang_type = ast.CreateArrayType (array_element_type,
6989                                                                   num_elements,
6990                                                                   is_vector);
6991                                 array_element_type = clang_type;
6992                                 array_element_bit_stride = num_elements ? array_element_bit_stride * num_elements : array_element_bit_stride;
6993                             }
6994                             ConstString empty_name;
6995                             type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6996                                                      this,
6997                                                      empty_name,
6998                                                      array_element_bit_stride / 8,
6999                                                      NULL,
7000                                                      type_die_offset,
7001                                                      Type::eEncodingIsUID,
7002                                                      &decl,
7003                                                      clang_type,
7004                                                      Type::eResolveStateFull));
7005                             type_sp->SetEncodingType (element_type);
7006                         }
7007                     }
7008                 }
7009                 break;
7010 
7011             case DW_TAG_ptr_to_member_type:
7012                 {
7013                     dw_offset_t type_die_offset = DW_INVALID_OFFSET;
7014                     dw_offset_t containing_type_die_offset = DW_INVALID_OFFSET;
7015 
7016                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
7017 
7018                     if (num_attributes > 0) {
7019                         uint32_t i;
7020                         for (i=0; i<num_attributes; ++i)
7021                         {
7022                             attr = attributes.AttributeAtIndex(i);
7023                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
7024                             {
7025                                 switch (attr)
7026                                 {
7027                                     case DW_AT_type:
7028                                         type_die_offset = form_value.Reference(dwarf_cu); break;
7029                                     case DW_AT_containing_type:
7030                                         containing_type_die_offset = form_value.Reference(dwarf_cu); break;
7031                                 }
7032                             }
7033                         }
7034 
7035                         Type *pointee_type = ResolveTypeUID(type_die_offset);
7036                         Type *class_type = ResolveTypeUID(containing_type_die_offset);
7037 
7038                         ClangASTType pointee_clang_type = pointee_type->GetClangForwardType();
7039                         ClangASTType class_clang_type = class_type->GetClangLayoutType();
7040 
7041                         clang_type = pointee_clang_type.CreateMemberPointerType(class_clang_type);
7042 
7043                         byte_size = clang_type.GetByteSize();
7044 
7045                         type_sp.reset( new Type (MakeUserID(die->GetOffset()),
7046                                                  this,
7047                                                  type_name_const_str,
7048                                                  byte_size,
7049                                                  NULL,
7050                                                  LLDB_INVALID_UID,
7051                                                  Type::eEncodingIsUID,
7052                                                  NULL,
7053                                                  clang_type,
7054                                                  Type::eResolveStateForward));
7055                     }
7056 
7057                     break;
7058                 }
7059             default:
7060                 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",
7061                                                            die->GetOffset(),
7062                                                            tag,
7063                                                            DW_TAG_value_to_name(tag));
7064                 break;
7065             }
7066 
7067             if (type_sp.get())
7068             {
7069                 const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
7070                 dw_tag_t sc_parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7071 
7072                 SymbolContextScope * symbol_context_scope = NULL;
7073                 if (sc_parent_tag == DW_TAG_compile_unit)
7074                 {
7075                     symbol_context_scope = sc.comp_unit;
7076                 }
7077                 else if (sc.function != NULL)
7078                 {
7079                     symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7080                     if (symbol_context_scope == NULL)
7081                         symbol_context_scope = sc.function;
7082                 }
7083 
7084                 if (symbol_context_scope != NULL)
7085                 {
7086                     type_sp->SetSymbolContextScope(symbol_context_scope);
7087                 }
7088 
7089                 // We are ready to put this type into the uniqued list up at the module level
7090                 type_list->Insert (type_sp);
7091 
7092                 m_die_to_type[die] = type_sp.get();
7093             }
7094         }
7095         else if (type_ptr != DIE_IS_BEING_PARSED)
7096         {
7097             type_sp = type_ptr->shared_from_this();
7098         }
7099     }
7100     return type_sp;
7101 }
7102 
7103 size_t
7104 SymbolFileDWARF::ParseTypes
7105 (
7106     const SymbolContext& sc,
7107     DWARFCompileUnit* dwarf_cu,
7108     const DWARFDebugInfoEntry *die,
7109     bool parse_siblings,
7110     bool parse_children
7111 )
7112 {
7113     size_t types_added = 0;
7114     while (die != NULL)
7115     {
7116         bool type_is_new = false;
7117         if (ParseType(sc, dwarf_cu, die, &type_is_new).get())
7118         {
7119             if (type_is_new)
7120                 ++types_added;
7121         }
7122 
7123         if (parse_children && die->HasChildren())
7124         {
7125             if (die->Tag() == DW_TAG_subprogram)
7126             {
7127                 SymbolContext child_sc(sc);
7128                 child_sc.function = sc.comp_unit->FindFunctionByUID(MakeUserID(die->GetOffset())).get();
7129                 types_added += ParseTypes(child_sc, dwarf_cu, die->GetFirstChild(), true, true);
7130             }
7131             else
7132                 types_added += ParseTypes(sc, dwarf_cu, die->GetFirstChild(), true, true);
7133         }
7134 
7135         if (parse_siblings)
7136             die = die->GetSibling();
7137         else
7138             die = NULL;
7139     }
7140     return types_added;
7141 }
7142 
7143 
7144 size_t
7145 SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext &sc)
7146 {
7147     assert(sc.comp_unit && sc.function);
7148     size_t functions_added = 0;
7149     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
7150     if (dwarf_cu)
7151     {
7152         dw_offset_t function_die_offset = sc.function->GetID();
7153         const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(function_die_offset);
7154         if (function_die)
7155         {
7156             ParseFunctionBlocks(sc, &sc.function->GetBlock (false), dwarf_cu, function_die, LLDB_INVALID_ADDRESS, 0);
7157         }
7158     }
7159 
7160     return functions_added;
7161 }
7162 
7163 
7164 size_t
7165 SymbolFileDWARF::ParseTypes (const SymbolContext &sc)
7166 {
7167     // At least a compile unit must be valid
7168     assert(sc.comp_unit);
7169     size_t types_added = 0;
7170     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
7171     if (dwarf_cu)
7172     {
7173         if (sc.function)
7174         {
7175             dw_offset_t function_die_offset = sc.function->GetID();
7176             const DWARFDebugInfoEntry *func_die = dwarf_cu->GetDIEPtr(function_die_offset);
7177             if (func_die && func_die->HasChildren())
7178             {
7179                 types_added = ParseTypes(sc, dwarf_cu, func_die->GetFirstChild(), true, true);
7180             }
7181         }
7182         else
7183         {
7184             const DWARFDebugInfoEntry *dwarf_cu_die = dwarf_cu->DIE();
7185             if (dwarf_cu_die && dwarf_cu_die->HasChildren())
7186             {
7187                 types_added = ParseTypes(sc, dwarf_cu, dwarf_cu_die->GetFirstChild(), true, true);
7188             }
7189         }
7190     }
7191 
7192     return types_added;
7193 }
7194 
7195 size_t
7196 SymbolFileDWARF::ParseVariablesForContext (const SymbolContext& sc)
7197 {
7198     if (sc.comp_unit != NULL)
7199     {
7200         DWARFDebugInfo* info = DebugInfo();
7201         if (info == NULL)
7202             return 0;
7203 
7204         if (sc.function)
7205         {
7206             DWARFCompileUnit* dwarf_cu = info->GetCompileUnitContainingDIE(sc.function->GetID()).get();
7207 
7208             if (dwarf_cu == NULL)
7209                 return 0;
7210 
7211             const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(sc.function->GetID());
7212 
7213             dw_addr_t func_lo_pc = function_die->GetAttributeValueAsUnsigned (this, dwarf_cu, DW_AT_low_pc, LLDB_INVALID_ADDRESS);
7214             if (func_lo_pc != LLDB_INVALID_ADDRESS)
7215             {
7216                 const size_t num_variables = ParseVariables(sc, dwarf_cu, func_lo_pc, function_die->GetFirstChild(), true, true);
7217 
7218                 // Let all blocks know they have parse all their variables
7219                 sc.function->GetBlock (false).SetDidParseVariables (true, true);
7220                 return num_variables;
7221             }
7222         }
7223         else if (sc.comp_unit)
7224         {
7225             DWARFCompileUnit* dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID()).get();
7226 
7227             if (dwarf_cu == NULL)
7228                 return 0;
7229 
7230             uint32_t vars_added = 0;
7231             VariableListSP variables (sc.comp_unit->GetVariableList(false));
7232 
7233             if (variables.get() == NULL)
7234             {
7235                 variables.reset(new VariableList());
7236                 sc.comp_unit->SetVariableList(variables);
7237 
7238                 DWARFCompileUnit* match_dwarf_cu = NULL;
7239                 const DWARFDebugInfoEntry* die = NULL;
7240                 DIEArray die_offsets;
7241                 if (m_using_apple_tables)
7242                 {
7243                     if (m_apple_names_ap.get())
7244                     {
7245                         DWARFMappedHash::DIEInfoArray hash_data_array;
7246                         if (m_apple_names_ap->AppendAllDIEsInRange (dwarf_cu->GetOffset(),
7247                                                                     dwarf_cu->GetNextCompileUnitOffset(),
7248                                                                     hash_data_array))
7249                         {
7250                             DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
7251                         }
7252                     }
7253                 }
7254                 else
7255                 {
7256                     // Index if we already haven't to make sure the compile units
7257                     // get indexed and make their global DIE index list
7258                     if (!m_indexed)
7259                         Index ();
7260 
7261                     m_global_index.FindAllEntriesForCompileUnit (dwarf_cu->GetOffset(),
7262                                                                  dwarf_cu->GetNextCompileUnitOffset(),
7263                                                                  die_offsets);
7264                 }
7265 
7266                 const size_t num_matches = die_offsets.size();
7267                 if (num_matches)
7268                 {
7269                     DWARFDebugInfo* debug_info = DebugInfo();
7270                     for (size_t i=0; i<num_matches; ++i)
7271                     {
7272                         const dw_offset_t die_offset = die_offsets[i];
7273                         die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &match_dwarf_cu);
7274                         if (die)
7275                         {
7276                             VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, LLDB_INVALID_ADDRESS));
7277                             if (var_sp)
7278                             {
7279                                 variables->AddVariableIfUnique (var_sp);
7280                                 ++vars_added;
7281                             }
7282                         }
7283                         else
7284                         {
7285                             if (m_using_apple_tables)
7286                             {
7287                                 GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x)\n", die_offset);
7288                             }
7289                         }
7290 
7291                     }
7292                 }
7293             }
7294             return vars_added;
7295         }
7296     }
7297     return 0;
7298 }
7299 
7300 
7301 VariableSP
7302 SymbolFileDWARF::ParseVariableDIE
7303 (
7304     const SymbolContext& sc,
7305     DWARFCompileUnit* dwarf_cu,
7306     const DWARFDebugInfoEntry *die,
7307     const lldb::addr_t func_low_pc
7308 )
7309 {
7310 
7311     VariableSP var_sp (m_die_to_variable_sp[die]);
7312     if (var_sp)
7313         return var_sp;  // Already been parsed!
7314 
7315     const dw_tag_t tag = die->Tag();
7316     ModuleSP module = GetObjectFile()->GetModule();
7317 
7318     if ((tag == DW_TAG_variable) ||
7319         (tag == DW_TAG_constant) ||
7320         (tag == DW_TAG_formal_parameter && sc.function))
7321     {
7322         DWARFDebugInfoEntry::Attributes attributes;
7323         const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
7324         if (num_attributes > 0)
7325         {
7326             const char *name = NULL;
7327             const char *mangled = NULL;
7328             Declaration decl;
7329             uint32_t i;
7330             lldb::user_id_t type_uid = LLDB_INVALID_UID;
7331             DWARFExpression location;
7332             bool is_external = false;
7333             bool is_artificial = false;
7334             bool location_is_const_value_data = false;
7335             bool has_explicit_location = false;
7336             //AccessType accessibility = eAccessNone;
7337 
7338             for (i=0; i<num_attributes; ++i)
7339             {
7340                 dw_attr_t attr = attributes.AttributeAtIndex(i);
7341                 DWARFFormValue form_value;
7342                 if (attributes.ExtractFormValueAtIndex(this, i, form_value))
7343                 {
7344                     switch (attr)
7345                     {
7346                     case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
7347                     case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
7348                     case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
7349                     case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
7350                     case DW_AT_linkage_name:
7351                     case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(&get_debug_str_data()); break;
7352                     case DW_AT_type:        type_uid = form_value.Reference(dwarf_cu); break;
7353                     case DW_AT_external:    is_external = form_value.Boolean(); break;
7354                     case DW_AT_const_value:
7355                         // If we have already found a DW_AT_location attribute, ignore this attribute.
7356                         if (!has_explicit_location)
7357                         {
7358                             location_is_const_value_data = true;
7359                             // The constant value will be either a block, a data value or a string.
7360                             const DWARFDataExtractor& debug_info_data = get_debug_info_data();
7361                             if (DWARFFormValue::IsBlockForm(form_value.Form()))
7362                             {
7363                                 // Retrieve the value as a block expression.
7364                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
7365                                 uint32_t block_length = form_value.Unsigned();
7366                                 location.CopyOpcodeData(module, debug_info_data, block_offset, block_length);
7367                             }
7368                             else if (DWARFFormValue::IsDataForm(form_value.Form()))
7369                             {
7370                                 // Retrieve the value as a data expression.
7371                                 const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
7372                                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
7373                                 uint32_t data_length = fixed_form_sizes[form_value.Form()];
7374                                 location.CopyOpcodeData(module, debug_info_data, data_offset, data_length);
7375                             }
7376                             else
7377                             {
7378                                 // Retrieve the value as a string expression.
7379                                 if (form_value.Form() == DW_FORM_strp)
7380                                 {
7381                                     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
7382                                     uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
7383                                     uint32_t data_length = fixed_form_sizes[form_value.Form()];
7384                                     location.CopyOpcodeData(module, debug_info_data, data_offset, data_length);
7385                                 }
7386                                 else
7387                                 {
7388                                     const char *str = form_value.AsCString(&debug_info_data);
7389                                     uint32_t string_offset = str - (const char *)debug_info_data.GetDataStart();
7390                                     uint32_t string_length = strlen(str) + 1;
7391                                     location.CopyOpcodeData(module, debug_info_data, string_offset, string_length);
7392                                 }
7393                             }
7394                         }
7395                         break;
7396                     case DW_AT_location:
7397                         {
7398                             location_is_const_value_data = false;
7399                             has_explicit_location = true;
7400                             if (form_value.BlockData())
7401                             {
7402                                 const DWARFDataExtractor& debug_info_data = get_debug_info_data();
7403 
7404                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
7405                                 uint32_t block_length = form_value.Unsigned();
7406                                 location.CopyOpcodeData(module, get_debug_info_data(), block_offset, block_length);
7407                             }
7408                             else
7409                             {
7410                                 const DWARFDataExtractor&    debug_loc_data = get_debug_loc_data();
7411                                 const dw_offset_t debug_loc_offset = form_value.Unsigned();
7412 
7413                                 size_t loc_list_length = DWARFLocationList::Size(debug_loc_data, debug_loc_offset);
7414                                 if (loc_list_length > 0)
7415                                 {
7416                                     location.CopyOpcodeData(module, debug_loc_data, debug_loc_offset, loc_list_length);
7417                                     assert (func_low_pc != LLDB_INVALID_ADDRESS);
7418                                     location.SetLocationListSlide (func_low_pc - dwarf_cu->GetBaseAddress());
7419                                 }
7420                             }
7421                         }
7422                         break;
7423 
7424                     case DW_AT_artificial:      is_artificial = form_value.Boolean(); break;
7425                     case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
7426                     case DW_AT_declaration:
7427                     case DW_AT_description:
7428                     case DW_AT_endianity:
7429                     case DW_AT_segment:
7430                     case DW_AT_start_scope:
7431                     case DW_AT_visibility:
7432                     default:
7433                     case DW_AT_abstract_origin:
7434                     case DW_AT_sibling:
7435                     case DW_AT_specification:
7436                         break;
7437                     }
7438                 }
7439             }
7440 
7441             ValueType scope = eValueTypeInvalid;
7442 
7443             const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
7444             dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7445             SymbolContextScope * symbol_context_scope = NULL;
7446 
7447             // DWARF doesn't specify if a DW_TAG_variable is a local, global
7448             // or static variable, so we have to do a little digging by
7449             // looking at the location of a varaible to see if it contains
7450             // a DW_OP_addr opcode _somewhere_ in the definition. I say
7451             // somewhere because clang likes to combine small global variables
7452             // into the same symbol and have locations like:
7453             // DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
7454             // So if we don't have a DW_TAG_formal_parameter, we can look at
7455             // the location to see if it contains a DW_OP_addr opcode, and
7456             // then we can correctly classify  our variables.
7457             if (tag == DW_TAG_formal_parameter)
7458                 scope = eValueTypeVariableArgument;
7459             else
7460             {
7461                 bool op_error = false;
7462                 // Check if the location has a DW_OP_addr with any address value...
7463                 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
7464                 if (!location_is_const_value_data)
7465                 {
7466                     location_DW_OP_addr = location.GetLocation_DW_OP_addr (0, op_error);
7467                     if (op_error)
7468                     {
7469                         StreamString strm;
7470                         location.DumpLocationForAddress (&strm, eDescriptionLevelFull, 0, 0, NULL);
7471                         GetObjectFile()->GetModule()->ReportError ("0x%8.8x: %s has an invalid location: %s", die->GetOffset(), DW_TAG_value_to_name(die->Tag()), strm.GetString().c_str());
7472                     }
7473                 }
7474 
7475                 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
7476                 {
7477                     if (is_external)
7478                         scope = eValueTypeVariableGlobal;
7479                     else
7480                         scope = eValueTypeVariableStatic;
7481 
7482 
7483                     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile ();
7484 
7485                     if (debug_map_symfile)
7486                     {
7487                         // When leaving the DWARF in the .o files on darwin,
7488                         // when we have a global variable that wasn't initialized,
7489                         // the .o file might not have allocated a virtual
7490                         // address for the global variable. In this case it will
7491                         // have created a symbol for the global variable
7492                         // that is undefined/data and external and the value will
7493                         // be the byte size of the variable. When we do the
7494                         // address map in SymbolFileDWARFDebugMap we rely on
7495                         // having an address, we need to do some magic here
7496                         // so we can get the correct address for our global
7497                         // variable. The address for all of these entries
7498                         // will be zero, and there will be an undefined symbol
7499                         // in this object file, and the executable will have
7500                         // a matching symbol with a good address. So here we
7501                         // dig up the correct address and replace it in the
7502                         // location for the variable, and set the variable's
7503                         // symbol context scope to be that of the main executable
7504                         // so the file address will resolve correctly.
7505                         bool linked_oso_file_addr = false;
7506                         if (is_external && location_DW_OP_addr == 0)
7507                         {
7508                             // we have a possible uninitialized extern global
7509                             ConstString const_name(mangled ? mangled : name);
7510                             ObjectFile *debug_map_objfile = debug_map_symfile->GetObjectFile();
7511                             if (debug_map_objfile)
7512                             {
7513                                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
7514                                 if (debug_map_symtab)
7515                                 {
7516                                     Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType (const_name,
7517                                                                                                            eSymbolTypeData,
7518                                                                                                            Symtab::eDebugYes,
7519                                                                                                            Symtab::eVisibilityExtern);
7520                                     if (exe_symbol)
7521                                     {
7522                                         if (exe_symbol->ValueIsAddress())
7523                                         {
7524                                             const addr_t exe_file_addr = exe_symbol->GetAddress().GetFileAddress();
7525                                             if (exe_file_addr != LLDB_INVALID_ADDRESS)
7526                                             {
7527                                                 if (location.Update_DW_OP_addr (exe_file_addr))
7528                                                 {
7529                                                     linked_oso_file_addr = true;
7530                                                     symbol_context_scope = exe_symbol;
7531                                                 }
7532                                             }
7533                                         }
7534                                     }
7535                                 }
7536                             }
7537                         }
7538 
7539                         if (!linked_oso_file_addr)
7540                         {
7541                             // The DW_OP_addr is not zero, but it contains a .o file address which
7542                             // needs to be linked up correctly.
7543                             const lldb::addr_t exe_file_addr = debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr);
7544                             if (exe_file_addr != LLDB_INVALID_ADDRESS)
7545                             {
7546                                 // Update the file address for this variable
7547                                 location.Update_DW_OP_addr (exe_file_addr);
7548                             }
7549                             else
7550                             {
7551                                 // Variable didn't make it into the final executable
7552                                 return var_sp;
7553                             }
7554                         }
7555                     }
7556                 }
7557                 else
7558                 {
7559                     scope = eValueTypeVariableLocal;
7560                 }
7561             }
7562 
7563             if (symbol_context_scope == NULL)
7564             {
7565                 switch (parent_tag)
7566                 {
7567                 case DW_TAG_subprogram:
7568                 case DW_TAG_inlined_subroutine:
7569                 case DW_TAG_lexical_block:
7570                     if (sc.function)
7571                     {
7572                         symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7573                         if (symbol_context_scope == NULL)
7574                             symbol_context_scope = sc.function;
7575                     }
7576                     break;
7577 
7578                 default:
7579                     symbol_context_scope = sc.comp_unit;
7580                     break;
7581                 }
7582             }
7583 
7584             if (symbol_context_scope)
7585             {
7586                 var_sp.reset (new Variable (MakeUserID(die->GetOffset()),
7587                                             name,
7588                                             mangled,
7589                                             SymbolFileTypeSP (new SymbolFileType(*this, type_uid)),
7590                                             scope,
7591                                             symbol_context_scope,
7592                                             &decl,
7593                                             location,
7594                                             is_external,
7595                                             is_artificial));
7596 
7597                 var_sp->SetLocationIsConstantValueData (location_is_const_value_data);
7598             }
7599             else
7600             {
7601                 // Not ready to parse this variable yet. It might be a global
7602                 // or static variable that is in a function scope and the function
7603                 // in the symbol context wasn't filled in yet
7604                 return var_sp;
7605             }
7606         }
7607         // Cache var_sp even if NULL (the variable was just a specification or
7608         // was missing vital information to be able to be displayed in the debugger
7609         // (missing location due to optimization, etc)) so we don't re-parse
7610         // this DIE over and over later...
7611         m_die_to_variable_sp[die] = var_sp;
7612     }
7613     return var_sp;
7614 }
7615 
7616 
7617 const DWARFDebugInfoEntry *
7618 SymbolFileDWARF::FindBlockContainingSpecification (dw_offset_t func_die_offset,
7619                                                    dw_offset_t spec_block_die_offset,
7620                                                    DWARFCompileUnit **result_die_cu_handle)
7621 {
7622     // Give the concrete function die specified by "func_die_offset", find the
7623     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7624     // to "spec_block_die_offset"
7625     DWARFDebugInfo* info = DebugInfo();
7626 
7627     const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint(func_die_offset, result_die_cu_handle);
7628     if (die)
7629     {
7630         assert (*result_die_cu_handle);
7631         return FindBlockContainingSpecification (*result_die_cu_handle, die, spec_block_die_offset, result_die_cu_handle);
7632     }
7633     return NULL;
7634 }
7635 
7636 
7637 const DWARFDebugInfoEntry *
7638 SymbolFileDWARF::FindBlockContainingSpecification(DWARFCompileUnit* dwarf_cu,
7639                                                   const DWARFDebugInfoEntry *die,
7640                                                   dw_offset_t spec_block_die_offset,
7641                                                   DWARFCompileUnit **result_die_cu_handle)
7642 {
7643     if (die)
7644     {
7645         switch (die->Tag())
7646         {
7647         case DW_TAG_subprogram:
7648         case DW_TAG_inlined_subroutine:
7649         case DW_TAG_lexical_block:
7650             {
7651                 if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
7652                 {
7653                     *result_die_cu_handle = dwarf_cu;
7654                     return die;
7655                 }
7656 
7657                 if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_abstract_origin, DW_INVALID_OFFSET) == spec_block_die_offset)
7658                 {
7659                     *result_die_cu_handle = dwarf_cu;
7660                     return die;
7661                 }
7662             }
7663             break;
7664         }
7665 
7666         // Give the concrete function die specified by "func_die_offset", find the
7667         // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7668         // to "spec_block_die_offset"
7669         for (const DWARFDebugInfoEntry *child_die = die->GetFirstChild(); child_die != NULL; child_die = child_die->GetSibling())
7670         {
7671             const DWARFDebugInfoEntry *result_die = FindBlockContainingSpecification (dwarf_cu,
7672                                                                                       child_die,
7673                                                                                       spec_block_die_offset,
7674                                                                                       result_die_cu_handle);
7675             if (result_die)
7676                 return result_die;
7677         }
7678     }
7679 
7680     *result_die_cu_handle = NULL;
7681     return NULL;
7682 }
7683 
7684 size_t
7685 SymbolFileDWARF::ParseVariables
7686 (
7687     const SymbolContext& sc,
7688     DWARFCompileUnit* dwarf_cu,
7689     const lldb::addr_t func_low_pc,
7690     const DWARFDebugInfoEntry *orig_die,
7691     bool parse_siblings,
7692     bool parse_children,
7693     VariableList* cc_variable_list
7694 )
7695 {
7696     if (orig_die == NULL)
7697         return 0;
7698 
7699     VariableListSP variable_list_sp;
7700 
7701     size_t vars_added = 0;
7702     const DWARFDebugInfoEntry *die = orig_die;
7703     while (die != NULL)
7704     {
7705         dw_tag_t tag = die->Tag();
7706 
7707         // Check to see if we have already parsed this variable or constant?
7708         if (m_die_to_variable_sp[die])
7709         {
7710             if (cc_variable_list)
7711                 cc_variable_list->AddVariableIfUnique (m_die_to_variable_sp[die]);
7712         }
7713         else
7714         {
7715             // We haven't already parsed it, lets do that now.
7716             if ((tag == DW_TAG_variable) ||
7717                 (tag == DW_TAG_constant) ||
7718                 (tag == DW_TAG_formal_parameter && sc.function))
7719             {
7720                 if (variable_list_sp.get() == NULL)
7721                 {
7722                     const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(orig_die);
7723                     dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7724                     switch (parent_tag)
7725                     {
7726                         case DW_TAG_compile_unit:
7727                             if (sc.comp_unit != NULL)
7728                             {
7729                                 variable_list_sp = sc.comp_unit->GetVariableList(false);
7730                                 if (variable_list_sp.get() == NULL)
7731                                 {
7732                                     variable_list_sp.reset(new VariableList());
7733                                     sc.comp_unit->SetVariableList(variable_list_sp);
7734                                 }
7735                             }
7736                             else
7737                             {
7738                                 GetObjectFile()->GetModule()->ReportError ("parent 0x%8.8" PRIx64 " %s with no valid compile unit in symbol context for 0x%8.8" PRIx64 " %s.\n",
7739                                                                            MakeUserID(sc_parent_die->GetOffset()),
7740                                                                            DW_TAG_value_to_name (parent_tag),
7741                                                                            MakeUserID(orig_die->GetOffset()),
7742                                                                            DW_TAG_value_to_name (orig_die->Tag()));
7743                             }
7744                             break;
7745 
7746                         case DW_TAG_subprogram:
7747                         case DW_TAG_inlined_subroutine:
7748                         case DW_TAG_lexical_block:
7749                             if (sc.function != NULL)
7750                             {
7751                                 // Check to see if we already have parsed the variables for the given scope
7752 
7753                                 Block *block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7754                                 if (block == NULL)
7755                                 {
7756                                     // This must be a specification or abstract origin with
7757                                     // a concrete block couterpart in the current function. We need
7758                                     // to find the concrete block so we can correctly add the
7759                                     // variable to it
7760                                     DWARFCompileUnit *concrete_block_die_cu = dwarf_cu;
7761                                     const DWARFDebugInfoEntry *concrete_block_die = FindBlockContainingSpecification (sc.function->GetID(),
7762                                                                                                                       sc_parent_die->GetOffset(),
7763                                                                                                                       &concrete_block_die_cu);
7764                                     if (concrete_block_die)
7765                                         block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(concrete_block_die->GetOffset()));
7766                                 }
7767 
7768                                 if (block != NULL)
7769                                 {
7770                                     const bool can_create = false;
7771                                     variable_list_sp = block->GetBlockVariableList (can_create);
7772                                     if (variable_list_sp.get() == NULL)
7773                                     {
7774                                         variable_list_sp.reset(new VariableList());
7775                                         block->SetVariableList(variable_list_sp);
7776                                     }
7777                                 }
7778                             }
7779                             break;
7780 
7781                         default:
7782                              GetObjectFile()->GetModule()->ReportError ("didn't find appropriate parent DIE for variable list for 0x%8.8" PRIx64 " %s.\n",
7783                                                                         MakeUserID(orig_die->GetOffset()),
7784                                                                         DW_TAG_value_to_name (orig_die->Tag()));
7785                             break;
7786                     }
7787                 }
7788 
7789                 if (variable_list_sp)
7790                 {
7791                     VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, func_low_pc));
7792                     if (var_sp)
7793                     {
7794                         variable_list_sp->AddVariableIfUnique (var_sp);
7795                         if (cc_variable_list)
7796                             cc_variable_list->AddVariableIfUnique (var_sp);
7797                         ++vars_added;
7798                     }
7799                 }
7800             }
7801         }
7802 
7803         bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
7804 
7805         if (!skip_children && parse_children && die->HasChildren())
7806         {
7807             vars_added += ParseVariables(sc, dwarf_cu, func_low_pc, die->GetFirstChild(), true, true, cc_variable_list);
7808         }
7809 
7810         if (parse_siblings)
7811             die = die->GetSibling();
7812         else
7813             die = NULL;
7814     }
7815     return vars_added;
7816 }
7817 
7818 //------------------------------------------------------------------
7819 // PluginInterface protocol
7820 //------------------------------------------------------------------
7821 ConstString
7822 SymbolFileDWARF::GetPluginName()
7823 {
7824     return GetPluginNameStatic();
7825 }
7826 
7827 uint32_t
7828 SymbolFileDWARF::GetPluginVersion()
7829 {
7830     return 1;
7831 }
7832 
7833 void
7834 SymbolFileDWARF::CompleteTagDecl (void *baton, clang::TagDecl *decl)
7835 {
7836     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7837     ClangASTType clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7838     if (clang_type)
7839         symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7840 }
7841 
7842 void
7843 SymbolFileDWARF::CompleteObjCInterfaceDecl (void *baton, clang::ObjCInterfaceDecl *decl)
7844 {
7845     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7846     ClangASTType clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7847     if (clang_type)
7848         symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7849 }
7850 
7851 void
7852 SymbolFileDWARF::DumpIndexes ()
7853 {
7854     StreamFile s(stdout, false);
7855 
7856     s.Printf ("DWARF index for (%s) '%s':",
7857               GetObjectFile()->GetModule()->GetArchitecture().GetArchitectureName(),
7858               GetObjectFile()->GetFileSpec().GetPath().c_str());
7859     s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
7860     s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
7861     s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
7862     s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
7863     s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
7864     s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
7865     s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
7866     s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
7867 }
7868 
7869 void
7870 SymbolFileDWARF::SearchDeclContext (const clang::DeclContext *decl_context,
7871                                     const char *name,
7872                                     llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7873 {
7874     DeclContextToDIEMap::iterator iter = m_decl_ctx_to_die.find(decl_context);
7875 
7876     if (iter == m_decl_ctx_to_die.end())
7877         return;
7878 
7879     for (DIEPointerSet::iterator pos = iter->second.begin(), end = iter->second.end(); pos != end; ++pos)
7880     {
7881         const DWARFDebugInfoEntry *context_die = *pos;
7882 
7883         if (!results)
7884             return;
7885 
7886         DWARFDebugInfo* info = DebugInfo();
7887 
7888         DIEArray die_offsets;
7889 
7890         DWARFCompileUnit* dwarf_cu = NULL;
7891         const DWARFDebugInfoEntry* die = NULL;
7892 
7893         if (m_using_apple_tables)
7894         {
7895             if (m_apple_types_ap.get())
7896                 m_apple_types_ap->FindByName (name, die_offsets);
7897         }
7898         else
7899         {
7900             if (!m_indexed)
7901                 Index ();
7902 
7903             m_type_index.Find (ConstString(name), die_offsets);
7904         }
7905 
7906         const size_t num_matches = die_offsets.size();
7907 
7908         if (num_matches)
7909         {
7910             for (size_t i = 0; i < num_matches; ++i)
7911             {
7912                 const dw_offset_t die_offset = die_offsets[i];
7913                 die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
7914 
7915                 if (die->GetParent() != context_die)
7916                     continue;
7917 
7918                 Type *matching_type = ResolveType (dwarf_cu, die);
7919 
7920                 clang::QualType qual_type = matching_type->GetClangForwardType().GetQualType();
7921 
7922                 if (const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr()))
7923                 {
7924                     clang::TagDecl *tag_decl = tag_type->getDecl();
7925                     results->push_back(tag_decl);
7926                 }
7927                 else if (const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(qual_type.getTypePtr()))
7928                 {
7929                     clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
7930                     results->push_back(typedef_decl);
7931                 }
7932             }
7933         }
7934     }
7935 }
7936 
7937 void
7938 SymbolFileDWARF::FindExternalVisibleDeclsByName (void *baton,
7939                                                  const clang::DeclContext *decl_context,
7940                                                  clang::DeclarationName decl_name,
7941                                                  llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7942 {
7943 
7944     switch (decl_context->getDeclKind())
7945     {
7946     case clang::Decl::Namespace:
7947     case clang::Decl::TranslationUnit:
7948         {
7949             SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7950             symbol_file_dwarf->SearchDeclContext (decl_context, decl_name.getAsString().c_str(), results);
7951         }
7952         break;
7953     default:
7954         break;
7955     }
7956 }
7957 
7958 bool
7959 SymbolFileDWARF::LayoutRecordType (void *baton,
7960                                    const clang::RecordDecl *record_decl,
7961                                    uint64_t &size,
7962                                    uint64_t &alignment,
7963                                    llvm::DenseMap <const clang::FieldDecl *, uint64_t> &field_offsets,
7964                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7965                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7966 {
7967     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7968     return symbol_file_dwarf->LayoutRecordType (record_decl, size, alignment, field_offsets, base_offsets, vbase_offsets);
7969 }
7970 
7971 
7972 bool
7973 SymbolFileDWARF::LayoutRecordType (const clang::RecordDecl *record_decl,
7974                                    uint64_t &bit_size,
7975                                    uint64_t &alignment,
7976                                    llvm::DenseMap <const clang::FieldDecl *, uint64_t> &field_offsets,
7977                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7978                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7979 {
7980     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
7981     RecordDeclToLayoutMap::iterator pos = m_record_decl_to_layout_map.find (record_decl);
7982     bool success = false;
7983     base_offsets.clear();
7984     vbase_offsets.clear();
7985     if (pos != m_record_decl_to_layout_map.end())
7986     {
7987         bit_size = pos->second.bit_size;
7988         alignment = pos->second.alignment;
7989         field_offsets.swap(pos->second.field_offsets);
7990         base_offsets.swap (pos->second.base_offsets);
7991         vbase_offsets.swap (pos->second.vbase_offsets);
7992         m_record_decl_to_layout_map.erase(pos);
7993         success = true;
7994     }
7995     else
7996     {
7997         bit_size = 0;
7998         alignment = 0;
7999         field_offsets.clear();
8000     }
8001 
8002     if (log)
8003         GetObjectFile()->GetModule()->LogMessage (log,
8004                                                   "SymbolFileDWARF::LayoutRecordType (record_decl = %p, bit_size = %" PRIu64 ", alignment = %" PRIu64 ", field_offsets[%u],base_offsets[%u], vbase_offsets[%u]) success = %i",
8005                                                   static_cast<const void*>(record_decl),
8006                                                   bit_size, alignment,
8007                                                   static_cast<uint32_t>(field_offsets.size()),
8008                                                   static_cast<uint32_t>(base_offsets.size()),
8009                                                   static_cast<uint32_t>(vbase_offsets.size()),
8010                                                   success);
8011     return success;
8012 }
8013 
8014 
8015 SymbolFileDWARFDebugMap *
8016 SymbolFileDWARF::GetDebugMapSymfile ()
8017 {
8018     if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired())
8019     {
8020         lldb::ModuleSP module_sp (m_debug_map_module_wp.lock());
8021         if (module_sp)
8022         {
8023             SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
8024             if (sym_vendor)
8025                 m_debug_map_symfile = (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
8026         }
8027     }
8028     return m_debug_map_symfile;
8029 }
8030 
8031 
8032