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