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