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