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