1 //===-- SymbolFileNativePDB.cpp ---------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "SymbolFileNativePDB.h"
11 
12 #include "clang/AST/Attr.h"
13 #include "clang/AST/CharUnits.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/Type.h"
17 
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/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 "PdbSymUid.h"
58 #include "PdbUtil.h"
59 #include "UdtRecordCompleter.h"
60 
61 using namespace lldb;
62 using namespace lldb_private;
63 using namespace npdb;
64 using namespace llvm::codeview;
65 using namespace llvm::pdb;
66 
67 static lldb::LanguageType TranslateLanguage(PDB_Lang lang) {
68   switch (lang) {
69   case PDB_Lang::Cpp:
70     return lldb::LanguageType::eLanguageTypeC_plus_plus;
71   case PDB_Lang::C:
72     return lldb::LanguageType::eLanguageTypeC;
73   default:
74     return lldb::LanguageType::eLanguageTypeUnknown;
75   }
76 }
77 
78 static std::unique_ptr<PDBFile> loadPDBFile(std::string PdbPath,
79                                             llvm::BumpPtrAllocator &Allocator) {
80   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ErrorOrBuffer =
81       llvm::MemoryBuffer::getFile(PdbPath, /*FileSize=*/-1,
82                                   /*RequiresNullTerminator=*/false);
83   if (!ErrorOrBuffer)
84     return nullptr;
85   std::unique_ptr<llvm::MemoryBuffer> Buffer = std::move(*ErrorOrBuffer);
86 
87   llvm::StringRef Path = Buffer->getBufferIdentifier();
88   auto Stream = llvm::make_unique<llvm::MemoryBufferByteStream>(
89       std::move(Buffer), llvm::support::little);
90 
91   auto File = llvm::make_unique<PDBFile>(Path, std::move(Stream), Allocator);
92   if (auto EC = File->parseFileHeaders()) {
93     llvm::consumeError(std::move(EC));
94     return nullptr;
95   }
96   if (auto EC = File->parseStreamData()) {
97     llvm::consumeError(std::move(EC));
98     return nullptr;
99   }
100 
101   return File;
102 }
103 
104 static std::unique_ptr<PDBFile>
105 loadMatchingPDBFile(std::string exe_path, llvm::BumpPtrAllocator &allocator) {
106   // Try to find a matching PDB for an EXE.
107   using namespace llvm::object;
108   auto expected_binary = createBinary(exe_path);
109 
110   // If the file isn't a PE/COFF executable, fail.
111   if (!expected_binary) {
112     llvm::consumeError(expected_binary.takeError());
113     return nullptr;
114   }
115   OwningBinary<Binary> binary = std::move(*expected_binary);
116 
117   auto *obj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary.getBinary());
118   if (!obj)
119     return nullptr;
120   const llvm::codeview::DebugInfo *pdb_info = nullptr;
121 
122   // If it doesn't have a debug directory, fail.
123   llvm::StringRef pdb_file;
124   auto ec = obj->getDebugPDBInfo(pdb_info, pdb_file);
125   if (ec)
126     return nullptr;
127 
128   // if the file doesn't exist, is not a pdb, or doesn't have a matching guid,
129   // fail.
130   llvm::file_magic magic;
131   ec = llvm::identify_magic(pdb_file, magic);
132   if (ec || magic != llvm::file_magic::pdb)
133     return nullptr;
134   std::unique_ptr<PDBFile> pdb = loadPDBFile(pdb_file, allocator);
135   if (!pdb)
136     return nullptr;
137 
138   auto expected_info = pdb->getPDBInfoStream();
139   if (!expected_info) {
140     llvm::consumeError(expected_info.takeError());
141     return nullptr;
142   }
143   llvm::codeview::GUID guid;
144   memcpy(&guid, pdb_info->PDB70.Signature, 16);
145 
146   if (expected_info->getGuid() != guid)
147     return nullptr;
148   return pdb;
149 }
150 
151 static bool IsFunctionPrologue(const CompilandIndexItem &cci,
152                                lldb::addr_t addr) {
153   // FIXME: Implement this.
154   return false;
155 }
156 
157 static bool IsFunctionEpilogue(const CompilandIndexItem &cci,
158                                lldb::addr_t addr) {
159   // FIXME: Implement this.
160   return false;
161 }
162 
163 static clang::MSInheritanceAttr::Spelling
164 GetMSInheritance(LazyRandomTypeCollection &tpi, const ClassRecord &record) {
165   if (record.DerivationList == TypeIndex::None())
166     return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
167 
168   CVType bases = tpi.getType(record.DerivationList);
169   ArgListRecord base_list;
170   cantFail(TypeDeserializer::deserializeAs<ArgListRecord>(bases, base_list));
171   if (base_list.ArgIndices.empty())
172     return clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance;
173 
174   int base_count = 0;
175   for (TypeIndex ti : base_list.ArgIndices) {
176     CVType base = tpi.getType(ti);
177     if (base.kind() == LF_VBCLASS || base.kind() == LF_IVBCLASS)
178       return clang::MSInheritanceAttr::Spelling::Keyword_virtual_inheritance;
179     ++base_count;
180   }
181 
182   if (base_count > 1)
183     return clang::MSInheritanceAttr::Keyword_multiple_inheritance;
184   return clang::MSInheritanceAttr::Keyword_single_inheritance;
185 }
186 
187 static lldb::BasicType GetCompilerTypeForSimpleKind(SimpleTypeKind kind) {
188   switch (kind) {
189   case SimpleTypeKind::Boolean128:
190   case SimpleTypeKind::Boolean16:
191   case SimpleTypeKind::Boolean32:
192   case SimpleTypeKind::Boolean64:
193   case SimpleTypeKind::Boolean8:
194     return lldb::eBasicTypeBool;
195   case SimpleTypeKind::Byte:
196   case SimpleTypeKind::UnsignedCharacter:
197     return lldb::eBasicTypeUnsignedChar;
198   case SimpleTypeKind::NarrowCharacter:
199     return lldb::eBasicTypeChar;
200   case SimpleTypeKind::SignedCharacter:
201   case SimpleTypeKind::SByte:
202     return lldb::eBasicTypeSignedChar;
203   case SimpleTypeKind::Character16:
204     return lldb::eBasicTypeChar16;
205   case SimpleTypeKind::Character32:
206     return lldb::eBasicTypeChar32;
207   case SimpleTypeKind::Complex80:
208     return lldb::eBasicTypeLongDoubleComplex;
209   case SimpleTypeKind::Complex64:
210     return lldb::eBasicTypeDoubleComplex;
211   case SimpleTypeKind::Complex32:
212     return lldb::eBasicTypeFloatComplex;
213   case SimpleTypeKind::Float128:
214   case SimpleTypeKind::Float80:
215     return lldb::eBasicTypeLongDouble;
216   case SimpleTypeKind::Float64:
217     return lldb::eBasicTypeDouble;
218   case SimpleTypeKind::Float32:
219     return lldb::eBasicTypeFloat;
220   case SimpleTypeKind::Float16:
221     return lldb::eBasicTypeHalf;
222   case SimpleTypeKind::Int128:
223     return lldb::eBasicTypeInt128;
224   case SimpleTypeKind::Int64:
225   case SimpleTypeKind::Int64Quad:
226     return lldb::eBasicTypeLongLong;
227   case SimpleTypeKind::Int32:
228     return lldb::eBasicTypeInt;
229   case SimpleTypeKind::Int16:
230   case SimpleTypeKind::Int16Short:
231     return lldb::eBasicTypeShort;
232   case SimpleTypeKind::UInt128:
233     return lldb::eBasicTypeUnsignedInt128;
234   case SimpleTypeKind::UInt64:
235   case SimpleTypeKind::UInt64Quad:
236     return lldb::eBasicTypeUnsignedLongLong;
237   case SimpleTypeKind::HResult:
238   case SimpleTypeKind::UInt32:
239     return lldb::eBasicTypeUnsignedInt;
240   case SimpleTypeKind::UInt16:
241   case SimpleTypeKind::UInt16Short:
242     return lldb::eBasicTypeUnsignedShort;
243   case SimpleTypeKind::Int32Long:
244     return lldb::eBasicTypeLong;
245   case SimpleTypeKind::UInt32Long:
246     return lldb::eBasicTypeUnsignedLong;
247   case SimpleTypeKind::Void:
248     return lldb::eBasicTypeVoid;
249   case SimpleTypeKind::WideCharacter:
250     return lldb::eBasicTypeWChar;
251   default:
252     return lldb::eBasicTypeInvalid;
253   }
254 }
255 
256 static size_t GetTypeSizeForSimpleKind(SimpleTypeKind kind) {
257   switch (kind) {
258   case SimpleTypeKind::Boolean128:
259   case SimpleTypeKind::Int128:
260   case SimpleTypeKind::UInt128:
261   case SimpleTypeKind::Float128:
262     return 16;
263   case SimpleTypeKind::Complex80:
264   case SimpleTypeKind::Float80:
265     return 10;
266   case SimpleTypeKind::Boolean64:
267   case SimpleTypeKind::Complex64:
268   case SimpleTypeKind::UInt64:
269   case SimpleTypeKind::UInt64Quad:
270   case SimpleTypeKind::Float64:
271   case SimpleTypeKind::Int64:
272   case SimpleTypeKind::Int64Quad:
273     return 8;
274   case SimpleTypeKind::Boolean32:
275   case SimpleTypeKind::Character32:
276   case SimpleTypeKind::Complex32:
277   case SimpleTypeKind::Float32:
278   case SimpleTypeKind::Int32:
279   case SimpleTypeKind::Int32Long:
280   case SimpleTypeKind::UInt32Long:
281   case SimpleTypeKind::HResult:
282   case SimpleTypeKind::UInt32:
283     return 4;
284   case SimpleTypeKind::Boolean16:
285   case SimpleTypeKind::Character16:
286   case SimpleTypeKind::Float16:
287   case SimpleTypeKind::Int16:
288   case SimpleTypeKind::Int16Short:
289   case SimpleTypeKind::UInt16:
290   case SimpleTypeKind::UInt16Short:
291   case SimpleTypeKind::WideCharacter:
292     return 2;
293   case SimpleTypeKind::Boolean8:
294   case SimpleTypeKind::Byte:
295   case SimpleTypeKind::UnsignedCharacter:
296   case SimpleTypeKind::NarrowCharacter:
297   case SimpleTypeKind::SignedCharacter:
298   case SimpleTypeKind::SByte:
299     return 1;
300   case SimpleTypeKind::Void:
301   default:
302     return 0;
303   }
304 }
305 
306 static llvm::StringRef GetSimpleTypeName(SimpleTypeKind kind) {
307   switch (kind) {
308   case SimpleTypeKind::Boolean128:
309   case SimpleTypeKind::Boolean16:
310   case SimpleTypeKind::Boolean32:
311   case SimpleTypeKind::Boolean64:
312   case SimpleTypeKind::Boolean8:
313     return "bool";
314   case SimpleTypeKind::Byte:
315   case SimpleTypeKind::UnsignedCharacter:
316     return "unsigned char";
317   case SimpleTypeKind::NarrowCharacter:
318     return "char";
319   case SimpleTypeKind::SignedCharacter:
320   case SimpleTypeKind::SByte:
321     return "signed char";
322   case SimpleTypeKind::Character16:
323     return "char16_t";
324   case SimpleTypeKind::Character32:
325     return "char32_t";
326   case SimpleTypeKind::Complex80:
327   case SimpleTypeKind::Complex64:
328   case SimpleTypeKind::Complex32:
329     return "complex";
330   case SimpleTypeKind::Float128:
331   case SimpleTypeKind::Float80:
332     return "long double";
333   case SimpleTypeKind::Float64:
334     return "double";
335   case SimpleTypeKind::Float32:
336     return "float";
337   case SimpleTypeKind::Float16:
338     return "single";
339   case SimpleTypeKind::Int128:
340     return "__int128";
341   case SimpleTypeKind::Int64:
342   case SimpleTypeKind::Int64Quad:
343     return "int64_t";
344   case SimpleTypeKind::Int32:
345     return "int";
346   case SimpleTypeKind::Int16:
347     return "short";
348   case SimpleTypeKind::UInt128:
349     return "unsigned __int128";
350   case SimpleTypeKind::UInt64:
351   case SimpleTypeKind::UInt64Quad:
352     return "uint64_t";
353   case SimpleTypeKind::HResult:
354     return "HRESULT";
355   case SimpleTypeKind::UInt32:
356     return "unsigned";
357   case SimpleTypeKind::UInt16:
358   case SimpleTypeKind::UInt16Short:
359     return "unsigned short";
360   case SimpleTypeKind::Int32Long:
361     return "long";
362   case SimpleTypeKind::UInt32Long:
363     return "unsigned long";
364   case SimpleTypeKind::Void:
365     return "void";
366   case SimpleTypeKind::WideCharacter:
367     return "wchar_t";
368   default:
369     return "";
370   }
371 }
372 
373 static bool IsClassRecord(TypeLeafKind kind) {
374   switch (kind) {
375   case LF_STRUCTURE:
376   case LF_CLASS:
377   case LF_INTERFACE:
378     return true;
379   default:
380     return false;
381   }
382 }
383 
384 static PDB_SymType GetPdbSymType(TpiStream &tpi, TypeIndex ti) {
385   if (ti.isSimple()) {
386     if (ti.getSimpleMode() == SimpleTypeMode::Direct)
387       return PDB_SymType::BuiltinType;
388     return PDB_SymType::PointerType;
389   }
390 
391   CVType cvt = tpi.getType(ti);
392   TypeLeafKind kind = cvt.kind();
393   if (kind != LF_MODIFIER)
394     return CVTypeToPDBType(kind);
395 
396   // If this is an LF_MODIFIER, look through it to get the kind that it
397   // modifies.  Note that it's not possible to have an LF_MODIFIER that
398   // modifies another LF_MODIFIER, although this would handle that anyway.
399   return GetPdbSymType(tpi, LookThroughModifierRecord(cvt));
400 }
401 
402 static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
403   if (args.empty())
404     return false;
405   return args.back() == TypeIndex::None();
406 }
407 
408 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
409   switch (cr.Kind) {
410   case TypeRecordKind::Class:
411     return clang::TTK_Class;
412   case TypeRecordKind::Struct:
413     return clang::TTK_Struct;
414   case TypeRecordKind::Union:
415     return clang::TTK_Union;
416   case TypeRecordKind::Interface:
417     return clang::TTK_Interface;
418   case TypeRecordKind::Enum:
419     return clang::TTK_Enum;
420   default:
421     lldbassert(false && "Invalid tag record kind!");
422     return clang::TTK_Struct;
423   }
424 }
425 
426 static llvm::Optional<clang::CallingConv>
427 TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
428   using CC = llvm::codeview::CallingConvention;
429   switch (conv) {
430 
431   case CC::NearC:
432   case CC::FarC:
433     return clang::CallingConv::CC_C;
434   case CC::NearPascal:
435   case CC::FarPascal:
436     return clang::CallingConv::CC_X86Pascal;
437   case CC::NearFast:
438   case CC::FarFast:
439     return clang::CallingConv::CC_X86FastCall;
440   case CC::NearStdCall:
441   case CC::FarStdCall:
442     return clang::CallingConv::CC_X86StdCall;
443   case CC::ThisCall:
444     return clang::CallingConv::CC_X86ThisCall;
445   case CC::NearVector:
446     return clang::CallingConv::CC_X86VectorCall;
447   default:
448     return llvm::None;
449   }
450 }
451 
452 void SymbolFileNativePDB::Initialize() {
453   PluginManager::RegisterPlugin(GetPluginNameStatic(),
454                                 GetPluginDescriptionStatic(), CreateInstance,
455                                 DebuggerInitialize);
456 }
457 
458 void SymbolFileNativePDB::Terminate() {
459   PluginManager::UnregisterPlugin(CreateInstance);
460 }
461 
462 void SymbolFileNativePDB::DebuggerInitialize(Debugger &debugger) {}
463 
464 ConstString SymbolFileNativePDB::GetPluginNameStatic() {
465   static ConstString g_name("native-pdb");
466   return g_name;
467 }
468 
469 const char *SymbolFileNativePDB::GetPluginDescriptionStatic() {
470   return "Microsoft PDB debug symbol cross-platform file reader.";
471 }
472 
473 SymbolFile *SymbolFileNativePDB::CreateInstance(ObjectFile *obj_file) {
474   return new SymbolFileNativePDB(obj_file);
475 }
476 
477 SymbolFileNativePDB::SymbolFileNativePDB(ObjectFile *object_file)
478     : SymbolFile(object_file) {}
479 
480 SymbolFileNativePDB::~SymbolFileNativePDB() {}
481 
482 uint32_t SymbolFileNativePDB::CalculateAbilities() {
483   uint32_t abilities = 0;
484   if (!m_obj_file)
485     return 0;
486 
487   if (!m_index) {
488     // Lazily load and match the PDB file, but only do this once.
489     std::unique_ptr<PDBFile> file_up =
490         loadMatchingPDBFile(m_obj_file->GetFileSpec().GetPath(), m_allocator);
491 
492     if (!file_up) {
493       auto module_sp = m_obj_file->GetModule();
494       if (!module_sp)
495         return 0;
496       // See if any symbol file is specified through `--symfile` option.
497       FileSpec symfile = module_sp->GetSymbolFileFileSpec();
498       if (!symfile)
499         return 0;
500       file_up = loadPDBFile(symfile.GetPath(), m_allocator);
501     }
502 
503     if (!file_up)
504       return 0;
505 
506     auto expected_index = PdbIndex::create(std::move(file_up));
507     if (!expected_index) {
508       llvm::consumeError(expected_index.takeError());
509       return 0;
510     }
511     m_index = std::move(*expected_index);
512   }
513   if (!m_index)
514     return 0;
515 
516   // We don't especially have to be precise here.  We only distinguish between
517   // stripped and not stripped.
518   abilities = kAllAbilities;
519 
520   if (m_index->dbi().isStripped())
521     abilities &= ~(Blocks | LocalVariables);
522   return abilities;
523 }
524 
525 void SymbolFileNativePDB::InitializeObject() {
526   m_obj_load_address = m_obj_file->GetFileOffset();
527   m_index->SetLoadAddress(m_obj_load_address);
528   m_index->ParseSectionContribs();
529 
530   TypeSystem *ts = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
531   m_clang = llvm::dyn_cast_or_null<ClangASTContext>(ts);
532   m_importer = llvm::make_unique<ClangASTImporter>();
533 
534   PreprocessTpiStream();
535   lldbassert(m_clang);
536 }
537 
538 void SymbolFileNativePDB::PreprocessTpiStream() {
539   LazyRandomTypeCollection &types = m_index->tpi().typeCollection();
540 
541   for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
542     CVType type = types.getType(*ti);
543     if (!IsTagRecord(type))
544       continue;
545 
546     CVTagRecord tag = CVTagRecord::create(type);
547     // We're looking for LF_NESTTYPE records in the field list, so ignore
548     // forward references (no field list), and anything without a nested class
549     // (since there won't be any LF_NESTTYPE records).
550     if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
551       continue;
552 
553     struct ProcessTpiStream : public TypeVisitorCallbacks {
554       ProcessTpiStream(PdbIndex &index, TypeIndex parent,
555                        llvm::DenseMap<TypeIndex, TypeIndex> &parents)
556           : index(index), parents(parents), parent(parent) {}
557 
558       PdbIndex &index;
559       llvm::DenseMap<TypeIndex, TypeIndex> &parents;
560       TypeIndex parent;
561 
562       llvm::Error visitKnownMember(CVMemberRecord &CVR,
563                                    NestedTypeRecord &Record) override {
564         parents[Record.Type] = parent;
565         CVType child = index.tpi().getType(Record.Type);
566         if (!IsForwardRefUdt(child))
567           return llvm::ErrorSuccess();
568         llvm::Expected<TypeIndex> full_decl =
569             index.tpi().findFullDeclForForwardRef(Record.Type);
570         if (!full_decl) {
571           llvm::consumeError(full_decl.takeError());
572           return llvm::ErrorSuccess();
573         }
574         parents[*full_decl] = parent;
575         return llvm::ErrorSuccess();
576       }
577     };
578 
579     CVType field_list = m_index->tpi().getType(tag.asTag().FieldList);
580     ProcessTpiStream process(*m_index, *ti, m_parent_types);
581     llvm::Error error = visitMemberRecordStream(field_list.data(), process);
582     if (error)
583       llvm::consumeError(std::move(error));
584   }
585 }
586 
587 uint32_t SymbolFileNativePDB::GetNumCompileUnits() {
588   const DbiModuleList &modules = m_index->dbi().modules();
589   uint32_t count = modules.getModuleCount();
590   if (count == 0)
591     return count;
592 
593   // The linker can inject an additional "dummy" compilation unit into the
594   // PDB. Ignore this special compile unit for our purposes, if it is there.
595   // It is always the last one.
596   DbiModuleDescriptor last = modules.getModuleDescriptor(count - 1);
597   if (last.getModuleName() == "* Linker *")
598     --count;
599   return count;
600 }
601 
602 lldb::FunctionSP SymbolFileNativePDB::CreateFunction(PdbSymUid func_uid,
603                                                      const SymbolContext &sc) {
604   lldbassert(func_uid.tag() == PDB_SymType::Function);
605 
606   PdbSymUid cuid = PdbSymUid::makeCompilandId(func_uid.asCuSym().modi);
607 
608   const CompilandIndexItem *cci = m_index->compilands().GetCompiland(cuid);
609   lldbassert(cci);
610   CVSymbol sym_record =
611       cci->m_debug_stream.readSymbolAtOffset(func_uid.asCuSym().offset);
612 
613   lldbassert(sym_record.kind() == S_LPROC32 || sym_record.kind() == S_GPROC32);
614   SegmentOffsetLength sol = GetSegmentOffsetAndLength(sym_record);
615 
616   auto file_vm_addr = m_index->MakeVirtualAddress(sol.so);
617   if (file_vm_addr == LLDB_INVALID_ADDRESS || file_vm_addr == 0)
618     return nullptr;
619 
620   AddressRange func_range(file_vm_addr, sol.length,
621                           sc.module_sp->GetSectionList());
622   if (!func_range.GetBaseAddress().IsValid())
623     return nullptr;
624 
625   Type *func_type = nullptr;
626 
627   // FIXME: Resolve types and mangled names.
628   PdbSymUid sig_uid =
629       PdbSymUid::makeTypeSymId(PDB_SymType::FunctionSig, TypeIndex{0}, false);
630   Mangled mangled(getSymbolName(sym_record));
631   FunctionSP func_sp = std::make_shared<Function>(
632       sc.comp_unit, func_uid.toOpaqueId(), sig_uid.toOpaqueId(), mangled,
633       func_type, func_range);
634 
635   sc.comp_unit->AddFunction(func_sp);
636   return func_sp;
637 }
638 
639 CompUnitSP
640 SymbolFileNativePDB::CreateCompileUnit(const CompilandIndexItem &cci) {
641   lldb::LanguageType lang =
642       cci.m_compile_opts ? TranslateLanguage(cci.m_compile_opts->getLanguage())
643                          : lldb::eLanguageTypeUnknown;
644 
645   LazyBool optimized = eLazyBoolNo;
646   if (cci.m_compile_opts && cci.m_compile_opts->hasOptimizations())
647     optimized = eLazyBoolYes;
648 
649   llvm::StringRef source_file_name =
650       m_index->compilands().GetMainSourceFile(cci);
651   FileSpec fs(source_file_name);
652 
653   CompUnitSP cu_sp =
654       std::make_shared<CompileUnit>(m_obj_file->GetModule(), nullptr, fs,
655                                     cci.m_uid.toOpaqueId(), lang, optimized);
656 
657   const PdbCompilandId &cuid = cci.m_uid.asCompiland();
658   m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cuid.modi,
659                                                                     cu_sp);
660   return cu_sp;
661 }
662 
663 lldb::TypeSP SymbolFileNativePDB::CreateModifierType(PdbSymUid type_uid,
664                                                      const ModifierRecord &mr) {
665   TpiStream &stream = m_index->tpi();
666 
667   TypeSP t = GetOrCreateType(mr.ModifiedType);
668   CompilerType ct = t->GetForwardCompilerType();
669   if ((mr.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
670     ct = ct.AddConstModifier();
671   if ((mr.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
672     ct = ct.AddVolatileModifier();
673   std::string name;
674   if (mr.ModifiedType.isSimple())
675     name = GetSimpleTypeName(mr.ModifiedType.getSimpleKind());
676   else
677     name = computeTypeName(stream.typeCollection(), mr.ModifiedType);
678   Declaration decl;
679   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
680                                 ConstString(name), t->GetByteSize(), nullptr,
681                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
682                                 ct, Type::eResolveStateFull);
683 }
684 
685 lldb::TypeSP SymbolFileNativePDB::CreatePointerType(
686     PdbSymUid type_uid, const llvm::codeview::PointerRecord &pr) {
687   TypeSP pointee = GetOrCreateType(pr.ReferentType);
688   if (!pointee)
689     return nullptr;
690   CompilerType pointee_ct = pointee->GetForwardCompilerType();
691   lldbassert(pointee_ct);
692   Declaration decl;
693 
694   if (pr.isPointerToMember()) {
695     MemberPointerInfo mpi = pr.getMemberInfo();
696     TypeSP class_type = GetOrCreateType(mpi.ContainingType);
697 
698     CompilerType ct = ClangASTContext::CreateMemberPointerType(
699         class_type->GetLayoutCompilerType(), pointee_ct);
700 
701     return std::make_shared<Type>(
702         type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(),
703         pr.getSize(), nullptr, LLDB_INVALID_UID, Type::eEncodingIsUID, decl, ct,
704         Type::eResolveStateFull);
705   }
706 
707   CompilerType pointer_ct = pointee_ct;
708   if (pr.getMode() == PointerMode::LValueReference)
709     pointer_ct = pointer_ct.GetLValueReferenceType();
710   else if (pr.getMode() == PointerMode::RValueReference)
711     pointer_ct = pointer_ct.GetRValueReferenceType();
712   else
713     pointer_ct = pointer_ct.GetPointerType();
714 
715   if ((pr.getOptions() & PointerOptions::Const) != PointerOptions::None)
716     pointer_ct = pointer_ct.AddConstModifier();
717 
718   if ((pr.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
719     pointer_ct = pointer_ct.AddVolatileModifier();
720 
721   if ((pr.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
722     pointer_ct = pointer_ct.AddRestrictModifier();
723 
724   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
725                                 ConstString(), pr.getSize(), nullptr,
726                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
727                                 pointer_ct, Type::eResolveStateFull);
728 }
729 
730 lldb::TypeSP SymbolFileNativePDB::CreateSimpleType(TypeIndex ti) {
731   if (ti == TypeIndex::NullptrT()) {
732     PdbSymUid uid =
733         PdbSymUid::makeTypeSymId(PDB_SymType::BuiltinType, ti, false);
734     CompilerType ct = m_clang->GetBasicType(eBasicTypeNullPtr);
735     Declaration decl;
736     return std::make_shared<Type>(uid.toOpaqueId(), this,
737                                   ConstString("std::nullptr_t"), 0, nullptr,
738                                   LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
739                                   ct, Type::eResolveStateFull);
740   }
741 
742   if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
743     PdbSymUid uid =
744         PdbSymUid::makeTypeSymId(PDB_SymType::PointerType, ti, false);
745     TypeSP direct_sp = GetOrCreateType(ti.makeDirect());
746     CompilerType ct = direct_sp->GetFullCompilerType();
747     ct = ct.GetPointerType();
748     uint32_t pointer_size = 0;
749     switch (ti.getSimpleMode()) {
750     case SimpleTypeMode::FarPointer32:
751     case SimpleTypeMode::NearPointer32:
752       pointer_size = 4;
753       break;
754     case SimpleTypeMode::NearPointer64:
755       pointer_size = 8;
756       break;
757     default:
758       // 128-bit and 16-bit pointers unsupported.
759       return nullptr;
760     }
761     Declaration decl;
762     return std::make_shared<Type>(uid.toOpaqueId(), m_clang->GetSymbolFile(),
763                                   ConstString(), pointer_size, nullptr,
764                                   LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
765                                   ct, Type::eResolveStateFull);
766   }
767 
768   PdbSymUid uid = PdbSymUid::makeTypeSymId(PDB_SymType::BuiltinType, ti, false);
769   if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
770     return nullptr;
771 
772   lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
773   if (bt == lldb::eBasicTypeInvalid)
774     return nullptr;
775   CompilerType ct = m_clang->GetBasicType(bt);
776   size_t size = GetTypeSizeForSimpleKind(ti.getSimpleKind());
777 
778   llvm::StringRef type_name = GetSimpleTypeName(ti.getSimpleKind());
779 
780   Declaration decl;
781   return std::make_shared<Type>(uid.toOpaqueId(), m_clang->GetSymbolFile(),
782                                 ConstString(type_name), size, nullptr,
783                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
784                                 ct, Type::eResolveStateFull);
785 }
786 
787 static std::string RenderDemanglerNode(llvm::ms_demangle::Node *n) {
788   OutputStream OS;
789   initializeOutputStream(nullptr, nullptr, OS, 1024);
790   n->output(OS, llvm::ms_demangle::OF_Default);
791   OS << '\0';
792   return {OS.getBuffer()};
793 }
794 
795 std::pair<clang::DeclContext *, std::string>
796 SymbolFileNativePDB::CreateDeclInfoForType(const TagRecord &record,
797                                            TypeIndex ti) {
798   llvm::ms_demangle::Demangler demangler;
799   StringView sv(record.UniqueName.begin(), record.UniqueName.size());
800   llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
801   llvm::ms_demangle::IdentifierNode *idn =
802       ttn->QualifiedName->getUnqualifiedIdentifier();
803   std::string uname = RenderDemanglerNode(idn);
804 
805   llvm::ms_demangle::NodeArrayNode *name_components =
806       ttn->QualifiedName->Components;
807   llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
808                                                    name_components->Count - 1);
809 
810   clang::DeclContext *context = m_clang->GetTranslationUnitDecl();
811 
812   // If this type doesn't have a parent type in the debug info, then the best we
813   // can do is to say that it's either a series of namespaces (if the scope is
814   // non-empty), or the translation unit (if the scope is empty).
815   auto parent_iter = m_parent_types.find(ti);
816   if (parent_iter == m_parent_types.end()) {
817     if (scopes.empty())
818       return {context, uname};
819 
820     for (llvm::ms_demangle::Node *scope : scopes) {
821       auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
822       std::string str = RenderDemanglerNode(nii);
823       context = m_clang->GetUniqueNamespaceDeclaration(str.c_str(), context);
824     }
825     return {context, uname};
826   }
827 
828   // Otherwise, all we need to do is get the parent type of this type and
829   // recurse into our lazy type creation / AST reconstruction logic to get an
830   // LLDB TypeSP for the parent.  This will cause the AST to automatically get
831   // the right DeclContext created for any parent.
832   TypeSP parent = GetOrCreateType(parent_iter->second);
833   if (!parent)
834     return {context, uname};
835   CompilerType parent_ct = parent->GetForwardCompilerType();
836   clang::QualType qt = ClangUtil::GetCanonicalQualType(parent_ct);
837   context = clang::TagDecl::castToDeclContext(qt->getAsTagDecl());
838   return {context, uname};
839 }
840 
841 lldb::TypeSP SymbolFileNativePDB::CreateClassStructUnion(
842     PdbSymUid type_uid, const llvm::codeview::TagRecord &record, size_t size,
843     clang::TagTypeKind ttk, clang::MSInheritanceAttr::Spelling inheritance) {
844 
845   const PdbTypeSymId &tid = type_uid.asTypeSym();
846   TypeIndex ti(tid.index);
847   clang::DeclContext *decl_context = nullptr;
848   std::string uname;
849   std::tie(decl_context, uname) = CreateDeclInfoForType(record, ti);
850 
851   lldb::AccessType access =
852       (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
853 
854   ClangASTMetadata metadata;
855   metadata.SetUserID(type_uid.toOpaqueId());
856   metadata.SetIsDynamicCXXType(false);
857 
858   CompilerType ct =
859       m_clang->CreateRecordType(decl_context, access, uname.c_str(), ttk,
860                                 lldb::eLanguageTypeC_plus_plus, &metadata);
861 
862   lldbassert(ct.IsValid());
863 
864   clang::CXXRecordDecl *record_decl =
865       m_clang->GetAsCXXRecordDecl(ct.GetOpaqueQualType());
866   lldbassert(record_decl);
867 
868   clang::MSInheritanceAttr *attr = clang::MSInheritanceAttr::CreateImplicit(
869       *m_clang->getASTContext(), inheritance);
870   record_decl->addAttr(attr);
871 
872   ClangASTContext::StartTagDeclarationDefinition(ct);
873 
874   // Even if it's possible, don't complete it at this point. Just mark it
875   // forward resolved, and if/when LLDB needs the full definition, it can
876   // ask us.
877   ClangASTContext::SetHasExternalStorage(ct.GetOpaqueQualType(), true);
878 
879   // FIXME: Search IPI stream for LF_UDT_MOD_SRC_LINE.
880   Declaration decl;
881   return std::make_shared<Type>(type_uid.toOpaqueId(), m_clang->GetSymbolFile(),
882                                 ConstString(uname), size, nullptr,
883                                 LLDB_INVALID_UID, Type::eEncodingIsUID, decl,
884                                 ct, Type::eResolveStateForward);
885 }
886 
887 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
888                                                 const ClassRecord &cr) {
889   clang::TagTypeKind ttk = TranslateUdtKind(cr);
890 
891   clang::MSInheritanceAttr::Spelling inheritance =
892       GetMSInheritance(m_index->tpi().typeCollection(), cr);
893   return CreateClassStructUnion(type_uid, cr, cr.getSize(), ttk, inheritance);
894 }
895 
896 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
897                                                 const UnionRecord &ur) {
898   return CreateClassStructUnion(
899       type_uid, ur, ur.getSize(), clang::TTK_Union,
900       clang::MSInheritanceAttr::Spelling::Keyword_single_inheritance);
901 }
902 
903 lldb::TypeSP SymbolFileNativePDB::CreateTagType(PdbSymUid type_uid,
904                                                 const EnumRecord &er) {
905   llvm::StringRef name = DropNameScope(er.getName());
906 
907   clang::DeclContext *decl_context = m_clang->GetTranslationUnitDecl();
908 
909   Declaration decl;
910   TypeSP underlying_type = GetOrCreateType(er.UnderlyingType);
911   CompilerType enum_ct = m_clang->CreateEnumerationType(
912       name.str().c_str(), decl_context, decl,
913       underlying_type->GetFullCompilerType(), er.isScoped());
914 
915   ClangASTContext::StartTagDeclarationDefinition(enum_ct);
916   ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
917 
918   // We're just going to forward resolve this for now.  We'll complete
919   // it only if the user requests.
920   return std::make_shared<lldb_private::Type>(
921       type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(name),
922       underlying_type->GetByteSize(), nullptr, LLDB_INVALID_UID,
923       lldb_private::Type::eEncodingIsUID, decl, enum_ct,
924       lldb_private::Type::eResolveStateForward);
925 }
926 
927 TypeSP SymbolFileNativePDB::CreateArrayType(PdbSymUid type_uid,
928                                             const ArrayRecord &ar) {
929   TypeSP element_type = GetOrCreateType(ar.ElementType);
930   uint64_t element_count = ar.Size / element_type->GetByteSize();
931 
932   CompilerType element_ct = element_type->GetFullCompilerType();
933 
934   CompilerType array_ct =
935       m_clang->CreateArrayType(element_ct, element_count, false);
936 
937   Declaration decl;
938   TypeSP array_sp = std::make_shared<lldb_private::Type>(
939       type_uid.toOpaqueId(), m_clang->GetSymbolFile(), ConstString(), ar.Size,
940       nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
941       array_ct, lldb_private::Type::eResolveStateFull);
942   array_sp->SetEncodingType(element_type.get());
943   return array_sp;
944 }
945 
946 TypeSP SymbolFileNativePDB::CreateProcedureType(PdbSymUid type_uid,
947                                                 const ProcedureRecord &pr) {
948   TpiStream &stream = m_index->tpi();
949   CVType args_cvt = stream.getType(pr.ArgumentList);
950   ArgListRecord args;
951   llvm::cantFail(
952       TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
953 
954   llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
955   bool is_variadic = IsCVarArgsFunction(arg_indices);
956   if (is_variadic)
957     arg_indices = arg_indices.drop_back();
958 
959   std::vector<CompilerType> arg_list;
960   arg_list.reserve(arg_list.size());
961 
962   for (TypeIndex arg_index : arg_indices) {
963     TypeSP arg_sp = GetOrCreateType(arg_index);
964     if (!arg_sp)
965       return nullptr;
966     arg_list.push_back(arg_sp->GetFullCompilerType());
967   }
968 
969   TypeSP return_type_sp = GetOrCreateType(pr.ReturnType);
970   if (!return_type_sp)
971     return nullptr;
972 
973   llvm::Optional<clang::CallingConv> cc =
974       TranslateCallingConvention(pr.CallConv);
975   if (!cc)
976     return nullptr;
977 
978   CompilerType return_ct = return_type_sp->GetFullCompilerType();
979   CompilerType func_sig_ast_type = m_clang->CreateFunctionType(
980       return_ct, arg_list.data(), arg_list.size(), is_variadic, 0, *cc);
981 
982   Declaration decl;
983   return std::make_shared<lldb_private::Type>(
984       type_uid.toOpaqueId(), this, ConstString(), 0, nullptr, LLDB_INVALID_UID,
985       lldb_private::Type::eEncodingIsUID, decl, func_sig_ast_type,
986       lldb_private::Type::eResolveStateFull);
987 }
988 
989 TypeSP SymbolFileNativePDB::CreateType(PdbSymUid type_uid) {
990   const PdbTypeSymId &tsid = type_uid.asTypeSym();
991   TypeIndex index(tsid.index);
992 
993   if (index.getIndex() < TypeIndex::FirstNonSimpleIndex)
994     return CreateSimpleType(index);
995 
996   TpiStream &stream = tsid.is_ipi ? m_index->ipi() : m_index->tpi();
997   CVType cvt = stream.getType(index);
998 
999   if (cvt.kind() == LF_MODIFIER) {
1000     ModifierRecord modifier;
1001     llvm::cantFail(
1002         TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
1003     return CreateModifierType(type_uid, modifier);
1004   }
1005 
1006   if (cvt.kind() == LF_POINTER) {
1007     PointerRecord pointer;
1008     llvm::cantFail(
1009         TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
1010     return CreatePointerType(type_uid, pointer);
1011   }
1012 
1013   if (IsClassRecord(cvt.kind())) {
1014     ClassRecord cr;
1015     llvm::cantFail(TypeDeserializer::deserializeAs<ClassRecord>(cvt, cr));
1016     return CreateTagType(type_uid, cr);
1017   }
1018 
1019   if (cvt.kind() == LF_ENUM) {
1020     EnumRecord er;
1021     llvm::cantFail(TypeDeserializer::deserializeAs<EnumRecord>(cvt, er));
1022     return CreateTagType(type_uid, er);
1023   }
1024 
1025   if (cvt.kind() == LF_UNION) {
1026     UnionRecord ur;
1027     llvm::cantFail(TypeDeserializer::deserializeAs<UnionRecord>(cvt, ur));
1028     return CreateTagType(type_uid, ur);
1029   }
1030 
1031   if (cvt.kind() == LF_ARRAY) {
1032     ArrayRecord ar;
1033     llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
1034     return CreateArrayType(type_uid, ar);
1035   }
1036 
1037   if (cvt.kind() == LF_PROCEDURE) {
1038     ProcedureRecord pr;
1039     llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
1040     return CreateProcedureType(type_uid, pr);
1041   }
1042 
1043   return nullptr;
1044 }
1045 
1046 TypeSP SymbolFileNativePDB::CreateAndCacheType(PdbSymUid type_uid) {
1047   // If they search for a UDT which is a forward ref, try and resolve the full
1048   // decl and just map the forward ref uid to the full decl record.
1049   llvm::Optional<PdbSymUid> full_decl_uid;
1050   if (type_uid.tag() == PDB_SymType::UDT ||
1051       type_uid.tag() == PDB_SymType::Enum) {
1052     const PdbTypeSymId &type_id = type_uid.asTypeSym();
1053     TypeIndex ti(type_id.index);
1054     lldbassert(!ti.isSimple());
1055     CVType cvt = m_index->tpi().getType(ti);
1056 
1057     if (IsForwardRefUdt(cvt)) {
1058       auto expected_full_ti = m_index->tpi().findFullDeclForForwardRef(ti);
1059       if (!expected_full_ti)
1060         llvm::consumeError(expected_full_ti.takeError());
1061       else if (*expected_full_ti != ti) {
1062         full_decl_uid = PdbSymUid::makeTypeSymId(
1063             type_uid.tag(), *expected_full_ti, type_id.is_ipi);
1064 
1065         // It's possible that a lookup would occur for the full decl causing it
1066         // to be cached, then a second lookup would occur for the forward decl.
1067         // We don't want to create a second full decl, so make sure the full
1068         // decl hasn't already been cached.
1069         auto full_iter = m_types.find(full_decl_uid->toOpaqueId());
1070         if (full_iter != m_types.end()) {
1071           TypeSP result = full_iter->second;
1072           // Map the forward decl to the TypeSP for the full decl so we can take
1073           // the fast path next time.
1074           m_types[type_uid.toOpaqueId()] = result;
1075           return result;
1076         }
1077       }
1078     }
1079   }
1080 
1081   PdbSymUid best_uid = full_decl_uid ? *full_decl_uid : type_uid;
1082   TypeSP result = CreateType(best_uid);
1083   if (!result)
1084     return nullptr;
1085   m_types[best_uid.toOpaqueId()] = result;
1086   // If we had both a forward decl and a full decl, make both point to the new
1087   // type.
1088   if (full_decl_uid)
1089     m_types[type_uid.toOpaqueId()] = result;
1090 
1091   const PdbTypeSymId &type_id = best_uid.asTypeSym();
1092   if (best_uid.tag() == PDB_SymType::UDT ||
1093       best_uid.tag() == PDB_SymType::Enum) {
1094     clang::TagDecl *record_decl =
1095         m_clang->GetAsTagDecl(result->GetForwardCompilerType());
1096     lldbassert(record_decl);
1097 
1098     TypeIndex ti(type_id.index);
1099     m_uid_to_decl[best_uid.toOpaqueId()] = record_decl;
1100     m_decl_to_status[record_decl] =
1101         DeclStatus(best_uid.toOpaqueId(), Type::eResolveStateForward);
1102   }
1103   return result;
1104 }
1105 
1106 TypeSP SymbolFileNativePDB::GetOrCreateType(PdbSymUid type_uid) {
1107   lldbassert(PdbSymUid::isTypeSym(type_uid.tag()));
1108   // We can't use try_emplace / overwrite here because the process of creating
1109   // a type could create nested types, which could invalidate iterators.  So
1110   // we have to do a 2-phase lookup / insert.
1111   auto iter = m_types.find(type_uid.toOpaqueId());
1112   if (iter != m_types.end())
1113     return iter->second;
1114 
1115   return CreateAndCacheType(type_uid);
1116 }
1117 
1118 static DWARFExpression MakeGlobalLocationExpression(uint16_t section,
1119                                                     uint32_t offset,
1120                                                     ModuleSP module) {
1121   assert(section > 0);
1122   assert(module);
1123 
1124   const ArchSpec &architecture = module->GetArchitecture();
1125   ByteOrder byte_order = architecture.GetByteOrder();
1126   uint32_t address_size = architecture.GetAddressByteSize();
1127   uint32_t byte_size = architecture.GetDataByteSize();
1128   assert(byte_order != eByteOrderInvalid && address_size != 0);
1129 
1130   RegisterKind register_kind = eRegisterKindDWARF;
1131   StreamBuffer<32> stream(Stream::eBinary, address_size, byte_order);
1132   stream.PutHex8(DW_OP_addr);
1133 
1134   SectionList *section_list = module->GetSectionList();
1135   assert(section_list);
1136 
1137   // Section indices in PDB are 1-based, but in DWARF they are 0-based, so we
1138   // need to subtract 1.
1139   uint32_t section_idx = section - 1;
1140   if (section_idx >= section_list->GetSize())
1141     return DWARFExpression(nullptr);
1142 
1143   auto section_ptr = section_list->GetSectionAtIndex(section_idx);
1144   if (!section_ptr)
1145     return DWARFExpression(nullptr);
1146 
1147   stream.PutMaxHex64(section_ptr->GetFileAddress() + offset, address_size,
1148                      byte_order);
1149   DataBufferSP buffer =
1150       std::make_shared<DataBufferHeap>(stream.GetData(), stream.GetSize());
1151   DataExtractor extractor(buffer, byte_order, address_size, byte_size);
1152   DWARFExpression result(module, extractor, nullptr, 0, buffer->GetByteSize());
1153   result.SetRegisterKind(register_kind);
1154   return result;
1155 }
1156 
1157 VariableSP SymbolFileNativePDB::CreateGlobalVariable(PdbSymUid var_uid) {
1158   const PdbCuSymId &cu_sym = var_uid.asCuSym();
1159   lldbassert(cu_sym.global);
1160   CVSymbol sym = m_index->symrecords().readRecord(cu_sym.offset);
1161   lldb::ValueType scope = eValueTypeInvalid;
1162   TypeIndex ti;
1163   llvm::StringRef name;
1164   lldb::addr_t addr = 0;
1165   uint16_t section = 0;
1166   uint32_t offset = 0;
1167   bool is_external = false;
1168   switch (sym.kind()) {
1169   case S_GDATA32:
1170     is_external = true;
1171     LLVM_FALLTHROUGH;
1172   case S_LDATA32: {
1173     DataSym ds(sym.kind());
1174     llvm::cantFail(SymbolDeserializer::deserializeAs<DataSym>(sym, ds));
1175     ti = ds.Type;
1176     scope = (sym.kind() == S_GDATA32) ? eValueTypeVariableGlobal
1177                                       : eValueTypeVariableStatic;
1178     name = ds.Name;
1179     section = ds.Segment;
1180     offset = ds.DataOffset;
1181     addr = m_index->MakeVirtualAddress(ds.Segment, ds.DataOffset);
1182     break;
1183   }
1184   case S_GTHREAD32:
1185     is_external = true;
1186     LLVM_FALLTHROUGH;
1187   case S_LTHREAD32: {
1188     ThreadLocalDataSym tlds(sym.kind());
1189     llvm::cantFail(
1190         SymbolDeserializer::deserializeAs<ThreadLocalDataSym>(sym, tlds));
1191     ti = tlds.Type;
1192     name = tlds.Name;
1193     section = tlds.Segment;
1194     offset = tlds.DataOffset;
1195     addr = m_index->MakeVirtualAddress(tlds.Segment, tlds.DataOffset);
1196     scope = eValueTypeVariableThreadLocal;
1197     break;
1198   }
1199   default:
1200     llvm_unreachable("unreachable!");
1201   }
1202 
1203   CompUnitSP comp_unit;
1204   llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(addr);
1205   if (modi) {
1206     PdbSymUid cuid = PdbSymUid::makeCompilandId(*modi);
1207     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(cuid);
1208     comp_unit = GetOrCreateCompileUnit(cci);
1209   }
1210 
1211   Declaration decl;
1212   PDB_SymType pdbst = GetPdbSymType(m_index->tpi(), ti);
1213   PdbSymUid tuid = PdbSymUid::makeTypeSymId(pdbst, ti, false);
1214   SymbolFileTypeSP type_sp =
1215       std::make_shared<SymbolFileType>(*this, tuid.toOpaqueId());
1216   Variable::RangeList ranges;
1217 
1218   DWARFExpression location = MakeGlobalLocationExpression(
1219       section, offset, GetObjectFile()->GetModule());
1220 
1221   std::string global_name("::");
1222   global_name += name;
1223   VariableSP var_sp = std::make_shared<Variable>(
1224       var_uid.toOpaqueId(), name.str().c_str(), global_name.c_str(), type_sp,
1225       scope, comp_unit.get(), ranges, &decl, location, is_external, false,
1226       false);
1227   var_sp->SetLocationIsConstantValueData(false);
1228 
1229   return var_sp;
1230 }
1231 
1232 VariableSP SymbolFileNativePDB::GetOrCreateGlobalVariable(PdbSymUid var_uid) {
1233   lldbassert(var_uid.isGlobalVariable());
1234 
1235   auto emplace_result =
1236       m_global_vars.try_emplace(var_uid.toOpaqueId(), nullptr);
1237   if (emplace_result.second)
1238     emplace_result.first->second = CreateGlobalVariable(var_uid);
1239 
1240   return emplace_result.first->second;
1241 }
1242 
1243 lldb::TypeSP
1244 SymbolFileNativePDB::GetOrCreateType(llvm::codeview::TypeIndex ti) {
1245   PDB_SymType pdbst = GetPdbSymType(m_index->tpi(), ti);
1246   PdbSymUid tuid = PdbSymUid::makeTypeSymId(pdbst, ti, false);
1247   return GetOrCreateType(tuid);
1248 }
1249 
1250 FunctionSP SymbolFileNativePDB::GetOrCreateFunction(PdbSymUid func_uid,
1251                                                     const SymbolContext &sc) {
1252   lldbassert(func_uid.tag() == PDB_SymType::Function);
1253   auto emplace_result = m_functions.try_emplace(func_uid.toOpaqueId(), nullptr);
1254   if (emplace_result.second)
1255     emplace_result.first->second = CreateFunction(func_uid, sc);
1256 
1257   lldbassert(emplace_result.first->second);
1258   return emplace_result.first->second;
1259 }
1260 
1261 CompUnitSP
1262 SymbolFileNativePDB::GetOrCreateCompileUnit(const CompilandIndexItem &cci) {
1263   auto emplace_result =
1264       m_compilands.try_emplace(cci.m_uid.toOpaqueId(), nullptr);
1265   if (emplace_result.second)
1266     emplace_result.first->second = CreateCompileUnit(cci);
1267 
1268   lldbassert(emplace_result.first->second);
1269   return emplace_result.first->second;
1270 }
1271 
1272 lldb::CompUnitSP SymbolFileNativePDB::ParseCompileUnitAtIndex(uint32_t index) {
1273   if (index >= GetNumCompileUnits())
1274     return CompUnitSP();
1275   lldbassert(index < UINT16_MAX);
1276   if (index >= UINT16_MAX)
1277     return nullptr;
1278 
1279   CompilandIndexItem &item = m_index->compilands().GetOrCreateCompiland(index);
1280 
1281   return GetOrCreateCompileUnit(item);
1282 }
1283 
1284 lldb::LanguageType
1285 SymbolFileNativePDB::ParseCompileUnitLanguage(const SymbolContext &sc) {
1286   // What fields should I expect to be filled out on the SymbolContext?  Is it
1287   // safe to assume that `sc.comp_unit` is valid?
1288   if (!sc.comp_unit)
1289     return lldb::eLanguageTypeUnknown;
1290   PdbSymUid uid = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
1291   lldbassert(uid.tag() == PDB_SymType::Compiland);
1292 
1293   CompilandIndexItem *item = m_index->compilands().GetCompiland(uid);
1294   lldbassert(item);
1295   if (!item->m_compile_opts)
1296     return lldb::eLanguageTypeUnknown;
1297 
1298   return TranslateLanguage(item->m_compile_opts->getLanguage());
1299 }
1300 
1301 size_t SymbolFileNativePDB::ParseCompileUnitFunctions(const SymbolContext &sc) {
1302   lldbassert(sc.comp_unit);
1303   return false;
1304 }
1305 
1306 static bool NeedsResolvedCompileUnit(uint32_t resolve_scope) {
1307   // If any of these flags are set, we need to resolve the compile unit.
1308   uint32_t flags = eSymbolContextCompUnit;
1309   flags |= eSymbolContextVariable;
1310   flags |= eSymbolContextFunction;
1311   flags |= eSymbolContextBlock;
1312   flags |= eSymbolContextLineEntry;
1313   return (resolve_scope & flags) != 0;
1314 }
1315 
1316 uint32_t SymbolFileNativePDB::ResolveSymbolContext(
1317     const Address &addr, SymbolContextItem resolve_scope, SymbolContext &sc) {
1318   uint32_t resolved_flags = 0;
1319   lldb::addr_t file_addr = addr.GetFileAddress();
1320 
1321   if (NeedsResolvedCompileUnit(resolve_scope)) {
1322     llvm::Optional<uint16_t> modi = m_index->GetModuleIndexForVa(file_addr);
1323     if (!modi)
1324       return 0;
1325     PdbSymUid cuid = PdbSymUid::makeCompilandId(*modi);
1326     CompilandIndexItem *cci = m_index->compilands().GetCompiland(cuid);
1327     if (!cci)
1328       return 0;
1329 
1330     sc.comp_unit = GetOrCreateCompileUnit(*cci).get();
1331     resolved_flags |= eSymbolContextCompUnit;
1332   }
1333 
1334   if (resolve_scope & eSymbolContextFunction) {
1335     lldbassert(sc.comp_unit);
1336     std::vector<SymbolAndUid> matches = m_index->FindSymbolsByVa(file_addr);
1337     for (const auto &match : matches) {
1338       if (match.uid.tag() != PDB_SymType::Function)
1339         continue;
1340       sc.function = GetOrCreateFunction(match.uid, sc).get();
1341     }
1342     resolved_flags |= eSymbolContextFunction;
1343   }
1344 
1345   if (resolve_scope & eSymbolContextLineEntry) {
1346     lldbassert(sc.comp_unit);
1347     if (auto *line_table = sc.comp_unit->GetLineTable()) {
1348       if (line_table->FindLineEntryByAddress(addr, sc.line_entry))
1349         resolved_flags |= eSymbolContextLineEntry;
1350     }
1351   }
1352 
1353   return resolved_flags;
1354 }
1355 
1356 static void AppendLineEntryToSequence(LineTable &table, LineSequence &sequence,
1357                                       const CompilandIndexItem &cci,
1358                                       lldb::addr_t base_addr,
1359                                       uint32_t file_number,
1360                                       const LineFragmentHeader &block,
1361                                       const LineNumberEntry &cur) {
1362   LineInfo cur_info(cur.Flags);
1363 
1364   if (cur_info.isAlwaysStepInto() || cur_info.isNeverStepInto())
1365     return;
1366 
1367   uint64_t addr = base_addr + cur.Offset;
1368 
1369   bool is_statement = cur_info.isStatement();
1370   bool is_prologue = IsFunctionPrologue(cci, addr);
1371   bool is_epilogue = IsFunctionEpilogue(cci, addr);
1372 
1373   uint32_t lno = cur_info.getStartLine();
1374 
1375   table.AppendLineEntryToSequence(&sequence, addr, lno, 0, file_number,
1376                                   is_statement, false, is_prologue, is_epilogue,
1377                                   false);
1378 }
1379 
1380 static void TerminateLineSequence(LineTable &table,
1381                                   const LineFragmentHeader &block,
1382                                   lldb::addr_t base_addr, uint32_t file_number,
1383                                   uint32_t last_line,
1384                                   std::unique_ptr<LineSequence> seq) {
1385   // The end is always a terminal entry, so insert it regardless.
1386   table.AppendLineEntryToSequence(seq.get(), base_addr + block.CodeSize,
1387                                   last_line, 0, file_number, false, false,
1388                                   false, false, true);
1389   table.InsertSequence(seq.release());
1390 }
1391 
1392 bool SymbolFileNativePDB::ParseCompileUnitLineTable(const SymbolContext &sc) {
1393   // Unfortunately LLDB is set up to parse the entire compile unit line table
1394   // all at once, even if all it really needs is line info for a specific
1395   // function.  In the future it would be nice if it could set the sc.m_function
1396   // member, and we could only get the line info for the function in question.
1397   lldbassert(sc.comp_unit);
1398   PdbSymUid cu_id = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
1399   lldbassert(cu_id.isCompiland());
1400   CompilandIndexItem *cci = m_index->compilands().GetCompiland(cu_id);
1401   lldbassert(cci);
1402   auto line_table = llvm::make_unique<LineTable>(sc.comp_unit);
1403 
1404   // This is basically a copy of the .debug$S subsections from all original COFF
1405   // object files merged together with address relocations applied.  We are
1406   // looking for all DEBUG_S_LINES subsections.
1407   for (const DebugSubsectionRecord &dssr :
1408        cci->m_debug_stream.getSubsectionsArray()) {
1409     if (dssr.kind() != DebugSubsectionKind::Lines)
1410       continue;
1411 
1412     DebugLinesSubsectionRef lines;
1413     llvm::BinaryStreamReader reader(dssr.getRecordData());
1414     if (auto EC = lines.initialize(reader)) {
1415       llvm::consumeError(std::move(EC));
1416       return false;
1417     }
1418 
1419     const LineFragmentHeader *lfh = lines.header();
1420     uint64_t virtual_addr =
1421         m_index->MakeVirtualAddress(lfh->RelocSegment, lfh->RelocOffset);
1422 
1423     const auto &checksums = cci->m_strings.checksums().getArray();
1424     const auto &strings = cci->m_strings.strings();
1425     for (const LineColumnEntry &group : lines) {
1426       // Indices in this structure are actually offsets of records in the
1427       // DEBUG_S_FILECHECKSUMS subsection.  Those entries then have an index
1428       // into the global PDB string table.
1429       auto iter = checksums.at(group.NameIndex);
1430       if (iter == checksums.end())
1431         continue;
1432 
1433       llvm::Expected<llvm::StringRef> efn =
1434           strings.getString(iter->FileNameOffset);
1435       if (!efn) {
1436         llvm::consumeError(efn.takeError());
1437         continue;
1438       }
1439 
1440       // LLDB wants the index of the file in the list of support files.
1441       auto fn_iter = llvm::find(cci->m_file_list, *efn);
1442       lldbassert(fn_iter != cci->m_file_list.end());
1443       uint32_t file_index = std::distance(cci->m_file_list.begin(), fn_iter);
1444 
1445       std::unique_ptr<LineSequence> sequence(
1446           line_table->CreateLineSequenceContainer());
1447       lldbassert(!group.LineNumbers.empty());
1448 
1449       for (const LineNumberEntry &entry : group.LineNumbers) {
1450         AppendLineEntryToSequence(*line_table, *sequence, *cci, virtual_addr,
1451                                   file_index, *lfh, entry);
1452       }
1453       LineInfo last_line(group.LineNumbers.back().Flags);
1454       TerminateLineSequence(*line_table, *lfh, virtual_addr, file_index,
1455                             last_line.getEndLine(), std::move(sequence));
1456     }
1457   }
1458 
1459   if (line_table->GetSize() == 0)
1460     return false;
1461 
1462   sc.comp_unit->SetLineTable(line_table.release());
1463   return true;
1464 }
1465 
1466 bool SymbolFileNativePDB::ParseCompileUnitDebugMacros(const SymbolContext &sc) {
1467   // PDB doesn't contain information about macros
1468   return false;
1469 }
1470 
1471 bool SymbolFileNativePDB::ParseCompileUnitSupportFiles(
1472     const SymbolContext &sc, FileSpecList &support_files) {
1473   lldbassert(sc.comp_unit);
1474 
1475   PdbSymUid comp_uid = PdbSymUid::fromOpaqueId(sc.comp_unit->GetID());
1476   lldbassert(comp_uid.tag() == PDB_SymType::Compiland);
1477 
1478   const CompilandIndexItem *cci = m_index->compilands().GetCompiland(comp_uid);
1479   lldbassert(cci);
1480 
1481   for (llvm::StringRef f : cci->m_file_list) {
1482     FileSpec::Style style =
1483         f.startswith("/") ? FileSpec::Style::posix : FileSpec::Style::windows;
1484     FileSpec spec(f, style);
1485     support_files.Append(spec);
1486   }
1487 
1488   return true;
1489 }
1490 
1491 bool SymbolFileNativePDB::ParseImportedModules(
1492     const SymbolContext &sc, std::vector<ConstString> &imported_modules) {
1493   // PDB does not yet support module debug info
1494   return false;
1495 }
1496 
1497 size_t SymbolFileNativePDB::ParseFunctionBlocks(const SymbolContext &sc) {
1498   lldbassert(sc.comp_unit && sc.function);
1499   return 0;
1500 }
1501 
1502 void SymbolFileNativePDB::DumpClangAST(Stream &s) {
1503   if (!m_clang)
1504     return;
1505   m_clang->Dump(s);
1506 }
1507 
1508 uint32_t SymbolFileNativePDB::FindGlobalVariables(
1509     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1510     uint32_t max_matches, VariableList &variables) {
1511   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1512 
1513   std::vector<SymbolAndOffset> results = m_index->globals().findRecordsByName(
1514       name.GetStringRef(), m_index->symrecords());
1515   for (const SymbolAndOffset &result : results) {
1516     VariableSP var;
1517     switch (result.second.kind()) {
1518     case SymbolKind::S_GDATA32:
1519     case SymbolKind::S_LDATA32:
1520     case SymbolKind::S_GTHREAD32:
1521     case SymbolKind::S_LTHREAD32: {
1522       PdbSymUid uid = PdbSymUid::makeGlobalVariableUid(result.first);
1523       var = GetOrCreateGlobalVariable(uid);
1524       variables.AddVariable(var);
1525       break;
1526     }
1527     default:
1528       continue;
1529     }
1530   }
1531   return variables.GetSize();
1532 }
1533 
1534 uint32_t SymbolFileNativePDB::FindFunctions(
1535     const ConstString &name, const CompilerDeclContext *parent_decl_ctx,
1536     FunctionNameType name_type_mask, bool include_inlines, bool append,
1537     SymbolContextList &sc_list) {
1538   // For now we only support lookup by method name.
1539   if (!(name_type_mask & eFunctionNameTypeMethod))
1540     return 0;
1541 
1542   using SymbolAndOffset = std::pair<uint32_t, llvm::codeview::CVSymbol>;
1543 
1544   std::vector<SymbolAndOffset> matches = m_index->globals().findRecordsByName(
1545       name.GetStringRef(), m_index->symrecords());
1546   for (const SymbolAndOffset &match : matches) {
1547     if (match.second.kind() != S_PROCREF && match.second.kind() != S_LPROCREF)
1548       continue;
1549     ProcRefSym proc(match.second.kind());
1550     cantFail(SymbolDeserializer::deserializeAs<ProcRefSym>(match.second, proc));
1551 
1552     if (!IsValidRecord(proc))
1553       continue;
1554 
1555     PdbSymUid cuid = PdbSymUid::makeCompilandId(proc);
1556     CompilandIndexItem &cci = m_index->compilands().GetOrCreateCompiland(cuid);
1557     SymbolContext sc;
1558 
1559     sc.comp_unit = GetOrCreateCompileUnit(cci).get();
1560     sc.module_sp = sc.comp_unit->GetModule();
1561     PdbSymUid func_uid = PdbSymUid::makeCuSymId(proc);
1562     sc.function = GetOrCreateFunction(func_uid, sc).get();
1563 
1564     sc_list.Append(sc);
1565   }
1566 
1567   return sc_list.GetSize();
1568 }
1569 
1570 uint32_t SymbolFileNativePDB::FindFunctions(const RegularExpression &regex,
1571                                             bool include_inlines, bool append,
1572                                             SymbolContextList &sc_list) {
1573   return 0;
1574 }
1575 
1576 uint32_t SymbolFileNativePDB::FindTypes(
1577     const SymbolContext &sc, const ConstString &name,
1578     const CompilerDeclContext *parent_decl_ctx, bool append,
1579     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
1580     TypeMap &types) {
1581   if (!append)
1582     types.Clear();
1583   if (!name)
1584     return 0;
1585 
1586   searched_symbol_files.clear();
1587   searched_symbol_files.insert(this);
1588 
1589   // There is an assumption 'name' is not a regex
1590   size_t match_count = FindTypesByName(name.GetStringRef(), max_matches, types);
1591 
1592   return match_count;
1593 }
1594 
1595 size_t
1596 SymbolFileNativePDB::FindTypes(const std::vector<CompilerContext> &context,
1597                                bool append, TypeMap &types) {
1598   return 0;
1599 }
1600 
1601 size_t SymbolFileNativePDB::FindTypesByName(llvm::StringRef name,
1602                                             uint32_t max_matches,
1603                                             TypeMap &types) {
1604 
1605   size_t match_count = 0;
1606   std::vector<TypeIndex> matches = m_index->tpi().findRecordsByName(name);
1607   if (max_matches > 0 && max_matches < matches.size())
1608     matches.resize(max_matches);
1609 
1610   for (TypeIndex ti : matches) {
1611     TypeSP type = GetOrCreateType(ti);
1612     if (!type)
1613       continue;
1614 
1615     types.Insert(type);
1616     ++match_count;
1617   }
1618   return match_count;
1619 }
1620 
1621 size_t SymbolFileNativePDB::ParseTypes(const SymbolContext &sc) { return 0; }
1622 
1623 Type *SymbolFileNativePDB::ResolveTypeUID(lldb::user_id_t type_uid) {
1624   auto iter = m_types.find(type_uid);
1625   // lldb should not be passing us non-sensical type uids.  the only way it
1626   // could have a type uid in the first place is if we handed it out, in which
1627   // case we should know about the type.  However, that doesn't mean we've
1628   // instantiated it yet.  We can vend out a UID for a future type.  So if the
1629   // type doesn't exist, let's instantiate it now.
1630   if (iter != m_types.end())
1631     return &*iter->second;
1632 
1633   PdbSymUid uid = PdbSymUid::fromOpaqueId(type_uid);
1634   lldbassert(uid.isTypeSym(uid.tag()));
1635   const PdbTypeSymId &type_id = uid.asTypeSym();
1636   TypeIndex ti(type_id.index);
1637   if (ti.isNoneType())
1638     return nullptr;
1639 
1640   TypeSP type_sp = CreateAndCacheType(uid);
1641   return &*type_sp;
1642 }
1643 
1644 llvm::Optional<SymbolFile::ArrayInfo>
1645 SymbolFileNativePDB::GetDynamicArrayInfoForUID(
1646     lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1647   return llvm::None;
1648 }
1649 
1650 
1651 bool SymbolFileNativePDB::CompleteType(CompilerType &compiler_type) {
1652   // If this is not in our map, it's an error.
1653   clang::TagDecl *tag_decl = m_clang->GetAsTagDecl(compiler_type);
1654   lldbassert(tag_decl);
1655   auto status_iter = m_decl_to_status.find(tag_decl);
1656   lldbassert(status_iter != m_decl_to_status.end());
1657 
1658   // If it's already complete, just return.
1659   DeclStatus &status = status_iter->second;
1660   if (status.status == Type::eResolveStateFull)
1661     return true;
1662 
1663   PdbSymUid uid = PdbSymUid::fromOpaqueId(status.uid);
1664   lldbassert(uid.tag() == PDB_SymType::UDT || uid.tag() == PDB_SymType::Enum);
1665 
1666   const PdbTypeSymId &type_id = uid.asTypeSym();
1667 
1668   ClangASTContext::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
1669                                          false);
1670 
1671   // In CreateAndCacheType, we already go out of our way to resolve forward
1672   // ref UDTs to full decls, and the uids we vend out always refer to full
1673   // decls if a full decl exists in the debug info.  So if we don't have a full
1674   // decl here, it means one doesn't exist in the debug info, and we can't
1675   // complete the type.
1676   CVType cvt = m_index->tpi().getType(TypeIndex(type_id.index));
1677   if (IsForwardRefUdt(cvt))
1678     return false;
1679 
1680   auto types_iter = m_types.find(uid.toOpaqueId());
1681   lldbassert(types_iter != m_types.end());
1682 
1683   if (cvt.kind() == LF_MODIFIER) {
1684     TypeIndex unmodified_type = LookThroughModifierRecord(cvt);
1685     cvt = m_index->tpi().getType(unmodified_type);
1686     // LF_MODIFIERS usually point to forward decls, so this is the one case
1687     // where we won't have been able to resolve a forward decl to a full decl
1688     // earlier on.  So we need to do that now.
1689     if (IsForwardRefUdt(cvt)) {
1690       llvm::Expected<TypeIndex> expected_full_ti =
1691           m_index->tpi().findFullDeclForForwardRef(unmodified_type);
1692       if (!expected_full_ti) {
1693         llvm::consumeError(expected_full_ti.takeError());
1694         return false;
1695       }
1696       cvt = m_index->tpi().getType(*expected_full_ti);
1697       lldbassert(!IsForwardRefUdt(cvt));
1698       unmodified_type = *expected_full_ti;
1699     }
1700     uid = PdbSymUid::makeTypeSymId(uid.tag(), unmodified_type, false);
1701   }
1702   TypeIndex field_list_ti = GetFieldListIndex(cvt);
1703   CVType field_list_cvt = m_index->tpi().getType(field_list_ti);
1704   if (field_list_cvt.kind() != LF_FIELDLIST)
1705     return false;
1706 
1707   // Visit all members of this class, then perform any finalization necessary
1708   // to complete the class.
1709   UdtRecordCompleter completer(uid, compiler_type, *tag_decl, *this);
1710   auto error =
1711       llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
1712   completer.complete();
1713 
1714   status.status = Type::eResolveStateFull;
1715   if (!error)
1716     return true;
1717 
1718   llvm::consumeError(std::move(error));
1719   return false;
1720 }
1721 
1722 size_t SymbolFileNativePDB::GetTypes(lldb_private::SymbolContextScope *sc_scope,
1723                                      TypeClass type_mask,
1724                                      lldb_private::TypeList &type_list) {
1725   return 0;
1726 }
1727 
1728 CompilerDeclContext
1729 SymbolFileNativePDB::FindNamespace(const SymbolContext &sc,
1730                                    const ConstString &name,
1731                                    const CompilerDeclContext *parent_decl_ctx) {
1732   return {};
1733 }
1734 
1735 TypeSystem *
1736 SymbolFileNativePDB::GetTypeSystemForLanguage(lldb::LanguageType language) {
1737   auto type_system =
1738       m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
1739   if (type_system)
1740     type_system->SetSymbolFile(this);
1741   return type_system;
1742 }
1743 
1744 ConstString SymbolFileNativePDB::GetPluginName() {
1745   static ConstString g_name("pdb");
1746   return g_name;
1747 }
1748 
1749 uint32_t SymbolFileNativePDB::GetPluginVersion() { return 1; }
1750