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