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