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