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