xref: /freebsd/contrib/llvm-project/lldb/source/Plugins/SymbolFile/PDB/SymbolFilePDB.cpp (revision ebacd8013fe5f7fdf9f6a5b286f6680dd2891036)
1 //===-- SymbolFilePDB.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 "SymbolFilePDB.h"
10 
11 #include "PDBASTParser.h"
12 #include "PDBLocationToDWARFExpression.h"
13 
14 #include "clang/Lex/Lexer.h"
15 
16 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Symbol/CompileUnit.h"
20 #include "lldb/Symbol/LineTable.h"
21 #include "lldb/Symbol/ObjectFile.h"
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Symbol/SymbolVendor.h"
24 #include "lldb/Symbol/TypeList.h"
25 #include "lldb/Symbol/TypeMap.h"
26 #include "lldb/Symbol/Variable.h"
27 #include "lldb/Utility/LLDBLog.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/RegularExpression.h"
30 
31 #include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h"
32 #include "llvm/DebugInfo/PDB/GenericError.h"
33 #include "llvm/DebugInfo/PDB/IPDBDataStream.h"
34 #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
35 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
36 #include "llvm/DebugInfo/PDB/IPDBSectionContrib.h"
37 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
38 #include "llvm/DebugInfo/PDB/IPDBTable.h"
39 #include "llvm/DebugInfo/PDB/PDBSymbol.h"
40 #include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"
41 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
42 #include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
43 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
44 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
45 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
46 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
47 #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
48 #include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
49 #include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h"
50 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
51 #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"
52 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
53 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
54 
55 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
56 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
57 #include "Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.h"
58 
59 #if defined(_WIN32)
60 #include "llvm/Config/llvm-config.h"
61 #endif
62 
63 using namespace lldb;
64 using namespace lldb_private;
65 using namespace llvm::pdb;
66 
67 LLDB_PLUGIN_DEFINE(SymbolFilePDB)
68 
69 char SymbolFilePDB::ID;
70 
71 namespace {
72 lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
73   switch (lang) {
74   case PDB_Lang::Cpp:
75     return lldb::LanguageType::eLanguageTypeC_plus_plus;
76   case PDB_Lang::C:
77     return lldb::LanguageType::eLanguageTypeC;
78   case PDB_Lang::Swift:
79     return lldb::LanguageType::eLanguageTypeSwift;
80   case PDB_Lang::Rust:
81     return lldb::LanguageType::eLanguageTypeRust;
82   default:
83     return lldb::LanguageType::eLanguageTypeUnknown;
84   }
85 }
86 
87 bool ShouldAddLine(uint32_t requested_line, uint32_t actual_line,
88                    uint32_t addr_length) {
89   return ((requested_line == 0 || actual_line == requested_line) &&
90           addr_length > 0);
91 }
92 } // namespace
93 
94 static bool ShouldUseNativeReader() {
95 #if defined(_WIN32)
96 #if LLVM_ENABLE_DIA_SDK
97   llvm::StringRef use_native = ::getenv("LLDB_USE_NATIVE_PDB_READER");
98   if (!use_native.equals_insensitive("on") &&
99       !use_native.equals_insensitive("yes") &&
100       !use_native.equals_insensitive("1") &&
101       !use_native.equals_insensitive("true"))
102     return false;
103 #endif
104 #endif
105   return true;
106 }
107 
108 void SymbolFilePDB::Initialize() {
109   if (ShouldUseNativeReader()) {
110     npdb::SymbolFileNativePDB::Initialize();
111   } else {
112     PluginManager::RegisterPlugin(GetPluginNameStatic(),
113                                   GetPluginDescriptionStatic(), CreateInstance,
114                                   DebuggerInitialize);
115   }
116 }
117 
118 void SymbolFilePDB::Terminate() {
119   if (ShouldUseNativeReader()) {
120     npdb::SymbolFileNativePDB::Terminate();
121   } else {
122     PluginManager::UnregisterPlugin(CreateInstance);
123   }
124 }
125 
126 void SymbolFilePDB::DebuggerInitialize(lldb_private::Debugger &debugger) {}
127 
128 llvm::StringRef SymbolFilePDB::GetPluginDescriptionStatic() {
129   return "Microsoft PDB debug symbol file reader.";
130 }
131 
132 lldb_private::SymbolFile *
133 SymbolFilePDB::CreateInstance(ObjectFileSP objfile_sp) {
134   return new SymbolFilePDB(std::move(objfile_sp));
135 }
136 
137 SymbolFilePDB::SymbolFilePDB(lldb::ObjectFileSP objfile_sp)
138     : SymbolFileCommon(std::move(objfile_sp)), m_session_up(), m_global_scope_up() {}
139 
140 SymbolFilePDB::~SymbolFilePDB() = default;
141 
142 uint32_t SymbolFilePDB::CalculateAbilities() {
143   uint32_t abilities = 0;
144   if (!m_objfile_sp)
145     return 0;
146 
147   if (!m_session_up) {
148     // Lazily load and match the PDB file, but only do this once.
149     std::string exePath = m_objfile_sp->GetFileSpec().GetPath();
150     auto error = loadDataForEXE(PDB_ReaderType::DIA, llvm::StringRef(exePath),
151                                 m_session_up);
152     if (error) {
153       llvm::consumeError(std::move(error));
154       auto module_sp = m_objfile_sp->GetModule();
155       if (!module_sp)
156         return 0;
157       // See if any symbol file is specified through `--symfile` option.
158       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
159       if (!symfile)
160         return 0;
161       error = loadDataForPDB(PDB_ReaderType::DIA,
162                              llvm::StringRef(symfile.GetPath()), m_session_up);
163       if (error) {
164         llvm::consumeError(std::move(error));
165         return 0;
166       }
167     }
168   }
169   if (!m_session_up)
170     return 0;
171 
172   auto enum_tables_up = m_session_up->getEnumTables();
173   if (!enum_tables_up)
174     return 0;
175   while (auto table_up = enum_tables_up->getNext()) {
176     if (table_up->getItemCount() == 0)
177       continue;
178     auto type = table_up->getTableType();
179     switch (type) {
180     case PDB_TableType::Symbols:
181       // This table represents a store of symbols with types listed in
182       // PDBSym_Type
183       abilities |= (CompileUnits | Functions | Blocks | GlobalVariables |
184                     LocalVariables | VariableTypes);
185       break;
186     case PDB_TableType::LineNumbers:
187       abilities |= LineTables;
188       break;
189     default:
190       break;
191     }
192   }
193   return abilities;
194 }
195 
196 void SymbolFilePDB::InitializeObject() {
197   lldb::addr_t obj_load_address =
198       m_objfile_sp->GetBaseAddress().GetFileAddress();
199   lldbassert(obj_load_address && obj_load_address != LLDB_INVALID_ADDRESS);
200   m_session_up->setLoadAddress(obj_load_address);
201   if (!m_global_scope_up)
202     m_global_scope_up = m_session_up->getGlobalScope();
203   lldbassert(m_global_scope_up.get());
204 }
205 
206 uint32_t SymbolFilePDB::CalculateNumCompileUnits() {
207   auto compilands = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
208   if (!compilands)
209     return 0;
210 
211   // The linker could link *.dll (compiland language = LINK), or import
212   // *.dll. For example, a compiland with name `Import:KERNEL32.dll` could be
213   // found as a child of the global scope (PDB executable). Usually, such
214   // compilands contain `thunk` symbols in which we are not interested for
215   // now. However we still count them in the compiland list. If we perform
216   // any compiland related activity, like finding symbols through
217   // llvm::pdb::IPDBSession methods, such compilands will all be searched
218   // automatically no matter whether we include them or not.
219   uint32_t compile_unit_count = compilands->getChildCount();
220 
221   // The linker can inject an additional "dummy" compilation unit into the
222   // PDB. Ignore this special compile unit for our purposes, if it is there.
223   // It is always the last one.
224   auto last_compiland_up = compilands->getChildAtIndex(compile_unit_count - 1);
225   lldbassert(last_compiland_up.get());
226   std::string name = last_compiland_up->getName();
227   if (name == "* Linker *")
228     --compile_unit_count;
229   return compile_unit_count;
230 }
231 
232 void SymbolFilePDB::GetCompileUnitIndex(
233     const llvm::pdb::PDBSymbolCompiland &pdb_compiland, uint32_t &index) {
234   auto results_up = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
235   if (!results_up)
236     return;
237   auto uid = pdb_compiland.getSymIndexId();
238   for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
239     auto compiland_up = results_up->getChildAtIndex(cu_idx);
240     if (!compiland_up)
241       continue;
242     if (compiland_up->getSymIndexId() == uid) {
243       index = cu_idx;
244       return;
245     }
246   }
247   index = UINT32_MAX;
248 }
249 
250 std::unique_ptr<llvm::pdb::PDBSymbolCompiland>
251 SymbolFilePDB::GetPDBCompilandByUID(uint32_t uid) {
252   return m_session_up->getConcreteSymbolById<PDBSymbolCompiland>(uid);
253 }
254 
255 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitAtIndex(uint32_t index) {
256   if (index >= GetNumCompileUnits())
257     return CompUnitSP();
258 
259   // Assuming we always retrieve same compilands listed in same order through
260   // `PDBSymbolExe::findAllChildren` method, otherwise using `index` to get a
261   // compile unit makes no sense.
262   auto results = m_global_scope_up->findAllChildren<PDBSymbolCompiland>();
263   if (!results)
264     return CompUnitSP();
265   auto compiland_up = results->getChildAtIndex(index);
266   if (!compiland_up)
267     return CompUnitSP();
268   return ParseCompileUnitForUID(compiland_up->getSymIndexId(), index);
269 }
270 
271 lldb::LanguageType SymbolFilePDB::ParseLanguage(CompileUnit &comp_unit) {
272   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
273   auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
274   if (!compiland_up)
275     return lldb::eLanguageTypeUnknown;
276   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
277   if (!details)
278     return lldb::eLanguageTypeUnknown;
279   return TranslateLanguage(details->getLanguage());
280 }
281 
282 lldb_private::Function *
283 SymbolFilePDB::ParseCompileUnitFunctionForPDBFunc(const PDBSymbolFunc &pdb_func,
284                                                   CompileUnit &comp_unit) {
285   if (FunctionSP result = comp_unit.FindFunctionByUID(pdb_func.getSymIndexId()))
286     return result.get();
287 
288   auto file_vm_addr = pdb_func.getVirtualAddress();
289   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
290     return nullptr;
291 
292   auto func_length = pdb_func.getLength();
293   AddressRange func_range =
294       AddressRange(file_vm_addr, func_length,
295                    GetObjectFile()->GetModule()->GetSectionList());
296   if (!func_range.GetBaseAddress().IsValid())
297     return nullptr;
298 
299   lldb_private::Type *func_type = ResolveTypeUID(pdb_func.getSymIndexId());
300   if (!func_type)
301     return nullptr;
302 
303   user_id_t func_type_uid = pdb_func.getSignatureId();
304 
305   Mangled mangled = GetMangledForPDBFunc(pdb_func);
306 
307   FunctionSP func_sp =
308       std::make_shared<Function>(&comp_unit, pdb_func.getSymIndexId(),
309                                  func_type_uid, mangled, func_type, func_range);
310 
311   comp_unit.AddFunction(func_sp);
312 
313   LanguageType lang = ParseLanguage(comp_unit);
314   auto type_system_or_err = GetTypeSystemForLanguage(lang);
315   if (auto err = type_system_or_err.takeError()) {
316     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
317                    "Unable to parse PDBFunc");
318     return nullptr;
319   }
320 
321   TypeSystemClang *clang_type_system =
322     llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
323   if (!clang_type_system)
324     return nullptr;
325   clang_type_system->GetPDBParser()->GetDeclForSymbol(pdb_func);
326 
327   return func_sp.get();
328 }
329 
330 size_t SymbolFilePDB::ParseFunctions(CompileUnit &comp_unit) {
331   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
332   size_t func_added = 0;
333   auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
334   if (!compiland_up)
335     return 0;
336   auto results_up = compiland_up->findAllChildren<PDBSymbolFunc>();
337   if (!results_up)
338     return 0;
339   while (auto pdb_func_up = results_up->getNext()) {
340     auto func_sp = comp_unit.FindFunctionByUID(pdb_func_up->getSymIndexId());
341     if (!func_sp) {
342       if (ParseCompileUnitFunctionForPDBFunc(*pdb_func_up, comp_unit))
343         ++func_added;
344     }
345   }
346   return func_added;
347 }
348 
349 bool SymbolFilePDB::ParseLineTable(CompileUnit &comp_unit) {
350   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
351   if (comp_unit.GetLineTable())
352     return true;
353   return ParseCompileUnitLineTable(comp_unit, 0);
354 }
355 
356 bool SymbolFilePDB::ParseDebugMacros(CompileUnit &comp_unit) {
357   // PDB doesn't contain information about macros
358   return false;
359 }
360 
361 bool SymbolFilePDB::ParseSupportFiles(
362     CompileUnit &comp_unit, lldb_private::FileSpecList &support_files) {
363 
364   // In theory this is unnecessary work for us, because all of this information
365   // is easily (and quickly) accessible from DebugInfoPDB, so caching it a
366   // second time seems like a waste.  Unfortunately, there's no good way around
367   // this short of a moderate refactor since SymbolVendor depends on being able
368   // to cache this list.
369   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
370   auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
371   if (!compiland_up)
372     return false;
373   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
374   if (!files || files->getChildCount() == 0)
375     return false;
376 
377   while (auto file = files->getNext()) {
378     FileSpec spec(file->getFileName(), FileSpec::Style::windows);
379     support_files.AppendIfUnique(spec);
380   }
381 
382   return true;
383 }
384 
385 bool SymbolFilePDB::ParseImportedModules(
386     const lldb_private::SymbolContext &sc,
387     std::vector<SourceModule> &imported_modules) {
388   // PDB does not yet support module debug info
389   return false;
390 }
391 
392 static size_t ParseFunctionBlocksForPDBSymbol(
393     uint64_t func_file_vm_addr, const llvm::pdb::PDBSymbol *pdb_symbol,
394     lldb_private::Block *parent_block, bool is_top_parent) {
395   assert(pdb_symbol && parent_block);
396 
397   size_t num_added = 0;
398   switch (pdb_symbol->getSymTag()) {
399   case PDB_SymType::Block:
400   case PDB_SymType::Function: {
401     Block *block = nullptr;
402     auto &raw_sym = pdb_symbol->getRawSymbol();
403     if (auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(pdb_symbol)) {
404       if (pdb_func->hasNoInlineAttribute())
405         break;
406       if (is_top_parent)
407         block = parent_block;
408       else
409         break;
410     } else if (llvm::isa<PDBSymbolBlock>(pdb_symbol)) {
411       auto uid = pdb_symbol->getSymIndexId();
412       if (parent_block->FindBlockByID(uid))
413         break;
414       if (raw_sym.getVirtualAddress() < func_file_vm_addr)
415         break;
416 
417       auto block_sp = std::make_shared<Block>(pdb_symbol->getSymIndexId());
418       parent_block->AddChild(block_sp);
419       block = block_sp.get();
420     } else
421       llvm_unreachable("Unexpected PDB symbol!");
422 
423     block->AddRange(Block::Range(
424         raw_sym.getVirtualAddress() - func_file_vm_addr, raw_sym.getLength()));
425     block->FinalizeRanges();
426     ++num_added;
427 
428     auto results_up = pdb_symbol->findAllChildren();
429     if (!results_up)
430       break;
431     while (auto symbol_up = results_up->getNext()) {
432       num_added += ParseFunctionBlocksForPDBSymbol(
433           func_file_vm_addr, symbol_up.get(), block, false);
434     }
435   } break;
436   default:
437     break;
438   }
439   return num_added;
440 }
441 
442 size_t SymbolFilePDB::ParseBlocksRecursive(Function &func) {
443   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
444   size_t num_added = 0;
445   auto uid = func.GetID();
446   auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
447   if (!pdb_func_up)
448     return 0;
449   Block &parent_block = func.GetBlock(false);
450   num_added = ParseFunctionBlocksForPDBSymbol(
451       pdb_func_up->getVirtualAddress(), pdb_func_up.get(), &parent_block, true);
452   return num_added;
453 }
454 
455 size_t SymbolFilePDB::ParseTypes(CompileUnit &comp_unit) {
456   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
457 
458   size_t num_added = 0;
459   auto compiland = GetPDBCompilandByUID(comp_unit.GetID());
460   if (!compiland)
461     return 0;
462 
463   auto ParseTypesByTagFn = [&num_added, this](const PDBSymbol &raw_sym) {
464     std::unique_ptr<IPDBEnumSymbols> results;
465     PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
466                                     PDB_SymType::UDT};
467     for (auto tag : tags_to_search) {
468       results = raw_sym.findAllChildren(tag);
469       if (!results || results->getChildCount() == 0)
470         continue;
471       while (auto symbol = results->getNext()) {
472         switch (symbol->getSymTag()) {
473         case PDB_SymType::Enum:
474         case PDB_SymType::UDT:
475         case PDB_SymType::Typedef:
476           break;
477         default:
478           continue;
479         }
480 
481         // This should cause the type to get cached and stored in the `m_types`
482         // lookup.
483         if (auto type = ResolveTypeUID(symbol->getSymIndexId())) {
484           // Resolve the type completely to avoid a completion
485           // (and so a list change, which causes an iterators invalidation)
486           // during a TypeList dumping
487           type->GetFullCompilerType();
488           ++num_added;
489         }
490       }
491     }
492   };
493 
494   ParseTypesByTagFn(*compiland);
495 
496   // Also parse global types particularly coming from this compiland.
497   // Unfortunately, PDB has no compiland information for each global type. We
498   // have to parse them all. But ensure we only do this once.
499   static bool parse_all_global_types = false;
500   if (!parse_all_global_types) {
501     ParseTypesByTagFn(*m_global_scope_up);
502     parse_all_global_types = true;
503   }
504   return num_added;
505 }
506 
507 size_t
508 SymbolFilePDB::ParseVariablesForContext(const lldb_private::SymbolContext &sc) {
509   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
510   if (!sc.comp_unit)
511     return 0;
512 
513   size_t num_added = 0;
514   if (sc.function) {
515     auto pdb_func = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(
516         sc.function->GetID());
517     if (!pdb_func)
518       return 0;
519 
520     num_added += ParseVariables(sc, *pdb_func);
521     sc.function->GetBlock(false).SetDidParseVariables(true, true);
522   } else if (sc.comp_unit) {
523     auto compiland = GetPDBCompilandByUID(sc.comp_unit->GetID());
524     if (!compiland)
525       return 0;
526 
527     if (sc.comp_unit->GetVariableList(false))
528       return 0;
529 
530     auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
531     if (results && results->getChildCount()) {
532       while (auto result = results->getNext()) {
533         auto cu_id = GetCompilandId(*result);
534         // FIXME: We are not able to determine variable's compile unit.
535         if (cu_id == 0)
536           continue;
537 
538         if (cu_id == sc.comp_unit->GetID())
539           num_added += ParseVariables(sc, *result);
540       }
541     }
542 
543     // FIXME: A `file static` or `global constant` variable appears both in
544     // compiland's children and global scope's children with unexpectedly
545     // different symbol's Id making it ambiguous.
546 
547     // FIXME: 'local constant', for example, const char var[] = "abc", declared
548     // in a function scope, can't be found in PDB.
549 
550     // Parse variables in this compiland.
551     num_added += ParseVariables(sc, *compiland);
552   }
553 
554   return num_added;
555 }
556 
557 lldb_private::Type *SymbolFilePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
558   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
559   auto find_result = m_types.find(type_uid);
560   if (find_result != m_types.end())
561     return find_result->second.get();
562 
563   auto type_system_or_err =
564       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
565   if (auto err = type_system_or_err.takeError()) {
566     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
567                    "Unable to ResolveTypeUID");
568     return nullptr;
569   }
570 
571   TypeSystemClang *clang_type_system =
572       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
573   if (!clang_type_system)
574     return nullptr;
575   PDBASTParser *pdb = clang_type_system->GetPDBParser();
576   if (!pdb)
577     return nullptr;
578 
579   auto pdb_type = m_session_up->getSymbolById(type_uid);
580   if (pdb_type == nullptr)
581     return nullptr;
582 
583   lldb::TypeSP result = pdb->CreateLLDBTypeFromPDBType(*pdb_type);
584   if (result) {
585     m_types.insert(std::make_pair(type_uid, result));
586     GetTypeList().Insert(result);
587   }
588   return result.get();
589 }
590 
591 llvm::Optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID(
592     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
593   return llvm::None;
594 }
595 
596 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) {
597   std::lock_guard<std::recursive_mutex> guard(
598       GetObjectFile()->GetModule()->GetMutex());
599 
600   auto type_system_or_err =
601       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
602   if (auto err = type_system_or_err.takeError()) {
603     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
604                    "Unable to get dynamic array info for UID");
605     return false;
606   }
607 
608   TypeSystemClang *clang_ast_ctx =
609       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
610 
611   if (!clang_ast_ctx)
612     return false;
613 
614   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
615   if (!pdb)
616     return false;
617 
618   return pdb->CompleteTypeFromPDB(compiler_type);
619 }
620 
621 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) {
622   auto type_system_or_err =
623       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
624   if (auto err = type_system_or_err.takeError()) {
625     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
626                    "Unable to get decl for UID");
627     return CompilerDecl();
628   }
629 
630   TypeSystemClang *clang_ast_ctx =
631       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
632   if (!clang_ast_ctx)
633     return CompilerDecl();
634 
635   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
636   if (!pdb)
637     return CompilerDecl();
638 
639   auto symbol = m_session_up->getSymbolById(uid);
640   if (!symbol)
641     return CompilerDecl();
642 
643   auto decl = pdb->GetDeclForSymbol(*symbol);
644   if (!decl)
645     return CompilerDecl();
646 
647   return clang_ast_ctx->GetCompilerDecl(decl);
648 }
649 
650 lldb_private::CompilerDeclContext
651 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) {
652   auto type_system_or_err =
653       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
654   if (auto err = type_system_or_err.takeError()) {
655     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
656                    "Unable to get DeclContext for UID");
657     return CompilerDeclContext();
658   }
659 
660   TypeSystemClang *clang_ast_ctx =
661       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
662   if (!clang_ast_ctx)
663     return CompilerDeclContext();
664 
665   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
666   if (!pdb)
667     return CompilerDeclContext();
668 
669   auto symbol = m_session_up->getSymbolById(uid);
670   if (!symbol)
671     return CompilerDeclContext();
672 
673   auto decl_context = pdb->GetDeclContextForSymbol(*symbol);
674   if (!decl_context)
675     return GetDeclContextContainingUID(uid);
676 
677   return clang_ast_ctx->CreateDeclContext(decl_context);
678 }
679 
680 lldb_private::CompilerDeclContext
681 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
682   auto type_system_or_err =
683       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
684   if (auto err = type_system_or_err.takeError()) {
685     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
686                    "Unable to get DeclContext containing UID");
687     return CompilerDeclContext();
688   }
689 
690   TypeSystemClang *clang_ast_ctx =
691       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
692   if (!clang_ast_ctx)
693     return CompilerDeclContext();
694 
695   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
696   if (!pdb)
697     return CompilerDeclContext();
698 
699   auto symbol = m_session_up->getSymbolById(uid);
700   if (!symbol)
701     return CompilerDeclContext();
702 
703   auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol);
704   assert(decl_context);
705 
706   return clang_ast_ctx->CreateDeclContext(decl_context);
707 }
708 
709 void SymbolFilePDB::ParseDeclsForContext(
710     lldb_private::CompilerDeclContext decl_ctx) {
711   auto type_system_or_err =
712       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
713   if (auto err = type_system_or_err.takeError()) {
714     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
715                    "Unable to parse decls for context");
716     return;
717   }
718 
719   TypeSystemClang *clang_ast_ctx =
720       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
721   if (!clang_ast_ctx)
722     return;
723 
724   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
725   if (!pdb)
726     return;
727 
728   pdb->ParseDeclsForDeclContext(
729       static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext()));
730 }
731 
732 uint32_t
733 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr,
734                                     SymbolContextItem resolve_scope,
735                                     lldb_private::SymbolContext &sc) {
736   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
737   uint32_t resolved_flags = 0;
738   if (resolve_scope & eSymbolContextCompUnit ||
739       resolve_scope & eSymbolContextVariable ||
740       resolve_scope & eSymbolContextFunction ||
741       resolve_scope & eSymbolContextBlock ||
742       resolve_scope & eSymbolContextLineEntry) {
743     auto cu_sp = GetCompileUnitContainsAddress(so_addr);
744     if (!cu_sp) {
745       if (resolved_flags & eSymbolContextVariable) {
746         // TODO: Resolve variables
747       }
748       return 0;
749     }
750     sc.comp_unit = cu_sp.get();
751     resolved_flags |= eSymbolContextCompUnit;
752     lldbassert(sc.module_sp == cu_sp->GetModule());
753   }
754 
755   if (resolve_scope & eSymbolContextFunction ||
756       resolve_scope & eSymbolContextBlock) {
757     addr_t file_vm_addr = so_addr.GetFileAddress();
758     auto symbol_up =
759         m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function);
760     if (symbol_up) {
761       auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
762       assert(pdb_func);
763       auto func_uid = pdb_func->getSymIndexId();
764       sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
765       if (sc.function == nullptr)
766         sc.function =
767             ParseCompileUnitFunctionForPDBFunc(*pdb_func, *sc.comp_unit);
768       if (sc.function) {
769         resolved_flags |= eSymbolContextFunction;
770         if (resolve_scope & eSymbolContextBlock) {
771           auto block_symbol = m_session_up->findSymbolByAddress(
772               file_vm_addr, PDB_SymType::Block);
773           auto block_id = block_symbol ? block_symbol->getSymIndexId()
774                                        : sc.function->GetID();
775           sc.block = sc.function->GetBlock(true).FindBlockByID(block_id);
776           if (sc.block)
777             resolved_flags |= eSymbolContextBlock;
778         }
779       }
780     }
781   }
782 
783   if (resolve_scope & eSymbolContextLineEntry) {
784     if (auto *line_table = sc.comp_unit->GetLineTable()) {
785       Address addr(so_addr);
786       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
787         resolved_flags |= eSymbolContextLineEntry;
788     }
789   }
790 
791   return resolved_flags;
792 }
793 
794 uint32_t SymbolFilePDB::ResolveSymbolContext(
795     const lldb_private::SourceLocationSpec &src_location_spec,
796     SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) {
797   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
798   const size_t old_size = sc_list.GetSize();
799   const FileSpec &file_spec = src_location_spec.GetFileSpec();
800   const uint32_t line = src_location_spec.GetLine().value_or(0);
801   if (resolve_scope & lldb::eSymbolContextCompUnit) {
802     // Locate all compilation units with line numbers referencing the specified
803     // file.  For example, if `file_spec` is <vector>, then this should return
804     // all source files and header files that reference <vector>, either
805     // directly or indirectly.
806     auto compilands = m_session_up->findCompilandsForSourceFile(
807         file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);
808 
809     if (!compilands)
810       return 0;
811 
812     // For each one, either find its previously parsed data or parse it afresh
813     // and add it to the symbol context list.
814     while (auto compiland = compilands->getNext()) {
815       // If we're not checking inlines, then don't add line information for
816       // this file unless the FileSpec matches. For inline functions, we don't
817       // have to match the FileSpec since they could be defined in headers
818       // other than file specified in FileSpec.
819       if (!src_location_spec.GetCheckInlines()) {
820         std::string source_file = compiland->getSourceFileFullPath();
821         if (source_file.empty())
822           continue;
823         FileSpec this_spec(source_file, FileSpec::Style::windows);
824         bool need_full_match = !file_spec.GetDirectory().IsEmpty();
825         if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)
826           continue;
827       }
828 
829       SymbolContext sc;
830       auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());
831       if (!cu)
832         continue;
833       sc.comp_unit = cu.get();
834       sc.module_sp = cu->GetModule();
835 
836       // If we were asked to resolve line entries, add all entries to the line
837       // table that match the requested line (or all lines if `line` == 0).
838       if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock |
839                            eSymbolContextLineEntry)) {
840         bool has_line_table = ParseCompileUnitLineTable(*sc.comp_unit, line);
841 
842         if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) {
843           // The query asks for line entries, but we can't get them for the
844           // compile unit. This is not normal for `line` = 0. So just assert
845           // it.
846           assert(line && "Couldn't get all line entries!\n");
847 
848           // Current compiland does not have the requested line. Search next.
849           continue;
850         }
851 
852         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
853           if (!has_line_table)
854             continue;
855 
856           auto *line_table = sc.comp_unit->GetLineTable();
857           lldbassert(line_table);
858 
859           uint32_t num_line_entries = line_table->GetSize();
860           // Skip the terminal line entry.
861           --num_line_entries;
862 
863           // If `line `!= 0, see if we can resolve function for each line entry
864           // in the line table.
865           for (uint32_t line_idx = 0; line && line_idx < num_line_entries;
866                ++line_idx) {
867             if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry))
868               continue;
869 
870             auto file_vm_addr =
871                 sc.line_entry.range.GetBaseAddress().GetFileAddress();
872             if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
873               continue;
874 
875             auto symbol_up = m_session_up->findSymbolByAddress(
876                 file_vm_addr, PDB_SymType::Function);
877             if (symbol_up) {
878               auto func_uid = symbol_up->getSymIndexId();
879               sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
880               if (sc.function == nullptr) {
881                 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
882                 assert(pdb_func);
883                 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func,
884                                                                  *sc.comp_unit);
885               }
886               if (sc.function && (resolve_scope & eSymbolContextBlock)) {
887                 Block &block = sc.function->GetBlock(true);
888                 sc.block = block.FindBlockByID(sc.function->GetID());
889               }
890             }
891             sc_list.Append(sc);
892           }
893         } else if (has_line_table) {
894           // We can parse line table for the compile unit. But no query to
895           // resolve function or block. We append `sc` to the list anyway.
896           sc_list.Append(sc);
897         }
898       } else {
899         // No query for line entry, function or block. But we have a valid
900         // compile unit, append `sc` to the list.
901         sc_list.Append(sc);
902       }
903     }
904   }
905   return sc_list.GetSize() - old_size;
906 }
907 
908 std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) {
909   // Cache public names at first
910   if (m_public_names.empty())
911     if (auto result_up =
912             m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol))
913       while (auto symbol_up = result_up->getNext())
914         if (auto addr = symbol_up->getRawSymbol().getVirtualAddress())
915           m_public_names[addr] = symbol_up->getRawSymbol().getName();
916 
917   // Look up the name in the cache
918   return m_public_names.lookup(pdb_data.getVirtualAddress());
919 }
920 
921 VariableSP SymbolFilePDB::ParseVariableForPDBData(
922     const lldb_private::SymbolContext &sc,
923     const llvm::pdb::PDBSymbolData &pdb_data) {
924   VariableSP var_sp;
925   uint32_t var_uid = pdb_data.getSymIndexId();
926   auto result = m_variables.find(var_uid);
927   if (result != m_variables.end())
928     return result->second;
929 
930   ValueType scope = eValueTypeInvalid;
931   bool is_static_member = false;
932   bool is_external = false;
933   bool is_artificial = false;
934 
935   switch (pdb_data.getDataKind()) {
936   case PDB_DataKind::Global:
937     scope = eValueTypeVariableGlobal;
938     is_external = true;
939     break;
940   case PDB_DataKind::Local:
941     scope = eValueTypeVariableLocal;
942     break;
943   case PDB_DataKind::FileStatic:
944     scope = eValueTypeVariableStatic;
945     break;
946   case PDB_DataKind::StaticMember:
947     is_static_member = true;
948     scope = eValueTypeVariableStatic;
949     break;
950   case PDB_DataKind::Member:
951     scope = eValueTypeVariableStatic;
952     break;
953   case PDB_DataKind::Param:
954     scope = eValueTypeVariableArgument;
955     break;
956   case PDB_DataKind::Constant:
957     scope = eValueTypeConstResult;
958     break;
959   default:
960     break;
961   }
962 
963   switch (pdb_data.getLocationType()) {
964   case PDB_LocType::TLS:
965     scope = eValueTypeVariableThreadLocal;
966     break;
967   case PDB_LocType::RegRel: {
968     // It is a `this` pointer.
969     if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) {
970       scope = eValueTypeVariableArgument;
971       is_artificial = true;
972     }
973   } break;
974   default:
975     break;
976   }
977 
978   Declaration decl;
979   if (!is_artificial && !pdb_data.isCompilerGenerated()) {
980     if (auto lines = pdb_data.getLineNumbers()) {
981       if (auto first_line = lines->getNext()) {
982         uint32_t src_file_id = first_line->getSourceFileId();
983         auto src_file = m_session_up->getSourceFileById(src_file_id);
984         if (src_file) {
985           FileSpec spec(src_file->getFileName());
986           decl.SetFile(spec);
987           decl.SetColumn(first_line->getColumnNumber());
988           decl.SetLine(first_line->getLineNumber());
989         }
990       }
991     }
992   }
993 
994   Variable::RangeList ranges;
995   SymbolContextScope *context_scope = sc.comp_unit;
996   if (scope == eValueTypeVariableLocal || scope == eValueTypeVariableArgument) {
997     if (sc.function) {
998       Block &function_block = sc.function->GetBlock(true);
999       Block *block =
1000           function_block.FindBlockByID(pdb_data.getLexicalParentId());
1001       if (!block)
1002         block = &function_block;
1003 
1004       context_scope = block;
1005 
1006       for (size_t i = 0, num_ranges = block->GetNumRanges(); i < num_ranges;
1007            ++i) {
1008         AddressRange range;
1009         if (!block->GetRangeAtIndex(i, range))
1010           continue;
1011 
1012         ranges.Append(range.GetBaseAddress().GetFileAddress(),
1013                       range.GetByteSize());
1014       }
1015     }
1016   }
1017 
1018   SymbolFileTypeSP type_sp =
1019       std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());
1020 
1021   auto var_name = pdb_data.getName();
1022   auto mangled = GetMangledForPDBData(pdb_data);
1023   auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();
1024 
1025   bool is_constant;
1026   ModuleSP module_sp = GetObjectFile()->GetModule();
1027   DWARFExpressionList location(module_sp,
1028                                ConvertPDBLocationToDWARFExpression(
1029                                    module_sp, pdb_data, ranges, is_constant),
1030                                nullptr);
1031 
1032   var_sp = std::make_shared<Variable>(
1033       var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,
1034       ranges, &decl, location, is_external, is_artificial, is_constant,
1035       is_static_member);
1036 
1037   m_variables.insert(std::make_pair(var_uid, var_sp));
1038   return var_sp;
1039 }
1040 
1041 size_t
1042 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc,
1043                               const llvm::pdb::PDBSymbol &pdb_symbol,
1044                               lldb_private::VariableList *variable_list) {
1045   size_t num_added = 0;
1046 
1047   if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {
1048     VariableListSP local_variable_list_sp;
1049 
1050     auto result = m_variables.find(pdb_data->getSymIndexId());
1051     if (result != m_variables.end()) {
1052       if (variable_list)
1053         variable_list->AddVariableIfUnique(result->second);
1054     } else {
1055       // Prepare right VariableList for this variable.
1056       if (auto lexical_parent = pdb_data->getLexicalParent()) {
1057         switch (lexical_parent->getSymTag()) {
1058         case PDB_SymType::Exe:
1059           assert(sc.comp_unit);
1060           LLVM_FALLTHROUGH;
1061         case PDB_SymType::Compiland: {
1062           if (sc.comp_unit) {
1063             local_variable_list_sp = sc.comp_unit->GetVariableList(false);
1064             if (!local_variable_list_sp) {
1065               local_variable_list_sp = std::make_shared<VariableList>();
1066               sc.comp_unit->SetVariableList(local_variable_list_sp);
1067             }
1068           }
1069         } break;
1070         case PDB_SymType::Block:
1071         case PDB_SymType::Function: {
1072           if (sc.function) {
1073             Block *block = sc.function->GetBlock(true).FindBlockByID(
1074                 lexical_parent->getSymIndexId());
1075             if (block) {
1076               local_variable_list_sp = block->GetBlockVariableList(false);
1077               if (!local_variable_list_sp) {
1078                 local_variable_list_sp = std::make_shared<VariableList>();
1079                 block->SetVariableList(local_variable_list_sp);
1080               }
1081             }
1082           }
1083         } break;
1084         default:
1085           break;
1086         }
1087       }
1088 
1089       if (local_variable_list_sp) {
1090         if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {
1091           local_variable_list_sp->AddVariableIfUnique(var_sp);
1092           if (variable_list)
1093             variable_list->AddVariableIfUnique(var_sp);
1094           ++num_added;
1095           PDBASTParser *ast = GetPDBAstParser();
1096           if (ast)
1097             ast->GetDeclForSymbol(*pdb_data);
1098         }
1099       }
1100     }
1101   }
1102 
1103   if (auto results = pdb_symbol.findAllChildren()) {
1104     while (auto result = results->getNext())
1105       num_added += ParseVariables(sc, *result, variable_list);
1106   }
1107 
1108   return num_added;
1109 }
1110 
1111 void SymbolFilePDB::FindGlobalVariables(
1112     lldb_private::ConstString name, const CompilerDeclContext &parent_decl_ctx,
1113     uint32_t max_matches, lldb_private::VariableList &variables) {
1114   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1115   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1116     return;
1117   if (name.IsEmpty())
1118     return;
1119 
1120   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1121   if (!results)
1122     return;
1123 
1124   uint32_t matches = 0;
1125   size_t old_size = variables.GetSize();
1126   while (auto result = results->getNext()) {
1127     auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());
1128     if (max_matches > 0 && matches >= max_matches)
1129       break;
1130 
1131     SymbolContext sc;
1132     sc.module_sp = m_objfile_sp->GetModule();
1133     lldbassert(sc.module_sp.get());
1134 
1135     if (!name.GetStringRef().equals(
1136             MSVCUndecoratedNameParser::DropScope(pdb_data->getName())))
1137       continue;
1138 
1139     sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1140     // FIXME: We are not able to determine the compile unit.
1141     if (sc.comp_unit == nullptr)
1142       continue;
1143 
1144     if (parent_decl_ctx.IsValid() &&
1145         GetDeclContextContainingUID(result->getSymIndexId()) != parent_decl_ctx)
1146       continue;
1147 
1148     ParseVariables(sc, *pdb_data, &variables);
1149     matches = variables.GetSize() - old_size;
1150   }
1151 }
1152 
1153 void SymbolFilePDB::FindGlobalVariables(
1154     const lldb_private::RegularExpression &regex, uint32_t max_matches,
1155     lldb_private::VariableList &variables) {
1156   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1157   if (!regex.IsValid())
1158     return;
1159   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1160   if (!results)
1161     return;
1162 
1163   uint32_t matches = 0;
1164   size_t old_size = variables.GetSize();
1165   while (auto pdb_data = results->getNext()) {
1166     if (max_matches > 0 && matches >= max_matches)
1167       break;
1168 
1169     auto var_name = pdb_data->getName();
1170     if (var_name.empty())
1171       continue;
1172     if (!regex.Execute(var_name))
1173       continue;
1174     SymbolContext sc;
1175     sc.module_sp = m_objfile_sp->GetModule();
1176     lldbassert(sc.module_sp.get());
1177 
1178     sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1179     // FIXME: We are not able to determine the compile unit.
1180     if (sc.comp_unit == nullptr)
1181       continue;
1182 
1183     ParseVariables(sc, *pdb_data, &variables);
1184     matches = variables.GetSize() - old_size;
1185   }
1186 }
1187 
1188 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,
1189                                     bool include_inlines,
1190                                     lldb_private::SymbolContextList &sc_list) {
1191   lldb_private::SymbolContext sc;
1192   sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();
1193   if (!sc.comp_unit)
1194     return false;
1195   sc.module_sp = sc.comp_unit->GetModule();
1196   sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, *sc.comp_unit);
1197   if (!sc.function)
1198     return false;
1199 
1200   sc_list.Append(sc);
1201   return true;
1202 }
1203 
1204 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,
1205                                     lldb_private::SymbolContextList &sc_list) {
1206   auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
1207   if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))
1208     return false;
1209   return ResolveFunction(*pdb_func_up, include_inlines, sc_list);
1210 }
1211 
1212 void SymbolFilePDB::CacheFunctionNames() {
1213   if (!m_func_full_names.IsEmpty())
1214     return;
1215 
1216   std::map<uint64_t, uint32_t> addr_ids;
1217 
1218   if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {
1219     while (auto pdb_func_up = results_up->getNext()) {
1220       if (pdb_func_up->isCompilerGenerated())
1221         continue;
1222 
1223       auto name = pdb_func_up->getName();
1224       auto demangled_name = pdb_func_up->getUndecoratedName();
1225       if (name.empty() && demangled_name.empty())
1226         continue;
1227 
1228       auto uid = pdb_func_up->getSymIndexId();
1229       if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())
1230         addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));
1231 
1232       if (auto parent = pdb_func_up->getClassParent()) {
1233 
1234         // PDB have symbols for class/struct methods or static methods in Enum
1235         // Class. We won't bother to check if the parent is UDT or Enum here.
1236         m_func_method_names.Append(ConstString(name), uid);
1237 
1238         // To search a method name, like NS::Class:MemberFunc, LLDB searches
1239         // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does
1240         // not have information of this, we extract base names and cache them
1241         // by our own effort.
1242         llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1243         if (!basename.empty())
1244           m_func_base_names.Append(ConstString(basename), uid);
1245         else {
1246           m_func_base_names.Append(ConstString(name), uid);
1247         }
1248 
1249         if (!demangled_name.empty())
1250           m_func_full_names.Append(ConstString(demangled_name), uid);
1251 
1252       } else {
1253         // Handle not-method symbols.
1254 
1255         // The function name might contain namespace, or its lexical scope.
1256         llvm::StringRef basename = MSVCUndecoratedNameParser::DropScope(name);
1257         if (!basename.empty())
1258           m_func_base_names.Append(ConstString(basename), uid);
1259         else
1260           m_func_base_names.Append(ConstString(name), uid);
1261 
1262         if (name == "main") {
1263           m_func_full_names.Append(ConstString(name), uid);
1264 
1265           if (!demangled_name.empty() && name != demangled_name) {
1266             m_func_full_names.Append(ConstString(demangled_name), uid);
1267             m_func_base_names.Append(ConstString(demangled_name), uid);
1268           }
1269         } else if (!demangled_name.empty()) {
1270           m_func_full_names.Append(ConstString(demangled_name), uid);
1271         } else {
1272           m_func_full_names.Append(ConstString(name), uid);
1273         }
1274       }
1275     }
1276   }
1277 
1278   if (auto results_up =
1279           m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {
1280     while (auto pub_sym_up = results_up->getNext()) {
1281       if (!pub_sym_up->isFunction())
1282         continue;
1283       auto name = pub_sym_up->getName();
1284       if (name.empty())
1285         continue;
1286 
1287       if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) {
1288         auto vm_addr = pub_sym_up->getVirtualAddress();
1289 
1290         // PDB public symbol has mangled name for its associated function.
1291         if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) {
1292           // Cache mangled name.
1293           m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]);
1294         }
1295       }
1296     }
1297   }
1298   // Sort them before value searching is working properly
1299   m_func_full_names.Sort();
1300   m_func_full_names.SizeToFit();
1301   m_func_method_names.Sort();
1302   m_func_method_names.SizeToFit();
1303   m_func_base_names.Sort();
1304   m_func_base_names.SizeToFit();
1305 }
1306 
1307 void SymbolFilePDB::FindFunctions(
1308     lldb_private::ConstString name,
1309     const lldb_private::CompilerDeclContext &parent_decl_ctx,
1310     FunctionNameType name_type_mask, bool include_inlines,
1311     lldb_private::SymbolContextList &sc_list) {
1312   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1313   lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);
1314 
1315   if (name_type_mask == eFunctionNameTypeNone)
1316     return;
1317   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1318     return;
1319   if (name.IsEmpty())
1320     return;
1321 
1322   if (name_type_mask & eFunctionNameTypeFull ||
1323       name_type_mask & eFunctionNameTypeBase ||
1324       name_type_mask & eFunctionNameTypeMethod) {
1325     CacheFunctionNames();
1326 
1327     std::set<uint32_t> resolved_ids;
1328     auto ResolveFn = [this, &name, parent_decl_ctx, include_inlines, &sc_list,
1329                       &resolved_ids](UniqueCStringMap<uint32_t> &Names) {
1330       std::vector<uint32_t> ids;
1331       if (!Names.GetValues(name, ids))
1332         return;
1333 
1334       for (uint32_t id : ids) {
1335         if (resolved_ids.find(id) != resolved_ids.end())
1336           continue;
1337 
1338         if (parent_decl_ctx.IsValid() &&
1339             GetDeclContextContainingUID(id) != parent_decl_ctx)
1340           continue;
1341 
1342         if (ResolveFunction(id, include_inlines, sc_list))
1343           resolved_ids.insert(id);
1344       }
1345     };
1346     if (name_type_mask & eFunctionNameTypeFull) {
1347       ResolveFn(m_func_full_names);
1348       ResolveFn(m_func_base_names);
1349       ResolveFn(m_func_method_names);
1350     }
1351     if (name_type_mask & eFunctionNameTypeBase)
1352       ResolveFn(m_func_base_names);
1353     if (name_type_mask & eFunctionNameTypeMethod)
1354       ResolveFn(m_func_method_names);
1355   }
1356 }
1357 
1358 void SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression &regex,
1359                                   bool include_inlines,
1360                                   lldb_private::SymbolContextList &sc_list) {
1361   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1362   if (!regex.IsValid())
1363     return;
1364 
1365   CacheFunctionNames();
1366 
1367   std::set<uint32_t> resolved_ids;
1368   auto ResolveFn = [&regex, include_inlines, &sc_list, &resolved_ids,
1369                     this](UniqueCStringMap<uint32_t> &Names) {
1370     std::vector<uint32_t> ids;
1371     if (Names.GetValues(regex, ids)) {
1372       for (auto id : ids) {
1373         if (resolved_ids.find(id) == resolved_ids.end())
1374           if (ResolveFunction(id, include_inlines, sc_list))
1375             resolved_ids.insert(id);
1376       }
1377     }
1378   };
1379   ResolveFn(m_func_full_names);
1380   ResolveFn(m_func_base_names);
1381 }
1382 
1383 void SymbolFilePDB::GetMangledNamesForFunction(
1384     const std::string &scope_qualified_name,
1385     std::vector<lldb_private::ConstString> &mangled_names) {}
1386 
1387 void SymbolFilePDB::AddSymbols(lldb_private::Symtab &symtab) {
1388   std::set<lldb::addr_t> sym_addresses;
1389   for (size_t i = 0; i < symtab.GetNumSymbols(); i++)
1390     sym_addresses.insert(symtab.SymbolAtIndex(i)->GetFileAddress());
1391 
1392   auto results = m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>();
1393   if (!results)
1394     return;
1395 
1396   auto section_list = m_objfile_sp->GetSectionList();
1397   if (!section_list)
1398     return;
1399 
1400   while (auto pub_symbol = results->getNext()) {
1401     auto section_id = pub_symbol->getAddressSection();
1402 
1403     auto section = section_list->FindSectionByID(section_id);
1404     if (!section)
1405       continue;
1406 
1407     auto offset = pub_symbol->getAddressOffset();
1408 
1409     auto file_addr = section->GetFileAddress() + offset;
1410     if (sym_addresses.find(file_addr) != sym_addresses.end())
1411       continue;
1412     sym_addresses.insert(file_addr);
1413 
1414     auto size = pub_symbol->getLength();
1415     symtab.AddSymbol(
1416         Symbol(pub_symbol->getSymIndexId(),   // symID
1417                pub_symbol->getName().c_str(), // name
1418                pub_symbol->isCode() ? eSymbolTypeCode : eSymbolTypeData, // type
1419                true,      // external
1420                false,     // is_debug
1421                false,     // is_trampoline
1422                false,     // is_artificial
1423                section,   // section_sp
1424                offset,    // value
1425                size,      // size
1426                size != 0, // size_is_valid
1427                false,     // contains_linker_annotations
1428                0          // flags
1429                ));
1430   }
1431 
1432   symtab.Finalize();
1433 }
1434 
1435 void SymbolFilePDB::FindTypes(
1436     lldb_private::ConstString name, const CompilerDeclContext &parent_decl_ctx,
1437     uint32_t max_matches,
1438     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1439     lldb_private::TypeMap &types) {
1440   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1441   if (!name)
1442     return;
1443   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1444     return;
1445 
1446   searched_symbol_files.clear();
1447   searched_symbol_files.insert(this);
1448 
1449   // There is an assumption 'name' is not a regex
1450   FindTypesByName(name.GetStringRef(), parent_decl_ctx, max_matches, types);
1451 }
1452 
1453 void SymbolFilePDB::DumpClangAST(Stream &s) {
1454   auto type_system_or_err =
1455       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1456   if (auto err = type_system_or_err.takeError()) {
1457     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1458                    "Unable to dump ClangAST");
1459     return;
1460   }
1461 
1462   auto *clang_type_system =
1463       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
1464   if (!clang_type_system)
1465     return;
1466   clang_type_system->Dump(s.AsRawOstream());
1467 }
1468 
1469 void SymbolFilePDB::FindTypesByRegex(
1470     const lldb_private::RegularExpression &regex, uint32_t max_matches,
1471     lldb_private::TypeMap &types) {
1472   // When searching by regex, we need to go out of our way to limit the search
1473   // space as much as possible since this searches EVERYTHING in the PDB,
1474   // manually doing regex comparisons.  PDB library isn't optimized for regex
1475   // searches or searches across multiple symbol types at the same time, so the
1476   // best we can do is to search enums, then typedefs, then classes one by one,
1477   // and do a regex comparison against each of them.
1478   PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1479                                   PDB_SymType::UDT};
1480   std::unique_ptr<IPDBEnumSymbols> results;
1481 
1482   uint32_t matches = 0;
1483 
1484   for (auto tag : tags_to_search) {
1485     results = m_global_scope_up->findAllChildren(tag);
1486     if (!results)
1487       continue;
1488 
1489     while (auto result = results->getNext()) {
1490       if (max_matches > 0 && matches >= max_matches)
1491         break;
1492 
1493       std::string type_name;
1494       if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1495         type_name = enum_type->getName();
1496       else if (auto typedef_type =
1497                    llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1498         type_name = typedef_type->getName();
1499       else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1500         type_name = class_type->getName();
1501       else {
1502         // We're looking only for types that have names.  Skip symbols, as well
1503         // as unnamed types such as arrays, pointers, etc.
1504         continue;
1505       }
1506 
1507       if (!regex.Execute(type_name))
1508         continue;
1509 
1510       // This should cause the type to get cached and stored in the `m_types`
1511       // lookup.
1512       if (!ResolveTypeUID(result->getSymIndexId()))
1513         continue;
1514 
1515       auto iter = m_types.find(result->getSymIndexId());
1516       if (iter == m_types.end())
1517         continue;
1518       types.Insert(iter->second);
1519       ++matches;
1520     }
1521   }
1522 }
1523 
1524 void SymbolFilePDB::FindTypesByName(
1525     llvm::StringRef name,
1526     const lldb_private::CompilerDeclContext &parent_decl_ctx,
1527     uint32_t max_matches, lldb_private::TypeMap &types) {
1528   std::unique_ptr<IPDBEnumSymbols> results;
1529   if (name.empty())
1530     return;
1531   results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1532   if (!results)
1533     return;
1534 
1535   uint32_t matches = 0;
1536 
1537   while (auto result = results->getNext()) {
1538     if (max_matches > 0 && matches >= max_matches)
1539       break;
1540 
1541     if (MSVCUndecoratedNameParser::DropScope(
1542             result->getRawSymbol().getName()) != name)
1543       continue;
1544 
1545     switch (result->getSymTag()) {
1546     case PDB_SymType::Enum:
1547     case PDB_SymType::UDT:
1548     case PDB_SymType::Typedef:
1549       break;
1550     default:
1551       // We're looking only for types that have names.  Skip symbols, as well
1552       // as unnamed types such as arrays, pointers, etc.
1553       continue;
1554     }
1555 
1556     // This should cause the type to get cached and stored in the `m_types`
1557     // lookup.
1558     if (!ResolveTypeUID(result->getSymIndexId()))
1559       continue;
1560 
1561     if (parent_decl_ctx.IsValid() &&
1562         GetDeclContextContainingUID(result->getSymIndexId()) != parent_decl_ctx)
1563       continue;
1564 
1565     auto iter = m_types.find(result->getSymIndexId());
1566     if (iter == m_types.end())
1567       continue;
1568     types.Insert(iter->second);
1569     ++matches;
1570   }
1571 }
1572 
1573 void SymbolFilePDB::FindTypes(
1574     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1575     llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1576     lldb_private::TypeMap &types) {}
1577 
1578 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1579                                          uint32_t type_mask,
1580                                          TypeCollection &type_collection) {
1581   bool can_parse = false;
1582   switch (pdb_symbol.getSymTag()) {
1583   case PDB_SymType::ArrayType:
1584     can_parse = ((type_mask & eTypeClassArray) != 0);
1585     break;
1586   case PDB_SymType::BuiltinType:
1587     can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1588     break;
1589   case PDB_SymType::Enum:
1590     can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1591     break;
1592   case PDB_SymType::Function:
1593   case PDB_SymType::FunctionSig:
1594     can_parse = ((type_mask & eTypeClassFunction) != 0);
1595     break;
1596   case PDB_SymType::PointerType:
1597     can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1598                                eTypeClassMemberPointer)) != 0);
1599     break;
1600   case PDB_SymType::Typedef:
1601     can_parse = ((type_mask & eTypeClassTypedef) != 0);
1602     break;
1603   case PDB_SymType::UDT: {
1604     auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1605     assert(udt);
1606     can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1607                  ((type_mask & (eTypeClassClass | eTypeClassStruct |
1608                                 eTypeClassUnion)) != 0));
1609   } break;
1610   default:
1611     break;
1612   }
1613 
1614   if (can_parse) {
1615     if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1616       auto result =
1617           std::find(type_collection.begin(), type_collection.end(), type);
1618       if (result == type_collection.end())
1619         type_collection.push_back(type);
1620     }
1621   }
1622 
1623   auto results_up = pdb_symbol.findAllChildren();
1624   while (auto symbol_up = results_up->getNext())
1625     GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1626 }
1627 
1628 void SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1629                              TypeClass type_mask,
1630                              lldb_private::TypeList &type_list) {
1631   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1632   TypeCollection type_collection;
1633   CompileUnit *cu =
1634       sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1635   if (cu) {
1636     auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1637     if (!compiland_up)
1638       return;
1639     GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1640   } else {
1641     for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1642       auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1643       if (cu_sp) {
1644         if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1645           GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1646       }
1647     }
1648   }
1649 
1650   for (auto type : type_collection) {
1651     type->GetForwardCompilerType();
1652     type_list.Insert(type->shared_from_this());
1653   }
1654 }
1655 
1656 llvm::Expected<lldb_private::TypeSystem &>
1657 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1658   auto type_system_or_err =
1659       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1660   if (type_system_or_err) {
1661     type_system_or_err->SetSymbolFile(this);
1662   }
1663   return type_system_or_err;
1664 }
1665 
1666 PDBASTParser *SymbolFilePDB::GetPDBAstParser() {
1667   auto type_system_or_err =
1668       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1669   if (auto err = type_system_or_err.takeError()) {
1670     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1671                    "Unable to get PDB AST parser");
1672     return nullptr;
1673   }
1674 
1675   auto *clang_type_system =
1676       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
1677   if (!clang_type_system)
1678     return nullptr;
1679 
1680   return clang_type_system->GetPDBParser();
1681 }
1682 
1683 lldb_private::CompilerDeclContext
1684 SymbolFilePDB::FindNamespace(lldb_private::ConstString name,
1685                              const CompilerDeclContext &parent_decl_ctx) {
1686   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1687   auto type_system_or_err =
1688       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1689   if (auto err = type_system_or_err.takeError()) {
1690     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1691                    "Unable to find namespace {}", name.AsCString());
1692     return CompilerDeclContext();
1693   }
1694 
1695   auto *clang_type_system =
1696       llvm::dyn_cast_or_null<TypeSystemClang>(&type_system_or_err.get());
1697   if (!clang_type_system)
1698     return CompilerDeclContext();
1699 
1700   PDBASTParser *pdb = clang_type_system->GetPDBParser();
1701   if (!pdb)
1702     return CompilerDeclContext();
1703 
1704   clang::DeclContext *decl_context = nullptr;
1705   if (parent_decl_ctx)
1706     decl_context = static_cast<clang::DeclContext *>(
1707         parent_decl_ctx.GetOpaqueDeclContext());
1708 
1709   auto namespace_decl =
1710       pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1711   if (!namespace_decl)
1712     return CompilerDeclContext();
1713 
1714   return clang_type_system->CreateDeclContext(namespace_decl);
1715 }
1716 
1717 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
1718 
1719 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1720   return *m_session_up;
1721 }
1722 
1723 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,
1724                                                        uint32_t index) {
1725   auto found_cu = m_comp_units.find(id);
1726   if (found_cu != m_comp_units.end())
1727     return found_cu->second;
1728 
1729   auto compiland_up = GetPDBCompilandByUID(id);
1730   if (!compiland_up)
1731     return CompUnitSP();
1732 
1733   lldb::LanguageType lang;
1734   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1735   if (!details)
1736     lang = lldb::eLanguageTypeC_plus_plus;
1737   else
1738     lang = TranslateLanguage(details->getLanguage());
1739 
1740   if (lang == lldb::LanguageType::eLanguageTypeUnknown)
1741     return CompUnitSP();
1742 
1743   std::string path = compiland_up->getSourceFileFullPath();
1744   if (path.empty())
1745     return CompUnitSP();
1746 
1747   // Don't support optimized code for now, DebugInfoPDB does not return this
1748   // information.
1749   LazyBool optimized = eLazyBoolNo;
1750   auto cu_sp = std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr,
1751                                              path.c_str(), id, lang, optimized);
1752 
1753   if (!cu_sp)
1754     return CompUnitSP();
1755 
1756   m_comp_units.insert(std::make_pair(id, cu_sp));
1757   if (index == UINT32_MAX)
1758     GetCompileUnitIndex(*compiland_up, index);
1759   lldbassert(index != UINT32_MAX);
1760   SetCompileUnitAtIndex(index, cu_sp);
1761   return cu_sp;
1762 }
1763 
1764 bool SymbolFilePDB::ParseCompileUnitLineTable(CompileUnit &comp_unit,
1765                                               uint32_t match_line) {
1766   auto compiland_up = GetPDBCompilandByUID(comp_unit.GetID());
1767   if (!compiland_up)
1768     return false;
1769 
1770   // LineEntry needs the *index* of the file into the list of support files
1771   // returned by ParseCompileUnitSupportFiles.  But the underlying SDK gives us
1772   // a globally unique idenfitifier in the namespace of the PDB.  So, we have
1773   // to do a mapping so that we can hand out indices.
1774   llvm::DenseMap<uint32_t, uint32_t> index_map;
1775   BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1776   auto line_table = std::make_unique<LineTable>(&comp_unit);
1777 
1778   // Find contributions to `compiland` from all source and header files.
1779   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1780   if (!files)
1781     return false;
1782 
1783   // For each source and header file, create a LineSequence for contributions
1784   // to the compiland from that file, and add the sequence.
1785   while (auto file = files->getNext()) {
1786     std::unique_ptr<LineSequence> sequence(
1787         line_table->CreateLineSequenceContainer());
1788     auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1789     if (!lines)
1790       continue;
1791     int entry_count = lines->getChildCount();
1792 
1793     uint64_t prev_addr;
1794     uint32_t prev_length;
1795     uint32_t prev_line;
1796     uint32_t prev_source_idx;
1797 
1798     for (int i = 0; i < entry_count; ++i) {
1799       auto line = lines->getChildAtIndex(i);
1800 
1801       uint64_t lno = line->getLineNumber();
1802       uint64_t addr = line->getVirtualAddress();
1803       uint32_t length = line->getLength();
1804       uint32_t source_id = line->getSourceFileId();
1805       uint32_t col = line->getColumnNumber();
1806       uint32_t source_idx = index_map[source_id];
1807 
1808       // There was a gap between the current entry and the previous entry if
1809       // the addresses don't perfectly line up.
1810       bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1811 
1812       // Before inserting the current entry, insert a terminal entry at the end
1813       // of the previous entry's address range if the current entry resulted in
1814       // a gap from the previous entry.
1815       if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1816         line_table->AppendLineEntryToSequence(
1817             sequence.get(), prev_addr + prev_length, prev_line, 0,
1818             prev_source_idx, false, false, false, false, true);
1819 
1820         line_table->InsertSequence(sequence.get());
1821         sequence = line_table->CreateLineSequenceContainer();
1822       }
1823 
1824       if (ShouldAddLine(match_line, lno, length)) {
1825         bool is_statement = line->isStatement();
1826         bool is_prologue = false;
1827         bool is_epilogue = false;
1828         auto func =
1829             m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1830         if (func) {
1831           auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1832           if (prologue)
1833             is_prologue = (addr == prologue->getVirtualAddress());
1834 
1835           auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1836           if (epilogue)
1837             is_epilogue = (addr == epilogue->getVirtualAddress());
1838         }
1839 
1840         line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
1841                                               source_idx, is_statement, false,
1842                                               is_prologue, is_epilogue, false);
1843       }
1844 
1845       prev_addr = addr;
1846       prev_length = length;
1847       prev_line = lno;
1848       prev_source_idx = source_idx;
1849     }
1850 
1851     if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1852       // The end is always a terminal entry, so insert it regardless.
1853       line_table->AppendLineEntryToSequence(
1854           sequence.get(), prev_addr + prev_length, prev_line, 0,
1855           prev_source_idx, false, false, false, false, true);
1856     }
1857 
1858     line_table->InsertSequence(sequence.get());
1859   }
1860 
1861   if (line_table->GetSize()) {
1862     comp_unit.SetLineTable(line_table.release());
1863     return true;
1864   }
1865   return false;
1866 }
1867 
1868 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
1869     const PDBSymbolCompiland &compiland,
1870     llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1871   // This is a hack, but we need to convert the source id into an index into
1872   // the support files array.  We don't want to do path comparisons to avoid
1873   // basename / full path issues that may or may not even be a problem, so we
1874   // use the globally unique source file identifiers.  Ideally we could use the
1875   // global identifiers everywhere, but LineEntry currently assumes indices.
1876   auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1877   if (!source_files)
1878     return;
1879 
1880   int index = 0;
1881   while (auto file = source_files->getNext()) {
1882     uint32_t source_id = file->getUniqueId();
1883     index_map[source_id] = index++;
1884   }
1885 }
1886 
1887 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(
1888     const lldb_private::Address &so_addr) {
1889   lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1890   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1891     return nullptr;
1892 
1893   // If it is a PDB function's vm addr, this is the first sure bet.
1894   if (auto lines =
1895           m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1896     if (auto first_line = lines->getNext())
1897       return ParseCompileUnitForUID(first_line->getCompilandId());
1898   }
1899 
1900   // Otherwise we resort to section contributions.
1901   if (auto sec_contribs = m_session_up->getSectionContribs()) {
1902     while (auto section = sec_contribs->getNext()) {
1903       auto va = section->getVirtualAddress();
1904       if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1905         return ParseCompileUnitForUID(section->getCompilandId());
1906     }
1907   }
1908   return nullptr;
1909 }
1910 
1911 Mangled
1912 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1913   Mangled mangled;
1914   auto func_name = pdb_func.getName();
1915   auto func_undecorated_name = pdb_func.getUndecoratedName();
1916   std::string func_decorated_name;
1917 
1918   // Seek from public symbols for non-static function's decorated name if any.
1919   // For static functions, they don't have undecorated names and aren't exposed
1920   // in Public Symbols either.
1921   if (!func_undecorated_name.empty()) {
1922     auto result_up = m_global_scope_up->findChildren(
1923         PDB_SymType::PublicSymbol, func_undecorated_name,
1924         PDB_NameSearchFlags::NS_UndecoratedName);
1925     if (result_up) {
1926       while (auto symbol_up = result_up->getNext()) {
1927         // For a public symbol, it is unique.
1928         lldbassert(result_up->getChildCount() == 1);
1929         if (auto *pdb_public_sym =
1930                 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
1931                     symbol_up.get())) {
1932           if (pdb_public_sym->isFunction()) {
1933             func_decorated_name = pdb_public_sym->getName();
1934             break;
1935           }
1936         }
1937       }
1938     }
1939   }
1940   if (!func_decorated_name.empty()) {
1941     mangled.SetMangledName(ConstString(func_decorated_name));
1942 
1943     // For MSVC, format of C funciton's decorated name depends on calling
1944     // convention. Unfortunately none of the format is recognized by current
1945     // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
1946     // `__purecall` is retrieved as both its decorated and undecorated name
1947     // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
1948     // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
1949     // Mangled::GetDemangledName method will fail internally and caches an
1950     // empty string as its undecorated name. So we will face a contradiction
1951     // here for the same symbol:
1952     //   non-empty undecorated name from PDB
1953     //   empty undecorated name from LLDB
1954     if (!func_undecorated_name.empty() && mangled.GetDemangledName().IsEmpty())
1955       mangled.SetDemangledName(ConstString(func_undecorated_name));
1956 
1957     // LLDB uses several flags to control how a C++ decorated name is
1958     // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
1959     // yielded name could be different from what we retrieve from
1960     // PDB source unless we also apply same flags in getting undecorated
1961     // name through PDBSymbolFunc::getUndecoratedNameEx method.
1962     if (!func_undecorated_name.empty() &&
1963         mangled.GetDemangledName() != ConstString(func_undecorated_name))
1964       mangled.SetDemangledName(ConstString(func_undecorated_name));
1965   } else if (!func_undecorated_name.empty()) {
1966     mangled.SetDemangledName(ConstString(func_undecorated_name));
1967   } else if (!func_name.empty())
1968     mangled.SetValue(ConstString(func_name), false);
1969 
1970   return mangled;
1971 }
1972 
1973 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(
1974     const lldb_private::CompilerDeclContext &decl_ctx) {
1975   if (!decl_ctx.IsValid())
1976     return true;
1977 
1978   TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem();
1979   if (!decl_ctx_type_system)
1980     return false;
1981   auto type_system_or_err = GetTypeSystemForLanguage(
1982       decl_ctx_type_system->GetMinimumLanguage(nullptr));
1983   if (auto err = type_system_or_err.takeError()) {
1984     LLDB_LOG_ERROR(
1985         GetLog(LLDBLog::Symbols), std::move(err),
1986         "Unable to determine if DeclContext matches this symbol file");
1987     return false;
1988   }
1989 
1990   if (decl_ctx_type_system == &type_system_or_err.get())
1991     return true; // The type systems match, return true
1992 
1993   return false;
1994 }
1995 
1996 uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {
1997   static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {
1998     return lhs < rhs.Offset;
1999   };
2000 
2001   // Cache section contributions
2002   if (m_sec_contribs.empty()) {
2003     if (auto SecContribs = m_session_up->getSectionContribs()) {
2004       while (auto SectionContrib = SecContribs->getNext()) {
2005         auto comp_id = SectionContrib->getCompilandId();
2006         if (!comp_id)
2007           continue;
2008 
2009         auto sec = SectionContrib->getAddressSection();
2010         auto &sec_cs = m_sec_contribs[sec];
2011 
2012         auto offset = SectionContrib->getAddressOffset();
2013         auto it =
2014             std::upper_bound(sec_cs.begin(), sec_cs.end(), offset, pred_upper);
2015 
2016         auto size = SectionContrib->getLength();
2017         sec_cs.insert(it, {offset, size, comp_id});
2018       }
2019     }
2020   }
2021 
2022   // Check by line number
2023   if (auto Lines = data.getLineNumbers()) {
2024     if (auto FirstLine = Lines->getNext())
2025       return FirstLine->getCompilandId();
2026   }
2027 
2028   // Retrieve section + offset
2029   uint32_t DataSection = data.getAddressSection();
2030   uint32_t DataOffset = data.getAddressOffset();
2031   if (DataSection == 0) {
2032     if (auto RVA = data.getRelativeVirtualAddress())
2033       m_session_up->addressForRVA(RVA, DataSection, DataOffset);
2034   }
2035 
2036   if (DataSection) {
2037     // Search by section contributions
2038     auto &sec_cs = m_sec_contribs[DataSection];
2039     auto it =
2040         std::upper_bound(sec_cs.begin(), sec_cs.end(), DataOffset, pred_upper);
2041     if (it != sec_cs.begin()) {
2042       --it;
2043       if (DataOffset < it->Offset + it->Size)
2044         return it->CompilandId;
2045     }
2046   } else {
2047     // Search in lexical tree
2048     auto LexParentId = data.getLexicalParentId();
2049     while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {
2050       if (LexParent->getSymTag() == PDB_SymType::Exe)
2051         break;
2052       if (LexParent->getSymTag() == PDB_SymType::Compiland)
2053         return LexParentId;
2054       LexParentId = LexParent->getRawSymbol().getLexicalParentId();
2055     }
2056   }
2057 
2058   return 0;
2059 }
2060