1 //===-- SymbolFileNativePDB.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolFileNativePDB.h"
10 
11 #include "clang/AST/Attr.h"
12 #include "clang/AST/CharUnits.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/Type.h"
16 
17 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
18 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
19 #include "Plugins/ObjectFile/PDB/ObjectFilePDB.h"
20 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Core/StreamBuffer.h"
24 #include "lldb/Core/StreamFile.h"
25 #include "lldb/Symbol/CompileUnit.h"
26 #include "lldb/Symbol/LineTable.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/Symbol/SymbolVendor.h"
30 #include "lldb/Symbol/Variable.h"
31 #include "lldb/Symbol/VariableList.h"
32 #include "lldb/Utility/LLDBLog.h"
33 #include "lldb/Utility/Log.h"
34 
35 #include "llvm/DebugInfo/CodeView/CVRecord.h"
36 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
37 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
38 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
39 #include "llvm/DebugInfo/CodeView/RecordName.h"
40 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
41 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
42 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
43 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
44 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
45 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
46 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
47 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
48 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
49 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
50 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
51 #include "llvm/DebugInfo/PDB/PDB.h"
52 #include "llvm/DebugInfo/PDB/PDBTypes.h"
53 #include "llvm/Demangle/MicrosoftDemangle.h"
54 #include "llvm/Object/COFF.h"
55 #include "llvm/Support/Allocator.h"
56 #include "llvm/Support/BinaryStreamReader.h"
57 #include "llvm/Support/Error.h"
58 #include "llvm/Support/ErrorOr.h"
59 #include "llvm/Support/MemoryBuffer.h"
60 
61 #include "DWARFLocationExpression.h"
62 #include "PdbAstBuilder.h"
63 #include "PdbSymUid.h"
64 #include "PdbUtil.h"
65 #include "UdtRecordCompleter.h"
66 
67 using namespace lldb;
68 using namespace lldb_private;
69 using namespace npdb;
70 using namespace llvm::codeview;
71 using namespace llvm::pdb;
72 
73 char SymbolFileNativePDB::ID;
74 
75 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
76   switch (lang) {
77   case PDB_Lang::Cpp:
78     return lldb::LanguageType::eLanguageTypeC_plus_plus;
79   case PDB_Lang::C:
80     return lldb::LanguageType::eLanguageTypeC;
81   case PDB_Lang::Swift:
82     return lldb::LanguageType::eLanguageTypeSwift;
83   case PDB_Lang::Rust:
84     return lldb::LanguageType::eLanguageTypeRust;
85   default:
86     return lldb::LanguageType::eLanguageTypeUnknown;
87   }
88 }
89 
90 static std::unique_ptr<PDBFile>
91 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
92   // Try to find a matching PDB for an EXE.
93   using namespace llvm::object;
94   auto expected_binary = createBinary(exe_path);
95 
96   // If the file isn't a PE/COFF executable, fail.
97   if (!expected_binary) {
98     llvm::consumeError(expected_binary.takeError());
99     return nullptr;
100   }
101   OwningBinary<Binary> binary = std::move(*expected_binary);
102 
103   // TODO: Avoid opening the PE/COFF binary twice by reading this information
104   // directly from the lldb_private::ObjectFile.
105   auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
106   if (!obj)
107     return nullptr;
108   const llvm::codeview::DebugInfo *pdb_info = nullptr;
109 
110   // If it doesn't have a debug directory, fail.
111   llvm::StringRef pdb_file;
112   if (llvm::Error e = obj->getDebugPDBInfo(pdb_info, pdb_file)) {
113     consumeError(std::move(e));
114     return nullptr;
115   }
116 
117   // If the file doesn't exist, perhaps the path specified at build time
118   // doesn't match the PDB's current location, so check the location of the
119   // executable.
120   if (!FileSystem::Instance().Exists(pdb_file)) {
121     const auto exe_dir = FileSpec(exe_path).CopyByRemovingLastPathComponent();
122     const auto pdb_name = FileSpec(pdb_file).GetFilename().GetCString();
123     pdb_file = exe_dir.CopyByAppendingPathComponent(pdb_name).GetCString();
124   }
125 
126   // If the file is not a PDB or if it doesn't have a matching GUID, fail.
127   auto pdb = ObjectFilePDB::loadPDBFile(std::string(pdb_file), allocator);
128   if (!pdb)
129     return nullptr;
130 
131   auto expected_info = pdb->getPDBInfoStream();
132   if (!expected_info) {
133     llvm::consumeError(expected_info.takeError());
134     return nullptr;
135   }
136   llvm::codeview::GUID guid;
137   memcpy(&guid, pdb_info->PDB70.Signature, 16);
138 
139   if (expected_info->getGuid() != guid)
140     return nullptr;
141   return pdb;
142 }
143 
144 static bool IsFunctionPrologue(const CompilandIndexItem &cci,
145                                lldb::addr_t addr) {
146   // FIXME: Implement this.
147   return false;
148 }
149 
150 static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
151                                lldb::addr_t addr) {
152   // FIXME: Implement this.
153   return false;
154 }
155 
156 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
157   switch (kind) {
158   case SimpleTypeKind::Boolean128:
159   case SimpleTypeKind::Boolean16:
160   case SimpleTypeKind::Boolean32:
161   case SimpleTypeKind::Boolean64:
162   case SimpleTypeKind::Boolean8:
163     return "bool";
164   case SimpleTypeKind::Byte:
165   case SimpleTypeKind::UnsignedCharacter:
166     return "unsigned char";
167   case SimpleTypeKind::NarrowCharacter:
168     return "char";
169   case SimpleTypeKind::SignedCharacter:
170   case SimpleTypeKind::SByte:
171     return "signed char";
172   case SimpleTypeKind::Character16:
173     return "char16_t";
174   case SimpleTypeKind::Character32:
175     return "char32_t";
176   case SimpleTypeKind::Character8:
177     return "char8_t";
178   case SimpleTypeKind::Complex80:
179   case SimpleTypeKind::Complex64:
180   case SimpleTypeKind::Complex32:
181     return "complex";
182   case SimpleTypeKind::Float128:
183   case SimpleTypeKind::Float80:
184     return "long double";
185   case SimpleTypeKind::Float64:
186     return "double";
187   case SimpleTypeKind::Float32:
188     return "float";
189   case SimpleTypeKind::Float16:
190     return "single";
191   case SimpleTypeKind::Int128:
192     return "__int128";
193   case SimpleTypeKind::Int64:
194   case SimpleTypeKind::Int64Quad:
195     return "int64_t";
196   case SimpleTypeKind::Int32:
197     return "int";
198   case SimpleTypeKind::Int16:
199     return "short";
200   case SimpleTypeKind::UInt128:
201     return "unsigned __int128";
202   case SimpleTypeKind::UInt64:
203   case SimpleTypeKind::UInt64Quad:
204     return "uint64_t";
205   case SimpleTypeKind::HResult:
206     return "HRESULT";
207   case SimpleTypeKind::UInt32:
208     return "unsigned";
209   case SimpleTypeKind::UInt16:
210   case SimpleTypeKind::UInt16Short:
211     return "unsigned short";
212   case SimpleTypeKind::Int32Long:
213     return "long";
214   case SimpleTypeKind::UInt32Long:
215     return "unsigned long";
216   case SimpleTypeKind::Void:
217     return "void";
218   case SimpleTypeKind::WideCharacter:
219     return "wchar_t";
220   default:
221     return "";
222   }
223 }
224 
225 static bool IsClassRecord(TypeLeafKind kind) {
226   switch (kind) {
227   case LF_STRUCTURE:
228   case LF_CLASS:
229   case LF_INTERFACE:
230     return true;
231   default:
232     return false;
233   }
234 }
235 
236 void SymbolFileNativePDB::Initialize() {
237   PluginManager::RegisterPlugin(GetPluginNameStatic(),
238                                 GetPluginDescriptionStatic(), CreateInstance,
239                                 DebuggerInitialize);
240 }
241 
242 void SymbolFileNativePDB::Terminate() {
243   PluginManager::UnregisterPlugin(CreateInstance);
244 }
245 
246 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
247 
248 llvm::StringRef SymbolFileNativePDB::GetPluginDescriptionStatic() {
249   return "Microsoft PDB debug symbol cross-platform file reader.";
250 }
251 
252 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFileSP objfile_sp) {
253   return new SymbolFileNativePDB(std::move(objfile_sp));
254 }
255 
256 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFileSP objfile_sp)
257     : SymbolFileCommon(std::move(objfile_sp)) {}
258 
259 SymbolFileNativePDB::~SymbolFileNativePDB() = default;
260 
261 uint32_t SymbolFileNativePDB::CalculateAbilities() {
262   uint32_t abilities = 0;
263   if (!m_objfile_sp)
264     return 0;
265 
266   if (!m_index) {
267     // Lazily load and match the PDB file, but only do this once.
268     PDBFile *pdb_file;
269     if (auto *pdb = llvm::dyn_cast<ObjectFilePDB>(m_objfile_sp.get())) {
270       pdb_file = &pdb->GetPDBFile();
271     } else {
272       m_file_up = loadMatchingPDBFile(m_objfile_sp->GetFileSpec().GetPath(),
273                                       m_allocator);
274       pdb_file = m_file_up.get();
275     }
276 
277     if (!pdb_file)
278       return 0;
279 
280     auto expected_index = PdbIndex::create(pdb_file);
281     if (!expected_index) {
282       llvm::consumeError(expected_index.takeError());
283       return 0;
284     }
285     m_index = std::move(*expected_index);
286   }
287   if (!m_index)
288     return 0;
289 
290   // We don't especially have to be precise here.  We only distinguish between
291   // stripped and not stripped.
292   abilities = kAllAbilities;
293 
294   if (m_index->dbi().isStripped())
295     abilities &= ~(Blocks | LocalVariables);
296   return abilities;
297 }
298 
299 void SymbolFileNativePDB::InitializeObject() {
300   m_obj_load_address = m_objfile_sp->GetModule()
301                            ->GetObjectFile()
302                            ->GetBaseAddress()
303                            .GetFileAddress();
304   m_index->SetLoadAddress(m_obj_load_address);
305   m_index->ParseSectionContribs();
306 
307   auto ts_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage(
308       lldb::eLanguageTypeC_plus_plus);
309   if (auto err = ts_or_err.takeError()) {
310     LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
311                    "Failed to initialize");
312   } else {
313     ts_or_err->SetSymbolFile(this);
314     auto *clang = llvm::cast_or_null<TypeSystemClang>(&ts_or_err.get());
315     lldbassert(clang);
316     m_ast = std::make_unique<PdbAstBuilder>(*m_objfile_sp, *m_index, *clang);
317   }
318 }
319 
320 uint32_t SymbolFileNativePDB::CalculateNumCompileUnits() {
321   const DbiModuleList &modules = m_index->dbi().modules();
322   uint32_t count = modules.getModuleCount();
323   if (count == 0)
324     return count;
325 
326   // The linker can inject an additional "dummy" compilation unit into the
327   // PDB. Ignore this special compile unit for our purposes, if it is there.
328   // It is always the last one.
329   DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
330   if (last.getModuleName() == "* Linker *")
331     --count;
332   return count;
333 }
334 
335 Block &SymbolFileNativePDB::CreateBlock(PdbCompilandSymId block_id) {
336   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
337   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
338   CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
339   lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id);
340   BlockSP child_block = std::make_shared<Block>(opaque_block_uid);
341 
342   switch (sym.kind()) {
343   case S_GPROC32:
344   case S_LPROC32: {
345     // This is a function.  It must be global.  Creating the Function entry
346     // for it automatically creates a block for it.
347     FunctionSP func = GetOrCreateFunction(block_id, *comp_unit);
348     Block &block = func->GetBlock(false);
349     if (block.GetNumRanges() == 0)
350       block.AddRange(Block::Range(0, func->GetAddressRange().GetByteSize()));
351     return block;
352   }
353   case S_BLOCK32: {
354     // This is a block.  Its parent is either a function or another block.  In
355     // either case, its parent can be viewed as a block (e.g. a function
356     // contains 1 big block.  So just get the parent block and add this block
357     // to it.
358     BlockSym block(static_cast<SymbolRecordKind>(sym.kind()));
359     cantFail(SymbolDeserializer::deserializeAs<BlockSym>(sym, block));
360     lldbassert(block.Parent != 0);
361     PdbCompilandSymId parent_id(block_id.modi, block.Parent);
362     Block &parent_block = GetOrCreateBlock(parent_id);
363     parent_block.AddChild(child_block);
364     m_ast->GetOrCreateBlockDecl(block_id);
365     m_blocks.insert({opaque_block_uid, child_block});
366     break;
367   }
368   case S_INLINESITE: {
369     // This ensures line table is parsed first so we have inline sites info.
370     comp_unit->GetLineTable();
371 
372     std::shared_ptr<InlineSite> inline_site = m_inline_sites[opaque_block_uid];
373     Block &parent_block = GetOrCreateBlock(inline_site->parent_id);
374     parent_block.AddChild(child_block);
375     m_ast->GetOrCreateInlinedFunctionDecl(block_id);
376     // Copy ranges from InlineSite to Block.
377     for (size_t i = 0; i < inline_site->ranges.GetSize(); ++i) {
378       auto *entry = inline_site->ranges.GetEntryAtIndex(i);
379       child_block->AddRange(
380           Block::Range(entry->GetRangeBase(), entry->GetByteSize()));
381     }
382     child_block->FinalizeRanges();
383 
384     // Get the inlined function callsite info.
385     Declaration &decl = inline_site->inline_function_info->GetDeclaration();
386     Declaration &callsite = inline_site->inline_function_info->GetCallSite();
387     child_block->SetInlinedFunctionInfo(
388         inline_site->inline_function_info->GetName().GetCString(), nullptr,
389         &decl, &callsite);
390     m_blocks.insert({opaque_block_uid, child_block});
391     break;
392   }
393   default:
394     lldbassert(false && "Symbol is not a block!");
395   }
396 
397   return *child_block;
398 }
399 
400 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id,
401                                                      CompileUnit &comp_unit) {
402   const CompilandIndexItem *cci =
403       m_index->compilands().GetCompiland(func_id.modi);
404   lldbassert(cci);
405   CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
406 
407   lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
408   SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
409 
410   auto file_vm_addr =
411       m_index->MakeVirtualAddress(sol.so.segment, sol.so.offset);
412   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
413     return nullptr;
414 
415   AddressRange func_range(file_vm_addr, sol.length,
416                           comp_unit.GetModule()->GetSectionList());
417   if (!func_range.GetBaseAddress().IsValid())
418     return nullptr;
419 
420   ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
421   cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc));
422   if (proc.FunctionType == TypeIndex::None())
423     return nullptr;
424   TypeSP func_type = GetOrCreateType(proc.FunctionType);
425   if (!func_type)
426     return nullptr;
427 
428   PdbTypeSymId sig_id(proc.FunctionType, false);
429   Mangled mangled(proc.Name);
430   FunctionSP func_sp = std::make_shared<Function>(
431       &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
432       func_type.get(), func_range);
433 
434   comp_unit.AddFunction(func_sp);
435 
436   m_ast->GetOrCreateFunctionDecl(func_id);
437 
438   return func_sp;
439 }
440 
441 CompUnitSP
442 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
443   lldb::LanguageType lang =
444       cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
445                          : lldb::eLanguageTypeUnknown;
446 
447   LazyBool optimized = eLazyBoolNo;
448   if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
449     optimized = eLazyBoolYes;
450 
451   llvm::SmallString<64> source_file_name =
452       m_index->compilands().GetMainSourceFile(cci);
453   FileSpec fs(llvm::sys::path::convert_to_slash(
454       source_file_name, llvm::sys::path::Style::windows_backslash));
455 
456   CompUnitSP cu_sp =
457       std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, fs,
458                                     toOpaqueUid(cci.m_id), lang, optimized);
459 
460   SetCompileUnitAtIndex(cci.m_id.modi, cu_sp);
461   return cu_sp;
462 }
463 
464 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id,
465                                                      const ModifierRecord &mr,
466                                                      CompilerType ct) {
467   TpiStream &stream = m_index->tpi();
468 
469   std::string name;
470   if (mr.ModifiedType.isSimple())
471     name = std::string(GetSimpleTypeName(mr.ModifiedType.getSimpleKind()));
472   else
473     name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
474   Declaration decl;
475   lldb::TypeSP modified_type = GetOrCreateType(mr.ModifiedType);
476 
477   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(name),
478                                 modified_type->GetByteSize(nullptr), nullptr,
479                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
480                                 ct, Type::ResolveState::Full);
481 }
482 
483 lldb::TypeSP
484 SymbolFileNativePDB::CreatePointerType(PdbTypeSymId type_id,
485                                        const llvm::codeview::PointerRecord &pr,
486                                        CompilerType ct) {
487   TypeSP pointee = GetOrCreateType(pr.ReferentType);
488   if (!pointee)
489     return nullptr;
490 
491   if (pr.isPointerToMember()) {
492     MemberPointerInfo mpi = pr.getMemberInfo();
493     GetOrCreateType(mpi.ContainingType);
494   }
495 
496   Declaration decl;
497   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(),
498                                 pr.getSize(), nullptr, LLDB_INVALID_UID,
499                                 Type::eEncodingIsUID, decl, ct,
500                                 Type::ResolveState::Full);
501 }
502 
503 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti,
504                                                    CompilerType ct) {
505   uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
506   if (ti == TypeIndex::NullptrT()) {
507     Declaration decl;
508     return std::make_shared<Type>(
509         uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID,
510         Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
511   }
512 
513   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
514     TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
515     uint32_t pointer_size = 0;
516     switch (ti.getSimpleMode()) {
517     case SimpleTypeMode::FarPointer32:
518     case SimpleTypeMode::NearPointer32:
519       pointer_size = 4;
520       break;
521     case SimpleTypeMode::NearPointer64:
522       pointer_size = 8;
523       break;
524     default:
525       // 128-bit and 16-bit pointers unsupported.
526       return nullptr;
527     }
528     Declaration decl;
529     return std::make_shared<Type>(
530         uid, this, ConstString(), pointer_size, nullptr, LLDB_INVALID_UID,
531         Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
532   }
533 
534   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
535     return nullptr;
536 
537   size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
538   llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
539 
540   Declaration decl;
541   return std::make_shared<Type>(uid, this, ConstString(type_name), size,
542                                 nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID,
543                                 decl, ct, Type::ResolveState::Full);
544 }
545 
546 static std::string GetUnqualifiedTypeName(const TagRecord &record) {
547   if (!record.hasUniqueName()) {
548     MSVCUndecoratedNameParser parser(record.Name);
549     llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
550 
551     return std::string(specs.back().GetBaseName());
552   }
553 
554   llvm::ms_demangle::Demangler demangler;
555   StringView sv(record.UniqueName.begin(), record.UniqueName.size());
556   llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
557   if (demangler.Error)
558     return std::string(record.Name);
559 
560   llvm::ms_demangle::IdentifierNode *idn =
561       ttn->QualifiedName->getUnqualifiedIdentifier();
562   return idn->toString();
563 }
564 
565 lldb::TypeSP
566 SymbolFileNativePDB::CreateClassStructUnion(PdbTypeSymId type_id,
567                                             const TagRecord &record,
568                                             size_t size, CompilerType ct) {
569 
570   std::string uname = GetUnqualifiedTypeName(record);
571 
572   // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
573   Declaration decl;
574   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(uname),
575                                 size, nullptr, LLDB_INVALID_UID,
576                                 Type::eEncodingIsUID, decl, ct,
577                                 Type::ResolveState::Forward);
578 }
579 
580 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
581                                                 const ClassRecord &cr,
582                                                 CompilerType ct) {
583   return CreateClassStructUnion(type_id, cr, cr.getSize(), ct);
584 }
585 
586 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
587                                                 const UnionRecord &ur,
588                                                 CompilerType ct) {
589   return CreateClassStructUnion(type_id, ur, ur.getSize(), ct);
590 }
591 
592 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
593                                                 const EnumRecord &er,
594                                                 CompilerType ct) {
595   std::string uname = GetUnqualifiedTypeName(er);
596 
597   Declaration decl;
598   TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
599 
600   return std::make_shared<lldb_private::Type>(
601       toOpaqueUid(type_id), this, ConstString(uname),
602       underlying_type->GetByteSize(nullptr), nullptr, LLDB_INVALID_UID,
603       lldb_private::Type::eEncodingIsUID, decl, ct,
604       lldb_private::Type::ResolveState::Forward);
605 }
606 
607 TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id,
608                                             const ArrayRecord &ar,
609                                             CompilerType ct) {
610   TypeSP element_type = GetOrCreateType(ar.ElementType);
611 
612   Declaration decl;
613   TypeSP array_sp = std::make_shared<lldb_private::Type>(
614       toOpaqueUid(type_id), this, ConstString(), ar.Size, nullptr,
615       LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, ct,
616       lldb_private::Type::ResolveState::Full);
617   array_sp->SetEncodingType(element_type.get());
618   return array_sp;
619 }
620 
621 
622 TypeSP SymbolFileNativePDB::CreateFunctionType(PdbTypeSymId type_id,
623                                                const MemberFunctionRecord &mfr,
624                                                CompilerType ct) {
625   Declaration decl;
626   return std::make_shared<lldb_private::Type>(
627       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
628       lldb_private::Type::eEncodingIsUID, decl, ct,
629       lldb_private::Type::ResolveState::Full);
630 }
631 
632 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id,
633                                                 const ProcedureRecord &pr,
634                                                 CompilerType ct) {
635   Declaration decl;
636   return std::make_shared<lldb_private::Type>(
637       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
638       lldb_private::Type::eEncodingIsUID, decl, ct,
639       lldb_private::Type::ResolveState::Full);
640 }
641 
642 TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id, CompilerType ct) {
643   if (type_id.index.isSimple())
644     return CreateSimpleType(type_id.index, ct);
645 
646   TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
647   CVType cvt = stream.getType(type_id.index);
648 
649   if (cvt.kind() == LF_MODIFIER) {
650     ModifierRecord modifier;
651     llvm::cantFail(
652         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
653     return CreateModifierType(type_id, modifier, ct);
654   }
655 
656   if (cvt.kind() == LF_POINTER) {
657     PointerRecord pointer;
658     llvm::cantFail(
659         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
660     return CreatePointerType(type_id, pointer, ct);
661   }
662 
663   if (IsClassRecord(cvt.kind())) {
664     ClassRecord cr;
665     llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
666     return CreateTagType(type_id, cr, ct);
667   }
668 
669   if (cvt.kind() == LF_ENUM) {
670     EnumRecord er;
671     llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
672     return CreateTagType(type_id, er, ct);
673   }
674 
675   if (cvt.kind() == LF_UNION) {
676     UnionRecord ur;
677     llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
678     return CreateTagType(type_id, ur, ct);
679   }
680 
681   if (cvt.kind() == LF_ARRAY) {
682     ArrayRecord ar;
683     llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
684     return CreateArrayType(type_id, ar, ct);
685   }
686 
687   if (cvt.kind() == LF_PROCEDURE) {
688     ProcedureRecord pr;
689     llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
690     return CreateProcedureType(type_id, pr, ct);
691   }
692   if (cvt.kind() == LF_MFUNCTION) {
693     MemberFunctionRecord mfr;
694     llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
695     return CreateFunctionType(type_id, mfr, ct);
696   }
697 
698   return nullptr;
699 }
700 
701 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) {
702   // If they search for a UDT which is a forward ref, try and resolve the full
703   // decl and just map the forward ref uid to the full decl record.
704   llvm::Optional<PdbTypeSymId> full_decl_uid;
705   if (IsForwardRefUdt(type_id, m_index->tpi())) {
706     auto expected_full_ti =
707         m_index->tpi().findFullDeclForForwardRef(type_id.index);
708     if (!expected_full_ti)
709       llvm::consumeError(expected_full_ti.takeError());
710     else if (*expected_full_ti != type_id.index) {
711       full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
712 
713       // It's possible that a lookup would occur for the full decl causing it
714       // to be cached, then a second lookup would occur for the forward decl.
715       // We don't want to create a second full decl, so make sure the full
716       // decl hasn't already been cached.
717       auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
718       if (full_iter != m_types.end()) {
719         TypeSP result = full_iter->second;
720         // Map the forward decl to the TypeSP for the full decl so we can take
721         // the fast path next time.
722         m_types[toOpaqueUid(type_id)] = result;
723         return result;
724       }
725     }
726   }
727 
728   PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
729 
730   clang::QualType qt = m_ast->GetOrCreateType(best_decl_id);
731   if (qt.isNull())
732     return nullptr;
733 
734   TypeSP result = CreateType(best_decl_id, m_ast->ToCompilerType(qt));
735   if (!result)
736     return nullptr;
737 
738   uint64_t best_uid = toOpaqueUid(best_decl_id);
739   m_types[best_uid] = result;
740   // If we had both a forward decl and a full decl, make both point to the new
741   // type.
742   if (full_decl_uid)
743     m_types[toOpaqueUid(type_id)] = result;
744 
745   return result;
746 }
747 
748 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) {
749   // We can't use try_emplace / overwrite here because the process of creating
750   // a type could create nested types, which could invalidate iterators.  So
751   // we have to do a 2-phase lookup / insert.
752   auto iter = m_types.find(toOpaqueUid(type_id));
753   if (iter != m_types.end())
754     return iter->second;
755 
756   TypeSP type = CreateAndCacheType(type_id);
757   if (type)
758     GetTypeList().Insert(type);
759   return type;
760 }
761 
762 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) {
763   CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
764   if (sym.kind() == S_CONSTANT)
765     return CreateConstantSymbol(var_id, sym);
766 
767   lldb::ValueType scope = eValueTypeInvalid;
768   TypeIndex ti;
769   llvm::StringRef name;
770   lldb::addr_t addr = 0;
771   uint16_t section = 0;
772   uint32_t offset = 0;
773   bool is_external = false;
774   switch (sym.kind()) {
775   case S_GDATA32:
776     is_external = true;
777     LLVM_FALLTHROUGH;
778   case S_LDATA32: {
779     DataSym ds(sym.kind());
780     llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
781     ti = ds.Type;
782     scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
783                                       : eValueTypeVariableStatic;
784     name = ds.Name;
785     section = ds.Segment;
786     offset = ds.DataOffset;
787     addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
788     break;
789   }
790   case S_GTHREAD32:
791     is_external = true;
792     LLVM_FALLTHROUGH;
793   case S_LTHREAD32: {
794     ThreadLocalDataSym tlds(sym.kind());
795     llvm::cantFail(
796         SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
797     ti = tlds.Type;
798     name = tlds.Name;
799     section = tlds.Segment;
800     offset = tlds.DataOffset;
801     addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
802     scope = eValueTypeVariableThreadLocal;
803     break;
804   }
805   default:
806     llvm_unreachable("unreachable!");
807   }
808 
809   CompUnitSP comp_unit;
810   llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
811   if (!modi) {
812     return nullptr;
813   }
814 
815   CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
816   comp_unit = GetOrCreateCompileUnit(cci);
817 
818   Declaration decl;
819   PdbTypeSymId tid(ti, false);
820   SymbolFileTypeSP type_sp =
821       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
822   Variable::RangeList ranges;
823 
824   m_ast->GetOrCreateVariableDecl(var_id);
825 
826   DWARFExpression location = MakeGlobalLocationExpression(
827       section, offset, GetObjectFile()->GetModule());
828 
829   std::string global_name("::");
830   global_name += name;
831   bool artificial = false;
832   bool location_is_constant_data = false;
833   bool static_member = false;
834   VariableSP var_sp = std::make_shared<Variable>(
835       toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
836       scope, comp_unit.get(), ranges, &decl, location, is_external, artificial,
837       location_is_constant_data, static_member);
838 
839   return var_sp;
840 }
841 
842 lldb::VariableSP
843 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
844                                           const CVSymbol &cvs) {
845   TpiStream &tpi = m_index->tpi();
846   ConstantSym constant(cvs.kind());
847 
848   llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
849   std::string global_name("::");
850   global_name += constant.Name;
851   PdbTypeSymId tid(constant.Type, false);
852   SymbolFileTypeSP type_sp =
853       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
854 
855   Declaration decl;
856   Variable::RangeList ranges;
857   ModuleSP module = GetObjectFile()->GetModule();
858   DWARFExpression location = MakeConstantLocationExpression(
859       constant.Type, tpi, constant.Value, module);
860 
861   bool external = false;
862   bool artificial = false;
863   bool location_is_constant_data = true;
864   bool static_member = false;
865   VariableSP var_sp = std::make_shared<Variable>(
866       toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
867       type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
868       external, artificial, location_is_constant_data, static_member);
869   return var_sp;
870 }
871 
872 VariableSP
873 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
874   auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
875   if (emplace_result.second) {
876     if (VariableSP var_sp = CreateGlobalVariable(var_id))
877       emplace_result.first->second = var_sp;
878     else
879       return nullptr;
880   }
881 
882   return emplace_result.first->second;
883 }
884 
885 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
886   return GetOrCreateType(PdbTypeSymId(ti, false));
887 }
888 
889 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
890                                                     CompileUnit &comp_unit) {
891   auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
892   if (emplace_result.second)
893     emplace_result.first->second = CreateFunction(func_id, comp_unit);
894 
895   return emplace_result.first->second;
896 }
897 
898 CompUnitSP
899 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
900 
901   auto emplace_result =
902       m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
903   if (emplace_result.second)
904     emplace_result.first->second = CreateCompileUnit(cci);
905 
906   lldbassert(emplace_result.first->second);
907   return emplace_result.first->second;
908 }
909 
910 Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) {
911   auto iter = m_blocks.find(toOpaqueUid(block_id));
912   if (iter != m_blocks.end())
913     return *iter->second;
914 
915   return CreateBlock(block_id);
916 }
917 
918 void SymbolFileNativePDB::ParseDeclsForContext(
919     lldb_private::CompilerDeclContext decl_ctx) {
920   clang::DeclContext *context = m_ast->FromCompilerDeclContext(decl_ctx);
921   if (!context)
922     return;
923   m_ast->ParseDeclsForContext(*context);
924 }
925 
926 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
927   if (index >= GetNumCompileUnits())
928     return CompUnitSP();
929   lldbassert(index < UINT16_MAX);
930   if (index >= UINT16_MAX)
931     return nullptr;
932 
933   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
934 
935   return GetOrCreateCompileUnit(item);
936 }
937 
938 lldb::LanguageType SymbolFileNativePDB::ParseLanguage(CompileUnit &comp_unit) {
939   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
940   PdbSymUid uid(comp_unit.GetID());
941   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
942 
943   CompilandIndexItem *item =
944       m_index->compilands().GetCompiland(uid.asCompiland().modi);
945   lldbassert(item);
946   if (!item->m_compile_opts)
947     return lldb::eLanguageTypeUnknown;
948 
949   return TranslateLanguage(item->m_compile_opts->getLanguage());
950 }
951 
952 void SymbolFileNativePDB::AddSymbols(Symtab &symtab) {}
953 
954 size_t SymbolFileNativePDB::ParseFunctions(CompileUnit &comp_unit) {
955   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
956   PdbSymUid uid{comp_unit.GetID()};
957   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
958   uint16_t modi = uid.asCompiland().modi;
959   CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
960 
961   size_t count = comp_unit.GetNumFunctions();
962   const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
963   for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
964     if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
965       continue;
966 
967     PdbCompilandSymId sym_id{modi, iter.offset()};
968 
969     FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
970   }
971 
972   size_t new_count = comp_unit.GetNumFunctions();
973   lldbassert(new_count >= count);
974   return new_count - count;
975 }
976 
977 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
978   // If any of these flags are set, we need to resolve the compile unit.
979   uint32_t flags = eSymbolContextCompUnit;
980   flags |= eSymbolContextVariable;
981   flags |= eSymbolContextFunction;
982   flags |= eSymbolContextBlock;
983   flags |= eSymbolContextLineEntry;
984   return (resolve_scope & flags) != 0;
985 }
986 
987 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
988     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
989   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
990   uint32_t resolved_flags = 0;
991   lldb::addr_t file_addr = addr.GetFileAddress();
992 
993   if (NeedsResolvedCompileUnit(resolve_scope)) {
994     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
995     if (!modi)
996       return 0;
997     CompUnitSP cu_sp = GetCompileUnitAtIndex(*modi);
998     if (!cu_sp)
999       return 0;
1000 
1001     sc.comp_unit = cu_sp.get();
1002     resolved_flags |= eSymbolContextCompUnit;
1003   }
1004 
1005   if (resolve_scope & eSymbolContextFunction ||
1006       resolve_scope & eSymbolContextBlock) {
1007     lldbassert(sc.comp_unit);
1008     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1009     // Search the matches in reverse.  This way if there are multiple matches
1010     // (for example we are 3 levels deep in a nested scope) it will find the
1011     // innermost one first.
1012     for (const auto &match : llvm::reverse(matches)) {
1013       if (match.uid.kind() != PdbSymUidKind::CompilandSym)
1014         continue;
1015 
1016       PdbCompilandSymId csid = match.uid.asCompilandSym();
1017       CVSymbol cvs = m_index->ReadSymbolRecord(csid);
1018       PDB_SymType type = CVSymToPDBSym(cvs.kind());
1019       if (type != PDB_SymType::Function && type != PDB_SymType::Block)
1020         continue;
1021       if (type == PDB_SymType::Function) {
1022         sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
1023         Block &block = sc.function->GetBlock(true);
1024         addr_t func_base =
1025             sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
1026         addr_t offset = file_addr - func_base;
1027         sc.block = block.FindInnermostBlockByOffset(offset);
1028       }
1029 
1030       if (type == PDB_SymType::Block) {
1031         sc.block = &GetOrCreateBlock(csid);
1032         sc.function = sc.block->CalculateSymbolContextFunction();
1033       }
1034       if (sc.function)
1035         resolved_flags |= eSymbolContextFunction;
1036       if (sc.block)
1037         resolved_flags |= eSymbolContextBlock;
1038       break;
1039     }
1040   }
1041 
1042   if (resolve_scope & eSymbolContextLineEntry) {
1043     lldbassert(sc.comp_unit);
1044     if (auto *line_table = sc.comp_unit->GetLineTable()) {
1045       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1046         resolved_flags |= eSymbolContextLineEntry;
1047     }
1048   }
1049 
1050   return resolved_flags;
1051 }
1052 
1053 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1054     const SourceLocationSpec &src_location_spec,
1055     lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1056   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1057   const uint32_t prev_size = sc_list.GetSize();
1058   if (resolve_scope & eSymbolContextCompUnit) {
1059     for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1060          ++cu_idx) {
1061       CompileUnit *cu = ParseCompileUnitAtIndex(cu_idx).get();
1062       if (!cu)
1063         continue;
1064 
1065       bool file_spec_matches_cu_file_spec = FileSpec::Match(
1066           src_location_spec.GetFileSpec(), cu->GetPrimaryFile());
1067       if (file_spec_matches_cu_file_spec) {
1068         cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
1069         break;
1070       }
1071     }
1072   }
1073   return sc_list.GetSize() - prev_size;
1074 }
1075 
1076 bool SymbolFileNativePDB::ParseLineTable(CompileUnit &comp_unit) {
1077   // Unfortunately LLDB is set up to parse the entire compile unit line table
1078   // all at once, even if all it really needs is line info for a specific
1079   // function.  In the future it would be nice if it could set the sc.m_function
1080   // member, and we could only get the line info for the function in question.
1081   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1082   PdbSymUid cu_id(comp_unit.GetID());
1083   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1084   uint16_t modi = cu_id.asCompiland().modi;
1085   CompilandIndexItem *cii = m_index->compilands().GetCompiland(modi);
1086   lldbassert(cii);
1087 
1088   // Parse DEBUG_S_LINES subsections first, then parse all S_INLINESITE records
1089   // in this CU. Add line entries into the set first so that if there are line
1090   // entries with same addres, the later is always more accurate than the
1091   // former.
1092   std::set<LineTable::Entry, LineTableEntryComparator> line_set;
1093 
1094   // This is basically a copy of the .debug$S subsections from all original COFF
1095   // object files merged together with address relocations applied.  We are
1096   // looking for all DEBUG_S_LINES subsections.
1097   for (const DebugSubsectionRecord &dssr :
1098        cii->m_debug_stream.getSubsectionsArray()) {
1099     if (dssr.kind() != DebugSubsectionKind::Lines)
1100       continue;
1101 
1102     DebugLinesSubsectionRef lines;
1103     llvm::BinaryStreamReader reader(dssr.getRecordData());
1104     if (auto EC = lines.initialize(reader)) {
1105       llvm::consumeError(std::move(EC));
1106       return false;
1107     }
1108 
1109     const LineFragmentHeader *lfh = lines.header();
1110     uint64_t virtual_addr =
1111         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1112     if (virtual_addr == LLDB_INVALID_ADDRESS)
1113       continue;
1114 
1115     for (const LineColumnEntry &group : lines) {
1116       llvm::Expected<uint32_t> file_index_or_err =
1117           GetFileIndex(*cii, group.NameIndex);
1118       if (!file_index_or_err)
1119         continue;
1120       uint32_t file_index = file_index_or_err.get();
1121       lldbassert(!group.LineNumbers.empty());
1122       CompilandIndexItem::GlobalLineTable::Entry line_entry(
1123           LLDB_INVALID_ADDRESS, 0);
1124       for (const LineNumberEntry &entry : group.LineNumbers) {
1125         LineInfo cur_info(entry.Flags);
1126 
1127         if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1128           continue;
1129 
1130         uint64_t addr = virtual_addr + entry.Offset;
1131 
1132         bool is_statement = cur_info.isStatement();
1133         bool is_prologue = IsFunctionPrologue(*cii, addr);
1134         bool is_epilogue = IsFunctionEpilogue(*cii, addr);
1135 
1136         uint32_t lno = cur_info.getStartLine();
1137 
1138         LineTable::Entry new_entry(addr, lno, 0, file_index, is_statement, false,
1139                                  is_prologue, is_epilogue, false);
1140         // Terminal entry has lower precedence than new entry.
1141         auto iter = line_set.find(new_entry);
1142         if (iter != line_set.end() && iter->is_terminal_entry)
1143           line_set.erase(iter);
1144         line_set.insert(new_entry);
1145 
1146         if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1147           line_entry.SetRangeEnd(addr);
1148           cii->m_global_line_table.Append(line_entry);
1149         }
1150         line_entry.SetRangeBase(addr);
1151         line_entry.data = {file_index, lno};
1152       }
1153       LineInfo last_line(group.LineNumbers.back().Flags);
1154       line_set.emplace(virtual_addr + lfh->CodeSize, last_line.getEndLine(), 0,
1155                        file_index, false, false, false, false, true);
1156 
1157       if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1158         line_entry.SetRangeEnd(virtual_addr + lfh->CodeSize);
1159         cii->m_global_line_table.Append(line_entry);
1160       }
1161     }
1162   }
1163 
1164   cii->m_global_line_table.Sort();
1165 
1166   // Parse all S_INLINESITE in this CU.
1167   const CVSymbolArray &syms = cii->m_debug_stream.getSymbolArray();
1168   for (auto iter = syms.begin(); iter != syms.end();) {
1169     if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) {
1170       ++iter;
1171       continue;
1172     }
1173 
1174     uint32_t record_offset = iter.offset();
1175     CVSymbol func_record =
1176         cii->m_debug_stream.readSymbolAtOffset(record_offset);
1177     SegmentOffsetLength sol = GetSegmentOffsetAndLength(func_record);
1178     addr_t file_vm_addr =
1179         m_index->MakeVirtualAddress(sol.so.segment, sol.so.offset);
1180     if (file_vm_addr == LLDB_INVALID_ADDRESS)
1181       continue;
1182 
1183     AddressRange func_range(file_vm_addr, sol.length,
1184                             comp_unit.GetModule()->GetSectionList());
1185     Address func_base = func_range.GetBaseAddress();
1186     PdbCompilandSymId func_id{modi, record_offset};
1187 
1188     // Iterate all S_INLINESITEs in the function.
1189     auto parse_inline_sites = [&](SymbolKind kind, PdbCompilandSymId id) {
1190       if (kind != S_INLINESITE)
1191         return false;
1192 
1193       ParseInlineSite(id, func_base);
1194 
1195       for (const auto &line_entry :
1196            m_inline_sites[toOpaqueUid(id)]->line_entries) {
1197         // If line_entry is not terminal entry, remove previous line entry at
1198         // the same address and insert new one. Terminal entry inside an inline
1199         // site might not be terminal entry for its parent.
1200         if (!line_entry.is_terminal_entry)
1201           line_set.erase(line_entry);
1202         line_set.insert(line_entry);
1203       }
1204       // No longer useful after adding to line_set.
1205       m_inline_sites[toOpaqueUid(id)]->line_entries.clear();
1206       return true;
1207     };
1208     ParseSymbolArrayInScope(func_id, parse_inline_sites);
1209     // Jump to the end of the function record.
1210     iter = syms.at(getScopeEndOffset(func_record));
1211   }
1212 
1213   cii->m_global_line_table.Clear();
1214 
1215   // Add line entries in line_set to line_table.
1216   auto line_table = std::make_unique<LineTable>(&comp_unit);
1217   std::unique_ptr<LineSequence> sequence(
1218       line_table->CreateLineSequenceContainer());
1219   for (const auto &line_entry : line_set) {
1220     line_table->AppendLineEntryToSequence(
1221         sequence.get(), line_entry.file_addr, line_entry.line,
1222         line_entry.column, line_entry.file_idx,
1223         line_entry.is_start_of_statement, line_entry.is_start_of_basic_block,
1224         line_entry.is_prologue_end, line_entry.is_epilogue_begin,
1225         line_entry.is_terminal_entry);
1226   }
1227   line_table->InsertSequence(sequence.get());
1228 
1229   if (line_table->GetSize() == 0)
1230     return false;
1231 
1232   comp_unit.SetLineTable(line_table.release());
1233   return true;
1234 }
1235 
1236 bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) {
1237   // PDB doesn't contain information about macros
1238   return false;
1239 }
1240 
1241 llvm::Expected<uint32_t>
1242 SymbolFileNativePDB::GetFileIndex(const CompilandIndexItem &cii,
1243                                   uint32_t file_id) {
1244   const auto &checksums = cii.m_strings.checksums().getArray();
1245   const auto &strings = cii.m_strings.strings();
1246   // Indices in this structure are actually offsets of records in the
1247   // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1248   // into the global PDB string table.
1249   auto iter = checksums.at(file_id);
1250   if (iter == checksums.end())
1251     return llvm::make_error<RawError>(raw_error_code::no_entry);
1252 
1253   llvm::Expected<llvm::StringRef> efn = strings.getString(iter->FileNameOffset);
1254   if (!efn) {
1255     return efn.takeError();
1256   }
1257 
1258   // LLDB wants the index of the file in the list of support files.
1259   auto fn_iter = llvm::find(cii.m_file_list, *efn);
1260   if (fn_iter != cii.m_file_list.end())
1261     return std::distance(cii.m_file_list.begin(), fn_iter);
1262   return llvm::make_error<RawError>(raw_error_code::no_entry);
1263 }
1264 
1265 bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit,
1266                                             FileSpecList &support_files) {
1267   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1268   PdbSymUid cu_id(comp_unit.GetID());
1269   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1270   CompilandIndexItem *cci =
1271       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1272   lldbassert(cci);
1273 
1274   for (llvm::StringRef f : cci->m_file_list) {
1275     FileSpec::Style style =
1276         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1277     FileSpec spec(f, style);
1278     support_files.Append(spec);
1279   }
1280   return true;
1281 }
1282 
1283 bool SymbolFileNativePDB::ParseImportedModules(
1284     const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1285   // PDB does not yet support module debug info
1286   return false;
1287 }
1288 
1289 void SymbolFileNativePDB::ParseInlineSite(PdbCompilandSymId id,
1290                                           Address func_addr) {
1291   lldb::user_id_t opaque_uid = toOpaqueUid(id);
1292   if (m_inline_sites.find(opaque_uid) != m_inline_sites.end())
1293     return;
1294 
1295   addr_t func_base = func_addr.GetFileAddress();
1296   CompilandIndexItem *cii = m_index->compilands().GetCompiland(id.modi);
1297   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(id.offset);
1298   CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
1299 
1300   InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind()));
1301   cantFail(SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site));
1302   PdbCompilandSymId parent_id(id.modi, inline_site.Parent);
1303 
1304   std::shared_ptr<InlineSite> inline_site_sp =
1305       std::make_shared<InlineSite>(parent_id);
1306 
1307   // Get the inlined function declaration info.
1308   auto iter = cii->m_inline_map.find(inline_site.Inlinee);
1309   if (iter == cii->m_inline_map.end())
1310     return;
1311   InlineeSourceLine inlinee_line = iter->second;
1312 
1313   const FileSpecList &files = comp_unit->GetSupportFiles();
1314   FileSpec decl_file;
1315   llvm::Expected<uint32_t> file_index_or_err =
1316       GetFileIndex(*cii, inlinee_line.Header->FileID);
1317   if (!file_index_or_err)
1318     return;
1319   uint32_t file_offset = file_index_or_err.get();
1320   decl_file = files.GetFileSpecAtIndex(file_offset);
1321   uint32_t decl_line = inlinee_line.Header->SourceLineNum;
1322   std::unique_ptr<Declaration> decl_up =
1323       std::make_unique<Declaration>(decl_file, decl_line);
1324 
1325   // Parse range and line info.
1326   uint32_t code_offset = 0;
1327   int32_t line_offset = 0;
1328   llvm::Optional<uint32_t> code_offset_base;
1329   llvm::Optional<uint32_t> code_offset_end;
1330   llvm::Optional<int32_t> cur_line_offset;
1331   llvm::Optional<int32_t> next_line_offset;
1332   llvm::Optional<uint32_t> next_file_offset;
1333 
1334   bool is_terminal_entry = false;
1335   bool is_start_of_statement = true;
1336   // The first instruction is the prologue end.
1337   bool is_prologue_end = true;
1338 
1339   auto update_code_offset = [&](uint32_t code_delta) {
1340     if (!code_offset_base)
1341       code_offset_base = code_offset;
1342     else if (!code_offset_end)
1343       code_offset_end = *code_offset_base + code_delta;
1344   };
1345   auto update_line_offset = [&](int32_t line_delta) {
1346     line_offset += line_delta;
1347     if (!code_offset_base || !cur_line_offset)
1348       cur_line_offset = line_offset;
1349     else
1350       next_line_offset = line_offset;
1351     ;
1352   };
1353   auto update_file_offset = [&](uint32_t offset) {
1354     if (!code_offset_base)
1355       file_offset = offset;
1356     else
1357       next_file_offset = offset;
1358   };
1359 
1360   for (auto &annot : inline_site.annotations()) {
1361     switch (annot.OpCode) {
1362     case BinaryAnnotationsOpCode::CodeOffset:
1363     case BinaryAnnotationsOpCode::ChangeCodeOffset:
1364     case BinaryAnnotationsOpCode::ChangeCodeOffsetBase:
1365       code_offset += annot.U1;
1366       update_code_offset(annot.U1);
1367       break;
1368     case BinaryAnnotationsOpCode::ChangeLineOffset:
1369       update_line_offset(annot.S1);
1370       break;
1371     case BinaryAnnotationsOpCode::ChangeCodeLength:
1372       update_code_offset(annot.U1);
1373       code_offset += annot.U1;
1374       is_terminal_entry = true;
1375       break;
1376     case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
1377       code_offset += annot.U1;
1378       update_code_offset(annot.U1);
1379       update_line_offset(annot.S1);
1380       break;
1381     case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
1382       code_offset += annot.U2;
1383       update_code_offset(annot.U2);
1384       update_code_offset(annot.U1);
1385       code_offset += annot.U1;
1386       is_terminal_entry = true;
1387       break;
1388     case BinaryAnnotationsOpCode::ChangeFile:
1389       update_file_offset(annot.U1);
1390       break;
1391     default:
1392       break;
1393     }
1394 
1395     // Add range if current range is finished.
1396     if (code_offset_base && code_offset_end && cur_line_offset) {
1397       inline_site_sp->ranges.Append(RangeSourceLineVector::Entry(
1398           *code_offset_base, *code_offset_end - *code_offset_base,
1399           decl_line + *cur_line_offset));
1400       // Set base, end, file offset and line offset for next range.
1401       if (next_file_offset)
1402         file_offset = *next_file_offset;
1403       if (next_line_offset) {
1404         cur_line_offset = next_line_offset;
1405         next_line_offset = llvm::None;
1406       }
1407       code_offset_base = is_terminal_entry ? llvm::None : code_offset_end;
1408       code_offset_end = next_file_offset = llvm::None;
1409     }
1410     if (code_offset_base && cur_line_offset) {
1411       if (is_terminal_entry) {
1412         LineTable::Entry line_entry(
1413             func_base + *code_offset_base, decl_line + *cur_line_offset, 0,
1414             file_offset, false, false, false, false, true);
1415         inline_site_sp->line_entries.push_back(line_entry);
1416       } else {
1417         LineTable::Entry line_entry(func_base + *code_offset_base,
1418                                     decl_line + *cur_line_offset, 0,
1419                                     file_offset, is_start_of_statement, false,
1420                                     is_prologue_end, false, false);
1421         inline_site_sp->line_entries.push_back(line_entry);
1422         is_prologue_end = false;
1423         is_start_of_statement = false;
1424       }
1425     }
1426     if (is_terminal_entry)
1427       is_start_of_statement = true;
1428     is_terminal_entry = false;
1429   }
1430 
1431   inline_site_sp->ranges.Sort();
1432 
1433   // Get the inlined function callsite info.
1434   std::unique_ptr<Declaration> callsite_up;
1435   if (!inline_site_sp->ranges.IsEmpty()) {
1436     auto *entry = inline_site_sp->ranges.GetEntryAtIndex(0);
1437     addr_t base_offset = entry->GetRangeBase();
1438     if (cii->m_debug_stream.readSymbolAtOffset(parent_id.offset).kind() ==
1439         S_INLINESITE) {
1440       // Its parent is another inline site, lookup parent site's range vector
1441       // for callsite line.
1442       ParseInlineSite(parent_id, func_base);
1443       std::shared_ptr<InlineSite> parent_site =
1444           m_inline_sites[toOpaqueUid(parent_id)];
1445       FileSpec &parent_decl_file =
1446           parent_site->inline_function_info->GetDeclaration().GetFile();
1447       if (auto *parent_entry =
1448               parent_site->ranges.FindEntryThatContains(base_offset)) {
1449         callsite_up =
1450             std::make_unique<Declaration>(parent_decl_file, parent_entry->data);
1451       }
1452     } else {
1453       // Its parent is a function, lookup global line table for callsite.
1454       if (auto *entry = cii->m_global_line_table.FindEntryThatContains(
1455               func_base + base_offset)) {
1456         const FileSpec &callsite_file =
1457             files.GetFileSpecAtIndex(entry->data.first);
1458         callsite_up =
1459             std::make_unique<Declaration>(callsite_file, entry->data.second);
1460       }
1461     }
1462   }
1463 
1464   // Get the inlined function name.
1465   CVType inlinee_cvt = m_index->ipi().getType(inline_site.Inlinee);
1466   std::string inlinee_name;
1467   if (inlinee_cvt.kind() == LF_MFUNC_ID) {
1468     MemberFuncIdRecord mfr;
1469     cantFail(
1470         TypeDeserializer::deserializeAs<MemberFuncIdRecord>(inlinee_cvt, mfr));
1471     LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1472     inlinee_name.append(std::string(types.getTypeName(mfr.ClassType)));
1473     inlinee_name.append("::");
1474     inlinee_name.append(mfr.getName().str());
1475   } else if (inlinee_cvt.kind() == LF_FUNC_ID) {
1476     FuncIdRecord fir;
1477     cantFail(TypeDeserializer::deserializeAs<FuncIdRecord>(inlinee_cvt, fir));
1478     TypeIndex parent_idx = fir.getParentScope();
1479     if (!parent_idx.isNoneType()) {
1480       LazyRandomTypeCollection &ids = m_index->ipi().typeCollection();
1481       inlinee_name.append(std::string(ids.getTypeName(parent_idx)));
1482       inlinee_name.append("::");
1483     }
1484     inlinee_name.append(fir.getName().str());
1485   }
1486   inline_site_sp->inline_function_info = std::make_shared<InlineFunctionInfo>(
1487       inlinee_name.c_str(), llvm::StringRef(), decl_up.get(),
1488       callsite_up.get());
1489 
1490   m_inline_sites[opaque_uid] = inline_site_sp;
1491 }
1492 
1493 size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) {
1494   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1495   PdbCompilandSymId func_id = PdbSymUid(func.GetID()).asCompilandSym();
1496   // After we iterate through inline sites inside the function, we already get
1497   // all the info needed, removing from the map to save memory.
1498   std::set<uint64_t> remove_uids;
1499   auto parse_blocks = [&](SymbolKind kind, PdbCompilandSymId id) {
1500     if (kind == S_GPROC32 || kind == S_LPROC32 || kind == S_BLOCK32 ||
1501         kind == S_INLINESITE) {
1502       GetOrCreateBlock(id);
1503       if (kind == S_INLINESITE)
1504         remove_uids.insert(toOpaqueUid(id));
1505       return true;
1506     }
1507     return false;
1508   };
1509   size_t count = ParseSymbolArrayInScope(func_id, parse_blocks);
1510   for (uint64_t uid : remove_uids) {
1511     m_inline_sites.erase(uid);
1512   }
1513   return count;
1514 }
1515 
1516 size_t SymbolFileNativePDB::ParseSymbolArrayInScope(
1517     PdbCompilandSymId parent_id,
1518     llvm::function_ref<bool(SymbolKind, PdbCompilandSymId)> fn) {
1519   CompilandIndexItem *cii = m_index->compilands().GetCompiland(parent_id.modi);
1520   CVSymbolArray syms =
1521       cii->m_debug_stream.getSymbolArrayForScope(parent_id.offset);
1522 
1523   size_t count = 1;
1524   for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1525     PdbCompilandSymId child_id(parent_id.modi, iter.offset());
1526     if (fn(iter->kind(), child_id))
1527       ++count;
1528   }
1529 
1530   return count;
1531 }
1532 
1533 void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); }
1534 
1535 void SymbolFileNativePDB::FindGlobalVariables(
1536     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1537     uint32_t max_matches, VariableList &variables) {
1538   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1539   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1540 
1541   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1542       name.GetStringRef(), m_index->symrecords());
1543   for (const SymbolAndOffset &result : results) {
1544     switch (result.second.kind()) {
1545     case SymbolKind::S_GDATA32:
1546     case SymbolKind::S_LDATA32:
1547     case SymbolKind::S_GTHREAD32:
1548     case SymbolKind::S_LTHREAD32:
1549     case SymbolKind::S_CONSTANT: {
1550       PdbGlobalSymId global(result.first, false);
1551       if (VariableSP var = GetOrCreateGlobalVariable(global))
1552         variables.AddVariable(var);
1553       break;
1554     }
1555     default:
1556       continue;
1557     }
1558   }
1559 }
1560 
1561 void SymbolFileNativePDB::FindFunctions(
1562     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1563     FunctionNameType name_type_mask, bool include_inlines,
1564     SymbolContextList &sc_list) {
1565   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1566   // For now we only support lookup by method name or full name.
1567   if (!(name_type_mask & eFunctionNameTypeFull ||
1568         name_type_mask & eFunctionNameTypeMethod))
1569     return;
1570 
1571   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1572 
1573   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1574       name.GetStringRef(), m_index->symrecords());
1575   for (const SymbolAndOffset &match : matches) {
1576     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1577       continue;
1578     ProcRefSym proc(match.second.kind());
1579     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1580 
1581     if (!IsValidRecord(proc))
1582       continue;
1583 
1584     CompilandIndexItem &cci =
1585         m_index->compilands().GetOrCreateCompiland(proc.modi());
1586     SymbolContext sc;
1587 
1588     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1589     PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
1590     sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
1591 
1592     sc_list.Append(sc);
1593   }
1594 }
1595 
1596 void SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1597                                         bool include_inlines,
1598                                         SymbolContextList &sc_list) {}
1599 
1600 void SymbolFileNativePDB::FindTypes(
1601     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1602     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1603     TypeMap &types) {
1604   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1605   if (!name)
1606     return;
1607 
1608   searched_symbol_files.clear();
1609   searched_symbol_files.insert(this);
1610 
1611   // There is an assumption 'name' is not a regex
1612   FindTypesByName(name.GetStringRef(), max_matches, types);
1613 }
1614 
1615 void SymbolFileNativePDB::FindTypes(
1616     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1617     llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {}
1618 
1619 void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1620                                           uint32_t max_matches,
1621                                           TypeMap &types) {
1622 
1623   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1624   if (max_matches > 0 && max_matches < matches.size())
1625     matches.resize(max_matches);
1626 
1627   for (TypeIndex ti : matches) {
1628     TypeSP type = GetOrCreateType(ti);
1629     if (!type)
1630       continue;
1631 
1632     types.Insert(type);
1633   }
1634 }
1635 
1636 size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) {
1637   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1638   // Only do the full type scan the first time.
1639   if (m_done_full_type_scan)
1640     return 0;
1641 
1642   const size_t old_count = GetTypeList().GetSize();
1643   LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1644 
1645   // First process the entire TPI stream.
1646   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
1647     TypeSP type = GetOrCreateType(*ti);
1648     if (type)
1649       (void)type->GetFullCompilerType();
1650   }
1651 
1652   // Next look for S_UDT records in the globals stream.
1653   for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
1654     PdbGlobalSymId global{gid, false};
1655     CVSymbol sym = m_index->ReadSymbolRecord(global);
1656     if (sym.kind() != S_UDT)
1657       continue;
1658 
1659     UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1660     bool is_typedef = true;
1661     if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
1662       CVType cvt = m_index->tpi().getType(udt.Type);
1663       llvm::StringRef name = CVTagRecord::create(cvt).name();
1664       if (name == udt.Name)
1665         is_typedef = false;
1666     }
1667 
1668     if (is_typedef)
1669       GetOrCreateTypedef(global);
1670   }
1671 
1672   const size_t new_count = GetTypeList().GetSize();
1673 
1674   m_done_full_type_scan = true;
1675 
1676   return new_count - old_count;
1677 }
1678 
1679 size_t
1680 SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit,
1681                                                   VariableList &variables) {
1682   PdbSymUid sym_uid(comp_unit.GetID());
1683   lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland);
1684   return 0;
1685 }
1686 
1687 VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id,
1688                                                     PdbCompilandSymId var_id,
1689                                                     bool is_param) {
1690   ModuleSP module = GetObjectFile()->GetModule();
1691   Block &block = GetOrCreateBlock(scope_id);
1692   VariableInfo var_info =
1693       GetVariableLocationInfo(*m_index, var_id, block, module);
1694   if (!var_info.location || !var_info.ranges)
1695     return nullptr;
1696 
1697   CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
1698   CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
1699   TypeSP type_sp = GetOrCreateType(var_info.type);
1700   std::string name = var_info.name.str();
1701   Declaration decl;
1702   SymbolFileTypeSP sftype =
1703       std::make_shared<SymbolFileType>(*this, type_sp->GetID());
1704 
1705   is_param |= var_info.is_param;
1706   ValueType var_scope =
1707       is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal;
1708   bool external = false;
1709   bool artificial = false;
1710   bool location_is_constant_data = false;
1711   bool static_member = false;
1712   VariableSP var_sp = std::make_shared<Variable>(
1713       toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope,
1714       &block, *var_info.ranges, &decl, *var_info.location, external,
1715       artificial, location_is_constant_data, static_member);
1716 
1717   if (!is_param)
1718     m_ast->GetOrCreateVariableDecl(scope_id, var_id);
1719 
1720   m_local_variables[toOpaqueUid(var_id)] = var_sp;
1721   return var_sp;
1722 }
1723 
1724 VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable(
1725     PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) {
1726   auto iter = m_local_variables.find(toOpaqueUid(var_id));
1727   if (iter != m_local_variables.end())
1728     return iter->second;
1729 
1730   return CreateLocalVariable(scope_id, var_id, is_param);
1731 }
1732 
1733 TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) {
1734   CVSymbol sym = m_index->ReadSymbolRecord(id);
1735   lldbassert(sym.kind() == SymbolKind::S_UDT);
1736 
1737   UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1738 
1739   TypeSP target_type = GetOrCreateType(udt.Type);
1740 
1741   (void)m_ast->GetOrCreateTypedefDecl(id);
1742 
1743   Declaration decl;
1744   return std::make_shared<lldb_private::Type>(
1745       toOpaqueUid(id), this, ConstString(udt.Name),
1746       target_type->GetByteSize(nullptr), nullptr, target_type->GetID(),
1747       lldb_private::Type::eEncodingIsTypedefUID, decl,
1748       target_type->GetForwardCompilerType(),
1749       lldb_private::Type::ResolveState::Forward);
1750 }
1751 
1752 TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) {
1753   auto iter = m_types.find(toOpaqueUid(id));
1754   if (iter != m_types.end())
1755     return iter->second;
1756 
1757   return CreateTypedef(id);
1758 }
1759 
1760 size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) {
1761   Block &block = GetOrCreateBlock(block_id);
1762 
1763   size_t count = 0;
1764 
1765   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
1766   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
1767   uint32_t params_remaining = 0;
1768   switch (sym.kind()) {
1769   case S_GPROC32:
1770   case S_LPROC32: {
1771     ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
1772     cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc));
1773     CVType signature = m_index->tpi().getType(proc.FunctionType);
1774     ProcedureRecord sig;
1775     cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig));
1776     params_remaining = sig.getParameterCount();
1777     break;
1778   }
1779   case S_BLOCK32:
1780     break;
1781   case S_INLINESITE:
1782     break;
1783   default:
1784     lldbassert(false && "Symbol is not a block!");
1785     return 0;
1786   }
1787 
1788   VariableListSP variables = block.GetBlockVariableList(false);
1789   if (!variables) {
1790     variables = std::make_shared<VariableList>();
1791     block.SetVariableList(variables);
1792   }
1793 
1794   CVSymbolArray syms = limitSymbolArrayToScope(
1795       cii->m_debug_stream.getSymbolArray(), block_id.offset);
1796 
1797   // Skip the first record since it's a PROC32 or BLOCK32, and there's
1798   // no point examining it since we know it's not a local variable.
1799   syms.drop_front();
1800   auto iter = syms.begin();
1801   auto end = syms.end();
1802 
1803   while (iter != end) {
1804     uint32_t record_offset = iter.offset();
1805     CVSymbol variable_cvs = *iter;
1806     PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
1807     ++iter;
1808 
1809     // If this is a block or inline site, recurse into its children and then
1810     // skip it.
1811     if (variable_cvs.kind() == S_BLOCK32 ||
1812         variable_cvs.kind() == S_INLINESITE) {
1813       uint32_t block_end = getScopeEndOffset(variable_cvs);
1814       count += ParseVariablesForBlock(child_sym_id);
1815       iter = syms.at(block_end);
1816       continue;
1817     }
1818 
1819     bool is_param = params_remaining > 0;
1820     VariableSP variable;
1821     switch (variable_cvs.kind()) {
1822     case S_REGREL32:
1823     case S_REGISTER:
1824     case S_LOCAL:
1825       variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
1826       if (is_param)
1827         --params_remaining;
1828       if (variable)
1829         variables->AddVariableIfUnique(variable);
1830       break;
1831     default:
1832       break;
1833     }
1834   }
1835 
1836   // Pass false for set_children, since we call this recursively so that the
1837   // children will call this for themselves.
1838   block.SetDidParseVariables(true, false);
1839 
1840   return count;
1841 }
1842 
1843 size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) {
1844   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1845   lldbassert(sc.function || sc.comp_unit);
1846 
1847   VariableListSP variables;
1848   if (sc.block) {
1849     PdbSymUid block_id(sc.block->GetID());
1850 
1851     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1852     return count;
1853   }
1854 
1855   if (sc.function) {
1856     PdbSymUid block_id(sc.function->GetID());
1857 
1858     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1859     return count;
1860   }
1861 
1862   if (sc.comp_unit) {
1863     variables = sc.comp_unit->GetVariableList(false);
1864     if (!variables) {
1865       variables = std::make_shared<VariableList>();
1866       sc.comp_unit->SetVariableList(variables);
1867     }
1868     return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
1869   }
1870 
1871   llvm_unreachable("Unreachable!");
1872 }
1873 
1874 CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) {
1875   if (auto decl = m_ast->GetOrCreateDeclForUid(uid))
1876     return *decl;
1877   else
1878     return CompilerDecl();
1879 }
1880 
1881 CompilerDeclContext
1882 SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) {
1883   clang::DeclContext *context =
1884       m_ast->GetOrCreateDeclContextForUid(PdbSymUid(uid));
1885   if (!context)
1886     return {};
1887 
1888   return m_ast->ToCompilerDeclContext(*context);
1889 }
1890 
1891 CompilerDeclContext
1892 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1893   clang::DeclContext *context = m_ast->GetParentDeclContext(PdbSymUid(uid));
1894   return m_ast->ToCompilerDeclContext(*context);
1895 }
1896 
1897 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1898   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1899   auto iter = m_types.find(type_uid);
1900   // lldb should not be passing us non-sensical type uids.  the only way it
1901   // could have a type uid in the first place is if we handed it out, in which
1902   // case we should know about the type.  However, that doesn't mean we've
1903   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1904   // type doesn't exist, let's instantiate it now.
1905   if (iter != m_types.end())
1906     return &*iter->second;
1907 
1908   PdbSymUid uid(type_uid);
1909   lldbassert(uid.kind() == PdbSymUidKind::Type);
1910   PdbTypeSymId type_id = uid.asTypeSym();
1911   if (type_id.index.isNoneType())
1912     return nullptr;
1913 
1914   TypeSP type_sp = CreateAndCacheType(type_id);
1915   return &*type_sp;
1916 }
1917 
1918 llvm::Optional<SymbolFile::ArrayInfo>
1919 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1920     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1921   return llvm::None;
1922 }
1923 
1924 
1925 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1926   clang::QualType qt =
1927       clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType());
1928 
1929   return m_ast->CompleteType(qt);
1930 }
1931 
1932 void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1933                                    TypeClass type_mask,
1934                                    lldb_private::TypeList &type_list) {}
1935 
1936 CompilerDeclContext
1937 SymbolFileNativePDB::FindNamespace(ConstString name,
1938                                    const CompilerDeclContext &parent_decl_ctx) {
1939   return {};
1940 }
1941 
1942 llvm::Expected<TypeSystem &>
1943 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1944   auto type_system_or_err =
1945       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1946   if (type_system_or_err) {
1947     type_system_or_err->SetSymbolFile(this);
1948   }
1949   return type_system_or_err;
1950 }
1951 
1952 uint64_t SymbolFileNativePDB::GetDebugInfoSize() {
1953   // PDB files are a separate file that contains all debug info.
1954   return m_index->pdb().getFileSize();
1955 }
1956