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