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