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