1 //===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolFileDWARF.h"
10 
11 #include "llvm/Support/Casting.h"
12 #include "llvm/Support/Threading.h"
13 
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleList.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Core/StreamFile.h"
20 #include "lldb/Core/Value.h"
21 #include "lldb/Utility/ArchSpec.h"
22 #include "lldb/Utility/RegularExpression.h"
23 #include "lldb/Utility/Scalar.h"
24 #include "lldb/Utility/StreamString.h"
25 #include "lldb/Utility/Timer.h"
26 
27 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
28 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
29 
30 #include "lldb/Host/FileSystem.h"
31 #include "lldb/Host/Host.h"
32 
33 #include "lldb/Interpreter/OptionValueFileSpecList.h"
34 #include "lldb/Interpreter/OptionValueProperties.h"
35 
36 #include "lldb/Symbol/Block.h"
37 #include "lldb/Symbol/ClangASTContext.h"
38 #include "lldb/Symbol/ClangUtil.h"
39 #include "lldb/Symbol/CompileUnit.h"
40 #include "lldb/Symbol/CompilerDecl.h"
41 #include "lldb/Symbol/CompilerDeclContext.h"
42 #include "lldb/Symbol/DebugMacros.h"
43 #include "lldb/Symbol/LineTable.h"
44 #include "lldb/Symbol/LocateSymbolFile.h"
45 #include "lldb/Symbol/ObjectFile.h"
46 #include "lldb/Symbol/SymbolVendor.h"
47 #include "lldb/Symbol/TypeMap.h"
48 #include "lldb/Symbol/TypeSystem.h"
49 #include "lldb/Symbol/VariableList.h"
50 
51 #include "lldb/Target/Language.h"
52 #include "lldb/Target/Target.h"
53 
54 #include "AppleDWARFIndex.h"
55 #include "DWARFASTParser.h"
56 #include "DWARFASTParserClang.h"
57 #include "DWARFCompileUnit.h"
58 #include "DWARFDebugAbbrev.h"
59 #include "DWARFDebugAranges.h"
60 #include "DWARFDebugInfo.h"
61 #include "DWARFDebugLine.h"
62 #include "DWARFDebugMacro.h"
63 #include "DWARFDebugRanges.h"
64 #include "DWARFDeclContext.h"
65 #include "DWARFFormValue.h"
66 #include "DWARFTypeUnit.h"
67 #include "DWARFUnit.h"
68 #include "DebugNamesDWARFIndex.h"
69 #include "LogChannelDWARF.h"
70 #include "ManualDWARFIndex.h"
71 #include "SymbolFileDWARFDebugMap.h"
72 #include "SymbolFileDWARFDwo.h"
73 #include "SymbolFileDWARFDwp.h"
74 
75 #include "llvm/Support/FileSystem.h"
76 
77 #include <algorithm>
78 #include <map>
79 #include <memory>
80 
81 #include <ctype.h>
82 #include <string.h>
83 
84 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
85 
86 #ifdef ENABLE_DEBUG_PRINTF
87 #include <stdio.h>
88 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
89 #else
90 #define DEBUG_PRINTF(fmt, ...)
91 #endif
92 
93 using namespace lldb;
94 using namespace lldb_private;
95 
96 // static inline bool
97 // child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
98 //{
99 //    switch (tag)
100 //    {
101 //    default:
102 //        break;
103 //    case DW_TAG_subprogram:
104 //    case DW_TAG_inlined_subroutine:
105 //    case DW_TAG_class_type:
106 //    case DW_TAG_structure_type:
107 //    case DW_TAG_union_type:
108 //        return true;
109 //    }
110 //    return false;
111 //}
112 //
113 
114 namespace {
115 
116 static constexpr PropertyDefinition g_properties[] = {
117     {"comp-dir-symlink-paths", OptionValue::eTypeFileSpecList, true, 0, nullptr,
118      {},
119      "If the DW_AT_comp_dir matches any of these paths the symbolic "
120      "links will be resolved at DWARF parse time."},
121     {"ignore-file-indexes", OptionValue::eTypeBoolean, true, 0, nullptr, {},
122      "Ignore indexes present in the object files and always index DWARF "
123      "manually."}};
124 
125 enum {
126   ePropertySymLinkPaths,
127   ePropertyIgnoreIndexes,
128 };
129 
130 class PluginProperties : public Properties {
131 public:
132   static ConstString GetSettingName() {
133     return SymbolFileDWARF::GetPluginNameStatic();
134   }
135 
136   PluginProperties() {
137     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
138     m_collection_sp->Initialize(g_properties);
139   }
140 
141   FileSpecList GetSymLinkPaths() {
142     const OptionValueFileSpecList *option_value =
143         m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(
144             nullptr, true, ePropertySymLinkPaths);
145     assert(option_value);
146     return option_value->GetCurrentValue();
147   }
148 
149   bool IgnoreFileIndexes() const {
150     return m_collection_sp->GetPropertyAtIndexAsBoolean(
151         nullptr, ePropertyIgnoreIndexes, false);
152   }
153 };
154 
155 typedef std::shared_ptr<PluginProperties> SymbolFileDWARFPropertiesSP;
156 
157 static const SymbolFileDWARFPropertiesSP &GetGlobalPluginProperties() {
158   static const auto g_settings_sp(std::make_shared<PluginProperties>());
159   return g_settings_sp;
160 }
161 
162 } // anonymous namespace end
163 
164 FileSpecList SymbolFileDWARF::GetSymlinkPaths() {
165   return GetGlobalPluginProperties()->GetSymLinkPaths();
166 }
167 
168 void SymbolFileDWARF::Initialize() {
169   LogChannelDWARF::Initialize();
170   PluginManager::RegisterPlugin(GetPluginNameStatic(),
171                                 GetPluginDescriptionStatic(), CreateInstance,
172                                 DebuggerInitialize);
173 }
174 
175 void SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) {
176   if (!PluginManager::GetSettingForSymbolFilePlugin(
177           debugger, PluginProperties::GetSettingName())) {
178     const bool is_global_setting = true;
179     PluginManager::CreateSettingForSymbolFilePlugin(
180         debugger, GetGlobalPluginProperties()->GetValueProperties(),
181         ConstString("Properties for the dwarf symbol-file plug-in."),
182         is_global_setting);
183   }
184 }
185 
186 void SymbolFileDWARF::Terminate() {
187   PluginManager::UnregisterPlugin(CreateInstance);
188   LogChannelDWARF::Terminate();
189 }
190 
191 lldb_private::ConstString SymbolFileDWARF::GetPluginNameStatic() {
192   static ConstString g_name("dwarf");
193   return g_name;
194 }
195 
196 const char *SymbolFileDWARF::GetPluginDescriptionStatic() {
197   return "DWARF and DWARF3 debug symbol file reader.";
198 }
199 
200 SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFile *obj_file) {
201   return new SymbolFileDWARF(obj_file,
202                              /*dwo_section_list*/ nullptr);
203 }
204 
205 TypeList *SymbolFileDWARF::GetTypeList() {
206   // This method can be called without going through the symbol vendor so we
207   // need to lock the module.
208   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
209   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
210   if (debug_map_symfile)
211     return debug_map_symfile->GetTypeList();
212   else
213     return m_obj_file->GetModule()->GetTypeList();
214 }
215 void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset,
216                                dw_offset_t max_die_offset, uint32_t type_mask,
217                                TypeSet &type_set) {
218   if (die) {
219     const dw_offset_t die_offset = die.GetOffset();
220 
221     if (die_offset >= max_die_offset)
222       return;
223 
224     if (die_offset >= min_die_offset) {
225       const dw_tag_t tag = die.Tag();
226 
227       bool add_type = false;
228 
229       switch (tag) {
230       case DW_TAG_array_type:
231         add_type = (type_mask & eTypeClassArray) != 0;
232         break;
233       case DW_TAG_unspecified_type:
234       case DW_TAG_base_type:
235         add_type = (type_mask & eTypeClassBuiltin) != 0;
236         break;
237       case DW_TAG_class_type:
238         add_type = (type_mask & eTypeClassClass) != 0;
239         break;
240       case DW_TAG_structure_type:
241         add_type = (type_mask & eTypeClassStruct) != 0;
242         break;
243       case DW_TAG_union_type:
244         add_type = (type_mask & eTypeClassUnion) != 0;
245         break;
246       case DW_TAG_enumeration_type:
247         add_type = (type_mask & eTypeClassEnumeration) != 0;
248         break;
249       case DW_TAG_subroutine_type:
250       case DW_TAG_subprogram:
251       case DW_TAG_inlined_subroutine:
252         add_type = (type_mask & eTypeClassFunction) != 0;
253         break;
254       case DW_TAG_pointer_type:
255         add_type = (type_mask & eTypeClassPointer) != 0;
256         break;
257       case DW_TAG_rvalue_reference_type:
258       case DW_TAG_reference_type:
259         add_type = (type_mask & eTypeClassReference) != 0;
260         break;
261       case DW_TAG_typedef:
262         add_type = (type_mask & eTypeClassTypedef) != 0;
263         break;
264       case DW_TAG_ptr_to_member_type:
265         add_type = (type_mask & eTypeClassMemberPointer) != 0;
266         break;
267       }
268 
269       if (add_type) {
270         const bool assert_not_being_parsed = true;
271         Type *type = ResolveTypeUID(die, assert_not_being_parsed);
272         if (type) {
273           if (type_set.find(type) == type_set.end())
274             type_set.insert(type);
275         }
276       }
277     }
278 
279     for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
280          child_die = child_die.GetSibling()) {
281       GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set);
282     }
283   }
284 }
285 
286 size_t SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope,
287                                  TypeClass type_mask, TypeList &type_list)
288 
289 {
290   ASSERT_MODULE_LOCK(this);
291   TypeSet type_set;
292 
293   CompileUnit *comp_unit = nullptr;
294   DWARFUnit *dwarf_cu = nullptr;
295   if (sc_scope)
296     comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
297 
298   if (comp_unit) {
299     dwarf_cu = GetDWARFCompileUnit(comp_unit);
300     if (dwarf_cu == nullptr)
301       return 0;
302     GetTypes(dwarf_cu->DIE(), dwarf_cu->GetOffset(),
303              dwarf_cu->GetNextUnitOffset(), type_mask, type_set);
304   } else {
305     DWARFDebugInfo *info = DebugInfo();
306     if (info) {
307       const size_t num_cus = info->GetNumUnits();
308       for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) {
309         dwarf_cu = info->GetUnitAtIndex(cu_idx);
310         if (dwarf_cu) {
311           GetTypes(dwarf_cu->DIE(), 0, UINT32_MAX, type_mask, type_set);
312         }
313       }
314     }
315   }
316 
317   std::set<CompilerType> compiler_type_set;
318   size_t num_types_added = 0;
319   for (Type *type : type_set) {
320     CompilerType compiler_type = type->GetForwardCompilerType();
321     if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) {
322       compiler_type_set.insert(compiler_type);
323       type_list.Insert(type->shared_from_this());
324       ++num_types_added;
325     }
326   }
327   return num_types_added;
328 }
329 
330 // Gets the first parent that is a lexical block, function or inlined
331 // subroutine, or compile unit.
332 DWARFDIE
333 SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) {
334   DWARFDIE die;
335   for (die = child_die.GetParent(); die; die = die.GetParent()) {
336     dw_tag_t tag = die.Tag();
337 
338     switch (tag) {
339     case DW_TAG_compile_unit:
340     case DW_TAG_partial_unit:
341     case DW_TAG_subprogram:
342     case DW_TAG_inlined_subroutine:
343     case DW_TAG_lexical_block:
344       return die;
345     }
346   }
347   return DWARFDIE();
348 }
349 
350 SymbolFileDWARF::SymbolFileDWARF(ObjectFile *objfile,
351                                  SectionList *dwo_section_list)
352     : SymbolFile(objfile),
353       UserID(0x7fffffff00000000), // Used by SymbolFileDWARFDebugMap to
354                                   // when this class parses .o files to
355                                   // contain the .o file index/ID
356       m_debug_map_module_wp(), m_debug_map_symfile(nullptr),
357       m_context(objfile->GetModule()->GetSectionList(), dwo_section_list),
358       m_data_debug_loc(), m_abbr(), m_info(), m_fetched_external_modules(false),
359       m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate),
360       m_unique_ast_type_map() {}
361 
362 SymbolFileDWARF::~SymbolFileDWARF() {}
363 
364 static ConstString GetDWARFMachOSegmentName() {
365   static ConstString g_dwarf_section_name("__DWARF");
366   return g_dwarf_section_name;
367 }
368 
369 UniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() {
370   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
371   if (debug_map_symfile)
372     return debug_map_symfile->GetUniqueDWARFASTTypeMap();
373   else
374     return m_unique_ast_type_map;
375 }
376 
377 TypeSystem *SymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) {
378   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
379   TypeSystem *type_system;
380   if (debug_map_symfile) {
381     type_system = debug_map_symfile->GetTypeSystemForLanguage(language);
382   } else {
383     type_system = m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
384     if (type_system)
385       type_system->SetSymbolFile(this);
386   }
387   return type_system;
388 }
389 
390 void SymbolFileDWARF::InitializeObject() {
391   Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
392 
393   if (!GetGlobalPluginProperties()->IgnoreFileIndexes()) {
394     DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc;
395     LoadSectionData(eSectionTypeDWARFAppleNames, apple_names);
396     LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces);
397     LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types);
398     LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc);
399 
400     m_index = AppleDWARFIndex::Create(
401         *GetObjectFile()->GetModule(), apple_names, apple_namespaces,
402         apple_types, apple_objc, m_context.getOrLoadStrData());
403 
404     if (m_index)
405       return;
406 
407     DWARFDataExtractor debug_names;
408     LoadSectionData(eSectionTypeDWARFDebugNames, debug_names);
409     if (debug_names.GetByteSize() > 0) {
410       llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or =
411           DebugNamesDWARFIndex::Create(
412               *GetObjectFile()->GetModule(), debug_names,
413               m_context.getOrLoadStrData(), DebugInfo());
414       if (index_or) {
415         m_index = std::move(*index_or);
416         return;
417       }
418       LLDB_LOG_ERROR(log, index_or.takeError(),
419                      "Unable to read .debug_names data: {0}");
420     }
421   }
422 
423   m_index = llvm::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(),
424                                                 DebugInfo());
425 }
426 
427 bool SymbolFileDWARF::SupportedVersion(uint16_t version) {
428   return version >= 2 && version <= 5;
429 }
430 
431 uint32_t SymbolFileDWARF::CalculateAbilities() {
432   uint32_t abilities = 0;
433   if (m_obj_file != nullptr) {
434     const Section *section = nullptr;
435     const SectionList *section_list = m_obj_file->GetSectionList();
436     if (section_list == nullptr)
437       return 0;
438 
439     uint64_t debug_abbrev_file_size = 0;
440     uint64_t debug_info_file_size = 0;
441     uint64_t debug_line_file_size = 0;
442 
443     section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get();
444 
445     if (section)
446       section_list = &section->GetChildren();
447 
448     section =
449         section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get();
450     if (section != nullptr) {
451       debug_info_file_size = section->GetFileSize();
452 
453       section =
454           section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true)
455               .get();
456       if (section)
457         debug_abbrev_file_size = section->GetFileSize();
458 
459       DWARFDebugAbbrev *abbrev = DebugAbbrev();
460       if (abbrev) {
461         std::set<dw_form_t> invalid_forms;
462         abbrev->GetUnsupportedForms(invalid_forms);
463         if (!invalid_forms.empty()) {
464           StreamString error;
465           error.Printf("unsupported DW_FORM value%s:", invalid_forms.size() > 1 ? "s" : "");
466           for (auto form : invalid_forms)
467             error.Printf(" %#x", form);
468           m_obj_file->GetModule()->ReportWarning("%s", error.GetString().str().c_str());
469           return 0;
470         }
471       }
472 
473       section =
474           section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true)
475               .get();
476       if (section)
477         debug_line_file_size = section->GetFileSize();
478     } else {
479       const char *symfile_dir_cstr =
480           m_obj_file->GetFileSpec().GetDirectory().GetCString();
481       if (symfile_dir_cstr) {
482         if (strcasestr(symfile_dir_cstr, ".dsym")) {
483           if (m_obj_file->GetType() == ObjectFile::eTypeDebugInfo) {
484             // We have a dSYM file that didn't have a any debug info. If the
485             // string table has a size of 1, then it was made from an
486             // executable with no debug info, or from an executable that was
487             // stripped.
488             section =
489                 section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true)
490                     .get();
491             if (section && section->GetFileSize() == 1) {
492               m_obj_file->GetModule()->ReportWarning(
493                   "empty dSYM file detected, dSYM was created with an "
494                   "executable with no debug info.");
495             }
496           }
497         }
498       }
499     }
500 
501     if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
502       abilities |= CompileUnits | Functions | Blocks | GlobalVariables |
503                    LocalVariables | VariableTypes;
504 
505     if (debug_line_file_size > 0)
506       abilities |= LineTables;
507   }
508   return abilities;
509 }
510 
511 const DWARFDataExtractor &
512 SymbolFileDWARF::GetCachedSectionData(lldb::SectionType sect_type,
513                                       DWARFDataSegment &data_segment) {
514   llvm::call_once(data_segment.m_flag, [this, sect_type, &data_segment] {
515     this->LoadSectionData(sect_type, std::ref(data_segment.m_data));
516   });
517   return data_segment.m_data;
518 }
519 
520 void SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type,
521                                       DWARFDataExtractor &data) {
522   ModuleSP module_sp(m_obj_file->GetModule());
523   const SectionList *section_list = module_sp->GetSectionList();
524   if (!section_list)
525     return;
526 
527   SectionSP section_sp(section_list->FindSectionByType(sect_type, true));
528   if (!section_sp)
529     return;
530 
531   data.Clear();
532   m_obj_file->ReadSectionData(section_sp.get(), data);
533 }
534 
535 const DWARFDataExtractor &SymbolFileDWARF::DebugLocData() {
536   const DWARFDataExtractor &debugLocData = get_debug_loc_data();
537   if (debugLocData.GetByteSize() > 0)
538     return debugLocData;
539   return get_debug_loclists_data();
540 }
541 
542 const DWARFDataExtractor &SymbolFileDWARF::get_debug_loc_data() {
543   return GetCachedSectionData(eSectionTypeDWARFDebugLoc, m_data_debug_loc);
544 }
545 
546 const DWARFDataExtractor &SymbolFileDWARF::get_debug_loclists_data() {
547   return GetCachedSectionData(eSectionTypeDWARFDebugLocLists,
548                               m_data_debug_loclists);
549 }
550 
551 DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
552   if (m_abbr)
553     return m_abbr.get();
554 
555   const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData();
556   if (debug_abbrev_data.GetByteSize() == 0)
557     return nullptr;
558 
559   auto abbr = llvm::make_unique<DWARFDebugAbbrev>();
560   llvm::Error error = abbr->parse(debug_abbrev_data);
561   if (error) {
562     Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
563     LLDB_LOG_ERROR(log, std::move(error),
564                    "Unable to read .debug_abbrev section: {0}");
565     return nullptr;
566   }
567 
568   m_abbr = std::move(abbr);
569   return m_abbr.get();
570 }
571 
572 const DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() const {
573   return m_abbr.get();
574 }
575 
576 DWARFDebugInfo *SymbolFileDWARF::DebugInfo() {
577   if (m_info == nullptr) {
578     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
579     Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
580                        static_cast<void *>(this));
581     if (m_context.getOrLoadDebugInfoData().GetByteSize() > 0)
582       m_info = llvm::make_unique<DWARFDebugInfo>(*this, m_context);
583   }
584   return m_info.get();
585 }
586 
587 const DWARFDebugInfo *SymbolFileDWARF::DebugInfo() const {
588   return m_info.get();
589 }
590 
591 DWARFUnit *
592 SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) {
593   if (!comp_unit)
594     return nullptr;
595 
596   DWARFDebugInfo *info = DebugInfo();
597   if (info) {
598     // The compile unit ID is the index of the DWARF unit.
599     DWARFUnit *dwarf_cu = info->GetUnitAtIndex(comp_unit->GetID());
600     if (dwarf_cu && dwarf_cu->GetUserData() == nullptr)
601       dwarf_cu->SetUserData(comp_unit);
602     return dwarf_cu;
603   }
604   return nullptr;
605 }
606 
607 DWARFDebugRangesBase *SymbolFileDWARF::GetDebugRanges() {
608   if (!m_ranges) {
609     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
610     Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
611                        static_cast<void *>(this));
612 
613     if (m_context.getOrLoadRangesData().GetByteSize() > 0)
614       m_ranges.reset(new DWARFDebugRanges());
615 
616     if (m_ranges)
617       m_ranges->Extract(m_context);
618   }
619   return m_ranges.get();
620 }
621 
622 DWARFDebugRangesBase *SymbolFileDWARF::GetDebugRngLists() {
623   if (!m_rnglists) {
624     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
625     Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
626                        static_cast<void *>(this));
627 
628     if (m_context.getOrLoadRngListsData().GetByteSize() > 0)
629       m_rnglists.reset(new DWARFDebugRngLists());
630 
631     if (m_rnglists)
632       m_rnglists->Extract(m_context);
633   }
634   return m_rnglists.get();
635 }
636 
637 lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) {
638   CompUnitSP cu_sp;
639   CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData();
640   if (comp_unit) {
641     // We already parsed this compile unit, had out a shared pointer to it
642     cu_sp = comp_unit->shared_from_this();
643   } else {
644     if (&dwarf_cu.GetSymbolFileDWARF() != this) {
645       return dwarf_cu.GetSymbolFileDWARF().ParseCompileUnit(dwarf_cu);
646     } else if (dwarf_cu.GetOffset() == 0 && GetDebugMapSymfile()) {
647       // Let the debug map create the compile unit
648       cu_sp = m_debug_map_symfile->GetCompileUnit(this);
649       dwarf_cu.SetUserData(cu_sp.get());
650     } else {
651       ModuleSP module_sp(m_obj_file->GetModule());
652       if (module_sp) {
653         const DWARFDIE cu_die = dwarf_cu.DIE();
654         if (cu_die) {
655           FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle());
656           if (cu_file_spec) {
657             // If we have a full path to the compile unit, we don't need to
658             // resolve the file.  This can be expensive e.g. when the source
659             // files are NFS mounted.
660             cu_file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory());
661 
662             std::string remapped_file;
663             if (module_sp->RemapSourceFile(cu_file_spec.GetPath(),
664                                            remapped_file))
665               cu_file_spec.SetFile(remapped_file, FileSpec::Style::native);
666           }
667 
668           LanguageType cu_language = DWARFUnit::LanguageTypeFromDWARF(
669               cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0));
670 
671           bool is_optimized = dwarf_cu.GetIsOptimized();
672           BuildCuTranslationTable();
673           cu_sp = std::make_shared<CompileUnit>(
674               module_sp, &dwarf_cu, cu_file_spec,
675               *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language,
676               is_optimized ? eLazyBoolYes : eLazyBoolNo);
677 
678           dwarf_cu.SetUserData(cu_sp.get());
679 
680           m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(
681               dwarf_cu.GetID(), cu_sp);
682         }
683       }
684     }
685   }
686   return cu_sp;
687 }
688 
689 void SymbolFileDWARF::BuildCuTranslationTable() {
690   if (!m_lldb_cu_to_dwarf_unit.empty())
691     return;
692 
693   DWARFDebugInfo *info = DebugInfo();
694   if (!info)
695     return;
696 
697   if (!info->ContainsTypeUnits()) {
698     // We can use a 1-to-1 mapping. No need to build a translation table.
699     return;
700   }
701   for (uint32_t i = 0, num = info->GetNumUnits(); i < num; ++i) {
702     if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info->GetUnitAtIndex(i))) {
703       cu->SetID(m_lldb_cu_to_dwarf_unit.size());
704       m_lldb_cu_to_dwarf_unit.push_back(i);
705     }
706   }
707 }
708 
709 llvm::Optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) {
710   BuildCuTranslationTable();
711   if (m_lldb_cu_to_dwarf_unit.empty())
712     return cu_idx;
713   if (cu_idx >= m_lldb_cu_to_dwarf_unit.size())
714     return llvm::None;
715   return m_lldb_cu_to_dwarf_unit[cu_idx];
716 }
717 
718 uint32_t SymbolFileDWARF::GetNumCompileUnits() {
719   DWARFDebugInfo *info = DebugInfo();
720   if (!info)
721     return 0;
722   BuildCuTranslationTable();
723   return m_lldb_cu_to_dwarf_unit.empty() ? info->GetNumUnits()
724                                          : m_lldb_cu_to_dwarf_unit.size();
725 }
726 
727 CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) {
728   ASSERT_MODULE_LOCK(this);
729   DWARFDebugInfo *info = DebugInfo();
730   if (!info)
731     return {};
732 
733   if (llvm::Optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) {
734     if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>(
735             info->GetUnitAtIndex(*dwarf_idx)))
736       return ParseCompileUnit(*dwarf_cu);
737   }
738   return {};
739 }
740 
741 Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit,
742                                          const DWARFDIE &die) {
743   ASSERT_MODULE_LOCK(this);
744   if (die.IsValid()) {
745     TypeSystem *type_system =
746         GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
747 
748     if (type_system) {
749       DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
750       if (dwarf_ast)
751         return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die);
752     }
753   }
754   return nullptr;
755 }
756 
757 bool SymbolFileDWARF::FixupAddress(Address &addr) {
758   SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
759   if (debug_map_symfile) {
760     return debug_map_symfile->LinkOSOAddress(addr);
761   }
762   // This is a normal DWARF file, no address fixups need to happen
763   return true;
764 }
765 lldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) {
766   ASSERT_MODULE_LOCK(this);
767   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
768   if (dwarf_cu)
769     return dwarf_cu->GetLanguageType();
770   else
771     return eLanguageTypeUnknown;
772 }
773 
774 size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) {
775   ASSERT_MODULE_LOCK(this);
776   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
777   if (!dwarf_cu)
778     return 0;
779 
780   size_t functions_added = 0;
781   std::vector<DWARFDIE> function_dies;
782   dwarf_cu->AppendDIEsWithTag(DW_TAG_subprogram, function_dies);
783   for (const DWARFDIE &die : function_dies) {
784     if (comp_unit.FindFunctionByUID(die.GetID()))
785       continue;
786     if (ParseFunction(comp_unit, die))
787       ++functions_added;
788   }
789   // FixupTypes();
790   return functions_added;
791 }
792 
793 bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit,
794                                         FileSpecList &support_files) {
795   ASSERT_MODULE_LOCK(this);
796   if (DWARFUnit *unit = GetDWARFCompileUnit(&comp_unit)) {
797     const dw_offset_t stmt_list = unit->GetLineTableOffset();
798     if (stmt_list != DW_INVALID_OFFSET) {
799       // All file indexes in DWARF are one based and a file of index zero is
800       // supposed to be the compile unit itself.
801       support_files.Append(comp_unit);
802       return DWARFDebugLine::ParseSupportFiles(comp_unit.GetModule(),
803                                                m_context.getOrLoadLineData(),
804                                                stmt_list, support_files, unit);
805     }
806   }
807   return false;
808 }
809 
810 FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) {
811   if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) {
812     if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu))
813       return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx);
814     return FileSpec();
815   }
816 
817   auto &tu = llvm::cast<DWARFTypeUnit>(unit);
818   return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx);
819 }
820 
821 const FileSpecList &
822 SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) {
823   static FileSpecList empty_list;
824 
825   dw_offset_t offset = tu.GetLineTableOffset();
826   if (offset == DW_INVALID_OFFSET ||
827       offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() ||
828       offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey())
829     return empty_list;
830 
831   // Many type units can share a line table, so parse the support file list
832   // once, and cache it based on the offset field.
833   auto iter_bool = m_type_unit_support_files.try_emplace(offset);
834   FileSpecList &list = iter_bool.first->second;
835   if (iter_bool.second) {
836     list.Append(FileSpec());
837     DWARFDebugLine::ParseSupportFiles(GetObjectFile()->GetModule(),
838                                       m_context.getOrLoadLineData(), offset,
839                                       list, &tu);
840   }
841   return list;
842 }
843 
844 bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) {
845   ASSERT_MODULE_LOCK(this);
846   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
847   if (dwarf_cu)
848     return dwarf_cu->GetIsOptimized();
849   return false;
850 }
851 
852 bool SymbolFileDWARF::ParseImportedModules(
853     const lldb_private::SymbolContext &sc,
854     std::vector<SourceModule> &imported_modules) {
855   ASSERT_MODULE_LOCK(this);
856   assert(sc.comp_unit);
857   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
858   if (!dwarf_cu)
859     return false;
860   if (!ClangModulesDeclVendor::LanguageSupportsClangModules(
861           sc.comp_unit->GetLanguage()))
862     return false;
863   UpdateExternalModuleListIfNeeded();
864 
865   const DWARFDIE die = dwarf_cu->DIE();
866   if (!die)
867     return false;
868 
869   for (DWARFDIE child_die = die.GetFirstChild(); child_die;
870        child_die = child_die.GetSibling()) {
871     if (child_die.Tag() != DW_TAG_imported_declaration)
872       continue;
873 
874     DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import);
875     if (module_die.Tag() != DW_TAG_module)
876       continue;
877 
878     if (const char *name =
879             module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) {
880       SourceModule module;
881       module.path.push_back(ConstString(name));
882 
883       DWARFDIE parent_die = module_die;
884       while ((parent_die = parent_die.GetParent())) {
885         if (parent_die.Tag() != DW_TAG_module)
886           break;
887         if (const char *name =
888                 parent_die.GetAttributeValueAsString(DW_AT_name, nullptr))
889           module.path.push_back(ConstString(name));
890       }
891       std::reverse(module.path.begin(), module.path.end());
892       if (const char *include_path = module_die.GetAttributeValueAsString(
893               DW_AT_LLVM_include_path, nullptr))
894         module.search_path = ConstString(include_path);
895       if (const char *sysroot = module_die.GetAttributeValueAsString(
896               DW_AT_LLVM_isysroot, nullptr))
897         module.sysroot = ConstString(sysroot);
898       imported_modules.push_back(module);
899     }
900   }
901   return true;
902 }
903 
904 struct ParseDWARFLineTableCallbackInfo {
905   LineTable *line_table;
906   std::unique_ptr<LineSequence> sequence_up;
907   lldb::addr_t addr_mask;
908 };
909 
910 // ParseStatementTableCallback
911 static void ParseDWARFLineTableCallback(dw_offset_t offset,
912                                         const DWARFDebugLine::State &state,
913                                         void *userData) {
914   if (state.row == DWARFDebugLine::State::StartParsingLineTable) {
915     // Just started parsing the line table
916   } else if (state.row == DWARFDebugLine::State::DoneParsingLineTable) {
917     // Done parsing line table, nothing to do for the cleanup
918   } else {
919     ParseDWARFLineTableCallbackInfo *info =
920         (ParseDWARFLineTableCallbackInfo *)userData;
921     LineTable *line_table = info->line_table;
922 
923     // If this is our first time here, we need to create a sequence container.
924     if (!info->sequence_up) {
925       info->sequence_up.reset(line_table->CreateLineSequenceContainer());
926       assert(info->sequence_up.get());
927     }
928     line_table->AppendLineEntryToSequence(
929         info->sequence_up.get(), state.address & info->addr_mask, state.line,
930         state.column, state.file, state.is_stmt, state.basic_block,
931         state.prologue_end, state.epilogue_begin, state.end_sequence);
932     if (state.end_sequence) {
933       // First, put the current sequence into the line table.
934       line_table->InsertSequence(info->sequence_up.get());
935       // Then, empty it to prepare for the next sequence.
936       info->sequence_up->Clear();
937     }
938   }
939 }
940 
941 bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) {
942   ASSERT_MODULE_LOCK(this);
943   if (comp_unit.GetLineTable() != nullptr)
944     return true;
945 
946   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
947   if (dwarf_cu) {
948     const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
949     if (dwarf_cu_die) {
950       const dw_offset_t cu_line_offset =
951           dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_stmt_list,
952                                                    DW_INVALID_OFFSET);
953       if (cu_line_offset != DW_INVALID_OFFSET) {
954         std::unique_ptr<LineTable> line_table_up(new LineTable(&comp_unit));
955         if (line_table_up) {
956           ParseDWARFLineTableCallbackInfo info;
957           info.line_table = line_table_up.get();
958 
959           /*
960            * MIPS:
961            * The SymbolContext may not have a valid target, thus we may not be
962            * able
963            * to call Address::GetOpcodeLoadAddress() which would clear the bit
964            * #0
965            * for MIPS. Use ArchSpec to clear the bit #0.
966           */
967           switch (GetObjectFile()->GetArchitecture().GetMachine()) {
968           case llvm::Triple::mips:
969           case llvm::Triple::mipsel:
970           case llvm::Triple::mips64:
971           case llvm::Triple::mips64el:
972             info.addr_mask = ~((lldb::addr_t)1);
973             break;
974           default:
975             info.addr_mask = ~((lldb::addr_t)0);
976             break;
977           }
978 
979           lldb::offset_t offset = cu_line_offset;
980           DWARFDebugLine::ParseStatementTable(
981               m_context.getOrLoadLineData(), &offset,
982               ParseDWARFLineTableCallback, &info, dwarf_cu);
983           SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
984           if (debug_map_symfile) {
985             // We have an object file that has a line table with addresses that
986             // are not linked. We need to link the line table and convert the
987             // addresses that are relative to the .o file into addresses for
988             // the main executable.
989             comp_unit.SetLineTable(
990                 debug_map_symfile->LinkOSOLineTable(this, line_table_up.get()));
991           } else {
992             comp_unit.SetLineTable(line_table_up.release());
993             return true;
994           }
995         }
996       }
997     }
998   }
999   return false;
1000 }
1001 
1002 lldb_private::DebugMacrosSP
1003 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) {
1004   auto iter = m_debug_macros_map.find(*offset);
1005   if (iter != m_debug_macros_map.end())
1006     return iter->second;
1007 
1008   const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData();
1009   if (debug_macro_data.GetByteSize() == 0)
1010     return DebugMacrosSP();
1011 
1012   lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1013   m_debug_macros_map[*offset] = debug_macros_sp;
1014 
1015   const DWARFDebugMacroHeader &header =
1016       DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1017   DWARFDebugMacroEntry::ReadMacroEntries(
1018       debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(),
1019       offset, this, debug_macros_sp);
1020 
1021   return debug_macros_sp;
1022 }
1023 
1024 bool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) {
1025   ASSERT_MODULE_LOCK(this);
1026 
1027   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1028   if (dwarf_cu == nullptr)
1029     return false;
1030 
1031   const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1032   if (!dwarf_cu_die)
1033     return false;
1034 
1035   lldb::offset_t sect_offset =
1036       dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1037   if (sect_offset == DW_INVALID_OFFSET)
1038     sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1039                                                            DW_INVALID_OFFSET);
1040   if (sect_offset == DW_INVALID_OFFSET)
1041     return false;
1042 
1043   comp_unit.SetDebugMacros(ParseDebugMacros(&sect_offset));
1044 
1045   return true;
1046 }
1047 
1048 size_t SymbolFileDWARF::ParseBlocksRecursive(
1049     lldb_private::CompileUnit &comp_unit, Block *parent_block,
1050     const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) {
1051   size_t blocks_added = 0;
1052   DWARFDIE die = orig_die;
1053   while (die) {
1054     dw_tag_t tag = die.Tag();
1055 
1056     switch (tag) {
1057     case DW_TAG_inlined_subroutine:
1058     case DW_TAG_subprogram:
1059     case DW_TAG_lexical_block: {
1060       Block *block = nullptr;
1061       if (tag == DW_TAG_subprogram) {
1062         // Skip any DW_TAG_subprogram DIEs that are inside of a normal or
1063         // inlined functions. These will be parsed on their own as separate
1064         // entities.
1065 
1066         if (depth > 0)
1067           break;
1068 
1069         block = parent_block;
1070       } else {
1071         BlockSP block_sp(new Block(die.GetID()));
1072         parent_block->AddChild(block_sp);
1073         block = block_sp.get();
1074       }
1075       DWARFRangeList ranges;
1076       const char *name = nullptr;
1077       const char *mangled_name = nullptr;
1078 
1079       int decl_file = 0;
1080       int decl_line = 0;
1081       int decl_column = 0;
1082       int call_file = 0;
1083       int call_line = 0;
1084       int call_column = 0;
1085       if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1086                                    decl_line, decl_column, call_file, call_line,
1087                                    call_column, nullptr)) {
1088         if (tag == DW_TAG_subprogram) {
1089           assert(subprogram_low_pc == LLDB_INVALID_ADDRESS);
1090           subprogram_low_pc = ranges.GetMinRangeBase(0);
1091         } else if (tag == DW_TAG_inlined_subroutine) {
1092           // We get called here for inlined subroutines in two ways. The first
1093           // time is when we are making the Function object for this inlined
1094           // concrete instance.  Since we're creating a top level block at
1095           // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we
1096           // need to adjust the containing address. The second time is when we
1097           // are parsing the blocks inside the function that contains the
1098           // inlined concrete instance.  Since these will be blocks inside the
1099           // containing "real" function the offset will be for that function.
1100           if (subprogram_low_pc == LLDB_INVALID_ADDRESS) {
1101             subprogram_low_pc = ranges.GetMinRangeBase(0);
1102           }
1103         }
1104 
1105         const size_t num_ranges = ranges.GetSize();
1106         for (size_t i = 0; i < num_ranges; ++i) {
1107           const DWARFRangeList::Entry &range = ranges.GetEntryRef(i);
1108           const addr_t range_base = range.GetRangeBase();
1109           if (range_base >= subprogram_low_pc)
1110             block->AddRange(Block::Range(range_base - subprogram_low_pc,
1111                                          range.GetByteSize()));
1112           else {
1113             GetObjectFile()->GetModule()->ReportError(
1114                 "0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64
1115                 ") which has a base that is less than the function's low PC "
1116                 "0x%" PRIx64 ". Please file a bug and attach the file at the "
1117                              "start of this error message",
1118                 block->GetID(), range_base, range.GetRangeEnd(),
1119                 subprogram_low_pc);
1120           }
1121         }
1122         block->FinalizeRanges();
1123 
1124         if (tag != DW_TAG_subprogram &&
1125             (name != nullptr || mangled_name != nullptr)) {
1126           std::unique_ptr<Declaration> decl_up;
1127           if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1128             decl_up.reset(new Declaration(
1129                 comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),
1130                 decl_line, decl_column));
1131 
1132           std::unique_ptr<Declaration> call_up;
1133           if (call_file != 0 || call_line != 0 || call_column != 0)
1134             call_up.reset(new Declaration(
1135                 comp_unit.GetSupportFiles().GetFileSpecAtIndex(call_file),
1136                 call_line, call_column));
1137 
1138           block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(),
1139                                         call_up.get());
1140         }
1141 
1142         ++blocks_added;
1143 
1144         if (die.HasChildren()) {
1145           blocks_added +=
1146               ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(),
1147                                    subprogram_low_pc, depth + 1);
1148         }
1149       }
1150     } break;
1151     default:
1152       break;
1153     }
1154 
1155     // Only parse siblings of the block if we are not at depth zero. A depth of
1156     // zero indicates we are currently parsing the top level DW_TAG_subprogram
1157     // DIE
1158 
1159     if (depth == 0)
1160       die.Clear();
1161     else
1162       die = die.GetSibling();
1163   }
1164   return blocks_added;
1165 }
1166 
1167 bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) {
1168   if (parent_die) {
1169     for (DWARFDIE die = parent_die.GetFirstChild(); die;
1170          die = die.GetSibling()) {
1171       dw_tag_t tag = die.Tag();
1172       bool check_virtuality = false;
1173       switch (tag) {
1174       case DW_TAG_inheritance:
1175       case DW_TAG_subprogram:
1176         check_virtuality = true;
1177         break;
1178       default:
1179         break;
1180       }
1181       if (check_virtuality) {
1182         if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1183           return true;
1184       }
1185     }
1186   }
1187   return false;
1188 }
1189 
1190 void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) {
1191   TypeSystem *type_system = decl_ctx.GetTypeSystem();
1192   DWARFASTParser *ast_parser = type_system->GetDWARFParser();
1193   std::vector<DWARFDIE> decl_ctx_die_list =
1194       ast_parser->GetDIEForDeclContext(decl_ctx);
1195 
1196   for (DWARFDIE decl_ctx_die : decl_ctx_die_list)
1197     for (DWARFDIE decl = decl_ctx_die.GetFirstChild(); decl;
1198          decl = decl.GetSibling())
1199       ast_parser->GetDeclForUIDFromDWARF(decl);
1200 }
1201 
1202 user_id_t SymbolFileDWARF::GetUID(DIERef ref) {
1203   if (GetDebugMapSymfile())
1204     return GetID() | ref.die_offset();
1205 
1206   return user_id_t(GetDwoNum().getValueOr(0x7fffffff)) << 32 |
1207          ref.die_offset() |
1208          (lldb::user_id_t(ref.section() == DIERef::Section::DebugTypes) << 63);
1209 }
1210 
1211 llvm::Optional<SymbolFileDWARF::DecodedUID>
1212 SymbolFileDWARF::DecodeUID(lldb::user_id_t uid) {
1213   // This method can be called without going through the symbol vendor so we
1214   // need to lock the module.
1215   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1216   // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1217   // must make sure we use the correct DWARF file when resolving things. On
1218   // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1219   // SymbolFileDWARF classes, one for each .o file. We can often end up with
1220   // references to other DWARF objects and we must be ready to receive a
1221   // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1222   // instance.
1223   if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) {
1224     SymbolFileDWARF *dwarf = debug_map->GetSymbolFileByOSOIndex(
1225         debug_map->GetOSOIndexFromUserID(uid));
1226     return DecodedUID{
1227         *dwarf, {llvm::None, DIERef::Section::DebugInfo, dw_offset_t(uid)}};
1228   }
1229   dw_offset_t die_offset = uid;
1230   if (die_offset == DW_INVALID_OFFSET)
1231     return llvm::None;
1232 
1233   DIERef::Section section =
1234       uid >> 63 ? DIERef::Section::DebugTypes : DIERef::Section::DebugInfo;
1235 
1236   llvm::Optional<uint32_t> dwo_num = uid >> 32 & 0x7fffffff;
1237   if (*dwo_num == 0x7fffffff)
1238     dwo_num = llvm::None;
1239 
1240   return DecodedUID{*this, {dwo_num, section, die_offset}};
1241 }
1242 
1243 DWARFDIE
1244 SymbolFileDWARF::GetDIE(lldb::user_id_t uid) {
1245   // This method can be called without going through the symbol vendor so we
1246   // need to lock the module.
1247   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1248 
1249   llvm::Optional<DecodedUID> decoded = DecodeUID(uid);
1250 
1251   if (decoded)
1252     return decoded->dwarf.GetDIE(decoded->ref);
1253 
1254   return DWARFDIE();
1255 }
1256 
1257 CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) {
1258   // This method can be called without going through the symbol vendor so we
1259   // need to lock the module.
1260   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1261   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1262   // SymbolFileDWARF::GetDIE(). See comments inside the
1263   // SymbolFileDWARF::GetDIE() for details.
1264   if (DWARFDIE die = GetDIE(type_uid))
1265     return die.GetDecl();
1266   return CompilerDecl();
1267 }
1268 
1269 CompilerDeclContext
1270 SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) {
1271   // This method can be called without going through the symbol vendor so we
1272   // need to lock the module.
1273   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1274   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1275   // SymbolFileDWARF::GetDIE(). See comments inside the
1276   // SymbolFileDWARF::GetDIE() for details.
1277   if (DWARFDIE die = GetDIE(type_uid))
1278     return die.GetDeclContext();
1279   return CompilerDeclContext();
1280 }
1281 
1282 CompilerDeclContext
1283 SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) {
1284   // This method can be called without going through the symbol vendor so we
1285   // need to lock the module.
1286   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1287   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1288   // SymbolFileDWARF::GetDIE(). See comments inside the
1289   // SymbolFileDWARF::GetDIE() for details.
1290   if (DWARFDIE die = GetDIE(type_uid))
1291     return die.GetContainingDeclContext();
1292   return CompilerDeclContext();
1293 }
1294 
1295 Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) {
1296   // This method can be called without going through the symbol vendor so we
1297   // need to lock the module.
1298   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1299   // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1300   // SymbolFileDWARF::GetDIE(). See comments inside the
1301   // SymbolFileDWARF::GetDIE() for details.
1302   if (DWARFDIE type_die = GetDIE(type_uid))
1303     return type_die.ResolveType();
1304   else
1305     return nullptr;
1306 }
1307 
1308 llvm::Optional<SymbolFile::ArrayInfo>
1309 SymbolFileDWARF::GetDynamicArrayInfoForUID(
1310     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1311   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1312   if (DWARFDIE type_die = GetDIE(type_uid))
1313     return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx);
1314   else
1315     return llvm::None;
1316 }
1317 
1318 Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1319   return ResolveType(GetDIE(die_ref), true);
1320 }
1321 
1322 Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1323                                       bool assert_not_being_parsed) {
1324   if (die) {
1325     Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1326     if (log)
1327       GetObjectFile()->GetModule()->LogMessage(
1328           log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1329           die.GetOffset(), die.GetTagAsCString(), die.GetName());
1330 
1331     // We might be coming in in the middle of a type tree (a class within a
1332     // class, an enum within a class), so parse any needed parent DIEs before
1333     // we get to this one...
1334     DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1335     if (decl_ctx_die) {
1336       if (log) {
1337         switch (decl_ctx_die.Tag()) {
1338         case DW_TAG_structure_type:
1339         case DW_TAG_union_type:
1340         case DW_TAG_class_type: {
1341           // Get the type, which could be a forward declaration
1342           if (log)
1343             GetObjectFile()->GetModule()->LogMessage(
1344                 log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' "
1345                      "resolve parent forward type for 0x%8.8x",
1346                 die.GetOffset(), die.GetTagAsCString(), die.GetName(),
1347                 decl_ctx_die.GetOffset());
1348         } break;
1349 
1350         default:
1351           break;
1352         }
1353       }
1354     }
1355     return ResolveType(die);
1356   }
1357   return nullptr;
1358 }
1359 
1360 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1361 // SymbolFileDWARF objects to detect if this DWARF file is the one that can
1362 // resolve a compiler_type.
1363 bool SymbolFileDWARF::HasForwardDeclForClangType(
1364     const CompilerType &compiler_type) {
1365   CompilerType compiler_type_no_qualifiers =
1366       ClangUtil::RemoveFastQualifiers(compiler_type);
1367   if (GetForwardDeclClangTypeToDie().count(
1368           compiler_type_no_qualifiers.GetOpaqueQualType())) {
1369     return true;
1370   }
1371   TypeSystem *type_system = compiler_type.GetTypeSystem();
1372 
1373   ClangASTContext *clang_type_system =
1374       llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1375   if (!clang_type_system)
1376     return false;
1377   DWARFASTParserClang *ast_parser =
1378       static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1379   return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1380 }
1381 
1382 bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1383   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1384 
1385   ClangASTContext *clang_type_system =
1386       llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem());
1387   if (clang_type_system) {
1388     DWARFASTParserClang *ast_parser =
1389         static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1390     if (ast_parser &&
1391         ast_parser->GetClangASTImporter().CanImport(compiler_type))
1392       return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1393   }
1394 
1395   // We have a struct/union/class/enum that needs to be fully resolved.
1396   CompilerType compiler_type_no_qualifiers =
1397       ClangUtil::RemoveFastQualifiers(compiler_type);
1398   auto die_it = GetForwardDeclClangTypeToDie().find(
1399       compiler_type_no_qualifiers.GetOpaqueQualType());
1400   if (die_it == GetForwardDeclClangTypeToDie().end()) {
1401     // We have already resolved this type...
1402     return true;
1403   }
1404 
1405   DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1406   if (dwarf_die) {
1407     // Once we start resolving this type, remove it from the forward
1408     // declaration map in case anyone child members or other types require this
1409     // type to get resolved. The type will get resolved when all of the calls
1410     // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done.
1411     GetForwardDeclClangTypeToDie().erase(die_it);
1412 
1413     Type *type = GetDIEToType().lookup(dwarf_die.GetDIE());
1414 
1415     Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
1416                                           DWARF_LOG_TYPE_COMPLETION));
1417     if (log)
1418       GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1419           log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1420           dwarf_die.GetID(), dwarf_die.GetTagAsCString(),
1421           type->GetName().AsCString());
1422     assert(compiler_type);
1423     DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser();
1424     if (dwarf_ast)
1425       return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type);
1426   }
1427   return false;
1428 }
1429 
1430 Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1431                                    bool assert_not_being_parsed,
1432                                    bool resolve_function_context) {
1433   if (die) {
1434     Type *type = GetTypeForDIE(die, resolve_function_context).get();
1435 
1436     if (assert_not_being_parsed) {
1437       if (type != DIE_IS_BEING_PARSED)
1438         return type;
1439 
1440       GetObjectFile()->GetModule()->ReportError(
1441           "Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1442           die.GetOffset(), die.GetTagAsCString(), die.GetName());
1443 
1444     } else
1445       return type;
1446   }
1447   return nullptr;
1448 }
1449 
1450 CompileUnit *
1451 SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) {
1452   // Check if the symbol vendor already knows about this compile unit?
1453   if (dwarf_cu.GetUserData() == nullptr) {
1454     // The symbol vendor doesn't know about this compile unit, we need to parse
1455     // and add it to the symbol vendor object.
1456     return ParseCompileUnit(dwarf_cu).get();
1457   }
1458   return (CompileUnit *)dwarf_cu.GetUserData();
1459 }
1460 
1461 size_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name,
1462                                                 DIEArray &method_die_offsets) {
1463   method_die_offsets.clear();
1464   m_index->GetObjCMethods(class_name, method_die_offsets);
1465   return method_die_offsets.size();
1466 }
1467 
1468 bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1469   sc.Clear(false);
1470 
1471   if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) {
1472     // Check if the symbol vendor already knows about this compile unit?
1473     sc.comp_unit =
1474         GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU()));
1475 
1476     sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1477     if (sc.function == nullptr)
1478       sc.function = ParseFunction(*sc.comp_unit, die);
1479 
1480     if (sc.function) {
1481       sc.module_sp = sc.function->CalculateSymbolContextModule();
1482       return true;
1483     }
1484   }
1485 
1486   return false;
1487 }
1488 
1489 lldb::ModuleSP SymbolFileDWARF::GetDWOModule(ConstString name) {
1490   UpdateExternalModuleListIfNeeded();
1491   const auto &pos = m_external_type_modules.find(name);
1492   if (pos != m_external_type_modules.end())
1493     return pos->second;
1494   else
1495     return lldb::ModuleSP();
1496 }
1497 
1498 DWARFDIE
1499 SymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1500   if (die_ref.dwo_num()) {
1501     return DebugInfo()
1502         ->GetUnitAtIndex(*die_ref.dwo_num())
1503         ->GetDwoSymbolFile()
1504         ->GetDIE(die_ref);
1505   }
1506 
1507 
1508   DWARFDebugInfo *debug_info = DebugInfo();
1509   if (debug_info)
1510     return debug_info->GetDIE(die_ref);
1511   else
1512     return DWARFDIE();
1513 }
1514 
1515 std::unique_ptr<SymbolFileDWARFDwo>
1516 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1517     DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) {
1518   // If we are using a dSYM file, we never want the standard DWO files since
1519   // the -gmodules support uses the same DWO machanism to specify full debug
1520   // info files for modules.
1521   if (GetDebugMapSymfile())
1522     return nullptr;
1523 
1524   DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit);
1525   // Only compile units can be split into two parts.
1526   if (!dwarf_cu)
1527     return nullptr;
1528 
1529   const char *dwo_name =
1530       cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1531   if (!dwo_name)
1532     return nullptr;
1533 
1534   SymbolFileDWARFDwp *dwp_symfile = GetDwpSymbolFile();
1535   if (dwp_symfile) {
1536     uint64_t dwo_id =
1537         cu_die.GetAttributeValueAsUnsigned(dwarf_cu, DW_AT_GNU_dwo_id, 0);
1538     std::unique_ptr<SymbolFileDWARFDwo> dwo_symfile =
1539         dwp_symfile->GetSymbolFileForDwoId(*dwarf_cu, dwo_id);
1540     if (dwo_symfile)
1541       return dwo_symfile;
1542   }
1543 
1544   FileSpec dwo_file(dwo_name);
1545   FileSystem::Instance().Resolve(dwo_file);
1546   if (dwo_file.IsRelative()) {
1547     const char *comp_dir =
1548         cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr);
1549     if (!comp_dir)
1550       return nullptr;
1551 
1552     dwo_file.SetFile(comp_dir, FileSpec::Style::native);
1553     FileSystem::Instance().Resolve(dwo_file);
1554     dwo_file.AppendPathComponent(dwo_name);
1555   }
1556 
1557   if (!FileSystem::Instance().Exists(dwo_file))
1558     return nullptr;
1559 
1560   const lldb::offset_t file_offset = 0;
1561   DataBufferSP dwo_file_data_sp;
1562   lldb::offset_t dwo_file_data_offset = 0;
1563   ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1564       GetObjectFile()->GetModule(), &dwo_file, file_offset,
1565       FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp,
1566       dwo_file_data_offset);
1567   if (dwo_obj_file == nullptr)
1568     return nullptr;
1569 
1570   return llvm::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, *dwarf_cu);
1571 }
1572 
1573 void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
1574   if (m_fetched_external_modules)
1575     return;
1576   m_fetched_external_modules = true;
1577 
1578   DWARFDebugInfo *debug_info = DebugInfo();
1579 
1580   const uint32_t num_compile_units = GetNumCompileUnits();
1581   for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
1582     DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx);
1583 
1584     const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
1585     if (die && !die.HasChildren()) {
1586       const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1587 
1588       if (name) {
1589         ConstString const_name(name);
1590         if (m_external_type_modules.find(const_name) ==
1591             m_external_type_modules.end()) {
1592           ModuleSP module_sp;
1593           const char *dwo_path =
1594               die.GetAttributeValueAsString(DW_AT_GNU_dwo_name, nullptr);
1595           if (dwo_path) {
1596             ModuleSpec dwo_module_spec;
1597             dwo_module_spec.GetFileSpec().SetFile(dwo_path,
1598                                                   FileSpec::Style::native);
1599             if (dwo_module_spec.GetFileSpec().IsRelative()) {
1600               const char *comp_dir =
1601                   die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1602               if (comp_dir) {
1603                 dwo_module_spec.GetFileSpec().SetFile(comp_dir,
1604                                                       FileSpec::Style::native);
1605                 FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
1606                 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1607               }
1608             }
1609             dwo_module_spec.GetArchitecture() =
1610                 m_obj_file->GetModule()->GetArchitecture();
1611 
1612             // When LLDB loads "external" modules it looks at the presence of
1613             // DW_AT_GNU_dwo_name. However, when the already created module
1614             // (corresponding to .dwo itself) is being processed, it will see
1615             // the presence of DW_AT_GNU_dwo_name (which contains the name of
1616             // dwo file) and will try to call ModuleList::GetSharedModule
1617             // again. In some cases (i.e. for empty files) Clang 4.0 generates
1618             // a *.dwo file which has DW_AT_GNU_dwo_name, but no
1619             // DW_AT_comp_dir. In this case the method
1620             // ModuleList::GetSharedModule will fail and the warning will be
1621             // printed. However, as one can notice in this case we don't
1622             // actually need to try to load the already loaded module
1623             // (corresponding to .dwo) so we simply skip it.
1624             if (m_obj_file->GetFileSpec().GetFileNameExtension() == ".dwo" &&
1625                 llvm::StringRef(m_obj_file->GetFileSpec().GetPath())
1626                     .endswith(dwo_module_spec.GetFileSpec().GetPath())) {
1627               continue;
1628             }
1629 
1630             Status error = ModuleList::GetSharedModule(
1631                 dwo_module_spec, module_sp, nullptr, nullptr, nullptr);
1632             if (!module_sp) {
1633               GetObjectFile()->GetModule()->ReportWarning(
1634                   "0x%8.8x: unable to locate module needed for external types: "
1635                   "%s\nerror: %s\nDebugging will be degraded due to missing "
1636                   "types. Rebuilding your project will regenerate the needed "
1637                   "module files.",
1638                   die.GetOffset(),
1639                   dwo_module_spec.GetFileSpec().GetPath().c_str(),
1640                   error.AsCString("unknown error"));
1641             }
1642           }
1643           m_external_type_modules[const_name] = module_sp;
1644         }
1645       }
1646     }
1647   }
1648 }
1649 
1650 SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
1651   if (!m_global_aranges_up) {
1652     m_global_aranges_up.reset(new GlobalVariableMap());
1653 
1654     ModuleSP module_sp = GetObjectFile()->GetModule();
1655     if (module_sp) {
1656       const size_t num_cus = module_sp->GetNumCompileUnits();
1657       for (size_t i = 0; i < num_cus; ++i) {
1658         CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1659         if (cu_sp) {
1660           VariableListSP globals_sp = cu_sp->GetVariableList(true);
1661           if (globals_sp) {
1662             const size_t num_globals = globals_sp->GetSize();
1663             for (size_t g = 0; g < num_globals; ++g) {
1664               VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1665               if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
1666                 const DWARFExpression &location = var_sp->LocationExpression();
1667                 Value location_result;
1668                 Status error;
1669                 if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr,
1670                                       nullptr, location_result, &error)) {
1671                   if (location_result.GetValueType() ==
1672                       Value::eValueTypeFileAddress) {
1673                     lldb::addr_t file_addr =
1674                         location_result.GetScalar().ULongLong();
1675                     lldb::addr_t byte_size = 1;
1676                     if (var_sp->GetType())
1677                       byte_size =
1678                           var_sp->GetType()->GetByteSize().getValueOr(0);
1679                     m_global_aranges_up->Append(GlobalVariableMap::Entry(
1680                         file_addr, byte_size, var_sp.get()));
1681                   }
1682                 }
1683               }
1684             }
1685           }
1686         }
1687       }
1688     }
1689     m_global_aranges_up->Sort();
1690   }
1691   return *m_global_aranges_up;
1692 }
1693 
1694 uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
1695                                                SymbolContextItem resolve_scope,
1696                                                SymbolContext &sc) {
1697   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1698   Timer scoped_timer(func_cat,
1699                      "SymbolFileDWARF::"
1700                      "ResolveSymbolContext (so_addr = { "
1701                      "section = %p, offset = 0x%" PRIx64
1702                      " }, resolve_scope = 0x%8.8x)",
1703                      static_cast<void *>(so_addr.GetSection().get()),
1704                      so_addr.GetOffset(), resolve_scope);
1705   uint32_t resolved = 0;
1706   if (resolve_scope &
1707       (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
1708        eSymbolContextLineEntry | eSymbolContextVariable)) {
1709     lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1710 
1711     DWARFDebugInfo *debug_info = DebugInfo();
1712     if (debug_info) {
1713       llvm::Expected<DWARFDebugAranges &> aranges =
1714           debug_info->GetCompileUnitAranges();
1715       if (!aranges) {
1716         Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
1717         LLDB_LOG_ERROR(log, aranges.takeError(),
1718                        "SymbolFileDWARF::ResolveSymbolContext failed to get cu "
1719                        "aranges.  {0}");
1720         return 0;
1721       }
1722 
1723       const dw_offset_t cu_offset = aranges->FindAddress(file_vm_addr);
1724       if (cu_offset == DW_INVALID_OFFSET) {
1725         // Global variables are not in the compile unit address ranges. The
1726         // only way to currently find global variables is to iterate over the
1727         // .debug_pubnames or the __apple_names table and find all items in
1728         // there that point to DW_TAG_variable DIEs and then find the address
1729         // that matches.
1730         if (resolve_scope & eSymbolContextVariable) {
1731           GlobalVariableMap &map = GetGlobalAranges();
1732           const GlobalVariableMap::Entry *entry =
1733               map.FindEntryThatContains(file_vm_addr);
1734           if (entry && entry->data) {
1735             Variable *variable = entry->data;
1736             SymbolContextScope *scc = variable->GetSymbolContextScope();
1737             if (scc) {
1738               scc->CalculateSymbolContext(&sc);
1739               sc.variable = variable;
1740             }
1741             return sc.GetResolvedMask();
1742           }
1743         }
1744       } else {
1745         uint32_t cu_idx = DW_INVALID_INDEX;
1746         if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
1747                 debug_info->GetUnitAtOffset(DIERef::Section::DebugInfo,
1748                                             cu_offset, &cu_idx))) {
1749           sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
1750           if (sc.comp_unit) {
1751             resolved |= eSymbolContextCompUnit;
1752 
1753             bool force_check_line_table = false;
1754             if (resolve_scope &
1755                 (eSymbolContextFunction | eSymbolContextBlock)) {
1756               DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
1757               DWARFDIE block_die;
1758               if (function_die) {
1759                 sc.function =
1760                     sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
1761                 if (sc.function == nullptr)
1762                   sc.function = ParseFunction(*sc.comp_unit, function_die);
1763 
1764                 if (sc.function && (resolve_scope & eSymbolContextBlock))
1765                   block_die = function_die.LookupDeepestBlock(file_vm_addr);
1766               } else {
1767                 // We might have had a compile unit that had discontiguous
1768                 // address ranges where the gaps are symbols that don't have
1769                 // any debug info. Discontiguous compile unit address ranges
1770                 // should only happen when there aren't other functions from
1771                 // other compile units in these gaps. This helps keep the size
1772                 // of the aranges down.
1773                 force_check_line_table = true;
1774               }
1775 
1776               if (sc.function != nullptr) {
1777                 resolved |= eSymbolContextFunction;
1778 
1779                 if (resolve_scope & eSymbolContextBlock) {
1780                   Block &block = sc.function->GetBlock(true);
1781 
1782                   if (block_die)
1783                     sc.block = block.FindBlockByID(block_die.GetID());
1784                   else
1785                     sc.block = block.FindBlockByID(function_die.GetID());
1786                   if (sc.block)
1787                     resolved |= eSymbolContextBlock;
1788                 }
1789               }
1790             }
1791 
1792             if ((resolve_scope & eSymbolContextLineEntry) ||
1793                 force_check_line_table) {
1794               LineTable *line_table = sc.comp_unit->GetLineTable();
1795               if (line_table != nullptr) {
1796                 // And address that makes it into this function should be in
1797                 // terms of this debug file if there is no debug map, or it
1798                 // will be an address in the .o file which needs to be fixed up
1799                 // to be in terms of the debug map executable. Either way,
1800                 // calling FixupAddress() will work for us.
1801                 Address exe_so_addr(so_addr);
1802                 if (FixupAddress(exe_so_addr)) {
1803                   if (line_table->FindLineEntryByAddress(exe_so_addr,
1804                                                          sc.line_entry)) {
1805                     resolved |= eSymbolContextLineEntry;
1806                   }
1807                 }
1808               }
1809             }
1810 
1811             if (force_check_line_table &&
1812                 !(resolved & eSymbolContextLineEntry)) {
1813               // We might have had a compile unit that had discontiguous
1814               // address ranges where the gaps are symbols that don't have any
1815               // debug info. Discontiguous compile unit address ranges should
1816               // only happen when there aren't other functions from other
1817               // compile units in these gaps. This helps keep the size of the
1818               // aranges down.
1819               sc.comp_unit = nullptr;
1820               resolved &= ~eSymbolContextCompUnit;
1821             }
1822           } else {
1823             GetObjectFile()->GetModule()->ReportWarning(
1824                 "0x%8.8x: compile unit %u failed to create a valid "
1825                 "lldb_private::CompileUnit class.",
1826                 cu_offset, cu_idx);
1827           }
1828         }
1829       }
1830     }
1831   }
1832   return resolved;
1833 }
1834 
1835 uint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec,
1836                                                uint32_t line,
1837                                                bool check_inlines,
1838                                                SymbolContextItem resolve_scope,
1839                                                SymbolContextList &sc_list) {
1840   const uint32_t prev_size = sc_list.GetSize();
1841   if (resolve_scope & eSymbolContextCompUnit) {
1842     for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1843          ++cu_idx) {
1844       CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get();
1845       if (!dc_cu)
1846         continue;
1847 
1848       const bool full_match = (bool)file_spec.GetDirectory();
1849       bool file_spec_matches_cu_file_spec =
1850           FileSpec::Equal(file_spec, *dc_cu, full_match);
1851       if (check_inlines || file_spec_matches_cu_file_spec) {
1852         SymbolContext sc(m_obj_file->GetModule());
1853         sc.comp_unit = dc_cu;
1854         uint32_t file_idx = UINT32_MAX;
1855 
1856         // If we are looking for inline functions only and we don't find it
1857         // in the support files, we are done.
1858         if (check_inlines) {
1859           file_idx =
1860               sc.comp_unit->GetSupportFiles().FindFileIndex(1, file_spec, true);
1861           if (file_idx == UINT32_MAX)
1862             continue;
1863         }
1864 
1865         if (line != 0) {
1866           LineTable *line_table = sc.comp_unit->GetLineTable();
1867 
1868           if (line_table != nullptr && line != 0) {
1869             // We will have already looked up the file index if we are
1870             // searching for inline entries.
1871             if (!check_inlines)
1872               file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1873                   1, file_spec, true);
1874 
1875             if (file_idx != UINT32_MAX) {
1876               uint32_t found_line;
1877               uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex(
1878                   0, file_idx, line, false, &sc.line_entry);
1879               found_line = sc.line_entry.line;
1880 
1881               while (line_idx != UINT32_MAX) {
1882                 sc.function = nullptr;
1883                 sc.block = nullptr;
1884                 if (resolve_scope &
1885                     (eSymbolContextFunction | eSymbolContextBlock)) {
1886                   const lldb::addr_t file_vm_addr =
1887                       sc.line_entry.range.GetBaseAddress().GetFileAddress();
1888                   if (file_vm_addr != LLDB_INVALID_ADDRESS) {
1889                     DWARFDIE function_die =
1890                         GetDWARFCompileUnit(dc_cu)->LookupAddress(file_vm_addr);
1891                     DWARFDIE block_die;
1892                     if (function_die) {
1893                       sc.function =
1894                           sc.comp_unit->FindFunctionByUID(function_die.GetID())
1895                               .get();
1896                       if (sc.function == nullptr)
1897                         sc.function =
1898                             ParseFunction(*sc.comp_unit, function_die);
1899 
1900                       if (sc.function && (resolve_scope & eSymbolContextBlock))
1901                         block_die =
1902                             function_die.LookupDeepestBlock(file_vm_addr);
1903                     }
1904 
1905                     if (sc.function != nullptr) {
1906                       Block &block = sc.function->GetBlock(true);
1907 
1908                       if (block_die)
1909                         sc.block = block.FindBlockByID(block_die.GetID());
1910                       else if (function_die)
1911                         sc.block = block.FindBlockByID(function_die.GetID());
1912                     }
1913                   }
1914                 }
1915 
1916                 sc_list.Append(sc);
1917                 line_idx = line_table->FindLineEntryIndexByFileIndex(
1918                     line_idx + 1, file_idx, found_line, true, &sc.line_entry);
1919               }
1920             }
1921           } else if (file_spec_matches_cu_file_spec && !check_inlines) {
1922             // only append the context if we aren't looking for inline call
1923             // sites by file and line and if the file spec matches that of
1924             // the compile unit
1925             sc_list.Append(sc);
1926           }
1927         } else if (file_spec_matches_cu_file_spec && !check_inlines) {
1928           // only append the context if we aren't looking for inline call
1929           // sites by file and line and if the file spec matches that of
1930           // the compile unit
1931           sc_list.Append(sc);
1932         }
1933 
1934         if (!check_inlines)
1935           break;
1936       }
1937     }
1938   }
1939   return sc_list.GetSize() - prev_size;
1940 }
1941 
1942 void SymbolFileDWARF::PreloadSymbols() {
1943   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1944   m_index->Preload();
1945 }
1946 
1947 std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
1948   lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
1949   if (module_sp)
1950     return module_sp->GetMutex();
1951   return GetObjectFile()->GetModule()->GetMutex();
1952 }
1953 
1954 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
1955     const lldb_private::CompilerDeclContext *decl_ctx) {
1956   if (decl_ctx == nullptr || !decl_ctx->IsValid()) {
1957     // Invalid namespace decl which means we aren't matching only things in
1958     // this symbol file, so return true to indicate it matches this symbol
1959     // file.
1960     return true;
1961   }
1962 
1963   TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1964   TypeSystem *type_system = GetTypeSystemForLanguage(
1965       decl_ctx_type_system->GetMinimumLanguage(nullptr));
1966   if (decl_ctx_type_system == type_system)
1967     return true; // The type systems match, return true
1968 
1969   // The namespace AST was valid, and it does not match...
1970   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
1971 
1972   if (log)
1973     GetObjectFile()->GetModule()->LogMessage(
1974         log, "Valid namespace does not match symbol file");
1975 
1976   return false;
1977 }
1978 
1979 uint32_t SymbolFileDWARF::FindGlobalVariables(
1980     ConstString name, const CompilerDeclContext *parent_decl_ctx,
1981     uint32_t max_matches, VariableList &variables) {
1982   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
1983 
1984   if (log)
1985     GetObjectFile()->GetModule()->LogMessage(
1986         log,
1987         "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
1988         "parent_decl_ctx=%p, max_matches=%u, variables)",
1989         name.GetCString(), static_cast<const void *>(parent_decl_ctx),
1990         max_matches);
1991 
1992   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1993     return 0;
1994 
1995   DWARFDebugInfo *info = DebugInfo();
1996   if (info == nullptr)
1997     return 0;
1998 
1999   // Remember how many variables are in the list before we search.
2000   const uint32_t original_size = variables.GetSize();
2001 
2002   llvm::StringRef basename;
2003   llvm::StringRef context;
2004   bool name_is_mangled = (bool)Mangled(name);
2005 
2006   if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2007                                                       context, basename))
2008     basename = name.GetStringRef();
2009 
2010   DIEArray die_offsets;
2011   m_index->GetGlobalVariables(ConstString(basename), die_offsets);
2012   const size_t num_die_matches = die_offsets.size();
2013   if (num_die_matches) {
2014     SymbolContext sc;
2015     sc.module_sp = m_obj_file->GetModule();
2016     assert(sc.module_sp);
2017 
2018     // Loop invariant: Variables up to this index have been checked for context
2019     // matches.
2020     uint32_t pruned_idx = original_size;
2021 
2022     bool done = false;
2023     for (size_t i = 0; i < num_die_matches && !done; ++i) {
2024       const DIERef &die_ref = die_offsets[i];
2025       DWARFDIE die = GetDIE(die_ref);
2026 
2027       if (die) {
2028         switch (die.Tag()) {
2029         default:
2030         case DW_TAG_subprogram:
2031         case DW_TAG_inlined_subroutine:
2032         case DW_TAG_try_block:
2033         case DW_TAG_catch_block:
2034           break;
2035 
2036         case DW_TAG_variable: {
2037           auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2038           if (!dwarf_cu)
2039             continue;
2040           sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2041 
2042           if (parent_decl_ctx) {
2043             DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2044             if (dwarf_ast) {
2045               CompilerDeclContext actual_parent_decl_ctx =
2046                   dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2047               if (!actual_parent_decl_ctx ||
2048                   actual_parent_decl_ctx != *parent_decl_ctx)
2049                 continue;
2050             }
2051           }
2052 
2053           ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false,
2054                          &variables);
2055           while (pruned_idx < variables.GetSize()) {
2056             VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2057             if (name_is_mangled ||
2058                 var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2059               ++pruned_idx;
2060             else
2061               variables.RemoveVariableAtIndex(pruned_idx);
2062           }
2063 
2064           if (variables.GetSize() - original_size >= max_matches)
2065             done = true;
2066         } break;
2067         }
2068       } else {
2069         m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2070       }
2071     }
2072   }
2073 
2074   // Return the number of variable that were appended to the list
2075   const uint32_t num_matches = variables.GetSize() - original_size;
2076   if (log && num_matches > 0) {
2077     GetObjectFile()->GetModule()->LogMessage(
2078         log,
2079         "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2080         "parent_decl_ctx=%p, max_matches=%u, variables) => %u",
2081         name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2082         max_matches, num_matches);
2083   }
2084   return num_matches;
2085 }
2086 
2087 uint32_t SymbolFileDWARF::FindGlobalVariables(const RegularExpression &regex,
2088                                               uint32_t max_matches,
2089                                               VariableList &variables) {
2090   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2091 
2092   if (log) {
2093     GetObjectFile()->GetModule()->LogMessage(
2094         log,
2095         "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", "
2096         "max_matches=%u, variables)",
2097         regex.GetText().str().c_str(), max_matches);
2098   }
2099 
2100   DWARFDebugInfo *info = DebugInfo();
2101   if (info == nullptr)
2102     return 0;
2103 
2104   // Remember how many variables are in the list before we search.
2105   const uint32_t original_size = variables.GetSize();
2106 
2107   DIEArray die_offsets;
2108   m_index->GetGlobalVariables(regex, die_offsets);
2109 
2110   SymbolContext sc;
2111   sc.module_sp = m_obj_file->GetModule();
2112   assert(sc.module_sp);
2113 
2114   const size_t num_matches = die_offsets.size();
2115   if (num_matches) {
2116     for (size_t i = 0; i < num_matches; ++i) {
2117       const DIERef &die_ref = die_offsets[i];
2118       DWARFDIE die = GetDIE(die_ref);
2119 
2120       if (die) {
2121         DWARFCompileUnit *dwarf_cu =
2122             llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2123         if (!dwarf_cu)
2124           continue;
2125         sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2126 
2127         ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2128 
2129         if (variables.GetSize() - original_size >= max_matches)
2130           break;
2131       } else
2132         m_index->ReportInvalidDIERef(die_ref, regex.GetText());
2133     }
2134   }
2135 
2136   // Return the number of variable that were appended to the list
2137   return variables.GetSize() - original_size;
2138 }
2139 
2140 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2141                                       bool include_inlines,
2142                                       SymbolContextList &sc_list) {
2143   SymbolContext sc;
2144 
2145   if (!orig_die)
2146     return false;
2147 
2148   // If we were passed a die that is not a function, just return false...
2149   if (!(orig_die.Tag() == DW_TAG_subprogram ||
2150         (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2151     return false;
2152 
2153   DWARFDIE die = orig_die;
2154   DWARFDIE inlined_die;
2155   if (die.Tag() == DW_TAG_inlined_subroutine) {
2156     inlined_die = die;
2157 
2158     while (true) {
2159       die = die.GetParent();
2160 
2161       if (die) {
2162         if (die.Tag() == DW_TAG_subprogram)
2163           break;
2164       } else
2165         break;
2166     }
2167   }
2168   assert(die && die.Tag() == DW_TAG_subprogram);
2169   if (GetFunction(die, sc)) {
2170     Address addr;
2171     // Parse all blocks if needed
2172     if (inlined_die) {
2173       Block &function_block = sc.function->GetBlock(true);
2174       sc.block = function_block.FindBlockByID(inlined_die.GetID());
2175       if (sc.block == nullptr)
2176         sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2177       if (sc.block == nullptr || !sc.block->GetStartAddress(addr))
2178         addr.Clear();
2179     } else {
2180       sc.block = nullptr;
2181       addr = sc.function->GetAddressRange().GetBaseAddress();
2182     }
2183 
2184     if (addr.IsValid()) {
2185       sc_list.Append(sc);
2186       return true;
2187     }
2188   }
2189 
2190   return false;
2191 }
2192 
2193 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext *decl_ctx,
2194                                        const DWARFDIE &die) {
2195   // If we have no parent decl context to match this DIE matches, and if the
2196   // parent decl context isn't valid, we aren't trying to look for any
2197   // particular decl context so any die matches.
2198   if (decl_ctx == nullptr || !decl_ctx->IsValid())
2199     return true;
2200 
2201   if (die) {
2202     DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2203     if (dwarf_ast) {
2204       CompilerDeclContext actual_decl_ctx =
2205           dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2206       if (actual_decl_ctx)
2207         return decl_ctx->IsContainedInLookup(actual_decl_ctx);
2208     }
2209   }
2210   return false;
2211 }
2212 
2213 uint32_t SymbolFileDWARF::FindFunctions(
2214     ConstString name, const CompilerDeclContext *parent_decl_ctx,
2215     FunctionNameType name_type_mask, bool include_inlines, bool append,
2216     SymbolContextList &sc_list) {
2217   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2218   Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')",
2219                      name.AsCString());
2220 
2221   // eFunctionNameTypeAuto should be pre-resolved by a call to
2222   // Module::LookupInfo::LookupInfo()
2223   assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2224 
2225   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2226 
2227   if (log) {
2228     GetObjectFile()->GetModule()->LogMessage(
2229         log, "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2230              "name_type_mask=0x%x, append=%u, sc_list)",
2231         name.GetCString(), name_type_mask, append);
2232   }
2233 
2234   // If we aren't appending the results to this list, then clear the list
2235   if (!append)
2236     sc_list.Clear();
2237 
2238   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2239     return 0;
2240 
2241   // If name is empty then we won't find anything.
2242   if (name.IsEmpty())
2243     return 0;
2244 
2245   // Remember how many sc_list are in the list before we search in case we are
2246   // appending the results to a variable list.
2247 
2248   const uint32_t original_size = sc_list.GetSize();
2249 
2250   llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2251   DIEArray offsets;
2252   CompilerDeclContext empty_decl_ctx;
2253   if (!parent_decl_ctx)
2254     parent_decl_ctx = &empty_decl_ctx;
2255 
2256   std::vector<DWARFDIE> dies;
2257   m_index->GetFunctions(name, *this, *parent_decl_ctx, name_type_mask, dies);
2258   for (const DWARFDIE &die: dies) {
2259     if (resolved_dies.insert(die.GetDIE()).second)
2260       ResolveFunction(die, include_inlines, sc_list);
2261   }
2262 
2263   // Return the number of variable that were appended to the list
2264   const uint32_t num_matches = sc_list.GetSize() - original_size;
2265 
2266   if (log && num_matches > 0) {
2267     GetObjectFile()->GetModule()->LogMessage(
2268         log, "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2269              "name_type_mask=0x%x, include_inlines=%d, append=%u, sc_list) => "
2270              "%u",
2271         name.GetCString(), name_type_mask, include_inlines, append,
2272         num_matches);
2273   }
2274   return num_matches;
2275 }
2276 
2277 uint32_t SymbolFileDWARF::FindFunctions(const RegularExpression &regex,
2278                                         bool include_inlines, bool append,
2279                                         SymbolContextList &sc_list) {
2280   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2281   Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')",
2282                      regex.GetText().str().c_str());
2283 
2284   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2285 
2286   if (log) {
2287     GetObjectFile()->GetModule()->LogMessage(
2288         log,
2289         "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
2290         regex.GetText().str().c_str(), append);
2291   }
2292 
2293   // If we aren't appending the results to this list, then clear the list
2294   if (!append)
2295     sc_list.Clear();
2296 
2297   DWARFDebugInfo *info = DebugInfo();
2298   if (!info)
2299     return 0;
2300 
2301   // Remember how many sc_list are in the list before we search in case we are
2302   // appending the results to a variable list.
2303   uint32_t original_size = sc_list.GetSize();
2304 
2305   DIEArray offsets;
2306   m_index->GetFunctions(regex, offsets);
2307 
2308   llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2309   for (DIERef ref : offsets) {
2310     DWARFDIE die = info->GetDIE(ref);
2311     if (!die) {
2312       m_index->ReportInvalidDIERef(ref, regex.GetText());
2313       continue;
2314     }
2315     if (resolved_dies.insert(die.GetDIE()).second)
2316       ResolveFunction(die, include_inlines, sc_list);
2317   }
2318 
2319   // Return the number of variable that were appended to the list
2320   return sc_list.GetSize() - original_size;
2321 }
2322 
2323 void SymbolFileDWARF::GetMangledNamesForFunction(
2324     const std::string &scope_qualified_name,
2325     std::vector<ConstString> &mangled_names) {
2326   DWARFDebugInfo *info = DebugInfo();
2327   uint32_t num_comp_units = 0;
2328   if (info)
2329     num_comp_units = info->GetNumUnits();
2330 
2331   for (uint32_t i = 0; i < num_comp_units; i++) {
2332     DWARFUnit *cu = info->GetUnitAtIndex(i);
2333     if (cu == nullptr)
2334       continue;
2335 
2336     SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2337     if (dwo)
2338       dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2339   }
2340 
2341   for (lldb::user_id_t uid :
2342        m_function_scope_qualified_name_map.lookup(scope_qualified_name)) {
2343     DWARFDIE die = GetDIE(uid);
2344     mangled_names.push_back(ConstString(die.GetMangledName()));
2345   }
2346 }
2347 
2348 uint32_t SymbolFileDWARF::FindTypes(
2349     ConstString name, const CompilerDeclContext *parent_decl_ctx,
2350     bool append, uint32_t max_matches,
2351     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2352     TypeMap &types) {
2353   // If we aren't appending the results to this list, then clear the list
2354   if (!append)
2355     types.Clear();
2356 
2357   // Make sure we haven't already searched this SymbolFile before...
2358   if (searched_symbol_files.count(this))
2359     return 0;
2360   else
2361     searched_symbol_files.insert(this);
2362 
2363   DWARFDebugInfo *info = DebugInfo();
2364   if (info == nullptr)
2365     return 0;
2366 
2367   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2368 
2369   if (log) {
2370     if (parent_decl_ctx)
2371       GetObjectFile()->GetModule()->LogMessage(
2372           log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2373                "%p (\"%s\"), append=%u, max_matches=%u, type_list)",
2374           name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2375           parent_decl_ctx->GetName().AsCString("<NULL>"), append, max_matches);
2376     else
2377       GetObjectFile()->GetModule()->LogMessage(
2378           log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2379                "NULL, append=%u, max_matches=%u, type_list)",
2380           name.GetCString(), append, max_matches);
2381   }
2382 
2383   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2384     return 0;
2385 
2386   DIEArray die_offsets;
2387   m_index->GetTypes(name, die_offsets);
2388   const size_t num_die_matches = die_offsets.size();
2389 
2390   if (num_die_matches) {
2391     const uint32_t initial_types_size = types.GetSize();
2392     for (size_t i = 0; i < num_die_matches; ++i) {
2393       const DIERef &die_ref = die_offsets[i];
2394       DWARFDIE die = GetDIE(die_ref);
2395 
2396       if (die) {
2397         if (!DIEInDeclContext(parent_decl_ctx, die))
2398           continue; // The containing decl contexts don't match
2399 
2400         Type *matching_type = ResolveType(die, true, true);
2401         if (matching_type) {
2402           // We found a type pointer, now find the shared pointer form our type
2403           // list
2404           types.InsertUnique(matching_type->shared_from_this());
2405           if (types.GetSize() >= max_matches)
2406             break;
2407         }
2408       } else {
2409         m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2410       }
2411     }
2412     const uint32_t num_matches = types.GetSize() - initial_types_size;
2413     if (log && num_matches) {
2414       if (parent_decl_ctx) {
2415         GetObjectFile()->GetModule()->LogMessage(
2416             log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2417                  "= %p (\"%s\"), append=%u, max_matches=%u, type_list) => %u",
2418             name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2419             parent_decl_ctx->GetName().AsCString("<NULL>"), append, max_matches,
2420             num_matches);
2421       } else {
2422         GetObjectFile()->GetModule()->LogMessage(
2423             log, "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2424                  "= NULL, append=%u, max_matches=%u, type_list) => %u",
2425             name.GetCString(), append, max_matches, num_matches);
2426       }
2427     }
2428     return num_matches;
2429   } else {
2430     UpdateExternalModuleListIfNeeded();
2431 
2432     for (const auto &pair : m_external_type_modules) {
2433       ModuleSP external_module_sp = pair.second;
2434       if (external_module_sp) {
2435         SymbolVendor *sym_vendor = external_module_sp->GetSymbolVendor();
2436         if (sym_vendor) {
2437           const uint32_t num_external_matches =
2438               sym_vendor->FindTypes(name, parent_decl_ctx, append, max_matches,
2439                                     searched_symbol_files, types);
2440           if (num_external_matches)
2441             return num_external_matches;
2442         }
2443       }
2444     }
2445   }
2446 
2447   return 0;
2448 }
2449 
2450 size_t SymbolFileDWARF::FindTypes(const std::vector<CompilerContext> &context,
2451                                   bool append, TypeMap &types) {
2452   if (!append)
2453     types.Clear();
2454 
2455   if (context.empty())
2456     return 0;
2457 
2458   ConstString name = context.back().name;
2459 
2460   if (!name)
2461     return 0;
2462 
2463   DIEArray die_offsets;
2464   m_index->GetTypes(name, die_offsets);
2465   const size_t num_die_matches = die_offsets.size();
2466 
2467   if (num_die_matches) {
2468     size_t num_matches = 0;
2469     for (size_t i = 0; i < num_die_matches; ++i) {
2470       const DIERef &die_ref = die_offsets[i];
2471       DWARFDIE die = GetDIE(die_ref);
2472 
2473       if (die) {
2474         std::vector<CompilerContext> die_context;
2475         die.GetDeclContext(die_context);
2476         if (die_context != context)
2477           continue;
2478 
2479         Type *matching_type = ResolveType(die, true, true);
2480         if (matching_type) {
2481           // We found a type pointer, now find the shared pointer form our type
2482           // list
2483           types.InsertUnique(matching_type->shared_from_this());
2484           ++num_matches;
2485         }
2486       } else {
2487         m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2488       }
2489     }
2490     return num_matches;
2491   }
2492   return 0;
2493 }
2494 
2495 CompilerDeclContext
2496 SymbolFileDWARF::FindNamespace(ConstString name,
2497                                const CompilerDeclContext *parent_decl_ctx) {
2498   Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2499 
2500   if (log) {
2501     GetObjectFile()->GetModule()->LogMessage(
2502         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2503         name.GetCString());
2504   }
2505 
2506   CompilerDeclContext namespace_decl_ctx;
2507 
2508   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2509     return namespace_decl_ctx;
2510 
2511   DWARFDebugInfo *info = DebugInfo();
2512   if (info) {
2513     DIEArray die_offsets;
2514     m_index->GetNamespaces(name, die_offsets);
2515     const size_t num_matches = die_offsets.size();
2516     if (num_matches) {
2517       for (size_t i = 0; i < num_matches; ++i) {
2518         const DIERef &die_ref = die_offsets[i];
2519         DWARFDIE die = GetDIE(die_ref);
2520 
2521         if (die) {
2522           if (!DIEInDeclContext(parent_decl_ctx, die))
2523             continue; // The containing decl contexts don't match
2524 
2525           DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2526           if (dwarf_ast) {
2527             namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2528             if (namespace_decl_ctx)
2529               break;
2530           }
2531         } else {
2532           m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2533         }
2534       }
2535     }
2536   }
2537   if (log && namespace_decl_ctx) {
2538     GetObjectFile()->GetModule()->LogMessage(
2539         log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2540              "CompilerDeclContext(%p/%p) \"%s\"",
2541         name.GetCString(),
2542         static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2543         static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2544         namespace_decl_ctx.GetName().AsCString("<NULL>"));
2545   }
2546 
2547   return namespace_decl_ctx;
2548 }
2549 
2550 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2551                                       bool resolve_function_context) {
2552   TypeSP type_sp;
2553   if (die) {
2554     Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2555     if (type_ptr == nullptr) {
2556       SymbolContextScope *scope;
2557       if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
2558         scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2559       else
2560         scope = GetObjectFile()->GetModule().get();
2561       assert(scope);
2562       SymbolContext sc(scope);
2563       const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2564       while (parent_die != nullptr) {
2565         if (parent_die->Tag() == DW_TAG_subprogram)
2566           break;
2567         parent_die = parent_die->GetParent();
2568       }
2569       SymbolContext sc_backup = sc;
2570       if (resolve_function_context && parent_die != nullptr &&
2571           !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2572         sc = sc_backup;
2573 
2574       type_sp = ParseType(sc, die, nullptr);
2575     } else if (type_ptr != DIE_IS_BEING_PARSED) {
2576       // Grab the existing type from the master types lists
2577       type_sp = type_ptr->shared_from_this();
2578     }
2579   }
2580   return type_sp;
2581 }
2582 
2583 DWARFDIE
2584 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2585   if (orig_die) {
2586     DWARFDIE die = orig_die;
2587 
2588     while (die) {
2589       // If this is the original DIE that we are searching for a declaration
2590       // for, then don't look in the cache as we don't want our own decl
2591       // context to be our decl context...
2592       if (orig_die != die) {
2593         switch (die.Tag()) {
2594         case DW_TAG_compile_unit:
2595         case DW_TAG_partial_unit:
2596         case DW_TAG_namespace:
2597         case DW_TAG_structure_type:
2598         case DW_TAG_union_type:
2599         case DW_TAG_class_type:
2600         case DW_TAG_lexical_block:
2601         case DW_TAG_subprogram:
2602           return die;
2603         case DW_TAG_inlined_subroutine: {
2604           DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2605           if (abs_die) {
2606             return abs_die;
2607           }
2608           break;
2609         }
2610         default:
2611           break;
2612         }
2613       }
2614 
2615       DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2616       if (spec_die) {
2617         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2618         if (decl_ctx_die)
2619           return decl_ctx_die;
2620       }
2621 
2622       DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2623       if (abs_die) {
2624         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2625         if (decl_ctx_die)
2626           return decl_ctx_die;
2627       }
2628 
2629       die = die.GetParent();
2630     }
2631   }
2632   return DWARFDIE();
2633 }
2634 
2635 Symbol *
2636 SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
2637   Symbol *objc_class_symbol = nullptr;
2638   if (m_obj_file) {
2639     Symtab *symtab = m_obj_file->GetSymtab();
2640     if (symtab) {
2641       objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2642           objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2643           Symtab::eVisibilityAny);
2644     }
2645   }
2646   return objc_class_symbol;
2647 }
2648 
2649 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2650 // they don't then we can end up looking through all class types for a complete
2651 // type and never find the full definition. We need to know if this attribute
2652 // is supported, so we determine this here and cache th result. We also need to
2653 // worry about the debug map
2654 // DWARF file
2655 // if we are doing darwin DWARF in .o file debugging.
2656 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(
2657     DWARFUnit *cu) {
2658   if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2659     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2660     if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2661       m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2662     else {
2663       DWARFDebugInfo *debug_info = DebugInfo();
2664       const uint32_t num_compile_units = GetNumCompileUnits();
2665       for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2666         DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx);
2667         if (dwarf_cu != cu &&
2668             dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2669           m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2670           break;
2671         }
2672       }
2673     }
2674     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2675         GetDebugMapSymfile())
2676       return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2677   }
2678   return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2679 }
2680 
2681 // This function can be used when a DIE is found that is a forward declaration
2682 // DIE and we want to try and find a type that has the complete definition.
2683 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2684     const DWARFDIE &die, ConstString type_name,
2685     bool must_be_implementation) {
2686 
2687   TypeSP type_sp;
2688 
2689   if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2690     return type_sp;
2691 
2692   DIEArray die_offsets;
2693   m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2694 
2695   const size_t num_matches = die_offsets.size();
2696 
2697   if (num_matches) {
2698     for (size_t i = 0; i < num_matches; ++i) {
2699       const DIERef &die_ref = die_offsets[i];
2700       DWARFDIE type_die = GetDIE(die_ref);
2701 
2702       if (type_die) {
2703         bool try_resolving_type = false;
2704 
2705         // Don't try and resolve the DIE we are looking for with the DIE
2706         // itself!
2707         if (type_die != die) {
2708           switch (type_die.Tag()) {
2709           case DW_TAG_class_type:
2710           case DW_TAG_structure_type:
2711             try_resolving_type = true;
2712             break;
2713           default:
2714             break;
2715           }
2716         }
2717 
2718         if (try_resolving_type) {
2719           if (must_be_implementation &&
2720               type_die.Supports_DW_AT_APPLE_objc_complete_type())
2721             try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2722                 DW_AT_APPLE_objc_complete_type, 0);
2723 
2724           if (try_resolving_type) {
2725             Type *resolved_type = ResolveType(type_die, false, true);
2726             if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2727               DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2728                            " (cu 0x%8.8" PRIx64 ")\n",
2729                            die.GetID(),
2730                            m_obj_file->GetFileSpec().GetFilename().AsCString(
2731                                "<Unknown>"),
2732                            type_die.GetID(), type_cu->GetID());
2733 
2734               if (die)
2735                 GetDIEToType()[die.GetDIE()] = resolved_type;
2736               type_sp = resolved_type->shared_from_this();
2737               break;
2738             }
2739           }
2740         }
2741       } else {
2742         m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2743       }
2744     }
2745   }
2746   return type_sp;
2747 }
2748 
2749 // This function helps to ensure that the declaration contexts match for two
2750 // different DIEs. Often times debug information will refer to a forward
2751 // declaration of a type (the equivalent of "struct my_struct;". There will
2752 // often be a declaration of that type elsewhere that has the full definition.
2753 // When we go looking for the full type "my_struct", we will find one or more
2754 // matches in the accelerator tables and we will then need to make sure the
2755 // type was in the same declaration context as the original DIE. This function
2756 // can efficiently compare two DIEs and will return true when the declaration
2757 // context matches, and false when they don't.
2758 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2759                                            const DWARFDIE &die2) {
2760   if (die1 == die2)
2761     return true;
2762 
2763   std::vector<DWARFDIE> decl_ctx_1;
2764   std::vector<DWARFDIE> decl_ctx_2;
2765   // The declaration DIE stack is a stack of the declaration context DIEs all
2766   // the way back to the compile unit. If a type "T" is declared inside a class
2767   // "B", and class "B" is declared inside a class "A" and class "A" is in a
2768   // namespace "lldb", and the namespace is in a compile unit, there will be a
2769   // stack of DIEs:
2770   //
2771   //   [0] DW_TAG_class_type for "B"
2772   //   [1] DW_TAG_class_type for "A"
2773   //   [2] DW_TAG_namespace  for "lldb"
2774   //   [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2775   //
2776   // We grab both contexts and make sure that everything matches all the way
2777   // back to the compiler unit.
2778 
2779   // First lets grab the decl contexts for both DIEs
2780   decl_ctx_1 = die1.GetDeclContextDIEs();
2781   decl_ctx_2 = die2.GetDeclContextDIEs();
2782   // Make sure the context arrays have the same size, otherwise we are done
2783   const size_t count1 = decl_ctx_1.size();
2784   const size_t count2 = decl_ctx_2.size();
2785   if (count1 != count2)
2786     return false;
2787 
2788   // Make sure the DW_TAG values match all the way back up the compile unit. If
2789   // they don't, then we are done.
2790   DWARFDIE decl_ctx_die1;
2791   DWARFDIE decl_ctx_die2;
2792   size_t i;
2793   for (i = 0; i < count1; i++) {
2794     decl_ctx_die1 = decl_ctx_1[i];
2795     decl_ctx_die2 = decl_ctx_2[i];
2796     if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2797       return false;
2798   }
2799 #ifndef NDEBUG
2800 
2801   // Make sure the top item in the decl context die array is always
2802   // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2803   // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2804   // function.
2805   dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag();
2806   UNUSED_IF_ASSERT_DISABLED(cu_tag);
2807   assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2808 
2809 #endif
2810   // Always skip the compile unit when comparing by only iterating up to "count
2811   // - 1". Here we compare the names as we go.
2812   for (i = 0; i < count1 - 1; i++) {
2813     decl_ctx_die1 = decl_ctx_1[i];
2814     decl_ctx_die2 = decl_ctx_2[i];
2815     const char *name1 = decl_ctx_die1.GetName();
2816     const char *name2 = decl_ctx_die2.GetName();
2817     // If the string was from a DW_FORM_strp, then the pointer will often be
2818     // the same!
2819     if (name1 == name2)
2820       continue;
2821 
2822     // Name pointers are not equal, so only compare the strings if both are not
2823     // NULL.
2824     if (name1 && name2) {
2825       // If the strings don't compare, we are done...
2826       if (strcmp(name1, name2) != 0)
2827         return false;
2828     } else {
2829       // One name was NULL while the other wasn't
2830       return false;
2831     }
2832   }
2833   // We made it through all of the checks and the declaration contexts are
2834   // equal.
2835   return true;
2836 }
2837 
2838 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2839     const DWARFDeclContext &dwarf_decl_ctx) {
2840   TypeSP type_sp;
2841 
2842   const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2843   if (dwarf_decl_ctx_count > 0) {
2844     const ConstString type_name(dwarf_decl_ctx[0].name);
2845     const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2846 
2847     if (type_name) {
2848       Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2849                                             DWARF_LOG_LOOKUPS));
2850       if (log) {
2851         GetObjectFile()->GetModule()->LogMessage(
2852             log, "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2853                  "s, qualified-name='%s')",
2854             DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2855             dwarf_decl_ctx.GetQualifiedName());
2856       }
2857 
2858       DIEArray die_offsets;
2859       m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2860       const size_t num_matches = die_offsets.size();
2861 
2862       // Get the type system that we are looking to find a type for. We will
2863       // use this to ensure any matches we find are in a language that this
2864       // type system supports
2865       const LanguageType language = dwarf_decl_ctx.GetLanguage();
2866       TypeSystem *type_system = (language == eLanguageTypeUnknown)
2867                                     ? nullptr
2868                                     : GetTypeSystemForLanguage(language);
2869 
2870       if (num_matches) {
2871         for (size_t i = 0; i < num_matches; ++i) {
2872           const DIERef &die_ref = die_offsets[i];
2873           DWARFDIE type_die = GetDIE(die_ref);
2874 
2875           if (type_die) {
2876             // Make sure type_die's langauge matches the type system we are
2877             // looking for. We don't want to find a "Foo" type from Java if we
2878             // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2879             if (type_system &&
2880                 !type_system->SupportsLanguage(type_die.GetLanguage()))
2881               continue;
2882             bool try_resolving_type = false;
2883 
2884             // Don't try and resolve the DIE we are looking for with the DIE
2885             // itself!
2886             const dw_tag_t type_tag = type_die.Tag();
2887             // Make sure the tags match
2888             if (type_tag == tag) {
2889               // The tags match, lets try resolving this type
2890               try_resolving_type = true;
2891             } else {
2892               // The tags don't match, but we need to watch our for a forward
2893               // declaration for a struct and ("struct foo") ends up being a
2894               // class ("class foo { ... };") or vice versa.
2895               switch (type_tag) {
2896               case DW_TAG_class_type:
2897                 // We had a "class foo", see if we ended up with a "struct foo
2898                 // { ... };"
2899                 try_resolving_type = (tag == DW_TAG_structure_type);
2900                 break;
2901               case DW_TAG_structure_type:
2902                 // We had a "struct foo", see if we ended up with a "class foo
2903                 // { ... };"
2904                 try_resolving_type = (tag == DW_TAG_class_type);
2905                 break;
2906               default:
2907                 // Tags don't match, don't event try to resolve using this type
2908                 // whose name matches....
2909                 break;
2910               }
2911             }
2912 
2913             if (try_resolving_type) {
2914               DWARFDeclContext type_dwarf_decl_ctx;
2915               type_die.GetDWARFDeclContext(type_dwarf_decl_ctx);
2916 
2917               if (log) {
2918                 GetObjectFile()->GetModule()->LogMessage(
2919                     log, "SymbolFileDWARF::"
2920                          "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2921                          "qualified-name='%s') trying die=0x%8.8x (%s)",
2922                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2923                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2924                     type_dwarf_decl_ctx.GetQualifiedName());
2925               }
2926 
2927               // Make sure the decl contexts match all the way up
2928               if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
2929                 Type *resolved_type = ResolveType(type_die, false);
2930                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2931                   type_sp = resolved_type->shared_from_this();
2932                   break;
2933                 }
2934               }
2935             } else {
2936               if (log) {
2937                 std::string qualified_name;
2938                 type_die.GetQualifiedName(qualified_name);
2939                 GetObjectFile()->GetModule()->LogMessage(
2940                     log, "SymbolFileDWARF::"
2941                          "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
2942                          "qualified-name='%s') ignoring die=0x%8.8x (%s)",
2943                     DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2944                     dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
2945                     qualified_name.c_str());
2946               }
2947             }
2948           } else {
2949             m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2950           }
2951         }
2952       }
2953     }
2954   }
2955   return type_sp;
2956 }
2957 
2958 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
2959                                   bool *type_is_new_ptr) {
2960   if (!die)
2961     return {};
2962 
2963   TypeSystem *type_system =
2964       GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
2965   if (!type_system)
2966     return {};
2967 
2968   DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
2969   if (!dwarf_ast)
2970     return {};
2971 
2972   Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
2973   TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, log, type_is_new_ptr);
2974   if (type_sp) {
2975     TypeList *type_list = GetTypeList();
2976     if (type_list)
2977       type_list->Insert(type_sp);
2978 
2979     if (die.Tag() == DW_TAG_subprogram) {
2980       std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
2981                                            .GetScopeQualifiedName()
2982                                            .AsCString(""));
2983       if (scope_qualified_name.size()) {
2984         m_function_scope_qualified_name_map[scope_qualified_name].insert(
2985             die.GetID());
2986       }
2987     }
2988   }
2989 
2990   return type_sp;
2991 }
2992 
2993 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
2994                                    const DWARFDIE &orig_die,
2995                                    bool parse_siblings, bool parse_children) {
2996   size_t types_added = 0;
2997   DWARFDIE die = orig_die;
2998   while (die) {
2999     bool type_is_new = false;
3000     if (ParseType(sc, die, &type_is_new).get()) {
3001       if (type_is_new)
3002         ++types_added;
3003     }
3004 
3005     if (parse_children && die.HasChildren()) {
3006       if (die.Tag() == DW_TAG_subprogram) {
3007         SymbolContext child_sc(sc);
3008         child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3009         types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3010       } else
3011         types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3012     }
3013 
3014     if (parse_siblings)
3015       die = die.GetSibling();
3016     else
3017       die.Clear();
3018   }
3019   return types_added;
3020 }
3021 
3022 size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) {
3023   ASSERT_MODULE_LOCK(this);
3024   CompileUnit *comp_unit = func.GetCompileUnit();
3025   lldbassert(comp_unit);
3026 
3027   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3028   if (!dwarf_cu)
3029     return 0;
3030 
3031   size_t functions_added = 0;
3032   const dw_offset_t function_die_offset = func.GetID();
3033   DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset);
3034   if (function_die) {
3035     ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die,
3036                          LLDB_INVALID_ADDRESS, 0);
3037   }
3038 
3039   return functions_added;
3040 }
3041 
3042 size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) {
3043   ASSERT_MODULE_LOCK(this);
3044   size_t types_added = 0;
3045   DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3046   if (dwarf_cu) {
3047     DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3048     if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3049       SymbolContext sc;
3050       sc.comp_unit = &comp_unit;
3051       types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3052     }
3053   }
3054 
3055   return types_added;
3056 }
3057 
3058 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3059   ASSERT_MODULE_LOCK(this);
3060   if (sc.comp_unit != nullptr) {
3061     DWARFDebugInfo *info = DebugInfo();
3062     if (info == nullptr)
3063       return 0;
3064 
3065     if (sc.function) {
3066       DWARFDIE function_die = GetDIE(sc.function->GetID());
3067 
3068       const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3069           DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3070       if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3071         const size_t num_variables = ParseVariables(
3072             sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3073 
3074         // Let all blocks know they have parse all their variables
3075         sc.function->GetBlock(false).SetDidParseVariables(true, true);
3076         return num_variables;
3077       }
3078     } else if (sc.comp_unit) {
3079       DWARFUnit *dwarf_cu = info->GetUnitAtIndex(sc.comp_unit->GetID());
3080 
3081       if (dwarf_cu == nullptr)
3082         return 0;
3083 
3084       uint32_t vars_added = 0;
3085       VariableListSP variables(sc.comp_unit->GetVariableList(false));
3086 
3087       if (variables.get() == nullptr) {
3088         variables = std::make_shared<VariableList>();
3089         sc.comp_unit->SetVariableList(variables);
3090 
3091         DIEArray die_offsets;
3092         m_index->GetGlobalVariables(dwarf_cu->GetNonSkeletonUnit(),
3093                                     die_offsets);
3094         const size_t num_matches = die_offsets.size();
3095         if (num_matches) {
3096           for (size_t i = 0; i < num_matches; ++i) {
3097             const DIERef &die_ref = die_offsets[i];
3098             DWARFDIE die = GetDIE(die_ref);
3099             if (die) {
3100               VariableSP var_sp(
3101                   ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3102               if (var_sp) {
3103                 variables->AddVariableIfUnique(var_sp);
3104                 ++vars_added;
3105               }
3106             } else
3107               m_index->ReportInvalidDIERef(die_ref, "");
3108           }
3109         }
3110       }
3111       return vars_added;
3112     }
3113   }
3114   return 0;
3115 }
3116 
3117 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3118                                              const DWARFDIE &die,
3119                                              const lldb::addr_t func_low_pc) {
3120   if (die.GetDWARF() != this)
3121     return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3122 
3123   VariableSP var_sp;
3124   if (!die)
3125     return var_sp;
3126 
3127   var_sp = GetDIEToVariable()[die.GetDIE()];
3128   if (var_sp)
3129     return var_sp; // Already been parsed!
3130 
3131   const dw_tag_t tag = die.Tag();
3132   ModuleSP module = GetObjectFile()->GetModule();
3133 
3134   if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3135       (tag == DW_TAG_formal_parameter && sc.function)) {
3136     DWARFAttributes attributes;
3137     const size_t num_attributes = die.GetAttributes(attributes);
3138     DWARFDIE spec_die;
3139     if (num_attributes > 0) {
3140       const char *name = nullptr;
3141       const char *mangled = nullptr;
3142       Declaration decl;
3143       uint32_t i;
3144       DWARFFormValue type_die_form;
3145       DWARFExpression location;
3146       bool is_external = false;
3147       bool is_artificial = false;
3148       bool location_is_const_value_data = false;
3149       bool has_explicit_location = false;
3150       DWARFFormValue const_value;
3151       Variable::RangeList scope_ranges;
3152       // AccessType accessibility = eAccessNone;
3153 
3154       for (i = 0; i < num_attributes; ++i) {
3155         dw_attr_t attr = attributes.AttributeAtIndex(i);
3156         DWARFFormValue form_value;
3157 
3158         if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3159           switch (attr) {
3160           case DW_AT_decl_file:
3161             decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3162                 form_value.Unsigned()));
3163             break;
3164           case DW_AT_decl_line:
3165             decl.SetLine(form_value.Unsigned());
3166             break;
3167           case DW_AT_decl_column:
3168             decl.SetColumn(form_value.Unsigned());
3169             break;
3170           case DW_AT_name:
3171             name = form_value.AsCString();
3172             break;
3173           case DW_AT_linkage_name:
3174           case DW_AT_MIPS_linkage_name:
3175             mangled = form_value.AsCString();
3176             break;
3177           case DW_AT_type:
3178             type_die_form = form_value;
3179             break;
3180           case DW_AT_external:
3181             is_external = form_value.Boolean();
3182             break;
3183           case DW_AT_const_value:
3184             // If we have already found a DW_AT_location attribute, ignore this
3185             // attribute.
3186             if (!has_explicit_location) {
3187               location_is_const_value_data = true;
3188               // The constant value will be either a block, a data value or a
3189               // string.
3190               auto debug_info_data = die.GetData();
3191               if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3192                 // Retrieve the value as a block expression.
3193                 uint32_t block_offset =
3194                     form_value.BlockData() - debug_info_data.GetDataStart();
3195                 uint32_t block_length = form_value.Unsigned();
3196                 location = DWARFExpression(module, debug_info_data, die.GetCU(),
3197                                            block_offset, block_length);
3198               } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3199                 // Retrieve the value as a data expression.
3200                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3201                 if (auto data_length = form_value.GetFixedSize())
3202                   location =
3203                       DWARFExpression(module, debug_info_data, die.GetCU(),
3204                                       data_offset, *data_length);
3205                 else {
3206                   const uint8_t *data_pointer = form_value.BlockData();
3207                   if (data_pointer) {
3208                     form_value.Unsigned();
3209                   } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3210                     // we need to get the byte size of the type later after we
3211                     // create the variable
3212                     const_value = form_value;
3213                   }
3214                 }
3215               } else {
3216                 // Retrieve the value as a string expression.
3217                 if (form_value.Form() == DW_FORM_strp) {
3218                   uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3219                   if (auto data_length = form_value.GetFixedSize())
3220                     location =
3221                         DWARFExpression(module, debug_info_data, die.GetCU(),
3222                                         data_offset, *data_length);
3223                 } else {
3224                   const char *str = form_value.AsCString();
3225                   uint32_t string_offset =
3226                       str - (const char *)debug_info_data.GetDataStart();
3227                   uint32_t string_length = strlen(str) + 1;
3228                   location =
3229                       DWARFExpression(module, debug_info_data, die.GetCU(),
3230                                       string_offset, string_length);
3231                 }
3232               }
3233             }
3234             break;
3235           case DW_AT_location: {
3236             location_is_const_value_data = false;
3237             has_explicit_location = true;
3238             if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3239               auto data = die.GetData();
3240 
3241               uint32_t block_offset =
3242                   form_value.BlockData() - data.GetDataStart();
3243               uint32_t block_length = form_value.Unsigned();
3244               location = DWARFExpression(module, data, die.GetCU(),
3245                                          block_offset, block_length);
3246             } else {
3247               const DWARFDataExtractor &debug_loc_data = DebugLocData();
3248               const dw_offset_t debug_loc_offset = form_value.Unsigned();
3249 
3250               size_t loc_list_length = DWARFExpression::LocationListSize(
3251                   die.GetCU(), debug_loc_data, debug_loc_offset);
3252               if (loc_list_length > 0) {
3253                 location = DWARFExpression(module, debug_loc_data, die.GetCU(),
3254                                            debug_loc_offset, loc_list_length);
3255                 assert(func_low_pc != LLDB_INVALID_ADDRESS);
3256                 location.SetLocationListSlide(
3257                     func_low_pc -
3258                     attributes.CompileUnitAtIndex(i)->GetBaseAddress());
3259               }
3260             }
3261           } break;
3262           case DW_AT_specification:
3263             spec_die = form_value.Reference();
3264             break;
3265           case DW_AT_start_scope:
3266             // TODO: Implement this.
3267             break;
3268           case DW_AT_artificial:
3269             is_artificial = form_value.Boolean();
3270             break;
3271           case DW_AT_accessibility:
3272             break; // accessibility =
3273                    // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3274           case DW_AT_declaration:
3275           case DW_AT_description:
3276           case DW_AT_endianity:
3277           case DW_AT_segment:
3278           case DW_AT_visibility:
3279           default:
3280           case DW_AT_abstract_origin:
3281           case DW_AT_sibling:
3282             break;
3283           }
3284         }
3285       }
3286 
3287       const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3288       const dw_tag_t parent_tag = die.GetParent().Tag();
3289       bool is_static_member =
3290           (parent_tag == DW_TAG_compile_unit ||
3291            parent_tag == DW_TAG_partial_unit) &&
3292           (parent_context_die.Tag() == DW_TAG_class_type ||
3293            parent_context_die.Tag() == DW_TAG_structure_type);
3294 
3295       ValueType scope = eValueTypeInvalid;
3296 
3297       const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3298       SymbolContextScope *symbol_context_scope = nullptr;
3299 
3300       bool has_explicit_mangled = mangled != nullptr;
3301       if (!mangled) {
3302         // LLDB relies on the mangled name (DW_TAG_linkage_name or
3303         // DW_AT_MIPS_linkage_name) to generate fully qualified names
3304         // of global variables with commands like "frame var j". For
3305         // example, if j were an int variable holding a value 4 and
3306         // declared in a namespace B which in turn is contained in a
3307         // namespace A, the command "frame var j" returns
3308         //   "(int) A::B::j = 4".
3309         // If the compiler does not emit a linkage name, we should be
3310         // able to generate a fully qualified name from the
3311         // declaration context.
3312         if ((parent_tag == DW_TAG_compile_unit ||
3313              parent_tag == DW_TAG_partial_unit) &&
3314             Language::LanguageIsCPlusPlus(die.GetLanguage())) {
3315           DWARFDeclContext decl_ctx;
3316 
3317           die.GetDWARFDeclContext(decl_ctx);
3318           mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
3319         }
3320       }
3321 
3322       if (tag == DW_TAG_formal_parameter)
3323         scope = eValueTypeVariableArgument;
3324       else {
3325         // DWARF doesn't specify if a DW_TAG_variable is a local, global
3326         // or static variable, so we have to do a little digging:
3327         // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3328         // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3329         // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3330         // Clang likes to combine small global variables into the same symbol
3331         // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3332         // so we need to look through the whole expression.
3333         bool is_static_lifetime =
3334             has_explicit_mangled ||
3335             (has_explicit_location && !location.IsValid());
3336         // Check if the location has a DW_OP_addr with any address value...
3337         lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3338         if (!location_is_const_value_data) {
3339           bool op_error = false;
3340           location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3341           if (op_error) {
3342             StreamString strm;
3343             location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3344                                             nullptr);
3345             GetObjectFile()->GetModule()->ReportError(
3346                 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3347                 die.GetTagAsCString(), strm.GetData());
3348           }
3349           if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3350             is_static_lifetime = true;
3351         }
3352         SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3353         if (debug_map_symfile)
3354           // Set the module of the expression to the linked module
3355           // instead of the oject file so the relocated address can be
3356           // found there.
3357           location.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3358 
3359         if (is_static_lifetime) {
3360           if (is_external)
3361             scope = eValueTypeVariableGlobal;
3362           else
3363             scope = eValueTypeVariableStatic;
3364 
3365           if (debug_map_symfile) {
3366             // When leaving the DWARF in the .o files on darwin, when we have a
3367             // global variable that wasn't initialized, the .o file might not
3368             // have allocated a virtual address for the global variable. In
3369             // this case it will have created a symbol for the global variable
3370             // that is undefined/data and external and the value will be the
3371             // byte size of the variable. When we do the address map in
3372             // SymbolFileDWARFDebugMap we rely on having an address, we need to
3373             // do some magic here so we can get the correct address for our
3374             // global variable. The address for all of these entries will be
3375             // zero, and there will be an undefined symbol in this object file,
3376             // and the executable will have a matching symbol with a good
3377             // address. So here we dig up the correct address and replace it in
3378             // the location for the variable, and set the variable's symbol
3379             // context scope to be that of the main executable so the file
3380             // address will resolve correctly.
3381             bool linked_oso_file_addr = false;
3382             if (is_external && location_DW_OP_addr == 0) {
3383               // we have a possible uninitialized extern global
3384               ConstString const_name(mangled ? mangled : name);
3385               ObjectFile *debug_map_objfile =
3386                   debug_map_symfile->GetObjectFile();
3387               if (debug_map_objfile) {
3388                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3389                 if (debug_map_symtab) {
3390                   Symbol *exe_symbol =
3391                       debug_map_symtab->FindFirstSymbolWithNameAndType(
3392                           const_name, eSymbolTypeData, Symtab::eDebugYes,
3393                           Symtab::eVisibilityExtern);
3394                   if (exe_symbol) {
3395                     if (exe_symbol->ValueIsAddress()) {
3396                       const addr_t exe_file_addr =
3397                           exe_symbol->GetAddressRef().GetFileAddress();
3398                       if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3399                         if (location.Update_DW_OP_addr(exe_file_addr)) {
3400                           linked_oso_file_addr = true;
3401                           symbol_context_scope = exe_symbol;
3402                         }
3403                       }
3404                     }
3405                   }
3406                 }
3407               }
3408             }
3409 
3410             if (!linked_oso_file_addr) {
3411               // The DW_OP_addr is not zero, but it contains a .o file address
3412               // which needs to be linked up correctly.
3413               const lldb::addr_t exe_file_addr =
3414                   debug_map_symfile->LinkOSOFileAddress(this,
3415                                                         location_DW_OP_addr);
3416               if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3417                 // Update the file address for this variable
3418                 location.Update_DW_OP_addr(exe_file_addr);
3419               } else {
3420                 // Variable didn't make it into the final executable
3421                 return var_sp;
3422               }
3423             }
3424           }
3425         } else {
3426           if (location_is_const_value_data)
3427             scope = eValueTypeVariableStatic;
3428           else {
3429             scope = eValueTypeVariableLocal;
3430             if (debug_map_symfile) {
3431               // We need to check for TLS addresses that we need to fixup
3432               if (location.ContainsThreadLocalStorage()) {
3433                 location.LinkThreadLocalStorage(
3434                     debug_map_symfile->GetObjectFile()->GetModule(),
3435                     [this, debug_map_symfile](
3436                         lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3437                       return debug_map_symfile->LinkOSOFileAddress(
3438                           this, unlinked_file_addr);
3439                     });
3440                 scope = eValueTypeVariableThreadLocal;
3441               }
3442             }
3443           }
3444         }
3445       }
3446 
3447       if (symbol_context_scope == nullptr) {
3448         switch (parent_tag) {
3449         case DW_TAG_subprogram:
3450         case DW_TAG_inlined_subroutine:
3451         case DW_TAG_lexical_block:
3452           if (sc.function) {
3453             symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3454                 sc_parent_die.GetID());
3455             if (symbol_context_scope == nullptr)
3456               symbol_context_scope = sc.function;
3457           }
3458           break;
3459 
3460         default:
3461           symbol_context_scope = sc.comp_unit;
3462           break;
3463         }
3464       }
3465 
3466       if (symbol_context_scope) {
3467         SymbolFileTypeSP type_sp(
3468             new SymbolFileType(*this, GetUID(type_die_form.Reference())));
3469 
3470         if (const_value.Form() && type_sp && type_sp->GetType())
3471           location.UpdateValue(const_value.Unsigned(),
3472                                type_sp->GetType()->GetByteSize().getValueOr(0),
3473                                die.GetCU()->GetAddressByteSize());
3474 
3475         var_sp = std::make_shared<Variable>(
3476             die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
3477             scope_ranges, &decl, location, is_external, is_artificial,
3478             is_static_member);
3479 
3480         var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3481       } else {
3482         // Not ready to parse this variable yet. It might be a global or static
3483         // variable that is in a function scope and the function in the symbol
3484         // context wasn't filled in yet
3485         return var_sp;
3486       }
3487     }
3488     // Cache var_sp even if NULL (the variable was just a specification or was
3489     // missing vital information to be able to be displayed in the debugger
3490     // (missing location due to optimization, etc)) so we don't re-parse this
3491     // DIE over and over later...
3492     GetDIEToVariable()[die.GetDIE()] = var_sp;
3493     if (spec_die)
3494       GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3495   }
3496   return var_sp;
3497 }
3498 
3499 DWARFDIE
3500 SymbolFileDWARF::FindBlockContainingSpecification(
3501     const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3502   // Give the concrete function die specified by "func_die_offset", find the
3503   // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3504   // to "spec_block_die_offset"
3505   return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3506                                           spec_block_die_offset);
3507 }
3508 
3509 DWARFDIE
3510 SymbolFileDWARF::FindBlockContainingSpecification(
3511     const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3512   if (die) {
3513     switch (die.Tag()) {
3514     case DW_TAG_subprogram:
3515     case DW_TAG_inlined_subroutine:
3516     case DW_TAG_lexical_block: {
3517       if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
3518           spec_block_die_offset)
3519         return die;
3520 
3521       if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
3522           spec_block_die_offset)
3523         return die;
3524     } break;
3525     }
3526 
3527     // Give the concrete function die specified by "func_die_offset", find the
3528     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3529     // to "spec_block_die_offset"
3530     for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3531          child_die = child_die.GetSibling()) {
3532       DWARFDIE result_die =
3533           FindBlockContainingSpecification(child_die, spec_block_die_offset);
3534       if (result_die)
3535         return result_die;
3536     }
3537   }
3538 
3539   return DWARFDIE();
3540 }
3541 
3542 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3543                                        const DWARFDIE &orig_die,
3544                                        const lldb::addr_t func_low_pc,
3545                                        bool parse_siblings, bool parse_children,
3546                                        VariableList *cc_variable_list) {
3547   if (!orig_die)
3548     return 0;
3549 
3550   VariableListSP variable_list_sp;
3551 
3552   size_t vars_added = 0;
3553   DWARFDIE die = orig_die;
3554   while (die) {
3555     dw_tag_t tag = die.Tag();
3556 
3557     // Check to see if we have already parsed this variable or constant?
3558     VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3559     if (var_sp) {
3560       if (cc_variable_list)
3561         cc_variable_list->AddVariableIfUnique(var_sp);
3562     } else {
3563       // We haven't already parsed it, lets do that now.
3564       if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3565           (tag == DW_TAG_formal_parameter && sc.function)) {
3566         if (variable_list_sp.get() == nullptr) {
3567           DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3568           dw_tag_t parent_tag = sc_parent_die.Tag();
3569           switch (parent_tag) {
3570           case DW_TAG_compile_unit:
3571           case DW_TAG_partial_unit:
3572             if (sc.comp_unit != nullptr) {
3573               variable_list_sp = sc.comp_unit->GetVariableList(false);
3574               if (variable_list_sp.get() == nullptr) {
3575                 variable_list_sp = std::make_shared<VariableList>();
3576               }
3577             } else {
3578               GetObjectFile()->GetModule()->ReportError(
3579                   "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3580                                          "symbol context for 0x%8.8" PRIx64
3581                   " %s.\n",
3582                   sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3583                   orig_die.GetID(), orig_die.GetTagAsCString());
3584             }
3585             break;
3586 
3587           case DW_TAG_subprogram:
3588           case DW_TAG_inlined_subroutine:
3589           case DW_TAG_lexical_block:
3590             if (sc.function != nullptr) {
3591               // Check to see if we already have parsed the variables for the
3592               // given scope
3593 
3594               Block *block = sc.function->GetBlock(true).FindBlockByID(
3595                   sc_parent_die.GetID());
3596               if (block == nullptr) {
3597                 // This must be a specification or abstract origin with a
3598                 // concrete block counterpart in the current function. We need
3599                 // to find the concrete block so we can correctly add the
3600                 // variable to it
3601                 const DWARFDIE concrete_block_die =
3602                     FindBlockContainingSpecification(
3603                         GetDIE(sc.function->GetID()),
3604                         sc_parent_die.GetOffset());
3605                 if (concrete_block_die)
3606                   block = sc.function->GetBlock(true).FindBlockByID(
3607                       concrete_block_die.GetID());
3608               }
3609 
3610               if (block != nullptr) {
3611                 const bool can_create = false;
3612                 variable_list_sp = block->GetBlockVariableList(can_create);
3613                 if (variable_list_sp.get() == nullptr) {
3614                   variable_list_sp = std::make_shared<VariableList>();
3615                   block->SetVariableList(variable_list_sp);
3616                 }
3617               }
3618             }
3619             break;
3620 
3621           default:
3622             GetObjectFile()->GetModule()->ReportError(
3623                 "didn't find appropriate parent DIE for variable list for "
3624                 "0x%8.8" PRIx64 " %s.\n",
3625                 orig_die.GetID(), orig_die.GetTagAsCString());
3626             break;
3627           }
3628         }
3629 
3630         if (variable_list_sp) {
3631           VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3632           if (var_sp) {
3633             variable_list_sp->AddVariableIfUnique(var_sp);
3634             if (cc_variable_list)
3635               cc_variable_list->AddVariableIfUnique(var_sp);
3636             ++vars_added;
3637           }
3638         }
3639       }
3640     }
3641 
3642     bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram);
3643 
3644     if (!skip_children && parse_children && die.HasChildren()) {
3645       vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3646                                    true, cc_variable_list);
3647     }
3648 
3649     if (parse_siblings)
3650       die = die.GetSibling();
3651     else
3652       die.Clear();
3653   }
3654   return vars_added;
3655 }
3656 
3657 /// Collect call graph edges present in a function DIE.
3658 static std::vector<lldb_private::CallEdge>
3659 CollectCallEdges(DWARFDIE function_die) {
3660   // Check if the function has a supported call site-related attribute.
3661   // TODO: In the future it may be worthwhile to support call_all_source_calls.
3662   uint64_t has_call_edges =
3663       function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0);
3664   if (!has_call_edges)
3665     return {};
3666 
3667   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3668   LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
3669            function_die.GetPubname());
3670 
3671   // Scan the DIE for TAG_call_site entries.
3672   // TODO: A recursive scan of all blocks in the subprogram is needed in order
3673   // to be DWARF5-compliant. This may need to be done lazily to be performant.
3674   // For now, assume that all entries are nested directly under the subprogram
3675   // (this is the kind of DWARF LLVM produces) and parse them eagerly.
3676   std::vector<CallEdge> call_edges;
3677   for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid();
3678        child = child.GetSibling()) {
3679     if (child.Tag() != DW_TAG_call_site)
3680       continue;
3681 
3682     // Extract DW_AT_call_origin (the call target's DIE).
3683     DWARFDIE call_origin = child.GetReferencedDIE(DW_AT_call_origin);
3684     if (!call_origin.IsValid()) {
3685       LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
3686                function_die.GetPubname());
3687       continue;
3688     }
3689 
3690     // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
3691     // available. It should only ever be unavailable for tail call edges, in
3692     // which case use LLDB_INVALID_ADDRESS.
3693     addr_t return_pc = child.GetAttributeValueAsAddress(DW_AT_call_return_pc,
3694                                                         LLDB_INVALID_ADDRESS);
3695 
3696     LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x})",
3697              call_origin.GetPubname(), return_pc);
3698     call_edges.emplace_back(call_origin.GetMangledName(), return_pc);
3699   }
3700   return call_edges;
3701 }
3702 
3703 std::vector<lldb_private::CallEdge>
3704 SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) {
3705   DWARFDIE func_die = GetDIE(func_id.GetID());
3706   if (func_die.IsValid())
3707     return CollectCallEdges(func_die);
3708   return {};
3709 }
3710 
3711 // PluginInterface protocol
3712 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3713 
3714 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3715 
3716 void SymbolFileDWARF::Dump(lldb_private::Stream &s) { m_index->Dump(s); }
3717 
3718 void SymbolFileDWARF::DumpClangAST(Stream &s) {
3719   TypeSystem *ts = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
3720   ClangASTContext *clang = llvm::dyn_cast_or_null<ClangASTContext>(ts);
3721   if (!clang)
3722     return;
3723   clang->Dump(s);
3724 }
3725 
3726 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3727   if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) {
3728     lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3729     if (module_sp) {
3730       SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
3731       if (sym_vendor)
3732         m_debug_map_symfile =
3733             (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
3734     }
3735   }
3736   return m_debug_map_symfile;
3737 }
3738 
3739 DWARFExpression::LocationListFormat
3740 SymbolFileDWARF::GetLocationListFormat() const {
3741   if (m_data_debug_loclists.m_data.GetByteSize() > 0)
3742     return DWARFExpression::LocLists;
3743   return DWARFExpression::RegularLocationList;
3744 }
3745 
3746 SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() {
3747   llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3748     ModuleSpec module_spec;
3749     module_spec.GetFileSpec() = m_obj_file->GetFileSpec();
3750     module_spec.GetSymbolFileSpec() =
3751         FileSpec(m_obj_file->GetFileSpec().GetPath() + ".dwp");
3752 
3753     FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
3754     FileSpec dwp_filespec =
3755         Symbols::LocateExecutableSymbolFile(module_spec, search_paths);
3756     if (FileSystem::Instance().Exists(dwp_filespec)) {
3757       m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(),
3758                                                  dwp_filespec);
3759     }
3760   });
3761   return m_dwp_symfile.get();
3762 }
3763