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       *this = rhs;
1508     }
1509 
1510     DelayedAddObjCClassProperty& operator= (const DelayedAddObjCClassProperty &rhs)
1511     {
1512         m_ast                  = rhs.m_ast;
1513         m_class_opaque_type    = rhs.m_class_opaque_type;
1514         m_property_name        = rhs.m_property_name;
1515         m_property_opaque_type = rhs.m_property_opaque_type;
1516         m_ivar_decl            = rhs.m_ivar_decl;
1517         m_property_setter_name = rhs.m_property_setter_name;
1518         m_property_getter_name = rhs.m_property_getter_name;
1519         m_property_attributes  = rhs.m_property_attributes;
1520 
1521         if (rhs.m_metadata_ap.get())
1522         {
1523             m_metadata_ap.reset (new ClangASTMetadata());
1524             *(m_metadata_ap.get()) = *(rhs.m_metadata_ap.get());
1525         }
1526         return *this;
1527     }
1528 
1529     bool Finalize() const
1530     {
1531         return ClangASTContext::AddObjCClassProperty(m_ast,
1532                                                      m_class_opaque_type,
1533                                                      m_property_name,
1534                                                      m_property_opaque_type,
1535                                                      m_ivar_decl,
1536                                                      m_property_setter_name,
1537                                                      m_property_getter_name,
1538                                                      m_property_attributes,
1539                                                      m_metadata_ap.get());
1540     }
1541 private:
1542     clang::ASTContext      *m_ast;
1543     lldb::clang_type_t      m_class_opaque_type;
1544     const char             *m_property_name;
1545     lldb::clang_type_t      m_property_opaque_type;
1546     clang::ObjCIvarDecl    *m_ivar_decl;
1547     const char             *m_property_setter_name;
1548     const char             *m_property_getter_name;
1549     uint32_t                m_property_attributes;
1550     std::auto_ptr<ClangASTMetadata>        m_metadata_ap;
1551 };
1552 
1553 size_t
1554 SymbolFileDWARF::ParseChildMembers
1555 (
1556     const SymbolContext& sc,
1557     DWARFCompileUnit* dwarf_cu,
1558     const DWARFDebugInfoEntry *parent_die,
1559     clang_type_t class_clang_type,
1560     const LanguageType class_language,
1561     std::vector<clang::CXXBaseSpecifier *>& base_classes,
1562     std::vector<int>& member_accessibilities,
1563     DWARFDIECollection& member_function_dies,
1564     BitfieldMap &bitfield_map,
1565     DelayedPropertyList& delayed_properties,
1566     AccessType& default_accessibility,
1567     bool &is_a_class,
1568     LayoutInfo &layout_info
1569 )
1570 {
1571     if (parent_die == NULL)
1572         return 0;
1573 
1574     size_t count = 0;
1575     const DWARFDebugInfoEntry *die;
1576     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
1577     uint32_t member_idx = 0;
1578 
1579     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
1580     {
1581         dw_tag_t tag = die->Tag();
1582 
1583         switch (tag)
1584         {
1585         case DW_TAG_member:
1586         case DW_TAG_APPLE_property:
1587             {
1588                 DWARFDebugInfoEntry::Attributes attributes;
1589                 const size_t num_attributes = die->GetAttributes (this,
1590                                                                   dwarf_cu,
1591                                                                   fixed_form_sizes,
1592                                                                   attributes);
1593                 if (num_attributes > 0)
1594                 {
1595                     Declaration decl;
1596                     //DWARFExpression location;
1597                     const char *name = NULL;
1598                     const char *prop_name = NULL;
1599                     const char *prop_getter_name = NULL;
1600                     const char *prop_setter_name = NULL;
1601                     uint32_t        prop_attributes = 0;
1602 
1603 
1604                     bool is_artificial = false;
1605                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
1606                     AccessType accessibility = eAccessNone;
1607                     uint32_t member_byte_offset = UINT32_MAX;
1608                     size_t byte_size = 0;
1609                     size_t bit_offset = 0;
1610                     size_t bit_size = 0;
1611                     uint32_t i;
1612                     for (i=0; i<num_attributes && !is_artificial; ++i)
1613                     {
1614                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
1615                         DWARFFormValue form_value;
1616                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1617                         {
1618                             switch (attr)
1619                             {
1620                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
1621                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
1622                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
1623                             case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
1624                             case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
1625                             case DW_AT_bit_offset:  bit_offset = form_value.Unsigned(); break;
1626                             case DW_AT_bit_size:    bit_size = form_value.Unsigned(); break;
1627                             case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
1628                             case DW_AT_data_member_location:
1629                                 if (form_value.BlockData())
1630                                 {
1631                                     Value initialValue(0);
1632                                     Value memberOffset(0);
1633                                     const DataExtractor& debug_info_data = get_debug_info_data();
1634                                     uint32_t block_length = form_value.Unsigned();
1635                                     uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
1636                                     if (DWARFExpression::Evaluate(NULL, // ExecutionContext *
1637                                                                   NULL, // clang::ASTContext *
1638                                                                   NULL, // ClangExpressionVariableList *
1639                                                                   NULL, // ClangExpressionDeclMap *
1640                                                                   NULL, // RegisterContext *
1641                                                                   debug_info_data,
1642                                                                   block_offset,
1643                                                                   block_length,
1644                                                                   eRegisterKindDWARF,
1645                                                                   &initialValue,
1646                                                                   memberOffset,
1647                                                                   NULL))
1648                                     {
1649                                         member_byte_offset = memberOffset.ResolveValue(NULL, NULL).UInt();
1650                                     }
1651                                 }
1652                                 break;
1653 
1654                             case DW_AT_accessibility: accessibility = DW_ACCESS_to_AccessType (form_value.Unsigned()); break;
1655                             case DW_AT_artificial: is_artificial = form_value.Unsigned() != 0; break;
1656                             case DW_AT_APPLE_property_name:      prop_name = form_value.AsCString(&get_debug_str_data()); break;
1657                             case DW_AT_APPLE_property_getter:    prop_getter_name = form_value.AsCString(&get_debug_str_data()); break;
1658                             case DW_AT_APPLE_property_setter:    prop_setter_name = form_value.AsCString(&get_debug_str_data()); break;
1659                             case DW_AT_APPLE_property_attribute: prop_attributes = form_value.Unsigned(); break;
1660 
1661                             default:
1662                             case DW_AT_declaration:
1663                             case DW_AT_description:
1664                             case DW_AT_mutable:
1665                             case DW_AT_visibility:
1666                             case DW_AT_sibling:
1667                                 break;
1668                             }
1669                         }
1670                     }
1671 
1672                     if (prop_name)
1673                     {
1674                         ConstString fixed_getter;
1675                         ConstString fixed_setter;
1676 
1677                         // Check if the property getter/setter were provided as full
1678                         // names.  We want basenames, so we extract them.
1679 
1680                         if (prop_getter_name && prop_getter_name[0] == '-')
1681                         {
1682                             ObjCLanguageRuntime::ParseMethodName (prop_getter_name,
1683                                                                   NULL,
1684                                                                   &fixed_getter,
1685                                                                   NULL,
1686                                                                   NULL);
1687                             prop_getter_name = fixed_getter.GetCString();
1688                         }
1689 
1690                         if (prop_setter_name && prop_setter_name[0] == '-')
1691                         {
1692                             ObjCLanguageRuntime::ParseMethodName (prop_setter_name,
1693                                                                   NULL,
1694                                                                   &fixed_setter,
1695                                                                   NULL,
1696                                                                   NULL);
1697                             prop_setter_name = fixed_setter.GetCString();
1698                         }
1699 
1700                         // If the names haven't been provided, they need to be
1701                         // filled in.
1702 
1703                         if (!prop_getter_name)
1704                         {
1705                             prop_getter_name = prop_name;
1706                         }
1707                         if (!prop_setter_name && prop_name[0] && !(prop_attributes & DW_APPLE_PROPERTY_readonly))
1708                         {
1709                             StreamString ss;
1710 
1711                             ss.Printf("set%c%s:",
1712                                       toupper(prop_name[0]),
1713                                       &prop_name[1]);
1714 
1715                             fixed_setter.SetCString(ss.GetData());
1716                             prop_setter_name = fixed_setter.GetCString();
1717                         }
1718                     }
1719 
1720                     // Clang has a DWARF generation bug where sometimes it
1721                     // represents fields that are references with bad byte size
1722                     // and bit size/offset information such as:
1723                     //
1724                     //  DW_AT_byte_size( 0x00 )
1725                     //  DW_AT_bit_size( 0x40 )
1726                     //  DW_AT_bit_offset( 0xffffffffffffffc0 )
1727                     //
1728                     // So check the bit offset to make sure it is sane, and if
1729                     // the values are not sane, remove them. If we don't do this
1730                     // then we will end up with a crash if we try to use this
1731                     // type in an expression when clang becomes unhappy with its
1732                     // recycled debug info.
1733 
1734                     if (bit_offset > 128)
1735                     {
1736                         bit_size = 0;
1737                         bit_offset = 0;
1738                     }
1739 
1740                     // FIXME: Make Clang ignore Objective-C accessibility for expressions
1741                     if (class_language == eLanguageTypeObjC ||
1742                         class_language == eLanguageTypeObjC_plus_plus)
1743                         accessibility = eAccessNone;
1744 
1745                     if (member_idx == 0 && !is_artificial && name && (strstr (name, "_vptr$") == name))
1746                     {
1747                         // Not all compilers will mark the vtable pointer
1748                         // member as artificial (llvm-gcc). We can't have
1749                         // the virtual members in our classes otherwise it
1750                         // throws off all child offsets since we end up
1751                         // having and extra pointer sized member in our
1752                         // class layouts.
1753                         is_artificial = true;
1754                     }
1755 
1756                     if (is_artificial == false)
1757                     {
1758                         Type *member_type = ResolveTypeUID(encoding_uid);
1759                         clang::FieldDecl *field_decl = NULL;
1760                         if (tag == DW_TAG_member)
1761                         {
1762                             if (member_type)
1763                             {
1764                                 if (accessibility == eAccessNone)
1765                                     accessibility = default_accessibility;
1766                                 member_accessibilities.push_back(accessibility);
1767 
1768                                 // Code to detect unnamed bitifields
1769                                 if (bit_size > 0 && member_byte_offset != UINT32_MAX)
1770                                 {
1771                                     // Objective C has invalid DW_AT_bit_offset values in older versions
1772                                     // of clang, so we have to be careful and only detect unnammed bitfields
1773                                     // if we have a new enough clang.
1774                                     bool detect_unnamed_bitfields = true;
1775 
1776                                     if (class_language == eLanguageTypeObjC || class_language == eLanguageTypeObjC_plus_plus)
1777                                         detect_unnamed_bitfields = dwarf_cu->Supports_unnamed_objc_bitfields ();
1778 
1779                                     if (detect_unnamed_bitfields)
1780                                     {
1781                                         // We have a bitfield, we need to watch out for
1782                                         // unnamed bitfields that we need to insert if
1783                                         // there is a gap in the bytes as many compilers
1784                                         // doesn't emit DWARF DW_TAG_member tags for
1785                                         // unnammed bitfields.
1786                                         BitfieldMap::iterator bit_pos = bitfield_map.find(member_byte_offset);
1787                                         uint32_t unnamed_bit_size = 0;
1788                                         uint32_t unnamed_bit_offset = 0;
1789                                         if (bit_pos == bitfield_map.end())
1790                                         {
1791                                             // First bitfield in an integral type.
1792 
1793                                             // We might need to insert a leading unnamed bitfield
1794                                             if (bit_offset < byte_size * 8)
1795                                             {
1796                                                 unnamed_bit_size = byte_size * 8 - (bit_size + bit_offset);
1797                                                 unnamed_bit_offset = byte_size * 8 - unnamed_bit_size;
1798                                             }
1799 
1800                                             // Now put the current bitfield info into the map
1801                                             bitfield_map[member_byte_offset].bit_size = bit_size;
1802                                             bitfield_map[member_byte_offset].bit_offset = bit_offset;
1803                                         }
1804                                         else
1805                                         {
1806                                             // Subsequent bitfield in an integral type.
1807 
1808                                             // We have a bitfield that isn't the first for this
1809                                             // integral type, check to make sure there aren't any
1810                                             // gaps.
1811                                             assert (bit_pos->second.bit_size > 0);
1812                                             if (bit_offset < bit_pos->second.bit_offset)
1813                                             {
1814                                                 unnamed_bit_size = bit_pos->second.bit_offset - (bit_size + bit_offset);
1815                                                 unnamed_bit_offset = bit_pos->second.bit_offset - unnamed_bit_size;
1816                                             }
1817 
1818                                             // Now put the current bitfield info into the map
1819                                             bit_pos->second.bit_size = bit_size;
1820                                             bit_pos->second.bit_offset = bit_offset;
1821                                         }
1822 
1823                                         if (unnamed_bit_size > 0)
1824                                         {
1825                                             clang::FieldDecl *unnamed_bitfield_decl = GetClangASTContext().AddFieldToRecordType (class_clang_type,
1826                                                                                                                                  NULL,
1827                                                                                                                                  member_type->GetClangLayoutType(),
1828                                                                                                                                  accessibility,
1829                                                                                                                                  unnamed_bit_size);
1830                                             uint64_t total_bit_offset = 0;
1831 
1832                                             total_bit_offset += (member_byte_offset == UINT32_MAX ? 0 : (member_byte_offset * 8));
1833 
1834                                             if (GetObjectFile()->GetByteOrder() == eByteOrderLittle)
1835                                             {
1836                                                 total_bit_offset += byte_size * 8;
1837                                                 total_bit_offset -= (unnamed_bit_offset + unnamed_bit_size);
1838                                             }
1839                                             else
1840                                             {
1841                                                 total_bit_offset += unnamed_bit_size;
1842                                             }
1843 
1844                                             layout_info.field_offsets.insert(std::make_pair(unnamed_bitfield_decl, total_bit_offset));
1845                                         }
1846                                     }
1847                                 }
1848                                 field_decl = GetClangASTContext().AddFieldToRecordType (class_clang_type,
1849                                                                                         name,
1850                                                                                         member_type->GetClangLayoutType(),
1851                                                                                         accessibility,
1852                                                                                         bit_size);
1853 
1854                                 GetClangASTContext().SetMetadataAsUserID ((uintptr_t)field_decl, MakeUserID(die->GetOffset()));
1855                             }
1856                             else
1857                             {
1858                                 if (name)
1859                                     GetObjectFile()->GetModule()->ReportError ("0x%8.8llx: DW_TAG_member '%s' refers to type 0x%8.8llx which was unable to be parsed",
1860                                                                                MakeUserID(die->GetOffset()),
1861                                                                                name,
1862                                                                                encoding_uid);
1863                                 else
1864                                     GetObjectFile()->GetModule()->ReportError ("0x%8.8llx: DW_TAG_member refers to type 0x%8.8llx which was unable to be parsed",
1865                                                                                MakeUserID(die->GetOffset()),
1866                                                                                encoding_uid);
1867                             }
1868 
1869                             if (member_byte_offset != UINT32_MAX || bit_size != 0)
1870                             {
1871                                 /////////////////////////////////////////////////////////////
1872                                 // How to locate a field given the DWARF debug information
1873                                 //
1874                                 // AT_byte_size indicates the size of the word in which the
1875                                 // bit offset must be interpreted.
1876                                 //
1877                                 // AT_data_member_location indicates the byte offset of the
1878                                 // word from the base address of the structure.
1879                                 //
1880                                 // AT_bit_offset indicates how many bits into the word
1881                                 // (according to the host endianness) the low-order bit of
1882                                 // the field starts.  AT_bit_offset can be negative.
1883                                 //
1884                                 // AT_bit_size indicates the size of the field in bits.
1885                                 /////////////////////////////////////////////////////////////
1886 
1887                                 uint64_t total_bit_offset = 0;
1888 
1889                                 total_bit_offset += (member_byte_offset == UINT32_MAX ? 0 : (member_byte_offset * 8));
1890 
1891                                 if (GetObjectFile()->GetByteOrder() == eByteOrderLittle)
1892                                 {
1893                                     total_bit_offset += byte_size * 8;
1894                                     total_bit_offset -= (bit_offset + bit_size);
1895                                 }
1896                                 else
1897                                 {
1898                                     total_bit_offset += bit_offset;
1899                                 }
1900 
1901                                 layout_info.field_offsets.insert(std::make_pair(field_decl, total_bit_offset));
1902                             }
1903                         }
1904 
1905                         if (prop_name != NULL)
1906                         {
1907                             clang::ObjCIvarDecl *ivar_decl = NULL;
1908 
1909                             if (field_decl)
1910                             {
1911                                 ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl);
1912                                 assert (ivar_decl != NULL);
1913                             }
1914 
1915                             ClangASTMetadata metadata;
1916                             metadata.SetUserID (MakeUserID(die->GetOffset()));
1917                             delayed_properties.push_back(DelayedAddObjCClassProperty(GetClangASTContext().getASTContext(),
1918                                                                                      class_clang_type,
1919                                                                                      prop_name,
1920                                                                                      member_type->GetClangLayoutType(),
1921                                                                                      ivar_decl,
1922                                                                                      prop_setter_name,
1923                                                                                      prop_getter_name,
1924                                                                                      prop_attributes,
1925                                                                                      &metadata));
1926 
1927                             if (ivar_decl)
1928                                 GetClangASTContext().SetMetadataAsUserID ((uintptr_t)ivar_decl, MakeUserID(die->GetOffset()));
1929                         }
1930                     }
1931                 }
1932                 ++member_idx;
1933             }
1934             break;
1935 
1936         case DW_TAG_subprogram:
1937             // Let the type parsing code handle this one for us.
1938             member_function_dies.Append (die);
1939             break;
1940 
1941         case DW_TAG_inheritance:
1942             {
1943                 is_a_class = true;
1944                 if (default_accessibility == eAccessNone)
1945                     default_accessibility = eAccessPrivate;
1946                 // TODO: implement DW_TAG_inheritance type parsing
1947                 DWARFDebugInfoEntry::Attributes attributes;
1948                 const size_t num_attributes = die->GetAttributes (this,
1949                                                                   dwarf_cu,
1950                                                                   fixed_form_sizes,
1951                                                                   attributes);
1952                 if (num_attributes > 0)
1953                 {
1954                     Declaration decl;
1955                     DWARFExpression location;
1956                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
1957                     AccessType accessibility = default_accessibility;
1958                     bool is_virtual = false;
1959                     bool is_base_of_class = true;
1960                     off_t member_byte_offset = 0;
1961                     uint32_t i;
1962                     for (i=0; i<num_attributes; ++i)
1963                     {
1964                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
1965                         DWARFFormValue form_value;
1966                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1967                         {
1968                             switch (attr)
1969                             {
1970                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
1971                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
1972                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
1973                             case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
1974                             case DW_AT_data_member_location:
1975                                 if (form_value.BlockData())
1976                                 {
1977                                     Value initialValue(0);
1978                                     Value memberOffset(0);
1979                                     const DataExtractor& debug_info_data = get_debug_info_data();
1980                                     uint32_t block_length = form_value.Unsigned();
1981                                     uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
1982                                     if (DWARFExpression::Evaluate (NULL,
1983                                                                    NULL,
1984                                                                    NULL,
1985                                                                    NULL,
1986                                                                    NULL,
1987                                                                    debug_info_data,
1988                                                                    block_offset,
1989                                                                    block_length,
1990                                                                    eRegisterKindDWARF,
1991                                                                    &initialValue,
1992                                                                    memberOffset,
1993                                                                    NULL))
1994                                     {
1995                                         member_byte_offset = memberOffset.ResolveValue(NULL, NULL).UInt();
1996                                     }
1997                                 }
1998                                 break;
1999 
2000                             case DW_AT_accessibility:
2001                                 accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
2002                                 break;
2003 
2004                             case DW_AT_virtuality: is_virtual = form_value.Unsigned() != 0; break;
2005                             default:
2006                             case DW_AT_sibling:
2007                                 break;
2008                             }
2009                         }
2010                     }
2011 
2012                     Type *base_class_type = ResolveTypeUID(encoding_uid);
2013                     assert(base_class_type);
2014 
2015                     clang_type_t base_class_clang_type = base_class_type->GetClangFullType();
2016                     assert (base_class_clang_type);
2017                     if (class_language == eLanguageTypeObjC)
2018                     {
2019                         GetClangASTContext().SetObjCSuperClass(class_clang_type, base_class_clang_type);
2020                     }
2021                     else
2022                     {
2023                         base_classes.push_back (GetClangASTContext().CreateBaseClassSpecifier (base_class_clang_type,
2024                                                                                                accessibility,
2025                                                                                                is_virtual,
2026                                                                                                is_base_of_class));
2027 
2028                         if (is_virtual)
2029                         {
2030                             layout_info.vbase_offsets.insert(std::make_pair(ClangASTType::GetAsCXXRecordDecl(class_clang_type),
2031                                                                             clang::CharUnits::fromQuantity(member_byte_offset)));
2032                         }
2033                         else
2034                         {
2035                             layout_info.base_offsets.insert(std::make_pair(ClangASTType::GetAsCXXRecordDecl(class_clang_type),
2036                                                                            clang::CharUnits::fromQuantity(member_byte_offset)));
2037                         }
2038                     }
2039                 }
2040             }
2041             break;
2042 
2043         default:
2044             break;
2045         }
2046     }
2047 
2048     return count;
2049 }
2050 
2051 
2052 clang::DeclContext*
2053 SymbolFileDWARF::GetClangDeclContextContainingTypeUID (lldb::user_id_t type_uid)
2054 {
2055     DWARFDebugInfo* debug_info = DebugInfo();
2056     if (debug_info && UserIDMatches(type_uid))
2057     {
2058         DWARFCompileUnitSP cu_sp;
2059         const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(type_uid, &cu_sp);
2060         if (die)
2061             return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
2062     }
2063     return NULL;
2064 }
2065 
2066 clang::DeclContext*
2067 SymbolFileDWARF::GetClangDeclContextForTypeUID (const lldb_private::SymbolContext &sc, lldb::user_id_t type_uid)
2068 {
2069     if (UserIDMatches(type_uid))
2070         return GetClangDeclContextForDIEOffset (sc, type_uid);
2071     return NULL;
2072 }
2073 
2074 Type*
2075 SymbolFileDWARF::ResolveTypeUID (lldb::user_id_t type_uid)
2076 {
2077     if (UserIDMatches(type_uid))
2078     {
2079         DWARFDebugInfo* debug_info = DebugInfo();
2080         if (debug_info)
2081         {
2082             DWARFCompileUnitSP cu_sp;
2083             const DWARFDebugInfoEntry* type_die = debug_info->GetDIEPtr(type_uid, &cu_sp);
2084             const bool assert_not_being_parsed = true;
2085             return ResolveTypeUID (cu_sp.get(), type_die, assert_not_being_parsed);
2086         }
2087     }
2088     return NULL;
2089 }
2090 
2091 Type*
2092 SymbolFileDWARF::ResolveTypeUID (DWARFCompileUnit* cu, const DWARFDebugInfoEntry* die, bool assert_not_being_parsed)
2093 {
2094     if (die != NULL)
2095     {
2096         LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
2097         if (log)
2098             GetObjectFile()->GetModule()->LogMessage (log.get(),
2099                                                       "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
2100                                                       die->GetOffset(),
2101                                                       DW_TAG_value_to_name(die->Tag()),
2102                                                       die->GetName(this, cu));
2103 
2104         // We might be coming in in the middle of a type tree (a class
2105         // withing a class, an enum within a class), so parse any needed
2106         // parent DIEs before we get to this one...
2107         const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
2108         switch (decl_ctx_die->Tag())
2109         {
2110             case DW_TAG_structure_type:
2111             case DW_TAG_union_type:
2112             case DW_TAG_class_type:
2113             {
2114                 // Get the type, which could be a forward declaration
2115                 if (log)
2116                     GetObjectFile()->GetModule()->LogMessage (log.get(),
2117                                                               "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent forward type for 0x%8.8x",
2118                                                               die->GetOffset(),
2119                                                               DW_TAG_value_to_name(die->Tag()),
2120                                                               die->GetName(this, cu),
2121                                                               decl_ctx_die->GetOffset());
2122 //
2123 //                Type *parent_type = ResolveTypeUID (cu, decl_ctx_die, assert_not_being_parsed);
2124 //                if (child_requires_parent_class_union_or_struct_to_be_completed(die->Tag()))
2125 //                {
2126 //                    if (log)
2127 //                        GetObjectFile()->GetModule()->LogMessage (log.get(),
2128 //                                                                  "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent full type for 0x%8.8x since die is a function",
2129 //                                                                  die->GetOffset(),
2130 //                                                                  DW_TAG_value_to_name(die->Tag()),
2131 //                                                                  die->GetName(this, cu),
2132 //                                                                  decl_ctx_die->GetOffset());
2133 //                    // Ask the type to complete itself if it already hasn't since if we
2134 //                    // want a function (method or static) from a class, the class must
2135 //                    // create itself and add it's own methods and class functions.
2136 //                    if (parent_type)
2137 //                        parent_type->GetClangFullType();
2138 //                }
2139             }
2140             break;
2141 
2142             default:
2143                 break;
2144         }
2145         return ResolveType (cu, die);
2146     }
2147     return NULL;
2148 }
2149 
2150 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
2151 // SymbolFileDWARF objects to detect if this DWARF file is the one that
2152 // can resolve a clang_type.
2153 bool
2154 SymbolFileDWARF::HasForwardDeclForClangType (lldb::clang_type_t clang_type)
2155 {
2156     clang_type_t clang_type_no_qualifiers = ClangASTType::RemoveFastQualifiers(clang_type);
2157     const DWARFDebugInfoEntry* die = m_forward_decl_clang_type_to_die.lookup (clang_type_no_qualifiers);
2158     return die != NULL;
2159 }
2160 
2161 
2162 lldb::clang_type_t
2163 SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (lldb::clang_type_t clang_type)
2164 {
2165     // We have a struct/union/class/enum that needs to be fully resolved.
2166     clang_type_t clang_type_no_qualifiers = ClangASTType::RemoveFastQualifiers(clang_type);
2167     const DWARFDebugInfoEntry* die = m_forward_decl_clang_type_to_die.lookup (clang_type_no_qualifiers);
2168     if (die == NULL)
2169     {
2170         // We have already resolved this type...
2171         return clang_type;
2172     }
2173     // Once we start resolving this type, remove it from the forward declaration
2174     // map in case anyone child members or other types require this type to get resolved.
2175     // The type will get resolved when all of the calls to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition
2176     // are done.
2177     m_forward_decl_clang_type_to_die.erase (clang_type_no_qualifiers);
2178 
2179 
2180     // Disable external storage for this type so we don't get anymore
2181     // clang::ExternalASTSource queries for this type.
2182     ClangASTContext::SetHasExternalStorage (clang_type, false);
2183 
2184     DWARFDebugInfo* debug_info = DebugInfo();
2185 
2186     DWARFCompileUnit *dwarf_cu = debug_info->GetCompileUnitContainingDIE (die->GetOffset()).get();
2187     Type *type = m_die_to_type.lookup (die);
2188 
2189     const dw_tag_t tag = die->Tag();
2190 
2191     LogSP log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
2192     if (log)
2193     {
2194         GetObjectFile()->GetModule()->LogMessageVerboseBacktrace (log.get(),
2195                                                                   "0x%8.8llx: %s '%s' resolving forward declaration...",
2196                                                                   MakeUserID(die->GetOffset()),
2197                                                                   DW_TAG_value_to_name(tag),
2198                                                                   type->GetName().AsCString());
2199 
2200     }
2201     assert (clang_type);
2202     DWARFDebugInfoEntry::Attributes attributes;
2203 
2204     ClangASTContext &ast = GetClangASTContext();
2205 
2206     switch (tag)
2207     {
2208     case DW_TAG_structure_type:
2209     case DW_TAG_union_type:
2210     case DW_TAG_class_type:
2211         {
2212             LayoutInfo layout_info;
2213 
2214             {
2215                 if (die->HasChildren())
2216                 {
2217 
2218                     LanguageType class_language = eLanguageTypeUnknown;
2219                     bool is_objc_class = ClangASTContext::IsObjCClassType (clang_type);
2220                     if (is_objc_class)
2221                     {
2222                         class_language = eLanguageTypeObjC;
2223                         // For objective C we don't start the definition when
2224                         // the class is created.
2225                         ast.StartTagDeclarationDefinition (clang_type);
2226                     }
2227 
2228                     int tag_decl_kind = -1;
2229                     AccessType default_accessibility = eAccessNone;
2230                     if (tag == DW_TAG_structure_type)
2231                     {
2232                         tag_decl_kind = clang::TTK_Struct;
2233                         default_accessibility = eAccessPublic;
2234                     }
2235                     else if (tag == DW_TAG_union_type)
2236                     {
2237                         tag_decl_kind = clang::TTK_Union;
2238                         default_accessibility = eAccessPublic;
2239                     }
2240                     else if (tag == DW_TAG_class_type)
2241                     {
2242                         tag_decl_kind = clang::TTK_Class;
2243                         default_accessibility = eAccessPrivate;
2244                     }
2245 
2246                     SymbolContext sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
2247                     std::vector<clang::CXXBaseSpecifier *> base_classes;
2248                     std::vector<int> member_accessibilities;
2249                     bool is_a_class = false;
2250                     // Parse members and base classes first
2251                     DWARFDIECollection member_function_dies;
2252 
2253                     DelayedPropertyList delayed_properties;
2254                     BitfieldMap bitfield_map;
2255                     ParseChildMembers (sc,
2256                                        dwarf_cu,
2257                                        die,
2258                                        clang_type,
2259                                        class_language,
2260                                        base_classes,
2261                                        member_accessibilities,
2262                                        member_function_dies,
2263                                        bitfield_map,
2264                                        delayed_properties,
2265                                        default_accessibility,
2266                                        is_a_class,
2267                                        layout_info);
2268 
2269                     // Now parse any methods if there were any...
2270                     size_t num_functions = member_function_dies.Size();
2271                     if (num_functions > 0)
2272                     {
2273                         for (size_t i=0; i<num_functions; ++i)
2274                         {
2275                             ResolveType(dwarf_cu, member_function_dies.GetDIEPtrAtIndex(i));
2276                         }
2277                     }
2278 
2279                     if (class_language == eLanguageTypeObjC)
2280                     {
2281                         std::string class_str (ClangASTType::GetTypeNameForOpaqueQualType(ast.getASTContext(), clang_type));
2282                         if (!class_str.empty())
2283                         {
2284 
2285                             DIEArray method_die_offsets;
2286                             if (m_using_apple_tables)
2287                             {
2288                                 if (m_apple_objc_ap.get())
2289                                     m_apple_objc_ap->FindByName(class_str.c_str(), method_die_offsets);
2290                             }
2291                             else
2292                             {
2293                                 if (!m_indexed)
2294                                     Index ();
2295 
2296                                 ConstString class_name (class_str.c_str());
2297                                 m_objc_class_selectors_index.Find (class_name, method_die_offsets);
2298                             }
2299 
2300                             if (!method_die_offsets.empty())
2301                             {
2302                                 DWARFDebugInfo* debug_info = DebugInfo();
2303 
2304                                 DWARFCompileUnit* method_cu = NULL;
2305                                 const size_t num_matches = method_die_offsets.size();
2306                                 for (size_t i=0; i<num_matches; ++i)
2307                                 {
2308                                     const dw_offset_t die_offset = method_die_offsets[i];
2309                                     DWARFDebugInfoEntry *method_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &method_cu);
2310 
2311                                     if (method_die)
2312                                         ResolveType (method_cu, method_die);
2313                                     else
2314                                     {
2315                                         if (m_using_apple_tables)
2316                                         {
2317                                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_objc accelerator table had bad die 0x%8.8x for '%s')\n",
2318                                                                                                        die_offset, class_str.c_str());
2319                                         }
2320                                     }
2321                                 }
2322                             }
2323 
2324                             for (DelayedPropertyList::const_iterator pi = delayed_properties.begin(), pe = delayed_properties.end();
2325                                  pi != pe;
2326                                  ++pi)
2327                                 pi->Finalize();
2328                         }
2329                     }
2330 
2331                     // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we
2332                     // need to tell the clang type it is actually a class.
2333                     if (class_language != eLanguageTypeObjC)
2334                     {
2335                         if (is_a_class && tag_decl_kind != clang::TTK_Class)
2336                             ast.SetTagTypeKind (clang_type, clang::TTK_Class);
2337                     }
2338 
2339                     // Since DW_TAG_structure_type gets used for both classes
2340                     // and structures, we may need to set any DW_TAG_member
2341                     // fields to have a "private" access if none was specified.
2342                     // When we parsed the child members we tracked that actual
2343                     // accessibility value for each DW_TAG_member in the
2344                     // "member_accessibilities" array. If the value for the
2345                     // member is zero, then it was set to the "default_accessibility"
2346                     // which for structs was "public". Below we correct this
2347                     // by setting any fields to "private" that weren't correctly
2348                     // set.
2349                     if (is_a_class && !member_accessibilities.empty())
2350                     {
2351                         // This is a class and all members that didn't have
2352                         // their access specified are private.
2353                         ast.SetDefaultAccessForRecordFields (clang_type,
2354                                                              eAccessPrivate,
2355                                                              &member_accessibilities.front(),
2356                                                              member_accessibilities.size());
2357                     }
2358 
2359                     if (!base_classes.empty())
2360                     {
2361                         ast.SetBaseClassesForClassType (clang_type,
2362                                                         &base_classes.front(),
2363                                                         base_classes.size());
2364 
2365                         // Clang will copy each CXXBaseSpecifier in "base_classes"
2366                         // so we have to free them all.
2367                         ClangASTContext::DeleteBaseClassSpecifiers (&base_classes.front(),
2368                                                                     base_classes.size());
2369                     }
2370                 }
2371             }
2372 
2373             ast.BuildIndirectFields (clang_type);
2374 
2375             ast.CompleteTagDeclarationDefinition (clang_type);
2376 
2377             if (!layout_info.field_offsets.empty() ||
2378                 !layout_info.base_offsets.empty()  ||
2379                 !layout_info.vbase_offsets.empty() )
2380             {
2381                 if (type)
2382                     layout_info.bit_size = type->GetByteSize() * 8;
2383                 if (layout_info.bit_size == 0)
2384                     layout_info.bit_size = die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_byte_size, 0) * 8;
2385 
2386                 clang::CXXRecordDecl *record_decl = ClangASTType::GetAsCXXRecordDecl(clang_type);
2387                 if (record_decl)
2388                 {
2389                     if (log)
2390                     {
2391                         GetObjectFile()->GetModule()->LogMessage (log.get(),
2392                                                                   "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])",
2393                                                                   clang_type,
2394                                                                   record_decl,
2395                                                                   layout_info.bit_size,
2396                                                                   layout_info.alignment,
2397                                                                   (uint32_t)layout_info.field_offsets.size(),
2398                                                                   (uint32_t)layout_info.base_offsets.size(),
2399                                                                   (uint32_t)layout_info.vbase_offsets.size());
2400 
2401                         uint32_t idx;
2402                         {
2403                         llvm::DenseMap <const clang::FieldDecl *, uint64_t>::const_iterator pos, end = layout_info.field_offsets.end();
2404                         for (idx = 0, pos = layout_info.field_offsets.begin(); pos != end; ++pos, ++idx)
2405                         {
2406                             GetObjectFile()->GetModule()->LogMessage (log.get(),
2407                                                                       "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) field[%u] = { bit_offset=%u, name='%s' }",
2408                                                                       clang_type,
2409                                                                       idx,
2410                                                                       (uint32_t)pos->second,
2411                                                                       pos->first->getNameAsString().c_str());
2412                         }
2413                         }
2414 
2415                         {
2416                         llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits>::const_iterator base_pos, base_end = layout_info.base_offsets.end();
2417                         for (idx = 0, base_pos = layout_info.base_offsets.begin(); base_pos != base_end; ++base_pos, ++idx)
2418                         {
2419                             GetObjectFile()->GetModule()->LogMessage (log.get(),
2420                                                                       "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) base[%u] = { byte_offset=%u, name='%s' }",
2421                                                                       clang_type,
2422                                                                       idx,
2423                                                                       (uint32_t)base_pos->second.getQuantity(),
2424                                                                       base_pos->first->getNameAsString().c_str());
2425                         }
2426                         }
2427                         {
2428                         llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits>::const_iterator vbase_pos, vbase_end = layout_info.vbase_offsets.end();
2429                         for (idx = 0, vbase_pos = layout_info.vbase_offsets.begin(); vbase_pos != vbase_end; ++vbase_pos, ++idx)
2430                         {
2431                             GetObjectFile()->GetModule()->LogMessage (log.get(),
2432                                                                       "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) vbase[%u] = { byte_offset=%u, name='%s' }",
2433                                                                       clang_type,
2434                                                                       idx,
2435                                                                       (uint32_t)vbase_pos->second.getQuantity(),
2436                                                                       vbase_pos->first->getNameAsString().c_str());
2437                         }
2438                         }
2439                     }
2440                     m_record_decl_to_layout_map.insert(std::make_pair(record_decl, layout_info));
2441                 }
2442             }
2443         }
2444 
2445         return clang_type;
2446 
2447     case DW_TAG_enumeration_type:
2448         ast.StartTagDeclarationDefinition (clang_type);
2449         if (die->HasChildren())
2450         {
2451             SymbolContext sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
2452             ParseChildEnumerators(sc, clang_type, type->GetByteSize(), dwarf_cu, die);
2453         }
2454         ast.CompleteTagDeclarationDefinition (clang_type);
2455         return clang_type;
2456 
2457     default:
2458         assert(false && "not a forward clang type decl!");
2459         break;
2460     }
2461     return NULL;
2462 }
2463 
2464 Type*
2465 SymbolFileDWARF::ResolveType (DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry* type_die, bool assert_not_being_parsed)
2466 {
2467     if (type_die != NULL)
2468     {
2469         Type *type = m_die_to_type.lookup (type_die);
2470 
2471         if (type == NULL)
2472             type = GetTypeForDIE (dwarf_cu, type_die).get();
2473 
2474         if (assert_not_being_parsed)
2475         {
2476             if (type != DIE_IS_BEING_PARSED)
2477                 return type;
2478 
2479             GetObjectFile()->GetModule()->ReportError ("Parsing a die that is being parsed die: 0x%8.8x: %s %s",
2480                                                        type_die->GetOffset(),
2481                                                        DW_TAG_value_to_name(type_die->Tag()),
2482                                                        type_die->GetName(this, dwarf_cu));
2483 
2484         }
2485         else
2486             return type;
2487     }
2488     return NULL;
2489 }
2490 
2491 CompileUnit*
2492 SymbolFileDWARF::GetCompUnitForDWARFCompUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
2493 {
2494     // Check if the symbol vendor already knows about this compile unit?
2495     if (dwarf_cu->GetUserData() == NULL)
2496     {
2497         // The symbol vendor doesn't know about this compile unit, we
2498         // need to parse and add it to the symbol vendor object.
2499         return ParseCompileUnit(dwarf_cu, cu_idx).get();
2500     }
2501     return (CompileUnit*)dwarf_cu->GetUserData();
2502 }
2503 
2504 bool
2505 SymbolFileDWARF::GetFunction (DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry* func_die, SymbolContext& sc)
2506 {
2507     sc.Clear();
2508     // Check if the symbol vendor already knows about this compile unit?
2509     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
2510 
2511     sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(func_die->GetOffset())).get();
2512     if (sc.function == NULL)
2513         sc.function = ParseCompileUnitFunction(sc, dwarf_cu, func_die);
2514 
2515     if (sc.function)
2516     {
2517         sc.module_sp = sc.function->CalculateSymbolContextModule();
2518         return true;
2519     }
2520 
2521     return false;
2522 }
2523 
2524 uint32_t
2525 SymbolFileDWARF::ResolveSymbolContext (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
2526 {
2527     Timer scoped_timer(__PRETTY_FUNCTION__,
2528                        "SymbolFileDWARF::ResolveSymbolContext (so_addr = { section = %p, offset = 0x%llx }, resolve_scope = 0x%8.8x)",
2529                        so_addr.GetSection().get(),
2530                        so_addr.GetOffset(),
2531                        resolve_scope);
2532     uint32_t resolved = 0;
2533     if (resolve_scope & (   eSymbolContextCompUnit |
2534                             eSymbolContextFunction |
2535                             eSymbolContextBlock |
2536                             eSymbolContextLineEntry))
2537     {
2538         lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
2539 
2540         DWARFDebugInfo* debug_info = DebugInfo();
2541         if (debug_info)
2542         {
2543             const dw_offset_t cu_offset = debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr);
2544             if (cu_offset != DW_INVALID_OFFSET)
2545             {
2546                 uint32_t cu_idx = DW_INVALID_INDEX;
2547                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnit(cu_offset, &cu_idx).get();
2548                 if (dwarf_cu)
2549                 {
2550                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2551                     if (sc.comp_unit)
2552                     {
2553                         resolved |= eSymbolContextCompUnit;
2554 
2555                         if (resolve_scope & eSymbolContextLineEntry)
2556                         {
2557                             LineTable *line_table = sc.comp_unit->GetLineTable();
2558                             if (line_table != NULL)
2559                             {
2560                                 if (so_addr.IsLinkedAddress())
2561                                 {
2562                                     Address linked_addr (so_addr);
2563                                     linked_addr.ResolveLinkedAddress();
2564                                     if (line_table->FindLineEntryByAddress (linked_addr, sc.line_entry))
2565                                     {
2566                                         resolved |= eSymbolContextLineEntry;
2567                                     }
2568                                 }
2569                                 else if (line_table->FindLineEntryByAddress (so_addr, sc.line_entry))
2570                                 {
2571                                     resolved |= eSymbolContextLineEntry;
2572                                 }
2573                             }
2574                         }
2575 
2576                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2577                         {
2578                             DWARFDebugInfoEntry *function_die = NULL;
2579                             DWARFDebugInfoEntry *block_die = NULL;
2580                             if (resolve_scope & eSymbolContextBlock)
2581                             {
2582                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, &block_die);
2583                             }
2584                             else
2585                             {
2586                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, NULL);
2587                             }
2588 
2589                             if (function_die != NULL)
2590                             {
2591                                 sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(function_die->GetOffset())).get();
2592                                 if (sc.function == NULL)
2593                                     sc.function = ParseCompileUnitFunction(sc, dwarf_cu, function_die);
2594                             }
2595                             else
2596                             {
2597                                 // We might have had a compile unit that had discontiguous
2598                                 // address ranges where the gaps are symbols that don't have
2599                                 // any debug info. Discontiguous compile unit address ranges
2600                                 // should only happen when there aren't other functions from
2601                                 // other compile units in these gaps. This helps keep the size
2602                                 // of the aranges down.
2603                                 sc.comp_unit = NULL;
2604                                 resolved &= ~eSymbolContextCompUnit;
2605                             }
2606 
2607                             if (sc.function != NULL)
2608                             {
2609                                 resolved |= eSymbolContextFunction;
2610 
2611                                 if (resolve_scope & eSymbolContextBlock)
2612                                 {
2613                                     Block& block = sc.function->GetBlock (true);
2614 
2615                                     if (block_die != NULL)
2616                                         sc.block = block.FindBlockByID (MakeUserID(block_die->GetOffset()));
2617                                     else
2618                                         sc.block = block.FindBlockByID (MakeUserID(function_die->GetOffset()));
2619                                     if (sc.block)
2620                                         resolved |= eSymbolContextBlock;
2621                                 }
2622                             }
2623                         }
2624                     }
2625                     else
2626                     {
2627                         GetObjectFile()->GetModule()->ReportWarning ("0x%8.8x: compile unit %u failed to create a valid lldb_private::CompileUnit class.",
2628                                                                      cu_offset,
2629                                                                      cu_idx);
2630                     }
2631                 }
2632             }
2633         }
2634     }
2635     return resolved;
2636 }
2637 
2638 
2639 
2640 uint32_t
2641 SymbolFileDWARF::ResolveSymbolContext(const FileSpec& file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
2642 {
2643     const uint32_t prev_size = sc_list.GetSize();
2644     if (resolve_scope & eSymbolContextCompUnit)
2645     {
2646         DWARFDebugInfo* debug_info = DebugInfo();
2647         if (debug_info)
2648         {
2649             uint32_t cu_idx;
2650             DWARFCompileUnit* dwarf_cu = NULL;
2651 
2652             for (cu_idx = 0; (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL; ++cu_idx)
2653             {
2654                 CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2655                 const bool full_match = file_spec.GetDirectory();
2656                 bool file_spec_matches_cu_file_spec = dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match);
2657                 if (check_inlines || file_spec_matches_cu_file_spec)
2658                 {
2659                     SymbolContext sc (m_obj_file->GetModule());
2660                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2661                     if (sc.comp_unit)
2662                     {
2663                         uint32_t file_idx = UINT32_MAX;
2664 
2665                         // If we are looking for inline functions only and we don't
2666                         // find it in the support files, we are done.
2667                         if (check_inlines)
2668                         {
2669                             file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2670                             if (file_idx == UINT32_MAX)
2671                                 continue;
2672                         }
2673 
2674                         if (line != 0)
2675                         {
2676                             LineTable *line_table = sc.comp_unit->GetLineTable();
2677 
2678                             if (line_table != NULL && line != 0)
2679                             {
2680                                 // We will have already looked up the file index if
2681                                 // we are searching for inline entries.
2682                                 if (!check_inlines)
2683                                     file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2684 
2685                                 if (file_idx != UINT32_MAX)
2686                                 {
2687                                     uint32_t found_line;
2688                                     uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex (0, file_idx, line, false, &sc.line_entry);
2689                                     found_line = sc.line_entry.line;
2690 
2691                                     while (line_idx != UINT32_MAX)
2692                                     {
2693                                         sc.function = NULL;
2694                                         sc.block = NULL;
2695                                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2696                                         {
2697                                             const lldb::addr_t file_vm_addr = sc.line_entry.range.GetBaseAddress().GetFileAddress();
2698                                             if (file_vm_addr != LLDB_INVALID_ADDRESS)
2699                                             {
2700                                                 DWARFDebugInfoEntry *function_die = NULL;
2701                                                 DWARFDebugInfoEntry *block_die = NULL;
2702                                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, resolve_scope & eSymbolContextBlock ? &block_die : NULL);
2703 
2704                                                 if (function_die != NULL)
2705                                                 {
2706                                                     sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(function_die->GetOffset())).get();
2707                                                     if (sc.function == NULL)
2708                                                         sc.function = ParseCompileUnitFunction(sc, dwarf_cu, function_die);
2709                                                 }
2710 
2711                                                 if (sc.function != NULL)
2712                                                 {
2713                                                     Block& block = sc.function->GetBlock (true);
2714 
2715                                                     if (block_die != NULL)
2716                                                         sc.block = block.FindBlockByID (MakeUserID(block_die->GetOffset()));
2717                                                     else
2718                                                         sc.block = block.FindBlockByID (MakeUserID(function_die->GetOffset()));
2719                                                 }
2720                                             }
2721                                         }
2722 
2723                                         sc_list.Append(sc);
2724                                         line_idx = line_table->FindLineEntryIndexByFileIndex (line_idx + 1, file_idx, found_line, true, &sc.line_entry);
2725                                     }
2726                                 }
2727                             }
2728                             else if (file_spec_matches_cu_file_spec && !check_inlines)
2729                             {
2730                                 // only append the context if we aren't looking for inline call sites
2731                                 // by file and line and if the file spec matches that of the compile unit
2732                                 sc_list.Append(sc);
2733                             }
2734                         }
2735                         else if (file_spec_matches_cu_file_spec && !check_inlines)
2736                         {
2737                             // only append the context if we aren't looking for inline call sites
2738                             // by file and line and if the file spec matches that of the compile unit
2739                             sc_list.Append(sc);
2740                         }
2741 
2742                         if (!check_inlines)
2743                             break;
2744                     }
2745                 }
2746             }
2747         }
2748     }
2749     return sc_list.GetSize() - prev_size;
2750 }
2751 
2752 void
2753 SymbolFileDWARF::Index ()
2754 {
2755     if (m_indexed)
2756         return;
2757     m_indexed = true;
2758     Timer scoped_timer (__PRETTY_FUNCTION__,
2759                         "SymbolFileDWARF::Index (%s)",
2760                         GetObjectFile()->GetFileSpec().GetFilename().AsCString());
2761 
2762     DWARFDebugInfo* debug_info = DebugInfo();
2763     if (debug_info)
2764     {
2765         uint32_t cu_idx = 0;
2766         const uint32_t num_compile_units = GetNumCompileUnits();
2767         for (cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
2768         {
2769             DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
2770 
2771             bool clear_dies = dwarf_cu->ExtractDIEsIfNeeded (false) > 1;
2772 
2773             dwarf_cu->Index (cu_idx,
2774                              m_function_basename_index,
2775                              m_function_fullname_index,
2776                              m_function_method_index,
2777                              m_function_selector_index,
2778                              m_objc_class_selectors_index,
2779                              m_global_index,
2780                              m_type_index,
2781                              m_namespace_index);
2782 
2783             // Keep memory down by clearing DIEs if this generate function
2784             // caused them to be parsed
2785             if (clear_dies)
2786                 dwarf_cu->ClearDIEs (true);
2787         }
2788 
2789         m_function_basename_index.Finalize();
2790         m_function_fullname_index.Finalize();
2791         m_function_method_index.Finalize();
2792         m_function_selector_index.Finalize();
2793         m_objc_class_selectors_index.Finalize();
2794         m_global_index.Finalize();
2795         m_type_index.Finalize();
2796         m_namespace_index.Finalize();
2797 
2798 #if defined (ENABLE_DEBUG_PRINTF)
2799         StreamFile s(stdout, false);
2800         s.Printf ("DWARF index for '%s/%s':",
2801                   GetObjectFile()->GetFileSpec().GetDirectory().AsCString(),
2802                   GetObjectFile()->GetFileSpec().GetFilename().AsCString());
2803         s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
2804         s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
2805         s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
2806         s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
2807         s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
2808         s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
2809         s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
2810         s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
2811 #endif
2812     }
2813 }
2814 
2815 bool
2816 SymbolFileDWARF::NamespaceDeclMatchesThisSymbolFile (const ClangNamespaceDecl *namespace_decl)
2817 {
2818     if (namespace_decl == NULL)
2819     {
2820         // Invalid namespace decl which means we aren't matching only things
2821         // in this symbol file, so return true to indicate it matches this
2822         // symbol file.
2823         return true;
2824     }
2825 
2826     clang::ASTContext *namespace_ast = namespace_decl->GetASTContext();
2827 
2828     if (namespace_ast == NULL)
2829         return true;    // No AST in the "namespace_decl", return true since it
2830                         // could then match any symbol file, including this one
2831 
2832     if (namespace_ast == GetClangASTContext().getASTContext())
2833         return true;    // The ASTs match, return true
2834 
2835     // The namespace AST was valid, and it does not match...
2836     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2837 
2838     if (log)
2839         GetObjectFile()->GetModule()->LogMessage(log.get(), "Valid namespace does not match symbol file");
2840 
2841     return false;
2842 }
2843 
2844 bool
2845 SymbolFileDWARF::DIEIsInNamespace (const ClangNamespaceDecl *namespace_decl,
2846                                    DWARFCompileUnit* cu,
2847                                    const DWARFDebugInfoEntry* die)
2848 {
2849     // No namespace specified, so the answesr i
2850     if (namespace_decl == NULL)
2851         return true;
2852 
2853     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2854 
2855     const DWARFDebugInfoEntry *decl_ctx_die = NULL;
2856     clang::DeclContext *die_clang_decl_ctx = GetClangDeclContextContainingDIE (cu, die, &decl_ctx_die);
2857     if (decl_ctx_die)
2858     {
2859         clang::NamespaceDecl *clang_namespace_decl = namespace_decl->GetNamespaceDecl();
2860 
2861         if (clang_namespace_decl)
2862         {
2863             if (decl_ctx_die->Tag() != DW_TAG_namespace)
2864             {
2865                 if (log)
2866                     GetObjectFile()->GetModule()->LogMessage(log.get(), "Found a match, but its parent is not a namespace");
2867                 return false;
2868             }
2869 
2870             if (clang_namespace_decl == die_clang_decl_ctx)
2871                 return true;
2872             else
2873                 return false;
2874         }
2875         else
2876         {
2877             // We have a namespace_decl that was not NULL but it contained
2878             // a NULL "clang::NamespaceDecl", so this means the global namespace
2879             // So as long the the contained decl context DIE isn't a namespace
2880             // we should be ok.
2881             if (decl_ctx_die->Tag() != DW_TAG_namespace)
2882                 return true;
2883         }
2884     }
2885 
2886     if (log)
2887         GetObjectFile()->GetModule()->LogMessage(log.get(), "Found a match, but its parent doesn't exist");
2888 
2889     return false;
2890 }
2891 uint32_t
2892 SymbolFileDWARF::FindGlobalVariables (const ConstString &name, const lldb_private::ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, VariableList& variables)
2893 {
2894     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2895 
2896     if (log)
2897     {
2898         GetObjectFile()->GetModule()->LogMessage (log.get(),
2899                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", namespace_decl=%p, append=%u, max_matches=%u, variables)",
2900                                                   name.GetCString(),
2901                                                   namespace_decl,
2902                                                   append,
2903                                                   max_matches);
2904     }
2905 
2906     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
2907 		return 0;
2908 
2909     DWARFDebugInfo* info = DebugInfo();
2910     if (info == NULL)
2911         return 0;
2912 
2913     // If we aren't appending the results to this list, then clear the list
2914     if (!append)
2915         variables.Clear();
2916 
2917     // Remember how many variables are in the list before we search in case
2918     // we are appending the results to a variable list.
2919     const uint32_t original_size = variables.GetSize();
2920 
2921     DIEArray die_offsets;
2922 
2923     if (m_using_apple_tables)
2924     {
2925         if (m_apple_names_ap.get())
2926         {
2927             const char *name_cstr = name.GetCString();
2928             const char *base_name_start;
2929             const char *base_name_end = NULL;
2930 
2931             if (!CPPLanguageRuntime::StripNamespacesFromVariableName(name_cstr, base_name_start, base_name_end))
2932                 base_name_start = name_cstr;
2933 
2934             m_apple_names_ap->FindByName (base_name_start, die_offsets);
2935         }
2936     }
2937     else
2938     {
2939         // Index the DWARF if we haven't already
2940         if (!m_indexed)
2941             Index ();
2942 
2943         m_global_index.Find (name, die_offsets);
2944     }
2945 
2946     const size_t num_die_matches = die_offsets.size();
2947     if (num_die_matches)
2948     {
2949         SymbolContext sc;
2950         sc.module_sp = m_obj_file->GetModule();
2951         assert (sc.module_sp);
2952 
2953         DWARFDebugInfo* debug_info = DebugInfo();
2954         DWARFCompileUnit* dwarf_cu = NULL;
2955         const DWARFDebugInfoEntry* die = NULL;
2956         bool done = false;
2957         for (size_t i=0; i<num_die_matches && !done; ++i)
2958         {
2959             const dw_offset_t die_offset = die_offsets[i];
2960             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
2961 
2962             if (die)
2963             {
2964                 switch (die->Tag())
2965                 {
2966                     default:
2967                     case DW_TAG_subprogram:
2968                     case DW_TAG_inlined_subroutine:
2969                     case DW_TAG_try_block:
2970                     case DW_TAG_catch_block:
2971                         break;
2972 
2973                     case DW_TAG_variable:
2974                         {
2975                             sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
2976 
2977                             if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
2978                                 continue;
2979 
2980                             ParseVariables(sc, dwarf_cu, LLDB_INVALID_ADDRESS, die, false, false, &variables);
2981 
2982                             if (variables.GetSize() - original_size >= max_matches)
2983                                 done = true;
2984                         }
2985                         break;
2986                 }
2987             }
2988             else
2989             {
2990                 if (m_using_apple_tables)
2991                 {
2992                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')\n",
2993                                                                                die_offset, name.GetCString());
2994                 }
2995             }
2996         }
2997     }
2998 
2999     // Return the number of variable that were appended to the list
3000     const uint32_t num_matches = variables.GetSize() - original_size;
3001     if (log && num_matches > 0)
3002     {
3003         GetObjectFile()->GetModule()->LogMessage (log.get(),
3004                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", namespace_decl=%p, append=%u, max_matches=%u, variables) => %u",
3005                                                   name.GetCString(),
3006                                                   namespace_decl,
3007                                                   append,
3008                                                   max_matches,
3009                                                   num_matches);
3010     }
3011     return num_matches;
3012 }
3013 
3014 uint32_t
3015 SymbolFileDWARF::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
3016 {
3017     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3018 
3019     if (log)
3020     {
3021         GetObjectFile()->GetModule()->LogMessage (log.get(),
3022                                                   "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", append=%u, max_matches=%u, variables)",
3023                                                   regex.GetText(),
3024                                                   append,
3025                                                   max_matches);
3026     }
3027 
3028     DWARFDebugInfo* info = DebugInfo();
3029     if (info == NULL)
3030         return 0;
3031 
3032     // If we aren't appending the results to this list, then clear the list
3033     if (!append)
3034         variables.Clear();
3035 
3036     // Remember how many variables are in the list before we search in case
3037     // we are appending the results to a variable list.
3038     const uint32_t original_size = variables.GetSize();
3039 
3040     DIEArray die_offsets;
3041 
3042     if (m_using_apple_tables)
3043     {
3044         if (m_apple_names_ap.get())
3045         {
3046             DWARFMappedHash::DIEInfoArray hash_data_array;
3047             if (m_apple_names_ap->AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
3048                 DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
3049         }
3050     }
3051     else
3052     {
3053         // Index the DWARF if we haven't already
3054         if (!m_indexed)
3055             Index ();
3056 
3057         m_global_index.Find (regex, die_offsets);
3058     }
3059 
3060     SymbolContext sc;
3061     sc.module_sp = m_obj_file->GetModule();
3062     assert (sc.module_sp);
3063 
3064     DWARFCompileUnit* dwarf_cu = NULL;
3065     const DWARFDebugInfoEntry* die = NULL;
3066     const size_t num_matches = die_offsets.size();
3067     if (num_matches)
3068     {
3069         DWARFDebugInfo* debug_info = DebugInfo();
3070         for (size_t i=0; i<num_matches; ++i)
3071         {
3072             const dw_offset_t die_offset = die_offsets[i];
3073             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3074 
3075             if (die)
3076             {
3077                 sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
3078 
3079                 ParseVariables(sc, dwarf_cu, LLDB_INVALID_ADDRESS, die, false, false, &variables);
3080 
3081                 if (variables.GetSize() - original_size >= max_matches)
3082                     break;
3083             }
3084             else
3085             {
3086                 if (m_using_apple_tables)
3087                 {
3088                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for regex '%s')\n",
3089                                                                                die_offset, regex.GetText());
3090                 }
3091             }
3092         }
3093     }
3094 
3095     // Return the number of variable that were appended to the list
3096     return variables.GetSize() - original_size;
3097 }
3098 
3099 
3100 bool
3101 SymbolFileDWARF::ResolveFunction (dw_offset_t die_offset,
3102                                   DWARFCompileUnit *&dwarf_cu,
3103                                   SymbolContextList& sc_list)
3104 {
3105     const DWARFDebugInfoEntry *die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3106     return ResolveFunction (dwarf_cu, die, sc_list);
3107 }
3108 
3109 
3110 bool
3111 SymbolFileDWARF::ResolveFunction (DWARFCompileUnit *cu,
3112                                   const DWARFDebugInfoEntry *die,
3113                                   SymbolContextList& sc_list)
3114 {
3115     SymbolContext sc;
3116 
3117     if (die == NULL)
3118         return false;
3119 
3120     // If we were passed a die that is not a function, just return false...
3121     if (die->Tag() != DW_TAG_subprogram && die->Tag() != DW_TAG_inlined_subroutine)
3122         return false;
3123 
3124     const DWARFDebugInfoEntry* inlined_die = NULL;
3125     if (die->Tag() == DW_TAG_inlined_subroutine)
3126     {
3127         inlined_die = die;
3128 
3129         while ((die = die->GetParent()) != NULL)
3130         {
3131             if (die->Tag() == DW_TAG_subprogram)
3132                 break;
3133         }
3134     }
3135     assert (die->Tag() == DW_TAG_subprogram);
3136     if (GetFunction (cu, die, sc))
3137     {
3138         Address addr;
3139         // Parse all blocks if needed
3140         if (inlined_die)
3141         {
3142             sc.block = sc.function->GetBlock (true).FindBlockByID (MakeUserID(inlined_die->GetOffset()));
3143             assert (sc.block != NULL);
3144             if (sc.block->GetStartAddress (addr) == false)
3145                 addr.Clear();
3146         }
3147         else
3148         {
3149             sc.block = NULL;
3150             addr = sc.function->GetAddressRange().GetBaseAddress();
3151         }
3152 
3153         if (addr.IsValid())
3154         {
3155             sc_list.Append(sc);
3156             return true;
3157         }
3158     }
3159 
3160     return false;
3161 }
3162 
3163 void
3164 SymbolFileDWARF::FindFunctions (const ConstString &name,
3165                                 const NameToDIE &name_to_die,
3166                                 SymbolContextList& sc_list)
3167 {
3168     DIEArray die_offsets;
3169     if (name_to_die.Find (name, die_offsets))
3170     {
3171         ParseFunctions (die_offsets, sc_list);
3172     }
3173 }
3174 
3175 
3176 void
3177 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
3178                                 const NameToDIE &name_to_die,
3179                                 SymbolContextList& sc_list)
3180 {
3181     DIEArray die_offsets;
3182     if (name_to_die.Find (regex, die_offsets))
3183     {
3184         ParseFunctions (die_offsets, sc_list);
3185     }
3186 }
3187 
3188 
3189 void
3190 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
3191                                 const DWARFMappedHash::MemoryTable &memory_table,
3192                                 SymbolContextList& sc_list)
3193 {
3194     DIEArray die_offsets;
3195     DWARFMappedHash::DIEInfoArray hash_data_array;
3196     if (memory_table.AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
3197     {
3198         DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
3199         ParseFunctions (die_offsets, sc_list);
3200     }
3201 }
3202 
3203 void
3204 SymbolFileDWARF::ParseFunctions (const DIEArray &die_offsets,
3205                                  SymbolContextList& sc_list)
3206 {
3207     const size_t num_matches = die_offsets.size();
3208     if (num_matches)
3209     {
3210         SymbolContext sc;
3211 
3212         DWARFCompileUnit* dwarf_cu = NULL;
3213         for (size_t i=0; i<num_matches; ++i)
3214         {
3215             const dw_offset_t die_offset = die_offsets[i];
3216             ResolveFunction (die_offset, dwarf_cu, sc_list);
3217         }
3218     }
3219 }
3220 
3221 bool
3222 SymbolFileDWARF::FunctionDieMatchesPartialName (const DWARFDebugInfoEntry* die,
3223                                                 const DWARFCompileUnit *dwarf_cu,
3224                                                 uint32_t name_type_mask,
3225                                                 const char *partial_name,
3226                                                 const char *base_name_start,
3227                                                 const char *base_name_end)
3228 {
3229     // If we are looking only for methods, throw away all the ones that are or aren't in C++ classes:
3230     if (name_type_mask == eFunctionNameTypeMethod || name_type_mask == eFunctionNameTypeBase)
3231     {
3232         clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIEOffset(die->GetOffset());
3233         if (!containing_decl_ctx)
3234             return false;
3235 
3236         bool is_cxx_method = DeclKindIsCXXClass(containing_decl_ctx->getDeclKind());
3237 
3238         if (name_type_mask == eFunctionNameTypeMethod)
3239         {
3240             if (is_cxx_method == false)
3241                 return false;
3242         }
3243 
3244         if (name_type_mask == eFunctionNameTypeBase)
3245         {
3246             if (is_cxx_method == true)
3247                 return false;
3248         }
3249     }
3250 
3251     // Now we need to check whether the name we got back for this type matches the extra specifications
3252     // that were in the name we're looking up:
3253     if (base_name_start != partial_name || *base_name_end != '\0')
3254     {
3255         // First see if the stuff to the left matches the full name.  To do that let's see if
3256         // we can pull out the mips linkage name attribute:
3257 
3258         Mangled best_name;
3259         DWARFDebugInfoEntry::Attributes attributes;
3260         DWARFFormValue form_value;
3261         die->GetAttributes(this, dwarf_cu, NULL, attributes);
3262         uint32_t idx = attributes.FindAttributeIndex(DW_AT_MIPS_linkage_name);
3263         if (idx != UINT32_MAX)
3264         {
3265             if (attributes.ExtractFormValueAtIndex(this, idx, form_value))
3266             {
3267                 const char *mangled_name = form_value.AsCString(&get_debug_str_data());
3268                 if (mangled_name)
3269                     best_name.SetValue (ConstString(mangled_name), true);
3270             }
3271         }
3272 
3273         if (!best_name)
3274         {
3275             idx = attributes.FindAttributeIndex(DW_AT_name);
3276             if (idx != UINT32_MAX && attributes.ExtractFormValueAtIndex(this, idx, form_value))
3277             {
3278                 const char *name = form_value.AsCString(&get_debug_str_data());
3279                 best_name.SetValue (ConstString(name), false);
3280             }
3281         }
3282 
3283         if (best_name.GetDemangledName())
3284         {
3285             const char *demangled = best_name.GetDemangledName().GetCString();
3286             if (demangled)
3287             {
3288                 std::string name_no_parens(partial_name, base_name_end - partial_name);
3289                 const char *partial_in_demangled = strstr (demangled, name_no_parens.c_str());
3290                 if (partial_in_demangled == NULL)
3291                     return false;
3292                 else
3293                 {
3294                     // Sort out the case where our name is something like "Process::Destroy" and the match is
3295                     // "SBProcess::Destroy" - that shouldn't be a match.  We should really always match on
3296                     // namespace boundaries...
3297 
3298                     if (partial_name[0] == ':'  && partial_name[1] == ':')
3299                     {
3300                         // The partial name was already on a namespace boundary so all matches are good.
3301                         return true;
3302                     }
3303                     else if (partial_in_demangled == demangled)
3304                     {
3305                         // They both start the same, so this is an good match.
3306                         return true;
3307                     }
3308                     else
3309                     {
3310                         if (partial_in_demangled - demangled == 1)
3311                         {
3312                             // Only one character difference, can't be a namespace boundary...
3313                             return false;
3314                         }
3315                         else if (*(partial_in_demangled - 1) == ':' && *(partial_in_demangled - 2) == ':')
3316                         {
3317                             // We are on a namespace boundary, so this is also good.
3318                             return true;
3319                         }
3320                         else
3321                             return false;
3322                     }
3323                 }
3324             }
3325         }
3326     }
3327 
3328     return true;
3329 }
3330 
3331 uint32_t
3332 SymbolFileDWARF::FindFunctions (const ConstString &name,
3333                                 const lldb_private::ClangNamespaceDecl *namespace_decl,
3334                                 uint32_t name_type_mask,
3335                                 bool include_inlines,
3336                                 bool append,
3337                                 SymbolContextList& sc_list)
3338 {
3339     Timer scoped_timer (__PRETTY_FUNCTION__,
3340                         "SymbolFileDWARF::FindFunctions (name = '%s')",
3341                         name.AsCString());
3342 
3343     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3344 
3345     if (log)
3346     {
3347         GetObjectFile()->GetModule()->LogMessage (log.get(),
3348                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list)",
3349                                                   name.GetCString(),
3350                                                   name_type_mask,
3351                                                   append);
3352     }
3353 
3354     // If we aren't appending the results to this list, then clear the list
3355     if (!append)
3356         sc_list.Clear();
3357 
3358     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3359 		return 0;
3360 
3361     // If name is empty then we won't find anything.
3362     if (name.IsEmpty())
3363         return 0;
3364 
3365     // Remember how many sc_list are in the list before we search in case
3366     // we are appending the results to a variable list.
3367 
3368     const uint32_t original_size = sc_list.GetSize();
3369 
3370     const char *name_cstr = name.GetCString();
3371     uint32_t effective_name_type_mask = eFunctionNameTypeNone;
3372     const char *base_name_start = name_cstr;
3373     const char *base_name_end = name_cstr + strlen(name_cstr);
3374 
3375     if (name_type_mask & eFunctionNameTypeAuto)
3376     {
3377         if (CPPLanguageRuntime::IsCPPMangledName (name_cstr))
3378             effective_name_type_mask = eFunctionNameTypeFull;
3379         else if (ObjCLanguageRuntime::IsPossibleObjCMethodName (name_cstr))
3380             effective_name_type_mask = eFunctionNameTypeFull;
3381         else
3382         {
3383             if (ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
3384                 effective_name_type_mask |= eFunctionNameTypeSelector;
3385 
3386             if (CPPLanguageRuntime::IsPossibleCPPCall(name_cstr, base_name_start, base_name_end))
3387                 effective_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase);
3388         }
3389     }
3390     else
3391     {
3392         effective_name_type_mask = name_type_mask;
3393         if (effective_name_type_mask & eFunctionNameTypeMethod || name_type_mask & eFunctionNameTypeBase)
3394         {
3395             // If they've asked for a CPP method or function name and it can't be that, we don't
3396             // even need to search for CPP methods or names.
3397             if (!CPPLanguageRuntime::IsPossibleCPPCall(name_cstr, base_name_start, base_name_end))
3398             {
3399                 effective_name_type_mask &= ~(eFunctionNameTypeMethod | eFunctionNameTypeBase);
3400                 if (effective_name_type_mask == eFunctionNameTypeNone)
3401                     return 0;
3402             }
3403         }
3404 
3405         if (effective_name_type_mask & eFunctionNameTypeSelector)
3406         {
3407             if (!ObjCLanguageRuntime::IsPossibleObjCSelector(name_cstr))
3408             {
3409                 effective_name_type_mask &= ~(eFunctionNameTypeSelector);
3410                 if (effective_name_type_mask == eFunctionNameTypeNone)
3411                     return 0;
3412             }
3413         }
3414     }
3415 
3416     DWARFDebugInfo* info = DebugInfo();
3417     if (info == NULL)
3418         return 0;
3419 
3420     DWARFCompileUnit *dwarf_cu = NULL;
3421     if (m_using_apple_tables)
3422     {
3423         if (m_apple_names_ap.get())
3424         {
3425 
3426             DIEArray die_offsets;
3427 
3428             uint32_t num_matches = 0;
3429 
3430             if (effective_name_type_mask & eFunctionNameTypeFull)
3431             {
3432                 // If they asked for the full name, match what they typed.  At some point we may
3433                 // want to canonicalize this (strip double spaces, etc.  For now, we just add all the
3434                 // dies that we find by exact match.
3435                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3436                 for (uint32_t i = 0; i < num_matches; i++)
3437                 {
3438                     const dw_offset_t die_offset = die_offsets[i];
3439                     const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3440                     if (die)
3441                     {
3442                         if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3443                             continue;
3444 
3445                         if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3446                             continue;
3447 
3448                         ResolveFunction (dwarf_cu, die, sc_list);
3449                     }
3450                     else
3451                     {
3452                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3453                                                                                    die_offset, name_cstr);
3454                     }
3455                 }
3456             }
3457             else
3458             {
3459                 if (effective_name_type_mask & eFunctionNameTypeSelector)
3460                 {
3461                     if (namespace_decl && *namespace_decl)
3462                         return 0; // no selectors in namespaces
3463 
3464                     num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3465                     // Now make sure these are actually ObjC methods.  In this case we can simply look up the name,
3466                     // and if it is an ObjC method name, we're good.
3467 
3468                     for (uint32_t i = 0; i < num_matches; i++)
3469                     {
3470                         const dw_offset_t die_offset = die_offsets[i];
3471                         const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3472                         if (die)
3473                         {
3474                             const char *die_name = die->GetName(this, dwarf_cu);
3475                             if (ObjCLanguageRuntime::IsPossibleObjCMethodName(die_name))
3476                             {
3477                                 if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3478                                     continue;
3479 
3480                                 ResolveFunction (dwarf_cu, die, sc_list);
3481                             }
3482                         }
3483                         else
3484                         {
3485                             GetObjectFile()->GetModule()->ReportError ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3486                                                                        die_offset, name_cstr);
3487                         }
3488                     }
3489                     die_offsets.clear();
3490                 }
3491 
3492                 if (effective_name_type_mask & eFunctionNameTypeMethod
3493                     || effective_name_type_mask & eFunctionNameTypeBase)
3494                 {
3495                     if ((effective_name_type_mask & eFunctionNameTypeMethod) &&
3496                         (namespace_decl && *namespace_decl))
3497                         return 0; // no methods in namespaces
3498 
3499                     // The apple_names table stores just the "base name" of C++ methods in the table.  So we have to
3500                     // extract the base name, look that up, and if there is any other information in the name we were
3501                     // passed in we have to post-filter based on that.
3502 
3503                     // FIXME: Arrange the logic above so that we don't calculate the base name twice:
3504                     std::string base_name(base_name_start, base_name_end - base_name_start);
3505                     num_matches = m_apple_names_ap->FindByName (base_name.c_str(), die_offsets);
3506 
3507                     for (uint32_t i = 0; i < num_matches; i++)
3508                     {
3509                         const dw_offset_t die_offset = die_offsets[i];
3510                         const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3511                         if (die)
3512                         {
3513                             if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3514                                 continue;
3515 
3516                             if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3517                                 continue;
3518 
3519                             if (!FunctionDieMatchesPartialName(die,
3520                                                                dwarf_cu,
3521                                                                effective_name_type_mask,
3522                                                                name_cstr,
3523                                                                base_name_start,
3524                                                                base_name_end))
3525                                 continue;
3526 
3527                             // If we get to here, the die is good, and we should add it:
3528                             ResolveFunction (dwarf_cu, die, sc_list);
3529                         }
3530                         else
3531                         {
3532                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3533                                                                                        die_offset, name_cstr);
3534                         }
3535                     }
3536                     die_offsets.clear();
3537                 }
3538             }
3539         }
3540     }
3541     else
3542     {
3543 
3544         // Index the DWARF if we haven't already
3545         if (!m_indexed)
3546             Index ();
3547 
3548         if (name_type_mask & eFunctionNameTypeFull)
3549             FindFunctions (name, m_function_fullname_index, sc_list);
3550 
3551         std::string base_name(base_name_start, base_name_end - base_name_start);
3552         ConstString base_name_const(base_name.c_str());
3553         DIEArray die_offsets;
3554         DWARFCompileUnit *dwarf_cu = NULL;
3555 
3556         if (effective_name_type_mask & eFunctionNameTypeBase)
3557         {
3558             uint32_t num_base = m_function_basename_index.Find(base_name_const, die_offsets);
3559             for (uint32_t i = 0; i < num_base; i++)
3560             {
3561                 const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3562                 if (die)
3563                 {
3564                     if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3565                         continue;
3566 
3567                     if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3568                         continue;
3569 
3570                     if (!FunctionDieMatchesPartialName(die,
3571                                                        dwarf_cu,
3572                                                        eFunctionNameTypeBase,
3573                                                        name_cstr,
3574                                                        base_name_start,
3575                                                        base_name_end))
3576                         continue;
3577 
3578                     // If we get to here, the die is good, and we should add it:
3579                     ResolveFunction (dwarf_cu, die, sc_list);
3580                 }
3581             }
3582             die_offsets.clear();
3583         }
3584 
3585         if (effective_name_type_mask & eFunctionNameTypeMethod)
3586         {
3587             if (namespace_decl && *namespace_decl)
3588                 return 0; // no methods in namespaces
3589 
3590             uint32_t num_base = m_function_method_index.Find(base_name_const, die_offsets);
3591             {
3592                 for (uint32_t i = 0; i < num_base; i++)
3593                 {
3594                     const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3595                     if (die)
3596                     {
3597                         if (!include_inlines && die->Tag() == DW_TAG_inlined_subroutine)
3598                             continue;
3599 
3600                         if (!FunctionDieMatchesPartialName(die,
3601                                                            dwarf_cu,
3602                                                            eFunctionNameTypeMethod,
3603                                                            name_cstr,
3604                                                            base_name_start,
3605                                                            base_name_end))
3606                             continue;
3607 
3608                         // If we get to here, the die is good, and we should add it:
3609                         ResolveFunction (dwarf_cu, die, sc_list);
3610                     }
3611                 }
3612             }
3613             die_offsets.clear();
3614         }
3615 
3616         if ((effective_name_type_mask & eFunctionNameTypeSelector) && (!namespace_decl || !*namespace_decl))
3617         {
3618             FindFunctions (name, m_function_selector_index, sc_list);
3619         }
3620 
3621     }
3622 
3623     // Return the number of variable that were appended to the list
3624     const uint32_t num_matches = sc_list.GetSize() - original_size;
3625 
3626     if (log && num_matches > 0)
3627     {
3628         GetObjectFile()->GetModule()->LogMessage (log.get(),
3629                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list) => %u",
3630                                                   name.GetCString(),
3631                                                   name_type_mask,
3632                                                   append,
3633                                                   num_matches);
3634     }
3635     return num_matches;
3636 }
3637 
3638 uint32_t
3639 SymbolFileDWARF::FindFunctions(const RegularExpression& regex, bool include_inlines, bool append, SymbolContextList& sc_list)
3640 {
3641     Timer scoped_timer (__PRETTY_FUNCTION__,
3642                         "SymbolFileDWARF::FindFunctions (regex = '%s')",
3643                         regex.GetText());
3644 
3645     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3646 
3647     if (log)
3648     {
3649         GetObjectFile()->GetModule()->LogMessage (log.get(),
3650                                                   "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
3651                                                   regex.GetText(),
3652                                                   append);
3653     }
3654 
3655 
3656     // If we aren't appending the results to this list, then clear the list
3657     if (!append)
3658         sc_list.Clear();
3659 
3660     // Remember how many sc_list are in the list before we search in case
3661     // we are appending the results to a variable list.
3662     uint32_t original_size = sc_list.GetSize();
3663 
3664     if (m_using_apple_tables)
3665     {
3666         if (m_apple_names_ap.get())
3667             FindFunctions (regex, *m_apple_names_ap, sc_list);
3668     }
3669     else
3670     {
3671         // Index the DWARF if we haven't already
3672         if (!m_indexed)
3673             Index ();
3674 
3675         FindFunctions (regex, m_function_basename_index, sc_list);
3676 
3677         FindFunctions (regex, m_function_fullname_index, sc_list);
3678     }
3679 
3680     // Return the number of variable that were appended to the list
3681     return sc_list.GetSize() - original_size;
3682 }
3683 
3684 uint32_t
3685 SymbolFileDWARF::FindTypes (const SymbolContext& sc,
3686                             const ConstString &name,
3687                             const lldb_private::ClangNamespaceDecl *namespace_decl,
3688                             bool append,
3689                             uint32_t max_matches,
3690                             TypeList& types)
3691 {
3692     DWARFDebugInfo* info = DebugInfo();
3693     if (info == NULL)
3694         return 0;
3695 
3696     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3697 
3698     if (log)
3699     {
3700         if (namespace_decl)
3701         {
3702             GetObjectFile()->GetModule()->LogMessage (log.get(),
3703                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list)",
3704                                                       name.GetCString(),
3705                                                       namespace_decl->GetNamespaceDecl(),
3706                                                       namespace_decl->GetQualifiedName().c_str(),
3707                                                       append,
3708                                                       max_matches);
3709         }
3710         else
3711         {
3712             GetObjectFile()->GetModule()->LogMessage (log.get(),
3713                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list)",
3714                                                       name.GetCString(),
3715                                                       append,
3716                                                       max_matches);
3717         }
3718     }
3719 
3720     // If we aren't appending the results to this list, then clear the list
3721     if (!append)
3722         types.Clear();
3723 
3724     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3725 		return 0;
3726 
3727     DIEArray die_offsets;
3728 
3729     if (m_using_apple_tables)
3730     {
3731         if (m_apple_types_ap.get())
3732         {
3733             const char *name_cstr = name.GetCString();
3734             m_apple_types_ap->FindByName (name_cstr, die_offsets);
3735         }
3736     }
3737     else
3738     {
3739         if (!m_indexed)
3740             Index ();
3741 
3742         m_type_index.Find (name, die_offsets);
3743     }
3744 
3745     const size_t num_die_matches = die_offsets.size();
3746 
3747     if (num_die_matches)
3748     {
3749         const uint32_t initial_types_size = types.GetSize();
3750         DWARFCompileUnit* dwarf_cu = NULL;
3751         const DWARFDebugInfoEntry* die = NULL;
3752         DWARFDebugInfo* debug_info = DebugInfo();
3753         for (size_t i=0; i<num_die_matches; ++i)
3754         {
3755             const dw_offset_t die_offset = die_offsets[i];
3756             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3757 
3758             if (die)
3759             {
3760                 if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3761                     continue;
3762 
3763                 Type *matching_type = ResolveType (dwarf_cu, die);
3764                 if (matching_type)
3765                 {
3766                     // We found a type pointer, now find the shared pointer form our type list
3767                     types.InsertUnique (matching_type->shared_from_this());
3768                     if (types.GetSize() >= max_matches)
3769                         break;
3770                 }
3771             }
3772             else
3773             {
3774                 if (m_using_apple_tables)
3775                 {
3776                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3777                                                                                die_offset, name.GetCString());
3778                 }
3779             }
3780 
3781         }
3782         const uint32_t num_matches = types.GetSize() - initial_types_size;
3783         if (log && num_matches)
3784         {
3785             if (namespace_decl)
3786             {
3787                 GetObjectFile()->GetModule()->LogMessage (log.get(),
3788                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list) => %u",
3789                                                           name.GetCString(),
3790                                                           namespace_decl->GetNamespaceDecl(),
3791                                                           namespace_decl->GetQualifiedName().c_str(),
3792                                                           append,
3793                                                           max_matches,
3794                                                           num_matches);
3795             }
3796             else
3797             {
3798                 GetObjectFile()->GetModule()->LogMessage (log.get(),
3799                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list) => %u",
3800                                                           name.GetCString(),
3801                                                           append,
3802                                                           max_matches,
3803                                                           num_matches);
3804             }
3805         }
3806         return num_matches;
3807     }
3808     return 0;
3809 }
3810 
3811 
3812 ClangNamespaceDecl
3813 SymbolFileDWARF::FindNamespace (const SymbolContext& sc,
3814                                 const ConstString &name,
3815                                 const lldb_private::ClangNamespaceDecl *parent_namespace_decl)
3816 {
3817     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3818 
3819     if (log)
3820     {
3821         GetObjectFile()->GetModule()->LogMessage (log.get(),
3822                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
3823                                                   name.GetCString());
3824     }
3825 
3826     if (!NamespaceDeclMatchesThisSymbolFile(parent_namespace_decl))
3827 		return ClangNamespaceDecl();
3828 
3829     ClangNamespaceDecl namespace_decl;
3830     DWARFDebugInfo* info = DebugInfo();
3831     if (info)
3832     {
3833         DIEArray die_offsets;
3834 
3835         // Index if we already haven't to make sure the compile units
3836         // get indexed and make their global DIE index list
3837         if (m_using_apple_tables)
3838         {
3839             if (m_apple_namespaces_ap.get())
3840             {
3841                 const char *name_cstr = name.GetCString();
3842                 m_apple_namespaces_ap->FindByName (name_cstr, die_offsets);
3843             }
3844         }
3845         else
3846         {
3847             if (!m_indexed)
3848                 Index ();
3849 
3850             m_namespace_index.Find (name, die_offsets);
3851         }
3852 
3853         DWARFCompileUnit* dwarf_cu = NULL;
3854         const DWARFDebugInfoEntry* die = NULL;
3855         const size_t num_matches = die_offsets.size();
3856         if (num_matches)
3857         {
3858             DWARFDebugInfo* debug_info = DebugInfo();
3859             for (size_t i=0; i<num_matches; ++i)
3860             {
3861                 const dw_offset_t die_offset = die_offsets[i];
3862                 die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3863 
3864                 if (die)
3865                 {
3866                     if (parent_namespace_decl && !DIEIsInNamespace (parent_namespace_decl, dwarf_cu, die))
3867                         continue;
3868 
3869                     clang::NamespaceDecl *clang_namespace_decl = ResolveNamespaceDIE (dwarf_cu, die);
3870                     if (clang_namespace_decl)
3871                     {
3872                         namespace_decl.SetASTContext (GetClangASTContext().getASTContext());
3873                         namespace_decl.SetNamespaceDecl (clang_namespace_decl);
3874                         break;
3875                     }
3876                 }
3877                 else
3878                 {
3879                     if (m_using_apple_tables)
3880                     {
3881                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_namespaces accelerator table had bad die 0x%8.8x for '%s')\n",
3882                                                                    die_offset, name.GetCString());
3883                     }
3884                 }
3885 
3886             }
3887         }
3888     }
3889     if (log && namespace_decl.GetNamespaceDecl())
3890     {
3891         GetObjectFile()->GetModule()->LogMessage (log.get(),
3892                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => clang::NamespaceDecl(%p) \"%s\"",
3893                                                   name.GetCString(),
3894                                                   namespace_decl.GetNamespaceDecl(),
3895                                                   namespace_decl.GetQualifiedName().c_str());
3896     }
3897 
3898     return namespace_decl;
3899 }
3900 
3901 uint32_t
3902 SymbolFileDWARF::FindTypes(std::vector<dw_offset_t> die_offsets, uint32_t max_matches, TypeList& types)
3903 {
3904     // Remember how many sc_list are in the list before we search in case
3905     // we are appending the results to a variable list.
3906     uint32_t original_size = types.GetSize();
3907 
3908     const uint32_t num_die_offsets = die_offsets.size();
3909     // Parse all of the types we found from the pubtypes matches
3910     uint32_t i;
3911     uint32_t num_matches = 0;
3912     for (i = 0; i < num_die_offsets; ++i)
3913     {
3914         Type *matching_type = ResolveTypeUID (die_offsets[i]);
3915         if (matching_type)
3916         {
3917             // We found a type pointer, now find the shared pointer form our type list
3918             types.InsertUnique (matching_type->shared_from_this());
3919             ++num_matches;
3920             if (num_matches >= max_matches)
3921                 break;
3922         }
3923     }
3924 
3925     // Return the number of variable that were appended to the list
3926     return types.GetSize() - original_size;
3927 }
3928 
3929 
3930 size_t
3931 SymbolFileDWARF::ParseChildParameters (const SymbolContext& sc,
3932                                        clang::DeclContext *containing_decl_ctx,
3933                                        DWARFCompileUnit* dwarf_cu,
3934                                        const DWARFDebugInfoEntry *parent_die,
3935                                        bool skip_artificial,
3936                                        bool &is_static,
3937                                        TypeList* type_list,
3938                                        std::vector<clang_type_t>& function_param_types,
3939                                        std::vector<clang::ParmVarDecl*>& function_param_decls,
3940                                        unsigned &type_quals,
3941                                        ClangASTContext::TemplateParameterInfos &template_param_infos)
3942 {
3943     if (parent_die == NULL)
3944         return 0;
3945 
3946     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
3947 
3948     size_t arg_idx = 0;
3949     const DWARFDebugInfoEntry *die;
3950     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
3951     {
3952         dw_tag_t tag = die->Tag();
3953         switch (tag)
3954         {
3955         case DW_TAG_formal_parameter:
3956             {
3957                 DWARFDebugInfoEntry::Attributes attributes;
3958                 const size_t num_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
3959                 if (num_attributes > 0)
3960                 {
3961                     const char *name = NULL;
3962                     Declaration decl;
3963                     dw_offset_t param_type_die_offset = DW_INVALID_OFFSET;
3964                     bool is_artificial = false;
3965                     // one of None, Auto, Register, Extern, Static, PrivateExtern
3966 
3967                     clang::StorageClass storage = clang::SC_None;
3968                     uint32_t i;
3969                     for (i=0; i<num_attributes; ++i)
3970                     {
3971                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
3972                         DWARFFormValue form_value;
3973                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
3974                         {
3975                             switch (attr)
3976                             {
3977                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
3978                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
3979                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
3980                             case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
3981                             case DW_AT_type:        param_type_die_offset = form_value.Reference(dwarf_cu); break;
3982                             case DW_AT_artificial:  is_artificial = form_value.Unsigned() != 0; break;
3983                             case DW_AT_location:
3984     //                          if (form_value.BlockData())
3985     //                          {
3986     //                              const DataExtractor& debug_info_data = debug_info();
3987     //                              uint32_t block_length = form_value.Unsigned();
3988     //                              DataExtractor location(debug_info_data, form_value.BlockData() - debug_info_data.GetDataStart(), block_length);
3989     //                          }
3990     //                          else
3991     //                          {
3992     //                          }
3993     //                          break;
3994                             case DW_AT_const_value:
3995                             case DW_AT_default_value:
3996                             case DW_AT_description:
3997                             case DW_AT_endianity:
3998                             case DW_AT_is_optional:
3999                             case DW_AT_segment:
4000                             case DW_AT_variable_parameter:
4001                             default:
4002                             case DW_AT_abstract_origin:
4003                             case DW_AT_sibling:
4004                                 break;
4005                             }
4006                         }
4007                     }
4008 
4009                     bool skip = false;
4010                     if (skip_artificial)
4011                     {
4012                         if (is_artificial)
4013                         {
4014                             // In order to determine if a C++ member function is
4015                             // "const" we have to look at the const-ness of "this"...
4016                             // Ugly, but that
4017                             if (arg_idx == 0)
4018                             {
4019                                 if (DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()))
4020                                 {
4021                                     // Often times compilers omit the "this" name for the
4022                                     // specification DIEs, so we can't rely upon the name
4023                                     // being in the formal parameter DIE...
4024                                     if (name == NULL || ::strcmp(name, "this")==0)
4025                                     {
4026                                         Type *this_type = ResolveTypeUID (param_type_die_offset);
4027                                         if (this_type)
4028                                         {
4029                                             uint32_t encoding_mask = this_type->GetEncodingMask();
4030                                             if (encoding_mask & Type::eEncodingIsPointerUID)
4031                                             {
4032                                                 is_static = false;
4033 
4034                                                 if (encoding_mask & (1u << Type::eEncodingIsConstUID))
4035                                                     type_quals |= clang::Qualifiers::Const;
4036                                                 if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
4037                                                     type_quals |= clang::Qualifiers::Volatile;
4038                                             }
4039                                         }
4040                                     }
4041                                 }
4042                             }
4043                             skip = true;
4044                         }
4045                         else
4046                         {
4047 
4048                             // HACK: Objective C formal parameters "self" and "_cmd"
4049                             // are not marked as artificial in the DWARF...
4050                             CompileUnit *comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
4051                             if (comp_unit)
4052                             {
4053                                 switch (comp_unit->GetLanguage())
4054                                 {
4055                                     case eLanguageTypeObjC:
4056                                     case eLanguageTypeObjC_plus_plus:
4057                                         if (name && name[0] && (strcmp (name, "self") == 0 || strcmp (name, "_cmd") == 0))
4058                                             skip = true;
4059                                         break;
4060                                     default:
4061                                         break;
4062                                 }
4063                             }
4064                         }
4065                     }
4066 
4067                     if (!skip)
4068                     {
4069                         Type *type = ResolveTypeUID(param_type_die_offset);
4070                         if (type)
4071                         {
4072                             function_param_types.push_back (type->GetClangForwardType());
4073 
4074                             clang::ParmVarDecl *param_var_decl = GetClangASTContext().CreateParameterDeclaration (name,
4075                                                                                                                   type->GetClangForwardType(),
4076                                                                                                                   storage);
4077                             assert(param_var_decl);
4078                             function_param_decls.push_back(param_var_decl);
4079 
4080                             GetClangASTContext().SetMetadataAsUserID ((uintptr_t)param_var_decl, MakeUserID(die->GetOffset()));
4081                         }
4082                     }
4083                 }
4084                 arg_idx++;
4085             }
4086             break;
4087 
4088         case DW_TAG_template_type_parameter:
4089         case DW_TAG_template_value_parameter:
4090             ParseTemplateDIE (dwarf_cu, die,template_param_infos);
4091             break;
4092 
4093         default:
4094             break;
4095         }
4096     }
4097     return arg_idx;
4098 }
4099 
4100 size_t
4101 SymbolFileDWARF::ParseChildEnumerators
4102 (
4103     const SymbolContext& sc,
4104     clang_type_t  enumerator_clang_type,
4105     uint32_t enumerator_byte_size,
4106     DWARFCompileUnit* dwarf_cu,
4107     const DWARFDebugInfoEntry *parent_die
4108 )
4109 {
4110     if (parent_die == NULL)
4111         return 0;
4112 
4113     size_t enumerators_added = 0;
4114     const DWARFDebugInfoEntry *die;
4115     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4116 
4117     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4118     {
4119         const dw_tag_t tag = die->Tag();
4120         if (tag == DW_TAG_enumerator)
4121         {
4122             DWARFDebugInfoEntry::Attributes attributes;
4123             const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4124             if (num_child_attributes > 0)
4125             {
4126                 const char *name = NULL;
4127                 bool got_value = false;
4128                 int64_t enum_value = 0;
4129                 Declaration decl;
4130 
4131                 uint32_t i;
4132                 for (i=0; i<num_child_attributes; ++i)
4133                 {
4134                     const dw_attr_t attr = attributes.AttributeAtIndex(i);
4135                     DWARFFormValue form_value;
4136                     if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4137                     {
4138                         switch (attr)
4139                         {
4140                         case DW_AT_const_value:
4141                             got_value = true;
4142                             enum_value = form_value.Unsigned();
4143                             break;
4144 
4145                         case DW_AT_name:
4146                             name = form_value.AsCString(&get_debug_str_data());
4147                             break;
4148 
4149                         case DW_AT_description:
4150                         default:
4151                         case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4152                         case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4153                         case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4154                         case DW_AT_sibling:
4155                             break;
4156                         }
4157                     }
4158                 }
4159 
4160                 if (name && name[0] && got_value)
4161                 {
4162                     GetClangASTContext().AddEnumerationValueToEnumerationType (enumerator_clang_type,
4163                                                                                enumerator_clang_type,
4164                                                                                decl,
4165                                                                                name,
4166                                                                                enum_value,
4167                                                                                enumerator_byte_size * 8);
4168                     ++enumerators_added;
4169                 }
4170             }
4171         }
4172     }
4173     return enumerators_added;
4174 }
4175 
4176 void
4177 SymbolFileDWARF::ParseChildArrayInfo
4178 (
4179     const SymbolContext& sc,
4180     DWARFCompileUnit* dwarf_cu,
4181     const DWARFDebugInfoEntry *parent_die,
4182     int64_t& first_index,
4183     std::vector<uint64_t>& element_orders,
4184     uint32_t& byte_stride,
4185     uint32_t& bit_stride
4186 )
4187 {
4188     if (parent_die == NULL)
4189         return;
4190 
4191     const DWARFDebugInfoEntry *die;
4192     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize());
4193     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4194     {
4195         const dw_tag_t tag = die->Tag();
4196         switch (tag)
4197         {
4198         case DW_TAG_subrange_type:
4199             {
4200                 DWARFDebugInfoEntry::Attributes attributes;
4201                 const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4202                 if (num_child_attributes > 0)
4203                 {
4204                     uint64_t num_elements = 0;
4205                     uint64_t lower_bound = 0;
4206                     uint64_t upper_bound = 0;
4207                     uint32_t i;
4208                     for (i=0; i<num_child_attributes; ++i)
4209                     {
4210                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
4211                         DWARFFormValue form_value;
4212                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4213                         {
4214                             switch (attr)
4215                             {
4216                             case DW_AT_name:
4217                                 break;
4218 
4219                             case DW_AT_count:
4220                                 num_elements = form_value.Unsigned();
4221                                 break;
4222 
4223                             case DW_AT_bit_stride:
4224                                 bit_stride = form_value.Unsigned();
4225                                 break;
4226 
4227                             case DW_AT_byte_stride:
4228                                 byte_stride = form_value.Unsigned();
4229                                 break;
4230 
4231                             case DW_AT_lower_bound:
4232                                 lower_bound = form_value.Unsigned();
4233                                 break;
4234 
4235                             case DW_AT_upper_bound:
4236                                 upper_bound = form_value.Unsigned();
4237                                 break;
4238 
4239                             default:
4240                             case DW_AT_abstract_origin:
4241                             case DW_AT_accessibility:
4242                             case DW_AT_allocated:
4243                             case DW_AT_associated:
4244                             case DW_AT_data_location:
4245                             case DW_AT_declaration:
4246                             case DW_AT_description:
4247                             case DW_AT_sibling:
4248                             case DW_AT_threads_scaled:
4249                             case DW_AT_type:
4250                             case DW_AT_visibility:
4251                                 break;
4252                             }
4253                         }
4254                     }
4255 
4256                     if (upper_bound > lower_bound)
4257                         num_elements = upper_bound - lower_bound + 1;
4258 
4259                     element_orders.push_back (num_elements);
4260                 }
4261             }
4262             break;
4263         }
4264     }
4265 }
4266 
4267 TypeSP
4268 SymbolFileDWARF::GetTypeForDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry* die)
4269 {
4270     TypeSP type_sp;
4271     if (die != NULL)
4272     {
4273         assert(dwarf_cu != NULL);
4274         Type *type_ptr = m_die_to_type.lookup (die);
4275         if (type_ptr == NULL)
4276         {
4277             CompileUnit* lldb_cu = GetCompUnitForDWARFCompUnit(dwarf_cu);
4278             assert (lldb_cu);
4279             SymbolContext sc(lldb_cu);
4280             type_sp = ParseType(sc, dwarf_cu, die, NULL);
4281         }
4282         else if (type_ptr != DIE_IS_BEING_PARSED)
4283         {
4284             // Grab the existing type from the master types lists
4285             type_sp = type_ptr->shared_from_this();
4286         }
4287 
4288     }
4289     return type_sp;
4290 }
4291 
4292 clang::DeclContext *
4293 SymbolFileDWARF::GetClangDeclContextContainingDIEOffset (dw_offset_t die_offset)
4294 {
4295     if (die_offset != DW_INVALID_OFFSET)
4296     {
4297         DWARFCompileUnitSP cu_sp;
4298         const DWARFDebugInfoEntry* die = DebugInfo()->GetDIEPtr(die_offset, &cu_sp);
4299         return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
4300     }
4301     return NULL;
4302 }
4303 
4304 clang::DeclContext *
4305 SymbolFileDWARF::GetClangDeclContextForDIEOffset (const SymbolContext &sc, dw_offset_t die_offset)
4306 {
4307     if (die_offset != DW_INVALID_OFFSET)
4308     {
4309         DWARFDebugInfo* debug_info = DebugInfo();
4310         if (debug_info)
4311         {
4312             DWARFCompileUnitSP cu_sp;
4313             const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(die_offset, &cu_sp);
4314             if (die)
4315                 return GetClangDeclContextForDIE (sc, cu_sp.get(), die);
4316         }
4317     }
4318     return NULL;
4319 }
4320 
4321 clang::NamespaceDecl *
4322 SymbolFileDWARF::ResolveNamespaceDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry *die)
4323 {
4324     if (die && die->Tag() == DW_TAG_namespace)
4325     {
4326         // See if we already parsed this namespace DIE and associated it with a
4327         // uniqued namespace declaration
4328         clang::NamespaceDecl *namespace_decl = static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die]);
4329         if (namespace_decl)
4330             return namespace_decl;
4331         else
4332         {
4333             const char *namespace_name = die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_name, NULL);
4334             clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, NULL);
4335             namespace_decl = GetClangASTContext().GetUniqueNamespaceDeclaration (namespace_name, containing_decl_ctx);
4336             LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4337             if (log)
4338             {
4339                 if (namespace_name)
4340                 {
4341                     GetObjectFile()->GetModule()->LogMessage (log.get(),
4342                                                               "ASTContext => %p: 0x%8.8llx: DW_TAG_namespace with DW_AT_name(\"%s\") => clang::NamespaceDecl *%p (original = %p)",
4343                                                               GetClangASTContext().getASTContext(),
4344                                                               MakeUserID(die->GetOffset()),
4345                                                               namespace_name,
4346                                                               namespace_decl,
4347                                                               namespace_decl->getOriginalNamespace());
4348                 }
4349                 else
4350                 {
4351                     GetObjectFile()->GetModule()->LogMessage (log.get(),
4352                                                               "ASTContext => %p: 0x%8.8llx: DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p (original = %p)",
4353                                                               GetClangASTContext().getASTContext(),
4354                                                               MakeUserID(die->GetOffset()),
4355                                                               namespace_decl,
4356                                                               namespace_decl->getOriginalNamespace());
4357                 }
4358             }
4359 
4360             if (namespace_decl)
4361                 LinkDeclContextToDIE((clang::DeclContext*)namespace_decl, die);
4362             return namespace_decl;
4363         }
4364     }
4365     return NULL;
4366 }
4367 
4368 clang::DeclContext *
4369 SymbolFileDWARF::GetClangDeclContextForDIE (const SymbolContext &sc, DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4370 {
4371     clang::DeclContext *clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4372     if (clang_decl_ctx)
4373         return clang_decl_ctx;
4374     // If this DIE has a specification, or an abstract origin, then trace to those.
4375 
4376     dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4377     if (die_offset != DW_INVALID_OFFSET)
4378         return GetClangDeclContextForDIEOffset (sc, die_offset);
4379 
4380     die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4381     if (die_offset != DW_INVALID_OFFSET)
4382         return GetClangDeclContextForDIEOffset (sc, die_offset);
4383 
4384     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4385     if (log)
4386         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));
4387     // This is the DIE we want.  Parse it, then query our map.
4388     bool assert_not_being_parsed = true;
4389     ResolveTypeUID (cu, die, assert_not_being_parsed);
4390 
4391     clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4392 
4393     return clang_decl_ctx;
4394 }
4395 
4396 clang::DeclContext *
4397 SymbolFileDWARF::GetClangDeclContextContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die, const DWARFDebugInfoEntry **decl_ctx_die_copy)
4398 {
4399     if (m_clang_tu_decl == NULL)
4400         m_clang_tu_decl = GetClangASTContext().getASTContext()->getTranslationUnitDecl();
4401 
4402     const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
4403 
4404     if (decl_ctx_die_copy)
4405         *decl_ctx_die_copy = decl_ctx_die;
4406 
4407     if (decl_ctx_die)
4408     {
4409 
4410         DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find (decl_ctx_die);
4411         if (pos != m_die_to_decl_ctx.end())
4412             return pos->second;
4413 
4414         switch (decl_ctx_die->Tag())
4415         {
4416         case DW_TAG_compile_unit:
4417             return m_clang_tu_decl;
4418 
4419         case DW_TAG_namespace:
4420             return ResolveNamespaceDIE (cu, decl_ctx_die);
4421             break;
4422 
4423         case DW_TAG_structure_type:
4424         case DW_TAG_union_type:
4425         case DW_TAG_class_type:
4426             {
4427                 Type* type = ResolveType (cu, decl_ctx_die);
4428                 if (type)
4429                 {
4430                     clang::DeclContext *decl_ctx = ClangASTContext::GetDeclContextForType (type->GetClangForwardType ());
4431                     if (decl_ctx)
4432                     {
4433                         LinkDeclContextToDIE (decl_ctx, decl_ctx_die);
4434                         if (decl_ctx)
4435                             return decl_ctx;
4436                     }
4437                 }
4438             }
4439             break;
4440 
4441         default:
4442             break;
4443         }
4444     }
4445     return m_clang_tu_decl;
4446 }
4447 
4448 
4449 const DWARFDebugInfoEntry *
4450 SymbolFileDWARF::GetDeclContextDIEContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4451 {
4452     if (cu && die)
4453     {
4454         const DWARFDebugInfoEntry * const decl_die = die;
4455 
4456         while (die != NULL)
4457         {
4458             // If this is the original DIE that we are searching for a declaration
4459             // for, then don't look in the cache as we don't want our own decl
4460             // context to be our decl context...
4461             if (decl_die != die)
4462             {
4463                 switch (die->Tag())
4464                 {
4465                     case DW_TAG_compile_unit:
4466                     case DW_TAG_namespace:
4467                     case DW_TAG_structure_type:
4468                     case DW_TAG_union_type:
4469                     case DW_TAG_class_type:
4470                         return die;
4471 
4472                     default:
4473                         break;
4474                 }
4475             }
4476 
4477             dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4478             if (die_offset != DW_INVALID_OFFSET)
4479             {
4480                 DWARFCompileUnit *spec_cu = cu;
4481                 const DWARFDebugInfoEntry *spec_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &spec_cu);
4482                 const DWARFDebugInfoEntry *spec_die_decl_ctx_die = GetDeclContextDIEContainingDIE (spec_cu, spec_die);
4483                 if (spec_die_decl_ctx_die)
4484                     return spec_die_decl_ctx_die;
4485             }
4486 
4487             die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4488             if (die_offset != DW_INVALID_OFFSET)
4489             {
4490                 DWARFCompileUnit *abs_cu = cu;
4491                 const DWARFDebugInfoEntry *abs_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &abs_cu);
4492                 const DWARFDebugInfoEntry *abs_die_decl_ctx_die = GetDeclContextDIEContainingDIE (abs_cu, abs_die);
4493                 if (abs_die_decl_ctx_die)
4494                     return abs_die_decl_ctx_die;
4495             }
4496 
4497             die = die->GetParent();
4498         }
4499     }
4500     return NULL;
4501 }
4502 
4503 
4504 Symbol *
4505 SymbolFileDWARF::GetObjCClassSymbol (const ConstString &objc_class_name)
4506 {
4507     Symbol *objc_class_symbol = NULL;
4508     if (m_obj_file)
4509     {
4510         Symtab *symtab = m_obj_file->GetSymtab();
4511         if (symtab)
4512         {
4513             objc_class_symbol = symtab->FindFirstSymbolWithNameAndType (objc_class_name,
4514                                                                         eSymbolTypeObjCClass,
4515                                                                         Symtab::eDebugNo,
4516                                                                         Symtab::eVisibilityAny);
4517         }
4518     }
4519     return objc_class_symbol;
4520 }
4521 
4522 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If they don't
4523 // then we can end up looking through all class types for a complete type and never find
4524 // the full definition. We need to know if this attribute is supported, so we determine
4525 // this here and cache th result. We also need to worry about the debug map DWARF file
4526 // if we are doing darwin DWARF in .o file debugging.
4527 bool
4528 SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type (DWARFCompileUnit *cu)
4529 {
4530     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate)
4531     {
4532         m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
4533         if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
4534             m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4535         else
4536         {
4537             DWARFDebugInfo* debug_info = DebugInfo();
4538             const uint32_t num_compile_units = GetNumCompileUnits();
4539             for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
4540             {
4541                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
4542                 if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type())
4543                 {
4544                     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4545                     break;
4546                 }
4547             }
4548         }
4549         if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && GetDebugMapSymfile ())
4550             return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type (this);
4551     }
4552     return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
4553 }
4554 
4555 // This function can be used when a DIE is found that is a forward declaration
4556 // DIE and we want to try and find a type that has the complete definition.
4557 TypeSP
4558 SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE (const DWARFDebugInfoEntry *die,
4559                                                        const ConstString &type_name,
4560                                                        bool must_be_implementation)
4561 {
4562 
4563     TypeSP type_sp;
4564 
4565     if (!type_name || (must_be_implementation && !GetObjCClassSymbol (type_name)))
4566         return type_sp;
4567 
4568     DIEArray die_offsets;
4569 
4570     if (m_using_apple_tables)
4571     {
4572         if (m_apple_types_ap.get())
4573         {
4574             const char *name_cstr = type_name.GetCString();
4575             m_apple_types_ap->FindCompleteObjCClassByName (name_cstr, die_offsets, must_be_implementation);
4576         }
4577     }
4578     else
4579     {
4580         if (!m_indexed)
4581             Index ();
4582 
4583         m_type_index.Find (type_name, die_offsets);
4584     }
4585 
4586     const size_t num_matches = die_offsets.size();
4587 
4588     DWARFCompileUnit* type_cu = NULL;
4589     const DWARFDebugInfoEntry* type_die = NULL;
4590     if (num_matches)
4591     {
4592         DWARFDebugInfo* debug_info = DebugInfo();
4593         for (size_t i=0; i<num_matches; ++i)
4594         {
4595             const dw_offset_t die_offset = die_offsets[i];
4596             type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
4597 
4598             if (type_die)
4599             {
4600                 bool try_resolving_type = false;
4601 
4602                 // Don't try and resolve the DIE we are looking for with the DIE itself!
4603                 if (type_die != die)
4604                 {
4605                     switch (type_die->Tag())
4606                     {
4607                         case DW_TAG_class_type:
4608                         case DW_TAG_structure_type:
4609                             try_resolving_type = true;
4610                             break;
4611                         default:
4612                             break;
4613                     }
4614                 }
4615 
4616                 if (try_resolving_type)
4617                 {
4618 					if (must_be_implementation && type_cu->Supports_DW_AT_APPLE_objc_complete_type())
4619 	                    try_resolving_type = type_die->GetAttributeValueAsUnsigned (this, type_cu, DW_AT_APPLE_objc_complete_type, 0);
4620 
4621                     if (try_resolving_type)
4622                     {
4623                         Type *resolved_type = ResolveType (type_cu, type_die, false);
4624                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
4625                         {
4626                             DEBUG_PRINTF ("resolved 0x%8.8llx (cu 0x%8.8llx) from %s to 0x%8.8llx (cu 0x%8.8llx)\n",
4627                                           MakeUserID(die->GetOffset()),
4628                                           MakeUserID(dwarf_cu->GetOffset()),
4629                                           m_obj_file->GetFileSpec().GetFilename().AsCString(),
4630                                           MakeUserID(type_die->GetOffset()),
4631                                           MakeUserID(type_cu->GetOffset()));
4632 
4633                             if (die)
4634                                 m_die_to_type[die] = resolved_type;
4635                             type_sp = resolved_type->shared_from_this();
4636                             break;
4637                         }
4638                     }
4639                 }
4640             }
4641             else
4642             {
4643                 if (m_using_apple_tables)
4644                 {
4645                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4646                                                                die_offset, type_name.GetCString());
4647                 }
4648             }
4649 
4650         }
4651     }
4652     return type_sp;
4653 }
4654 
4655 
4656 //----------------------------------------------------------------------
4657 // This function helps to ensure that the declaration contexts match for
4658 // two different DIEs. Often times debug information will refer to a
4659 // forward declaration of a type (the equivalent of "struct my_struct;".
4660 // There will often be a declaration of that type elsewhere that has the
4661 // full definition. When we go looking for the full type "my_struct", we
4662 // will find one or more matches in the accelerator tables and we will
4663 // then need to make sure the type was in the same declaration context
4664 // as the original DIE. This function can efficiently compare two DIEs
4665 // and will return true when the declaration context matches, and false
4666 // when they don't.
4667 //----------------------------------------------------------------------
4668 bool
4669 SymbolFileDWARF::DIEDeclContextsMatch (DWARFCompileUnit* cu1, const DWARFDebugInfoEntry *die1,
4670                                        DWARFCompileUnit* cu2, const DWARFDebugInfoEntry *die2)
4671 {
4672     if (die1 == die2)
4673         return true;
4674 
4675 #if defined (LLDB_CONFIGURATION_DEBUG)
4676     // You can't and shouldn't call this function with a compile unit from
4677     // two different SymbolFileDWARF instances.
4678     assert (DebugInfo()->ContainsCompileUnit (cu1));
4679     assert (DebugInfo()->ContainsCompileUnit (cu2));
4680 #endif
4681 
4682     DWARFDIECollection decl_ctx_1;
4683     DWARFDIECollection decl_ctx_2;
4684     //The declaration DIE stack is a stack of the declaration context
4685     // DIEs all the way back to the compile unit. If a type "T" is
4686     // declared inside a class "B", and class "B" is declared inside
4687     // a class "A" and class "A" is in a namespace "lldb", and the
4688     // namespace is in a compile unit, there will be a stack of DIEs:
4689     //
4690     //   [0] DW_TAG_class_type for "B"
4691     //   [1] DW_TAG_class_type for "A"
4692     //   [2] DW_TAG_namespace  for "lldb"
4693     //   [3] DW_TAG_compile_unit for the source file.
4694     //
4695     // We grab both contexts and make sure that everything matches
4696     // all the way back to the compiler unit.
4697 
4698     // First lets grab the decl contexts for both DIEs
4699     die1->GetDeclContextDIEs (this, cu1, decl_ctx_1);
4700     die2->GetDeclContextDIEs (this, cu2, decl_ctx_2);
4701     // Make sure the context arrays have the same size, otherwise
4702     // we are done
4703     const size_t count1 = decl_ctx_1.Size();
4704     const size_t count2 = decl_ctx_2.Size();
4705     if (count1 != count2)
4706         return false;
4707 
4708     // Make sure the DW_TAG values match all the way back up the the
4709     // compile unit. If they don't, then we are done.
4710     const DWARFDebugInfoEntry *decl_ctx_die1;
4711     const DWARFDebugInfoEntry *decl_ctx_die2;
4712     size_t i;
4713     for (i=0; i<count1; i++)
4714     {
4715         decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
4716         decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
4717         if (decl_ctx_die1->Tag() != decl_ctx_die2->Tag())
4718             return false;
4719     }
4720 #if defined LLDB_CONFIGURATION_DEBUG
4721 
4722     // Make sure the top item in the decl context die array is always
4723     // DW_TAG_compile_unit. If it isn't then something went wrong in
4724     // the DWARFDebugInfoEntry::GetDeclContextDIEs() function...
4725     assert (decl_ctx_1.GetDIEPtrAtIndex (count1 - 1)->Tag() == DW_TAG_compile_unit);
4726 
4727 #endif
4728     // Always skip the compile unit when comparing by only iterating up to
4729     // "count - 1". Here we compare the names as we go.
4730     for (i=0; i<count1 - 1; i++)
4731     {
4732         decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
4733         decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
4734         const char *name1 = decl_ctx_die1->GetName(this, cu1);
4735         const char *name2 = decl_ctx_die2->GetName(this, cu2);
4736         // If the string was from a DW_FORM_strp, then the pointer will often
4737         // be the same!
4738         if (name1 == name2)
4739             continue;
4740 
4741         // Name pointers are not equal, so only compare the strings
4742         // if both are not NULL.
4743         if (name1 && name2)
4744         {
4745             // If the strings don't compare, we are done...
4746             if (strcmp(name1, name2) != 0)
4747                 return false;
4748         }
4749         else
4750         {
4751             // One name was NULL while the other wasn't
4752             return false;
4753         }
4754     }
4755     // We made it through all of the checks and the declaration contexts
4756     // are equal.
4757     return true;
4758 }
4759 
4760 // This function can be used when a DIE is found that is a forward declaration
4761 // DIE and we want to try and find a type that has the complete definition.
4762 // "cu" and "die" must be from this SymbolFileDWARF
4763 TypeSP
4764 SymbolFileDWARF::FindDefinitionTypeForDIE (DWARFCompileUnit* cu,
4765                                            const DWARFDebugInfoEntry *die,
4766                                            const ConstString &type_name)
4767 {
4768     TypeSP type_sp;
4769 
4770 #if defined (LLDB_CONFIGURATION_DEBUG)
4771     // You can't and shouldn't call this function with a compile unit from
4772     // another SymbolFileDWARF instance.
4773     assert (DebugInfo()->ContainsCompileUnit (cu));
4774 #endif
4775 
4776     if (cu == NULL || die == NULL || !type_name)
4777         return type_sp;
4778 
4779     LogSP log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
4780     if (log)
4781     {
4782         std::string qualified_name;
4783         die->GetQualifiedName(this, cu, qualified_name);
4784         GetObjectFile()->GetModule()->LogMessage (log.get(),
4785                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x (%s), name='%s')",
4786                                                   die->GetOffset(),
4787                                                   qualified_name.c_str(),
4788                                                   type_name.GetCString());
4789     }
4790 
4791     DIEArray die_offsets;
4792 
4793     if (m_using_apple_tables)
4794     {
4795         if (m_apple_types_ap.get())
4796         {
4797             if (m_apple_types_ap->GetHeader().header_data.atoms.size() > 1)
4798             {
4799                 m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), die->Tag(), die_offsets);
4800             }
4801             else
4802             {
4803                 m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
4804             }
4805         }
4806     }
4807     else
4808     {
4809         if (!m_indexed)
4810             Index ();
4811 
4812         m_type_index.Find (type_name, die_offsets);
4813     }
4814 
4815     const size_t num_matches = die_offsets.size();
4816 
4817     const dw_tag_t die_tag = die->Tag();
4818 
4819     DWARFCompileUnit* type_cu = NULL;
4820     const DWARFDebugInfoEntry* type_die = NULL;
4821     if (num_matches)
4822     {
4823         DWARFDebugInfo* debug_info = DebugInfo();
4824         for (size_t i=0; i<num_matches; ++i)
4825         {
4826             const dw_offset_t die_offset = die_offsets[i];
4827             type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
4828 
4829             if (type_die)
4830             {
4831                 bool try_resolving_type = false;
4832 
4833                 // Don't try and resolve the DIE we are looking for with the DIE itself!
4834                 if (type_die != die)
4835                 {
4836                     const dw_tag_t type_die_tag = type_die->Tag();
4837                     // Make sure the tags match
4838                     if (type_die_tag == die_tag)
4839                     {
4840                         // The tags match, lets try resolving this type
4841                         try_resolving_type = true;
4842                     }
4843                     else
4844                     {
4845                         // The tags don't match, but we need to watch our for a
4846                         // forward declaration for a struct and ("struct foo")
4847                         // ends up being a class ("class foo { ... };") or
4848                         // vice versa.
4849                         switch (type_die_tag)
4850                         {
4851                         case DW_TAG_class_type:
4852                             // We had a "class foo", see if we ended up with a "struct foo { ... };"
4853                             try_resolving_type = (die_tag == DW_TAG_structure_type);
4854                             break;
4855                         case DW_TAG_structure_type:
4856                             // We had a "struct foo", see if we ended up with a "class foo { ... };"
4857                             try_resolving_type = (die_tag == DW_TAG_class_type);
4858                             break;
4859                         default:
4860                             // Tags don't match, don't event try to resolve
4861                             // using this type whose name matches....
4862                             break;
4863                         }
4864                     }
4865                 }
4866 
4867                 if (try_resolving_type)
4868                 {
4869                     if (log)
4870                     {
4871                         std::string qualified_name;
4872                         type_die->GetQualifiedName(this, cu, qualified_name);
4873                         GetObjectFile()->GetModule()->LogMessage (log.get(),
4874                                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x, name='%s') trying die=0x%8.8x (%s)",
4875                                                                   die->GetOffset(),
4876                                                                   type_name.GetCString(),
4877                                                                   type_die->GetOffset(),
4878                                                                   qualified_name.c_str());
4879                     }
4880 
4881                     // Make sure the decl contexts match all the way up
4882                     if (DIEDeclContextsMatch(cu, die, type_cu, type_die))
4883                     {
4884                         Type *resolved_type = ResolveType (type_cu, type_die, false);
4885                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
4886                         {
4887                             DEBUG_PRINTF ("resolved 0x%8.8llx (cu 0x%8.8llx) from %s to 0x%8.8llx (cu 0x%8.8llx)\n",
4888                                           MakeUserID(die->GetOffset()),
4889                                           MakeUserID(dwarf_cu->GetOffset()),
4890                                           m_obj_file->GetFileSpec().GetFilename().AsCString(),
4891                                           MakeUserID(type_die->GetOffset()),
4892                                           MakeUserID(type_cu->GetOffset()));
4893 
4894                             m_die_to_type[die] = resolved_type;
4895                             type_sp = resolved_type->shared_from_this();
4896                             break;
4897                         }
4898                     }
4899                 }
4900                 else
4901                 {
4902                     if (log)
4903                     {
4904                         std::string qualified_name;
4905                         type_die->GetQualifiedName(this, cu, qualified_name);
4906                         GetObjectFile()->GetModule()->LogMessage (log.get(),
4907                                                                   "SymbolFileDWARF::FindDefinitionTypeForDIE(die=0x%8.8x, name='%s') ignoring die=0x%8.8x (%s)",
4908                                                                   die->GetOffset(),
4909                                                                   type_name.GetCString(),
4910                                                                   type_die->GetOffset(),
4911                                                                   qualified_name.c_str());
4912                     }
4913                 }
4914             }
4915             else
4916             {
4917                 if (m_using_apple_tables)
4918                 {
4919                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4920                                                                                die_offset, type_name.GetCString());
4921                 }
4922             }
4923 
4924         }
4925     }
4926     return type_sp;
4927 }
4928 
4929 TypeSP
4930 SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext (const DWARFDeclContext &dwarf_decl_ctx)
4931 {
4932     TypeSP type_sp;
4933 
4934     const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
4935     if (dwarf_decl_ctx_count > 0)
4936     {
4937         const ConstString type_name(dwarf_decl_ctx[0].name);
4938         const dw_tag_t tag = dwarf_decl_ctx[0].tag;
4939 
4940         if (type_name)
4941         {
4942             LogSP log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
4943             if (log)
4944             {
4945                 GetObjectFile()->GetModule()->LogMessage (log.get(),
4946                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s')",
4947                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
4948                                                           dwarf_decl_ctx.GetQualifiedName());
4949             }
4950 
4951             DIEArray die_offsets;
4952 
4953             if (m_using_apple_tables)
4954             {
4955                 if (m_apple_types_ap.get())
4956                 {
4957                     if (m_apple_types_ap->GetHeader().header_data.atoms.size() > 1)
4958                     {
4959                         m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), tag, die_offsets);
4960                     }
4961                     else
4962                     {
4963                         m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
4964                     }
4965                 }
4966             }
4967             else
4968             {
4969                 if (!m_indexed)
4970                     Index ();
4971 
4972                 m_type_index.Find (type_name, die_offsets);
4973             }
4974 
4975             const size_t num_matches = die_offsets.size();
4976 
4977 
4978             DWARFCompileUnit* type_cu = NULL;
4979             const DWARFDebugInfoEntry* type_die = NULL;
4980             if (num_matches)
4981             {
4982                 DWARFDebugInfo* debug_info = DebugInfo();
4983                 for (size_t i=0; i<num_matches; ++i)
4984                 {
4985                     const dw_offset_t die_offset = die_offsets[i];
4986                     type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
4987 
4988                     if (type_die)
4989                     {
4990                         bool try_resolving_type = false;
4991 
4992                         // Don't try and resolve the DIE we are looking for with the DIE itself!
4993                         const dw_tag_t type_tag = type_die->Tag();
4994                         // Make sure the tags match
4995                         if (type_tag == tag)
4996                         {
4997                             // The tags match, lets try resolving this type
4998                             try_resolving_type = true;
4999                         }
5000                         else
5001                         {
5002                             // The tags don't match, but we need to watch our for a
5003                             // forward declaration for a struct and ("struct foo")
5004                             // ends up being a class ("class foo { ... };") or
5005                             // vice versa.
5006                             switch (type_tag)
5007                             {
5008                                 case DW_TAG_class_type:
5009                                     // We had a "class foo", see if we ended up with a "struct foo { ... };"
5010                                     try_resolving_type = (tag == DW_TAG_structure_type);
5011                                     break;
5012                                 case DW_TAG_structure_type:
5013                                     // We had a "struct foo", see if we ended up with a "class foo { ... };"
5014                                     try_resolving_type = (tag == DW_TAG_class_type);
5015                                     break;
5016                                 default:
5017                                     // Tags don't match, don't event try to resolve
5018                                     // using this type whose name matches....
5019                                     break;
5020                             }
5021                         }
5022 
5023                         if (try_resolving_type)
5024                         {
5025                             DWARFDeclContext type_dwarf_decl_ctx;
5026                             type_die->GetDWARFDeclContext (this, type_cu, type_dwarf_decl_ctx);
5027 
5028                             if (log)
5029                             {
5030                                 GetObjectFile()->GetModule()->LogMessage (log.get(),
5031                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') trying die=0x%8.8x (%s)",
5032                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5033                                                                           dwarf_decl_ctx.GetQualifiedName(),
5034                                                                           type_die->GetOffset(),
5035                                                                           type_dwarf_decl_ctx.GetQualifiedName());
5036                             }
5037 
5038                             // Make sure the decl contexts match all the way up
5039                             if (dwarf_decl_ctx == type_dwarf_decl_ctx)
5040                             {
5041                                 Type *resolved_type = ResolveType (type_cu, type_die, false);
5042                                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
5043                                 {
5044                                     type_sp = resolved_type->shared_from_this();
5045                                     break;
5046                                 }
5047                             }
5048                         }
5049                         else
5050                         {
5051                             if (log)
5052                             {
5053                                 std::string qualified_name;
5054                                 type_die->GetQualifiedName(this, type_cu, qualified_name);
5055                                 GetObjectFile()->GetModule()->LogMessage (log.get(),
5056                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') ignoring die=0x%8.8x (%s)",
5057                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5058                                                                           dwarf_decl_ctx.GetQualifiedName(),
5059                                                                           type_die->GetOffset(),
5060                                                                           qualified_name.c_str());
5061                             }
5062                         }
5063                     }
5064                     else
5065                     {
5066                         if (m_using_apple_tables)
5067                         {
5068                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
5069                                                                                        die_offset, type_name.GetCString());
5070                         }
5071                     }
5072 
5073                 }
5074             }
5075         }
5076     }
5077     return type_sp;
5078 }
5079 
5080 bool
5081 SymbolFileDWARF::CopyUniqueClassMethodTypes (Type *class_type,
5082                                              DWARFCompileUnit* src_cu,
5083                                              const DWARFDebugInfoEntry *src_class_die,
5084                                              DWARFCompileUnit* dst_cu,
5085                                              const DWARFDebugInfoEntry *dst_class_die)
5086 {
5087     if (!class_type || !src_cu || !src_class_die || !dst_cu || !dst_class_die)
5088         return false;
5089     if (src_class_die->Tag() != dst_class_die->Tag())
5090         return false;
5091 
5092     // We need to complete the class type so we can get all of the method types
5093     // parsed so we can then unique those types to their equivalent counterparts
5094     // in "dst_cu" and "dst_class_die"
5095     class_type->GetClangFullType();
5096 
5097     const DWARFDebugInfoEntry *src_die;
5098     const DWARFDebugInfoEntry *dst_die;
5099     UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die;
5100     UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die;
5101     UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die_artificial;
5102     UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die_artificial;
5103     for (src_die = src_class_die->GetFirstChild(); src_die != NULL; src_die = src_die->GetSibling())
5104     {
5105         if (src_die->Tag() == DW_TAG_subprogram)
5106         {
5107             // Make sure this is a declaration and not a concrete instance by looking
5108             // for DW_AT_declaration set to 1. Sometimes concrete function instances
5109             // are placed inside the class definitions and shouldn't be included in
5110             // the list of things are are tracking here.
5111             if (src_die->GetAttributeValueAsUnsigned(this, src_cu, DW_AT_declaration, 0) == 1)
5112             {
5113                 const char *src_name = src_die->GetMangledName (this, src_cu);
5114                 if (src_name)
5115                 {
5116                     ConstString src_const_name(src_name);
5117                     if (src_die->GetAttributeValueAsUnsigned(this, src_cu, DW_AT_artificial, 0))
5118                         src_name_to_die_artificial.Append(src_const_name.GetCString(), src_die);
5119                     else
5120                         src_name_to_die.Append(src_const_name.GetCString(), src_die);
5121                 }
5122             }
5123         }
5124     }
5125     for (dst_die = dst_class_die->GetFirstChild(); dst_die != NULL; dst_die = dst_die->GetSibling())
5126     {
5127         if (dst_die->Tag() == DW_TAG_subprogram)
5128         {
5129             // Make sure this is a declaration and not a concrete instance by looking
5130             // for DW_AT_declaration set to 1. Sometimes concrete function instances
5131             // are placed inside the class definitions and shouldn't be included in
5132             // the list of things are are tracking here.
5133             if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_declaration, 0) == 1)
5134             {
5135                 const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5136                 if (dst_name)
5137                 {
5138                     ConstString dst_const_name(dst_name);
5139                     if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_artificial, 0))
5140                         dst_name_to_die_artificial.Append(dst_const_name.GetCString(), dst_die);
5141                     else
5142                         dst_name_to_die.Append(dst_const_name.GetCString(), dst_die);
5143                 }
5144             }
5145         }
5146     }
5147     const uint32_t src_size = src_name_to_die.GetSize ();
5148     const uint32_t dst_size = dst_name_to_die.GetSize ();
5149     LogSP log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | DWARF_LOG_TYPE_COMPLETION));
5150 
5151     if (src_size == dst_size)
5152     {
5153         uint32_t idx;
5154         for (idx = 0; idx < src_size; ++idx)
5155         {
5156             src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5157             dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5158 
5159             if (src_die->Tag() != dst_die->Tag())
5160             {
5161                 if (log)
5162                     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)",
5163                                 src_class_die->GetOffset(),
5164                                 dst_class_die->GetOffset(),
5165                                 src_die->GetOffset(),
5166                                 DW_TAG_value_to_name(src_die->Tag()),
5167                                 dst_die->GetOffset(),
5168                                 DW_TAG_value_to_name(src_die->Tag()));
5169                 return false;
5170             }
5171 
5172             const char *src_name = src_die->GetMangledName (this, src_cu);
5173             const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5174 
5175             // Make sure the names match
5176             if (src_name == dst_name || (strcmp (src_name, dst_name) == 0))
5177                 continue;
5178 
5179             if (log)
5180                 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)",
5181                             src_class_die->GetOffset(),
5182                             dst_class_die->GetOffset(),
5183                             src_die->GetOffset(),
5184                             src_name,
5185                             dst_die->GetOffset(),
5186                             dst_name);
5187 
5188             return false;
5189         }
5190 
5191         for (idx = 0; idx < src_size; ++idx)
5192         {
5193             src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5194             dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5195 
5196             clang::DeclContext *src_decl_ctx = m_die_to_decl_ctx[src_die];
5197             if (src_decl_ctx)
5198             {
5199                 if (log)
5200                     log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x", src_decl_ctx, src_die->GetOffset(), dst_die->GetOffset());
5201                 LinkDeclContextToDIE (src_decl_ctx, dst_die);
5202             }
5203             else
5204             {
5205                 if (log)
5206                     log->Printf ("warning: tried to unique decl context from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5207             }
5208 
5209             Type *src_child_type = m_die_to_type[src_die];
5210             if (src_child_type)
5211             {
5212                 if (log)
5213                     log->Printf ("uniquing type %p (uid=0x%llx) from 0x%8.8x for 0x%8.8x", src_child_type, src_child_type->GetID(), src_die->GetOffset(), dst_die->GetOffset());
5214                 m_die_to_type[dst_die] = src_child_type;
5215             }
5216             else
5217             {
5218                 if (log)
5219                     log->Printf ("warning: tried to unique lldb_private::Type from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5220             }
5221         }
5222 
5223         const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize ();
5224 
5225         UniqueCStringMap<const DWARFDebugInfoEntry *> name_to_die_artificial_not_in_src;
5226 
5227         for (idx = 0; idx < src_size_artificial; ++idx)
5228         {
5229             const char *src_name_artificial = src_name_to_die_artificial.GetCStringAtIndex(idx);
5230             src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5231             dst_die = dst_name_to_die_artificial.Find(src_name_artificial, NULL);
5232 
5233             if (dst_die)
5234             {
5235                 // Erase this entry from the map
5236                 const size_t num_removed = dst_name_to_die_artificial.Erase (src_name_artificial);
5237                 assert (num_removed == 0 || num_removed == 1); // REMOVE THIS
5238                 // Both classes have the artificial types, link them
5239                 clang::DeclContext *src_decl_ctx = m_die_to_decl_ctx[src_die];
5240                 if (src_decl_ctx)
5241                 {
5242                     if (log)
5243                         log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x", src_decl_ctx, src_die->GetOffset(), dst_die->GetOffset());
5244                     LinkDeclContextToDIE (src_decl_ctx, dst_die);
5245                 }
5246                 else
5247                 {
5248                     if (log)
5249                         log->Printf ("warning: tried to unique decl context from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5250                 }
5251 
5252                 Type *src_child_type = m_die_to_type[src_die];
5253                 if (src_child_type)
5254                 {
5255                     if (log)
5256                         log->Printf ("uniquing type %p (uid=0x%llx) from 0x%8.8x for 0x%8.8x", src_child_type, src_child_type->GetID(), src_die->GetOffset(), dst_die->GetOffset());
5257                     m_die_to_type[dst_die] = src_child_type;
5258                 }
5259                 else
5260                 {
5261                     if (log)
5262                         log->Printf ("warning: tried to unique lldb_private::Type from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5263                 }
5264             }
5265         }
5266         const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize ();
5267 
5268         if (dst_size_artificial)
5269         {
5270             for (idx = 0; idx < dst_size_artificial; ++idx)
5271             {
5272                 const char *dst_name_artificial = dst_name_to_die_artificial.GetCStringAtIndex(idx);
5273                 dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5274                 if (log)
5275                     log->Printf ("warning: need to create artificial method for 0x%8.8x for method '%s'", dst_die->GetOffset(), dst_name_artificial);
5276             }
5277         }
5278         return true;
5279     }
5280     else if (src_size != 0 && dst_size != 0)
5281     {
5282         if (log)
5283             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)",
5284                         src_class_die->GetOffset(),
5285                         dst_class_die->GetOffset(),
5286                         src_size,
5287                         dst_size);
5288     }
5289     return false;
5290 }
5291 
5292 TypeSP
5293 SymbolFileDWARF::ParseType (const SymbolContext& sc, DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry *die, bool *type_is_new_ptr)
5294 {
5295     TypeSP type_sp;
5296 
5297     if (type_is_new_ptr)
5298         *type_is_new_ptr = false;
5299 
5300 #if defined(LLDB_CONFIGURATION_DEBUG) or defined(LLDB_CONFIGURATION_RELEASE)
5301     static DIEStack g_die_stack;
5302     DIEStack::ScopedPopper scoped_die_logger(g_die_stack);
5303 #endif
5304 
5305     AccessType accessibility = eAccessNone;
5306     if (die != NULL)
5307     {
5308         LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5309         if (log)
5310         {
5311             const DWARFDebugInfoEntry *context_die;
5312             clang::DeclContext *context = GetClangDeclContextContainingDIE (dwarf_cu, die, &context_die);
5313 
5314             GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die 0x%8.8x)) %s name = '%s')",
5315                         die->GetOffset(),
5316                         context,
5317                         context_die->GetOffset(),
5318                         DW_TAG_value_to_name(die->Tag()),
5319                         die->GetName(this, dwarf_cu));
5320 
5321 #if defined(LLDB_CONFIGURATION_DEBUG) or defined(LLDB_CONFIGURATION_RELEASE)
5322             scoped_die_logger.Push (dwarf_cu, die);
5323             g_die_stack.LogDIEs(log.get(), this);
5324 #endif
5325         }
5326 //
5327 //        LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5328 //        if (log && dwarf_cu)
5329 //        {
5330 //            StreamString s;
5331 //            die->DumpLocation (this, dwarf_cu, s);
5332 //            GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDwarf::%s %s", __FUNCTION__, s.GetData());
5333 //
5334 //        }
5335 
5336         Type *type_ptr = m_die_to_type.lookup (die);
5337         TypeList* type_list = GetTypeList();
5338         if (type_ptr == NULL)
5339         {
5340             ClangASTContext &ast = GetClangASTContext();
5341             if (type_is_new_ptr)
5342                 *type_is_new_ptr = true;
5343 
5344             const dw_tag_t tag = die->Tag();
5345 
5346             bool is_forward_declaration = false;
5347             DWARFDebugInfoEntry::Attributes attributes;
5348             const char *type_name_cstr = NULL;
5349             ConstString type_name_const_str;
5350             Type::ResolveState resolve_state = Type::eResolveStateUnresolved;
5351             size_t byte_size = 0;
5352             Declaration decl;
5353 
5354             Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
5355             clang_type_t clang_type = NULL;
5356 
5357             dw_attr_t attr;
5358 
5359             switch (tag)
5360             {
5361             case DW_TAG_base_type:
5362             case DW_TAG_pointer_type:
5363             case DW_TAG_reference_type:
5364             case DW_TAG_rvalue_reference_type:
5365             case DW_TAG_typedef:
5366             case DW_TAG_const_type:
5367             case DW_TAG_restrict_type:
5368             case DW_TAG_volatile_type:
5369             case DW_TAG_unspecified_type:
5370                 {
5371                     // Set a bit that lets us know that we are currently parsing this
5372                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5373 
5374                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5375                     uint32_t encoding = 0;
5376                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
5377 
5378                     if (num_attributes > 0)
5379                     {
5380                         uint32_t i;
5381                         for (i=0; i<num_attributes; ++i)
5382                         {
5383                             attr = attributes.AttributeAtIndex(i);
5384                             DWARFFormValue form_value;
5385                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5386                             {
5387                                 switch (attr)
5388                                 {
5389                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
5390                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
5391                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
5392                                 case DW_AT_name:
5393 
5394                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5395                                     // Work around a bug in llvm-gcc where they give a name to a reference type which doesn't
5396                                     // include the "&"...
5397                                     if (tag == DW_TAG_reference_type)
5398                                     {
5399                                         if (strchr (type_name_cstr, '&') == NULL)
5400                                             type_name_cstr = NULL;
5401                                     }
5402                                     if (type_name_cstr)
5403                                         type_name_const_str.SetCString(type_name_cstr);
5404                                     break;
5405                                 case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
5406                                 case DW_AT_encoding:    encoding = form_value.Unsigned(); break;
5407                                 case DW_AT_type:        encoding_uid = form_value.Reference(dwarf_cu); break;
5408                                 default:
5409                                 case DW_AT_sibling:
5410                                     break;
5411                                 }
5412                             }
5413                         }
5414                     }
5415 
5416                     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);
5417 
5418                     switch (tag)
5419                     {
5420                     default:
5421                         break;
5422 
5423                     case DW_TAG_unspecified_type:
5424                         if (strcmp(type_name_cstr, "nullptr_t") == 0)
5425                         {
5426                             resolve_state = Type::eResolveStateFull;
5427                             clang_type = ast.getASTContext()->NullPtrTy.getAsOpaquePtr();
5428                             break;
5429                         }
5430                         // Fall through to base type below in case we can handle the type there...
5431 
5432                     case DW_TAG_base_type:
5433                         resolve_state = Type::eResolveStateFull;
5434                         clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (type_name_cstr,
5435                                                                                    encoding,
5436                                                                                    byte_size * 8);
5437                         break;
5438 
5439                     case DW_TAG_pointer_type:           encoding_data_type = Type::eEncodingIsPointerUID;           break;
5440                     case DW_TAG_reference_type:         encoding_data_type = Type::eEncodingIsLValueReferenceUID;   break;
5441                     case DW_TAG_rvalue_reference_type:  encoding_data_type = Type::eEncodingIsRValueReferenceUID;   break;
5442                     case DW_TAG_typedef:                encoding_data_type = Type::eEncodingIsTypedefUID;           break;
5443                     case DW_TAG_const_type:             encoding_data_type = Type::eEncodingIsConstUID;             break;
5444                     case DW_TAG_restrict_type:          encoding_data_type = Type::eEncodingIsRestrictUID;          break;
5445                     case DW_TAG_volatile_type:          encoding_data_type = Type::eEncodingIsVolatileUID;          break;
5446                     }
5447 
5448                     if (clang_type == NULL && (encoding_data_type == Type::eEncodingIsPointerUID || encoding_data_type == Type::eEncodingIsTypedefUID))
5449                     {
5450                         if (type_name_cstr != NULL && sc.comp_unit != NULL &&
5451                             (sc.comp_unit->GetLanguage() == eLanguageTypeObjC || sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus))
5452                         {
5453                             static ConstString g_objc_type_name_id("id");
5454                             static ConstString g_objc_type_name_Class("Class");
5455                             static ConstString g_objc_type_name_selector("SEL");
5456 
5457                             if (type_name_const_str == g_objc_type_name_id)
5458                             {
5459                                 if (log)
5460                                     GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'id' built-in type.",
5461                                                                               die->GetOffset(),
5462                                                                               DW_TAG_value_to_name(die->Tag()),
5463                                                                               die->GetName(this, dwarf_cu));
5464                                 clang_type = ast.GetBuiltInType_objc_id();
5465                                 encoding_data_type = Type::eEncodingIsUID;
5466                                 encoding_uid = LLDB_INVALID_UID;
5467                                 resolve_state = Type::eResolveStateFull;
5468 
5469                             }
5470                             else if (type_name_const_str == g_objc_type_name_Class)
5471                             {
5472                                 if (log)
5473                                     GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'Class' built-in type.",
5474                                                                               die->GetOffset(),
5475                                                                               DW_TAG_value_to_name(die->Tag()),
5476                                                                               die->GetName(this, dwarf_cu));
5477                                 clang_type = ast.GetBuiltInType_objc_Class();
5478                                 encoding_data_type = Type::eEncodingIsUID;
5479                                 encoding_uid = LLDB_INVALID_UID;
5480                                 resolve_state = Type::eResolveStateFull;
5481                             }
5482                             else if (type_name_const_str == g_objc_type_name_selector)
5483                             {
5484                                 if (log)
5485                                     GetObjectFile()->GetModule()->LogMessage (log.get(), "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'selector' built-in type.",
5486                                                                               die->GetOffset(),
5487                                                                               DW_TAG_value_to_name(die->Tag()),
5488                                                                               die->GetName(this, dwarf_cu));
5489                                 clang_type = ast.GetBuiltInType_objc_selector();
5490                                 encoding_data_type = Type::eEncodingIsUID;
5491                                 encoding_uid = LLDB_INVALID_UID;
5492                                 resolve_state = Type::eResolveStateFull;
5493                             }
5494                         }
5495                     }
5496 
5497                     type_sp.reset( new Type (MakeUserID(die->GetOffset()),
5498                                              this,
5499                                              type_name_const_str,
5500                                              byte_size,
5501                                              NULL,
5502                                              encoding_uid,
5503                                              encoding_data_type,
5504                                              &decl,
5505                                              clang_type,
5506                                              resolve_state));
5507 
5508                     m_die_to_type[die] = type_sp.get();
5509 
5510 //                  Type* encoding_type = GetUniquedTypeForDIEOffset(encoding_uid, type_sp, NULL, 0, 0, false);
5511 //                  if (encoding_type != NULL)
5512 //                  {
5513 //                      if (encoding_type != DIE_IS_BEING_PARSED)
5514 //                          type_sp->SetEncodingType(encoding_type);
5515 //                      else
5516 //                          m_indirect_fixups.push_back(type_sp.get());
5517 //                  }
5518                 }
5519                 break;
5520 
5521             case DW_TAG_structure_type:
5522             case DW_TAG_union_type:
5523             case DW_TAG_class_type:
5524                 {
5525                     // Set a bit that lets us know that we are currently parsing this
5526                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5527                     bool byte_size_valid = false;
5528 
5529                     LanguageType class_language = eLanguageTypeUnknown;
5530                     bool is_complete_objc_class = false;
5531                     //bool struct_is_class = false;
5532                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5533                     if (num_attributes > 0)
5534                     {
5535                         uint32_t i;
5536                         for (i=0; i<num_attributes; ++i)
5537                         {
5538                             attr = attributes.AttributeAtIndex(i);
5539                             DWARFFormValue form_value;
5540                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5541                             {
5542                                 switch (attr)
5543                                 {
5544                                 case DW_AT_decl_file:
5545                                     if (dwarf_cu->DW_AT_decl_file_attributes_are_invalid())
5546 									{
5547 										// llvm-gcc outputs invalid DW_AT_decl_file attributes that always
5548 										// point to the compile unit file, so we clear this invalid value
5549 										// so that we can still unique types efficiently.
5550                                         decl.SetFile(FileSpec ("<invalid>", false));
5551 									}
5552                                     else
5553                                         decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned()));
5554                                     break;
5555 
5556                                 case DW_AT_decl_line:
5557                                     decl.SetLine(form_value.Unsigned());
5558                                     break;
5559 
5560                                 case DW_AT_decl_column:
5561                                     decl.SetColumn(form_value.Unsigned());
5562                                     break;
5563 
5564                                 case DW_AT_name:
5565                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5566                                     type_name_const_str.SetCString(type_name_cstr);
5567                                     break;
5568 
5569                                 case DW_AT_byte_size:
5570                                     byte_size = form_value.Unsigned();
5571                                     byte_size_valid = true;
5572                                     break;
5573 
5574                                 case DW_AT_accessibility:
5575                                     accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
5576                                     break;
5577 
5578                                 case DW_AT_declaration:
5579                                     is_forward_declaration = form_value.Unsigned() != 0;
5580                                     break;
5581 
5582                                 case DW_AT_APPLE_runtime_class:
5583                                     class_language = (LanguageType)form_value.Signed();
5584                                     break;
5585 
5586                                 case DW_AT_APPLE_objc_complete_type:
5587                                     is_complete_objc_class = form_value.Signed();
5588                                     break;
5589 
5590                                 case DW_AT_allocated:
5591                                 case DW_AT_associated:
5592                                 case DW_AT_data_location:
5593                                 case DW_AT_description:
5594                                 case DW_AT_start_scope:
5595                                 case DW_AT_visibility:
5596                                 default:
5597                                 case DW_AT_sibling:
5598                                     break;
5599                                 }
5600                             }
5601                         }
5602                     }
5603 
5604                     UniqueDWARFASTType unique_ast_entry;
5605 
5606                     // Only try and unique the type if it has a name.
5607                     if (type_name_const_str &&
5608                         GetUniqueDWARFASTTypeMap().Find (type_name_const_str,
5609                                                          this,
5610                                                          dwarf_cu,
5611                                                          die,
5612                                                          decl,
5613                                                          byte_size_valid ? byte_size : -1,
5614                                                          unique_ast_entry))
5615                     {
5616                         // We have already parsed this type or from another
5617                         // compile unit. GCC loves to use the "one definition
5618                         // rule" which can result in multiple definitions
5619                         // of the same class over and over in each compile
5620                         // unit.
5621                         type_sp = unique_ast_entry.m_type_sp;
5622                         if (type_sp)
5623                         {
5624                             m_die_to_type[die] = type_sp.get();
5625                             return type_sp;
5626                         }
5627                     }
5628 
5629                     DEBUG_PRINTF ("0x%8.8llx: %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
5630 
5631                     int tag_decl_kind = -1;
5632                     AccessType default_accessibility = eAccessNone;
5633                     if (tag == DW_TAG_structure_type)
5634                     {
5635                         tag_decl_kind = clang::TTK_Struct;
5636                         default_accessibility = eAccessPublic;
5637                     }
5638                     else if (tag == DW_TAG_union_type)
5639                     {
5640                         tag_decl_kind = clang::TTK_Union;
5641                         default_accessibility = eAccessPublic;
5642                     }
5643                     else if (tag == DW_TAG_class_type)
5644                     {
5645                         tag_decl_kind = clang::TTK_Class;
5646                         default_accessibility = eAccessPrivate;
5647                     }
5648 
5649                     if (byte_size_valid && byte_size == 0 && type_name_cstr &&
5650                         die->HasChildren() == false &&
5651                         sc.comp_unit->GetLanguage() == eLanguageTypeObjC)
5652                     {
5653                         // Work around an issue with clang at the moment where
5654                         // forward declarations for objective C classes are emitted
5655                         // as:
5656                         //  DW_TAG_structure_type [2]
5657                         //  DW_AT_name( "ForwardObjcClass" )
5658                         //  DW_AT_byte_size( 0x00 )
5659                         //  DW_AT_decl_file( "..." )
5660                         //  DW_AT_decl_line( 1 )
5661                         //
5662                         // Note that there is no DW_AT_declaration and there are
5663                         // no children, and the byte size is zero.
5664                         is_forward_declaration = true;
5665                     }
5666 
5667                     if (class_language == eLanguageTypeObjC ||
5668                         class_language == eLanguageTypeObjC_plus_plus)
5669                     {
5670                         if (!is_complete_objc_class && Supports_DW_AT_APPLE_objc_complete_type(dwarf_cu))
5671                         {
5672                             // We have a valid eSymbolTypeObjCClass class symbol whose
5673                             // name matches the current objective C class that we
5674                             // are trying to find and this DIE isn't the complete
5675                             // definition (we checked is_complete_objc_class above and
5676                             // know it is false), so the real definition is in here somewhere
5677                             type_sp = FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
5678 
5679                             if (!type_sp && GetDebugMapSymfile ())
5680                             {
5681                                 // We weren't able to find a full declaration in
5682                                 // this DWARF, see if we have a declaration anywhere
5683                                 // else...
5684                                 type_sp = m_debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
5685                             }
5686 
5687                             if (type_sp)
5688                             {
5689                                 if (log)
5690                                 {
5691                                     GetObjectFile()->GetModule()->LogMessage (log.get(),
5692                                                                               "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an incomplete objc type, complete type is 0x%8.8llx",
5693                                                                               this,
5694                                                                               die->GetOffset(),
5695                                                                               DW_TAG_value_to_name(tag),
5696                                                                               type_name_cstr,
5697                                                                               type_sp->GetID());
5698                                 }
5699 
5700                                 // We found a real definition for this type elsewhere
5701                                 // so lets use it and cache the fact that we found
5702                                 // a complete type for this die
5703                                 m_die_to_type[die] = type_sp.get();
5704                                 return type_sp;
5705                             }
5706                         }
5707                     }
5708 
5709 
5710                     if (is_forward_declaration)
5711                     {
5712                         // We have a forward declaration to a type and we need
5713                         // to try and find a full declaration. We look in the
5714                         // current type index just in case we have a forward
5715                         // declaration followed by an actual declarations in the
5716                         // DWARF. If this fails, we need to look elsewhere...
5717                         if (log)
5718                         {
5719                             GetObjectFile()->GetModule()->LogMessage (log.get(),
5720                                                                       "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, trying to find complete type",
5721                                                                       this,
5722                                                                       die->GetOffset(),
5723                                                                       DW_TAG_value_to_name(tag),
5724                                                                       type_name_cstr);
5725                         }
5726 
5727                         DWARFDeclContext die_decl_ctx;
5728                         die->GetDWARFDeclContext(this, dwarf_cu, die_decl_ctx);
5729 
5730                         //type_sp = FindDefinitionTypeForDIE (dwarf_cu, die, type_name_const_str);
5731                         type_sp = FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
5732 
5733                         if (!type_sp && GetDebugMapSymfile ())
5734                         {
5735                             // We weren't able to find a full declaration in
5736                             // this DWARF, see if we have a declaration anywhere
5737                             // else...
5738                             type_sp = m_debug_map_symfile->FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
5739                         }
5740 
5741                         if (type_sp)
5742                         {
5743                             if (log)
5744                             {
5745                                 GetObjectFile()->GetModule()->LogMessage (log.get(),
5746                                                                           "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, complete type is 0x%8.8llx",
5747                                                                           this,
5748                                                                           die->GetOffset(),
5749                                                                           DW_TAG_value_to_name(tag),
5750                                                                           type_name_cstr,
5751                                                                           type_sp->GetID());
5752                             }
5753 
5754                             // We found a real definition for this type elsewhere
5755                             // so lets use it and cache the fact that we found
5756                             // a complete type for this die
5757                             m_die_to_type[die] = type_sp.get();
5758                             return type_sp;
5759                         }
5760                     }
5761                     assert (tag_decl_kind != -1);
5762                     bool clang_type_was_created = false;
5763                     clang_type = m_forward_decl_die_to_clang_type.lookup (die);
5764                     if (clang_type == NULL)
5765                     {
5766                         const DWARFDebugInfoEntry *decl_ctx_die;
5767 
5768                         clang::DeclContext *decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
5769                         if (accessibility == eAccessNone && decl_ctx)
5770                         {
5771                             // Check the decl context that contains this class/struct/union.
5772                             // If it is a class we must give it an accessability.
5773                             const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind();
5774                             if (DeclKindIsCXXClass (containing_decl_kind))
5775                                 accessibility = default_accessibility;
5776                         }
5777 
5778                         if (type_name_cstr && strchr (type_name_cstr, '<'))
5779                         {
5780                             ClangASTContext::TemplateParameterInfos template_param_infos;
5781                             if (ParseTemplateParameterInfos (dwarf_cu, die, template_param_infos))
5782                             {
5783                                 clang::ClassTemplateDecl *class_template_decl = ParseClassTemplateDecl (decl_ctx,
5784                                                                                                         accessibility,
5785                                                                                                         type_name_cstr,
5786                                                                                                         tag_decl_kind,
5787                                                                                                         template_param_infos);
5788 
5789                                 clang::ClassTemplateSpecializationDecl *class_specialization_decl = ast.CreateClassTemplateSpecializationDecl (decl_ctx,
5790                                                                                                                                                class_template_decl,
5791                                                                                                                                                tag_decl_kind,
5792                                                                                                                                                template_param_infos);
5793                                 clang_type = ast.CreateClassTemplateSpecializationType (class_specialization_decl);
5794                                 clang_type_was_created = true;
5795 
5796                                 GetClangASTContext().SetMetadataAsUserID ((uintptr_t)class_template_decl, MakeUserID(die->GetOffset()));
5797                                 GetClangASTContext().SetMetadataAsUserID ((uintptr_t)class_specialization_decl, MakeUserID(die->GetOffset()));
5798                             }
5799                         }
5800 
5801                         if (!clang_type_was_created)
5802                         {
5803                             clang_type_was_created = true;
5804                             ClangASTMetadata metadata;
5805                             metadata.SetUserID(MakeUserID(die->GetOffset()));
5806                             clang_type = ast.CreateRecordType (decl_ctx,
5807                                                                accessibility,
5808                                                                type_name_cstr,
5809                                                                tag_decl_kind,
5810                                                                class_language,
5811                                                                &metadata);
5812                         }
5813                     }
5814 
5815                     // Store a forward declaration to this class type in case any
5816                     // parameters in any class methods need it for the clang
5817                     // types for function prototypes.
5818                     LinkDeclContextToDIE(ClangASTContext::GetDeclContextForType(clang_type), die);
5819                     type_sp.reset (new Type (MakeUserID(die->GetOffset()),
5820                                              this,
5821                                              type_name_const_str,
5822                                              byte_size,
5823                                              NULL,
5824                                              LLDB_INVALID_UID,
5825                                              Type::eEncodingIsUID,
5826                                              &decl,
5827                                              clang_type,
5828                                              Type::eResolveStateForward));
5829 
5830                     type_sp->SetIsCompleteObjCClass(is_complete_objc_class);
5831 
5832 
5833                     // Add our type to the unique type map so we don't
5834                     // end up creating many copies of the same type over
5835                     // and over in the ASTContext for our module
5836                     unique_ast_entry.m_type_sp = type_sp;
5837                     unique_ast_entry.m_symfile = this;
5838                     unique_ast_entry.m_cu = dwarf_cu;
5839                     unique_ast_entry.m_die = die;
5840                     unique_ast_entry.m_declaration = decl;
5841                     unique_ast_entry.m_byte_size = byte_size;
5842                     GetUniqueDWARFASTTypeMap().Insert (type_name_const_str,
5843                                                        unique_ast_entry);
5844 
5845                     if (!is_forward_declaration)
5846                     {
5847                         // Always start the definition for a class type so that
5848                         // if the class has child classes or types that require
5849                         // the class to be created for use as their decl contexts
5850                         // the class will be ready to accept these child definitions.
5851                         if (die->HasChildren() == false)
5852                         {
5853                             // No children for this struct/union/class, lets finish it
5854                             ast.StartTagDeclarationDefinition (clang_type);
5855                             ast.CompleteTagDeclarationDefinition (clang_type);
5856 
5857                             if (tag == DW_TAG_structure_type) // this only applies in C
5858                             {
5859                                 clang::QualType qual_type = clang::QualType::getFromOpaquePtr (clang_type);
5860                                 const clang::RecordType *record_type = qual_type->getAs<clang::RecordType> ();
5861 
5862                                 if (record_type)
5863                                 {
5864                                     clang::RecordDecl *record_decl = record_type->getDecl();
5865 
5866                                     if (record_decl)
5867                                     {
5868                                         LayoutInfo layout_info;
5869 
5870                                         layout_info.alignment = 0;
5871                                         layout_info.bit_size = 0;
5872 
5873                                         m_record_decl_to_layout_map.insert(std::make_pair(record_decl, layout_info));
5874                                     }
5875                                 }
5876                             }
5877                         }
5878                         else if (clang_type_was_created)
5879                         {
5880                             // Start the definition if the class is not objective C since
5881                             // the underlying decls respond to isCompleteDefinition(). Objective
5882                             // C decls dont' respond to isCompleteDefinition() so we can't
5883                             // start the declaration definition right away. For C++ classs/union/structs
5884                             // we want to start the definition in case the class is needed as the
5885                             // declaration context for a contained class or type without the need
5886                             // to complete that type..
5887 
5888                             if (class_language != eLanguageTypeObjC &&
5889                                 class_language != eLanguageTypeObjC_plus_plus)
5890                                 ast.StartTagDeclarationDefinition (clang_type);
5891 
5892                             // Leave this as a forward declaration until we need
5893                             // to know the details of the type. lldb_private::Type
5894                             // will automatically call the SymbolFile virtual function
5895                             // "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition(Type *)"
5896                             // When the definition needs to be defined.
5897                             m_forward_decl_die_to_clang_type[die] = clang_type;
5898                             m_forward_decl_clang_type_to_die[ClangASTType::RemoveFastQualifiers (clang_type)] = die;
5899                             ClangASTContext::SetHasExternalStorage (clang_type, true);
5900                         }
5901                     }
5902 
5903                 }
5904                 break;
5905 
5906             case DW_TAG_enumeration_type:
5907                 {
5908                     // Set a bit that lets us know that we are currently parsing this
5909                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5910 
5911                     lldb::user_id_t encoding_uid = DW_INVALID_OFFSET;
5912 
5913                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5914                     if (num_attributes > 0)
5915                     {
5916                         uint32_t i;
5917 
5918                         for (i=0; i<num_attributes; ++i)
5919                         {
5920                             attr = attributes.AttributeAtIndex(i);
5921                             DWARFFormValue form_value;
5922                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5923                             {
5924                                 switch (attr)
5925                                 {
5926                                 case DW_AT_decl_file:       decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
5927                                 case DW_AT_decl_line:       decl.SetLine(form_value.Unsigned()); break;
5928                                 case DW_AT_decl_column:     decl.SetColumn(form_value.Unsigned()); break;
5929                                 case DW_AT_name:
5930                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5931                                     type_name_const_str.SetCString(type_name_cstr);
5932                                     break;
5933                                 case DW_AT_type:            encoding_uid = form_value.Reference(dwarf_cu); break;
5934                                 case DW_AT_byte_size:       byte_size = form_value.Unsigned(); break;
5935                                 case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
5936                                 case DW_AT_declaration:     break; //is_forward_declaration = form_value.Unsigned() != 0; break;
5937                                 case DW_AT_allocated:
5938                                 case DW_AT_associated:
5939                                 case DW_AT_bit_stride:
5940                                 case DW_AT_byte_stride:
5941                                 case DW_AT_data_location:
5942                                 case DW_AT_description:
5943                                 case DW_AT_start_scope:
5944                                 case DW_AT_visibility:
5945                                 case DW_AT_specification:
5946                                 case DW_AT_abstract_origin:
5947                                 case DW_AT_sibling:
5948                                     break;
5949                                 }
5950                             }
5951                         }
5952 
5953                         DEBUG_PRINTF ("0x%8.8llx: %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
5954 
5955                         clang_type_t enumerator_clang_type = NULL;
5956                         clang_type = m_forward_decl_die_to_clang_type.lookup (die);
5957                         if (clang_type == NULL)
5958                         {
5959                             enumerator_clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (NULL,
5960                                                                                                   DW_ATE_signed,
5961                                                                                                   byte_size * 8);
5962                             clang_type = ast.CreateEnumerationType (type_name_cstr,
5963                                                                     GetClangDeclContextContainingDIE (dwarf_cu, die, NULL),
5964                                                                     decl,
5965                                                                     enumerator_clang_type);
5966                         }
5967                         else
5968                         {
5969                             enumerator_clang_type = ClangASTContext::GetEnumerationIntegerType (clang_type);
5970                             assert (enumerator_clang_type != NULL);
5971                         }
5972 
5973                         LinkDeclContextToDIE(ClangASTContext::GetDeclContextForType(clang_type), die);
5974 
5975                         type_sp.reset( new Type (MakeUserID(die->GetOffset()),
5976                                                  this,
5977                                                  type_name_const_str,
5978                                                  byte_size,
5979                                                  NULL,
5980                                                  encoding_uid,
5981                                                  Type::eEncodingIsUID,
5982                                                  &decl,
5983                                                  clang_type,
5984                                                  Type::eResolveStateForward));
5985 
5986                         ast.StartTagDeclarationDefinition (clang_type);
5987                         if (die->HasChildren())
5988                         {
5989                             SymbolContext cu_sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
5990                             ParseChildEnumerators(cu_sc, clang_type, type_sp->GetByteSize(), dwarf_cu, die);
5991                         }
5992                         ast.CompleteTagDeclarationDefinition (clang_type);
5993                     }
5994                 }
5995                 break;
5996 
5997             case DW_TAG_inlined_subroutine:
5998             case DW_TAG_subprogram:
5999             case DW_TAG_subroutine_type:
6000                 {
6001                     // Set a bit that lets us know that we are currently parsing this
6002                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6003 
6004                     //const char *mangled = NULL;
6005                     dw_offset_t type_die_offset = DW_INVALID_OFFSET;
6006                     bool is_variadic = false;
6007                     bool is_inline = false;
6008                     bool is_static = false;
6009                     bool is_virtual = false;
6010                     bool is_explicit = false;
6011                     bool is_artificial = false;
6012                     dw_offset_t specification_die_offset = DW_INVALID_OFFSET;
6013                     dw_offset_t abstract_origin_die_offset = DW_INVALID_OFFSET;
6014                     dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET;
6015 
6016                     unsigned type_quals = 0;
6017                     clang::StorageClass storage = clang::SC_None;//, Extern, Static, PrivateExtern
6018 
6019 
6020                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6021                     if (num_attributes > 0)
6022                     {
6023                         uint32_t i;
6024                         for (i=0; i<num_attributes; ++i)
6025                         {
6026                             attr = attributes.AttributeAtIndex(i);
6027                             DWARFFormValue form_value;
6028                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6029                             {
6030                                 switch (attr)
6031                                 {
6032                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6033                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6034                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6035                                 case DW_AT_name:
6036                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6037                                     type_name_const_str.SetCString(type_name_cstr);
6038                                     break;
6039 
6040                                 case DW_AT_MIPS_linkage_name:   break; // mangled = form_value.AsCString(&get_debug_str_data()); break;
6041                                 case DW_AT_type:                type_die_offset = form_value.Reference(dwarf_cu); break;
6042                                 case DW_AT_accessibility:       accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6043                                 case DW_AT_declaration:         break; // is_forward_declaration = form_value.Unsigned() != 0; break;
6044                                 case DW_AT_inline:              is_inline = form_value.Unsigned() != 0; break;
6045                                 case DW_AT_virtuality:          is_virtual = form_value.Unsigned() != 0;  break;
6046                                 case DW_AT_explicit:            is_explicit = form_value.Unsigned() != 0;  break;
6047                                 case DW_AT_artificial:          is_artificial = form_value.Unsigned() != 0;  break;
6048 
6049 
6050                                 case DW_AT_external:
6051                                     if (form_value.Unsigned())
6052                                     {
6053                                         if (storage == clang::SC_None)
6054                                             storage = clang::SC_Extern;
6055                                         else
6056                                             storage = clang::SC_PrivateExtern;
6057                                     }
6058                                     break;
6059 
6060                                 case DW_AT_specification:
6061                                     specification_die_offset = form_value.Reference(dwarf_cu);
6062                                     break;
6063 
6064                                 case DW_AT_abstract_origin:
6065                                     abstract_origin_die_offset = form_value.Reference(dwarf_cu);
6066                                     break;
6067 
6068                                 case DW_AT_object_pointer:
6069                                     object_pointer_die_offset = form_value.Reference(dwarf_cu);
6070                                     break;
6071 
6072                                 case DW_AT_allocated:
6073                                 case DW_AT_associated:
6074                                 case DW_AT_address_class:
6075                                 case DW_AT_calling_convention:
6076                                 case DW_AT_data_location:
6077                                 case DW_AT_elemental:
6078                                 case DW_AT_entry_pc:
6079                                 case DW_AT_frame_base:
6080                                 case DW_AT_high_pc:
6081                                 case DW_AT_low_pc:
6082                                 case DW_AT_prototyped:
6083                                 case DW_AT_pure:
6084                                 case DW_AT_ranges:
6085                                 case DW_AT_recursive:
6086                                 case DW_AT_return_addr:
6087                                 case DW_AT_segment:
6088                                 case DW_AT_start_scope:
6089                                 case DW_AT_static_link:
6090                                 case DW_AT_trampoline:
6091                                 case DW_AT_visibility:
6092                                 case DW_AT_vtable_elem_location:
6093                                 case DW_AT_description:
6094                                 case DW_AT_sibling:
6095                                     break;
6096                                 }
6097                             }
6098                         }
6099                     }
6100 
6101                     std::string object_pointer_name;
6102                     if (object_pointer_die_offset != DW_INVALID_OFFSET)
6103                     {
6104                         // Get the name from the object pointer die
6105                         StreamString s;
6106                         if (DWARFDebugInfoEntry::GetName (this, dwarf_cu, object_pointer_die_offset, s))
6107                         {
6108                             object_pointer_name.assign(s.GetData());
6109                         }
6110                     }
6111 
6112                     DEBUG_PRINTF ("0x%8.8llx: %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6113 
6114                     clang_type_t return_clang_type = NULL;
6115                     Type *func_type = NULL;
6116 
6117                     if (type_die_offset != DW_INVALID_OFFSET)
6118                         func_type = ResolveTypeUID(type_die_offset);
6119 
6120                     if (func_type)
6121                         return_clang_type = func_type->GetClangForwardType();
6122                     else
6123                         return_clang_type = ast.GetBuiltInType_void();
6124 
6125 
6126                     std::vector<clang_type_t> function_param_types;
6127                     std::vector<clang::ParmVarDecl*> function_param_decls;
6128 
6129                     // Parse the function children for the parameters
6130 
6131                     const DWARFDebugInfoEntry *decl_ctx_die = NULL;
6132                     clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
6133                     const clang::Decl::Kind containing_decl_kind = containing_decl_ctx->getDeclKind();
6134 
6135                     const bool is_cxx_method = DeclKindIsCXXClass (containing_decl_kind);
6136                     // Start off static. This will be set to false in ParseChildParameters(...)
6137                     // if we find a "this" paramters as the first parameter
6138                     if (is_cxx_method)
6139                         is_static = true;
6140                     ClangASTContext::TemplateParameterInfos template_param_infos;
6141 
6142                     if (die->HasChildren())
6143                     {
6144                         bool skip_artificial = true;
6145                         ParseChildParameters (sc,
6146                                               containing_decl_ctx,
6147                                               dwarf_cu,
6148                                               die,
6149                                               skip_artificial,
6150                                               is_static,
6151                                               type_list,
6152                                               function_param_types,
6153                                               function_param_decls,
6154                                               type_quals,
6155                                               template_param_infos);
6156                     }
6157 
6158                     // clang_type will get the function prototype clang type after this call
6159                     clang_type = ast.CreateFunctionType (return_clang_type,
6160                                                          function_param_types.data(),
6161                                                          function_param_types.size(),
6162                                                          is_variadic,
6163                                                          type_quals);
6164 
6165                     if (type_name_cstr)
6166                     {
6167                         bool type_handled = false;
6168                         if (tag == DW_TAG_subprogram)
6169                         {
6170                             ConstString class_name;
6171                             ConstString class_name_no_category;
6172                             if (ObjCLanguageRuntime::ParseMethodName (type_name_cstr, &class_name, NULL, NULL, &class_name_no_category))
6173                             {
6174                                 // Use the class name with no category if there is one
6175                                 if (class_name_no_category)
6176                                     class_name = class_name_no_category;
6177 
6178                                 SymbolContext empty_sc;
6179                                 clang_type_t class_opaque_type = NULL;
6180                                 if (class_name)
6181                                 {
6182                                     TypeList types;
6183                                     TypeSP complete_objc_class_type_sp (FindCompleteObjCDefinitionTypeForDIE (NULL, class_name, false));
6184 
6185                                     if (complete_objc_class_type_sp)
6186                                     {
6187                                         clang_type_t type_clang_forward_type = complete_objc_class_type_sp->GetClangForwardType();
6188                                         if (ClangASTContext::IsObjCClassType (type_clang_forward_type))
6189                                             class_opaque_type = type_clang_forward_type;
6190                                     }
6191                                 }
6192 
6193                                 if (class_opaque_type)
6194                                 {
6195                                     // If accessibility isn't set to anything valid, assume public for
6196                                     // now...
6197                                     if (accessibility == eAccessNone)
6198                                         accessibility = eAccessPublic;
6199 
6200                                     clang::ObjCMethodDecl *objc_method_decl = ast.AddMethodToObjCObjectType (class_opaque_type,
6201                                                                                                              type_name_cstr,
6202                                                                                                              clang_type,
6203                                                                                                              accessibility);
6204                                     type_handled = objc_method_decl != NULL;
6205                                     if (type_handled)
6206                                     {
6207                                         LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(objc_method_decl), die);
6208                                         GetClangASTContext().SetMetadataAsUserID ((uintptr_t)objc_method_decl, MakeUserID(die->GetOffset()));
6209                                     }
6210                                 }
6211                             }
6212                             else if (is_cxx_method)
6213                             {
6214                                 // Look at the parent of this DIE and see if is is
6215                                 // a class or struct and see if this is actually a
6216                                 // C++ method
6217                                 Type *class_type = ResolveType (dwarf_cu, decl_ctx_die);
6218                                 if (class_type)
6219                                 {
6220                                     if (class_type->GetID() != MakeUserID(decl_ctx_die->GetOffset()))
6221                                     {
6222                                         // We uniqued the parent class of this function to another class
6223                                         // so we now need to associate all dies under "decl_ctx_die" to
6224                                         // DIEs in the DIE for "class_type"...
6225                                         DWARFCompileUnitSP class_type_cu_sp;
6226                                         const DWARFDebugInfoEntry *class_type_die = DebugInfo()->GetDIEPtr(class_type->GetID(), &class_type_cu_sp);
6227                                         if (class_type_die)
6228                                         {
6229                                             if (CopyUniqueClassMethodTypes (class_type,
6230                                                                             class_type_cu_sp.get(),
6231                                                                             class_type_die,
6232                                                                             dwarf_cu,
6233                                                                             decl_ctx_die))
6234                                             {
6235                                                 type_ptr = m_die_to_type[die];
6236                                                 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6237                                                 {
6238                                                     type_sp = type_ptr->shared_from_this();
6239                                                     break;
6240                                                 }
6241                                             }
6242                                         }
6243                                     }
6244 
6245                                     if (specification_die_offset != DW_INVALID_OFFSET)
6246                                     {
6247                                         // We have a specification which we are going to base our function
6248                                         // prototype off of, so we need this type to be completed so that the
6249                                         // m_die_to_decl_ctx for the method in the specification has a valid
6250                                         // clang decl context.
6251                                         class_type->GetClangForwardType();
6252                                         // If we have a specification, then the function type should have been
6253                                         // made with the specification and not with this die.
6254                                         DWARFCompileUnitSP spec_cu_sp;
6255                                         const DWARFDebugInfoEntry* spec_die = DebugInfo()->GetDIEPtr(specification_die_offset, &spec_cu_sp);
6256                                         clang::DeclContext *spec_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, spec_die);
6257                                         if (spec_clang_decl_ctx)
6258                                         {
6259                                             LinkDeclContextToDIE(spec_clang_decl_ctx, die);
6260                                         }
6261                                         else
6262                                         {
6263                                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8llx: DW_AT_specification(0x%8.8x) has no decl\n",
6264                                                                                          MakeUserID(die->GetOffset()),
6265                                                                                          specification_die_offset);
6266                                         }
6267                                         type_handled = true;
6268                                     }
6269                                     else if (abstract_origin_die_offset != DW_INVALID_OFFSET)
6270                                     {
6271                                         // We have a specification which we are going to base our function
6272                                         // prototype off of, so we need this type to be completed so that the
6273                                         // m_die_to_decl_ctx for the method in the abstract origin has a valid
6274                                         // clang decl context.
6275                                         class_type->GetClangForwardType();
6276 
6277                                         DWARFCompileUnitSP abs_cu_sp;
6278                                         const DWARFDebugInfoEntry* abs_die = DebugInfo()->GetDIEPtr(abstract_origin_die_offset, &abs_cu_sp);
6279                                         clang::DeclContext *abs_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, abs_die);
6280                                         if (abs_clang_decl_ctx)
6281                                         {
6282                                             LinkDeclContextToDIE (abs_clang_decl_ctx, die);
6283                                         }
6284                                         else
6285                                         {
6286                                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8llx: DW_AT_abstract_origin(0x%8.8x) has no decl\n",
6287                                                                                          MakeUserID(die->GetOffset()),
6288                                                                                          abstract_origin_die_offset);
6289                                         }
6290                                         type_handled = true;
6291                                     }
6292                                     else
6293                                     {
6294                                         clang_type_t class_opaque_type = class_type->GetClangForwardType();
6295                                         if (ClangASTContext::IsCXXClassType (class_opaque_type))
6296                                         {
6297                                             if (ClangASTContext::IsBeingDefined (class_opaque_type))
6298                                             {
6299                                                 // Neither GCC 4.2 nor clang++ currently set a valid accessibility
6300                                                 // in the DWARF for C++ methods... Default to public for now...
6301                                                 if (accessibility == eAccessNone)
6302                                                     accessibility = eAccessPublic;
6303 
6304                                                 if (!is_static && !die->HasChildren())
6305                                                 {
6306                                                     // We have a C++ member function with no children (this pointer!)
6307                                                     // and clang will get mad if we try and make a function that isn't
6308                                                     // well formed in the DWARF, so we will just skip it...
6309                                                     type_handled = true;
6310                                                 }
6311                                                 else
6312                                                 {
6313                                                     clang::CXXMethodDecl *cxx_method_decl;
6314                                                     // REMOVE THE CRASH DESCRIPTION BELOW
6315                                                     Host::SetCrashDescriptionWithFormat ("SymbolFileDWARF::ParseType() is adding a method %s to class %s in DIE 0x%8.8llx from %s/%s",
6316                                                                                          type_name_cstr,
6317                                                                                          class_type->GetName().GetCString(),
6318                                                                                          MakeUserID(die->GetOffset()),
6319                                                                                          m_obj_file->GetFileSpec().GetDirectory().GetCString(),
6320                                                                                          m_obj_file->GetFileSpec().GetFilename().GetCString());
6321 
6322                                                     const bool is_attr_used = false;
6323 
6324                                                     cxx_method_decl = ast.AddMethodToCXXRecordType (class_opaque_type,
6325                                                                                                     type_name_cstr,
6326                                                                                                     clang_type,
6327                                                                                                     accessibility,
6328                                                                                                     is_virtual,
6329                                                                                                     is_static,
6330                                                                                                     is_inline,
6331                                                                                                     is_explicit,
6332                                                                                                     is_attr_used,
6333                                                                                                     is_artificial);
6334 
6335                                                     type_handled = cxx_method_decl != NULL;
6336 
6337                                                     if (type_handled)
6338                                                     {
6339                                                         LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(cxx_method_decl), die);
6340 
6341                                                         Host::SetCrashDescription (NULL);
6342 
6343 
6344                                                         ClangASTMetadata metadata;
6345                                                         metadata.SetUserID(MakeUserID(die->GetOffset()));
6346 
6347                                                         if (!object_pointer_name.empty())
6348                                                         {
6349                                                             metadata.SetObjectPtrName(object_pointer_name.c_str());
6350                                                             if (log)
6351                                                                 log->Printf ("Setting object pointer name: %s on method object 0x%ld.\n",
6352                                                                              object_pointer_name.c_str(),
6353                                                                              (uintptr_t) cxx_method_decl);
6354                                                         }
6355                                                         GetClangASTContext().SetMetadata ((uintptr_t)cxx_method_decl, metadata);
6356                                                     }
6357                                                 }
6358                                             }
6359                                             else
6360                                             {
6361                                                 // We were asked to parse the type for a method in a class, yet the
6362                                                 // class hasn't been asked to complete itself through the
6363                                                 // clang::ExternalASTSource protocol, so we need to just have the
6364                                                 // class complete itself and do things the right way, then our
6365                                                 // DIE should then have an entry in the m_die_to_type map. First
6366                                                 // we need to modify the m_die_to_type so it doesn't think we are
6367                                                 // trying to parse this DIE anymore...
6368                                                 m_die_to_type[die] = NULL;
6369 
6370                                                 // Now we get the full type to force our class type to complete itself
6371                                                 // using the clang::ExternalASTSource protocol which will parse all
6372                                                 // base classes and all methods (including the method for this DIE).
6373                                                 class_type->GetClangFullType();
6374 
6375                                                 // The type for this DIE should have been filled in the function call above
6376                                                 type_ptr = m_die_to_type[die];
6377                                                 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6378                                                 {
6379                                                     type_sp = type_ptr->shared_from_this();
6380                                                     break;
6381                                                 }
6382 
6383                                                 // FIXME This is fixing some even uglier behavior but we really need to
6384                                                 // uniq the methods of each class as well as the class itself.
6385                                                 // <rdar://problem/11240464>
6386                                                 type_handled = true;
6387                                             }
6388                                         }
6389                                     }
6390                                 }
6391                             }
6392                         }
6393 
6394                         if (!type_handled)
6395                         {
6396                             // We just have a function that isn't part of a class
6397                             clang::FunctionDecl *function_decl = ast.CreateFunctionDeclaration (containing_decl_ctx,
6398                                                                                                 type_name_cstr,
6399                                                                                                 clang_type,
6400                                                                                                 storage,
6401                                                                                                 is_inline);
6402 
6403 //                            if (template_param_infos.GetSize() > 0)
6404 //                            {
6405 //                                clang::FunctionTemplateDecl *func_template_decl = ast.CreateFunctionTemplateDecl (containing_decl_ctx,
6406 //                                                                                                                  function_decl,
6407 //                                                                                                                  type_name_cstr,
6408 //                                                                                                                  template_param_infos);
6409 //
6410 //                                ast.CreateFunctionTemplateSpecializationInfo (function_decl,
6411 //                                                                              func_template_decl,
6412 //                                                                              template_param_infos);
6413 //                            }
6414                             // Add the decl to our DIE to decl context map
6415                             assert (function_decl);
6416                             LinkDeclContextToDIE(function_decl, die);
6417                             if (!function_param_decls.empty())
6418                                 ast.SetFunctionParameters (function_decl,
6419                                                            &function_param_decls.front(),
6420                                                            function_param_decls.size());
6421 
6422                             ClangASTMetadata metadata;
6423                             metadata.SetUserID(MakeUserID(die->GetOffset()));
6424 
6425                             if (!object_pointer_name.empty())
6426                             {
6427                                 metadata.SetObjectPtrName(object_pointer_name.c_str());
6428                                 if (log)
6429                                     log->Printf ("Setting object pointer name: %s on function object 0x%ld.\n",
6430                                                  object_pointer_name.c_str(),
6431                                                  (uintptr_t) function_decl);
6432                             }
6433                             GetClangASTContext().SetMetadata ((uintptr_t)function_decl, metadata);
6434                         }
6435                     }
6436                     type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6437                                              this,
6438                                              type_name_const_str,
6439                                              0,
6440                                              NULL,
6441                                              LLDB_INVALID_UID,
6442                                              Type::eEncodingIsUID,
6443                                              &decl,
6444                                              clang_type,
6445                                              Type::eResolveStateFull));
6446                     assert(type_sp.get());
6447                 }
6448                 break;
6449 
6450             case DW_TAG_array_type:
6451                 {
6452                     // Set a bit that lets us know that we are currently parsing this
6453                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6454 
6455                     lldb::user_id_t type_die_offset = DW_INVALID_OFFSET;
6456                     int64_t first_index = 0;
6457                     uint32_t byte_stride = 0;
6458                     uint32_t bit_stride = 0;
6459                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6460 
6461                     if (num_attributes > 0)
6462                     {
6463                         uint32_t i;
6464                         for (i=0; i<num_attributes; ++i)
6465                         {
6466                             attr = attributes.AttributeAtIndex(i);
6467                             DWARFFormValue form_value;
6468                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6469                             {
6470                                 switch (attr)
6471                                 {
6472                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6473                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6474                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6475                                 case DW_AT_name:
6476                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6477                                     type_name_const_str.SetCString(type_name_cstr);
6478                                     break;
6479 
6480                                 case DW_AT_type:            type_die_offset = form_value.Reference(dwarf_cu); break;
6481                                 case DW_AT_byte_size:       break; // byte_size = form_value.Unsigned(); break;
6482                                 case DW_AT_byte_stride:     byte_stride = form_value.Unsigned(); break;
6483                                 case DW_AT_bit_stride:      bit_stride = form_value.Unsigned(); break;
6484                                 case DW_AT_accessibility:   break; // accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6485                                 case DW_AT_declaration:     break; // is_forward_declaration = form_value.Unsigned() != 0; break;
6486                                 case DW_AT_allocated:
6487                                 case DW_AT_associated:
6488                                 case DW_AT_data_location:
6489                                 case DW_AT_description:
6490                                 case DW_AT_ordering:
6491                                 case DW_AT_start_scope:
6492                                 case DW_AT_visibility:
6493                                 case DW_AT_specification:
6494                                 case DW_AT_abstract_origin:
6495                                 case DW_AT_sibling:
6496                                     break;
6497                                 }
6498                             }
6499                         }
6500 
6501                         DEBUG_PRINTF ("0x%8.8llx: %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6502 
6503                         Type *element_type = ResolveTypeUID(type_die_offset);
6504 
6505                         if (element_type)
6506                         {
6507                             std::vector<uint64_t> element_orders;
6508                             ParseChildArrayInfo(sc, dwarf_cu, die, first_index, element_orders, byte_stride, bit_stride);
6509                             if (byte_stride == 0 && bit_stride == 0)
6510                                 byte_stride = element_type->GetByteSize();
6511                             clang_type_t array_element_type = element_type->GetClangForwardType();
6512                             uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
6513                             uint64_t num_elements = 0;
6514                             std::vector<uint64_t>::const_reverse_iterator pos;
6515                             std::vector<uint64_t>::const_reverse_iterator end = element_orders.rend();
6516                             for (pos = element_orders.rbegin(); pos != end; ++pos)
6517                             {
6518                                 num_elements = *pos;
6519                                 clang_type = ast.CreateArrayType (array_element_type,
6520                                                                   num_elements,
6521                                                                   num_elements * array_element_bit_stride);
6522                                 array_element_type = clang_type;
6523                                 array_element_bit_stride = array_element_bit_stride * num_elements;
6524                             }
6525                             ConstString empty_name;
6526                             type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6527                                                      this,
6528                                                      empty_name,
6529                                                      array_element_bit_stride / 8,
6530                                                      NULL,
6531                                                      type_die_offset,
6532                                                      Type::eEncodingIsUID,
6533                                                      &decl,
6534                                                      clang_type,
6535                                                      Type::eResolveStateFull));
6536                             type_sp->SetEncodingType (element_type);
6537                         }
6538                     }
6539                 }
6540                 break;
6541 
6542             case DW_TAG_ptr_to_member_type:
6543                 {
6544                     dw_offset_t type_die_offset = DW_INVALID_OFFSET;
6545                     dw_offset_t containing_type_die_offset = DW_INVALID_OFFSET;
6546 
6547                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6548 
6549                     if (num_attributes > 0) {
6550                         uint32_t i;
6551                         for (i=0; i<num_attributes; ++i)
6552                         {
6553                             attr = attributes.AttributeAtIndex(i);
6554                             DWARFFormValue form_value;
6555                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6556                             {
6557                                 switch (attr)
6558                                 {
6559                                     case DW_AT_type:
6560                                         type_die_offset = form_value.Reference(dwarf_cu); break;
6561                                     case DW_AT_containing_type:
6562                                         containing_type_die_offset = form_value.Reference(dwarf_cu); break;
6563                                 }
6564                             }
6565                         }
6566 
6567                         Type *pointee_type = ResolveTypeUID(type_die_offset);
6568                         Type *class_type = ResolveTypeUID(containing_type_die_offset);
6569 
6570                         clang_type_t pointee_clang_type = pointee_type->GetClangForwardType();
6571                         clang_type_t class_clang_type = class_type->GetClangLayoutType();
6572 
6573                         clang_type = ast.CreateMemberPointerType(pointee_clang_type,
6574                                                                  class_clang_type);
6575 
6576                         byte_size = ClangASTType::GetClangTypeBitWidth (ast.getASTContext(),
6577                                                                        clang_type) / 8;
6578 
6579                         type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6580                                                  this,
6581                                                  type_name_const_str,
6582                                                  byte_size,
6583                                                  NULL,
6584                                                  LLDB_INVALID_UID,
6585                                                  Type::eEncodingIsUID,
6586                                                  NULL,
6587                                                  clang_type,
6588                                                  Type::eResolveStateForward));
6589                     }
6590 
6591                     break;
6592                 }
6593             default:
6594                 GetObjectFile()->GetModule()->ReportError ("{0x%8.8x}: unhandled type tag 0x%4.4x (%s), please file a bug and attach the file at the start of this error message",
6595                                                            die->GetOffset(),
6596                                                            tag,
6597                                                            DW_TAG_value_to_name(tag));
6598                 break;
6599             }
6600 
6601             if (type_sp.get())
6602             {
6603                 const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
6604                 dw_tag_t sc_parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
6605 
6606                 SymbolContextScope * symbol_context_scope = NULL;
6607                 if (sc_parent_tag == DW_TAG_compile_unit)
6608                 {
6609                     symbol_context_scope = sc.comp_unit;
6610                 }
6611                 else if (sc.function != NULL)
6612                 {
6613                     symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
6614                     if (symbol_context_scope == NULL)
6615                         symbol_context_scope = sc.function;
6616                 }
6617 
6618                 if (symbol_context_scope != NULL)
6619                 {
6620                     type_sp->SetSymbolContextScope(symbol_context_scope);
6621                 }
6622 
6623                 // We are ready to put this type into the uniqued list up at the module level
6624                 type_list->Insert (type_sp);
6625 
6626                 m_die_to_type[die] = type_sp.get();
6627             }
6628         }
6629         else if (type_ptr != DIE_IS_BEING_PARSED)
6630         {
6631             type_sp = type_ptr->shared_from_this();
6632         }
6633     }
6634     return type_sp;
6635 }
6636 
6637 size_t
6638 SymbolFileDWARF::ParseTypes
6639 (
6640     const SymbolContext& sc,
6641     DWARFCompileUnit* dwarf_cu,
6642     const DWARFDebugInfoEntry *die,
6643     bool parse_siblings,
6644     bool parse_children
6645 )
6646 {
6647     size_t types_added = 0;
6648     while (die != NULL)
6649     {
6650         bool type_is_new = false;
6651         if (ParseType(sc, dwarf_cu, die, &type_is_new).get())
6652         {
6653             if (type_is_new)
6654                 ++types_added;
6655         }
6656 
6657         if (parse_children && die->HasChildren())
6658         {
6659             if (die->Tag() == DW_TAG_subprogram)
6660             {
6661                 SymbolContext child_sc(sc);
6662                 child_sc.function = sc.comp_unit->FindFunctionByUID(MakeUserID(die->GetOffset())).get();
6663                 types_added += ParseTypes(child_sc, dwarf_cu, die->GetFirstChild(), true, true);
6664             }
6665             else
6666                 types_added += ParseTypes(sc, dwarf_cu, die->GetFirstChild(), true, true);
6667         }
6668 
6669         if (parse_siblings)
6670             die = die->GetSibling();
6671         else
6672             die = NULL;
6673     }
6674     return types_added;
6675 }
6676 
6677 
6678 size_t
6679 SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext &sc)
6680 {
6681     assert(sc.comp_unit && sc.function);
6682     size_t functions_added = 0;
6683     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
6684     if (dwarf_cu)
6685     {
6686         dw_offset_t function_die_offset = sc.function->GetID();
6687         const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(function_die_offset);
6688         if (function_die)
6689         {
6690             ParseFunctionBlocks(sc, &sc.function->GetBlock (false), dwarf_cu, function_die, LLDB_INVALID_ADDRESS, 0);
6691         }
6692     }
6693 
6694     return functions_added;
6695 }
6696 
6697 
6698 size_t
6699 SymbolFileDWARF::ParseTypes (const SymbolContext &sc)
6700 {
6701     // At least a compile unit must be valid
6702     assert(sc.comp_unit);
6703     size_t types_added = 0;
6704     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
6705     if (dwarf_cu)
6706     {
6707         if (sc.function)
6708         {
6709             dw_offset_t function_die_offset = sc.function->GetID();
6710             const DWARFDebugInfoEntry *func_die = dwarf_cu->GetDIEPtr(function_die_offset);
6711             if (func_die && func_die->HasChildren())
6712             {
6713                 types_added = ParseTypes(sc, dwarf_cu, func_die->GetFirstChild(), true, true);
6714             }
6715         }
6716         else
6717         {
6718             const DWARFDebugInfoEntry *dwarf_cu_die = dwarf_cu->DIE();
6719             if (dwarf_cu_die && dwarf_cu_die->HasChildren())
6720             {
6721                 types_added = ParseTypes(sc, dwarf_cu, dwarf_cu_die->GetFirstChild(), true, true);
6722             }
6723         }
6724     }
6725 
6726     return types_added;
6727 }
6728 
6729 size_t
6730 SymbolFileDWARF::ParseVariablesForContext (const SymbolContext& sc)
6731 {
6732     if (sc.comp_unit != NULL)
6733     {
6734         DWARFDebugInfo* info = DebugInfo();
6735         if (info == NULL)
6736             return 0;
6737 
6738         uint32_t cu_idx = UINT32_MAX;
6739         DWARFCompileUnit* dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID(), &cu_idx).get();
6740 
6741         if (dwarf_cu == NULL)
6742             return 0;
6743 
6744         if (sc.function)
6745         {
6746             const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(sc.function->GetID());
6747 
6748             dw_addr_t func_lo_pc = function_die->GetAttributeValueAsUnsigned (this, dwarf_cu, DW_AT_low_pc, DW_INVALID_ADDRESS);
6749             if (func_lo_pc != DW_INVALID_ADDRESS)
6750             {
6751                 const size_t num_variables = ParseVariables(sc, dwarf_cu, func_lo_pc, function_die->GetFirstChild(), true, true);
6752 
6753                 // Let all blocks know they have parse all their variables
6754                 sc.function->GetBlock (false).SetDidParseVariables (true, true);
6755                 return num_variables;
6756             }
6757         }
6758         else if (sc.comp_unit)
6759         {
6760             uint32_t vars_added = 0;
6761             VariableListSP variables (sc.comp_unit->GetVariableList(false));
6762 
6763             if (variables.get() == NULL)
6764             {
6765                 variables.reset(new VariableList());
6766                 sc.comp_unit->SetVariableList(variables);
6767 
6768                 DWARFCompileUnit* match_dwarf_cu = NULL;
6769                 const DWARFDebugInfoEntry* die = NULL;
6770                 DIEArray die_offsets;
6771                 if (m_using_apple_tables)
6772                 {
6773                     if (m_apple_names_ap.get())
6774                     {
6775                         DWARFMappedHash::DIEInfoArray hash_data_array;
6776                         if (m_apple_names_ap->AppendAllDIEsInRange (dwarf_cu->GetOffset(),
6777                                                                     dwarf_cu->GetNextCompileUnitOffset(),
6778                                                                     hash_data_array))
6779                         {
6780                             DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
6781                         }
6782                     }
6783                 }
6784                 else
6785                 {
6786                     // Index if we already haven't to make sure the compile units
6787                     // get indexed and make their global DIE index list
6788                     if (!m_indexed)
6789                         Index ();
6790 
6791                     m_global_index.FindAllEntriesForCompileUnit (dwarf_cu->GetOffset(),
6792                                                                  dwarf_cu->GetNextCompileUnitOffset(),
6793                                                                  die_offsets);
6794                 }
6795 
6796                 const size_t num_matches = die_offsets.size();
6797                 if (num_matches)
6798                 {
6799                     DWARFDebugInfo* debug_info = DebugInfo();
6800                     for (size_t i=0; i<num_matches; ++i)
6801                     {
6802                         const dw_offset_t die_offset = die_offsets[i];
6803                         die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &match_dwarf_cu);
6804                         if (die)
6805                         {
6806                             VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, LLDB_INVALID_ADDRESS));
6807                             if (var_sp)
6808                             {
6809                                 variables->AddVariableIfUnique (var_sp);
6810                                 ++vars_added;
6811                             }
6812                         }
6813                         else
6814                         {
6815                             if (m_using_apple_tables)
6816                             {
6817                                 GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x)\n", die_offset);
6818                             }
6819                         }
6820 
6821                     }
6822                 }
6823             }
6824             return vars_added;
6825         }
6826     }
6827     return 0;
6828 }
6829 
6830 
6831 VariableSP
6832 SymbolFileDWARF::ParseVariableDIE
6833 (
6834     const SymbolContext& sc,
6835     DWARFCompileUnit* dwarf_cu,
6836     const DWARFDebugInfoEntry *die,
6837     const lldb::addr_t func_low_pc
6838 )
6839 {
6840 
6841     VariableSP var_sp (m_die_to_variable_sp[die]);
6842     if (var_sp)
6843         return var_sp;  // Already been parsed!
6844 
6845     const dw_tag_t tag = die->Tag();
6846 
6847     if ((tag == DW_TAG_variable) ||
6848         (tag == DW_TAG_constant) ||
6849         (tag == DW_TAG_formal_parameter && sc.function))
6850     {
6851         DWARFDebugInfoEntry::Attributes attributes;
6852         const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6853         if (num_attributes > 0)
6854         {
6855             const char *name = NULL;
6856             const char *mangled = NULL;
6857             Declaration decl;
6858             uint32_t i;
6859             lldb::user_id_t type_uid = LLDB_INVALID_UID;
6860             DWARFExpression location;
6861             bool is_external = false;
6862             bool is_artificial = false;
6863             bool location_is_const_value_data = false;
6864             //AccessType accessibility = eAccessNone;
6865 
6866             for (i=0; i<num_attributes; ++i)
6867             {
6868                 dw_attr_t attr = attributes.AttributeAtIndex(i);
6869                 DWARFFormValue form_value;
6870                 if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6871                 {
6872                     switch (attr)
6873                     {
6874                     case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6875                     case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6876                     case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6877                     case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
6878                     case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(&get_debug_str_data()); break;
6879                     case DW_AT_type:        type_uid = form_value.Reference(dwarf_cu); break;
6880                     case DW_AT_external:    is_external = form_value.Unsigned() != 0; break;
6881                     case DW_AT_const_value:
6882                         location_is_const_value_data = true;
6883                         // Fall through...
6884                     case DW_AT_location:
6885                         {
6886                             if (form_value.BlockData())
6887                             {
6888                                 const DataExtractor& debug_info_data = get_debug_info_data();
6889 
6890                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
6891                                 uint32_t block_length = form_value.Unsigned();
6892                                 location.CopyOpcodeData(get_debug_info_data(), block_offset, block_length);
6893                             }
6894                             else
6895                             {
6896                                 const DataExtractor&    debug_loc_data = get_debug_loc_data();
6897                                 const dw_offset_t debug_loc_offset = form_value.Unsigned();
6898 
6899                                 size_t loc_list_length = DWARFLocationList::Size(debug_loc_data, debug_loc_offset);
6900                                 if (loc_list_length > 0)
6901                                 {
6902                                     location.CopyOpcodeData(debug_loc_data, debug_loc_offset, loc_list_length);
6903                                     assert (func_low_pc != LLDB_INVALID_ADDRESS);
6904                                     location.SetLocationListSlide (func_low_pc - dwarf_cu->GetBaseAddress());
6905                                 }
6906                             }
6907                         }
6908                         break;
6909 
6910                     case DW_AT_artificial:      is_artificial = form_value.Unsigned() != 0; break;
6911                     case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6912                     case DW_AT_declaration:
6913                     case DW_AT_description:
6914                     case DW_AT_endianity:
6915                     case DW_AT_segment:
6916                     case DW_AT_start_scope:
6917                     case DW_AT_visibility:
6918                     default:
6919                     case DW_AT_abstract_origin:
6920                     case DW_AT_sibling:
6921                     case DW_AT_specification:
6922                         break;
6923                     }
6924                 }
6925             }
6926 
6927             if (location.IsValid())
6928             {
6929                 ValueType scope = eValueTypeInvalid;
6930 
6931                 const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
6932                 dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
6933                 SymbolContextScope * symbol_context_scope = NULL;
6934 
6935                 // DWARF doesn't specify if a DW_TAG_variable is a local, global
6936                 // or static variable, so we have to do a little digging by
6937                 // looking at the location of a varaible to see if it contains
6938                 // a DW_OP_addr opcode _somewhere_ in the definition. I say
6939                 // somewhere because clang likes to combine small global variables
6940                 // into the same symbol and have locations like:
6941                 // DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
6942                 // So if we don't have a DW_TAG_formal_parameter, we can look at
6943                 // the location to see if it contains a DW_OP_addr opcode, and
6944                 // then we can correctly classify  our variables.
6945                 if (tag == DW_TAG_formal_parameter)
6946                     scope = eValueTypeVariableArgument;
6947                 else
6948                 {
6949                     bool op_error = false;
6950                     // Check if the location has a DW_OP_addr with any address value...
6951                     addr_t location_has_op_addr = false;
6952                     if (!location_is_const_value_data)
6953                     {
6954                         location_has_op_addr = location.LocationContains_DW_OP_addr (LLDB_INVALID_ADDRESS, op_error);
6955                         if (op_error)
6956                         {
6957                             StreamString strm;
6958                             location.DumpLocationForAddress (&strm, eDescriptionLevelFull, 0, 0, NULL);
6959                             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());
6960                         }
6961                     }
6962 
6963                     if (location_has_op_addr)
6964                     {
6965                         if (is_external)
6966                         {
6967                             scope = eValueTypeVariableGlobal;
6968 
6969                             if (GetDebugMapSymfile ())
6970                             {
6971                                 // When leaving the DWARF in the .o files on darwin,
6972                                 // when we have a global variable that wasn't initialized,
6973                                 // the .o file might not have allocated a virtual
6974                                 // address for the global variable. In this case it will
6975                                 // have created a symbol for the global variable
6976                                 // that is undefined and external and the value will
6977                                 // be the byte size of the variable. When we do the
6978                                 // address map in SymbolFileDWARFDebugMap we rely on
6979                                 // having an address, we need to do some magic here
6980                                 // so we can get the correct address for our global
6981                                 // variable. The address for all of these entries
6982                                 // will be zero, and there will be an undefined symbol
6983                                 // in this object file, and the executable will have
6984                                 // a matching symbol with a good address. So here we
6985                                 // dig up the correct address and replace it in the
6986                                 // location for the variable, and set the variable's
6987                                 // symbol context scope to be that of the main executable
6988                                 // so the file address will resolve correctly.
6989                                 if (location.LocationContains_DW_OP_addr (0, op_error))
6990                                 {
6991 
6992                                     // we have a possible uninitialized extern global
6993                                     Symtab *symtab = m_obj_file->GetSymtab();
6994                                     if (symtab)
6995                                     {
6996                                         ConstString const_name(name);
6997                                         Symbol *undefined_symbol = symtab->FindFirstSymbolWithNameAndType (const_name,
6998                                                                                                            eSymbolTypeUndefined,
6999                                                                                                            Symtab::eDebugNo,
7000                                                                                                            Symtab::eVisibilityExtern);
7001 
7002                                         if (undefined_symbol)
7003                                         {
7004                                             ObjectFile *debug_map_objfile = m_debug_map_symfile->GetObjectFile();
7005                                             if (debug_map_objfile)
7006                                             {
7007                                                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
7008                                                 Symbol *defined_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType (const_name,
7009                                                                                                                            eSymbolTypeData,
7010                                                                                                                            Symtab::eDebugYes,
7011                                                                                                                            Symtab::eVisibilityExtern);
7012                                                 if (defined_symbol)
7013                                                 {
7014                                                     if (defined_symbol->ValueIsAddress())
7015                                                     {
7016                                                         const addr_t defined_addr = defined_symbol->GetAddress().GetFileAddress();
7017                                                         if (defined_addr != LLDB_INVALID_ADDRESS)
7018                                                         {
7019                                                             if (location.Update_DW_OP_addr (defined_addr))
7020                                                             {
7021                                                                 symbol_context_scope = defined_symbol;
7022                                                             }
7023                                                         }
7024                                                     }
7025                                                 }
7026                                             }
7027                                         }
7028                                     }
7029                                 }
7030                             }
7031                         }
7032                         else
7033                         {
7034                             scope = eValueTypeVariableStatic;
7035                         }
7036                     }
7037                     else
7038                     {
7039                         scope = eValueTypeVariableLocal;
7040                     }
7041                 }
7042 
7043                 if (symbol_context_scope == NULL)
7044                 {
7045                     switch (parent_tag)
7046                     {
7047                     case DW_TAG_subprogram:
7048                     case DW_TAG_inlined_subroutine:
7049                     case DW_TAG_lexical_block:
7050                         if (sc.function)
7051                         {
7052                             symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7053                             if (symbol_context_scope == NULL)
7054                                 symbol_context_scope = sc.function;
7055                         }
7056                         break;
7057 
7058                     default:
7059                         symbol_context_scope = sc.comp_unit;
7060                         break;
7061                     }
7062                 }
7063 
7064                 if (symbol_context_scope)
7065                 {
7066                     var_sp.reset (new Variable (MakeUserID(die->GetOffset()),
7067                                                 name,
7068                                                 mangled,
7069                                                 SymbolFileTypeSP (new SymbolFileType(*this, type_uid)),
7070                                                 scope,
7071                                                 symbol_context_scope,
7072                                                 &decl,
7073                                                 location,
7074                                                 is_external,
7075                                                 is_artificial));
7076 
7077                     var_sp->SetLocationIsConstantValueData (location_is_const_value_data);
7078                 }
7079                 else
7080                 {
7081                     // Not ready to parse this variable yet. It might be a global
7082                     // or static variable that is in a function scope and the function
7083                     // in the symbol context wasn't filled in yet
7084                     return var_sp;
7085                 }
7086             }
7087         }
7088         // Cache var_sp even if NULL (the variable was just a specification or
7089         // was missing vital information to be able to be displayed in the debugger
7090         // (missing location due to optimization, etc)) so we don't re-parse
7091         // this DIE over and over later...
7092         m_die_to_variable_sp[die] = var_sp;
7093     }
7094     return var_sp;
7095 }
7096 
7097 
7098 const DWARFDebugInfoEntry *
7099 SymbolFileDWARF::FindBlockContainingSpecification (dw_offset_t func_die_offset,
7100                                                    dw_offset_t spec_block_die_offset,
7101                                                    DWARFCompileUnit **result_die_cu_handle)
7102 {
7103     // Give the concrete function die specified by "func_die_offset", find the
7104     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7105     // to "spec_block_die_offset"
7106     DWARFDebugInfo* info = DebugInfo();
7107 
7108     const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint(func_die_offset, result_die_cu_handle);
7109     if (die)
7110     {
7111         assert (*result_die_cu_handle);
7112         return FindBlockContainingSpecification (*result_die_cu_handle, die, spec_block_die_offset, result_die_cu_handle);
7113     }
7114     return NULL;
7115 }
7116 
7117 
7118 const DWARFDebugInfoEntry *
7119 SymbolFileDWARF::FindBlockContainingSpecification(DWARFCompileUnit* dwarf_cu,
7120                                                   const DWARFDebugInfoEntry *die,
7121                                                   dw_offset_t spec_block_die_offset,
7122                                                   DWARFCompileUnit **result_die_cu_handle)
7123 {
7124     if (die)
7125     {
7126         switch (die->Tag())
7127         {
7128         case DW_TAG_subprogram:
7129         case DW_TAG_inlined_subroutine:
7130         case DW_TAG_lexical_block:
7131             {
7132                 if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
7133                 {
7134                     *result_die_cu_handle = dwarf_cu;
7135                     return die;
7136                 }
7137 
7138                 if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_abstract_origin, DW_INVALID_OFFSET) == spec_block_die_offset)
7139                 {
7140                     *result_die_cu_handle = dwarf_cu;
7141                     return die;
7142                 }
7143             }
7144             break;
7145         }
7146 
7147         // Give the concrete function die specified by "func_die_offset", find the
7148         // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7149         // to "spec_block_die_offset"
7150         for (const DWARFDebugInfoEntry *child_die = die->GetFirstChild(); child_die != NULL; child_die = child_die->GetSibling())
7151         {
7152             const DWARFDebugInfoEntry *result_die = FindBlockContainingSpecification (dwarf_cu,
7153                                                                                       child_die,
7154                                                                                       spec_block_die_offset,
7155                                                                                       result_die_cu_handle);
7156             if (result_die)
7157                 return result_die;
7158         }
7159     }
7160 
7161     *result_die_cu_handle = NULL;
7162     return NULL;
7163 }
7164 
7165 size_t
7166 SymbolFileDWARF::ParseVariables
7167 (
7168     const SymbolContext& sc,
7169     DWARFCompileUnit* dwarf_cu,
7170     const lldb::addr_t func_low_pc,
7171     const DWARFDebugInfoEntry *orig_die,
7172     bool parse_siblings,
7173     bool parse_children,
7174     VariableList* cc_variable_list
7175 )
7176 {
7177     if (orig_die == NULL)
7178         return 0;
7179 
7180     VariableListSP variable_list_sp;
7181 
7182     size_t vars_added = 0;
7183     const DWARFDebugInfoEntry *die = orig_die;
7184     while (die != NULL)
7185     {
7186         dw_tag_t tag = die->Tag();
7187 
7188         // Check to see if we have already parsed this variable or constant?
7189         if (m_die_to_variable_sp[die])
7190         {
7191             if (cc_variable_list)
7192                 cc_variable_list->AddVariableIfUnique (m_die_to_variable_sp[die]);
7193         }
7194         else
7195         {
7196             // We haven't already parsed it, lets do that now.
7197             if ((tag == DW_TAG_variable) ||
7198                 (tag == DW_TAG_constant) ||
7199                 (tag == DW_TAG_formal_parameter && sc.function))
7200             {
7201                 if (variable_list_sp.get() == NULL)
7202                 {
7203                     const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(orig_die);
7204                     dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7205                     switch (parent_tag)
7206                     {
7207                         case DW_TAG_compile_unit:
7208                             if (sc.comp_unit != NULL)
7209                             {
7210                                 variable_list_sp = sc.comp_unit->GetVariableList(false);
7211                                 if (variable_list_sp.get() == NULL)
7212                                 {
7213                                     variable_list_sp.reset(new VariableList());
7214                                     sc.comp_unit->SetVariableList(variable_list_sp);
7215                                 }
7216                             }
7217                             else
7218                             {
7219                                 GetObjectFile()->GetModule()->ReportError ("parent 0x%8.8llx %s with no valid compile unit in symbol context for 0x%8.8llx %s.\n",
7220                                                                            MakeUserID(sc_parent_die->GetOffset()),
7221                                                                            DW_TAG_value_to_name (parent_tag),
7222                                                                            MakeUserID(orig_die->GetOffset()),
7223                                                                            DW_TAG_value_to_name (orig_die->Tag()));
7224                             }
7225                             break;
7226 
7227                         case DW_TAG_subprogram:
7228                         case DW_TAG_inlined_subroutine:
7229                         case DW_TAG_lexical_block:
7230                             if (sc.function != NULL)
7231                             {
7232                                 // Check to see if we already have parsed the variables for the given scope
7233 
7234                                 Block *block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7235                                 if (block == NULL)
7236                                 {
7237                                     // This must be a specification or abstract origin with
7238                                     // a concrete block couterpart in the current function. We need
7239                                     // to find the concrete block so we can correctly add the
7240                                     // variable to it
7241                                     DWARFCompileUnit *concrete_block_die_cu = dwarf_cu;
7242                                     const DWARFDebugInfoEntry *concrete_block_die = FindBlockContainingSpecification (sc.function->GetID(),
7243                                                                                                                       sc_parent_die->GetOffset(),
7244                                                                                                                       &concrete_block_die_cu);
7245                                     if (concrete_block_die)
7246                                         block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(concrete_block_die->GetOffset()));
7247                                 }
7248 
7249                                 if (block != NULL)
7250                                 {
7251                                     const bool can_create = false;
7252                                     variable_list_sp = block->GetBlockVariableList (can_create);
7253                                     if (variable_list_sp.get() == NULL)
7254                                     {
7255                                         variable_list_sp.reset(new VariableList());
7256                                         block->SetVariableList(variable_list_sp);
7257                                     }
7258                                 }
7259                             }
7260                             break;
7261 
7262                         default:
7263                              GetObjectFile()->GetModule()->ReportError ("didn't find appropriate parent DIE for variable list for 0x%8.8llx %s.\n",
7264                                                                         MakeUserID(orig_die->GetOffset()),
7265                                                                         DW_TAG_value_to_name (orig_die->Tag()));
7266                             break;
7267                     }
7268                 }
7269 
7270                 if (variable_list_sp)
7271                 {
7272                     VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, func_low_pc));
7273                     if (var_sp)
7274                     {
7275                         variable_list_sp->AddVariableIfUnique (var_sp);
7276                         if (cc_variable_list)
7277                             cc_variable_list->AddVariableIfUnique (var_sp);
7278                         ++vars_added;
7279                     }
7280                 }
7281             }
7282         }
7283 
7284         bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
7285 
7286         if (!skip_children && parse_children && die->HasChildren())
7287         {
7288             vars_added += ParseVariables(sc, dwarf_cu, func_low_pc, die->GetFirstChild(), true, true, cc_variable_list);
7289         }
7290 
7291         if (parse_siblings)
7292             die = die->GetSibling();
7293         else
7294             die = NULL;
7295     }
7296     return vars_added;
7297 }
7298 
7299 //------------------------------------------------------------------
7300 // PluginInterface protocol
7301 //------------------------------------------------------------------
7302 const char *
7303 SymbolFileDWARF::GetPluginName()
7304 {
7305     return "SymbolFileDWARF";
7306 }
7307 
7308 const char *
7309 SymbolFileDWARF::GetShortPluginName()
7310 {
7311     return GetPluginNameStatic();
7312 }
7313 
7314 uint32_t
7315 SymbolFileDWARF::GetPluginVersion()
7316 {
7317     return 1;
7318 }
7319 
7320 void
7321 SymbolFileDWARF::CompleteTagDecl (void *baton, clang::TagDecl *decl)
7322 {
7323     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7324     clang_type_t clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7325     if (clang_type)
7326         symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7327 }
7328 
7329 void
7330 SymbolFileDWARF::CompleteObjCInterfaceDecl (void *baton, clang::ObjCInterfaceDecl *decl)
7331 {
7332     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7333     clang_type_t clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7334     if (clang_type)
7335         symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7336 }
7337 
7338 void
7339 SymbolFileDWARF::DumpIndexes ()
7340 {
7341     StreamFile s(stdout, false);
7342 
7343     s.Printf ("DWARF index for (%s) '%s/%s':",
7344               GetObjectFile()->GetModule()->GetArchitecture().GetArchitectureName(),
7345               GetObjectFile()->GetFileSpec().GetDirectory().AsCString(),
7346               GetObjectFile()->GetFileSpec().GetFilename().AsCString());
7347     s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
7348     s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
7349     s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
7350     s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
7351     s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
7352     s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
7353     s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
7354     s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
7355 }
7356 
7357 void
7358 SymbolFileDWARF::SearchDeclContext (const clang::DeclContext *decl_context,
7359                                     const char *name,
7360                                     llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7361 {
7362     DeclContextToDIEMap::iterator iter = m_decl_ctx_to_die.find(decl_context);
7363 
7364     if (iter == m_decl_ctx_to_die.end())
7365         return;
7366 
7367     for (DIEPointerSet::iterator pos = iter->second.begin(), end = iter->second.end(); pos != end; ++pos)
7368     {
7369         const DWARFDebugInfoEntry *context_die = *pos;
7370 
7371         if (!results)
7372             return;
7373 
7374         DWARFDebugInfo* info = DebugInfo();
7375 
7376         DIEArray die_offsets;
7377 
7378         DWARFCompileUnit* dwarf_cu = NULL;
7379         const DWARFDebugInfoEntry* die = NULL;
7380 
7381         if (m_using_apple_tables)
7382         {
7383             if (m_apple_types_ap.get())
7384                 m_apple_types_ap->FindByName (name, die_offsets);
7385         }
7386         else
7387         {
7388             if (!m_indexed)
7389                 Index ();
7390 
7391             m_type_index.Find (ConstString(name), die_offsets);
7392         }
7393 
7394         const size_t num_matches = die_offsets.size();
7395 
7396         if (num_matches)
7397         {
7398             for (size_t i = 0; i < num_matches; ++i)
7399             {
7400                 const dw_offset_t die_offset = die_offsets[i];
7401                 die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
7402 
7403                 if (die->GetParent() != context_die)
7404                     continue;
7405 
7406                 Type *matching_type = ResolveType (dwarf_cu, die);
7407 
7408                 lldb::clang_type_t type = matching_type->GetClangForwardType();
7409                 clang::QualType qual_type = clang::QualType::getFromOpaquePtr(type);
7410 
7411                 if (const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr()))
7412                 {
7413                     clang::TagDecl *tag_decl = tag_type->getDecl();
7414                     results->push_back(tag_decl);
7415                 }
7416                 else if (const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(qual_type.getTypePtr()))
7417                 {
7418                     clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
7419                     results->push_back(typedef_decl);
7420                 }
7421             }
7422         }
7423     }
7424 }
7425 
7426 void
7427 SymbolFileDWARF::FindExternalVisibleDeclsByName (void *baton,
7428                                                  const clang::DeclContext *decl_context,
7429                                                  clang::DeclarationName decl_name,
7430                                                  llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7431 {
7432 
7433     switch (decl_context->getDeclKind())
7434     {
7435     case clang::Decl::Namespace:
7436     case clang::Decl::TranslationUnit:
7437         {
7438             SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7439             symbol_file_dwarf->SearchDeclContext (decl_context, decl_name.getAsString().c_str(), results);
7440         }
7441         break;
7442     default:
7443         break;
7444     }
7445 }
7446 
7447 bool
7448 SymbolFileDWARF::LayoutRecordType (void *baton,
7449                                    const clang::RecordDecl *record_decl,
7450                                    uint64_t &size,
7451                                    uint64_t &alignment,
7452                                    llvm::DenseMap <const clang::FieldDecl *, uint64_t> &field_offsets,
7453                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7454                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7455 {
7456     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7457     return symbol_file_dwarf->LayoutRecordType (record_decl, size, alignment, field_offsets, base_offsets, vbase_offsets);
7458 }
7459 
7460 
7461 bool
7462 SymbolFileDWARF::LayoutRecordType (const clang::RecordDecl *record_decl,
7463                                    uint64_t &bit_size,
7464                                    uint64_t &alignment,
7465                                    llvm::DenseMap <const clang::FieldDecl *, uint64_t> &field_offsets,
7466                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7467                                    llvm::DenseMap <const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7468 {
7469     LogSP log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
7470     RecordDeclToLayoutMap::iterator pos = m_record_decl_to_layout_map.find (record_decl);
7471     bool success = false;
7472     base_offsets.clear();
7473     vbase_offsets.clear();
7474     if (pos != m_record_decl_to_layout_map.end())
7475     {
7476         bit_size = pos->second.bit_size;
7477         alignment = pos->second.alignment;
7478         field_offsets.swap(pos->second.field_offsets);
7479         base_offsets.swap (pos->second.base_offsets);
7480         vbase_offsets.swap (pos->second.vbase_offsets);
7481         m_record_decl_to_layout_map.erase(pos);
7482         success = true;
7483     }
7484     else
7485     {
7486         bit_size = 0;
7487         alignment = 0;
7488         field_offsets.clear();
7489     }
7490 
7491     if (log)
7492         GetObjectFile()->GetModule()->LogMessage (log.get(),
7493                                                   "SymbolFileDWARF::LayoutRecordType (record_decl = %p, bit_size = %llu, alignment = %llu, field_offsets[%u],base_offsets[%u], vbase_offsets[%u]) success = %i",
7494                                                   record_decl,
7495                                                   bit_size,
7496                                                   alignment,
7497                                                   (uint32_t)field_offsets.size(),
7498                                                   (uint32_t)base_offsets.size(),
7499                                                   (uint32_t)vbase_offsets.size(),
7500                                                   success);
7501     return success;
7502 }
7503 
7504 
7505 SymbolFileDWARFDebugMap *
7506 SymbolFileDWARF::GetDebugMapSymfile ()
7507 {
7508     if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired())
7509     {
7510         lldb::ModuleSP module_sp (m_debug_map_module_wp.lock());
7511         if (module_sp)
7512         {
7513             SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
7514             if (sym_vendor)
7515                 m_debug_map_symfile = (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
7516         }
7517     }
7518     return m_debug_map_symfile;
7519 }
7520 
7521 
7522