1 //===-- PDBASTParser.cpp --------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "PDBASTParser.h"
10 
11 #include "SymbolFilePDB.h"
12 
13 #include "clang/AST/CharUnits.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 
17 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
18 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
19 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
20 #include "lldb/Core/Declaration.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Symbol/SymbolFile.h"
23 #include "lldb/Symbol/TypeMap.h"
24 #include "lldb/Symbol/TypeSystem.h"
25 #include "lldb/Utility/LLDBLog.h"
26 #include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h"
27 #include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
28 #include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
29 #include "llvm/DebugInfo/PDB/PDBSymbol.h"
30 #include "llvm/DebugInfo/PDB/PDBSymbolData.h"
31 #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
32 #include "llvm/DebugInfo/PDB/PDBSymbolTypeArray.h"
33 #include "llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h"
34 #include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h"
35 #include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
36 #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h"
37 #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"
38 #include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h"
39 #include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
40 #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
41 
42 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
43 #include <optional>
44 
45 using namespace lldb;
46 using namespace lldb_private;
47 using namespace llvm::pdb;
48 
49 static int TranslateUdtKind(PDB_UdtType pdb_kind) {
50   switch (pdb_kind) {
51   case PDB_UdtType::Class:
52     return clang::TTK_Class;
53   case PDB_UdtType::Struct:
54     return clang::TTK_Struct;
55   case PDB_UdtType::Union:
56     return clang::TTK_Union;
57   case PDB_UdtType::Interface:
58     return clang::TTK_Interface;
59   }
60   llvm_unreachable("unsuported PDB UDT type");
61 }
62 
63 static lldb::Encoding TranslateBuiltinEncoding(PDB_BuiltinType type) {
64   switch (type) {
65   case PDB_BuiltinType::Float:
66     return lldb::eEncodingIEEE754;
67   case PDB_BuiltinType::Int:
68   case PDB_BuiltinType::Long:
69   case PDB_BuiltinType::Char:
70     return lldb::eEncodingSint;
71   case PDB_BuiltinType::Bool:
72   case PDB_BuiltinType::Char16:
73   case PDB_BuiltinType::Char32:
74   case PDB_BuiltinType::UInt:
75   case PDB_BuiltinType::ULong:
76   case PDB_BuiltinType::HResult:
77   case PDB_BuiltinType::WCharT:
78     return lldb::eEncodingUint;
79   default:
80     return lldb::eEncodingInvalid;
81   }
82 }
83 
84 static lldb::Encoding TranslateEnumEncoding(PDB_VariantType type) {
85   switch (type) {
86   case PDB_VariantType::Int8:
87   case PDB_VariantType::Int16:
88   case PDB_VariantType::Int32:
89   case PDB_VariantType::Int64:
90     return lldb::eEncodingSint;
91 
92   case PDB_VariantType::UInt8:
93   case PDB_VariantType::UInt16:
94   case PDB_VariantType::UInt32:
95   case PDB_VariantType::UInt64:
96     return lldb::eEncodingUint;
97 
98   default:
99     break;
100   }
101 
102   return lldb::eEncodingSint;
103 }
104 
105 static CompilerType
106 GetBuiltinTypeForPDBEncodingAndBitSize(TypeSystemClang &clang_ast,
107                                        const PDBSymbolTypeBuiltin &pdb_type,
108                                        Encoding encoding, uint32_t width) {
109   clang::ASTContext &ast = clang_ast.getASTContext();
110 
111   switch (pdb_type.getBuiltinType()) {
112   default:
113     break;
114   case PDB_BuiltinType::None:
115     return CompilerType();
116   case PDB_BuiltinType::Void:
117     return clang_ast.GetBasicType(eBasicTypeVoid);
118   case PDB_BuiltinType::Char:
119     return clang_ast.GetBasicType(eBasicTypeChar);
120   case PDB_BuiltinType::Bool:
121     return clang_ast.GetBasicType(eBasicTypeBool);
122   case PDB_BuiltinType::Long:
123     if (width == ast.getTypeSize(ast.LongTy))
124       return CompilerType(clang_ast.weak_from_this(),
125                           ast.LongTy.getAsOpaquePtr());
126     if (width == ast.getTypeSize(ast.LongLongTy))
127       return CompilerType(clang_ast.weak_from_this(),
128                           ast.LongLongTy.getAsOpaquePtr());
129     break;
130   case PDB_BuiltinType::ULong:
131     if (width == ast.getTypeSize(ast.UnsignedLongTy))
132       return CompilerType(clang_ast.weak_from_this(),
133                           ast.UnsignedLongTy.getAsOpaquePtr());
134     if (width == ast.getTypeSize(ast.UnsignedLongLongTy))
135       return CompilerType(clang_ast.weak_from_this(),
136                           ast.UnsignedLongLongTy.getAsOpaquePtr());
137     break;
138   case PDB_BuiltinType::WCharT:
139     if (width == ast.getTypeSize(ast.WCharTy))
140       return CompilerType(clang_ast.weak_from_this(),
141                           ast.WCharTy.getAsOpaquePtr());
142     break;
143   case PDB_BuiltinType::Char16:
144     return CompilerType(clang_ast.weak_from_this(),
145                         ast.Char16Ty.getAsOpaquePtr());
146   case PDB_BuiltinType::Char32:
147     return CompilerType(clang_ast.weak_from_this(),
148                         ast.Char32Ty.getAsOpaquePtr());
149   case PDB_BuiltinType::Float:
150     // Note: types `long double` and `double` have same bit size in MSVC and
151     // there is no information in the PDB to distinguish them. So when falling
152     // back to default search, the compiler type of `long double` will be
153     // represented by the one generated for `double`.
154     break;
155   }
156   // If there is no match on PDB_BuiltinType, fall back to default search by
157   // encoding and width only
158   return clang_ast.GetBuiltinTypeForEncodingAndBitSize(encoding, width);
159 }
160 
161 static ConstString GetPDBBuiltinTypeName(const PDBSymbolTypeBuiltin &pdb_type,
162                                          CompilerType &compiler_type) {
163   PDB_BuiltinType kind = pdb_type.getBuiltinType();
164   switch (kind) {
165   default:
166     break;
167   case PDB_BuiltinType::Currency:
168     return ConstString("CURRENCY");
169   case PDB_BuiltinType::Date:
170     return ConstString("DATE");
171   case PDB_BuiltinType::Variant:
172     return ConstString("VARIANT");
173   case PDB_BuiltinType::Complex:
174     return ConstString("complex");
175   case PDB_BuiltinType::Bitfield:
176     return ConstString("bitfield");
177   case PDB_BuiltinType::BSTR:
178     return ConstString("BSTR");
179   case PDB_BuiltinType::HResult:
180     return ConstString("HRESULT");
181   case PDB_BuiltinType::BCD:
182     return ConstString("BCD");
183   case PDB_BuiltinType::Char16:
184     return ConstString("char16_t");
185   case PDB_BuiltinType::Char32:
186     return ConstString("char32_t");
187   case PDB_BuiltinType::None:
188     return ConstString("...");
189   }
190   return compiler_type.GetTypeName();
191 }
192 
193 static bool GetDeclarationForSymbol(const PDBSymbol &symbol,
194                                     Declaration &decl) {
195   auto &raw_sym = symbol.getRawSymbol();
196   auto first_line_up = raw_sym.getSrcLineOnTypeDefn();
197 
198   if (!first_line_up) {
199     auto lines_up = symbol.getSession().findLineNumbersByAddress(
200         raw_sym.getVirtualAddress(), raw_sym.getLength());
201     if (!lines_up)
202       return false;
203     first_line_up = lines_up->getNext();
204     if (!first_line_up)
205       return false;
206   }
207   uint32_t src_file_id = first_line_up->getSourceFileId();
208   auto src_file_up = symbol.getSession().getSourceFileById(src_file_id);
209   if (!src_file_up)
210     return false;
211 
212   FileSpec spec(src_file_up->getFileName());
213   decl.SetFile(spec);
214   decl.SetColumn(first_line_up->getColumnNumber());
215   decl.SetLine(first_line_up->getLineNumber());
216   return true;
217 }
218 
219 static AccessType TranslateMemberAccess(PDB_MemberAccess access) {
220   switch (access) {
221   case PDB_MemberAccess::Private:
222     return eAccessPrivate;
223   case PDB_MemberAccess::Protected:
224     return eAccessProtected;
225   case PDB_MemberAccess::Public:
226     return eAccessPublic;
227   }
228   return eAccessNone;
229 }
230 
231 static AccessType GetDefaultAccessibilityForUdtKind(PDB_UdtType udt_kind) {
232   switch (udt_kind) {
233   case PDB_UdtType::Struct:
234   case PDB_UdtType::Union:
235     return eAccessPublic;
236   case PDB_UdtType::Class:
237   case PDB_UdtType::Interface:
238     return eAccessPrivate;
239   }
240   llvm_unreachable("unsupported PDB UDT type");
241 }
242 
243 static AccessType GetAccessibilityForUdt(const PDBSymbolTypeUDT &udt) {
244   AccessType access = TranslateMemberAccess(udt.getAccess());
245   if (access != lldb::eAccessNone || !udt.isNested())
246     return access;
247 
248   auto parent = udt.getClassParent();
249   if (!parent)
250     return lldb::eAccessNone;
251 
252   auto parent_udt = llvm::dyn_cast<PDBSymbolTypeUDT>(parent.get());
253   if (!parent_udt)
254     return lldb::eAccessNone;
255 
256   return GetDefaultAccessibilityForUdtKind(parent_udt->getUdtKind());
257 }
258 
259 static clang::MSInheritanceAttr::Spelling
260 GetMSInheritance(const PDBSymbolTypeUDT &udt) {
261   int base_count = 0;
262   bool has_virtual = false;
263 
264   auto bases_enum = udt.findAllChildren<PDBSymbolTypeBaseClass>();
265   if (bases_enum) {
266     while (auto base = bases_enum->getNext()) {
267       base_count++;
268       has_virtual |= base->isVirtualBaseClass();
269     }
270   }
271 
272   if (has_virtual)
273     return clang::MSInheritanceAttr::Keyword_virtual_inheritance;
274   if (base_count > 1)
275     return clang::MSInheritanceAttr::Keyword_multiple_inheritance;
276   return clang::MSInheritanceAttr::Keyword_single_inheritance;
277 }
278 
279 static std::unique_ptr<llvm::pdb::PDBSymbol>
280 GetClassOrFunctionParent(const llvm::pdb::PDBSymbol &symbol) {
281   const IPDBSession &session = symbol.getSession();
282   const IPDBRawSymbol &raw = symbol.getRawSymbol();
283   auto tag = symbol.getSymTag();
284 
285   // For items that are nested inside of a class, return the class that it is
286   // nested inside of.
287   // Note that only certain items can be nested inside of classes.
288   switch (tag) {
289   case PDB_SymType::Function:
290   case PDB_SymType::Data:
291   case PDB_SymType::UDT:
292   case PDB_SymType::Enum:
293   case PDB_SymType::FunctionSig:
294   case PDB_SymType::Typedef:
295   case PDB_SymType::BaseClass:
296   case PDB_SymType::VTable: {
297     auto class_parent_id = raw.getClassParentId();
298     if (auto class_parent = session.getSymbolById(class_parent_id))
299       return class_parent;
300     break;
301   }
302   default:
303     break;
304   }
305 
306   // Otherwise, if it is nested inside of a function, return the function.
307   // Note that only certain items can be nested inside of functions.
308   switch (tag) {
309   case PDB_SymType::Block:
310   case PDB_SymType::Data: {
311     auto lexical_parent_id = raw.getLexicalParentId();
312     auto lexical_parent = session.getSymbolById(lexical_parent_id);
313     if (!lexical_parent)
314       return nullptr;
315 
316     auto lexical_parent_tag = lexical_parent->getSymTag();
317     if (lexical_parent_tag == PDB_SymType::Function)
318       return lexical_parent;
319     if (lexical_parent_tag == PDB_SymType::Exe)
320       return nullptr;
321 
322     return GetClassOrFunctionParent(*lexical_parent);
323   }
324   default:
325     return nullptr;
326   }
327 }
328 
329 static clang::NamedDecl *
330 GetDeclFromContextByName(const clang::ASTContext &ast,
331                          const clang::DeclContext &decl_context,
332                          llvm::StringRef name) {
333   clang::IdentifierInfo &ident = ast.Idents.get(name);
334   clang::DeclarationName decl_name = ast.DeclarationNames.getIdentifier(&ident);
335   clang::DeclContext::lookup_result result = decl_context.lookup(decl_name);
336   if (result.empty())
337     return nullptr;
338 
339   return *result.begin();
340 }
341 
342 static bool IsAnonymousNamespaceName(llvm::StringRef name) {
343   return name == "`anonymous namespace'" || name == "`anonymous-namespace'";
344 }
345 
346 static clang::CallingConv TranslateCallingConvention(PDB_CallingConv pdb_cc) {
347   switch (pdb_cc) {
348   case llvm::codeview::CallingConvention::NearC:
349     return clang::CC_C;
350   case llvm::codeview::CallingConvention::NearStdCall:
351     return clang::CC_X86StdCall;
352   case llvm::codeview::CallingConvention::NearFast:
353     return clang::CC_X86FastCall;
354   case llvm::codeview::CallingConvention::ThisCall:
355     return clang::CC_X86ThisCall;
356   case llvm::codeview::CallingConvention::NearVector:
357     return clang::CC_X86VectorCall;
358   case llvm::codeview::CallingConvention::NearPascal:
359     return clang::CC_X86Pascal;
360   default:
361     assert(false && "Unknown calling convention");
362     return clang::CC_C;
363   }
364 }
365 
366 PDBASTParser::PDBASTParser(lldb_private::TypeSystemClang &ast) : m_ast(ast) {}
367 
368 PDBASTParser::~PDBASTParser() = default;
369 
370 // DebugInfoASTParser interface
371 
372 lldb::TypeSP PDBASTParser::CreateLLDBTypeFromPDBType(const PDBSymbol &type) {
373   Declaration decl;
374   switch (type.getSymTag()) {
375   case PDB_SymType::BaseClass: {
376     auto symbol_file = m_ast.GetSymbolFile();
377     if (!symbol_file)
378       return nullptr;
379 
380     auto ty = symbol_file->ResolveTypeUID(type.getRawSymbol().getTypeId());
381     return ty ? ty->shared_from_this() : nullptr;
382   } break;
383   case PDB_SymType::UDT: {
384     auto udt = llvm::dyn_cast<PDBSymbolTypeUDT>(&type);
385     assert(udt);
386 
387     // Note that, unnamed UDT being typedef-ed is generated as a UDT symbol
388     // other than a Typedef symbol in PDB. For example,
389     //    typedef union { short Row; short Col; } Union;
390     // is generated as a named UDT in PDB:
391     //    union Union { short Row; short Col; }
392     // Such symbols will be handled here.
393 
394     // Some UDT with trival ctor has zero length. Just ignore.
395     if (udt->getLength() == 0)
396       return nullptr;
397 
398     // Ignore unnamed-tag UDTs.
399     std::string name =
400         std::string(MSVCUndecoratedNameParser::DropScope(udt->getName()));
401     if (name.empty())
402       return nullptr;
403 
404     auto decl_context = GetDeclContextContainingSymbol(type);
405 
406     // Check if such an UDT already exists in the current context.
407     // This may occur with const or volatile types. There are separate type
408     // symbols in PDB for types with const or volatile modifiers, but we need
409     // to create only one declaration for them all.
410     Type::ResolveState type_resolve_state;
411     CompilerType clang_type = m_ast.GetTypeForIdentifier<clang::CXXRecordDecl>(
412         ConstString(name), decl_context);
413     if (!clang_type.IsValid()) {
414       auto access = GetAccessibilityForUdt(*udt);
415 
416       auto tag_type_kind = TranslateUdtKind(udt->getUdtKind());
417 
418       ClangASTMetadata metadata;
419       metadata.SetUserID(type.getSymIndexId());
420       metadata.SetIsDynamicCXXType(false);
421 
422       clang_type = m_ast.CreateRecordType(
423           decl_context, OptionalClangModuleID(), access, name, tag_type_kind,
424           lldb::eLanguageTypeC_plus_plus, &metadata);
425       assert(clang_type.IsValid());
426 
427       auto record_decl =
428           m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
429       assert(record_decl);
430       m_uid_to_decl[type.getSymIndexId()] = record_decl;
431 
432       auto inheritance_attr = clang::MSInheritanceAttr::CreateImplicit(
433           m_ast.getASTContext(), GetMSInheritance(*udt));
434       record_decl->addAttr(inheritance_attr);
435 
436       TypeSystemClang::StartTagDeclarationDefinition(clang_type);
437 
438       auto children = udt->findAllChildren();
439       if (!children || children->getChildCount() == 0) {
440         // PDB does not have symbol of forwarder. We assume we get an udt w/o
441         // any fields. Just complete it at this point.
442         TypeSystemClang::CompleteTagDeclarationDefinition(clang_type);
443 
444         TypeSystemClang::SetHasExternalStorage(clang_type.GetOpaqueQualType(),
445                                                false);
446 
447         type_resolve_state = Type::ResolveState::Full;
448       } else {
449         // Add the type to the forward declarations. It will help us to avoid
450         // an endless recursion in CompleteTypeFromUdt function.
451         m_forward_decl_to_uid[record_decl] = type.getSymIndexId();
452 
453         TypeSystemClang::SetHasExternalStorage(clang_type.GetOpaqueQualType(),
454                                                true);
455 
456         type_resolve_state = Type::ResolveState::Forward;
457       }
458     } else
459       type_resolve_state = Type::ResolveState::Forward;
460 
461     if (udt->isConstType())
462       clang_type = clang_type.AddConstModifier();
463 
464     if (udt->isVolatileType())
465       clang_type = clang_type.AddVolatileModifier();
466 
467     GetDeclarationForSymbol(type, decl);
468     return m_ast.GetSymbolFile()->MakeType(
469         type.getSymIndexId(), ConstString(name), udt->getLength(), nullptr,
470         LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, clang_type,
471         type_resolve_state);
472   } break;
473   case PDB_SymType::Enum: {
474     auto enum_type = llvm::dyn_cast<PDBSymbolTypeEnum>(&type);
475     assert(enum_type);
476 
477     std::string name =
478         std::string(MSVCUndecoratedNameParser::DropScope(enum_type->getName()));
479     auto decl_context = GetDeclContextContainingSymbol(type);
480     uint64_t bytes = enum_type->getLength();
481 
482     // Check if such an enum already exists in the current context
483     CompilerType ast_enum = m_ast.GetTypeForIdentifier<clang::EnumDecl>(
484         ConstString(name), decl_context);
485     if (!ast_enum.IsValid()) {
486       auto underlying_type_up = enum_type->getUnderlyingType();
487       if (!underlying_type_up)
488         return nullptr;
489 
490       lldb::Encoding encoding =
491           TranslateBuiltinEncoding(underlying_type_up->getBuiltinType());
492       // FIXME: Type of underlying builtin is always `Int`. We correct it with
493       // the very first enumerator's encoding if any.
494       auto first_child = enum_type->findOneChild<PDBSymbolData>();
495       if (first_child)
496         encoding = TranslateEnumEncoding(first_child->getValue().Type);
497 
498       CompilerType builtin_type;
499       if (bytes > 0)
500         builtin_type = GetBuiltinTypeForPDBEncodingAndBitSize(
501             m_ast, *underlying_type_up, encoding, bytes * 8);
502       else
503         builtin_type = m_ast.GetBasicType(eBasicTypeInt);
504 
505       // FIXME: PDB does not have information about scoped enumeration (Enum
506       // Class). Set it false for now.
507       bool isScoped = false;
508 
509       ast_enum = m_ast.CreateEnumerationType(name, decl_context,
510                                              OptionalClangModuleID(), decl,
511                                              builtin_type, isScoped);
512 
513       auto enum_decl = TypeSystemClang::GetAsEnumDecl(ast_enum);
514       assert(enum_decl);
515       m_uid_to_decl[type.getSymIndexId()] = enum_decl;
516 
517       auto enum_values = enum_type->findAllChildren<PDBSymbolData>();
518       if (enum_values) {
519         while (auto enum_value = enum_values->getNext()) {
520           if (enum_value->getDataKind() != PDB_DataKind::Constant)
521             continue;
522           AddEnumValue(ast_enum, *enum_value);
523         }
524       }
525 
526       if (TypeSystemClang::StartTagDeclarationDefinition(ast_enum))
527         TypeSystemClang::CompleteTagDeclarationDefinition(ast_enum);
528     }
529 
530     if (enum_type->isConstType())
531       ast_enum = ast_enum.AddConstModifier();
532 
533     if (enum_type->isVolatileType())
534       ast_enum = ast_enum.AddVolatileModifier();
535 
536     GetDeclarationForSymbol(type, decl);
537     return m_ast.GetSymbolFile()->MakeType(
538         type.getSymIndexId(), ConstString(name), bytes, nullptr,
539         LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl, ast_enum,
540         lldb_private::Type::ResolveState::Full);
541   } break;
542   case PDB_SymType::Typedef: {
543     auto type_def = llvm::dyn_cast<PDBSymbolTypeTypedef>(&type);
544     assert(type_def);
545 
546     SymbolFile *symbol_file = m_ast.GetSymbolFile();
547     if (!symbol_file)
548       return nullptr;
549 
550     lldb_private::Type *target_type =
551         symbol_file->ResolveTypeUID(type_def->getTypeId());
552     if (!target_type)
553       return nullptr;
554 
555     std::string name =
556         std::string(MSVCUndecoratedNameParser::DropScope(type_def->getName()));
557     auto decl_ctx = GetDeclContextContainingSymbol(type);
558 
559     // Check if such a typedef already exists in the current context
560     CompilerType ast_typedef =
561         m_ast.GetTypeForIdentifier<clang::TypedefNameDecl>(ConstString(name),
562                                                            decl_ctx);
563     if (!ast_typedef.IsValid()) {
564       CompilerType target_ast_type = target_type->GetFullCompilerType();
565 
566       ast_typedef = target_ast_type.CreateTypedef(
567           name.c_str(), m_ast.CreateDeclContext(decl_ctx), 0);
568       if (!ast_typedef)
569         return nullptr;
570 
571       auto typedef_decl = TypeSystemClang::GetAsTypedefDecl(ast_typedef);
572       assert(typedef_decl);
573       m_uid_to_decl[type.getSymIndexId()] = typedef_decl;
574     }
575 
576     if (type_def->isConstType())
577       ast_typedef = ast_typedef.AddConstModifier();
578 
579     if (type_def->isVolatileType())
580       ast_typedef = ast_typedef.AddVolatileModifier();
581 
582     GetDeclarationForSymbol(type, decl);
583     std::optional<uint64_t> size;
584     if (type_def->getLength())
585       size = type_def->getLength();
586     return m_ast.GetSymbolFile()->MakeType(
587         type_def->getSymIndexId(), ConstString(name), size, nullptr,
588         target_type->GetID(), lldb_private::Type::eEncodingIsTypedefUID, decl,
589         ast_typedef, lldb_private::Type::ResolveState::Full);
590   } break;
591   case PDB_SymType::Function:
592   case PDB_SymType::FunctionSig: {
593     std::string name;
594     PDBSymbolTypeFunctionSig *func_sig = nullptr;
595     if (auto pdb_func = llvm::dyn_cast<PDBSymbolFunc>(&type)) {
596       if (pdb_func->isCompilerGenerated())
597         return nullptr;
598 
599       auto sig = pdb_func->getSignature();
600       if (!sig)
601         return nullptr;
602       func_sig = sig.release();
603       // Function type is named.
604       name = std::string(
605           MSVCUndecoratedNameParser::DropScope(pdb_func->getName()));
606     } else if (auto pdb_func_sig =
607                    llvm::dyn_cast<PDBSymbolTypeFunctionSig>(&type)) {
608       func_sig = const_cast<PDBSymbolTypeFunctionSig *>(pdb_func_sig);
609     } else
610       llvm_unreachable("Unexpected PDB symbol!");
611 
612     auto arg_enum = func_sig->getArguments();
613     uint32_t num_args = arg_enum->getChildCount();
614     std::vector<CompilerType> arg_list;
615 
616     bool is_variadic = func_sig->isCVarArgs();
617     // Drop last variadic argument.
618     if (is_variadic)
619       --num_args;
620     for (uint32_t arg_idx = 0; arg_idx < num_args; arg_idx++) {
621       auto arg = arg_enum->getChildAtIndex(arg_idx);
622       if (!arg)
623         break;
624 
625       SymbolFile *symbol_file = m_ast.GetSymbolFile();
626       if (!symbol_file)
627         return nullptr;
628 
629       lldb_private::Type *arg_type =
630           symbol_file->ResolveTypeUID(arg->getSymIndexId());
631       // If there's some error looking up one of the dependent types of this
632       // function signature, bail.
633       if (!arg_type)
634         return nullptr;
635       CompilerType arg_ast_type = arg_type->GetFullCompilerType();
636       arg_list.push_back(arg_ast_type);
637     }
638     lldbassert(arg_list.size() <= num_args);
639 
640     auto pdb_return_type = func_sig->getReturnType();
641     SymbolFile *symbol_file = m_ast.GetSymbolFile();
642     if (!symbol_file)
643       return nullptr;
644 
645     lldb_private::Type *return_type =
646         symbol_file->ResolveTypeUID(pdb_return_type->getSymIndexId());
647     // If there's some error looking up one of the dependent types of this
648     // function signature, bail.
649     if (!return_type)
650       return nullptr;
651     CompilerType return_ast_type = return_type->GetFullCompilerType();
652     uint32_t type_quals = 0;
653     if (func_sig->isConstType())
654       type_quals |= clang::Qualifiers::Const;
655     if (func_sig->isVolatileType())
656       type_quals |= clang::Qualifiers::Volatile;
657     auto cc = TranslateCallingConvention(func_sig->getCallingConvention());
658     CompilerType func_sig_ast_type =
659         m_ast.CreateFunctionType(return_ast_type, arg_list.data(),
660                                  arg_list.size(), is_variadic, type_quals, cc);
661 
662     GetDeclarationForSymbol(type, decl);
663     return m_ast.GetSymbolFile()->MakeType(
664         type.getSymIndexId(), ConstString(name), std::nullopt, nullptr,
665         LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
666         func_sig_ast_type, lldb_private::Type::ResolveState::Full);
667   } break;
668   case PDB_SymType::ArrayType: {
669     auto array_type = llvm::dyn_cast<PDBSymbolTypeArray>(&type);
670     assert(array_type);
671     uint32_t num_elements = array_type->getCount();
672     uint32_t element_uid = array_type->getElementTypeId();
673     std::optional<uint64_t> bytes;
674     if (uint64_t size = array_type->getLength())
675       bytes = size;
676 
677     SymbolFile *symbol_file = m_ast.GetSymbolFile();
678     if (!symbol_file)
679       return nullptr;
680 
681     // If array rank > 0, PDB gives the element type at N=0. So element type
682     // will parsed in the order N=0, N=1,..., N=rank sequentially.
683     lldb_private::Type *element_type = symbol_file->ResolveTypeUID(element_uid);
684     if (!element_type)
685       return nullptr;
686 
687     CompilerType element_ast_type = element_type->GetForwardCompilerType();
688     // If element type is UDT, it needs to be complete.
689     if (TypeSystemClang::IsCXXClassType(element_ast_type) &&
690         !element_ast_type.GetCompleteType()) {
691       if (TypeSystemClang::StartTagDeclarationDefinition(element_ast_type)) {
692         TypeSystemClang::CompleteTagDeclarationDefinition(element_ast_type);
693       } else {
694         // We are not able to start definition.
695         return nullptr;
696       }
697     }
698     CompilerType array_ast_type = m_ast.CreateArrayType(
699         element_ast_type, num_elements, /*is_gnu_vector*/ false);
700     TypeSP type_sp = m_ast.GetSymbolFile()->MakeType(
701         array_type->getSymIndexId(), ConstString(), bytes, nullptr,
702         LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
703         array_ast_type, lldb_private::Type::ResolveState::Full);
704     type_sp->SetEncodingType(element_type);
705     return type_sp;
706   } break;
707   case PDB_SymType::BuiltinType: {
708     auto *builtin_type = llvm::dyn_cast<PDBSymbolTypeBuiltin>(&type);
709     assert(builtin_type);
710     PDB_BuiltinType builtin_kind = builtin_type->getBuiltinType();
711     if (builtin_kind == PDB_BuiltinType::None)
712       return nullptr;
713 
714     std::optional<uint64_t> bytes;
715     if (uint64_t size = builtin_type->getLength())
716       bytes = size;
717     Encoding encoding = TranslateBuiltinEncoding(builtin_kind);
718     CompilerType builtin_ast_type = GetBuiltinTypeForPDBEncodingAndBitSize(
719         m_ast, *builtin_type, encoding, bytes.value_or(0) * 8);
720 
721     if (builtin_type->isConstType())
722       builtin_ast_type = builtin_ast_type.AddConstModifier();
723 
724     if (builtin_type->isVolatileType())
725       builtin_ast_type = builtin_ast_type.AddVolatileModifier();
726 
727     auto type_name = GetPDBBuiltinTypeName(*builtin_type, builtin_ast_type);
728 
729     return m_ast.GetSymbolFile()->MakeType(
730         builtin_type->getSymIndexId(), type_name, bytes, nullptr,
731         LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
732         builtin_ast_type, lldb_private::Type::ResolveState::Full);
733   } break;
734   case PDB_SymType::PointerType: {
735     auto *pointer_type = llvm::dyn_cast<PDBSymbolTypePointer>(&type);
736     assert(pointer_type);
737 
738     SymbolFile *symbol_file = m_ast.GetSymbolFile();
739     if (!symbol_file)
740       return nullptr;
741 
742     Type *pointee_type = symbol_file->ResolveTypeUID(
743         pointer_type->getPointeeType()->getSymIndexId());
744     if (!pointee_type)
745       return nullptr;
746 
747     if (pointer_type->isPointerToDataMember() ||
748         pointer_type->isPointerToMemberFunction()) {
749       auto class_parent_uid = pointer_type->getRawSymbol().getClassParentId();
750       auto class_parent_type = symbol_file->ResolveTypeUID(class_parent_uid);
751       assert(class_parent_type);
752 
753       CompilerType pointer_ast_type;
754       pointer_ast_type = TypeSystemClang::CreateMemberPointerType(
755           class_parent_type->GetLayoutCompilerType(),
756           pointee_type->GetForwardCompilerType());
757       assert(pointer_ast_type);
758 
759       return m_ast.GetSymbolFile()->MakeType(
760           pointer_type->getSymIndexId(), ConstString(),
761           pointer_type->getLength(), nullptr, LLDB_INVALID_UID,
762           lldb_private::Type::eEncodingIsUID, decl, pointer_ast_type,
763           lldb_private::Type::ResolveState::Forward);
764     }
765 
766     CompilerType pointer_ast_type;
767     pointer_ast_type = pointee_type->GetFullCompilerType();
768     if (pointer_type->isReference())
769       pointer_ast_type = pointer_ast_type.GetLValueReferenceType();
770     else if (pointer_type->isRValueReference())
771       pointer_ast_type = pointer_ast_type.GetRValueReferenceType();
772     else
773       pointer_ast_type = pointer_ast_type.GetPointerType();
774 
775     if (pointer_type->isConstType())
776       pointer_ast_type = pointer_ast_type.AddConstModifier();
777 
778     if (pointer_type->isVolatileType())
779       pointer_ast_type = pointer_ast_type.AddVolatileModifier();
780 
781     if (pointer_type->isRestrictedType())
782       pointer_ast_type = pointer_ast_type.AddRestrictModifier();
783 
784     return m_ast.GetSymbolFile()->MakeType(
785         pointer_type->getSymIndexId(), ConstString(), pointer_type->getLength(),
786         nullptr, LLDB_INVALID_UID, lldb_private::Type::eEncodingIsUID, decl,
787         pointer_ast_type, lldb_private::Type::ResolveState::Full);
788   } break;
789   default:
790     break;
791   }
792   return nullptr;
793 }
794 
795 bool PDBASTParser::CompleteTypeFromPDB(
796     lldb_private::CompilerType &compiler_type) {
797   if (GetClangASTImporter().CanImport(compiler_type))
798     return GetClangASTImporter().CompleteType(compiler_type);
799 
800   // Remove the type from the forward declarations to avoid
801   // an endless recursion for types like a linked list.
802   clang::CXXRecordDecl *record_decl =
803       m_ast.GetAsCXXRecordDecl(compiler_type.GetOpaqueQualType());
804   auto uid_it = m_forward_decl_to_uid.find(record_decl);
805   if (uid_it == m_forward_decl_to_uid.end())
806     return true;
807 
808   auto symbol_file = static_cast<SymbolFilePDB *>(
809       m_ast.GetSymbolFile()->GetBackingSymbolFile());
810   if (!symbol_file)
811     return false;
812 
813   std::unique_ptr<PDBSymbol> symbol =
814       symbol_file->GetPDBSession().getSymbolById(uid_it->getSecond());
815   if (!symbol)
816     return false;
817 
818   m_forward_decl_to_uid.erase(uid_it);
819 
820   TypeSystemClang::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
821                                          false);
822 
823   switch (symbol->getSymTag()) {
824   case PDB_SymType::UDT: {
825     auto udt = llvm::dyn_cast<PDBSymbolTypeUDT>(symbol.get());
826     if (!udt)
827       return false;
828 
829     return CompleteTypeFromUDT(*symbol_file, compiler_type, *udt);
830   }
831   default:
832     llvm_unreachable("not a forward clang type decl!");
833   }
834 }
835 
836 clang::Decl *
837 PDBASTParser::GetDeclForSymbol(const llvm::pdb::PDBSymbol &symbol) {
838   uint32_t sym_id = symbol.getSymIndexId();
839   auto it = m_uid_to_decl.find(sym_id);
840   if (it != m_uid_to_decl.end())
841     return it->second;
842 
843   auto symbol_file = static_cast<SymbolFilePDB *>(
844       m_ast.GetSymbolFile()->GetBackingSymbolFile());
845   if (!symbol_file)
846     return nullptr;
847 
848   // First of all, check if the symbol is a member of a class. Resolve the full
849   // class type and return the declaration from the cache if so.
850   auto tag = symbol.getSymTag();
851   if (tag == PDB_SymType::Data || tag == PDB_SymType::Function) {
852     const IPDBSession &session = symbol.getSession();
853     const IPDBRawSymbol &raw = symbol.getRawSymbol();
854 
855     auto class_parent_id = raw.getClassParentId();
856     if (std::unique_ptr<PDBSymbol> class_parent =
857             session.getSymbolById(class_parent_id)) {
858       auto class_parent_type = symbol_file->ResolveTypeUID(class_parent_id);
859       if (!class_parent_type)
860         return nullptr;
861 
862       CompilerType class_parent_ct = class_parent_type->GetFullCompilerType();
863 
864       // Look a declaration up in the cache after completing the class
865       clang::Decl *decl = m_uid_to_decl.lookup(sym_id);
866       if (decl)
867         return decl;
868 
869       // A declaration was not found in the cache. It means that the symbol
870       // has the class parent, but the class doesn't have the symbol in its
871       // children list.
872       if (auto func = llvm::dyn_cast_or_null<PDBSymbolFunc>(&symbol)) {
873         // Try to find a class child method with the same RVA and use its
874         // declaration if found.
875         if (uint32_t rva = func->getRelativeVirtualAddress()) {
876           if (std::unique_ptr<ConcreteSymbolEnumerator<PDBSymbolFunc>>
877                   methods_enum =
878                       class_parent->findAllChildren<PDBSymbolFunc>()) {
879             while (std::unique_ptr<PDBSymbolFunc> method =
880                        methods_enum->getNext()) {
881               if (method->getRelativeVirtualAddress() == rva) {
882                 decl = m_uid_to_decl.lookup(method->getSymIndexId());
883                 if (decl)
884                   break;
885               }
886             }
887           }
888         }
889 
890         // If no class methods with the same RVA were found, then create a new
891         // method. It is possible for template methods.
892         if (!decl)
893           decl = AddRecordMethod(*symbol_file, class_parent_ct, *func);
894       }
895 
896       if (decl)
897         m_uid_to_decl[sym_id] = decl;
898 
899       return decl;
900     }
901   }
902 
903   // If we are here, then the symbol is not belonging to a class and is not
904   // contained in the cache. So create a declaration for it.
905   switch (symbol.getSymTag()) {
906   case PDB_SymType::Data: {
907     auto data = llvm::dyn_cast<PDBSymbolData>(&symbol);
908     assert(data);
909 
910     auto decl_context = GetDeclContextContainingSymbol(symbol);
911     assert(decl_context);
912 
913     // May be the current context is a class really, but we haven't found
914     // any class parent. This happens e.g. in the case of class static
915     // variables - they has two symbols, one is a child of the class when
916     // another is a child of the exe. So always complete the parent and use
917     // an existing declaration if possible.
918     if (auto parent_decl = llvm::dyn_cast_or_null<clang::TagDecl>(decl_context))
919       m_ast.GetCompleteDecl(parent_decl);
920 
921     std::string name =
922         std::string(MSVCUndecoratedNameParser::DropScope(data->getName()));
923 
924     // Check if the current context already contains the symbol with the name.
925     clang::Decl *decl =
926         GetDeclFromContextByName(m_ast.getASTContext(), *decl_context, name);
927     if (!decl) {
928       auto type = symbol_file->ResolveTypeUID(data->getTypeId());
929       if (!type)
930         return nullptr;
931 
932       decl = m_ast.CreateVariableDeclaration(
933           decl_context, OptionalClangModuleID(), name.c_str(),
934           ClangUtil::GetQualType(type->GetLayoutCompilerType()));
935     }
936 
937     m_uid_to_decl[sym_id] = decl;
938 
939     return decl;
940   }
941   case PDB_SymType::Function: {
942     auto func = llvm::dyn_cast<PDBSymbolFunc>(&symbol);
943     assert(func);
944 
945     auto decl_context = GetDeclContextContainingSymbol(symbol);
946     assert(decl_context);
947 
948     std::string name =
949         std::string(MSVCUndecoratedNameParser::DropScope(func->getName()));
950 
951     Type *type = symbol_file->ResolveTypeUID(sym_id);
952     if (!type)
953       return nullptr;
954 
955     auto storage = func->isStatic() ? clang::StorageClass::SC_Static
956                                     : clang::StorageClass::SC_None;
957 
958     auto decl = m_ast.CreateFunctionDeclaration(
959         decl_context, OptionalClangModuleID(), name,
960         type->GetForwardCompilerType(), storage, func->hasInlineAttribute());
961 
962     std::vector<clang::ParmVarDecl *> params;
963     if (std::unique_ptr<PDBSymbolTypeFunctionSig> sig = func->getSignature()) {
964       if (std::unique_ptr<ConcreteSymbolEnumerator<PDBSymbolTypeFunctionArg>>
965               arg_enum = sig->findAllChildren<PDBSymbolTypeFunctionArg>()) {
966         while (std::unique_ptr<PDBSymbolTypeFunctionArg> arg =
967                    arg_enum->getNext()) {
968           Type *arg_type = symbol_file->ResolveTypeUID(arg->getTypeId());
969           if (!arg_type)
970             continue;
971 
972           clang::ParmVarDecl *param = m_ast.CreateParameterDeclaration(
973               decl, OptionalClangModuleID(), nullptr,
974               arg_type->GetForwardCompilerType(), clang::SC_None, true);
975           if (param)
976             params.push_back(param);
977         }
978       }
979     }
980     if (params.size())
981       m_ast.SetFunctionParameters(decl, params);
982 
983     m_uid_to_decl[sym_id] = decl;
984 
985     return decl;
986   }
987   default: {
988     // It's not a variable and not a function, check if it's a type
989     Type *type = symbol_file->ResolveTypeUID(sym_id);
990     if (!type)
991       return nullptr;
992 
993     return m_uid_to_decl.lookup(sym_id);
994   }
995   }
996 }
997 
998 clang::DeclContext *
999 PDBASTParser::GetDeclContextForSymbol(const llvm::pdb::PDBSymbol &symbol) {
1000   if (symbol.getSymTag() == PDB_SymType::Function) {
1001     clang::DeclContext *result =
1002         llvm::dyn_cast_or_null<clang::FunctionDecl>(GetDeclForSymbol(symbol));
1003 
1004     if (result)
1005       m_decl_context_to_uid[result] = symbol.getSymIndexId();
1006 
1007     return result;
1008   }
1009 
1010   auto symbol_file = static_cast<SymbolFilePDB *>(
1011       m_ast.GetSymbolFile()->GetBackingSymbolFile());
1012   if (!symbol_file)
1013     return nullptr;
1014 
1015   auto type = symbol_file->ResolveTypeUID(symbol.getSymIndexId());
1016   if (!type)
1017     return nullptr;
1018 
1019   clang::DeclContext *result =
1020       m_ast.GetDeclContextForType(type->GetForwardCompilerType());
1021 
1022   if (result)
1023     m_decl_context_to_uid[result] = symbol.getSymIndexId();
1024 
1025   return result;
1026 }
1027 
1028 clang::DeclContext *PDBASTParser::GetDeclContextContainingSymbol(
1029     const llvm::pdb::PDBSymbol &symbol) {
1030   auto parent = GetClassOrFunctionParent(symbol);
1031   while (parent) {
1032     if (auto parent_context = GetDeclContextForSymbol(*parent))
1033       return parent_context;
1034 
1035     parent = GetClassOrFunctionParent(*parent);
1036   }
1037 
1038   // We can't find any class or function parent of the symbol. So analyze
1039   // the full symbol name. The symbol may be belonging to a namespace
1040   // or function (or even to a class if it's e.g. a static variable symbol).
1041 
1042   // TODO: Make clang to emit full names for variables in namespaces
1043   // (as MSVC does)
1044 
1045   std::string name(symbol.getRawSymbol().getName());
1046   MSVCUndecoratedNameParser parser(name);
1047   llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
1048   if (specs.empty())
1049     return m_ast.GetTranslationUnitDecl();
1050 
1051   auto symbol_file = static_cast<SymbolFilePDB *>(
1052       m_ast.GetSymbolFile()->GetBackingSymbolFile());
1053   if (!symbol_file)
1054     return m_ast.GetTranslationUnitDecl();
1055 
1056   auto global = symbol_file->GetPDBSession().getGlobalScope();
1057   if (!global)
1058     return m_ast.GetTranslationUnitDecl();
1059 
1060   bool has_type_or_function_parent = false;
1061   clang::DeclContext *curr_context = m_ast.GetTranslationUnitDecl();
1062   for (std::size_t i = 0; i < specs.size() - 1; i++) {
1063     // Check if there is a function or a type with the current context's name.
1064     if (std::unique_ptr<IPDBEnumSymbols> children_enum = global->findChildren(
1065             PDB_SymType::None, specs[i].GetFullName(), NS_CaseSensitive)) {
1066       while (IPDBEnumChildren<PDBSymbol>::ChildTypePtr child =
1067                  children_enum->getNext()) {
1068         if (clang::DeclContext *child_context =
1069                 GetDeclContextForSymbol(*child)) {
1070           // Note that `GetDeclContextForSymbol' retrieves
1071           // a declaration context for functions and types only,
1072           // so if we are here then `child_context' is guaranteed
1073           // a function or a type declaration context.
1074           has_type_or_function_parent = true;
1075           curr_context = child_context;
1076         }
1077       }
1078     }
1079 
1080     // If there were no functions or types above then retrieve a namespace with
1081     // the current context's name. There can be no namespaces inside a function
1082     // or a type. We check it to avoid fake namespaces such as `__l2':
1083     // `N0::N1::CClass::PrivateFunc::__l2::InnerFuncStruct'
1084     if (!has_type_or_function_parent) {
1085       std::string namespace_name = std::string(specs[i].GetBaseName());
1086       const char *namespace_name_c_str =
1087           IsAnonymousNamespaceName(namespace_name) ? nullptr
1088                                                    : namespace_name.data();
1089       clang::NamespaceDecl *namespace_decl =
1090           m_ast.GetUniqueNamespaceDeclaration(
1091               namespace_name_c_str, curr_context, OptionalClangModuleID());
1092 
1093       m_parent_to_namespaces[curr_context].insert(namespace_decl);
1094       m_namespaces.insert(namespace_decl);
1095 
1096       curr_context = namespace_decl;
1097     }
1098   }
1099 
1100   return curr_context;
1101 }
1102 
1103 void PDBASTParser::ParseDeclsForDeclContext(
1104     const clang::DeclContext *decl_context) {
1105   auto symbol_file = static_cast<SymbolFilePDB *>(
1106       m_ast.GetSymbolFile()->GetBackingSymbolFile());
1107   if (!symbol_file)
1108     return;
1109 
1110   IPDBSession &session = symbol_file->GetPDBSession();
1111   auto symbol_up =
1112       session.getSymbolById(m_decl_context_to_uid.lookup(decl_context));
1113   auto global_up = session.getGlobalScope();
1114 
1115   PDBSymbol *symbol;
1116   if (symbol_up)
1117     symbol = symbol_up.get();
1118   else if (global_up)
1119     symbol = global_up.get();
1120   else
1121     return;
1122 
1123   if (auto children = symbol->findAllChildren())
1124     while (auto child = children->getNext())
1125       GetDeclForSymbol(*child);
1126 }
1127 
1128 clang::NamespaceDecl *
1129 PDBASTParser::FindNamespaceDecl(const clang::DeclContext *parent,
1130                                 llvm::StringRef name) {
1131   NamespacesSet *set;
1132   if (parent) {
1133     auto pit = m_parent_to_namespaces.find(parent);
1134     if (pit == m_parent_to_namespaces.end())
1135       return nullptr;
1136 
1137     set = &pit->second;
1138   } else {
1139     set = &m_namespaces;
1140   }
1141   assert(set);
1142 
1143   for (clang::NamespaceDecl *namespace_decl : *set)
1144     if (namespace_decl->getName().equals(name))
1145       return namespace_decl;
1146 
1147   for (clang::NamespaceDecl *namespace_decl : *set)
1148     if (namespace_decl->isAnonymousNamespace())
1149       return FindNamespaceDecl(namespace_decl, name);
1150 
1151   return nullptr;
1152 }
1153 
1154 bool PDBASTParser::AddEnumValue(CompilerType enum_type,
1155                                 const PDBSymbolData &enum_value) {
1156   Declaration decl;
1157   Variant v = enum_value.getValue();
1158   std::string name =
1159       std::string(MSVCUndecoratedNameParser::DropScope(enum_value.getName()));
1160   int64_t raw_value;
1161   switch (v.Type) {
1162   case PDB_VariantType::Int8:
1163     raw_value = v.Value.Int8;
1164     break;
1165   case PDB_VariantType::Int16:
1166     raw_value = v.Value.Int16;
1167     break;
1168   case PDB_VariantType::Int32:
1169     raw_value = v.Value.Int32;
1170     break;
1171   case PDB_VariantType::Int64:
1172     raw_value = v.Value.Int64;
1173     break;
1174   case PDB_VariantType::UInt8:
1175     raw_value = v.Value.UInt8;
1176     break;
1177   case PDB_VariantType::UInt16:
1178     raw_value = v.Value.UInt16;
1179     break;
1180   case PDB_VariantType::UInt32:
1181     raw_value = v.Value.UInt32;
1182     break;
1183   case PDB_VariantType::UInt64:
1184     raw_value = v.Value.UInt64;
1185     break;
1186   default:
1187     return false;
1188   }
1189   CompilerType underlying_type = m_ast.GetEnumerationIntegerType(enum_type);
1190   uint32_t byte_size = m_ast.getASTContext().getTypeSize(
1191       ClangUtil::GetQualType(underlying_type));
1192   auto enum_constant_decl = m_ast.AddEnumerationValueToEnumerationType(
1193       enum_type, decl, name.c_str(), raw_value, byte_size * 8);
1194   if (!enum_constant_decl)
1195     return false;
1196 
1197   m_uid_to_decl[enum_value.getSymIndexId()] = enum_constant_decl;
1198 
1199   return true;
1200 }
1201 
1202 bool PDBASTParser::CompleteTypeFromUDT(
1203     lldb_private::SymbolFile &symbol_file,
1204     lldb_private::CompilerType &compiler_type,
1205     llvm::pdb::PDBSymbolTypeUDT &udt) {
1206   ClangASTImporter::LayoutInfo layout_info;
1207   layout_info.bit_size = udt.getLength() * 8;
1208 
1209   auto nested_enums = udt.findAllChildren<PDBSymbolTypeUDT>();
1210   if (nested_enums)
1211     while (auto nested = nested_enums->getNext())
1212       symbol_file.ResolveTypeUID(nested->getSymIndexId());
1213 
1214   auto bases_enum = udt.findAllChildren<PDBSymbolTypeBaseClass>();
1215   if (bases_enum)
1216     AddRecordBases(symbol_file, compiler_type,
1217                    TranslateUdtKind(udt.getUdtKind()), *bases_enum,
1218                    layout_info);
1219 
1220   auto members_enum = udt.findAllChildren<PDBSymbolData>();
1221   if (members_enum)
1222     AddRecordMembers(symbol_file, compiler_type, *members_enum, layout_info);
1223 
1224   auto methods_enum = udt.findAllChildren<PDBSymbolFunc>();
1225   if (methods_enum)
1226     AddRecordMethods(symbol_file, compiler_type, *methods_enum);
1227 
1228   m_ast.AddMethodOverridesForCXXRecordType(compiler_type.GetOpaqueQualType());
1229   TypeSystemClang::BuildIndirectFields(compiler_type);
1230   TypeSystemClang::CompleteTagDeclarationDefinition(compiler_type);
1231 
1232   clang::CXXRecordDecl *record_decl =
1233       m_ast.GetAsCXXRecordDecl(compiler_type.GetOpaqueQualType());
1234   if (!record_decl)
1235     return static_cast<bool>(compiler_type);
1236 
1237   GetClangASTImporter().SetRecordLayout(record_decl, layout_info);
1238 
1239   return static_cast<bool>(compiler_type);
1240 }
1241 
1242 void PDBASTParser::AddRecordMembers(
1243     lldb_private::SymbolFile &symbol_file,
1244     lldb_private::CompilerType &record_type,
1245     PDBDataSymbolEnumerator &members_enum,
1246     lldb_private::ClangASTImporter::LayoutInfo &layout_info) {
1247   while (auto member = members_enum.getNext()) {
1248     if (member->isCompilerGenerated())
1249       continue;
1250 
1251     auto member_name = member->getName();
1252 
1253     auto member_type = symbol_file.ResolveTypeUID(member->getTypeId());
1254     if (!member_type)
1255       continue;
1256 
1257     auto member_comp_type = member_type->GetLayoutCompilerType();
1258     if (!member_comp_type.GetCompleteType()) {
1259       symbol_file.GetObjectFile()->GetModule()->ReportError(
1260           ":: Class '{0}' has a member '{1}' of type '{2}' "
1261           "which does not have a complete definition.",
1262           record_type.GetTypeName().GetCString(), member_name.c_str(),
1263           member_comp_type.GetTypeName().GetCString());
1264       if (TypeSystemClang::StartTagDeclarationDefinition(member_comp_type))
1265         TypeSystemClang::CompleteTagDeclarationDefinition(member_comp_type);
1266     }
1267 
1268     auto access = TranslateMemberAccess(member->getAccess());
1269 
1270     switch (member->getDataKind()) {
1271     case PDB_DataKind::Member: {
1272       auto location_type = member->getLocationType();
1273 
1274       auto bit_size = member->getLength();
1275       if (location_type == PDB_LocType::ThisRel)
1276         bit_size *= 8;
1277 
1278       auto decl = TypeSystemClang::AddFieldToRecordType(
1279           record_type, member_name.c_str(), member_comp_type, access, bit_size);
1280       if (!decl)
1281         continue;
1282 
1283       m_uid_to_decl[member->getSymIndexId()] = decl;
1284 
1285       auto offset = member->getOffset() * 8;
1286       if (location_type == PDB_LocType::BitField)
1287         offset += member->getBitPosition();
1288 
1289       layout_info.field_offsets.insert(std::make_pair(decl, offset));
1290 
1291       break;
1292     }
1293     case PDB_DataKind::StaticMember: {
1294       auto decl = TypeSystemClang::AddVariableToRecordType(
1295           record_type, member_name.c_str(), member_comp_type, access);
1296       if (!decl)
1297         continue;
1298 
1299       // Static constant members may be a const[expr] declaration.
1300       // Query the symbol's value as the variable initializer if valid.
1301       if (member_comp_type.IsConst()) {
1302         auto value = member->getValue();
1303         clang::QualType qual_type = decl->getType();
1304         unsigned type_width = m_ast.getASTContext().getIntWidth(qual_type);
1305         unsigned constant_width = value.getBitWidth();
1306 
1307         if (qual_type->isIntegralOrEnumerationType()) {
1308           if (type_width >= constant_width) {
1309             TypeSystemClang::SetIntegerInitializerForVariable(
1310                 decl, value.toAPSInt().extOrTrunc(type_width));
1311           } else {
1312             LLDB_LOG(GetLog(LLDBLog::AST),
1313                      "Class '{0}' has a member '{1}' of type '{2}' ({3} bits) "
1314                      "which resolves to a wider constant value ({4} bits). "
1315                      "Ignoring constant.",
1316                      record_type.GetTypeName(), member_name,
1317                      member_comp_type.GetTypeName(), type_width,
1318                      constant_width);
1319           }
1320         } else {
1321           switch (member_comp_type.GetBasicTypeEnumeration()) {
1322           case lldb::eBasicTypeFloat:
1323           case lldb::eBasicTypeDouble:
1324           case lldb::eBasicTypeLongDouble:
1325             if (type_width == constant_width) {
1326               TypeSystemClang::SetFloatingInitializerForVariable(
1327                   decl, value.toAPFloat());
1328               decl->setConstexpr(true);
1329             } else {
1330               LLDB_LOG(GetLog(LLDBLog::AST),
1331                        "Class '{0}' has a member '{1}' of type '{2}' ({3} "
1332                        "bits) which resolves to a constant value of mismatched "
1333                        "width ({4} bits). Ignoring constant.",
1334                        record_type.GetTypeName(), member_name,
1335                        member_comp_type.GetTypeName(), type_width,
1336                        constant_width);
1337             }
1338             break;
1339           default:
1340             break;
1341           }
1342         }
1343       }
1344 
1345       m_uid_to_decl[member->getSymIndexId()] = decl;
1346 
1347       break;
1348     }
1349     default:
1350       llvm_unreachable("unsupported PDB data kind");
1351     }
1352   }
1353 }
1354 
1355 void PDBASTParser::AddRecordBases(
1356     lldb_private::SymbolFile &symbol_file,
1357     lldb_private::CompilerType &record_type, int record_kind,
1358     PDBBaseClassSymbolEnumerator &bases_enum,
1359     lldb_private::ClangASTImporter::LayoutInfo &layout_info) const {
1360   std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> base_classes;
1361 
1362   while (auto base = bases_enum.getNext()) {
1363     auto base_type = symbol_file.ResolveTypeUID(base->getTypeId());
1364     if (!base_type)
1365       continue;
1366 
1367     auto base_comp_type = base_type->GetFullCompilerType();
1368     if (!base_comp_type.GetCompleteType()) {
1369       symbol_file.GetObjectFile()->GetModule()->ReportError(
1370           ":: Class '{0}' has a base class '{1}' "
1371           "which does not have a complete definition.",
1372           record_type.GetTypeName().GetCString(),
1373           base_comp_type.GetTypeName().GetCString());
1374       if (TypeSystemClang::StartTagDeclarationDefinition(base_comp_type))
1375         TypeSystemClang::CompleteTagDeclarationDefinition(base_comp_type);
1376     }
1377 
1378     auto access = TranslateMemberAccess(base->getAccess());
1379 
1380     auto is_virtual = base->isVirtualBaseClass();
1381 
1382     std::unique_ptr<clang::CXXBaseSpecifier> base_spec =
1383         m_ast.CreateBaseClassSpecifier(base_comp_type.GetOpaqueQualType(),
1384                                        access, is_virtual,
1385                                        record_kind == clang::TTK_Class);
1386     lldbassert(base_spec);
1387 
1388     base_classes.push_back(std::move(base_spec));
1389 
1390     if (is_virtual)
1391       continue;
1392 
1393     auto decl = m_ast.GetAsCXXRecordDecl(base_comp_type.GetOpaqueQualType());
1394     if (!decl)
1395       continue;
1396 
1397     auto offset = clang::CharUnits::fromQuantity(base->getOffset());
1398     layout_info.base_offsets.insert(std::make_pair(decl, offset));
1399   }
1400 
1401   m_ast.TransferBaseClasses(record_type.GetOpaqueQualType(),
1402                             std::move(base_classes));
1403 }
1404 
1405 void PDBASTParser::AddRecordMethods(lldb_private::SymbolFile &symbol_file,
1406                                     lldb_private::CompilerType &record_type,
1407                                     PDBFuncSymbolEnumerator &methods_enum) {
1408   while (std::unique_ptr<PDBSymbolFunc> method = methods_enum.getNext())
1409     if (clang::CXXMethodDecl *decl =
1410             AddRecordMethod(symbol_file, record_type, *method))
1411       m_uid_to_decl[method->getSymIndexId()] = decl;
1412 }
1413 
1414 clang::CXXMethodDecl *
1415 PDBASTParser::AddRecordMethod(lldb_private::SymbolFile &symbol_file,
1416                               lldb_private::CompilerType &record_type,
1417                               const llvm::pdb::PDBSymbolFunc &method) const {
1418   std::string name =
1419       std::string(MSVCUndecoratedNameParser::DropScope(method.getName()));
1420 
1421   Type *method_type = symbol_file.ResolveTypeUID(method.getSymIndexId());
1422   // MSVC specific __vecDelDtor.
1423   if (!method_type)
1424     return nullptr;
1425 
1426   CompilerType method_comp_type = method_type->GetFullCompilerType();
1427   if (!method_comp_type.GetCompleteType()) {
1428     symbol_file.GetObjectFile()->GetModule()->ReportError(
1429         ":: Class '{0}' has a method '{1}' whose type cannot be completed.",
1430         record_type.GetTypeName().GetCString(),
1431         method_comp_type.GetTypeName().GetCString());
1432     if (TypeSystemClang::StartTagDeclarationDefinition(method_comp_type))
1433       TypeSystemClang::CompleteTagDeclarationDefinition(method_comp_type);
1434   }
1435 
1436   AccessType access = TranslateMemberAccess(method.getAccess());
1437   if (access == eAccessNone)
1438     access = eAccessPublic;
1439 
1440   // TODO: get mangled name for the method.
1441   return m_ast.AddMethodToCXXRecordType(
1442       record_type.GetOpaqueQualType(), name.c_str(),
1443       /*mangled_name*/ nullptr, method_comp_type, access, method.isVirtual(),
1444       method.isStatic(), method.hasInlineAttribute(),
1445       /*is_explicit*/ false, // FIXME: Need this field in CodeView.
1446       /*is_attr_used*/ false,
1447       /*is_artificial*/ method.isCompilerGenerated());
1448 }
1449