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 llvm::Optional<SymbolFile::ArrayInfo> SymbolFilePDB::GetDynamicArrayInfoForUID(
591     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
592   return llvm::None;
593 }
594 
595 bool SymbolFilePDB::CompleteType(lldb_private::CompilerType &compiler_type) {
596   std::lock_guard<std::recursive_mutex> guard(
597       GetObjectFile()->GetModule()->GetMutex());
598 
599   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
600       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
601   if (!clang_ast_ctx)
602     return false;
603 
604   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
605   if (!pdb)
606     return false;
607 
608   return pdb->CompleteTypeFromPDB(compiler_type);
609 }
610 
611 lldb_private::CompilerDecl SymbolFilePDB::GetDeclForUID(lldb::user_id_t uid) {
612   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
613       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
614   if (!clang_ast_ctx)
615     return CompilerDecl();
616 
617   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
618   if (!pdb)
619     return CompilerDecl();
620 
621   auto symbol = m_session_up->getSymbolById(uid);
622   if (!symbol)
623     return CompilerDecl();
624 
625   auto decl = pdb->GetDeclForSymbol(*symbol);
626   if (!decl)
627     return CompilerDecl();
628 
629   return CompilerDecl(clang_ast_ctx, decl);
630 }
631 
632 lldb_private::CompilerDeclContext
633 SymbolFilePDB::GetDeclContextForUID(lldb::user_id_t uid) {
634   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
635       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
636   if (!clang_ast_ctx)
637     return CompilerDeclContext();
638 
639   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
640   if (!pdb)
641     return CompilerDeclContext();
642 
643   auto symbol = m_session_up->getSymbolById(uid);
644   if (!symbol)
645     return CompilerDeclContext();
646 
647   auto decl_context = pdb->GetDeclContextForSymbol(*symbol);
648   if (!decl_context)
649     return GetDeclContextContainingUID(uid);
650 
651   return CompilerDeclContext(clang_ast_ctx, decl_context);
652 }
653 
654 lldb_private::CompilerDeclContext
655 SymbolFilePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
656   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
657       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
658   if (!clang_ast_ctx)
659     return CompilerDeclContext();
660 
661   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
662   if (!pdb)
663     return CompilerDeclContext();
664 
665   auto symbol = m_session_up->getSymbolById(uid);
666   if (!symbol)
667     return CompilerDeclContext();
668 
669   auto decl_context = pdb->GetDeclContextContainingSymbol(*symbol);
670   assert(decl_context);
671 
672   return CompilerDeclContext(clang_ast_ctx, decl_context);
673 }
674 
675 void SymbolFilePDB::ParseDeclsForContext(
676     lldb_private::CompilerDeclContext decl_ctx) {
677   ClangASTContext *clang_ast_ctx = llvm::dyn_cast_or_null<ClangASTContext>(
678       GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus));
679   if (!clang_ast_ctx)
680     return;
681 
682   PDBASTParser *pdb = clang_ast_ctx->GetPDBParser();
683   if (!pdb)
684     return;
685 
686   pdb->ParseDeclsForDeclContext(
687       static_cast<clang::DeclContext *>(decl_ctx.GetOpaqueDeclContext()));
688 }
689 
690 uint32_t
691 SymbolFilePDB::ResolveSymbolContext(const lldb_private::Address &so_addr,
692                                     SymbolContextItem resolve_scope,
693                                     lldb_private::SymbolContext &sc) {
694   uint32_t resolved_flags = 0;
695   if (resolve_scope & eSymbolContextCompUnit ||
696       resolve_scope & eSymbolContextVariable ||
697       resolve_scope & eSymbolContextFunction ||
698       resolve_scope & eSymbolContextBlock ||
699       resolve_scope & eSymbolContextLineEntry) {
700     auto cu_sp = GetCompileUnitContainsAddress(so_addr);
701     if (!cu_sp) {
702       if (resolved_flags | eSymbolContextVariable) {
703         // TODO: Resolve variables
704       }
705       return 0;
706     }
707     sc.comp_unit = cu_sp.get();
708     resolved_flags |= eSymbolContextCompUnit;
709     lldbassert(sc.module_sp == cu_sp->GetModule());
710   }
711 
712   if (resolve_scope & eSymbolContextFunction ||
713       resolve_scope & eSymbolContextBlock) {
714     addr_t file_vm_addr = so_addr.GetFileAddress();
715     auto symbol_up =
716         m_session_up->findSymbolByAddress(file_vm_addr, PDB_SymType::Function);
717     if (symbol_up) {
718       auto *pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
719       assert(pdb_func);
720       auto func_uid = pdb_func->getSymIndexId();
721       sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
722       if (sc.function == nullptr)
723         sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, sc);
724       if (sc.function) {
725         resolved_flags |= eSymbolContextFunction;
726         if (resolve_scope & eSymbolContextBlock) {
727           auto block_symbol = m_session_up->findSymbolByAddress(
728               file_vm_addr, PDB_SymType::Block);
729           auto block_id = block_symbol ? block_symbol->getSymIndexId()
730                                        : sc.function->GetID();
731           sc.block = sc.function->GetBlock(true).FindBlockByID(block_id);
732           if (sc.block)
733             resolved_flags |= eSymbolContextBlock;
734         }
735       }
736     }
737   }
738 
739   if (resolve_scope & eSymbolContextLineEntry) {
740     if (auto *line_table = sc.comp_unit->GetLineTable()) {
741       Address addr(so_addr);
742       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
743         resolved_flags |= eSymbolContextLineEntry;
744     }
745   }
746 
747   return resolved_flags;
748 }
749 
750 uint32_t SymbolFilePDB::ResolveSymbolContext(
751     const lldb_private::FileSpec &file_spec, uint32_t line, bool check_inlines,
752     SymbolContextItem resolve_scope, lldb_private::SymbolContextList &sc_list) {
753   const size_t old_size = sc_list.GetSize();
754   if (resolve_scope & lldb::eSymbolContextCompUnit) {
755     // Locate all compilation units with line numbers referencing the specified
756     // file.  For example, if `file_spec` is <vector>, then this should return
757     // all source files and header files that reference <vector>, either
758     // directly or indirectly.
759     auto compilands = m_session_up->findCompilandsForSourceFile(
760         file_spec.GetPath(), PDB_NameSearchFlags::NS_CaseInsensitive);
761 
762     if (!compilands)
763       return 0;
764 
765     // For each one, either find its previously parsed data or parse it afresh
766     // and add it to the symbol context list.
767     while (auto compiland = compilands->getNext()) {
768       // If we're not checking inlines, then don't add line information for
769       // this file unless the FileSpec matches. For inline functions, we don't
770       // have to match the FileSpec since they could be defined in headers
771       // other than file specified in FileSpec.
772       if (!check_inlines) {
773         std::string source_file = compiland->getSourceFileFullPath();
774         if (source_file.empty())
775           continue;
776         FileSpec this_spec(source_file, FileSpec::Style::windows);
777         bool need_full_match = !file_spec.GetDirectory().IsEmpty();
778         if (FileSpec::Compare(file_spec, this_spec, need_full_match) != 0)
779           continue;
780       }
781 
782       SymbolContext sc;
783       auto cu = ParseCompileUnitForUID(compiland->getSymIndexId());
784       if (!cu)
785         continue;
786       sc.comp_unit = cu.get();
787       sc.module_sp = cu->GetModule();
788 
789       // If we were asked to resolve line entries, add all entries to the line
790       // table that match the requested line (or all lines if `line` == 0).
791       if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock |
792                            eSymbolContextLineEntry)) {
793         bool has_line_table = ParseCompileUnitLineTable(sc, line);
794 
795         if ((resolve_scope & eSymbolContextLineEntry) && !has_line_table) {
796           // The query asks for line entries, but we can't get them for the
797           // compile unit. This is not normal for `line` = 0. So just assert
798           // it.
799           assert(line && "Couldn't get all line entries!\n");
800 
801           // Current compiland does not have the requested line. Search next.
802           continue;
803         }
804 
805         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
806           if (!has_line_table)
807             continue;
808 
809           auto *line_table = sc.comp_unit->GetLineTable();
810           lldbassert(line_table);
811 
812           uint32_t num_line_entries = line_table->GetSize();
813           // Skip the terminal line entry.
814           --num_line_entries;
815 
816           // If `line `!= 0, see if we can resolve function for each line entry
817           // in the line table.
818           for (uint32_t line_idx = 0; line && line_idx < num_line_entries;
819                ++line_idx) {
820             if (!line_table->GetLineEntryAtIndex(line_idx, sc.line_entry))
821               continue;
822 
823             auto file_vm_addr =
824                 sc.line_entry.range.GetBaseAddress().GetFileAddress();
825             if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
826               continue;
827 
828             auto symbol_up = m_session_up->findSymbolByAddress(
829                 file_vm_addr, PDB_SymType::Function);
830             if (symbol_up) {
831               auto func_uid = symbol_up->getSymIndexId();
832               sc.function = sc.comp_unit->FindFunctionByUID(func_uid).get();
833               if (sc.function == nullptr) {
834                 auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(symbol_up.get());
835                 assert(pdb_func);
836                 sc.function = ParseCompileUnitFunctionForPDBFunc(*pdb_func, sc);
837               }
838               if (sc.function && (resolve_scope & eSymbolContextBlock)) {
839                 Block &block = sc.function->GetBlock(true);
840                 sc.block = block.FindBlockByID(sc.function->GetID());
841               }
842             }
843             sc_list.Append(sc);
844           }
845         } else if (has_line_table) {
846           // We can parse line table for the compile unit. But no query to
847           // resolve function or block. We append `sc` to the list anyway.
848           sc_list.Append(sc);
849         }
850       } else {
851         // No query for line entry, function or block. But we have a valid
852         // compile unit, append `sc` to the list.
853         sc_list.Append(sc);
854       }
855     }
856   }
857   return sc_list.GetSize() - old_size;
858 }
859 
860 std::string SymbolFilePDB::GetMangledForPDBData(const PDBSymbolData &pdb_data) {
861   // Cache public names at first
862   if (m_public_names.empty())
863     if (auto result_up =
864             m_global_scope_up->findAllChildren(PDB_SymType::PublicSymbol))
865       while (auto symbol_up = result_up->getNext())
866         if (auto addr = symbol_up->getRawSymbol().getVirtualAddress())
867           m_public_names[addr] = symbol_up->getRawSymbol().getName();
868 
869   // Look up the name in the cache
870   return m_public_names.lookup(pdb_data.getVirtualAddress());
871 }
872 
873 VariableSP SymbolFilePDB::ParseVariableForPDBData(
874     const lldb_private::SymbolContext &sc,
875     const llvm::pdb::PDBSymbolData &pdb_data) {
876   VariableSP var_sp;
877   uint32_t var_uid = pdb_data.getSymIndexId();
878   auto result = m_variables.find(var_uid);
879   if (result != m_variables.end())
880     return result->second;
881 
882   ValueType scope = eValueTypeInvalid;
883   bool is_static_member = false;
884   bool is_external = false;
885   bool is_artificial = false;
886 
887   switch (pdb_data.getDataKind()) {
888   case PDB_DataKind::Global:
889     scope = eValueTypeVariableGlobal;
890     is_external = true;
891     break;
892   case PDB_DataKind::Local:
893     scope = eValueTypeVariableLocal;
894     break;
895   case PDB_DataKind::FileStatic:
896     scope = eValueTypeVariableStatic;
897     break;
898   case PDB_DataKind::StaticMember:
899     is_static_member = true;
900     scope = eValueTypeVariableStatic;
901     break;
902   case PDB_DataKind::Member:
903     scope = eValueTypeVariableStatic;
904     break;
905   case PDB_DataKind::Param:
906     scope = eValueTypeVariableArgument;
907     break;
908   case PDB_DataKind::Constant:
909     scope = eValueTypeConstResult;
910     break;
911   default:
912     break;
913   }
914 
915   switch (pdb_data.getLocationType()) {
916   case PDB_LocType::TLS:
917     scope = eValueTypeVariableThreadLocal;
918     break;
919   case PDB_LocType::RegRel: {
920     // It is a `this` pointer.
921     if (pdb_data.getDataKind() == PDB_DataKind::ObjectPtr) {
922       scope = eValueTypeVariableArgument;
923       is_artificial = true;
924     }
925   } break;
926   default:
927     break;
928   }
929 
930   Declaration decl;
931   if (!is_artificial && !pdb_data.isCompilerGenerated()) {
932     if (auto lines = pdb_data.getLineNumbers()) {
933       if (auto first_line = lines->getNext()) {
934         uint32_t src_file_id = first_line->getSourceFileId();
935         auto src_file = m_session_up->getSourceFileById(src_file_id);
936         if (src_file) {
937           FileSpec spec(src_file->getFileName());
938           decl.SetFile(spec);
939           decl.SetColumn(first_line->getColumnNumber());
940           decl.SetLine(first_line->getLineNumber());
941         }
942       }
943     }
944   }
945 
946   Variable::RangeList ranges;
947   SymbolContextScope *context_scope = sc.comp_unit;
948   if (scope == eValueTypeVariableLocal) {
949     if (sc.function) {
950       context_scope = sc.function->GetBlock(true).FindBlockByID(
951           pdb_data.getLexicalParentId());
952       if (context_scope == nullptr)
953         context_scope = sc.function;
954     }
955   }
956 
957   SymbolFileTypeSP type_sp =
958       std::make_shared<SymbolFileType>(*this, pdb_data.getTypeId());
959 
960   auto var_name = pdb_data.getName();
961   auto mangled = GetMangledForPDBData(pdb_data);
962   auto mangled_cstr = mangled.empty() ? nullptr : mangled.c_str();
963 
964   bool is_constant;
965   DWARFExpression location = ConvertPDBLocationToDWARFExpression(
966       GetObjectFile()->GetModule(), pdb_data, is_constant);
967 
968   var_sp = std::make_shared<Variable>(
969       var_uid, var_name.c_str(), mangled_cstr, type_sp, scope, context_scope,
970       ranges, &decl, location, is_external, is_artificial, is_static_member);
971   var_sp->SetLocationIsConstantValueData(is_constant);
972 
973   m_variables.insert(std::make_pair(var_uid, var_sp));
974   return var_sp;
975 }
976 
977 size_t
978 SymbolFilePDB::ParseVariables(const lldb_private::SymbolContext &sc,
979                               const llvm::pdb::PDBSymbol &pdb_symbol,
980                               lldb_private::VariableList *variable_list) {
981   size_t num_added = 0;
982 
983   if (auto pdb_data = llvm::dyn_cast<PDBSymbolData>(&pdb_symbol)) {
984     VariableListSP local_variable_list_sp;
985 
986     auto result = m_variables.find(pdb_data->getSymIndexId());
987     if (result != m_variables.end()) {
988       if (variable_list)
989         variable_list->AddVariableIfUnique(result->second);
990     } else {
991       // Prepare right VariableList for this variable.
992       if (auto lexical_parent = pdb_data->getLexicalParent()) {
993         switch (lexical_parent->getSymTag()) {
994         case PDB_SymType::Exe:
995           assert(sc.comp_unit);
996           LLVM_FALLTHROUGH;
997         case PDB_SymType::Compiland: {
998           if (sc.comp_unit) {
999             local_variable_list_sp = sc.comp_unit->GetVariableList(false);
1000             if (!local_variable_list_sp) {
1001               local_variable_list_sp = std::make_shared<VariableList>();
1002               sc.comp_unit->SetVariableList(local_variable_list_sp);
1003             }
1004           }
1005         } break;
1006         case PDB_SymType::Block:
1007         case PDB_SymType::Function: {
1008           if (sc.function) {
1009             Block *block = sc.function->GetBlock(true).FindBlockByID(
1010                 lexical_parent->getSymIndexId());
1011             if (block) {
1012               local_variable_list_sp = block->GetBlockVariableList(false);
1013               if (!local_variable_list_sp) {
1014                 local_variable_list_sp = std::make_shared<VariableList>();
1015                 block->SetVariableList(local_variable_list_sp);
1016               }
1017             }
1018           }
1019         } break;
1020         default:
1021           break;
1022         }
1023       }
1024 
1025       if (local_variable_list_sp) {
1026         if (auto var_sp = ParseVariableForPDBData(sc, *pdb_data)) {
1027           local_variable_list_sp->AddVariableIfUnique(var_sp);
1028           if (variable_list)
1029             variable_list->AddVariableIfUnique(var_sp);
1030           ++num_added;
1031         }
1032       }
1033     }
1034   }
1035 
1036   if (auto results = pdb_symbol.findAllChildren()) {
1037     while (auto result = results->getNext())
1038       num_added += ParseVariables(sc, *result, variable_list);
1039   }
1040 
1041   return num_added;
1042 }
1043 
1044 uint32_t SymbolFilePDB::FindGlobalVariables(
1045     const lldb_private::ConstString &name,
1046     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1047     uint32_t max_matches, lldb_private::VariableList &variables) {
1048   if (!parent_decl_ctx)
1049     parent_decl_ctx = m_tu_decl_ctx_up.get();
1050   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1051     return 0;
1052   if (name.IsEmpty())
1053     return 0;
1054 
1055   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1056   if (!results)
1057     return 0;
1058 
1059   uint32_t matches = 0;
1060   size_t old_size = variables.GetSize();
1061   while (auto result = results->getNext()) {
1062     auto pdb_data = llvm::dyn_cast<PDBSymbolData>(result.get());
1063     if (max_matches > 0 && matches >= max_matches)
1064       break;
1065 
1066     SymbolContext sc;
1067     sc.module_sp = m_obj_file->GetModule();
1068     lldbassert(sc.module_sp.get());
1069 
1070     if (!name.GetStringRef().equals(
1071             PDBASTParser::PDBNameDropScope(pdb_data->getName())))
1072       continue;
1073 
1074     sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1075     // FIXME: We are not able to determine the compile unit.
1076     if (sc.comp_unit == nullptr)
1077       continue;
1078 
1079     auto actual_parent_decl_ctx =
1080         GetDeclContextContainingUID(result->getSymIndexId());
1081     if (actual_parent_decl_ctx != *parent_decl_ctx)
1082       continue;
1083 
1084     ParseVariables(sc, *pdb_data, &variables);
1085     matches = variables.GetSize() - old_size;
1086   }
1087 
1088   return matches;
1089 }
1090 
1091 uint32_t
1092 SymbolFilePDB::FindGlobalVariables(const lldb_private::RegularExpression &regex,
1093                                    uint32_t max_matches,
1094                                    lldb_private::VariableList &variables) {
1095   if (!regex.IsValid())
1096     return 0;
1097   auto results = m_global_scope_up->findAllChildren<PDBSymbolData>();
1098   if (!results)
1099     return 0;
1100 
1101   uint32_t matches = 0;
1102   size_t old_size = variables.GetSize();
1103   while (auto pdb_data = results->getNext()) {
1104     if (max_matches > 0 && matches >= max_matches)
1105       break;
1106 
1107     auto var_name = pdb_data->getName();
1108     if (var_name.empty())
1109       continue;
1110     if (!regex.Execute(var_name))
1111       continue;
1112     SymbolContext sc;
1113     sc.module_sp = m_obj_file->GetModule();
1114     lldbassert(sc.module_sp.get());
1115 
1116     sc.comp_unit = ParseCompileUnitForUID(GetCompilandId(*pdb_data)).get();
1117     // FIXME: We are not able to determine the compile unit.
1118     if (sc.comp_unit == nullptr)
1119       continue;
1120 
1121     ParseVariables(sc, *pdb_data, &variables);
1122     matches = variables.GetSize() - old_size;
1123   }
1124 
1125   return matches;
1126 }
1127 
1128 bool SymbolFilePDB::ResolveFunction(const llvm::pdb::PDBSymbolFunc &pdb_func,
1129                                     bool include_inlines,
1130                                     lldb_private::SymbolContextList &sc_list) {
1131   lldb_private::SymbolContext sc;
1132   sc.comp_unit = ParseCompileUnitForUID(pdb_func.getCompilandId()).get();
1133   if (!sc.comp_unit)
1134     return false;
1135   sc.module_sp = sc.comp_unit->GetModule();
1136   sc.function = ParseCompileUnitFunctionForPDBFunc(pdb_func, sc);
1137   if (!sc.function)
1138     return false;
1139 
1140   sc_list.Append(sc);
1141   return true;
1142 }
1143 
1144 bool SymbolFilePDB::ResolveFunction(uint32_t uid, bool include_inlines,
1145                                     lldb_private::SymbolContextList &sc_list) {
1146   auto pdb_func_up = m_session_up->getConcreteSymbolById<PDBSymbolFunc>(uid);
1147   if (!pdb_func_up && !(include_inlines && pdb_func_up->hasInlineAttribute()))
1148     return false;
1149   return ResolveFunction(*pdb_func_up, include_inlines, sc_list);
1150 }
1151 
1152 void SymbolFilePDB::CacheFunctionNames() {
1153   if (!m_func_full_names.IsEmpty())
1154     return;
1155 
1156   std::map<uint64_t, uint32_t> addr_ids;
1157 
1158   if (auto results_up = m_global_scope_up->findAllChildren<PDBSymbolFunc>()) {
1159     while (auto pdb_func_up = results_up->getNext()) {
1160       if (pdb_func_up->isCompilerGenerated())
1161         continue;
1162 
1163       auto name = pdb_func_up->getName();
1164       auto demangled_name = pdb_func_up->getUndecoratedName();
1165       if (name.empty() && demangled_name.empty())
1166         continue;
1167 
1168       auto uid = pdb_func_up->getSymIndexId();
1169       if (!demangled_name.empty() && pdb_func_up->getVirtualAddress())
1170         addr_ids.insert(std::make_pair(pdb_func_up->getVirtualAddress(), uid));
1171 
1172       if (auto parent = pdb_func_up->getClassParent()) {
1173 
1174         // PDB have symbols for class/struct methods or static methods in Enum
1175         // Class. We won't bother to check if the parent is UDT or Enum here.
1176         m_func_method_names.Append(ConstString(name), uid);
1177 
1178         ConstString cstr_name(name);
1179 
1180         // To search a method name, like NS::Class:MemberFunc, LLDB searches
1181         // its base name, i.e. MemberFunc by default. Since PDBSymbolFunc does
1182         // not have inforamtion of this, we extract base names and cache them
1183         // by our own effort.
1184         llvm::StringRef basename;
1185         CPlusPlusLanguage::MethodName cpp_method(cstr_name);
1186         if (cpp_method.IsValid()) {
1187           llvm::StringRef context;
1188           basename = cpp_method.GetBasename();
1189           if (basename.empty())
1190             CPlusPlusLanguage::ExtractContextAndIdentifier(name.c_str(),
1191                                                            context, basename);
1192         }
1193 
1194         if (!basename.empty())
1195           m_func_base_names.Append(ConstString(basename), uid);
1196         else {
1197           m_func_base_names.Append(ConstString(name), uid);
1198         }
1199 
1200         if (!demangled_name.empty())
1201           m_func_full_names.Append(ConstString(demangled_name), uid);
1202 
1203       } else {
1204         // Handle not-method symbols.
1205 
1206         // The function name might contain namespace, or its lexical scope. It
1207         // is not safe to get its base name by applying same scheme as we deal
1208         // with the method names.
1209         // FIXME: Remove namespace if function is static in a scope.
1210         m_func_base_names.Append(ConstString(name), uid);
1211 
1212         if (name == "main") {
1213           m_func_full_names.Append(ConstString(name), uid);
1214 
1215           if (!demangled_name.empty() && name != demangled_name) {
1216             m_func_full_names.Append(ConstString(demangled_name), uid);
1217             m_func_base_names.Append(ConstString(demangled_name), uid);
1218           }
1219         } else if (!demangled_name.empty()) {
1220           m_func_full_names.Append(ConstString(demangled_name), uid);
1221         } else {
1222           m_func_full_names.Append(ConstString(name), uid);
1223         }
1224       }
1225     }
1226   }
1227 
1228   if (auto results_up =
1229           m_global_scope_up->findAllChildren<PDBSymbolPublicSymbol>()) {
1230     while (auto pub_sym_up = results_up->getNext()) {
1231       if (!pub_sym_up->isFunction())
1232         continue;
1233       auto name = pub_sym_up->getName();
1234       if (name.empty())
1235         continue;
1236 
1237       if (CPlusPlusLanguage::IsCPPMangledName(name.c_str())) {
1238         auto vm_addr = pub_sym_up->getVirtualAddress();
1239 
1240         // PDB public symbol has mangled name for its associated function.
1241         if (vm_addr && addr_ids.find(vm_addr) != addr_ids.end()) {
1242           // Cache mangled name.
1243           m_func_full_names.Append(ConstString(name), addr_ids[vm_addr]);
1244         }
1245       }
1246     }
1247   }
1248   // Sort them before value searching is working properly
1249   m_func_full_names.Sort();
1250   m_func_full_names.SizeToFit();
1251   m_func_method_names.Sort();
1252   m_func_method_names.SizeToFit();
1253   m_func_base_names.Sort();
1254   m_func_base_names.SizeToFit();
1255 }
1256 
1257 uint32_t SymbolFilePDB::FindFunctions(
1258     const lldb_private::ConstString &name,
1259     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1260     FunctionNameType name_type_mask, bool include_inlines, bool append,
1261     lldb_private::SymbolContextList &sc_list) {
1262   if (!append)
1263     sc_list.Clear();
1264   lldbassert((name_type_mask & eFunctionNameTypeAuto) == 0);
1265 
1266   if (name_type_mask == eFunctionNameTypeNone)
1267     return 0;
1268   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1269     return 0;
1270   if (name.IsEmpty())
1271     return 0;
1272 
1273   auto old_size = sc_list.GetSize();
1274   if (name_type_mask & eFunctionNameTypeFull ||
1275       name_type_mask & eFunctionNameTypeBase ||
1276       name_type_mask & eFunctionNameTypeMethod) {
1277     CacheFunctionNames();
1278 
1279     std::set<uint32_t> resolved_ids;
1280     auto ResolveFn = [include_inlines, &name, &sc_list, &resolved_ids,
1281                       this](UniqueCStringMap<uint32_t> &Names) {
1282       std::vector<uint32_t> ids;
1283       if (Names.GetValues(name, ids)) {
1284         for (auto id : ids) {
1285           if (resolved_ids.find(id) == resolved_ids.end()) {
1286             if (ResolveFunction(id, include_inlines, sc_list))
1287               resolved_ids.insert(id);
1288           }
1289         }
1290       }
1291     };
1292     if (name_type_mask & eFunctionNameTypeFull) {
1293       ResolveFn(m_func_full_names);
1294     }
1295     if (name_type_mask & eFunctionNameTypeBase) {
1296       ResolveFn(m_func_base_names);
1297     }
1298     if (name_type_mask & eFunctionNameTypeMethod) {
1299       ResolveFn(m_func_method_names);
1300     }
1301   }
1302   return sc_list.GetSize() - old_size;
1303 }
1304 
1305 uint32_t
1306 SymbolFilePDB::FindFunctions(const lldb_private::RegularExpression &regex,
1307                              bool include_inlines, bool append,
1308                              lldb_private::SymbolContextList &sc_list) {
1309   if (!append)
1310     sc_list.Clear();
1311   if (!regex.IsValid())
1312     return 0;
1313 
1314   auto old_size = sc_list.GetSize();
1315   CacheFunctionNames();
1316 
1317   std::set<uint32_t> resolved_ids;
1318   auto ResolveFn = [&regex, include_inlines, &sc_list, &resolved_ids,
1319                     this](UniqueCStringMap<uint32_t> &Names) {
1320     std::vector<uint32_t> ids;
1321     if (Names.GetValues(regex, ids)) {
1322       for (auto id : ids) {
1323         if (resolved_ids.find(id) == resolved_ids.end())
1324           if (ResolveFunction(id, include_inlines, sc_list))
1325             resolved_ids.insert(id);
1326       }
1327     }
1328   };
1329   ResolveFn(m_func_full_names);
1330   ResolveFn(m_func_base_names);
1331 
1332   return sc_list.GetSize() - old_size;
1333 }
1334 
1335 void SymbolFilePDB::GetMangledNamesForFunction(
1336     const std::string &scope_qualified_name,
1337     std::vector<lldb_private::ConstString> &mangled_names) {}
1338 
1339 uint32_t SymbolFilePDB::FindTypes(
1340     const lldb_private::SymbolContext &sc,
1341     const lldb_private::ConstString &name,
1342     const lldb_private::CompilerDeclContext *parent_decl_ctx, bool append,
1343     uint32_t max_matches,
1344     llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
1345     lldb_private::TypeMap &types) {
1346   if (!append)
1347     types.Clear();
1348   if (!name)
1349     return 0;
1350   if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
1351     return 0;
1352 
1353   searched_symbol_files.clear();
1354   searched_symbol_files.insert(this);
1355 
1356   std::string name_str = name.AsCString();
1357 
1358   // There is an assumption 'name' is not a regex
1359   FindTypesByName(name_str, parent_decl_ctx, max_matches, types);
1360 
1361   return types.GetSize();
1362 }
1363 
1364 void SymbolFilePDB::DumpClangAST(Stream &s) {
1365   auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1366   auto clang = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1367   if (!clang)
1368     return;
1369   clang->Dump(s);
1370 }
1371 
1372 void SymbolFilePDB::FindTypesByRegex(
1373     const lldb_private::RegularExpression &regex, uint32_t max_matches,
1374     lldb_private::TypeMap &types) {
1375   // When searching by regex, we need to go out of our way to limit the search
1376   // space as much as possible since this searches EVERYTHING in the PDB,
1377   // manually doing regex comparisons.  PDB library isn't optimized for regex
1378   // searches or searches across multiple symbol types at the same time, so the
1379   // best we can do is to search enums, then typedefs, then classes one by one,
1380   // and do a regex comparison against each of them.
1381   PDB_SymType tags_to_search[] = {PDB_SymType::Enum, PDB_SymType::Typedef,
1382                                   PDB_SymType::UDT};
1383   std::unique_ptr<IPDBEnumSymbols> results;
1384 
1385   uint32_t matches = 0;
1386 
1387   for (auto tag : tags_to_search) {
1388     results = m_global_scope_up->findAllChildren(tag);
1389     if (!results)
1390       continue;
1391 
1392     while (auto result = results->getNext()) {
1393       if (max_matches > 0 && matches >= max_matches)
1394         break;
1395 
1396       std::string type_name;
1397       if (auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(result.get()))
1398         type_name = enum_type->getName();
1399       else if (auto typedef_type =
1400                    llvm::dyn_cast<PDBSymbolTypeTypedef>(result.get()))
1401         type_name = typedef_type->getName();
1402       else if (auto class_type = llvm::dyn_cast<PDBSymbolTypeUDT>(result.get()))
1403         type_name = class_type->getName();
1404       else {
1405         // We're looking only for types that have names.  Skip symbols, as well
1406         // as unnamed types such as arrays, pointers, etc.
1407         continue;
1408       }
1409 
1410       if (!regex.Execute(type_name))
1411         continue;
1412 
1413       // This should cause the type to get cached and stored in the `m_types`
1414       // lookup.
1415       if (!ResolveTypeUID(result->getSymIndexId()))
1416         continue;
1417 
1418       auto iter = m_types.find(result->getSymIndexId());
1419       if (iter == m_types.end())
1420         continue;
1421       types.Insert(iter->second);
1422       ++matches;
1423     }
1424   }
1425 }
1426 
1427 void SymbolFilePDB::FindTypesByName(
1428     const std::string &name,
1429     const lldb_private::CompilerDeclContext *parent_decl_ctx,
1430     uint32_t max_matches, lldb_private::TypeMap &types) {
1431   if (!parent_decl_ctx)
1432     parent_decl_ctx = m_tu_decl_ctx_up.get();
1433   std::unique_ptr<IPDBEnumSymbols> results;
1434   if (name.empty())
1435     return;
1436   results = m_global_scope_up->findAllChildren(PDB_SymType::None);
1437   if (!results)
1438     return;
1439 
1440   uint32_t matches = 0;
1441 
1442   while (auto result = results->getNext()) {
1443     if (max_matches > 0 && matches >= max_matches)
1444       break;
1445 
1446     if (PDBASTParser::PDBNameDropScope(result->getRawSymbol().getName()) !=
1447         name)
1448       continue;
1449 
1450     switch (result->getSymTag()) {
1451     case PDB_SymType::Enum:
1452     case PDB_SymType::UDT:
1453     case PDB_SymType::Typedef:
1454       break;
1455     default:
1456       // We're looking only for types that have names.  Skip symbols, as well
1457       // as unnamed types such as arrays, pointers, etc.
1458       continue;
1459     }
1460 
1461     // This should cause the type to get cached and stored in the `m_types`
1462     // lookup.
1463     if (!ResolveTypeUID(result->getSymIndexId()))
1464       continue;
1465 
1466     auto actual_parent_decl_ctx =
1467         GetDeclContextContainingUID(result->getSymIndexId());
1468     if (actual_parent_decl_ctx != *parent_decl_ctx)
1469       continue;
1470 
1471     auto iter = m_types.find(result->getSymIndexId());
1472     if (iter == m_types.end())
1473       continue;
1474     types.Insert(iter->second);
1475     ++matches;
1476   }
1477 }
1478 
1479 size_t SymbolFilePDB::FindTypes(
1480     const std::vector<lldb_private::CompilerContext> &contexts, bool append,
1481     lldb_private::TypeMap &types) {
1482   return 0;
1483 }
1484 
1485 lldb_private::TypeList *SymbolFilePDB::GetTypeList() {
1486   return m_obj_file->GetModule()->GetTypeList();
1487 }
1488 
1489 void SymbolFilePDB::GetTypesForPDBSymbol(const llvm::pdb::PDBSymbol &pdb_symbol,
1490                                          uint32_t type_mask,
1491                                          TypeCollection &type_collection) {
1492   bool can_parse = false;
1493   switch (pdb_symbol.getSymTag()) {
1494   case PDB_SymType::ArrayType:
1495     can_parse = ((type_mask & eTypeClassArray) != 0);
1496     break;
1497   case PDB_SymType::BuiltinType:
1498     can_parse = ((type_mask & eTypeClassBuiltin) != 0);
1499     break;
1500   case PDB_SymType::Enum:
1501     can_parse = ((type_mask & eTypeClassEnumeration) != 0);
1502     break;
1503   case PDB_SymType::Function:
1504   case PDB_SymType::FunctionSig:
1505     can_parse = ((type_mask & eTypeClassFunction) != 0);
1506     break;
1507   case PDB_SymType::PointerType:
1508     can_parse = ((type_mask & (eTypeClassPointer | eTypeClassBlockPointer |
1509                                eTypeClassMemberPointer)) != 0);
1510     break;
1511   case PDB_SymType::Typedef:
1512     can_parse = ((type_mask & eTypeClassTypedef) != 0);
1513     break;
1514   case PDB_SymType::UDT: {
1515     auto *udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&pdb_symbol);
1516     assert(udt);
1517     can_parse = (udt->getUdtKind() != PDB_UdtType::Interface &&
1518                  ((type_mask & (eTypeClassClass | eTypeClassStruct |
1519                                 eTypeClassUnion)) != 0));
1520   } break;
1521   default:
1522     break;
1523   }
1524 
1525   if (can_parse) {
1526     if (auto *type = ResolveTypeUID(pdb_symbol.getSymIndexId())) {
1527       auto result =
1528           std::find(type_collection.begin(), type_collection.end(), type);
1529       if (result == type_collection.end())
1530         type_collection.push_back(type);
1531     }
1532   }
1533 
1534   auto results_up = pdb_symbol.findAllChildren();
1535   while (auto symbol_up = results_up->getNext())
1536     GetTypesForPDBSymbol(*symbol_up, type_mask, type_collection);
1537 }
1538 
1539 size_t SymbolFilePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1540                                TypeClass type_mask,
1541                                lldb_private::TypeList &type_list) {
1542   TypeCollection type_collection;
1543   uint32_t old_size = type_list.GetSize();
1544   CompileUnit *cu =
1545       sc_scope ? sc_scope->CalculateSymbolContextCompileUnit() : nullptr;
1546   if (cu) {
1547     auto compiland_up = GetPDBCompilandByUID(cu->GetID());
1548     if (!compiland_up)
1549       return 0;
1550     GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1551   } else {
1552     for (uint32_t cu_idx = 0; cu_idx < GetNumCompileUnits(); ++cu_idx) {
1553       auto cu_sp = ParseCompileUnitAtIndex(cu_idx);
1554       if (cu_sp) {
1555         if (auto compiland_up = GetPDBCompilandByUID(cu_sp->GetID()))
1556           GetTypesForPDBSymbol(*compiland_up, type_mask, type_collection);
1557       }
1558     }
1559   }
1560 
1561   for (auto type : type_collection) {
1562     type->GetForwardCompilerType();
1563     type_list.Insert(type->shared_from_this());
1564   }
1565   return type_list.GetSize() - old_size;
1566 }
1567 
1568 lldb_private::TypeSystem *
1569 SymbolFilePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1570   auto type_system =
1571       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1572   if (type_system)
1573     type_system->SetSymbolFile(this);
1574   return type_system;
1575 }
1576 
1577 lldb_private::CompilerDeclContext SymbolFilePDB::FindNamespace(
1578     const lldb_private::SymbolContext &sc,
1579     const lldb_private::ConstString &name,
1580     const lldb_private::CompilerDeclContext *parent_decl_ctx) {
1581   auto type_system = GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus);
1582   auto clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1583   if (!clang_type_system)
1584     return CompilerDeclContext();
1585 
1586   PDBASTParser *pdb = clang_type_system->GetPDBParser();
1587   if (!pdb)
1588     return CompilerDeclContext();
1589 
1590   clang::DeclContext *decl_context = nullptr;
1591   if (parent_decl_ctx)
1592     decl_context = static_cast<clang::DeclContext *>(
1593         parent_decl_ctx->GetOpaqueDeclContext());
1594 
1595   auto namespace_decl =
1596       pdb->FindNamespaceDecl(decl_context, name.GetStringRef());
1597   if (!namespace_decl)
1598     return CompilerDeclContext();
1599 
1600   return CompilerDeclContext(type_system,
1601                              static_cast<clang::DeclContext *>(namespace_decl));
1602 }
1603 
1604 lldb_private::ConstString SymbolFilePDB::GetPluginName() {
1605   static ConstString g_name("pdb");
1606   return g_name;
1607 }
1608 
1609 uint32_t SymbolFilePDB::GetPluginVersion() { return 1; }
1610 
1611 IPDBSession &SymbolFilePDB::GetPDBSession() { return *m_session_up; }
1612 
1613 const IPDBSession &SymbolFilePDB::GetPDBSession() const {
1614   return *m_session_up;
1615 }
1616 
1617 lldb::CompUnitSP SymbolFilePDB::ParseCompileUnitForUID(uint32_t id,
1618                                                        uint32_t index) {
1619   auto found_cu = m_comp_units.find(id);
1620   if (found_cu != m_comp_units.end())
1621     return found_cu->second;
1622 
1623   auto compiland_up = GetPDBCompilandByUID(id);
1624   if (!compiland_up)
1625     return CompUnitSP();
1626 
1627   lldb::LanguageType lang;
1628   auto details = compiland_up->findOneChild<PDBSymbolCompilandDetails>();
1629   if (!details)
1630     lang = lldb::eLanguageTypeC_plus_plus;
1631   else
1632     lang = TranslateLanguage(details->getLanguage());
1633 
1634   if (lang == lldb::LanguageType::eLanguageTypeUnknown)
1635     return CompUnitSP();
1636 
1637   std::string path = compiland_up->getSourceFileFullPath();
1638   if (path.empty())
1639     return CompUnitSP();
1640 
1641   // Don't support optimized code for now, DebugInfoPDB does not return this
1642   // information.
1643   LazyBool optimized = eLazyBoolNo;
1644   auto cu_sp = std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr,
1645                                              path.c_str(), id, lang, optimized);
1646 
1647   if (!cu_sp)
1648     return CompUnitSP();
1649 
1650   m_comp_units.insert(std::make_pair(id, cu_sp));
1651   if (index == UINT32_MAX)
1652     GetCompileUnitIndex(*compiland_up, index);
1653   lldbassert(index != UINT32_MAX);
1654   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(index,
1655                                                                     cu_sp);
1656   return cu_sp;
1657 }
1658 
1659 bool SymbolFilePDB::ParseCompileUnitLineTable(
1660     const lldb_private::SymbolContext &sc, uint32_t match_line) {
1661   lldbassert(sc.comp_unit);
1662 
1663   auto compiland_up = GetPDBCompilandByUID(sc.comp_unit->GetID());
1664   if (!compiland_up)
1665     return false;
1666 
1667   // LineEntry needs the *index* of the file into the list of support files
1668   // returned by ParseCompileUnitSupportFiles.  But the underlying SDK gives us
1669   // a globally unique idenfitifier in the namespace of the PDB.  So, we have
1670   // to do a mapping so that we can hand out indices.
1671   llvm::DenseMap<uint32_t, uint32_t> index_map;
1672   BuildSupportFileIdToSupportFileIndexMap(*compiland_up, index_map);
1673   auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1674 
1675   // Find contributions to `compiland` from all source and header files.
1676   std::string path = sc.comp_unit->GetPath();
1677   auto files = m_session_up->getSourceFilesForCompiland(*compiland_up);
1678   if (!files)
1679     return false;
1680 
1681   // For each source and header file, create a LineSequence for contributions
1682   // to the compiland from that file, and add the sequence.
1683   while (auto file = files->getNext()) {
1684     std::unique_ptr<LineSequence> sequence(
1685         line_table->CreateLineSequenceContainer());
1686     auto lines = m_session_up->findLineNumbers(*compiland_up, *file);
1687     if (!lines)
1688       continue;
1689     int entry_count = lines->getChildCount();
1690 
1691     uint64_t prev_addr;
1692     uint32_t prev_length;
1693     uint32_t prev_line;
1694     uint32_t prev_source_idx;
1695 
1696     for (int i = 0; i < entry_count; ++i) {
1697       auto line = lines->getChildAtIndex(i);
1698 
1699       uint64_t lno = line->getLineNumber();
1700       uint64_t addr = line->getVirtualAddress();
1701       uint32_t length = line->getLength();
1702       uint32_t source_id = line->getSourceFileId();
1703       uint32_t col = line->getColumnNumber();
1704       uint32_t source_idx = index_map[source_id];
1705 
1706       // There was a gap between the current entry and the previous entry if
1707       // the addresses don't perfectly line up.
1708       bool is_gap = (i > 0) && (prev_addr + prev_length < addr);
1709 
1710       // Before inserting the current entry, insert a terminal entry at the end
1711       // of the previous entry's address range if the current entry resulted in
1712       // a gap from the previous entry.
1713       if (is_gap && ShouldAddLine(match_line, prev_line, prev_length)) {
1714         line_table->AppendLineEntryToSequence(
1715             sequence.get(), prev_addr + prev_length, prev_line, 0,
1716             prev_source_idx, false, false, false, false, true);
1717 
1718         line_table->InsertSequence(sequence.release());
1719         sequence.reset(line_table->CreateLineSequenceContainer());
1720       }
1721 
1722       if (ShouldAddLine(match_line, lno, length)) {
1723         bool is_statement = line->isStatement();
1724         bool is_prologue = false;
1725         bool is_epilogue = false;
1726         auto func =
1727             m_session_up->findSymbolByAddress(addr, PDB_SymType::Function);
1728         if (func) {
1729           auto prologue = func->findOneChild<PDBSymbolFuncDebugStart>();
1730           if (prologue)
1731             is_prologue = (addr == prologue->getVirtualAddress());
1732 
1733           auto epilogue = func->findOneChild<PDBSymbolFuncDebugEnd>();
1734           if (epilogue)
1735             is_epilogue = (addr == epilogue->getVirtualAddress());
1736         }
1737 
1738         line_table->AppendLineEntryToSequence(sequence.get(), addr, lno, col,
1739                                               source_idx, is_statement, false,
1740                                               is_prologue, is_epilogue, false);
1741       }
1742 
1743       prev_addr = addr;
1744       prev_length = length;
1745       prev_line = lno;
1746       prev_source_idx = source_idx;
1747     }
1748 
1749     if (entry_count > 0 && ShouldAddLine(match_line, prev_line, prev_length)) {
1750       // The end is always a terminal entry, so insert it regardless.
1751       line_table->AppendLineEntryToSequence(
1752           sequence.get(), prev_addr + prev_length, prev_line, 0,
1753           prev_source_idx, false, false, false, false, true);
1754     }
1755 
1756     line_table->InsertSequence(sequence.release());
1757   }
1758 
1759   if (line_table->GetSize()) {
1760     sc.comp_unit->SetLineTable(line_table.release());
1761     return true;
1762   }
1763   return false;
1764 }
1765 
1766 void SymbolFilePDB::BuildSupportFileIdToSupportFileIndexMap(
1767     const PDBSymbolCompiland &compiland,
1768     llvm::DenseMap<uint32_t, uint32_t> &index_map) const {
1769   // This is a hack, but we need to convert the source id into an index into
1770   // the support files array.  We don't want to do path comparisons to avoid
1771   // basename / full path issues that may or may not even be a problem, so we
1772   // use the globally unique source file identifiers.  Ideally we could use the
1773   // global identifiers everywhere, but LineEntry currently assumes indices.
1774   auto source_files = m_session_up->getSourceFilesForCompiland(compiland);
1775   if (!source_files)
1776     return;
1777 
1778   // LLDB uses the DWARF-like file numeration (one based)
1779   int index = 1;
1780 
1781   while (auto file = source_files->getNext()) {
1782     uint32_t source_id = file->getUniqueId();
1783     index_map[source_id] = index++;
1784   }
1785 }
1786 
1787 lldb::CompUnitSP SymbolFilePDB::GetCompileUnitContainsAddress(
1788     const lldb_private::Address &so_addr) {
1789   lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1790   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
1791     return nullptr;
1792 
1793   // If it is a PDB function's vm addr, this is the first sure bet.
1794   if (auto lines =
1795           m_session_up->findLineNumbersByAddress(file_vm_addr, /*Length=*/1)) {
1796     if (auto first_line = lines->getNext())
1797       return ParseCompileUnitForUID(first_line->getCompilandId());
1798   }
1799 
1800   // Otherwise we resort to section contributions.
1801   if (auto sec_contribs = m_session_up->getSectionContribs()) {
1802     while (auto section = sec_contribs->getNext()) {
1803       auto va = section->getVirtualAddress();
1804       if (file_vm_addr >= va && file_vm_addr < va + section->getLength())
1805         return ParseCompileUnitForUID(section->getCompilandId());
1806     }
1807   }
1808   return nullptr;
1809 }
1810 
1811 Mangled
1812 SymbolFilePDB::GetMangledForPDBFunc(const llvm::pdb::PDBSymbolFunc &pdb_func) {
1813   Mangled mangled;
1814   auto func_name = pdb_func.getName();
1815   auto func_undecorated_name = pdb_func.getUndecoratedName();
1816   std::string func_decorated_name;
1817 
1818   // Seek from public symbols for non-static function's decorated name if any.
1819   // For static functions, they don't have undecorated names and aren't exposed
1820   // in Public Symbols either.
1821   if (!func_undecorated_name.empty()) {
1822     auto result_up = m_global_scope_up->findChildren(
1823         PDB_SymType::PublicSymbol, func_undecorated_name,
1824         PDB_NameSearchFlags::NS_UndecoratedName);
1825     if (result_up) {
1826       while (auto symbol_up = result_up->getNext()) {
1827         // For a public symbol, it is unique.
1828         lldbassert(result_up->getChildCount() == 1);
1829         if (auto *pdb_public_sym =
1830                 llvm::dyn_cast_or_null<PDBSymbolPublicSymbol>(
1831                     symbol_up.get())) {
1832           if (pdb_public_sym->isFunction()) {
1833             func_decorated_name = pdb_public_sym->getName();
1834             break;
1835           }
1836         }
1837       }
1838     }
1839   }
1840   if (!func_decorated_name.empty()) {
1841     mangled.SetMangledName(ConstString(func_decorated_name));
1842 
1843     // For MSVC, format of C funciton's decorated name depends on calling
1844     // conventon. Unfortunately none of the format is recognized by current
1845     // LLDB. For example, `_purecall` is a __cdecl C function. From PDB,
1846     // `__purecall` is retrieved as both its decorated and undecorated name
1847     // (using PDBSymbolFunc::getUndecoratedName method). However `__purecall`
1848     // string is not treated as mangled in LLDB (neither `?` nor `_Z` prefix).
1849     // Mangled::GetDemangledName method will fail internally and caches an
1850     // empty string as its undecorated name. So we will face a contradition
1851     // here for the same symbol:
1852     //   non-empty undecorated name from PDB
1853     //   empty undecorated name from LLDB
1854     if (!func_undecorated_name.empty() &&
1855         mangled.GetDemangledName(mangled.GuessLanguage()).IsEmpty())
1856       mangled.SetDemangledName(ConstString(func_undecorated_name));
1857 
1858     // LLDB uses several flags to control how a C++ decorated name is
1859     // undecorated for MSVC. See `safeUndecorateName` in Class Mangled. So the
1860     // yielded name could be different from what we retrieve from
1861     // PDB source unless we also apply same flags in getting undecorated
1862     // name through PDBSymbolFunc::getUndecoratedNameEx method.
1863     if (!func_undecorated_name.empty() &&
1864         mangled.GetDemangledName(mangled.GuessLanguage()) !=
1865             ConstString(func_undecorated_name))
1866       mangled.SetDemangledName(ConstString(func_undecorated_name));
1867   } else if (!func_undecorated_name.empty()) {
1868     mangled.SetDemangledName(ConstString(func_undecorated_name));
1869   } else if (!func_name.empty())
1870     mangled.SetValue(ConstString(func_name), false);
1871 
1872   return mangled;
1873 }
1874 
1875 bool SymbolFilePDB::DeclContextMatchesThisSymbolFile(
1876     const lldb_private::CompilerDeclContext *decl_ctx) {
1877   if (decl_ctx == nullptr || !decl_ctx->IsValid())
1878     return true;
1879 
1880   TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
1881   if (!decl_ctx_type_system)
1882     return false;
1883   TypeSystem *type_system = GetTypeSystemForLanguage(
1884       decl_ctx_type_system->GetMinimumLanguage(nullptr));
1885   if (decl_ctx_type_system == type_system)
1886     return true; // The type systems match, return true
1887 
1888   return false;
1889 }
1890 
1891 uint32_t SymbolFilePDB::GetCompilandId(const llvm::pdb::PDBSymbolData &data) {
1892   static const auto pred_upper = [](uint32_t lhs, SecContribInfo rhs) {
1893     return lhs < rhs.Offset;
1894   };
1895 
1896   // Cache section contributions
1897   if (m_sec_contribs.empty()) {
1898     if (auto SecContribs = m_session_up->getSectionContribs()) {
1899       while (auto SectionContrib = SecContribs->getNext()) {
1900         auto comp_id = SectionContrib->getCompilandId();
1901         if (!comp_id)
1902           continue;
1903 
1904         auto sec = SectionContrib->getAddressSection();
1905         auto &sec_cs = m_sec_contribs[sec];
1906 
1907         auto offset = SectionContrib->getAddressOffset();
1908         auto it =
1909             std::upper_bound(sec_cs.begin(), sec_cs.end(), offset, pred_upper);
1910 
1911         auto size = SectionContrib->getLength();
1912         sec_cs.insert(it, {offset, size, comp_id});
1913       }
1914     }
1915   }
1916 
1917   // Check by line number
1918   if (auto Lines = data.getLineNumbers()) {
1919     if (auto FirstLine = Lines->getNext())
1920       return FirstLine->getCompilandId();
1921   }
1922 
1923   // Retrieve section + offset
1924   uint32_t DataSection = data.getAddressSection();
1925   uint32_t DataOffset = data.getAddressOffset();
1926   if (DataSection == 0) {
1927     if (auto RVA = data.getRelativeVirtualAddress())
1928       m_session_up->addressForRVA(RVA, DataSection, DataOffset);
1929   }
1930 
1931   if (DataSection) {
1932     // Search by section contributions
1933     auto &sec_cs = m_sec_contribs[DataSection];
1934     auto it =
1935         std::upper_bound(sec_cs.begin(), sec_cs.end(), DataOffset, pred_upper);
1936     if (it != sec_cs.begin()) {
1937       --it;
1938       if (DataOffset < it->Offset + it->Size)
1939         return it->CompilandId;
1940     }
1941   } else {
1942     // Search in lexical tree
1943     auto LexParentId = data.getLexicalParentId();
1944     while (auto LexParent = m_session_up->getSymbolById(LexParentId)) {
1945       if (LexParent->getSymTag() == PDB_SymType::Exe)
1946         break;
1947       if (LexParent->getSymTag() == PDB_SymType::Compiland)
1948         return LexParentId;
1949       LexParentId = LexParent->getRawSymbol().getLexicalParentId();
1950     }
1951   }
1952 
1953   return 0;
1954 }
1955