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