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