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