Coverage Report

Created: 2022-01-22 13:19

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