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