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