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