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