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