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