xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/SymbolFile/NativePDB/SymbolFileNativePDB.cpp (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
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/TypeSystem/Clang/TypeSystemClang.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/StreamBuffer.h"
23 #include "lldb/Core/StreamFile.h"
24 #include "lldb/Symbol/CompileUnit.h"
25 #include "lldb/Symbol/LineTable.h"
26 #include "lldb/Symbol/ObjectFile.h"
27 #include "lldb/Symbol/SymbolContext.h"
28 #include "lldb/Symbol/SymbolVendor.h"
29 #include "lldb/Symbol/Variable.h"
30 #include "lldb/Symbol/VariableList.h"
31 #include "lldb/Utility/Log.h"
32 
33 #include "llvm/DebugInfo/CodeView/CVRecord.h"
34 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
35 #include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
36 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
37 #include "llvm/DebugInfo/CodeView/RecordName.h"
38 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
39 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
40 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
41 #include "llvm/DebugInfo/PDB/Native/DbiStream.h"
42 #include "llvm/DebugInfo/PDB/Native/GlobalsStream.h"
43 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
44 #include "llvm/DebugInfo/PDB/Native/ModuleDebugStream.h"
45 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
46 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
47 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
48 #include "llvm/DebugInfo/PDB/PDBTypes.h"
49 #include "llvm/Demangle/MicrosoftDemangle.h"
50 #include "llvm/Object/COFF.h"
51 #include "llvm/Support/Allocator.h"
52 #include "llvm/Support/BinaryStreamReader.h"
53 #include "llvm/Support/Error.h"
54 #include "llvm/Support/ErrorOr.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 
57 #include "DWARFLocationExpression.h"
58 #include "PdbAstBuilder.h"
59 #include "PdbSymUid.h"
60 #include "PdbUtil.h"
61 #include "UdtRecordCompleter.h"
62 
63 using namespace lldb;
64 using namespace lldb_private;
65 using namespace npdb;
66 using namespace llvm::codeview;
67 using namespace llvm::pdb;
68 
69 char SymbolFileNativePDB::ID;
70 
71 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
72   switch (lang) {
73   case PDB_Lang::Cpp:
74     return lldb::LanguageType::eLanguageTypeC_plus_plus;
75   case PDB_Lang::C:
76     return lldb::LanguageType::eLanguageTypeC;
77   case PDB_Lang::Swift:
78     return lldb::LanguageType::eLanguageTypeSwift;
79   default:
80     return lldb::LanguageType::eLanguageTypeUnknown;
81   }
82 }
83 
84 static std::unique_ptr<PDBFile> loadPDBFile(std::string PdbPath,
85                                             llvm::BumpPtrAllocator &Allocator) {
86   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ErrorOrBuffer =
87       llvm::MemoryBuffer::getFile(PdbPath, /*FileSize=*/-1,
88                                   /*RequiresNullTerminator=*/false);
89   if (!ErrorOrBuffer)
90     return nullptr;
91   std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(*ErrorOrBuffer);
92 
93   llvm::StringRef Path = Buffer->getBufferIdentifier();
94   auto Stream = std::make_unique<llvm::MemoryBufferByteStream>(
95       std::move(Buffer), llvm::support::little);
96 
97   auto File = std::make_unique<PDBFile>(Path, std::move(Stream), Allocator);
98   if (auto EC = File->parseFileHeaders()) {
99     llvm::consumeError(std::move(EC));
100     return nullptr;
101   }
102   if (auto EC = File->parseStreamData()) {
103     llvm::consumeError(std::move(EC));
104     return nullptr;
105   }
106 
107   return File;
108 }
109 
110 static std::unique_ptr<PDBFile>
111 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
112   // Try to find a matching PDB for an EXE.
113   using namespace llvm::object;
114   auto expected_binary = createBinary(exe_path);
115 
116   // If the file isn't a PE/COFF executable, fail.
117   if (!expected_binary) {
118     llvm::consumeError(expected_binary.takeError());
119     return nullptr;
120   }
121   OwningBinary<Binary> binary = std::move(*expected_binary);
122 
123   // TODO: Avoid opening the PE/COFF binary twice by reading this information
124   // directly from the lldb_private::ObjectFile.
125   auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
126   if (!obj)
127     return nullptr;
128   const llvm::codeview::DebugInfo *pdb_info = nullptr;
129 
130   // If it doesn't have a debug directory, fail.
131   llvm::StringRef pdb_file;
132   if (llvm::Error e = obj->getDebugPDBInfo(pdb_info, pdb_file)) {
133     consumeError(std::move(e));
134     return nullptr;
135   }
136 
137   // if the file doesn't exist, is not a pdb, or doesn't have a matching guid,
138   // fail.
139   llvm::file_magic magic;
140   auto ec = llvm::identify_magic(pdb_file, magic);
141   if (ec || magic != llvm::file_magic::pdb)
142     return nullptr;
143   std::unique_ptr<PDBFile> pdb = loadPDBFile(std::string(pdb_file), allocator);
144   if (!pdb)
145     return nullptr;
146 
147   auto expected_info = pdb->getPDBInfoStream();
148   if (!expected_info) {
149     llvm::consumeError(expected_info.takeError());
150     return nullptr;
151   }
152   llvm::codeview::GUID guid;
153   memcpy(&guid, pdb_info->PDB70.Signature, 16);
154 
155   if (expected_info->getGuid() != guid)
156     return nullptr;
157   return pdb;
158 }
159 
160 static bool IsFunctionPrologue(const CompilandIndexItem &cci,
161                                lldb::addr_t addr) {
162   // FIXME: Implement this.
163   return false;
164 }
165 
166 static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
167                                lldb::addr_t addr) {
168   // FIXME: Implement this.
169   return false;
170 }
171 
172 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
173   switch (kind) {
174   case SimpleTypeKind::Boolean128:
175   case SimpleTypeKind::Boolean16:
176   case SimpleTypeKind::Boolean32:
177   case SimpleTypeKind::Boolean64:
178   case SimpleTypeKind::Boolean8:
179     return "bool";
180   case SimpleTypeKind::Byte:
181   case SimpleTypeKind::UnsignedCharacter:
182     return "unsigned char";
183   case SimpleTypeKind::NarrowCharacter:
184     return "char";
185   case SimpleTypeKind::SignedCharacter:
186   case SimpleTypeKind::SByte:
187     return "signed char";
188   case SimpleTypeKind::Character16:
189     return "char16_t";
190   case SimpleTypeKind::Character32:
191     return "char32_t";
192   case SimpleTypeKind::Complex80:
193   case SimpleTypeKind::Complex64:
194   case SimpleTypeKind::Complex32:
195     return "complex";
196   case SimpleTypeKind::Float128:
197   case SimpleTypeKind::Float80:
198     return "long double";
199   case SimpleTypeKind::Float64:
200     return "double";
201   case SimpleTypeKind::Float32:
202     return "float";
203   case SimpleTypeKind::Float16:
204     return "single";
205   case SimpleTypeKind::Int128:
206     return "__int128";
207   case SimpleTypeKind::Int64:
208   case SimpleTypeKind::Int64Quad:
209     return "int64_t";
210   case SimpleTypeKind::Int32:
211     return "int";
212   case SimpleTypeKind::Int16:
213     return "short";
214   case SimpleTypeKind::UInt128:
215     return "unsigned __int128";
216   case SimpleTypeKind::UInt64:
217   case SimpleTypeKind::UInt64Quad:
218     return "uint64_t";
219   case SimpleTypeKind::HResult:
220     return "HRESULT";
221   case SimpleTypeKind::UInt32:
222     return "unsigned";
223   case SimpleTypeKind::UInt16:
224   case SimpleTypeKind::UInt16Short:
225     return "unsigned short";
226   case SimpleTypeKind::Int32Long:
227     return "long";
228   case SimpleTypeKind::UInt32Long:
229     return "unsigned long";
230   case SimpleTypeKind::Void:
231     return "void";
232   case SimpleTypeKind::WideCharacter:
233     return "wchar_t";
234   default:
235     return "";
236   }
237 }
238 
239 static bool IsClassRecord(TypeLeafKind kind) {
240   switch (kind) {
241   case LF_STRUCTURE:
242   case LF_CLASS:
243   case LF_INTERFACE:
244     return true;
245   default:
246     return false;
247   }
248 }
249 
250 void SymbolFileNativePDB::Initialize() {
251   PluginManager::RegisterPlugin(GetPluginNameStatic(),
252                                 GetPluginDescriptionStatic(), CreateInstance,
253                                 DebuggerInitialize);
254 }
255 
256 void SymbolFileNativePDB::Terminate() {
257   PluginManager::UnregisterPlugin(CreateInstance);
258 }
259 
260 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
261 
262 ConstString SymbolFileNativePDB::GetPluginNameStatic() {
263   static ConstString g_name("native-pdb");
264   return g_name;
265 }
266 
267 const char *SymbolFileNativePDB::GetPluginDescriptionStatic() {
268   return "Microsoft PDB debug symbol cross-platform file reader.";
269 }
270 
271 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFileSP objfile_sp) {
272   return new SymbolFileNativePDB(std::move(objfile_sp));
273 }
274 
275 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFileSP objfile_sp)
276     : SymbolFile(std::move(objfile_sp)) {}
277 
278 SymbolFileNativePDB::~SymbolFileNativePDB() {}
279 
280 uint32_t SymbolFileNativePDB::CalculateAbilities() {
281   uint32_t abilities = 0;
282   if (!m_objfile_sp)
283     return 0;
284 
285   if (!m_index) {
286     // Lazily load and match the PDB file, but only do this once.
287     std::unique_ptr<PDBFile> file_up =
288         loadMatchingPDBFile(m_objfile_sp->GetFileSpec().GetPath(), m_allocator);
289 
290     if (!file_up) {
291       auto module_sp = m_objfile_sp->GetModule();
292       if (!module_sp)
293         return 0;
294       // See if any symbol file is specified through `--symfile` option.
295       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
296       if (!symfile)
297         return 0;
298       file_up = loadPDBFile(symfile.GetPath(), m_allocator);
299     }
300 
301     if (!file_up)
302       return 0;
303 
304     auto expected_index = PdbIndex::create(std::move(file_up));
305     if (!expected_index) {
306       llvm::consumeError(expected_index.takeError());
307       return 0;
308     }
309     m_index = std::move(*expected_index);
310   }
311   if (!m_index)
312     return 0;
313 
314   // We don't especially have to be precise here.  We only distinguish between
315   // stripped and not stripped.
316   abilities = kAllAbilities;
317 
318   if (m_index->dbi().isStripped())
319     abilities &= ~(Blocks | LocalVariables);
320   return abilities;
321 }
322 
323 void SymbolFileNativePDB::InitializeObject() {
324   m_obj_load_address = m_objfile_sp->GetBaseAddress().GetFileAddress();
325   m_index->SetLoadAddress(m_obj_load_address);
326   m_index->ParseSectionContribs();
327 
328   auto ts_or_err = m_objfile_sp->GetModule()->GetTypeSystemForLanguage(
329       lldb::eLanguageTypeC_plus_plus);
330   if (auto err = ts_or_err.takeError()) {
331     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
332                    std::move(err), "Failed to initialize");
333   } else {
334     ts_or_err->SetSymbolFile(this);
335     auto *clang = llvm::cast_or_null<TypeSystemClang>(&ts_or_err.get());
336     lldbassert(clang);
337     m_ast = std::make_unique<PdbAstBuilder>(*m_objfile_sp, *m_index, *clang);
338   }
339 }
340 
341 uint32_t SymbolFileNativePDB::CalculateNumCompileUnits() {
342   const DbiModuleList &modules = m_index->dbi().modules();
343   uint32_t count = modules.getModuleCount();
344   if (count == 0)
345     return count;
346 
347   // The linker can inject an additional "dummy" compilation unit into the
348   // PDB. Ignore this special compile unit for our purposes, if it is there.
349   // It is always the last one.
350   DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
351   if (last.getModuleName() == "* Linker *")
352     --count;
353   return count;
354 }
355 
356 Block &SymbolFileNativePDB::CreateBlock(PdbCompilandSymId block_id) {
357   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
358   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
359 
360   if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) {
361     // This is a function.  It must be global.  Creating the Function entry for
362     // it automatically creates a block for it.
363     CompUnitSP comp_unit = GetOrCreateCompileUnit(*cii);
364     return GetOrCreateFunction(block_id, *comp_unit)->GetBlock(false);
365   }
366 
367   lldbassert(sym.kind() == S_BLOCK32);
368 
369   // This is a block.  Its parent is either a function or another block.  In
370   // either case, its parent can be viewed as a block (e.g. a function contains
371   // 1 big block.  So just get the parent block and add this block to it.
372   BlockSym block(static_cast<SymbolRecordKind>(sym.kind()));
373   cantFail(SymbolDeserializer::deserializeAs<BlockSym>(sym, block));
374   lldbassert(block.Parent != 0);
375   PdbCompilandSymId parent_id(block_id.modi, block.Parent);
376   Block &parent_block = GetOrCreateBlock(parent_id);
377   lldb::user_id_t opaque_block_uid = toOpaqueUid(block_id);
378   BlockSP child_block = std::make_shared<Block>(opaque_block_uid);
379   parent_block.AddChild(child_block);
380 
381   m_ast->GetOrCreateBlockDecl(block_id);
382 
383   m_blocks.insert({opaque_block_uid, child_block});
384   return *child_block;
385 }
386 
387 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbCompilandSymId func_id,
388                                                      CompileUnit &comp_unit) {
389   const CompilandIndexItem *cci =
390       m_index->compilands().GetCompiland(func_id.modi);
391   lldbassert(cci);
392   CVSymbol sym_record = cci->m_debug_stream.readSymbolAtOffset(func_id.offset);
393 
394   lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
395   SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
396 
397   auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
398   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
399     return nullptr;
400 
401   AddressRange func_range(file_vm_addr, sol.length,
402                           comp_unit.GetModule()->GetSectionList());
403   if (!func_range.GetBaseAddress().IsValid())
404     return nullptr;
405 
406   ProcSym proc(static_cast<SymbolRecordKind>(sym_record.kind()));
407   cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym_record, proc));
408   if (proc.FunctionType == TypeIndex::None())
409     return nullptr;
410   TypeSP func_type = GetOrCreateType(proc.FunctionType);
411   if (!func_type)
412     return nullptr;
413 
414   PdbTypeSymId sig_id(proc.FunctionType, false);
415   Mangled mangled(proc.Name);
416   FunctionSP func_sp = std::make_shared<Function>(
417       &comp_unit, toOpaqueUid(func_id), toOpaqueUid(sig_id), mangled,
418       func_type.get(), func_range);
419 
420   comp_unit.AddFunction(func_sp);
421 
422   m_ast->GetOrCreateFunctionDecl(func_id);
423 
424   return func_sp;
425 }
426 
427 CompUnitSP
428 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
429   lldb::LanguageType lang =
430       cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
431                          : lldb::eLanguageTypeUnknown;
432 
433   LazyBool optimized = eLazyBoolNo;
434   if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
435     optimized = eLazyBoolYes;
436 
437   llvm::SmallString<64> source_file_name =
438       m_index->compilands().GetMainSourceFile(cci);
439   FileSpec fs(source_file_name);
440 
441   CompUnitSP cu_sp =
442       std::make_shared<CompileUnit>(m_objfile_sp->GetModule(), nullptr, fs,
443                                     toOpaqueUid(cci.m_id), lang, optimized);
444 
445   SetCompileUnitAtIndex(cci.m_id.modi, cu_sp);
446   return cu_sp;
447 }
448 
449 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbTypeSymId type_id,
450                                                      const ModifierRecord &mr,
451                                                      CompilerType ct) {
452   TpiStream &stream = m_index->tpi();
453 
454   std::string name;
455   if (mr.ModifiedType.isSimple())
456     name = std::string(GetSimpleTypeName(mr.ModifiedType.getSimpleKind()));
457   else
458     name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
459   Declaration decl;
460   lldb::TypeSP modified_type = GetOrCreateType(mr.ModifiedType);
461 
462   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(name),
463                                 modified_type->GetByteSize(), nullptr,
464                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
465                                 ct, Type::ResolveState::Full);
466 }
467 
468 lldb::TypeSP
469 SymbolFileNativePDB::CreatePointerType(PdbTypeSymId type_id,
470                                        const llvm::codeview::PointerRecord &pr,
471                                        CompilerType ct) {
472   TypeSP pointee = GetOrCreateType(pr.ReferentType);
473   if (!pointee)
474     return nullptr;
475 
476   if (pr.isPointerToMember()) {
477     MemberPointerInfo mpi = pr.getMemberInfo();
478     GetOrCreateType(mpi.ContainingType);
479   }
480 
481   Declaration decl;
482   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(),
483                                 pr.getSize(), nullptr, LLDB_INVALID_UID,
484                                 Type::eEncodingIsUID, decl, ct,
485                                 Type::ResolveState::Full);
486 }
487 
488 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti,
489                                                    CompilerType ct) {
490   uint64_t uid = toOpaqueUid(PdbTypeSymId(ti, false));
491   if (ti == TypeIndex::NullptrT()) {
492     Declaration decl;
493     return std::make_shared<Type>(
494         uid, this, ConstString("std::nullptr_t"), 0, nullptr, LLDB_INVALID_UID,
495         Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
496   }
497 
498   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
499     TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
500     uint32_t pointer_size = 0;
501     switch (ti.getSimpleMode()) {
502     case SimpleTypeMode::FarPointer32:
503     case SimpleTypeMode::NearPointer32:
504       pointer_size = 4;
505       break;
506     case SimpleTypeMode::NearPointer64:
507       pointer_size = 8;
508       break;
509     default:
510       // 128-bit and 16-bit pointers unsupported.
511       return nullptr;
512     }
513     Declaration decl;
514     return std::make_shared<Type>(
515         uid, this, ConstString(), pointer_size, nullptr, LLDB_INVALID_UID,
516         Type::eEncodingIsUID, decl, ct, Type::ResolveState::Full);
517   }
518 
519   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
520     return nullptr;
521 
522   size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
523   llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
524 
525   Declaration decl;
526   return std::make_shared<Type>(uid, this, ConstString(type_name), size,
527                                 nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID,
528                                 decl, ct, Type::ResolveState::Full);
529 }
530 
531 static std::string GetUnqualifiedTypeName(const TagRecord &record) {
532   if (!record.hasUniqueName()) {
533     MSVCUndecoratedNameParser parser(record.Name);
534     llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
535 
536     return std::string(specs.back().GetBaseName());
537   }
538 
539   llvm::ms_demangle::Demangler demangler;
540   StringView sv(record.UniqueName.begin(), record.UniqueName.size());
541   llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
542   if (demangler.Error)
543     return std::string(record.Name);
544 
545   llvm::ms_demangle::IdentifierNode *idn =
546       ttn->QualifiedName->getUnqualifiedIdentifier();
547   return idn->toString();
548 }
549 
550 lldb::TypeSP
551 SymbolFileNativePDB::CreateClassStructUnion(PdbTypeSymId type_id,
552                                             const TagRecord &record,
553                                             size_t size, CompilerType ct) {
554 
555   std::string uname = GetUnqualifiedTypeName(record);
556 
557   // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
558   Declaration decl;
559   return std::make_shared<Type>(toOpaqueUid(type_id), this, ConstString(uname),
560                                 size, nullptr, LLDB_INVALID_UID,
561                                 Type::eEncodingIsUID, decl, ct,
562                                 Type::ResolveState::Forward);
563 }
564 
565 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
566                                                 const ClassRecord &cr,
567                                                 CompilerType ct) {
568   return CreateClassStructUnion(type_id, cr, cr.getSize(), ct);
569 }
570 
571 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
572                                                 const UnionRecord &ur,
573                                                 CompilerType ct) {
574   return CreateClassStructUnion(type_id, ur, ur.getSize(), ct);
575 }
576 
577 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbTypeSymId type_id,
578                                                 const EnumRecord &er,
579                                                 CompilerType ct) {
580   std::string uname = GetUnqualifiedTypeName(er);
581 
582   Declaration decl;
583   TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
584 
585   return std::make_shared<lldb_private::Type>(
586       toOpaqueUid(type_id), this, ConstString(uname),
587       underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID,
588       lldb_private::Type::eEncodingIsUID, decl, ct,
589       lldb_private::Type::ResolveState::Forward);
590 }
591 
592 TypeSP SymbolFileNativePDB::CreateArrayType(PdbTypeSymId type_id,
593                                             const ArrayRecord &ar,
594                                             CompilerType ct) {
595   TypeSP element_type = GetOrCreateType(ar.ElementType);
596 
597   Declaration decl;
598   TypeSP array_sp = std::make_shared<lldb_private::Type>(
599       toOpaqueUid(type_id), this, ConstString(), ar.Size, nullptr,
600       LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, ct,
601       lldb_private::Type::ResolveState::Full);
602   array_sp->SetEncodingType(element_type.get());
603   return array_sp;
604 }
605 
606 
607 TypeSP SymbolFileNativePDB::CreateFunctionType(PdbTypeSymId type_id,
608                                                const MemberFunctionRecord &mfr,
609                                                CompilerType ct) {
610   Declaration decl;
611   return std::make_shared<lldb_private::Type>(
612       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
613       lldb_private::Type::eEncodingIsUID, decl, ct,
614       lldb_private::Type::ResolveState::Full);
615 }
616 
617 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbTypeSymId type_id,
618                                                 const ProcedureRecord &pr,
619                                                 CompilerType ct) {
620   Declaration decl;
621   return std::make_shared<lldb_private::Type>(
622       toOpaqueUid(type_id), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
623       lldb_private::Type::eEncodingIsUID, decl, ct,
624       lldb_private::Type::ResolveState::Full);
625 }
626 
627 TypeSP SymbolFileNativePDB::CreateType(PdbTypeSymId type_id, CompilerType ct) {
628   if (type_id.index.isSimple())
629     return CreateSimpleType(type_id.index, ct);
630 
631   TpiStream &stream = type_id.is_ipi ? m_index->ipi() : m_index->tpi();
632   CVType cvt = stream.getType(type_id.index);
633 
634   if (cvt.kind() == LF_MODIFIER) {
635     ModifierRecord modifier;
636     llvm::cantFail(
637         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
638     return CreateModifierType(type_id, modifier, ct);
639   }
640 
641   if (cvt.kind() == LF_POINTER) {
642     PointerRecord pointer;
643     llvm::cantFail(
644         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
645     return CreatePointerType(type_id, pointer, ct);
646   }
647 
648   if (IsClassRecord(cvt.kind())) {
649     ClassRecord cr;
650     llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
651     return CreateTagType(type_id, cr, ct);
652   }
653 
654   if (cvt.kind() == LF_ENUM) {
655     EnumRecord er;
656     llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
657     return CreateTagType(type_id, er, ct);
658   }
659 
660   if (cvt.kind() == LF_UNION) {
661     UnionRecord ur;
662     llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
663     return CreateTagType(type_id, ur, ct);
664   }
665 
666   if (cvt.kind() == LF_ARRAY) {
667     ArrayRecord ar;
668     llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
669     return CreateArrayType(type_id, ar, ct);
670   }
671 
672   if (cvt.kind() == LF_PROCEDURE) {
673     ProcedureRecord pr;
674     llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
675     return CreateProcedureType(type_id, pr, ct);
676   }
677   if (cvt.kind() == LF_MFUNCTION) {
678     MemberFunctionRecord mfr;
679     llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
680     return CreateFunctionType(type_id, mfr, ct);
681   }
682 
683   return nullptr;
684 }
685 
686 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbTypeSymId type_id) {
687   // If they search for a UDT which is a forward ref, try and resolve the full
688   // decl and just map the forward ref uid to the full decl record.
689   llvm::Optional<PdbTypeSymId> full_decl_uid;
690   if (IsForwardRefUdt(type_id, m_index->tpi())) {
691     auto expected_full_ti =
692         m_index->tpi().findFullDeclForForwardRef(type_id.index);
693     if (!expected_full_ti)
694       llvm::consumeError(expected_full_ti.takeError());
695     else if (*expected_full_ti != type_id.index) {
696       full_decl_uid = PdbTypeSymId(*expected_full_ti, false);
697 
698       // It's possible that a lookup would occur for the full decl causing it
699       // to be cached, then a second lookup would occur for the forward decl.
700       // We don't want to create a second full decl, so make sure the full
701       // decl hasn't already been cached.
702       auto full_iter = m_types.find(toOpaqueUid(*full_decl_uid));
703       if (full_iter != m_types.end()) {
704         TypeSP result = full_iter->second;
705         // Map the forward decl to the TypeSP for the full decl so we can take
706         // the fast path next time.
707         m_types[toOpaqueUid(type_id)] = result;
708         return result;
709       }
710     }
711   }
712 
713   PdbTypeSymId best_decl_id = full_decl_uid ? *full_decl_uid : type_id;
714 
715   clang::QualType qt = m_ast->GetOrCreateType(best_decl_id);
716 
717   TypeSP result = CreateType(best_decl_id, m_ast->ToCompilerType(qt));
718   if (!result)
719     return nullptr;
720 
721   uint64_t best_uid = toOpaqueUid(best_decl_id);
722   m_types[best_uid] = result;
723   // If we had both a forward decl and a full decl, make both point to the new
724   // type.
725   if (full_decl_uid)
726     m_types[toOpaqueUid(type_id)] = result;
727 
728   return result;
729 }
730 
731 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbTypeSymId type_id) {
732   // We can't use try_emplace / overwrite here because the process of creating
733   // a type could create nested types, which could invalidate iterators.  So
734   // we have to do a 2-phase lookup / insert.
735   auto iter = m_types.find(toOpaqueUid(type_id));
736   if (iter != m_types.end())
737     return iter->second;
738 
739   TypeSP type = CreateAndCacheType(type_id);
740   if (type)
741     GetTypeList().Insert(type);
742   return type;
743 }
744 
745 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbGlobalSymId var_id) {
746   CVSymbol sym = m_index->symrecords().readRecord(var_id.offset);
747   if (sym.kind() == S_CONSTANT)
748     return CreateConstantSymbol(var_id, sym);
749 
750   lldb::ValueType scope = eValueTypeInvalid;
751   TypeIndex ti;
752   llvm::StringRef name;
753   lldb::addr_t addr = 0;
754   uint16_t section = 0;
755   uint32_t offset = 0;
756   bool is_external = false;
757   switch (sym.kind()) {
758   case S_GDATA32:
759     is_external = true;
760     LLVM_FALLTHROUGH;
761   case S_LDATA32: {
762     DataSym ds(sym.kind());
763     llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
764     ti = ds.Type;
765     scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
766                                       : eValueTypeVariableStatic;
767     name = ds.Name;
768     section = ds.Segment;
769     offset = ds.DataOffset;
770     addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
771     break;
772   }
773   case S_GTHREAD32:
774     is_external = true;
775     LLVM_FALLTHROUGH;
776   case S_LTHREAD32: {
777     ThreadLocalDataSym tlds(sym.kind());
778     llvm::cantFail(
779         SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
780     ti = tlds.Type;
781     name = tlds.Name;
782     section = tlds.Segment;
783     offset = tlds.DataOffset;
784     addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
785     scope = eValueTypeVariableThreadLocal;
786     break;
787   }
788   default:
789     llvm_unreachable("unreachable!");
790   }
791 
792   CompUnitSP comp_unit;
793   llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
794   if (modi) {
795     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(*modi);
796     comp_unit = GetOrCreateCompileUnit(cci);
797   }
798 
799   Declaration decl;
800   PdbTypeSymId tid(ti, false);
801   SymbolFileTypeSP type_sp =
802       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
803   Variable::RangeList ranges;
804 
805   m_ast->GetOrCreateVariableDecl(var_id);
806 
807   DWARFExpression location = MakeGlobalLocationExpression(
808       section, offset, GetObjectFile()->GetModule());
809 
810   std::string global_name("::");
811   global_name += name;
812   VariableSP var_sp = std::make_shared<Variable>(
813       toOpaqueUid(var_id), name.str().c_str(), global_name.c_str(), type_sp,
814       scope, comp_unit.get(), ranges, &decl, location, is_external, false,
815       false);
816   var_sp->SetLocationIsConstantValueData(false);
817 
818   return var_sp;
819 }
820 
821 lldb::VariableSP
822 SymbolFileNativePDB::CreateConstantSymbol(PdbGlobalSymId var_id,
823                                           const CVSymbol &cvs) {
824   TpiStream &tpi = m_index->tpi();
825   ConstantSym constant(cvs.kind());
826 
827   llvm::cantFail(SymbolDeserializer::deserializeAs<ConstantSym>(cvs, constant));
828   std::string global_name("::");
829   global_name += constant.Name;
830   PdbTypeSymId tid(constant.Type, false);
831   SymbolFileTypeSP type_sp =
832       std::make_shared<SymbolFileType>(*this, toOpaqueUid(tid));
833 
834   Declaration decl;
835   Variable::RangeList ranges;
836   ModuleSP module = GetObjectFile()->GetModule();
837   DWARFExpression location = MakeConstantLocationExpression(
838       constant.Type, tpi, constant.Value, module);
839 
840   VariableSP var_sp = std::make_shared<Variable>(
841       toOpaqueUid(var_id), constant.Name.str().c_str(), global_name.c_str(),
842       type_sp, eValueTypeVariableGlobal, module.get(), ranges, &decl, location,
843       false, false, false);
844   var_sp->SetLocationIsConstantValueData(true);
845   return var_sp;
846 }
847 
848 VariableSP
849 SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbGlobalSymId var_id) {
850   auto emplace_result = m_global_vars.try_emplace(toOpaqueUid(var_id), nullptr);
851   if (emplace_result.second)
852     emplace_result.first->second = CreateGlobalVariable(var_id);
853 
854   return emplace_result.first->second;
855 }
856 
857 lldb::TypeSP SymbolFileNativePDB::GetOrCreateType(TypeIndex ti) {
858   return GetOrCreateType(PdbTypeSymId(ti, false));
859 }
860 
861 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbCompilandSymId func_id,
862                                                     CompileUnit &comp_unit) {
863   auto emplace_result = m_functions.try_emplace(toOpaqueUid(func_id), nullptr);
864   if (emplace_result.second)
865     emplace_result.first->second = CreateFunction(func_id, comp_unit);
866 
867   return emplace_result.first->second;
868 }
869 
870 CompUnitSP
871 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
872 
873   auto emplace_result =
874       m_compilands.try_emplace(toOpaqueUid(cci.m_id), nullptr);
875   if (emplace_result.second)
876     emplace_result.first->second = CreateCompileUnit(cci);
877 
878   lldbassert(emplace_result.first->second);
879   return emplace_result.first->second;
880 }
881 
882 Block &SymbolFileNativePDB::GetOrCreateBlock(PdbCompilandSymId block_id) {
883   auto iter = m_blocks.find(toOpaqueUid(block_id));
884   if (iter != m_blocks.end())
885     return *iter->second;
886 
887   return CreateBlock(block_id);
888 }
889 
890 void SymbolFileNativePDB::ParseDeclsForContext(
891     lldb_private::CompilerDeclContext decl_ctx) {
892   clang::DeclContext *context = m_ast->FromCompilerDeclContext(decl_ctx);
893   if (!context)
894     return;
895   m_ast->ParseDeclsForContext(*context);
896 }
897 
898 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
899   if (index >= GetNumCompileUnits())
900     return CompUnitSP();
901   lldbassert(index < UINT16_MAX);
902   if (index >= UINT16_MAX)
903     return nullptr;
904 
905   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
906 
907   return GetOrCreateCompileUnit(item);
908 }
909 
910 lldb::LanguageType SymbolFileNativePDB::ParseLanguage(CompileUnit &comp_unit) {
911   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
912   PdbSymUid uid(comp_unit.GetID());
913   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
914 
915   CompilandIndexItem *item =
916       m_index->compilands().GetCompiland(uid.asCompiland().modi);
917   lldbassert(item);
918   if (!item->m_compile_opts)
919     return lldb::eLanguageTypeUnknown;
920 
921   return TranslateLanguage(item->m_compile_opts->getLanguage());
922 }
923 
924 void SymbolFileNativePDB::AddSymbols(Symtab &symtab) { return; }
925 
926 size_t SymbolFileNativePDB::ParseFunctions(CompileUnit &comp_unit) {
927   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
928   PdbSymUid uid{comp_unit.GetID()};
929   lldbassert(uid.kind() == PdbSymUidKind::Compiland);
930   uint16_t modi = uid.asCompiland().modi;
931   CompilandIndexItem &cii = m_index->compilands().GetOrCreateCompiland(modi);
932 
933   size_t count = comp_unit.GetNumFunctions();
934   const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
935   for (auto iter = syms.begin(); iter != syms.end(); ++iter) {
936     if (iter->kind() != S_LPROC32 && iter->kind() != S_GPROC32)
937       continue;
938 
939     PdbCompilandSymId sym_id{modi, iter.offset()};
940 
941     FunctionSP func = GetOrCreateFunction(sym_id, comp_unit);
942   }
943 
944   size_t new_count = comp_unit.GetNumFunctions();
945   lldbassert(new_count >= count);
946   return new_count - count;
947 }
948 
949 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
950   // If any of these flags are set, we need to resolve the compile unit.
951   uint32_t flags = eSymbolContextCompUnit;
952   flags |= eSymbolContextVariable;
953   flags |= eSymbolContextFunction;
954   flags |= eSymbolContextBlock;
955   flags |= eSymbolContextLineEntry;
956   return (resolve_scope & flags) != 0;
957 }
958 
959 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
960     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
961   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
962   uint32_t resolved_flags = 0;
963   lldb::addr_t file_addr = addr.GetFileAddress();
964 
965   if (NeedsResolvedCompileUnit(resolve_scope)) {
966     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
967     if (!modi)
968       return 0;
969     CompilandIndexItem *cci = m_index->compilands().GetCompiland(*modi);
970     if (!cci)
971       return 0;
972 
973     sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
974     resolved_flags |= eSymbolContextCompUnit;
975   }
976 
977   if (resolve_scope & eSymbolContextFunction ||
978       resolve_scope & eSymbolContextBlock) {
979     lldbassert(sc.comp_unit);
980     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
981     // Search the matches in reverse.  This way if there are multiple matches
982     // (for example we are 3 levels deep in a nested scope) it will find the
983     // innermost one first.
984     for (const auto &match : llvm::reverse(matches)) {
985       if (match.uid.kind() != PdbSymUidKind::CompilandSym)
986         continue;
987 
988       PdbCompilandSymId csid = match.uid.asCompilandSym();
989       CVSymbol cvs = m_index->ReadSymbolRecord(csid);
990       PDB_SymType type = CVSymToPDBSym(cvs.kind());
991       if (type != PDB_SymType::Function && type != PDB_SymType::Block)
992         continue;
993       if (type == PDB_SymType::Function) {
994         sc.function = GetOrCreateFunction(csid, *sc.comp_unit).get();
995         sc.block = sc.GetFunctionBlock();
996       }
997 
998       if (type == PDB_SymType::Block) {
999         sc.block = &GetOrCreateBlock(csid);
1000         sc.function = sc.block->CalculateSymbolContextFunction();
1001       }
1002     resolved_flags |= eSymbolContextFunction;
1003     resolved_flags |= eSymbolContextBlock;
1004     break;
1005     }
1006   }
1007 
1008   if (resolve_scope & eSymbolContextLineEntry) {
1009     lldbassert(sc.comp_unit);
1010     if (auto *line_table = sc.comp_unit->GetLineTable()) {
1011       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1012         resolved_flags |= eSymbolContextLineEntry;
1013     }
1014   }
1015 
1016   return resolved_flags;
1017 }
1018 
1019 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1020     const FileSpec &file_spec, uint32_t line, bool check_inlines,
1021     lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
1022   return 0;
1023 }
1024 
1025 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1026                                       const CompilandIndexItem &cci,
1027                                       lldb::addr_t base_addr,
1028                                       uint32_t file_number,
1029                                       const LineFragmentHeader &block,
1030                                       const LineNumberEntry &cur) {
1031   LineInfo cur_info(cur.Flags);
1032 
1033   if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1034     return;
1035 
1036   uint64_t addr = base_addr + cur.Offset;
1037 
1038   bool is_statement = cur_info.isStatement();
1039   bool is_prologue = IsFunctionPrologue(cci, addr);
1040   bool is_epilogue = IsFunctionEpilogue(cci, addr);
1041 
1042   uint32_t lno = cur_info.getStartLine();
1043 
1044   table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1045                                   is_statement, false, is_prologue, is_epilogue,
1046                                   false);
1047 }
1048 
1049 static void TerminateLineSequence(LineTable &table,
1050                                   const LineFragmentHeader &block,
1051                                   lldb::addr_t base_addr, uint32_t file_number,
1052                                   uint32_t last_line,
1053                                   std::unique_ptr<LineSequence> seq) {
1054   // The end is always a terminal entry, so insert it regardless.
1055   table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1056                                   last_line, 0, file_number, false, false,
1057                                   false, false, true);
1058   table.InsertSequence(seq.release());
1059 }
1060 
1061 bool SymbolFileNativePDB::ParseLineTable(CompileUnit &comp_unit) {
1062   // Unfortunately LLDB is set up to parse the entire compile unit line table
1063   // all at once, even if all it really needs is line info for a specific
1064   // function.  In the future it would be nice if it could set the sc.m_function
1065   // member, and we could only get the line info for the function in question.
1066   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1067   PdbSymUid cu_id(comp_unit.GetID());
1068   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1069   CompilandIndexItem *cci =
1070       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1071   lldbassert(cci);
1072   auto line_table = std::make_unique<LineTable>(&comp_unit);
1073 
1074   // This is basically a copy of the .debug$S subsections from all original COFF
1075   // object files merged together with address relocations applied.  We are
1076   // looking for all DEBUG_S_LINES subsections.
1077   for (const DebugSubsectionRecord &dssr :
1078        cci->m_debug_stream.getSubsectionsArray()) {
1079     if (dssr.kind() != DebugSubsectionKind::Lines)
1080       continue;
1081 
1082     DebugLinesSubsectionRef lines;
1083     llvm::BinaryStreamReader reader(dssr.getRecordData());
1084     if (auto EC = lines.initialize(reader)) {
1085       llvm::consumeError(std::move(EC));
1086       return false;
1087     }
1088 
1089     const LineFragmentHeader *lfh = lines.header();
1090     uint64_t virtual_addr =
1091         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1092 
1093     const auto &checksums = cci->m_strings.checksums().getArray();
1094     const auto &strings = cci->m_strings.strings();
1095     for (const LineColumnEntry &group : lines) {
1096       // Indices in this structure are actually offsets of records in the
1097       // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1098       // into the global PDB string table.
1099       auto iter = checksums.at(group.NameIndex);
1100       if (iter == checksums.end())
1101         continue;
1102 
1103       llvm::Expected<llvm::StringRef> efn =
1104           strings.getString(iter->FileNameOffset);
1105       if (!efn) {
1106         llvm::consumeError(efn.takeError());
1107         continue;
1108       }
1109 
1110       // LLDB wants the index of the file in the list of support files.
1111       auto fn_iter = llvm::find(cci->m_file_list, *efn);
1112       lldbassert(fn_iter != cci->m_file_list.end());
1113       uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1114 
1115       std::unique_ptr<LineSequence> sequence(
1116           line_table->CreateLineSequenceContainer());
1117       lldbassert(!group.LineNumbers.empty());
1118 
1119       for (const LineNumberEntry &entry : group.LineNumbers) {
1120         AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1121                                   file_index, *lfh, entry);
1122       }
1123       LineInfo last_line(group.LineNumbers.back().Flags);
1124       TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1125                             last_line.getEndLine(), std::move(sequence));
1126     }
1127   }
1128 
1129   if (line_table->GetSize() == 0)
1130     return false;
1131 
1132   comp_unit.SetLineTable(line_table.release());
1133   return true;
1134 }
1135 
1136 bool SymbolFileNativePDB::ParseDebugMacros(CompileUnit &comp_unit) {
1137   // PDB doesn't contain information about macros
1138   return false;
1139 }
1140 
1141 bool SymbolFileNativePDB::ParseSupportFiles(CompileUnit &comp_unit,
1142                                             FileSpecList &support_files) {
1143   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1144   PdbSymUid cu_id(comp_unit.GetID());
1145   lldbassert(cu_id.kind() == PdbSymUidKind::Compiland);
1146   CompilandIndexItem *cci =
1147       m_index->compilands().GetCompiland(cu_id.asCompiland().modi);
1148   lldbassert(cci);
1149 
1150   for (llvm::StringRef f : cci->m_file_list) {
1151     FileSpec::Style style =
1152         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1153     FileSpec spec(f, style);
1154     support_files.Append(spec);
1155   }
1156   return true;
1157 }
1158 
1159 bool SymbolFileNativePDB::ParseImportedModules(
1160     const SymbolContext &sc, std::vector<SourceModule> &imported_modules) {
1161   // PDB does not yet support module debug info
1162   return false;
1163 }
1164 
1165 size_t SymbolFileNativePDB::ParseBlocksRecursive(Function &func) {
1166   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1167   GetOrCreateBlock(PdbSymUid(func.GetID()).asCompilandSym());
1168   // FIXME: Parse child blocks
1169   return 1;
1170 }
1171 
1172 void SymbolFileNativePDB::DumpClangAST(Stream &s) { m_ast->Dump(s); }
1173 
1174 void SymbolFileNativePDB::FindGlobalVariables(
1175     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1176     uint32_t max_matches, VariableList &variables) {
1177   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1178   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1179 
1180   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1181       name.GetStringRef(), m_index->symrecords());
1182   for (const SymbolAndOffset &result : results) {
1183     VariableSP var;
1184     switch (result.second.kind()) {
1185     case SymbolKind::S_GDATA32:
1186     case SymbolKind::S_LDATA32:
1187     case SymbolKind::S_GTHREAD32:
1188     case SymbolKind::S_LTHREAD32:
1189     case SymbolKind::S_CONSTANT: {
1190       PdbGlobalSymId global(result.first, false);
1191       var = GetOrCreateGlobalVariable(global);
1192       variables.AddVariable(var);
1193       break;
1194     }
1195     default:
1196       continue;
1197     }
1198   }
1199 }
1200 
1201 void SymbolFileNativePDB::FindFunctions(
1202     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1203     FunctionNameType name_type_mask, bool include_inlines,
1204     SymbolContextList &sc_list) {
1205   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1206   // For now we only support lookup by method name.
1207   if (!(name_type_mask & eFunctionNameTypeMethod))
1208     return;
1209 
1210   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1211 
1212   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1213       name.GetStringRef(), m_index->symrecords());
1214   for (const SymbolAndOffset &match : matches) {
1215     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1216       continue;
1217     ProcRefSym proc(match.second.kind());
1218     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1219 
1220     if (!IsValidRecord(proc))
1221       continue;
1222 
1223     CompilandIndexItem &cci =
1224         m_index->compilands().GetOrCreateCompiland(proc.modi());
1225     SymbolContext sc;
1226 
1227     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1228     PdbCompilandSymId func_id(proc.modi(), proc.SymOffset);
1229     sc.function = GetOrCreateFunction(func_id, *sc.comp_unit).get();
1230 
1231     sc_list.Append(sc);
1232   }
1233 }
1234 
1235 void SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1236                                         bool include_inlines,
1237                                         SymbolContextList &sc_list) {}
1238 
1239 void SymbolFileNativePDB::FindTypes(
1240     ConstString name, const CompilerDeclContext &parent_decl_ctx,
1241     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1242     TypeMap &types) {
1243   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1244   if (!name)
1245     return;
1246 
1247   searched_symbol_files.clear();
1248   searched_symbol_files.insert(this);
1249 
1250   // There is an assumption 'name' is not a regex
1251   FindTypesByName(name.GetStringRef(), max_matches, types);
1252 }
1253 
1254 void SymbolFileNativePDB::FindTypes(
1255     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
1256     llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {}
1257 
1258 void SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1259                                           uint32_t max_matches,
1260                                           TypeMap &types) {
1261 
1262   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1263   if (max_matches > 0 && max_matches < matches.size())
1264     matches.resize(max_matches);
1265 
1266   for (TypeIndex ti : matches) {
1267     TypeSP type = GetOrCreateType(ti);
1268     if (!type)
1269       continue;
1270 
1271     types.Insert(type);
1272   }
1273 }
1274 
1275 size_t SymbolFileNativePDB::ParseTypes(CompileUnit &comp_unit) {
1276   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1277   // Only do the full type scan the first time.
1278   if (m_done_full_type_scan)
1279     return 0;
1280 
1281   const size_t old_count = GetTypeList().GetSize();
1282   LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
1283 
1284   // First process the entire TPI stream.
1285   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
1286     TypeSP type = GetOrCreateType(*ti);
1287     if (type)
1288       (void)type->GetFullCompilerType();
1289   }
1290 
1291   // Next look for S_UDT records in the globals stream.
1292   for (const uint32_t gid : m_index->globals().getGlobalsTable()) {
1293     PdbGlobalSymId global{gid, false};
1294     CVSymbol sym = m_index->ReadSymbolRecord(global);
1295     if (sym.kind() != S_UDT)
1296       continue;
1297 
1298     UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1299     bool is_typedef = true;
1300     if (IsTagRecord(PdbTypeSymId{udt.Type, false}, m_index->tpi())) {
1301       CVType cvt = m_index->tpi().getType(udt.Type);
1302       llvm::StringRef name = CVTagRecord::create(cvt).name();
1303       if (name == udt.Name)
1304         is_typedef = false;
1305     }
1306 
1307     if (is_typedef)
1308       GetOrCreateTypedef(global);
1309   }
1310 
1311   const size_t new_count = GetTypeList().GetSize();
1312 
1313   m_done_full_type_scan = true;
1314 
1315   return new_count - old_count;
1316 }
1317 
1318 size_t
1319 SymbolFileNativePDB::ParseVariablesForCompileUnit(CompileUnit &comp_unit,
1320                                                   VariableList &variables) {
1321   PdbSymUid sym_uid(comp_unit.GetID());
1322   lldbassert(sym_uid.kind() == PdbSymUidKind::Compiland);
1323   return 0;
1324 }
1325 
1326 VariableSP SymbolFileNativePDB::CreateLocalVariable(PdbCompilandSymId scope_id,
1327                                                     PdbCompilandSymId var_id,
1328                                                     bool is_param) {
1329   ModuleSP module = GetObjectFile()->GetModule();
1330   Block &block = GetOrCreateBlock(scope_id);
1331   VariableInfo var_info =
1332       GetVariableLocationInfo(*m_index, var_id, block, module);
1333   if (!var_info.location || !var_info.ranges)
1334     return nullptr;
1335 
1336   CompilandIndexItem *cii = m_index->compilands().GetCompiland(var_id.modi);
1337   CompUnitSP comp_unit_sp = GetOrCreateCompileUnit(*cii);
1338   TypeSP type_sp = GetOrCreateType(var_info.type);
1339   std::string name = var_info.name.str();
1340   Declaration decl;
1341   SymbolFileTypeSP sftype =
1342       std::make_shared<SymbolFileType>(*this, type_sp->GetID());
1343 
1344   ValueType var_scope =
1345       is_param ? eValueTypeVariableArgument : eValueTypeVariableLocal;
1346   VariableSP var_sp = std::make_shared<Variable>(
1347       toOpaqueUid(var_id), name.c_str(), name.c_str(), sftype, var_scope,
1348       comp_unit_sp.get(), *var_info.ranges, &decl, *var_info.location, false,
1349       false, false);
1350 
1351   if (!is_param)
1352     m_ast->GetOrCreateVariableDecl(scope_id, var_id);
1353 
1354   m_local_variables[toOpaqueUid(var_id)] = var_sp;
1355   return var_sp;
1356 }
1357 
1358 VariableSP SymbolFileNativePDB::GetOrCreateLocalVariable(
1359     PdbCompilandSymId scope_id, PdbCompilandSymId var_id, bool is_param) {
1360   auto iter = m_local_variables.find(toOpaqueUid(var_id));
1361   if (iter != m_local_variables.end())
1362     return iter->second;
1363 
1364   return CreateLocalVariable(scope_id, var_id, is_param);
1365 }
1366 
1367 TypeSP SymbolFileNativePDB::CreateTypedef(PdbGlobalSymId id) {
1368   CVSymbol sym = m_index->ReadSymbolRecord(id);
1369   lldbassert(sym.kind() == SymbolKind::S_UDT);
1370 
1371   UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
1372 
1373   TypeSP target_type = GetOrCreateType(udt.Type);
1374 
1375   (void)m_ast->GetOrCreateTypedefDecl(id);
1376 
1377   Declaration decl;
1378   return std::make_shared<lldb_private::Type>(
1379       toOpaqueUid(id), this, ConstString(udt.Name), target_type->GetByteSize(),
1380       nullptr, target_type->GetID(), lldb_private::Type::eEncodingIsTypedefUID,
1381       decl, target_type->GetForwardCompilerType(),
1382       lldb_private::Type::ResolveState::Forward);
1383 }
1384 
1385 TypeSP SymbolFileNativePDB::GetOrCreateTypedef(PdbGlobalSymId id) {
1386   auto iter = m_types.find(toOpaqueUid(id));
1387   if (iter != m_types.end())
1388     return iter->second;
1389 
1390   return CreateTypedef(id);
1391 }
1392 
1393 size_t SymbolFileNativePDB::ParseVariablesForBlock(PdbCompilandSymId block_id) {
1394   Block &block = GetOrCreateBlock(block_id);
1395 
1396   size_t count = 0;
1397 
1398   CompilandIndexItem *cii = m_index->compilands().GetCompiland(block_id.modi);
1399   CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(block_id.offset);
1400   uint32_t params_remaining = 0;
1401   switch (sym.kind()) {
1402   case S_GPROC32:
1403   case S_LPROC32: {
1404     ProcSym proc(static_cast<SymbolRecordKind>(sym.kind()));
1405     cantFail(SymbolDeserializer::deserializeAs<ProcSym>(sym, proc));
1406     CVType signature = m_index->tpi().getType(proc.FunctionType);
1407     ProcedureRecord sig;
1408     cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(signature, sig));
1409     params_remaining = sig.getParameterCount();
1410     break;
1411   }
1412   case S_BLOCK32:
1413     break;
1414   default:
1415     lldbassert(false && "Symbol is not a block!");
1416     return 0;
1417   }
1418 
1419   VariableListSP variables = block.GetBlockVariableList(false);
1420   if (!variables) {
1421     variables = std::make_shared<VariableList>();
1422     block.SetVariableList(variables);
1423   }
1424 
1425   CVSymbolArray syms = limitSymbolArrayToScope(
1426       cii->m_debug_stream.getSymbolArray(), block_id.offset);
1427 
1428   // Skip the first record since it's a PROC32 or BLOCK32, and there's
1429   // no point examining it since we know it's not a local variable.
1430   syms.drop_front();
1431   auto iter = syms.begin();
1432   auto end = syms.end();
1433 
1434   while (iter != end) {
1435     uint32_t record_offset = iter.offset();
1436     CVSymbol variable_cvs = *iter;
1437     PdbCompilandSymId child_sym_id(block_id.modi, record_offset);
1438     ++iter;
1439 
1440     // If this is a block, recurse into its children and then skip it.
1441     if (variable_cvs.kind() == S_BLOCK32) {
1442       uint32_t block_end = getScopeEndOffset(variable_cvs);
1443       count += ParseVariablesForBlock(child_sym_id);
1444       iter = syms.at(block_end);
1445       continue;
1446     }
1447 
1448     bool is_param = params_remaining > 0;
1449     VariableSP variable;
1450     switch (variable_cvs.kind()) {
1451     case S_REGREL32:
1452     case S_REGISTER:
1453     case S_LOCAL:
1454       variable = GetOrCreateLocalVariable(block_id, child_sym_id, is_param);
1455       if (is_param)
1456         --params_remaining;
1457       if (variable)
1458         variables->AddVariableIfUnique(variable);
1459       break;
1460     default:
1461       break;
1462     }
1463   }
1464 
1465   // Pass false for set_children, since we call this recursively so that the
1466   // children will call this for themselves.
1467   block.SetDidParseVariables(true, false);
1468 
1469   return count;
1470 }
1471 
1472 size_t SymbolFileNativePDB::ParseVariablesForContext(const SymbolContext &sc) {
1473   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1474   lldbassert(sc.function || sc.comp_unit);
1475 
1476   VariableListSP variables;
1477   if (sc.block) {
1478     PdbSymUid block_id(sc.block->GetID());
1479 
1480     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1481     return count;
1482   }
1483 
1484   if (sc.function) {
1485     PdbSymUid block_id(sc.function->GetID());
1486 
1487     size_t count = ParseVariablesForBlock(block_id.asCompilandSym());
1488     return count;
1489   }
1490 
1491   if (sc.comp_unit) {
1492     variables = sc.comp_unit->GetVariableList(false);
1493     if (!variables) {
1494       variables = std::make_shared<VariableList>();
1495       sc.comp_unit->SetVariableList(variables);
1496     }
1497     return ParseVariablesForCompileUnit(*sc.comp_unit, *variables);
1498   }
1499 
1500   llvm_unreachable("Unreachable!");
1501 }
1502 
1503 CompilerDecl SymbolFileNativePDB::GetDeclForUID(lldb::user_id_t uid) {
1504   if (auto decl = m_ast->GetOrCreateDeclForUid(uid))
1505     return decl.getValue();
1506   else
1507     return CompilerDecl();
1508 }
1509 
1510 CompilerDeclContext
1511 SymbolFileNativePDB::GetDeclContextForUID(lldb::user_id_t uid) {
1512   clang::DeclContext *context =
1513       m_ast->GetOrCreateDeclContextForUid(PdbSymUid(uid));
1514   if (!context)
1515     return {};
1516 
1517   return m_ast->ToCompilerDeclContext(*context);
1518 }
1519 
1520 CompilerDeclContext
1521 SymbolFileNativePDB::GetDeclContextContainingUID(lldb::user_id_t uid) {
1522   clang::DeclContext *context = m_ast->GetParentDeclContext(PdbSymUid(uid));
1523   return m_ast->ToCompilerDeclContext(*context);
1524 }
1525 
1526 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1527   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1528   auto iter = m_types.find(type_uid);
1529   // lldb should not be passing us non-sensical type uids.  the only way it
1530   // could have a type uid in the first place is if we handed it out, in which
1531   // case we should know about the type.  However, that doesn't mean we've
1532   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1533   // type doesn't exist, let's instantiate it now.
1534   if (iter != m_types.end())
1535     return &*iter->second;
1536 
1537   PdbSymUid uid(type_uid);
1538   lldbassert(uid.kind() == PdbSymUidKind::Type);
1539   PdbTypeSymId type_id = uid.asTypeSym();
1540   if (type_id.index.isNoneType())
1541     return nullptr;
1542 
1543   TypeSP type_sp = CreateAndCacheType(type_id);
1544   return &*type_sp;
1545 }
1546 
1547 llvm::Optional<SymbolFile::ArrayInfo>
1548 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1549     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1550   return llvm::None;
1551 }
1552 
1553 
1554 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1555   clang::QualType qt =
1556       clang::QualType::getFromOpaquePtr(compiler_type.GetOpaqueQualType());
1557 
1558   return m_ast->CompleteType(qt);
1559 }
1560 
1561 void SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1562                                    TypeClass type_mask,
1563                                    lldb_private::TypeList &type_list) {}
1564 
1565 CompilerDeclContext
1566 SymbolFileNativePDB::FindNamespace(ConstString name,
1567                                    const CompilerDeclContext &parent_decl_ctx) {
1568   return {};
1569 }
1570 
1571 llvm::Expected<TypeSystem &>
1572 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1573   auto type_system_or_err =
1574       m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
1575   if (type_system_or_err) {
1576     type_system_or_err->SetSymbolFile(this);
1577   }
1578   return type_system_or_err;
1579 }
1580 
1581 ConstString SymbolFileNativePDB::GetPluginName() {
1582   static ConstString g_name("pdb");
1583   return g_name;
1584 }
1585 
1586 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }
1587