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