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