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         LineTable::Entry new_entry(addr, lno, 0, file_index, is_statement, false,
1123                                  is_prologue, is_epilogue, false);
1124         // Terminal entry has lower precedence than new entry.
1125         auto iter = line_set.find(new_entry);
1126         if (iter != line_set.end() && iter->is_terminal_entry)
1127           line_set.erase(iter);
1128         line_set.insert(new_entry);
1129 
1130         if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1131           line_entry.SetRangeEnd(addr);
1132           cii->m_global_line_table.Append(line_entry);
1133         }
1134         line_entry.SetRangeBase(addr);
1135         line_entry.data = {file_index, lno};
1136       }
1137       LineInfo last_line(group.LineNumbers.back().Flags);
1138       line_set.emplace(virtual_addr + lfh->CodeSize, last_line.getEndLine(), 0,
1139                        file_index, false, false, false, false, true);
1140 
1141       if (line_entry.GetRangeBase() != LLDB_INVALID_ADDRESS) {
1142         line_entry.SetRangeEnd(virtual_addr + lfh->CodeSize);
1143         cii->m_global_line_table.Append(line_entry);
1144       }
1145     }
1146   }
1147 
1148   cii->m_global_line_table.Sort();
1149 
1150   // Parse all S_INLINESITE in this CU.
1151   const CVSymbolArray &syms = cii->m_debug_stream.getSymbolArray();
1152   for (auto iter = syms.begin(); iter != syms.end();) {
1153     if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32) {
1154       ++iter;
1155       continue;
1156     }
1157 
1158     uint32_t record_offset = iter.offset();
1159     CVSymbol func_record =
1160         cii->m_debug_stream.readSymbolAtOffset(record_offset);
1161     SegmentOffsetLength sol = GetSegmentOffsetAndLength(func_record);
1162     addr_t file_vm_addr = m_index->MakeVirtualAddress(sol.so);
1163     AddressRange func_range(file_vm_addr, sol.length,
1164                             comp_unit.GetModule()->GetSectionList());
1165     Address func_base = func_range.GetBaseAddress();
1166     PdbCompilandSymId func_id{modi, record_offset};
1167 
1168     // Iterate all S_INLINESITEs in the function.
1169     auto parse_inline_sites = [&](SymbolKind kind, PdbCompilandSymId id) {
1170       if (kind != S_INLINESITE)
1171         return false;
1172 
1173       ParseInlineSite(id, func_base);
1174 
1175       for (const auto &line_entry :
1176            m_inline_sites[toOpaqueUid(id)]->line_entries) {
1177         // If line_entry is not terminal entry, remove previous line entry at
1178         // the same address and insert new one. Terminal entry inside an inline
1179         // site might not be terminal entry for its parent.
1180         if (!line_entry.is_terminal_entry)
1181           line_set.erase(line_entry);
1182         line_set.insert(line_entry);
1183       }
1184       // No longer useful after adding to line_set.
1185       m_inline_sites[toOpaqueUid(id)]->line_entries.clear();
1186       return true;
1187     };
1188     ParseSymbolArrayInScope(func_id, parse_inline_sites);
1189     // Jump to the end of the function record.
1190     iter = syms.at(getScopeEndOffset(func_record));
1191   }
1192 
1193   cii->m_global_line_table.Clear();
1194 
1195   // Add line entries in line_set to line_table.
1196   auto line_table = std::make_unique<LineTable>(&comp_unit);
1197   std::unique_ptr<LineSequence> sequence(
1198       line_table->CreateLineSequenceContainer());
1199   for (const auto &line_entry : line_set) {
1200     line_table->AppendLineEntryToSequence(
1201         sequence.get(), line_entry.file_addr, line_entry.line,
1202         line_entry.column, line_entry.file_idx,
1203         line_entry.is_start_of_statement, line_entry.is_start_of_basic_block,
1204         line_entry.is_prologue_end, line_entry.is_epilogue_begin,
1205         line_entry.is_terminal_entry);
1206   }
1207   line_table->InsertSequence(sequence.get());
1208 
1209   if (line_table->GetSize() == 0)
1210     return false;
1211 
1212   comp_unit.SetLineTable(line_table.release());
1213   return true;
1214 }
1215 
1216 bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) {
1217   // PDB doesn't contain information about macros
1218   return false;
1219 }
1220 
1221 llvm::Expected<uint32_t>
1222 SymbolFileNativePDB::GetFileIndex(const CompilandIndexItem &cii,
1223                                   uint32_t file_id) {
1224   auto index_iter = m_file_indexes.find(file_id);
1225   if (index_iter != m_file_indexes.end())
1226     return index_iter->getSecond();
1227   const auto &checksums = cii.m_strings.checksums().getArray();
1228   const auto &strings = cii.m_strings.strings();
1229   // Indices in this structure are actually offsets of records in the
1230   // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1231   // into the global PDB string table.
1232   auto iter = checksums.at(file_id);
1233   if (iter == checksums.end())
1234     return llvm::make_error<RawError>(raw_error_code::no_entry);
1235 
1236   llvm::Expected<llvm::StringRef> efn = strings.getString(iter->FileNameOffset);
1237   if (!efn) {
1238     return efn.takeError();
1239   }
1240 
1241   // LLDB wants the index of the file in the list of support files.
1242   auto fn_iter = llvm::find(cii.m_file_list, *efn);
1243   lldbassert(fn_iter != cii.m_file_list.end());
1244   m_file_indexes[file_id] = std::distance(cii.m_file_list.begin(), fn_iter);
1245   return m_file_indexes[file_id];
1246 }
1247 
1248 bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit,
1249                                             FileSpecList &support_files) {
1250   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1251   PdbSymUid cu_id(comp_unit.GetID());
1252   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1253   CompilandIndexItem *cci =
1254       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1255   lldbassert(cci);
1256 
1257   for (llvm::StringRef f : cci->m_file_list) {
1258     FileSpec::Style style =
1259         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1260     FileSpec spec(f, style);
1261     support_files.Append(spec);
1262   }
1263   return true;
1264 }
1265 
1266 bool SymbolFileNativePDB::ParseImportedModules(
1267     const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1268   // PDB does not yet support module debug info
1269   return false;
1270 }
1271 
1272 void SymbolFileNativePDB::ParseInlineSite(PdbCompilandSymId id,
1273                                           Address func_addr) {
1274   lldb::user_id_t opaque_uid = toOpaqueUid(id);
1275   if (m_inline_sites.find(opaque_uid) != m_inline_sites.end())
1276     return;
1277 
1278   addr_t func_base = func_addr.GetFileAddress();
1279   CompilandIndexItem *cii = m_index->compilands().GetCompiland(id.modi);
1280   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(id.offset);
1281   CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
1282 
1283   InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind()));
1284   cantFail(SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site));
1285   PdbCompilandSymId parent_id(id.modi, inline_site.Parent);
1286 
1287   std::shared_ptr<InlineSite> inline_site_sp =
1288       std::make_shared<InlineSite>(parent_id);
1289 
1290   // Get the inlined function declaration info.
1291   auto iter = cii->m_inline_map.find(inline_site.Inlinee);
1292   if (iter == cii->m_inline_map.end())
1293     return;
1294   InlineeSourceLine inlinee_line = iter->second;
1295 
1296   const FileSpecList &files = comp_unit->GetSupportFiles();
1297   FileSpec decl_file;
1298   llvm::Expected<uint32_t> file_index_or_err =
1299       GetFileIndex(*cii, inlinee_line.Header->FileID);
1300   if (!file_index_or_err)
1301     return;
1302   uint32_t decl_file_idx = file_index_or_err.get();
1303   decl_file = files.GetFileSpecAtIndex(decl_file_idx);
1304   uint32_t decl_line = inlinee_line.Header->SourceLineNum;
1305   std::unique_ptr<Declaration> decl_up =
1306       std::make_unique<Declaration>(decl_file, decl_line);
1307 
1308   // Parse range and line info.
1309   uint32_t code_offset = 0;
1310   int32_t line_offset = 0;
1311   bool has_base = false;
1312   bool is_new_line_offset = false;
1313 
1314   bool is_start_of_statement = false;
1315   // The first instruction is the prologue end.
1316   bool is_prologue_end = true;
1317 
1318   auto change_code_offset = [&](uint32_t code_delta) {
1319     if (has_base) {
1320       inline_site_sp->ranges.Append(RangeSourceLineVector::Entry(
1321           code_offset, code_delta, decl_line + line_offset));
1322       is_prologue_end = false;
1323       is_start_of_statement = false;
1324     } else {
1325       is_start_of_statement = true;
1326     }
1327     has_base = true;
1328     code_offset += code_delta;
1329 
1330     if (is_new_line_offset) {
1331       LineTable::Entry line_entry(func_base + code_offset,
1332                                   decl_line + line_offset, 0, decl_file_idx,
1333                                   true, false, is_prologue_end, false, false);
1334       inline_site_sp->line_entries.push_back(line_entry);
1335       is_new_line_offset = false;
1336     }
1337   };
1338   auto change_code_length = [&](uint32_t length) {
1339     inline_site_sp->ranges.Append(RangeSourceLineVector::Entry(
1340         code_offset, length, decl_line + line_offset));
1341     has_base = false;
1342 
1343     LineTable::Entry end_line_entry(func_base + code_offset + length,
1344                                     decl_line + line_offset, 0, decl_file_idx,
1345                                     false, false, false, false, true);
1346     inline_site_sp->line_entries.push_back(end_line_entry);
1347   };
1348   auto change_line_offset = [&](int32_t line_delta) {
1349     line_offset += line_delta;
1350     if (has_base) {
1351       LineTable::Entry line_entry(
1352           func_base + code_offset, decl_line + line_offset, 0, decl_file_idx,
1353           is_start_of_statement, false, is_prologue_end, false, false);
1354       inline_site_sp->line_entries.push_back(line_entry);
1355     } else {
1356       // Add line entry in next call to change_code_offset.
1357       is_new_line_offset = true;
1358     }
1359   };
1360 
1361   for (auto &annot : inline_site.annotations()) {
1362     switch (annot.OpCode) {
1363     case BinaryAnnotationsOpCode::CodeOffset:
1364     case BinaryAnnotationsOpCode::ChangeCodeOffset:
1365     case BinaryAnnotationsOpCode::ChangeCodeOffsetBase:
1366       change_code_offset(annot.U1);
1367       break;
1368     case BinaryAnnotationsOpCode::ChangeLineOffset:
1369       change_line_offset(annot.S1);
1370       break;
1371     case BinaryAnnotationsOpCode::ChangeCodeLength:
1372       change_code_length(annot.U1);
1373       code_offset += annot.U1;
1374       break;
1375     case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
1376       change_code_offset(annot.U1);
1377       change_line_offset(annot.S1);
1378       break;
1379     case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
1380       change_code_offset(annot.U2);
1381       change_code_length(annot.U1);
1382       break;
1383     default:
1384       break;
1385     }
1386   }
1387 
1388   inline_site_sp->ranges.Sort();
1389   inline_site_sp->ranges.CombineConsecutiveEntriesWithEqualData();
1390 
1391   // Get the inlined function callsite info.
1392   std::unique_ptr<Declaration> callsite_up;
1393   if (!inline_site_sp->ranges.IsEmpty()) {
1394     auto *entry = inline_site_sp->ranges.GetEntryAtIndex(0);
1395     addr_t base_offset = entry->GetRangeBase();
1396     if (cii->m_debug_stream.readSymbolAtOffset(parent_id.offset).kind() ==
1397         S_INLINESITE) {
1398       // Its parent is another inline site, lookup parent site's range vector
1399       // for callsite line.
1400       ParseInlineSite(parent_id, func_base);
1401       std::shared_ptr<InlineSite> parent_site =
1402           m_inline_sites[toOpaqueUid(parent_id)];
1403       FileSpec &parent_decl_file =
1404           parent_site->inline_function_info->GetDeclaration().GetFile();
1405       if (auto *parent_entry =
1406               parent_site->ranges.FindEntryThatContains(base_offset)) {
1407         callsite_up =
1408             std::make_unique<Declaration>(parent_decl_file, parent_entry->data);
1409       }
1410     } else {
1411       // Its parent is a function, lookup global line table for callsite.
1412       if (auto *entry = cii->m_global_line_table.FindEntryThatContains(
1413               func_base + base_offset)) {
1414         const FileSpec &callsite_file =
1415             files.GetFileSpecAtIndex(entry->data.first);
1416         callsite_up =
1417             std::make_unique<Declaration>(callsite_file, entry->data.second);
1418       }
1419     }
1420   }
1421 
1422   // Get the inlined function name.
1423   CVType inlinee_cvt = m_index->ipi().getType(inline_site.Inlinee);
1424   std::string inlinee_name;
1425   if (inlinee_cvt.kind() == LF_MFUNC_ID) {
1426     MemberFuncIdRecord mfr;
1427     cantFail(
1428         TypeDeserializer::deserializeAs<MemberFuncIdRecord>(inlinee_cvt, mfr));
1429     LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1430     inlinee_name.append(std::string(types.getTypeName(mfr.ClassType)));
1431     inlinee_name.append("::");
1432     inlinee_name.append(mfr.getName().str());
1433   } else if (inlinee_cvt.kind() == LF_FUNC_ID) {
1434     FuncIdRecord fir;
1435     cantFail(TypeDeserializer::deserializeAs<FuncIdRecord>(inlinee_cvt, fir));
1436     TypeIndex parent_idx = fir.getParentScope();
1437     if (!parent_idx.isNoneType()) {
1438       LazyRandomTypeCollection &ids = m_index->ipi().typeCollection();
1439       inlinee_name.append(std::string(ids.getTypeName(parent_idx)));
1440       inlinee_name.append("::");
1441     }
1442     inlinee_name.append(fir.getName().str());
1443   }
1444   inline_site_sp->inline_function_info = std::make_shared<InlineFunctionInfo>(
1445       inlinee_name.c_str(), llvm::StringRef(), decl_up.get(),
1446       callsite_up.get());
1447 
1448   m_inline_sites[opaque_uid] = inline_site_sp;
1449 }
1450 
1451 size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) {
1452   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1453   PdbCompilandSymId func_id = PdbSymUid(func.GetID()).asCompilandSym();
1454   // After we iterate through inline sites inside the function, we already get
1455   // all the info needed, removing from the map to save memory.
1456   std::set<uint64_t> remove_uids;
1457   auto parse_blocks = [&](SymbolKind kind, PdbCompilandSymId id) {
1458     if (kind == S_GPROC32 || kind == S_LPROC32 || kind == S_BLOCK32 ||
1459         kind == S_INLINESITE) {
1460       GetOrCreateBlock(id);
1461       if (kind == S_INLINESITE)
1462         remove_uids.insert(toOpaqueUid(id));
1463       return true;
1464     }
1465     return false;
1466   };
1467   size_t count = ParseSymbolArrayInScope(func_id, parse_blocks);
1468   for (uint64_t uid : remove_uids) {
1469     m_inline_sites.erase(uid);
1470   }
1471   return count;
1472 }
1473 
1474 size_t SymbolFileNativePDB::ParseSymbolArrayInScope(
1475     PdbCompilandSymId parent_id,
1476     llvm::function_ref<bool(SymbolKind, PdbCompilandSymId)> fn) {
1477   CompilandIndexItem *cii = m_index->compilands().GetCompiland(parent_id.modi);
1478   CVSymbolArray syms =
1479       cii->m_debug_stream.getSymbolArrayForScope(parent_id.offset);
1480 
1481   size_t count = 1;
1482   for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
1483     PdbCompilandSymId child_id(parent_id.modi, iter.offset());
1484     if (fn(iter->kind(), child_id))
1485       ++count;
1486   }
1487 
1488   return count;
1489 }
1490 
1491 void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); }
1492 
1493 void SymbolFileNativePDB::FindGlobalVariables(
1494     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1495     uint32_t max_matches, VariableList &variables) {
1496   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1497   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1498 
1499   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1500       name.GetStringRef(), m_index->symrecords());
1501   for (const SymbolAndOffset &result : results) {
1502     VariableSP var;
1503     switch (result.second.kind()) {
1504     case SymbolKind::S_GDATA32:
1505     case SymbolKind::S_LDATA32:
1506     case SymbolKind::S_GTHREAD32:
1507     case SymbolKind::S_LTHREAD32:
1508     case SymbolKind::S_CONSTANT: {
1509       PdbGlobalSymId global(result.first, false);
1510       var = GetOrCreateGlobalVariable(global);
1511       variables.AddVariable(var);
1512       break;
1513     }
1514     default:
1515       continue;
1516     }
1517   }
1518 }
1519 
1520 void SymbolFileNativePDB::FindFunctions(
1521     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1522     FunctionNameType name_type_mask, bool include_inlines,
1523     SymbolContextList &sc_list) {
1524   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1525   // For now we only support lookup by method name or full name.
1526   if (!(name_type_mask & eFunctionNameTypeFull ||
1527         name_type_mask & eFunctionNameTypeMethod))
1528     return;
1529 
1530   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1531 
1532   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1533       name.GetStringRef(), m_index->symrecords());
1534   for (const SymbolAndOffset &match : matches) {
1535     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1536       continue;
1537     ProcRefSym proc(match.second.kind());
1538     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1539 
1540     if (!IsValidRecord(proc))
1541       continue;
1542 
1543     CompilandIndexItem &cci =
1544         m_index->compilands().GetOrCreateCompiland(proc.modi());
1545     SymbolContext sc;
1546 
1547     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1548     PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
1549     sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
1550 
1551     sc_list.Append(sc);
1552   }
1553 }
1554 
1555 void SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1556                                         bool include_inlines,
1557                                         SymbolContextList &sc_list) {}
1558 
1559 void SymbolFileNativePDB::FindTypes(
1560     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1561     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1562     TypeMap &types) {
1563   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1564   if (!name)
1565     return;
1566 
1567   searched_symbol_files.clear();
1568   searched_symbol_files.insert(this);
1569 
1570   // There is an assumption 'name' is not a regex
1571   FindTypesByName(name.GetStringRef(), max_matches, types);
1572 }
1573 
1574 void SymbolFileNativePDB::FindTypes(
1575     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1576     llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {}
1577 
1578 void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1579                                           uint32_t max_matches,
1580                                           TypeMap &types) {
1581 
1582   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1583   if (max_matches > 0 && max_matches < matches.size())
1584     matches.resize(max_matches);
1585 
1586   for (TypeIndex ti : matches) {
1587     TypeSP type = GetOrCreateType(ti);
1588     if (!type)
1589       continue;
1590 
1591     types.Insert(type);
1592   }
1593 }
1594 
1595 size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) {
1596   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1597   // Only do the full type scan the first time.
1598   if (m_done_full_type_scan)
1599     return 0;
1600 
1601   const size_t old_count = GetTypeList().GetSize();
1602   LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1603 
1604   // First process the entire TPI stream.
1605   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
1606     TypeSP type = GetOrCreateType(*ti);
1607     if (type)
1608       (void)type->GetFullCompilerType();
1609   }
1610 
1611   // Next look for S_UDT records in the globals stream.
1612   for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
1613     PdbGlobalSymId global{gid, false};
1614     CVSymbol sym = m_index->ReadSymbolRecord(global);
1615     if (sym.kind() != S_UDT)
1616       continue;
1617 
1618     UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1619     bool is_typedef = true;
1620     if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
1621       CVType cvt = m_index->tpi().getType(udt.Type);
1622       llvm::StringRef name = CVTagRecord::create(cvt).name();
1623       if (name == udt.Name)
1624         is_typedef = false;
1625     }
1626 
1627     if (is_typedef)
1628       GetOrCreateTypedef(global);
1629   }
1630 
1631   const size_t new_count = GetTypeList().GetSize();
1632 
1633   m_done_full_type_scan = true;
1634 
1635   return new_count - old_count;
1636 }
1637 
1638 size_t
1639 SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit,
1640                                                   VariableList &variables) {
1641   PdbSymUid sym_uid(comp_unit.GetID());
1642   lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland);
1643   return 0;
1644 }
1645 
1646 VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id,
1647                                                     PdbCompilandSymId var_id,
1648                                                     bool is_param) {
1649   ModuleSP module = GetObjectFile()->GetModule();
1650   Block &block = GetOrCreateBlock(scope_id);
1651   VariableInfo var_info =
1652       GetVariableLocationInfo(*m_index, var_id, block, module);
1653   if (!var_info.location || !var_info.ranges)
1654     return nullptr;
1655 
1656   CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
1657   CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
1658   TypeSP type_sp = GetOrCreateType(var_info.type);
1659   std::string name = var_info.name.str();
1660   Declaration decl;
1661   SymbolFileTypeSP sftype =
1662       std::make_shared<SymbolFileType>(*this, type_sp->GetID());
1663 
1664   ValueType var_scope =
1665       is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal;
1666   bool external = false;
1667   bool artificial = false;
1668   bool location_is_constant_data = false;
1669   bool static_member = false;
1670   VariableSP var_sp = std::make_shared<Variable>(
1671       toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope,
1672       comp_unit_sp.get(), *var_info.ranges, &decl, *var_info.location, external,
1673       artificial, location_is_constant_data, static_member);
1674 
1675   if (!is_param)
1676     m_ast->GetOrCreateVariableDecl(scope_id, var_id);
1677 
1678   m_local_variables[toOpaqueUid(var_id)] = var_sp;
1679   return var_sp;
1680 }
1681 
1682 VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable(
1683     PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) {
1684   auto iter = m_local_variables.find(toOpaqueUid(var_id));
1685   if (iter != m_local_variables.end())
1686     return iter->second;
1687 
1688   return CreateLocalVariable(scope_id, var_id, is_param);
1689 }
1690 
1691 TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) {
1692   CVSymbol sym = m_index->ReadSymbolRecord(id);
1693   lldbassert(sym.kind() == SymbolKind::S_UDT);
1694 
1695   UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1696 
1697   TypeSP target_type = GetOrCreateType(udt.Type);
1698 
1699   (void)m_ast->GetOrCreateTypedefDecl(id);
1700 
1701   Declaration decl;
1702   return std::make_shared<lldb_private::Type>(
1703       toOpaqueUid(id), this, ConstString(udt.Name),
1704       target_type->GetByteSize(nullptr), nullptr, target_type->GetID(),
1705       lldb_private::Type::eEncodingIsTypedefUID, decl,
1706       target_type->GetForwardCompilerType(),
1707       lldb_private::Type::ResolveState::Forward);
1708 }
1709 
1710 TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) {
1711   auto iter = m_types.find(toOpaqueUid(id));
1712   if (iter != m_types.end())
1713     return iter->second;
1714 
1715   return CreateTypedef(id);
1716 }
1717 
1718 size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) {
1719   Block &block = GetOrCreateBlock(block_id);
1720 
1721   size_t count = 0;
1722 
1723   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
1724   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
1725   uint32_t params_remaining = 0;
1726   switch (sym.kind()) {
1727   case S_GPROC32:
1728   case S_LPROC32: {
1729     ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
1730     cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc));
1731     CVType signature = m_index->tpi().getType(proc.FunctionType);
1732     ProcedureRecord sig;
1733     cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig));
1734     params_remaining = sig.getParameterCount();
1735     break;
1736   }
1737   case S_BLOCK32:
1738     break;
1739   case S_INLINESITE:
1740     // TODO: Handle inline site case.
1741     return 0;
1742   default:
1743     lldbassert(false && "Symbol is not a block!");
1744     return 0;
1745   }
1746 
1747   VariableListSP variables = block.GetBlockVariableList(false);
1748   if (!variables) {
1749     variables = std::make_shared<VariableList>();
1750     block.SetVariableList(variables);
1751   }
1752 
1753   CVSymbolArray syms = limitSymbolArrayToScope(
1754       cii->m_debug_stream.getSymbolArray(), block_id.offset);
1755 
1756   // Skip the first record since it's a PROC32 or BLOCK32, and there's
1757   // no point examining it since we know it's not a local variable.
1758   syms.drop_front();
1759   auto iter = syms.begin();
1760   auto end = syms.end();
1761 
1762   while (iter != end) {
1763     uint32_t record_offset = iter.offset();
1764     CVSymbol variable_cvs = *iter;
1765     PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
1766     ++iter;
1767 
1768     // If this is a block, recurse into its children and then skip it.
1769     if (variable_cvs.kind() == S_BLOCK32) {
1770       uint32_t block_end = getScopeEndOffset(variable_cvs);
1771       count += ParseVariablesForBlock(child_sym_id);
1772       iter = syms.at(block_end);
1773       continue;
1774     }
1775 
1776     bool is_param = params_remaining > 0;
1777     VariableSP variable;
1778     switch (variable_cvs.kind()) {
1779     case S_REGREL32:
1780     case S_REGISTER:
1781     case S_LOCAL:
1782       variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
1783       if (is_param)
1784         --params_remaining;
1785       if (variable)
1786         variables->AddVariableIfUnique(variable);
1787       break;
1788     default:
1789       break;
1790     }
1791   }
1792 
1793   // Pass false for set_children, since we call this recursively so that the
1794   // children will call this for themselves.
1795   block.SetDidParseVariables(true, false);
1796 
1797   return count;
1798 }
1799 
1800 size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) {
1801   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1802   lldbassert(sc.function || sc.comp_unit);
1803 
1804   VariableListSP variables;
1805   if (sc.block) {
1806     PdbSymUid block_id(sc.block->GetID());
1807 
1808     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1809     return count;
1810   }
1811 
1812   if (sc.function) {
1813     PdbSymUid block_id(sc.function->GetID());
1814 
1815     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1816     return count;
1817   }
1818 
1819   if (sc.comp_unit) {
1820     variables = sc.comp_unit->GetVariableList(false);
1821     if (!variables) {
1822       variables = std::make_shared<VariableList>();
1823       sc.comp_unit->SetVariableList(variables);
1824     }
1825     return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
1826   }
1827 
1828   llvm_unreachable("Unreachable!");
1829 }
1830 
1831 CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) {
1832   if (auto decl = m_ast->GetOrCreateDeclForUid(uid))
1833     return decl.getValue();
1834   else
1835     return CompilerDecl();
1836 }
1837 
1838 CompilerDeclContext
1839 SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) {
1840   clang::DeclContext *context =
1841       m_ast->GetOrCreateDeclContextForUid(PdbSymUid(uid));
1842   if (!context)
1843     return {};
1844 
1845   return m_ast->ToCompilerDeclContext(*context);
1846 }
1847 
1848 CompilerDeclContext
1849 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1850   clang::DeclContext *context = m_ast->GetParentDeclContext(PdbSymUid(uid));
1851   return m_ast->ToCompilerDeclContext(*context);
1852 }
1853 
1854 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1855   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1856   auto iter = m_types.find(type_uid);
1857   // lldb should not be passing us non-sensical type uids.  the only way it
1858   // could have a type uid in the first place is if we handed it out, in which
1859   // case we should know about the type.  However, that doesn't mean we've
1860   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1861   // type doesn't exist, let's instantiate it now.
1862   if (iter != m_types.end())
1863     return &*iter->second;
1864 
1865   PdbSymUid uid(type_uid);
1866   lldbassert(uid.kind() == PdbSymUidKind::Type);
1867   PdbTypeSymId type_id = uid.asTypeSym();
1868   if (type_id.index.isNoneType())
1869     return nullptr;
1870 
1871   TypeSP type_sp = CreateAndCacheType(type_id);
1872   return &*type_sp;
1873 }
1874 
1875 llvm::Optional<SymbolFile::ArrayInfo>
1876 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1877     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1878   return llvm::None;
1879 }
1880 
1881 
1882 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1883   clang::QualType qt =
1884       clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType());
1885 
1886   return m_ast->CompleteType(qt);
1887 }
1888 
1889 void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1890                                    TypeClass type_mask,
1891                                    lldb_private::TypeList &type_list) {}
1892 
1893 CompilerDeclContext
1894 SymbolFileNativePDB::FindNamespace(ConstString name,
1895                                    const CompilerDeclContext &parent_decl_ctx) {
1896   return {};
1897 }
1898 
1899 llvm::Expected<TypeSystem &>
1900 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1901   auto type_system_or_err =
1902       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1903   if (type_system_or_err) {
1904     type_system_or_err->SetSymbolFile(this);
1905   }
1906   return type_system_or_err;
1907 }
1908 
1909 uint64_t SymbolFileNativePDB::GetDebugInfoSize() {
1910   // PDB files are a separate file that contains all debug info.
1911   return m_index->pdb().getFileSize();
1912 }
1913 
1914