1 #include "PdbAstBuilder.h" 2 3 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" 4 #include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h" 5 #include "llvm/DebugInfo/CodeView/RecordName.h" 6 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" 7 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 8 #include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h" 9 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h" 10 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h" 11 #include "llvm/DebugInfo/PDB/Native/DbiStream.h" 12 #include "llvm/DebugInfo/PDB/Native/PublicsStream.h" 13 #include "llvm/DebugInfo/PDB/Native/SymbolStream.h" 14 #include "llvm/DebugInfo/PDB/Native/TpiStream.h" 15 #include "llvm/Demangle/MicrosoftDemangle.h" 16 17 #include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h" 18 #include "lldb/Core/Module.h" 19 #include "lldb/Symbol/ClangASTContext.h" 20 #include "lldb/Symbol/ClangExternalASTSourceCommon.h" 21 #include "lldb/Symbol/ClangUtil.h" 22 #include "lldb/Symbol/ObjectFile.h" 23 #include "lldb/Utility/LLDBAssert.h" 24 25 #include "PdbUtil.h" 26 #include "UdtRecordCompleter.h" 27 28 using namespace lldb_private; 29 using namespace lldb_private::npdb; 30 using namespace llvm::codeview; 31 using namespace llvm::pdb; 32 33 static llvm::Optional<PdbCompilandSymId> FindSymbolScope(PdbIndex &index, 34 PdbCompilandSymId id) { 35 CVSymbol sym = index.ReadSymbolRecord(id); 36 if (symbolOpensScope(sym.kind())) { 37 // If this exact symbol opens a scope, we can just directly access its 38 // parent. 39 id.offset = getScopeParentOffset(sym); 40 // Global symbols have parent offset of 0. Return llvm::None to indicate 41 // this. 42 if (id.offset == 0) 43 return llvm::None; 44 return id; 45 } 46 47 // Otherwise we need to start at the beginning and iterate forward until we 48 // reach (or pass) this particular symbol 49 CompilandIndexItem &cii = index.compilands().GetOrCreateCompiland(id.modi); 50 const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray(); 51 52 auto begin = syms.begin(); 53 auto end = syms.at(id.offset); 54 std::vector<PdbCompilandSymId> scope_stack; 55 56 while (begin != end) { 57 if (id.offset == begin.offset()) { 58 // We have a match! Return the top of the stack 59 if (scope_stack.empty()) 60 return llvm::None; 61 return scope_stack.back(); 62 } 63 if (begin.offset() > id.offset) { 64 // We passed it. We couldn't even find this symbol record. 65 lldbassert(false && "Invalid compiland symbol id!"); 66 return llvm::None; 67 } 68 69 // We haven't found the symbol yet. Check if we need to open or close the 70 // scope stack. 71 if (symbolOpensScope(begin->kind())) { 72 // We can use the end offset of the scope to determine whether or not 73 // we can just outright skip this entire scope. 74 uint32_t scope_end = getScopeEndOffset(*begin); 75 if (scope_end < id.modi) { 76 begin = syms.at(scope_end); 77 } else { 78 // The symbol we're looking for is somewhere in this scope. 79 scope_stack.emplace_back(id.modi, begin.offset()); 80 } 81 } else if (symbolEndsScope(begin->kind())) { 82 scope_stack.pop_back(); 83 } 84 ++begin; 85 } 86 87 return llvm::None; 88 } 89 90 static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) { 91 switch (cr.Kind) { 92 case TypeRecordKind::Class: 93 return clang::TTK_Class; 94 case TypeRecordKind::Struct: 95 return clang::TTK_Struct; 96 case TypeRecordKind::Union: 97 return clang::TTK_Union; 98 case TypeRecordKind::Interface: 99 return clang::TTK_Interface; 100 case TypeRecordKind::Enum: 101 return clang::TTK_Enum; 102 default: 103 lldbassert(false && "Invalid tag record kind!"); 104 return clang::TTK_Struct; 105 } 106 } 107 108 static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) { 109 if (args.empty()) 110 return false; 111 return args.back() == TypeIndex::None(); 112 } 113 114 static bool 115 AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) { 116 for (llvm::ms_demangle::Node *n : scopes) { 117 auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n); 118 if (idn->TemplateParams) 119 return true; 120 } 121 return false; 122 } 123 124 static ClangASTContext &GetClangASTContext(ObjectFile &obj) { 125 TypeSystem *ts = 126 obj.GetModule()->GetTypeSystemForLanguage(lldb::eLanguageTypeC_plus_plus); 127 lldbassert(ts); 128 return static_cast<ClangASTContext &>(*ts); 129 } 130 131 static llvm::Optional<clang::CallingConv> 132 TranslateCallingConvention(llvm::codeview::CallingConvention conv) { 133 using CC = llvm::codeview::CallingConvention; 134 switch (conv) { 135 136 case CC::NearC: 137 case CC::FarC: 138 return clang::CallingConv::CC_C; 139 case CC::NearPascal: 140 case CC::FarPascal: 141 return clang::CallingConv::CC_X86Pascal; 142 case CC::NearFast: 143 case CC::FarFast: 144 return clang::CallingConv::CC_X86FastCall; 145 case CC::NearStdCall: 146 case CC::FarStdCall: 147 return clang::CallingConv::CC_X86StdCall; 148 case CC::ThisCall: 149 return clang::CallingConv::CC_X86ThisCall; 150 case CC::NearVector: 151 return clang::CallingConv::CC_X86VectorCall; 152 default: 153 return llvm::None; 154 } 155 } 156 157 static llvm::Optional<CVTagRecord> 158 GetNestedTagDefinition(const NestedTypeRecord &Record, 159 const CVTagRecord &parent, TpiStream &tpi) { 160 // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it 161 // is also used to indicate the primary definition of a nested class. That is 162 // to say, if you have: 163 // struct A { 164 // struct B {}; 165 // using C = B; 166 // }; 167 // Then in the debug info, this will appear as: 168 // LF_STRUCTURE `A::B` [type index = N] 169 // LF_STRUCTURE `A` 170 // LF_NESTTYPE [name = `B`, index = N] 171 // LF_NESTTYPE [name = `C`, index = N] 172 // In order to accurately reconstruct the decl context hierarchy, we need to 173 // know which ones are actual definitions and which ones are just aliases. 174 175 // If it's a simple type, then this is something like `using foo = int`. 176 if (Record.Type.isSimple()) 177 return llvm::None; 178 179 CVType cvt = tpi.getType(Record.Type); 180 181 if (!IsTagRecord(cvt)) 182 return llvm::None; 183 184 // If it's an inner definition, then treat whatever name we have here as a 185 // single component of a mangled name. So we can inject it into the parent's 186 // mangled name to see if it matches. 187 CVTagRecord child = CVTagRecord::create(cvt); 188 std::string qname = parent.asTag().getUniqueName(); 189 if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4) 190 return llvm::None; 191 192 // qname[3] is the tag type identifier (struct, class, union, etc). Since the 193 // inner tag type is not necessarily the same as the outer tag type, re-write 194 // it to match the inner tag type. 195 qname[3] = child.asTag().getUniqueName()[3]; 196 std::string piece; 197 if (qname[3] == 'W') 198 piece = "4"; 199 piece += Record.Name; 200 piece.push_back('@'); 201 qname.insert(4, std::move(piece)); 202 if (qname != child.asTag().UniqueName) 203 return llvm::None; 204 205 return std::move(child); 206 } 207 208 static bool IsAnonymousNamespaceName(llvm::StringRef name) { 209 return name == "`anonymous namespace'" || name == "`anonymous-namespace'"; 210 } 211 212 PdbAstBuilder::PdbAstBuilder(ObjectFile &obj, PdbIndex &index) 213 : m_index(index), m_clang(GetClangASTContext(obj)) { 214 BuildParentMap(); 215 } 216 217 clang::DeclContext &PdbAstBuilder::GetTranslationUnitDecl() { 218 return *m_clang.GetTranslationUnitDecl(); 219 } 220 221 std::pair<clang::DeclContext *, std::string> 222 PdbAstBuilder::CreateDeclInfoForType(const TagRecord &record, TypeIndex ti) { 223 // FIXME: Move this to GetDeclContextContainingUID. 224 if (!record.hasUniqueName()) 225 return CreateDeclInfoForUndecoratedName(record.Name); 226 227 llvm::ms_demangle::Demangler demangler; 228 StringView sv(record.UniqueName.begin(), record.UniqueName.size()); 229 llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv); 230 if (demangler.Error) 231 return {m_clang.GetTranslationUnitDecl(), record.UniqueName}; 232 233 llvm::ms_demangle::IdentifierNode *idn = 234 ttn->QualifiedName->getUnqualifiedIdentifier(); 235 std::string uname = idn->toString(llvm::ms_demangle::OF_NoTagSpecifier); 236 237 llvm::ms_demangle::NodeArrayNode *name_components = 238 ttn->QualifiedName->Components; 239 llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes, 240 name_components->Count - 1); 241 242 clang::DeclContext *context = m_clang.GetTranslationUnitDecl(); 243 244 // If this type doesn't have a parent type in the debug info, then the best we 245 // can do is to say that it's either a series of namespaces (if the scope is 246 // non-empty), or the translation unit (if the scope is empty). 247 auto parent_iter = m_parent_types.find(ti); 248 if (parent_iter == m_parent_types.end()) { 249 if (scopes.empty()) 250 return {context, uname}; 251 252 // If there is no parent in the debug info, but some of the scopes have 253 // template params, then this is a case of bad debug info. See, for 254 // example, llvm.org/pr39607. We don't want to create an ambiguity between 255 // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at 256 // global scope with the fully qualified name. 257 if (AnyScopesHaveTemplateParams(scopes)) 258 return {context, record.Name}; 259 260 for (llvm::ms_demangle::Node *scope : scopes) { 261 auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope); 262 std::string str = nii->toString(); 263 context = GetOrCreateNamespaceDecl(str.c_str(), *context); 264 } 265 return {context, uname}; 266 } 267 268 // Otherwise, all we need to do is get the parent type of this type and 269 // recurse into our lazy type creation / AST reconstruction logic to get an 270 // LLDB TypeSP for the parent. This will cause the AST to automatically get 271 // the right DeclContext created for any parent. 272 clang::QualType parent_qt = GetOrCreateType(parent_iter->second); 273 274 context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl()); 275 return {context, uname}; 276 } 277 278 void PdbAstBuilder::BuildParentMap() { 279 LazyRandomTypeCollection &types = m_index.tpi().typeCollection(); 280 281 llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full; 282 llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward; 283 284 struct RecordIndices { 285 TypeIndex forward; 286 TypeIndex full; 287 }; 288 289 llvm::StringMap<RecordIndices> record_indices; 290 291 for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) { 292 CVType type = types.getType(*ti); 293 if (!IsTagRecord(type)) 294 continue; 295 296 CVTagRecord tag = CVTagRecord::create(type); 297 298 RecordIndices &indices = record_indices[tag.asTag().getUniqueName()]; 299 if (tag.asTag().isForwardRef()) 300 indices.forward = *ti; 301 else 302 indices.full = *ti; 303 304 if (indices.full != TypeIndex::None() && 305 indices.forward != TypeIndex::None()) { 306 forward_to_full[indices.forward] = indices.full; 307 full_to_forward[indices.full] = indices.forward; 308 } 309 310 // We're looking for LF_NESTTYPE records in the field list, so ignore 311 // forward references (no field list), and anything without a nested class 312 // (since there won't be any LF_NESTTYPE records). 313 if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass()) 314 continue; 315 316 struct ProcessTpiStream : public TypeVisitorCallbacks { 317 ProcessTpiStream(PdbIndex &index, TypeIndex parent, 318 const CVTagRecord &parent_cvt, 319 llvm::DenseMap<TypeIndex, TypeIndex> &parents) 320 : index(index), parents(parents), parent(parent), 321 parent_cvt(parent_cvt) {} 322 323 PdbIndex &index; 324 llvm::DenseMap<TypeIndex, TypeIndex> &parents; 325 326 unsigned unnamed_type_index = 1; 327 TypeIndex parent; 328 const CVTagRecord &parent_cvt; 329 330 llvm::Error visitKnownMember(CVMemberRecord &CVR, 331 NestedTypeRecord &Record) override { 332 std::string unnamed_type_name; 333 if (Record.Name.empty()) { 334 unnamed_type_name = 335 llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str(); 336 Record.Name = unnamed_type_name; 337 ++unnamed_type_index; 338 } 339 llvm::Optional<CVTagRecord> tag = 340 GetNestedTagDefinition(Record, parent_cvt, index.tpi()); 341 if (!tag) 342 return llvm::ErrorSuccess(); 343 344 parents[Record.Type] = parent; 345 return llvm::ErrorSuccess(); 346 } 347 }; 348 349 CVType field_list = m_index.tpi().getType(tag.asTag().FieldList); 350 ProcessTpiStream process(m_index, *ti, tag, m_parent_types); 351 llvm::Error error = visitMemberRecordStream(field_list.data(), process); 352 if (error) 353 llvm::consumeError(std::move(error)); 354 } 355 356 // Now that we know the forward -> full mapping of all type indices, we can 357 // re-write all the indices. At the end of this process, we want a mapping 358 // consisting of fwd -> full and full -> full for all child -> parent indices. 359 // We can re-write the values in place, but for the keys, we must save them 360 // off so that we don't modify the map in place while also iterating it. 361 std::vector<TypeIndex> full_keys; 362 std::vector<TypeIndex> fwd_keys; 363 for (auto &entry : m_parent_types) { 364 TypeIndex key = entry.first; 365 TypeIndex value = entry.second; 366 367 auto iter = forward_to_full.find(value); 368 if (iter != forward_to_full.end()) 369 entry.second = iter->second; 370 371 iter = forward_to_full.find(key); 372 if (iter != forward_to_full.end()) 373 fwd_keys.push_back(key); 374 else 375 full_keys.push_back(key); 376 } 377 for (TypeIndex fwd : fwd_keys) { 378 TypeIndex full = forward_to_full[fwd]; 379 m_parent_types[full] = m_parent_types[fwd]; 380 } 381 for (TypeIndex full : full_keys) { 382 TypeIndex fwd = full_to_forward[full]; 383 m_parent_types[fwd] = m_parent_types[full]; 384 } 385 386 // Now that 387 } 388 389 static bool isLocalVariableType(SymbolKind K) { 390 switch (K) { 391 case S_REGISTER: 392 case S_REGREL32: 393 case S_LOCAL: 394 return true; 395 default: 396 break; 397 } 398 return false; 399 } 400 401 static std::string 402 RenderScopeList(llvm::ArrayRef<llvm::ms_demangle::Node *> nodes) { 403 lldbassert(!nodes.empty()); 404 405 std::string result = nodes.front()->toString(); 406 nodes = nodes.drop_front(); 407 while (!nodes.empty()) { 408 result += "::"; 409 result += nodes.front()->toString(llvm::ms_demangle::OF_NoTagSpecifier); 410 nodes = nodes.drop_front(); 411 } 412 return result; 413 } 414 415 static llvm::Optional<PublicSym32> FindPublicSym(const SegmentOffset &addr, 416 SymbolStream &syms, 417 PublicsStream &publics) { 418 llvm::FixedStreamArray<ulittle32_t> addr_map = publics.getAddressMap(); 419 auto iter = std::lower_bound( 420 addr_map.begin(), addr_map.end(), addr, 421 [&](const ulittle32_t &x, const SegmentOffset &y) { 422 CVSymbol s1 = syms.readRecord(x); 423 lldbassert(s1.kind() == S_PUB32); 424 PublicSym32 p1; 425 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(s1, p1)); 426 if (p1.Segment < y.segment) 427 return true; 428 return p1.Offset < y.offset; 429 }); 430 if (iter == addr_map.end()) 431 return llvm::None; 432 CVSymbol sym = syms.readRecord(*iter); 433 lldbassert(sym.kind() == S_PUB32); 434 PublicSym32 p; 435 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(sym, p)); 436 if (p.Segment == addr.segment && p.Offset == addr.offset) 437 return p; 438 return llvm::None; 439 } 440 441 clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) { 442 CVSymbol cvs = m_index.ReadSymbolRecord(id); 443 444 if (isLocalVariableType(cvs.kind())) { 445 clang::DeclContext *scope = GetParentDeclContext(id); 446 clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope); 447 PdbCompilandSymId scope_id(id.modi, m_decl_to_status[scope_decl].uid); 448 return GetOrCreateVariableDecl(scope_id, id); 449 } 450 451 switch (cvs.kind()) { 452 case S_GPROC32: 453 case S_LPROC32: 454 return GetOrCreateFunctionDecl(id); 455 case S_GDATA32: 456 case S_LDATA32: 457 case S_GTHREAD32: 458 case S_CONSTANT: 459 // global variable 460 return nullptr; 461 case S_BLOCK32: 462 return GetOrCreateBlockDecl(id); 463 default: 464 return nullptr; 465 } 466 } 467 468 clang::Decl *PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) { 469 if (clang::Decl *result = TryGetDecl(uid)) 470 return result; 471 472 clang::Decl *result = nullptr; 473 switch (uid.kind()) { 474 case PdbSymUidKind::CompilandSym: 475 result = GetOrCreateSymbolForId(uid.asCompilandSym()); 476 break; 477 case PdbSymUidKind::Type: { 478 clang::QualType qt = GetOrCreateType(uid.asTypeSym()); 479 if (auto *tag = qt->getAsTagDecl()) { 480 result = tag; 481 break; 482 } 483 return nullptr; 484 } 485 default: 486 return nullptr; 487 } 488 m_uid_to_decl[toOpaqueUid(uid)] = result; 489 return result; 490 } 491 492 clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) { 493 if (uid.kind() == PdbSymUidKind::CompilandSym) { 494 if (uid.asCompilandSym().offset == 0) 495 return &GetTranslationUnitDecl(); 496 } 497 498 clang::Decl *decl = GetOrCreateDeclForUid(uid); 499 if (!decl) 500 return nullptr; 501 502 return clang::Decl::castToDeclContext(decl); 503 } 504 505 std::pair<clang::DeclContext *, std::string> 506 PdbAstBuilder::CreateDeclInfoForUndecoratedName(llvm::StringRef name) { 507 MSVCUndecoratedNameParser parser(name); 508 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers(); 509 510 clang::DeclContext *context = &GetTranslationUnitDecl(); 511 512 llvm::StringRef uname = specs.back().GetBaseName(); 513 specs = specs.drop_back(); 514 if (specs.empty()) 515 return {context, name}; 516 517 llvm::StringRef scope_name = specs.back().GetFullName(); 518 519 // It might be a class name, try that first. 520 std::vector<TypeIndex> types = m_index.tpi().findRecordsByName(scope_name); 521 while (!types.empty()) { 522 clang::QualType qt = GetOrCreateType(types.back()); 523 clang::TagDecl *tag = qt->getAsTagDecl(); 524 if (tag) 525 return {clang::TagDecl::castToDeclContext(tag), uname}; 526 types.pop_back(); 527 } 528 529 // If that fails, treat it as a series of namespaces. 530 for (const MSVCUndecoratedNameSpecifier &spec : specs) { 531 std::string ns_name = spec.GetBaseName().str(); 532 context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context); 533 } 534 return {context, uname}; 535 } 536 537 clang::DeclContext * 538 PdbAstBuilder::GetParentDeclContextForSymbol(const CVSymbol &sym) { 539 if (!SymbolHasAddress(sym)) 540 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first; 541 SegmentOffset addr = GetSegmentAndOffset(sym); 542 llvm::Optional<PublicSym32> pub = 543 FindPublicSym(addr, m_index.symrecords(), m_index.publics()); 544 if (!pub) 545 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first; 546 547 llvm::ms_demangle::Demangler demangler; 548 StringView name{pub->Name.begin(), pub->Name.size()}; 549 llvm::ms_demangle::SymbolNode *node = demangler.parse(name); 550 if (!node) 551 return &GetTranslationUnitDecl(); 552 llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{ 553 node->Name->Components->Nodes, node->Name->Components->Count - 1}; 554 555 if (!name_components.empty()) { 556 // Render the current list of scope nodes as a fully qualified name, and 557 // look it up in the debug info as a type name. If we find something, 558 // this is a type (which may itself be prefixed by a namespace). If we 559 // don't, this is a list of namespaces. 560 std::string qname = RenderScopeList(name_components); 561 std::vector<TypeIndex> matches = m_index.tpi().findRecordsByName(qname); 562 while (!matches.empty()) { 563 clang::QualType qt = GetOrCreateType(matches.back()); 564 clang::TagDecl *tag = qt->getAsTagDecl(); 565 if (tag) 566 return clang::TagDecl::castToDeclContext(tag); 567 matches.pop_back(); 568 } 569 } 570 571 // It's not a type. It must be a series of namespaces. 572 clang::DeclContext *context = &GetTranslationUnitDecl(); 573 while (!name_components.empty()) { 574 std::string ns = name_components.front()->toString(); 575 context = GetOrCreateNamespaceDecl(ns.c_str(), *context); 576 name_components = name_components.drop_front(); 577 } 578 return context; 579 } 580 581 clang::DeclContext *PdbAstBuilder::GetParentDeclContext(PdbSymUid uid) { 582 // We must do this *without* calling GetOrCreate on the current uid, as 583 // that would be an infinite recursion. 584 switch (uid.kind()) { 585 case PdbSymUidKind::CompilandSym: { 586 llvm::Optional<PdbCompilandSymId> scope = 587 FindSymbolScope(m_index, uid.asCompilandSym()); 588 if (scope) 589 return GetOrCreateDeclContextForUid(*scope); 590 591 CVSymbol sym = m_index.ReadSymbolRecord(uid.asCompilandSym()); 592 return GetParentDeclContextForSymbol(sym); 593 } 594 case PdbSymUidKind::Type: { 595 // It could be a namespace, class, or global. We don't support nested 596 // functions yet. Anyway, we just need to consult the parent type map. 597 PdbTypeSymId type_id = uid.asTypeSym(); 598 auto iter = m_parent_types.find(type_id.index); 599 if (iter == m_parent_types.end()) 600 return &GetTranslationUnitDecl(); 601 return GetOrCreateDeclContextForUid(PdbTypeSymId(iter->second)); 602 } 603 case PdbSymUidKind::FieldListMember: 604 // In this case the parent DeclContext is the one for the class that this 605 // member is inside of. 606 break; 607 case PdbSymUidKind::GlobalSym: { 608 // If this refers to a compiland symbol, just recurse in with that symbol. 609 // The only other possibilities are S_CONSTANT and S_UDT, in which case we 610 // need to parse the undecorated name to figure out the scope, then look 611 // that up in the TPI stream. If it's found, it's a type, othewrise it's 612 // a series of namespaces. 613 // FIXME: do this. 614 CVSymbol global = m_index.ReadSymbolRecord(uid.asGlobalSym()); 615 switch (global.kind()) { 616 case SymbolKind::S_GDATA32: 617 case SymbolKind::S_LDATA32: 618 return GetParentDeclContextForSymbol(global); 619 case SymbolKind::S_PROCREF: 620 case SymbolKind::S_LPROCREF: { 621 ProcRefSym ref{global.kind()}; 622 llvm::cantFail( 623 SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref)); 624 PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset}; 625 return GetParentDeclContext(cu_sym_id); 626 } 627 case SymbolKind::S_CONSTANT: 628 case SymbolKind::S_UDT: 629 return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first; 630 default: 631 break; 632 } 633 break; 634 } 635 default: 636 break; 637 } 638 return &GetTranslationUnitDecl(); 639 } 640 641 bool PdbAstBuilder::CompleteType(clang::QualType qt) { 642 clang::TagDecl *tag = qt->getAsTagDecl(); 643 if (!tag) 644 return false; 645 646 return CompleteTagDecl(*tag); 647 } 648 649 bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) { 650 // If this is not in our map, it's an error. 651 auto status_iter = m_decl_to_status.find(&tag); 652 lldbassert(status_iter != m_decl_to_status.end()); 653 654 // If it's already complete, just return. 655 DeclStatus &status = status_iter->second; 656 if (status.resolved) 657 return true; 658 659 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym(); 660 661 lldbassert(IsTagRecord(type_id, m_index.tpi())); 662 663 clang::QualType tag_qt = m_clang.getASTContext()->getTypeDeclType(&tag); 664 ClangASTContext::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false); 665 666 TypeIndex tag_ti = type_id.index; 667 CVType cvt = m_index.tpi().getType(tag_ti); 668 if (cvt.kind() == LF_MODIFIER) 669 tag_ti = LookThroughModifierRecord(cvt); 670 671 PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi()); 672 cvt = m_index.tpi().getType(best_ti.index); 673 lldbassert(IsTagRecord(cvt)); 674 675 if (IsForwardRefUdt(cvt)) { 676 // If we can't find a full decl for this forward ref anywhere in the debug 677 // info, then we have no way to complete it. 678 return false; 679 } 680 681 TypeIndex field_list_ti = GetFieldListIndex(cvt); 682 CVType field_list_cvt = m_index.tpi().getType(field_list_ti); 683 if (field_list_cvt.kind() != LF_FIELDLIST) 684 return false; 685 686 // Visit all members of this class, then perform any finalization necessary 687 // to complete the class. 688 CompilerType ct = ToCompilerType(tag_qt); 689 UdtRecordCompleter completer(best_ti, ct, tag, *this, m_index.tpi()); 690 auto error = 691 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer); 692 completer.complete(); 693 694 status.resolved = true; 695 if (!error) 696 return true; 697 698 llvm::consumeError(std::move(error)); 699 return false; 700 } 701 702 clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) { 703 if (ti == TypeIndex::NullptrT()) 704 return GetBasicType(lldb::eBasicTypeNullPtr); 705 706 if (ti.getSimpleMode() != SimpleTypeMode::Direct) { 707 clang::QualType direct_type = GetOrCreateType(ti.makeDirect()); 708 return m_clang.getASTContext()->getPointerType(direct_type); 709 } 710 711 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated) 712 return {}; 713 714 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind()); 715 if (bt == lldb::eBasicTypeInvalid) 716 return {}; 717 718 return GetBasicType(bt); 719 } 720 721 clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) { 722 clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType); 723 724 // This can happen for pointers to LF_VTSHAPE records, which we shouldn't 725 // create in the AST. 726 if (pointee_type.isNull()) 727 return {}; 728 729 if (pointer.isPointerToMember()) { 730 MemberPointerInfo mpi = pointer.getMemberInfo(); 731 clang::QualType class_type = GetOrCreateType(mpi.ContainingType); 732 733 return m_clang.getASTContext()->getMemberPointerType( 734 pointee_type, class_type.getTypePtr()); 735 } 736 737 clang::QualType pointer_type; 738 if (pointer.getMode() == PointerMode::LValueReference) 739 pointer_type = 740 m_clang.getASTContext()->getLValueReferenceType(pointee_type); 741 else if (pointer.getMode() == PointerMode::RValueReference) 742 pointer_type = 743 m_clang.getASTContext()->getRValueReferenceType(pointee_type); 744 else 745 pointer_type = m_clang.getASTContext()->getPointerType(pointee_type); 746 747 if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None) 748 pointer_type.addConst(); 749 750 if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None) 751 pointer_type.addVolatile(); 752 753 if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None) 754 pointer_type.addRestrict(); 755 756 return pointer_type; 757 } 758 759 clang::QualType 760 PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) { 761 clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType); 762 if (unmodified_type.isNull()) 763 return {}; 764 765 if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None) 766 unmodified_type.addConst(); 767 if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None) 768 unmodified_type.addVolatile(); 769 770 return unmodified_type; 771 } 772 773 clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id, 774 const TagRecord &record) { 775 clang::DeclContext *context = nullptr; 776 std::string uname; 777 std::tie(context, uname) = CreateDeclInfoForType(record, id.index); 778 clang::TagTypeKind ttk = TranslateUdtKind(record); 779 lldb::AccessType access = 780 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic; 781 782 ClangASTMetadata metadata; 783 metadata.SetUserID(toOpaqueUid(id)); 784 metadata.SetIsDynamicCXXType(false); 785 786 CompilerType ct = 787 m_clang.CreateRecordType(context, access, uname.c_str(), ttk, 788 lldb::eLanguageTypeC_plus_plus, &metadata); 789 790 lldbassert(ct.IsValid()); 791 792 ClangASTContext::StartTagDeclarationDefinition(ct); 793 794 // Even if it's possible, don't complete it at this point. Just mark it 795 // forward resolved, and if/when LLDB needs the full definition, it can 796 // ask us. 797 clang::QualType result = 798 clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType()); 799 800 ClangASTContext::SetHasExternalStorage(result.getAsOpaquePtr(), true); 801 return result; 802 } 803 804 clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const { 805 auto iter = m_uid_to_decl.find(toOpaqueUid(uid)); 806 if (iter != m_uid_to_decl.end()) 807 return iter->second; 808 return nullptr; 809 } 810 811 clang::NamespaceDecl * 812 PdbAstBuilder::GetOrCreateNamespaceDecl(const char *name, 813 clang::DeclContext &context) { 814 return m_clang.GetUniqueNamespaceDeclaration( 815 IsAnonymousNamespaceName(name) ? nullptr : name, &context); 816 } 817 818 clang::BlockDecl * 819 PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) { 820 if (clang::Decl *decl = TryGetDecl(block_id)) 821 return llvm::dyn_cast<clang::BlockDecl>(decl); 822 823 clang::DeclContext *scope = GetParentDeclContext(block_id); 824 825 clang::BlockDecl *block_decl = m_clang.CreateBlockDeclaration(scope); 826 m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl}); 827 828 DeclStatus status; 829 status.resolved = true; 830 status.uid = toOpaqueUid(block_id); 831 m_decl_to_status.insert({block_decl, status}); 832 833 return block_decl; 834 } 835 836 clang::VarDecl *PdbAstBuilder::CreateVariableDecl(PdbSymUid uid, CVSymbol sym, 837 clang::DeclContext &scope) { 838 VariableInfo var_info = GetVariableNameInfo(sym); 839 clang::QualType qt = GetOrCreateType(var_info.type); 840 841 clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration( 842 &scope, var_info.name.str().c_str(), qt); 843 844 m_uid_to_decl[toOpaqueUid(uid)] = var_decl; 845 DeclStatus status; 846 status.resolved = true; 847 status.uid = toOpaqueUid(uid); 848 m_decl_to_status.insert({var_decl, status}); 849 return var_decl; 850 } 851 852 clang::VarDecl * 853 PdbAstBuilder::GetOrCreateVariableDecl(PdbCompilandSymId scope_id, 854 PdbCompilandSymId var_id) { 855 if (clang::Decl *decl = TryGetDecl(var_id)) 856 return llvm::dyn_cast<clang::VarDecl>(decl); 857 858 clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id); 859 860 CVSymbol sym = m_index.ReadSymbolRecord(var_id); 861 return CreateVariableDecl(PdbSymUid(var_id), sym, *scope); 862 } 863 864 clang::VarDecl *PdbAstBuilder::GetOrCreateVariableDecl(PdbGlobalSymId var_id) { 865 if (clang::Decl *decl = TryGetDecl(var_id)) 866 return llvm::dyn_cast<clang::VarDecl>(decl); 867 868 CVSymbol sym = m_index.ReadSymbolRecord(var_id); 869 return CreateVariableDecl(PdbSymUid(var_id), sym, GetTranslationUnitDecl()); 870 } 871 872 clang::TypedefNameDecl * 873 PdbAstBuilder::GetOrCreateTypedefDecl(PdbGlobalSymId id) { 874 if (clang::Decl *decl = TryGetDecl(id)) 875 return llvm::dyn_cast<clang::TypedefNameDecl>(decl); 876 877 CVSymbol sym = m_index.ReadSymbolRecord(id); 878 lldbassert(sym.kind() == S_UDT); 879 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym)); 880 881 clang::DeclContext *scope = GetParentDeclContext(id); 882 883 PdbTypeSymId real_type_id{udt.Type, false}; 884 clang::QualType qt = GetOrCreateType(real_type_id); 885 886 std::string uname = DropNameScope(udt.Name); 887 888 CompilerType ct = m_clang.CreateTypedefType(ToCompilerType(qt), uname.c_str(), 889 ToCompilerDeclContext(*scope)); 890 clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct); 891 DeclStatus status; 892 status.resolved = true; 893 status.uid = toOpaqueUid(id); 894 m_decl_to_status.insert({tnd, status}); 895 return tnd; 896 } 897 898 clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) { 899 CompilerType ct = m_clang.GetBasicType(type); 900 return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType()); 901 } 902 903 clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) { 904 if (type.index.isSimple()) 905 return CreateSimpleType(type.index); 906 907 CVType cvt = m_index.tpi().getType(type.index); 908 909 if (cvt.kind() == LF_MODIFIER) { 910 ModifierRecord modifier; 911 llvm::cantFail( 912 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)); 913 return CreateModifierType(modifier); 914 } 915 916 if (cvt.kind() == LF_POINTER) { 917 PointerRecord pointer; 918 llvm::cantFail( 919 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)); 920 return CreatePointerType(pointer); 921 } 922 923 if (IsTagRecord(cvt)) { 924 CVTagRecord tag = CVTagRecord::create(cvt); 925 if (tag.kind() == CVTagRecord::Union) 926 return CreateRecordType(type.index, tag.asUnion()); 927 if (tag.kind() == CVTagRecord::Enum) 928 return CreateEnumType(type.index, tag.asEnum()); 929 return CreateRecordType(type.index, tag.asClass()); 930 } 931 932 if (cvt.kind() == LF_ARRAY) { 933 ArrayRecord ar; 934 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)); 935 return CreateArrayType(ar); 936 } 937 938 if (cvt.kind() == LF_PROCEDURE) { 939 ProcedureRecord pr; 940 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); 941 return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv); 942 } 943 944 if (cvt.kind() == LF_MFUNCTION) { 945 MemberFunctionRecord mfr; 946 llvm::cantFail( 947 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)); 948 return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv); 949 } 950 951 return {}; 952 } 953 954 clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) { 955 lldb::user_id_t uid = toOpaqueUid(type); 956 auto iter = m_uid_to_type.find(uid); 957 if (iter != m_uid_to_type.end()) 958 return iter->second; 959 960 PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi()); 961 962 clang::QualType qt; 963 if (best_type.index != type.index) { 964 // This is a forward decl. Call GetOrCreate on the full decl, then map the 965 // forward decl id to the full decl QualType. 966 clang::QualType qt = GetOrCreateType(best_type); 967 m_uid_to_type[toOpaqueUid(type)] = qt; 968 return qt; 969 } 970 971 // This is either a full decl, or a forward decl with no matching full decl 972 // in the debug info. 973 qt = CreateType(type); 974 m_uid_to_type[toOpaqueUid(type)] = qt; 975 if (IsTagRecord(type, m_index.tpi())) { 976 clang::TagDecl *tag = qt->getAsTagDecl(); 977 lldbassert(m_decl_to_status.count(tag) == 0); 978 979 DeclStatus &status = m_decl_to_status[tag]; 980 status.uid = uid; 981 status.resolved = false; 982 } 983 return qt; 984 } 985 986 clang::FunctionDecl * 987 PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) { 988 if (clang::Decl *decl = TryGetDecl(func_id)) 989 return llvm::dyn_cast<clang::FunctionDecl>(decl); 990 991 clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id)); 992 std::string context_name; 993 if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) { 994 context_name = ns->getQualifiedNameAsString(); 995 } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) { 996 context_name = tag->getQualifiedNameAsString(); 997 } 998 999 CVSymbol cvs = m_index.ReadSymbolRecord(func_id); 1000 ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind())); 1001 llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc)); 1002 1003 PdbTypeSymId type_id(proc.FunctionType); 1004 clang::QualType qt = GetOrCreateType(type_id); 1005 if (qt.isNull()) 1006 return nullptr; 1007 1008 clang::StorageClass storage = clang::SC_None; 1009 if (proc.Kind == SymbolRecordKind::ProcSym) 1010 storage = clang::SC_Static; 1011 1012 const clang::FunctionProtoType *func_type = 1013 llvm::dyn_cast<clang::FunctionProtoType>(qt); 1014 1015 CompilerType func_ct = ToCompilerType(qt); 1016 1017 llvm::StringRef proc_name = proc.Name; 1018 proc_name.consume_front(context_name); 1019 proc_name.consume_front("::"); 1020 1021 clang::FunctionDecl *function_decl = m_clang.CreateFunctionDeclaration( 1022 parent, proc_name.str().c_str(), func_ct, storage, false); 1023 1024 lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0); 1025 m_uid_to_decl[toOpaqueUid(func_id)] = function_decl; 1026 DeclStatus status; 1027 status.resolved = true; 1028 status.uid = toOpaqueUid(func_id); 1029 m_decl_to_status.insert({function_decl, status}); 1030 1031 CreateFunctionParameters(func_id, *function_decl, func_type->getNumParams()); 1032 1033 return function_decl; 1034 } 1035 1036 void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id, 1037 clang::FunctionDecl &function_decl, 1038 uint32_t param_count) { 1039 CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi); 1040 CVSymbolArray scope = 1041 cii->m_debug_stream.getSymbolArrayForScope(func_id.offset); 1042 1043 auto begin = scope.begin(); 1044 auto end = scope.end(); 1045 std::vector<clang::ParmVarDecl *> params; 1046 while (begin != end && param_count > 0) { 1047 uint32_t record_offset = begin.offset(); 1048 CVSymbol sym = *begin++; 1049 1050 TypeIndex param_type; 1051 llvm::StringRef param_name; 1052 switch (sym.kind()) { 1053 case S_REGREL32: { 1054 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym); 1055 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg)); 1056 param_type = reg.Type; 1057 param_name = reg.Name; 1058 break; 1059 } 1060 case S_REGISTER: { 1061 RegisterSym reg(SymbolRecordKind::RegisterSym); 1062 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg)); 1063 param_type = reg.Index; 1064 param_name = reg.Name; 1065 break; 1066 } 1067 case S_LOCAL: { 1068 LocalSym local(SymbolRecordKind::LocalSym); 1069 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local)); 1070 if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None) 1071 continue; 1072 param_type = local.Type; 1073 param_name = local.Name; 1074 break; 1075 } 1076 case S_BLOCK32: 1077 // All parameters should come before the first block. If that isn't the 1078 // case, then perhaps this is bad debug info that doesn't contain 1079 // information about all parameters. 1080 return; 1081 default: 1082 continue; 1083 } 1084 1085 PdbCompilandSymId param_uid(func_id.modi, record_offset); 1086 clang::QualType qt = GetOrCreateType(param_type); 1087 1088 CompilerType param_type_ct(&m_clang, qt.getAsOpaquePtr()); 1089 clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration( 1090 &function_decl, param_name.str().c_str(), param_type_ct, 1091 clang::SC_None); 1092 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0); 1093 1094 m_uid_to_decl[toOpaqueUid(param_uid)] = param; 1095 params.push_back(param); 1096 --param_count; 1097 } 1098 1099 if (!params.empty()) 1100 m_clang.SetFunctionParameters(&function_decl, params.data(), params.size()); 1101 } 1102 1103 clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id, 1104 const EnumRecord &er) { 1105 clang::DeclContext *decl_context = nullptr; 1106 std::string uname; 1107 std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index); 1108 clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType); 1109 1110 Declaration declaration; 1111 CompilerType enum_ct = m_clang.CreateEnumerationType( 1112 uname.c_str(), decl_context, declaration, ToCompilerType(underlying_type), 1113 er.isScoped()); 1114 1115 ClangASTContext::StartTagDeclarationDefinition(enum_ct); 1116 ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true); 1117 1118 return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType()); 1119 } 1120 1121 clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) { 1122 clang::QualType element_type = GetOrCreateType(ar.ElementType); 1123 1124 uint64_t element_count = 1125 ar.Size / GetSizeOfType({ar.ElementType}, m_index.tpi()); 1126 1127 CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type), 1128 element_count, false); 1129 return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType()); 1130 } 1131 1132 clang::QualType PdbAstBuilder::CreateFunctionType( 1133 TypeIndex args_type_idx, TypeIndex return_type_idx, 1134 llvm::codeview::CallingConvention calling_convention) { 1135 TpiStream &stream = m_index.tpi(); 1136 CVType args_cvt = stream.getType(args_type_idx); 1137 ArgListRecord args; 1138 llvm::cantFail( 1139 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args)); 1140 1141 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices); 1142 bool is_variadic = IsCVarArgsFunction(arg_indices); 1143 if (is_variadic) 1144 arg_indices = arg_indices.drop_back(); 1145 1146 std::vector<CompilerType> arg_types; 1147 arg_types.reserve(arg_indices.size()); 1148 1149 for (TypeIndex arg_index : arg_indices) { 1150 clang::QualType arg_type = GetOrCreateType(arg_index); 1151 arg_types.push_back(ToCompilerType(arg_type)); 1152 } 1153 1154 clang::QualType return_type = GetOrCreateType(return_type_idx); 1155 1156 llvm::Optional<clang::CallingConv> cc = 1157 TranslateCallingConvention(calling_convention); 1158 if (!cc) 1159 return {}; 1160 1161 CompilerType return_ct = ToCompilerType(return_type); 1162 CompilerType func_sig_ast_type = m_clang.CreateFunctionType( 1163 return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc); 1164 1165 return clang::QualType::getFromOpaquePtr( 1166 func_sig_ast_type.GetOpaqueQualType()); 1167 } 1168 1169 static bool isTagDecl(clang::DeclContext &context) { 1170 return !!llvm::dyn_cast<clang::TagDecl>(&context); 1171 } 1172 1173 static bool isFunctionDecl(clang::DeclContext &context) { 1174 return !!llvm::dyn_cast<clang::FunctionDecl>(&context); 1175 } 1176 1177 static bool isBlockDecl(clang::DeclContext &context) { 1178 return !!llvm::dyn_cast<clang::BlockDecl>(&context); 1179 } 1180 1181 void PdbAstBuilder::ParseAllNamespacesPlusChildrenOf( 1182 llvm::Optional<llvm::StringRef> parent) { 1183 TypeIndex ti{m_index.tpi().TypeIndexBegin()}; 1184 for (const CVType &cvt : m_index.tpi().typeArray()) { 1185 PdbTypeSymId tid{ti}; 1186 ++ti; 1187 1188 if (!IsTagRecord(cvt)) 1189 continue; 1190 1191 CVTagRecord tag = CVTagRecord::create(cvt); 1192 1193 if (!parent.hasValue()) { 1194 clang::QualType qt = GetOrCreateType(tid); 1195 CompleteType(qt); 1196 continue; 1197 } 1198 1199 // Call CreateDeclInfoForType unconditionally so that the namespace info 1200 // gets created. But only call CreateRecordType if the namespace name 1201 // matches. 1202 clang::DeclContext *context = nullptr; 1203 std::string uname; 1204 std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index); 1205 if (!context->isNamespace()) 1206 continue; 1207 1208 clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(context); 1209 std::string actual_ns = ns->getQualifiedNameAsString(); 1210 if (llvm::StringRef(actual_ns).startswith(*parent)) { 1211 clang::QualType qt = GetOrCreateType(tid); 1212 CompleteType(qt); 1213 continue; 1214 } 1215 } 1216 1217 uint32_t module_count = m_index.dbi().modules().getModuleCount(); 1218 for (uint16_t modi = 0; modi < module_count; ++modi) { 1219 CompilandIndexItem &cii = m_index.compilands().GetOrCreateCompiland(modi); 1220 const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray(); 1221 auto iter = symbols.begin(); 1222 while (iter != symbols.end()) { 1223 PdbCompilandSymId sym_id{modi, iter.offset()}; 1224 1225 switch (iter->kind()) { 1226 case S_GPROC32: 1227 case S_LPROC32: 1228 GetOrCreateFunctionDecl(sym_id); 1229 iter = symbols.at(getScopeEndOffset(*iter)); 1230 break; 1231 case S_GDATA32: 1232 case S_GTHREAD32: 1233 case S_LDATA32: 1234 case S_LTHREAD32: 1235 GetOrCreateVariableDecl(PdbCompilandSymId(modi, 0), sym_id); 1236 ++iter; 1237 break; 1238 default: 1239 ++iter; 1240 continue; 1241 } 1242 } 1243 } 1244 } 1245 1246 static CVSymbolArray skipFunctionParameters(clang::Decl &decl, 1247 const CVSymbolArray &symbols) { 1248 clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl); 1249 if (!func_decl) 1250 return symbols; 1251 unsigned int params = func_decl->getNumParams(); 1252 if (params == 0) 1253 return symbols; 1254 1255 CVSymbolArray result = symbols; 1256 1257 while (!result.empty()) { 1258 if (params == 0) 1259 return result; 1260 1261 CVSymbol sym = *result.begin(); 1262 result.drop_front(); 1263 1264 if (!isLocalVariableType(sym.kind())) 1265 continue; 1266 1267 --params; 1268 } 1269 return result; 1270 } 1271 1272 void PdbAstBuilder::ParseBlockChildren(PdbCompilandSymId block_id) { 1273 CVSymbol sym = m_index.ReadSymbolRecord(block_id); 1274 lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 || 1275 sym.kind() == S_BLOCK32); 1276 CompilandIndexItem &cii = 1277 m_index.compilands().GetOrCreateCompiland(block_id.modi); 1278 CVSymbolArray symbols = 1279 cii.m_debug_stream.getSymbolArrayForScope(block_id.offset); 1280 1281 // Function parameters should already have been created when the function was 1282 // parsed. 1283 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) 1284 symbols = 1285 skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols); 1286 1287 auto begin = symbols.begin(); 1288 while (begin != symbols.end()) { 1289 PdbCompilandSymId child_sym_id(block_id.modi, begin.offset()); 1290 GetOrCreateSymbolForId(child_sym_id); 1291 if (begin->kind() == S_BLOCK32) { 1292 ParseBlockChildren(child_sym_id); 1293 begin = symbols.at(getScopeEndOffset(*begin)); 1294 } 1295 ++begin; 1296 } 1297 } 1298 1299 void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) { 1300 1301 clang::Decl *decl = clang::Decl::castFromDeclContext(&context); 1302 lldbassert(decl); 1303 1304 auto iter = m_decl_to_status.find(decl); 1305 lldbassert(iter != m_decl_to_status.end()); 1306 1307 if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) { 1308 CompleteTagDecl(*tag); 1309 return; 1310 } 1311 1312 if (isFunctionDecl(context) || isBlockDecl(context)) { 1313 PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym(); 1314 ParseBlockChildren(block_id); 1315 } 1316 } 1317 1318 void PdbAstBuilder::ParseDeclsForContext(clang::DeclContext &context) { 1319 // Namespaces aren't explicitly represented in the debug info, and the only 1320 // way to parse them is to parse all type info, demangling every single type 1321 // and trying to reconstruct the DeclContext hierarchy this way. Since this 1322 // is an expensive operation, we have to special case it so that we do other 1323 // work (such as parsing the items that appear within the namespaces) at the 1324 // same time. 1325 if (context.isTranslationUnit()) { 1326 ParseAllNamespacesPlusChildrenOf(llvm::None); 1327 return; 1328 } 1329 1330 if (context.isNamespace()) { 1331 clang::NamespaceDecl &ns = *llvm::dyn_cast<clang::NamespaceDecl>(&context); 1332 std::string qname = ns.getQualifiedNameAsString(); 1333 ParseAllNamespacesPlusChildrenOf(llvm::StringRef{qname}); 1334 return; 1335 } 1336 1337 if (isTagDecl(context) || isFunctionDecl(context) || isBlockDecl(context)) { 1338 ParseDeclsForSimpleContext(context); 1339 return; 1340 } 1341 } 1342 1343 CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) { 1344 return {&m_clang, &decl}; 1345 } 1346 1347 CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) { 1348 return {&m_clang, qt.getAsOpaquePtr()}; 1349 } 1350 1351 CompilerDeclContext 1352 PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) { 1353 return {&m_clang, &context}; 1354 } 1355 1356 clang::DeclContext * 1357 PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) { 1358 return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext()); 1359 } 1360 1361 void PdbAstBuilder::Dump(Stream &stream) { m_clang.Dump(stream); } 1362