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