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