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