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