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 = m_index.tpi().getType(tag.asTag().FieldList); 405 ProcessTpiStream process(m_index, *ti, tag, m_parent_types); 406 llvm::Error error = visitMemberRecordStream(field_list.data(), process); 407 if (error) 408 llvm::consumeError(std::move(error)); 409 } 410 411 // Now that we know the forward -> full mapping of all type indices, we can 412 // re-write all the indices. At the end of this process, we want a mapping 413 // consisting of fwd -> full and full -> full for all child -> parent indices. 414 // We can re-write the values in place, but for the keys, we must save them 415 // off so that we don't modify the map in place while also iterating it. 416 std::vector<TypeIndex> full_keys; 417 std::vector<TypeIndex> fwd_keys; 418 for (auto &entry : m_parent_types) { 419 TypeIndex key = entry.first; 420 TypeIndex value = entry.second; 421 422 auto iter = forward_to_full.find(value); 423 if (iter != forward_to_full.end()) 424 entry.second = iter->second; 425 426 iter = forward_to_full.find(key); 427 if (iter != forward_to_full.end()) 428 fwd_keys.push_back(key); 429 else 430 full_keys.push_back(key); 431 } 432 for (TypeIndex fwd : fwd_keys) { 433 TypeIndex full = forward_to_full[fwd]; 434 m_parent_types[full] = m_parent_types[fwd]; 435 } 436 for (TypeIndex full : full_keys) { 437 TypeIndex fwd = full_to_forward[full]; 438 m_parent_types[fwd] = m_parent_types[full]; 439 } 440 441 // Now that 442 } 443 444 static bool isLocalVariableType(SymbolKind K) { 445 switch (K) { 446 case S_REGISTER: 447 case S_REGREL32: 448 case S_LOCAL: 449 return true; 450 default: 451 break; 452 } 453 return false; 454 } 455 456 static std::string 457 RenderScopeList(llvm::ArrayRef<llvm::ms_demangle::Node *> nodes) { 458 lldbassert(!nodes.empty()); 459 460 std::string result = nodes.front()->toString(); 461 nodes = nodes.drop_front(); 462 while (!nodes.empty()) { 463 result += "::"; 464 result += nodes.front()->toString(llvm::ms_demangle::OF_NoTagSpecifier); 465 nodes = nodes.drop_front(); 466 } 467 return result; 468 } 469 470 static llvm::Optional<PublicSym32> FindPublicSym(const SegmentOffset &addr, 471 SymbolStream &syms, 472 PublicsStream &publics) { 473 llvm::FixedStreamArray<ulittle32_t> addr_map = publics.getAddressMap(); 474 auto iter = std::lower_bound( 475 addr_map.begin(), addr_map.end(), addr, 476 [&](const ulittle32_t &x, const SegmentOffset &y) { 477 CVSymbol s1 = syms.readRecord(x); 478 lldbassert(s1.kind() == S_PUB32); 479 PublicSym32 p1; 480 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(s1, p1)); 481 if (p1.Segment < y.segment) 482 return true; 483 return p1.Offset < y.offset; 484 }); 485 if (iter == addr_map.end()) 486 return llvm::None; 487 CVSymbol sym = syms.readRecord(*iter); 488 lldbassert(sym.kind() == S_PUB32); 489 PublicSym32 p; 490 llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(sym, p)); 491 if (p.Segment == addr.segment && p.Offset == addr.offset) 492 return p; 493 return llvm::None; 494 } 495 496 clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) { 497 CVSymbol cvs = m_index.ReadSymbolRecord(id); 498 499 if (isLocalVariableType(cvs.kind())) { 500 clang::DeclContext *scope = GetParentDeclContext(id); 501 clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope); 502 PdbCompilandSymId scope_id = 503 PdbSymUid(m_decl_to_status[scope_decl].uid).asCompilandSym(); 504 return GetOrCreateVariableDecl(scope_id, id); 505 } 506 507 switch (cvs.kind()) { 508 case S_GPROC32: 509 case S_LPROC32: 510 return GetOrCreateFunctionDecl(id); 511 case S_GDATA32: 512 case S_LDATA32: 513 case S_GTHREAD32: 514 case S_CONSTANT: 515 // global variable 516 return nullptr; 517 case S_BLOCK32: 518 return GetOrCreateBlockDecl(id); 519 case S_INLINESITE: 520 return GetOrCreateInlinedFunctionDecl(id); 521 default: 522 return nullptr; 523 } 524 } 525 526 llvm::Optional<CompilerDecl> PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) { 527 if (clang::Decl *result = TryGetDecl(uid)) 528 return ToCompilerDecl(*result); 529 530 clang::Decl *result = nullptr; 531 switch (uid.kind()) { 532 case PdbSymUidKind::CompilandSym: 533 result = GetOrCreateSymbolForId(uid.asCompilandSym()); 534 break; 535 case PdbSymUidKind::Type: { 536 clang::QualType qt = GetOrCreateType(uid.asTypeSym()); 537 if (qt.isNull()) 538 return llvm::None; 539 if (auto *tag = qt->getAsTagDecl()) { 540 result = tag; 541 break; 542 } 543 return llvm::None; 544 } 545 default: 546 return llvm::None; 547 } 548 549 if (!result) 550 return llvm::None; 551 m_uid_to_decl[toOpaqueUid(uid)] = result; 552 return ToCompilerDecl(*result); 553 } 554 555 clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) { 556 if (uid.kind() == PdbSymUidKind::CompilandSym) { 557 if (uid.asCompilandSym().offset == 0) 558 return FromCompilerDeclContext(GetTranslationUnitDecl()); 559 } 560 auto option = GetOrCreateDeclForUid(uid); 561 if (!option) 562 return nullptr; 563 clang::Decl *decl = FromCompilerDecl(option.getValue()); 564 if (!decl) 565 return nullptr; 566 567 return clang::Decl::castToDeclContext(decl); 568 } 569 570 std::pair<clang::DeclContext *, std::string> 571 PdbAstBuilder::CreateDeclInfoForUndecoratedName(llvm::StringRef name) { 572 MSVCUndecoratedNameParser parser(name); 573 llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers(); 574 575 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 576 577 llvm::StringRef uname = specs.back().GetBaseName(); 578 specs = specs.drop_back(); 579 if (specs.empty()) 580 return {context, std::string(name)}; 581 582 llvm::StringRef scope_name = specs.back().GetFullName(); 583 584 // It might be a class name, try that first. 585 std::vector<TypeIndex> types = m_index.tpi().findRecordsByName(scope_name); 586 while (!types.empty()) { 587 clang::QualType qt = GetOrCreateType(types.back()); 588 if (qt.isNull()) 589 continue; 590 clang::TagDecl *tag = qt->getAsTagDecl(); 591 if (tag) 592 return {clang::TagDecl::castToDeclContext(tag), std::string(uname)}; 593 types.pop_back(); 594 } 595 596 // If that fails, treat it as a series of namespaces. 597 for (const MSVCUndecoratedNameSpecifier &spec : specs) { 598 std::string ns_name = spec.GetBaseName().str(); 599 context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context); 600 } 601 return {context, std::string(uname)}; 602 } 603 604 clang::DeclContext * 605 PdbAstBuilder::GetParentDeclContextForSymbol(const CVSymbol &sym) { 606 if (!SymbolHasAddress(sym)) 607 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first; 608 SegmentOffset addr = GetSegmentAndOffset(sym); 609 llvm::Optional<PublicSym32> pub = 610 FindPublicSym(addr, m_index.symrecords(), m_index.publics()); 611 if (!pub) 612 return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first; 613 614 llvm::ms_demangle::Demangler demangler; 615 StringView name{pub->Name.begin(), pub->Name.size()}; 616 llvm::ms_demangle::SymbolNode *node = demangler.parse(name); 617 if (!node) 618 return FromCompilerDeclContext(GetTranslationUnitDecl()); 619 llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{ 620 node->Name->Components->Nodes, node->Name->Components->Count - 1}; 621 622 if (!name_components.empty()) { 623 // Render the current list of scope nodes as a fully qualified name, and 624 // look it up in the debug info as a type name. If we find something, 625 // this is a type (which may itself be prefixed by a namespace). If we 626 // don't, this is a list of namespaces. 627 std::string qname = RenderScopeList(name_components); 628 std::vector<TypeIndex> matches = m_index.tpi().findRecordsByName(qname); 629 while (!matches.empty()) { 630 clang::QualType qt = GetOrCreateType(matches.back()); 631 if (qt.isNull()) 632 continue; 633 clang::TagDecl *tag = qt->getAsTagDecl(); 634 if (tag) 635 return clang::TagDecl::castToDeclContext(tag); 636 matches.pop_back(); 637 } 638 } 639 640 // It's not a type. It must be a series of namespaces. 641 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 642 while (!name_components.empty()) { 643 std::string ns = name_components.front()->toString(); 644 context = GetOrCreateNamespaceDecl(ns.c_str(), *context); 645 name_components = name_components.drop_front(); 646 } 647 return context; 648 } 649 650 clang::DeclContext *PdbAstBuilder::GetParentDeclContext(PdbSymUid uid) { 651 // We must do this *without* calling GetOrCreate on the current uid, as 652 // that would be an infinite recursion. 653 switch (uid.kind()) { 654 case PdbSymUidKind::CompilandSym: { 655 llvm::Optional<PdbCompilandSymId> scope = 656 FindSymbolScope(m_index, uid.asCompilandSym()); 657 if (scope) 658 return GetOrCreateDeclContextForUid(*scope); 659 660 CVSymbol sym = m_index.ReadSymbolRecord(uid.asCompilandSym()); 661 return GetParentDeclContextForSymbol(sym); 662 } 663 case PdbSymUidKind::Type: { 664 // It could be a namespace, class, or global. We don't support nested 665 // functions yet. Anyway, we just need to consult the parent type map. 666 PdbTypeSymId type_id = uid.asTypeSym(); 667 auto iter = m_parent_types.find(type_id.index); 668 if (iter == m_parent_types.end()) 669 return FromCompilerDeclContext(GetTranslationUnitDecl()); 670 return GetOrCreateDeclContextForUid(PdbTypeSymId(iter->second)); 671 } 672 case PdbSymUidKind::FieldListMember: 673 // In this case the parent DeclContext is the one for the class that this 674 // member is inside of. 675 break; 676 case PdbSymUidKind::GlobalSym: { 677 // If this refers to a compiland symbol, just recurse in with that symbol. 678 // The only other possibilities are S_CONSTANT and S_UDT, in which case we 679 // need to parse the undecorated name to figure out the scope, then look 680 // that up in the TPI stream. If it's found, it's a type, othewrise it's 681 // a series of namespaces. 682 // FIXME: do this. 683 CVSymbol global = m_index.ReadSymbolRecord(uid.asGlobalSym()); 684 switch (global.kind()) { 685 case SymbolKind::S_GDATA32: 686 case SymbolKind::S_LDATA32: 687 return GetParentDeclContextForSymbol(global); 688 case SymbolKind::S_PROCREF: 689 case SymbolKind::S_LPROCREF: { 690 ProcRefSym ref{global.kind()}; 691 llvm::cantFail( 692 SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref)); 693 PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset}; 694 return GetParentDeclContext(cu_sym_id); 695 } 696 case SymbolKind::S_CONSTANT: 697 case SymbolKind::S_UDT: 698 return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first; 699 default: 700 break; 701 } 702 break; 703 } 704 default: 705 break; 706 } 707 return FromCompilerDeclContext(GetTranslationUnitDecl()); 708 } 709 710 bool PdbAstBuilder::CompleteType(clang::QualType qt) { 711 if (qt.isNull()) 712 return false; 713 clang::TagDecl *tag = qt->getAsTagDecl(); 714 if (!tag) 715 return false; 716 717 return CompleteTagDecl(*tag); 718 } 719 720 bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) { 721 // If this is not in our map, it's an error. 722 auto status_iter = m_decl_to_status.find(&tag); 723 lldbassert(status_iter != m_decl_to_status.end()); 724 725 // If it's already complete, just return. 726 DeclStatus &status = status_iter->second; 727 if (status.resolved) 728 return true; 729 730 PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym(); 731 732 lldbassert(IsTagRecord(type_id, m_index.tpi())); 733 734 clang::QualType tag_qt = m_clang.getASTContext().getTypeDeclType(&tag); 735 TypeSystemClang::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false); 736 737 TypeIndex tag_ti = type_id.index; 738 CVType cvt = m_index.tpi().getType(tag_ti); 739 if (cvt.kind() == LF_MODIFIER) 740 tag_ti = LookThroughModifierRecord(cvt); 741 742 PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi()); 743 cvt = m_index.tpi().getType(best_ti.index); 744 lldbassert(IsTagRecord(cvt)); 745 746 if (IsForwardRefUdt(cvt)) { 747 // If we can't find a full decl for this forward ref anywhere in the debug 748 // info, then we have no way to complete it. 749 return false; 750 } 751 752 TypeIndex field_list_ti = GetFieldListIndex(cvt); 753 CVType field_list_cvt = m_index.tpi().getType(field_list_ti); 754 if (field_list_cvt.kind() != LF_FIELDLIST) 755 return false; 756 757 // Visit all members of this class, then perform any finalization necessary 758 // to complete the class. 759 CompilerType ct = ToCompilerType(tag_qt); 760 UdtRecordCompleter completer(best_ti, ct, tag, *this, m_index, 761 m_cxx_record_map); 762 auto error = 763 llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer); 764 completer.complete(); 765 766 status.resolved = true; 767 if (!error) 768 return true; 769 770 llvm::consumeError(std::move(error)); 771 return false; 772 } 773 774 clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) { 775 if (ti == TypeIndex::NullptrT()) 776 return GetBasicType(lldb::eBasicTypeNullPtr); 777 778 if (ti.getSimpleMode() != SimpleTypeMode::Direct) { 779 clang::QualType direct_type = GetOrCreateType(ti.makeDirect()); 780 if (direct_type.isNull()) 781 return {}; 782 return m_clang.getASTContext().getPointerType(direct_type); 783 } 784 785 if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated) 786 return {}; 787 788 lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind()); 789 if (bt == lldb::eBasicTypeInvalid) 790 return {}; 791 792 return GetBasicType(bt); 793 } 794 795 clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) { 796 clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType); 797 798 // This can happen for pointers to LF_VTSHAPE records, which we shouldn't 799 // create in the AST. 800 if (pointee_type.isNull()) 801 return {}; 802 803 if (pointer.isPointerToMember()) { 804 MemberPointerInfo mpi = pointer.getMemberInfo(); 805 clang::QualType class_type = GetOrCreateType(mpi.ContainingType); 806 if (class_type.isNull()) 807 return {}; 808 return m_clang.getASTContext().getMemberPointerType( 809 pointee_type, class_type.getTypePtr()); 810 } 811 812 clang::QualType pointer_type; 813 if (pointer.getMode() == PointerMode::LValueReference) 814 pointer_type = m_clang.getASTContext().getLValueReferenceType(pointee_type); 815 else if (pointer.getMode() == PointerMode::RValueReference) 816 pointer_type = m_clang.getASTContext().getRValueReferenceType(pointee_type); 817 else 818 pointer_type = m_clang.getASTContext().getPointerType(pointee_type); 819 820 if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None) 821 pointer_type.addConst(); 822 823 if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None) 824 pointer_type.addVolatile(); 825 826 if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None) 827 pointer_type.addRestrict(); 828 829 return pointer_type; 830 } 831 832 clang::QualType 833 PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) { 834 clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType); 835 if (unmodified_type.isNull()) 836 return {}; 837 838 if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None) 839 unmodified_type.addConst(); 840 if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None) 841 unmodified_type.addVolatile(); 842 843 return unmodified_type; 844 } 845 846 clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id, 847 const TagRecord &record) { 848 clang::DeclContext *context = nullptr; 849 std::string uname; 850 std::tie(context, uname) = CreateDeclInfoForType(record, id.index); 851 if (!context) 852 return {}; 853 854 clang::TagTypeKind ttk = TranslateUdtKind(record); 855 lldb::AccessType access = 856 (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic; 857 858 ClangASTMetadata metadata; 859 metadata.SetUserID(toOpaqueUid(id)); 860 metadata.SetIsDynamicCXXType(false); 861 862 CompilerType ct = 863 m_clang.CreateRecordType(context, OptionalClangModuleID(), access, uname, 864 ttk, lldb::eLanguageTypeC_plus_plus, &metadata); 865 866 lldbassert(ct.IsValid()); 867 868 TypeSystemClang::StartTagDeclarationDefinition(ct); 869 870 // Even if it's possible, don't complete it at this point. Just mark it 871 // forward resolved, and if/when LLDB needs the full definition, it can 872 // ask us. 873 clang::QualType result = 874 clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType()); 875 876 TypeSystemClang::SetHasExternalStorage(result.getAsOpaquePtr(), true); 877 return result; 878 } 879 880 clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const { 881 auto iter = m_uid_to_decl.find(toOpaqueUid(uid)); 882 if (iter != m_uid_to_decl.end()) 883 return iter->second; 884 return nullptr; 885 } 886 887 clang::NamespaceDecl * 888 PdbAstBuilder::GetOrCreateNamespaceDecl(const char *name, 889 clang::DeclContext &context) { 890 return m_clang.GetUniqueNamespaceDeclaration( 891 IsAnonymousNamespaceName(name) ? nullptr : name, &context, 892 OptionalClangModuleID()); 893 } 894 895 clang::BlockDecl * 896 PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) { 897 if (clang::Decl *decl = TryGetDecl(block_id)) 898 return llvm::dyn_cast<clang::BlockDecl>(decl); 899 900 clang::DeclContext *scope = GetParentDeclContext(block_id); 901 902 clang::BlockDecl *block_decl = 903 m_clang.CreateBlockDeclaration(scope, OptionalClangModuleID()); 904 m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl}); 905 906 DeclStatus status; 907 status.resolved = true; 908 status.uid = toOpaqueUid(block_id); 909 m_decl_to_status.insert({block_decl, status}); 910 911 return block_decl; 912 } 913 914 clang::VarDecl *PdbAstBuilder::CreateVariableDecl(PdbSymUid uid, CVSymbol sym, 915 clang::DeclContext &scope) { 916 VariableInfo var_info = GetVariableNameInfo(sym); 917 clang::QualType qt = GetOrCreateType(var_info.type); 918 if (qt.isNull()) 919 return nullptr; 920 921 clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration( 922 &scope, OptionalClangModuleID(), var_info.name.str().c_str(), qt); 923 924 m_uid_to_decl[toOpaqueUid(uid)] = var_decl; 925 DeclStatus status; 926 status.resolved = true; 927 status.uid = toOpaqueUid(uid); 928 m_decl_to_status.insert({var_decl, status}); 929 return var_decl; 930 } 931 932 clang::VarDecl * 933 PdbAstBuilder::GetOrCreateVariableDecl(PdbCompilandSymId scope_id, 934 PdbCompilandSymId var_id) { 935 if (clang::Decl *decl = TryGetDecl(var_id)) 936 return llvm::dyn_cast<clang::VarDecl>(decl); 937 938 clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id); 939 if (!scope) 940 return nullptr; 941 942 CVSymbol sym = m_index.ReadSymbolRecord(var_id); 943 return CreateVariableDecl(PdbSymUid(var_id), sym, *scope); 944 } 945 946 clang::VarDecl *PdbAstBuilder::GetOrCreateVariableDecl(PdbGlobalSymId var_id) { 947 if (clang::Decl *decl = TryGetDecl(var_id)) 948 return llvm::dyn_cast<clang::VarDecl>(decl); 949 950 CVSymbol sym = m_index.ReadSymbolRecord(var_id); 951 auto context = FromCompilerDeclContext(GetTranslationUnitDecl()); 952 return CreateVariableDecl(PdbSymUid(var_id), sym, *context); 953 } 954 955 clang::TypedefNameDecl * 956 PdbAstBuilder::GetOrCreateTypedefDecl(PdbGlobalSymId id) { 957 if (clang::Decl *decl = TryGetDecl(id)) 958 return llvm::dyn_cast<clang::TypedefNameDecl>(decl); 959 960 CVSymbol sym = m_index.ReadSymbolRecord(id); 961 lldbassert(sym.kind() == S_UDT); 962 UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym)); 963 964 clang::DeclContext *scope = GetParentDeclContext(id); 965 966 PdbTypeSymId real_type_id{udt.Type, false}; 967 clang::QualType qt = GetOrCreateType(real_type_id); 968 if (qt.isNull()) 969 return nullptr; 970 971 std::string uname = std::string(DropNameScope(udt.Name)); 972 973 CompilerType ct = ToCompilerType(qt).CreateTypedef( 974 uname.c_str(), ToCompilerDeclContext(*scope), 0); 975 clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct); 976 DeclStatus status; 977 status.resolved = true; 978 status.uid = toOpaqueUid(id); 979 m_decl_to_status.insert({tnd, status}); 980 return tnd; 981 } 982 983 clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) { 984 CompilerType ct = m_clang.GetBasicType(type); 985 return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType()); 986 } 987 988 clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) { 989 if (type.index.isSimple()) 990 return CreateSimpleType(type.index); 991 992 CVType cvt = m_index.tpi().getType(type.index); 993 994 if (cvt.kind() == LF_MODIFIER) { 995 ModifierRecord modifier; 996 llvm::cantFail( 997 TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier)); 998 return CreateModifierType(modifier); 999 } 1000 1001 if (cvt.kind() == LF_POINTER) { 1002 PointerRecord pointer; 1003 llvm::cantFail( 1004 TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer)); 1005 return CreatePointerType(pointer); 1006 } 1007 1008 if (IsTagRecord(cvt)) { 1009 CVTagRecord tag = CVTagRecord::create(cvt); 1010 if (tag.kind() == CVTagRecord::Union) 1011 return CreateRecordType(type.index, tag.asUnion()); 1012 if (tag.kind() == CVTagRecord::Enum) 1013 return CreateEnumType(type.index, tag.asEnum()); 1014 return CreateRecordType(type.index, tag.asClass()); 1015 } 1016 1017 if (cvt.kind() == LF_ARRAY) { 1018 ArrayRecord ar; 1019 llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar)); 1020 return CreateArrayType(ar); 1021 } 1022 1023 if (cvt.kind() == LF_PROCEDURE) { 1024 ProcedureRecord pr; 1025 llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr)); 1026 return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv); 1027 } 1028 1029 if (cvt.kind() == LF_MFUNCTION) { 1030 MemberFunctionRecord mfr; 1031 llvm::cantFail( 1032 TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr)); 1033 return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv); 1034 } 1035 1036 return {}; 1037 } 1038 1039 clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) { 1040 if (type.index.isNoneType()) 1041 return {}; 1042 1043 lldb::user_id_t uid = toOpaqueUid(type); 1044 auto iter = m_uid_to_type.find(uid); 1045 if (iter != m_uid_to_type.end()) 1046 return iter->second; 1047 1048 PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi()); 1049 1050 clang::QualType qt; 1051 if (best_type.index != type.index) { 1052 // This is a forward decl. Call GetOrCreate on the full decl, then map the 1053 // forward decl id to the full decl QualType. 1054 clang::QualType qt = GetOrCreateType(best_type); 1055 if (qt.isNull()) 1056 return {}; 1057 m_uid_to_type[toOpaqueUid(type)] = qt; 1058 return qt; 1059 } 1060 1061 // This is either a full decl, or a forward decl with no matching full decl 1062 // in the debug info. 1063 qt = CreateType(type); 1064 if (qt.isNull()) 1065 return {}; 1066 1067 m_uid_to_type[toOpaqueUid(type)] = qt; 1068 if (IsTagRecord(type, m_index.tpi())) { 1069 clang::TagDecl *tag = qt->getAsTagDecl(); 1070 lldbassert(m_decl_to_status.count(tag) == 0); 1071 1072 DeclStatus &status = m_decl_to_status[tag]; 1073 status.uid = uid; 1074 status.resolved = false; 1075 } 1076 return qt; 1077 } 1078 1079 clang::FunctionDecl * 1080 PdbAstBuilder::CreateFunctionDecl(PdbCompilandSymId func_id, 1081 llvm::StringRef func_name, TypeIndex func_ti, 1082 CompilerType func_ct, uint32_t param_count, 1083 clang::StorageClass func_storage, 1084 bool is_inline, clang::DeclContext *parent) { 1085 clang::FunctionDecl *function_decl = nullptr; 1086 if (parent->isRecord()) { 1087 clang::QualType parent_qt = llvm::cast<clang::TypeDecl>(parent) 1088 ->getTypeForDecl() 1089 ->getCanonicalTypeInternal(); 1090 lldb::opaque_compiler_type_t parent_opaque_ty = 1091 ToCompilerType(parent_qt).GetOpaqueQualType(); 1092 auto iter = m_cxx_record_map.find(parent_opaque_ty); 1093 if (iter != m_cxx_record_map.end()) { 1094 if (iter->getSecond().contains({func_name, func_ct})) { 1095 return nullptr; 1096 } 1097 } 1098 1099 CVType cvt = m_index.tpi().getType(func_ti); 1100 MemberFunctionRecord func_record(static_cast<TypeRecordKind>(cvt.kind())); 1101 llvm::cantFail(TypeDeserializer::deserializeAs<MemberFunctionRecord>( 1102 cvt, func_record)); 1103 TypeIndex class_index = func_record.getClassType(); 1104 1105 CVType parent_cvt = m_index.tpi().getType(class_index); 1106 ClassRecord class_record = CVTagRecord::create(parent_cvt).asClass(); 1107 // If it's a forward reference, try to get the real TypeIndex. 1108 if (class_record.isForwardRef()) { 1109 llvm::Expected<TypeIndex> eti = 1110 m_index.tpi().findFullDeclForForwardRef(class_index); 1111 if (eti) { 1112 class_record = 1113 CVTagRecord::create(m_index.tpi().getType(*eti)).asClass(); 1114 } 1115 } 1116 if (!class_record.FieldList.isSimple()) { 1117 CVType field_list = m_index.tpi().getType(class_record.FieldList); 1118 CreateMethodDecl process(m_index, m_clang, func_ti, function_decl, 1119 parent_opaque_ty, func_name, func_ct); 1120 if (llvm::Error err = visitMemberRecordStream(field_list.data(), process)) 1121 llvm::consumeError(std::move(err)); 1122 } 1123 1124 if (!function_decl) { 1125 function_decl = m_clang.AddMethodToCXXRecordType( 1126 parent_opaque_ty, func_name, 1127 /*mangled_name=*/nullptr, func_ct, 1128 /*access=*/lldb::AccessType::eAccessPublic, 1129 /*is_virtual=*/false, /*is_static=*/false, 1130 /*is_inline=*/false, /*is_explicit=*/false, 1131 /*is_attr_used=*/false, /*is_artificial=*/false); 1132 } 1133 m_cxx_record_map[parent_opaque_ty].insert({func_name, func_ct}); 1134 } else { 1135 function_decl = m_clang.CreateFunctionDeclaration( 1136 parent, OptionalClangModuleID(), func_name, func_ct, func_storage, 1137 is_inline); 1138 CreateFunctionParameters(func_id, *function_decl, param_count); 1139 } 1140 return function_decl; 1141 } 1142 1143 clang::FunctionDecl * 1144 PdbAstBuilder::GetOrCreateInlinedFunctionDecl(PdbCompilandSymId inlinesite_id) { 1145 CompilandIndexItem *cii = 1146 m_index.compilands().GetCompiland(inlinesite_id.modi); 1147 CVSymbol sym = cii->m_debug_stream.readSymbolAtOffset(inlinesite_id.offset); 1148 InlineSiteSym inline_site(static_cast<SymbolRecordKind>(sym.kind())); 1149 cantFail(SymbolDeserializer::deserializeAs<InlineSiteSym>(sym, inline_site)); 1150 1151 // Inlinee is the id index to the function id record that is inlined. 1152 PdbTypeSymId func_id(inline_site.Inlinee, true); 1153 // Look up the function decl by the id index to see if we have created a 1154 // function decl for a different inlinesite that refers the same function. 1155 if (clang::Decl *decl = TryGetDecl(func_id)) 1156 return llvm::dyn_cast<clang::FunctionDecl>(decl); 1157 clang::FunctionDecl *function_decl = 1158 CreateFunctionDeclFromId(func_id, inlinesite_id); 1159 1160 // Use inline site id in m_decl_to_status because it's expected to be a 1161 // PdbCompilandSymId so that we can parse local variables info after it. 1162 uint64_t inlinesite_uid = toOpaqueUid(inlinesite_id); 1163 DeclStatus status; 1164 status.resolved = true; 1165 status.uid = inlinesite_uid; 1166 m_decl_to_status.insert({function_decl, status}); 1167 // Use the index in IPI stream as uid in m_uid_to_decl, because index in IPI 1168 // stream are unique and there could be multiple inline sites (different ids) 1169 // referring the same inline function. This avoid creating multiple same 1170 // inline function delcs. 1171 uint64_t func_uid = toOpaqueUid(func_id); 1172 lldbassert(m_uid_to_decl.count(func_uid) == 0); 1173 m_uid_to_decl[func_uid] = function_decl; 1174 return function_decl; 1175 } 1176 1177 clang::FunctionDecl * 1178 PdbAstBuilder::CreateFunctionDeclFromId(PdbTypeSymId func_tid, 1179 PdbCompilandSymId func_sid) { 1180 lldbassert(func_tid.is_ipi); 1181 CVType func_cvt = m_index.ipi().getType(func_tid.index); 1182 llvm::StringRef func_name; 1183 TypeIndex func_ti; 1184 clang::DeclContext *parent = nullptr; 1185 switch (func_cvt.kind()) { 1186 case LF_MFUNC_ID: { 1187 MemberFuncIdRecord mfr; 1188 cantFail( 1189 TypeDeserializer::deserializeAs<MemberFuncIdRecord>(func_cvt, mfr)); 1190 func_name = mfr.getName(); 1191 func_ti = mfr.getFunctionType(); 1192 PdbTypeSymId class_type_id(mfr.ClassType, false); 1193 parent = GetOrCreateDeclContextForUid(class_type_id); 1194 break; 1195 } 1196 case LF_FUNC_ID: { 1197 FuncIdRecord fir; 1198 cantFail(TypeDeserializer::deserializeAs<FuncIdRecord>(func_cvt, fir)); 1199 func_name = fir.getName(); 1200 func_ti = fir.getFunctionType(); 1201 parent = FromCompilerDeclContext(GetTranslationUnitDecl()); 1202 if (!fir.ParentScope.isNoneType()) { 1203 CVType parent_cvt = m_index.ipi().getType(fir.ParentScope); 1204 if (parent_cvt.kind() == LF_STRING_ID) { 1205 StringIdRecord sir; 1206 cantFail( 1207 TypeDeserializer::deserializeAs<StringIdRecord>(parent_cvt, sir)); 1208 parent = GetOrCreateNamespaceDecl(sir.String.data(), *parent); 1209 } 1210 } 1211 break; 1212 } 1213 default: 1214 lldbassert(false && "Invalid function id type!"); 1215 } 1216 clang::QualType func_qt = GetOrCreateType(func_ti); 1217 if (func_qt.isNull()) 1218 return nullptr; 1219 CompilerType func_ct = ToCompilerType(func_qt); 1220 uint32_t param_count = 1221 llvm::cast<clang::FunctionProtoType>(func_qt)->getNumParams(); 1222 return CreateFunctionDecl(func_sid, func_name, func_ti, func_ct, param_count, 1223 clang::SC_None, true, parent); 1224 } 1225 1226 clang::FunctionDecl * 1227 PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) { 1228 if (clang::Decl *decl = TryGetDecl(func_id)) 1229 return llvm::dyn_cast<clang::FunctionDecl>(decl); 1230 1231 clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id)); 1232 std::string context_name; 1233 if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) { 1234 context_name = ns->getQualifiedNameAsString(); 1235 } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) { 1236 context_name = tag->getQualifiedNameAsString(); 1237 } 1238 1239 CVSymbol cvs = m_index.ReadSymbolRecord(func_id); 1240 ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind())); 1241 llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc)); 1242 1243 PdbTypeSymId type_id(proc.FunctionType); 1244 clang::QualType qt = GetOrCreateType(type_id); 1245 if (qt.isNull()) 1246 return nullptr; 1247 1248 clang::StorageClass storage = clang::SC_None; 1249 if (proc.Kind == SymbolRecordKind::ProcSym) 1250 storage = clang::SC_Static; 1251 1252 const clang::FunctionProtoType *func_type = 1253 llvm::dyn_cast<clang::FunctionProtoType>(qt); 1254 1255 CompilerType func_ct = ToCompilerType(qt); 1256 1257 llvm::StringRef proc_name = proc.Name; 1258 proc_name.consume_front(context_name); 1259 proc_name.consume_front("::"); 1260 1261 clang::FunctionDecl *function_decl = 1262 CreateFunctionDecl(func_id, proc_name, proc.FunctionType, func_ct, 1263 func_type->getNumParams(), storage, false, parent); 1264 1265 lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0); 1266 m_uid_to_decl[toOpaqueUid(func_id)] = function_decl; 1267 DeclStatus status; 1268 status.resolved = true; 1269 status.uid = toOpaqueUid(func_id); 1270 m_decl_to_status.insert({function_decl, status}); 1271 1272 return function_decl; 1273 } 1274 1275 void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id, 1276 clang::FunctionDecl &function_decl, 1277 uint32_t param_count) { 1278 CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi); 1279 CVSymbolArray scope = 1280 cii->m_debug_stream.getSymbolArrayForScope(func_id.offset); 1281 1282 scope.drop_front(); 1283 auto begin = scope.begin(); 1284 auto end = scope.end(); 1285 std::vector<clang::ParmVarDecl *> params; 1286 for (uint32_t i = 0; i < param_count && begin != end;) { 1287 uint32_t record_offset = begin.offset(); 1288 CVSymbol sym = *begin++; 1289 1290 TypeIndex param_type; 1291 llvm::StringRef param_name; 1292 switch (sym.kind()) { 1293 case S_REGREL32: { 1294 RegRelativeSym reg(SymbolRecordKind::RegRelativeSym); 1295 cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg)); 1296 param_type = reg.Type; 1297 param_name = reg.Name; 1298 break; 1299 } 1300 case S_REGISTER: { 1301 RegisterSym reg(SymbolRecordKind::RegisterSym); 1302 cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg)); 1303 param_type = reg.Index; 1304 param_name = reg.Name; 1305 break; 1306 } 1307 case S_LOCAL: { 1308 LocalSym local(SymbolRecordKind::LocalSym); 1309 cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local)); 1310 if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None) 1311 continue; 1312 param_type = local.Type; 1313 param_name = local.Name; 1314 break; 1315 } 1316 case S_BLOCK32: 1317 case S_INLINESITE: 1318 case S_INLINESITE2: 1319 // All parameters should come before the first block/inlinesite. If that 1320 // isn't the case, then perhaps this is bad debug info that doesn't 1321 // contain information about all parameters. 1322 return; 1323 default: 1324 continue; 1325 } 1326 1327 PdbCompilandSymId param_uid(func_id.modi, record_offset); 1328 clang::QualType qt = GetOrCreateType(param_type); 1329 if (qt.isNull()) 1330 return; 1331 1332 CompilerType param_type_ct = m_clang.GetType(qt); 1333 clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration( 1334 &function_decl, OptionalClangModuleID(), param_name.str().c_str(), 1335 param_type_ct, clang::SC_None, true); 1336 lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0); 1337 1338 m_uid_to_decl[toOpaqueUid(param_uid)] = param; 1339 params.push_back(param); 1340 ++i; 1341 } 1342 1343 if (!params.empty() && params.size() == param_count) 1344 m_clang.SetFunctionParameters(&function_decl, params); 1345 } 1346 1347 clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id, 1348 const EnumRecord &er) { 1349 clang::DeclContext *decl_context = nullptr; 1350 std::string uname; 1351 std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index); 1352 if (!decl_context) 1353 return {}; 1354 1355 clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType); 1356 if (underlying_type.isNull()) 1357 return {}; 1358 1359 Declaration declaration; 1360 CompilerType enum_ct = m_clang.CreateEnumerationType( 1361 uname, decl_context, OptionalClangModuleID(), declaration, 1362 ToCompilerType(underlying_type), er.isScoped()); 1363 1364 TypeSystemClang::StartTagDeclarationDefinition(enum_ct); 1365 TypeSystemClang::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true); 1366 1367 return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType()); 1368 } 1369 1370 clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) { 1371 clang::QualType element_type = GetOrCreateType(ar.ElementType); 1372 1373 uint64_t element_size = GetSizeOfType({ar.ElementType}, m_index.tpi()); 1374 if (element_type.isNull() || element_size == 0) 1375 return {}; 1376 uint64_t element_count = ar.Size / element_size; 1377 1378 CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type), 1379 element_count, false); 1380 return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType()); 1381 } 1382 1383 clang::QualType PdbAstBuilder::CreateFunctionType( 1384 TypeIndex args_type_idx, TypeIndex return_type_idx, 1385 llvm::codeview::CallingConvention calling_convention) { 1386 TpiStream &stream = m_index.tpi(); 1387 CVType args_cvt = stream.getType(args_type_idx); 1388 ArgListRecord args; 1389 llvm::cantFail( 1390 TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args)); 1391 1392 llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices); 1393 bool is_variadic = IsCVarArgsFunction(arg_indices); 1394 if (is_variadic) 1395 arg_indices = arg_indices.drop_back(); 1396 1397 std::vector<CompilerType> arg_types; 1398 arg_types.reserve(arg_indices.size()); 1399 1400 for (TypeIndex arg_index : arg_indices) { 1401 clang::QualType arg_type = GetOrCreateType(arg_index); 1402 if (arg_type.isNull()) 1403 continue; 1404 arg_types.push_back(ToCompilerType(arg_type)); 1405 } 1406 1407 clang::QualType return_type = GetOrCreateType(return_type_idx); 1408 if (return_type.isNull()) 1409 return {}; 1410 1411 llvm::Optional<clang::CallingConv> cc = 1412 TranslateCallingConvention(calling_convention); 1413 if (!cc) 1414 return {}; 1415 1416 CompilerType return_ct = ToCompilerType(return_type); 1417 CompilerType func_sig_ast_type = m_clang.CreateFunctionType( 1418 return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc); 1419 1420 return clang::QualType::getFromOpaquePtr( 1421 func_sig_ast_type.GetOpaqueQualType()); 1422 } 1423 1424 static bool isTagDecl(clang::DeclContext &context) { 1425 return llvm::isa<clang::TagDecl>(&context); 1426 } 1427 1428 static bool isFunctionDecl(clang::DeclContext &context) { 1429 return llvm::isa<clang::FunctionDecl>(&context); 1430 } 1431 1432 static bool isBlockDecl(clang::DeclContext &context) { 1433 return llvm::isa<clang::BlockDecl>(&context); 1434 } 1435 1436 void PdbAstBuilder::ParseAllNamespacesPlusChildrenOf( 1437 llvm::Optional<llvm::StringRef> parent) { 1438 TypeIndex ti{m_index.tpi().TypeIndexBegin()}; 1439 for (const CVType &cvt : m_index.tpi().typeArray()) { 1440 PdbTypeSymId tid{ti}; 1441 ++ti; 1442 1443 if (!IsTagRecord(cvt)) 1444 continue; 1445 1446 CVTagRecord tag = CVTagRecord::create(cvt); 1447 1448 if (!parent.hasValue()) { 1449 clang::QualType qt = GetOrCreateType(tid); 1450 CompleteType(qt); 1451 continue; 1452 } 1453 1454 // Call CreateDeclInfoForType unconditionally so that the namespace info 1455 // gets created. But only call CreateRecordType if the namespace name 1456 // matches. 1457 clang::DeclContext *context = nullptr; 1458 std::string uname; 1459 std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index); 1460 if (!context || !context->isNamespace()) 1461 continue; 1462 1463 clang::NamespaceDecl *ns = llvm::cast<clang::NamespaceDecl>(context); 1464 std::string actual_ns = ns->getQualifiedNameAsString(); 1465 if (llvm::StringRef(actual_ns).startswith(*parent)) { 1466 clang::QualType qt = GetOrCreateType(tid); 1467 CompleteType(qt); 1468 continue; 1469 } 1470 } 1471 1472 uint32_t module_count = m_index.dbi().modules().getModuleCount(); 1473 for (uint16_t modi = 0; modi < module_count; ++modi) { 1474 CompilandIndexItem &cii = m_index.compilands().GetOrCreateCompiland(modi); 1475 const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray(); 1476 auto iter = symbols.begin(); 1477 while (iter != symbols.end()) { 1478 PdbCompilandSymId sym_id{modi, iter.offset()}; 1479 1480 switch (iter->kind()) { 1481 case S_GPROC32: 1482 case S_LPROC32: 1483 GetOrCreateFunctionDecl(sym_id); 1484 iter = symbols.at(getScopeEndOffset(*iter)); 1485 break; 1486 case S_GDATA32: 1487 case S_GTHREAD32: 1488 case S_LDATA32: 1489 case S_LTHREAD32: 1490 GetOrCreateVariableDecl(PdbCompilandSymId(modi, 0), sym_id); 1491 ++iter; 1492 break; 1493 default: 1494 ++iter; 1495 continue; 1496 } 1497 } 1498 } 1499 } 1500 1501 static CVSymbolArray skipFunctionParameters(clang::Decl &decl, 1502 const CVSymbolArray &symbols) { 1503 clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl); 1504 if (!func_decl) 1505 return symbols; 1506 unsigned int params = func_decl->getNumParams(); 1507 if (params == 0) 1508 return symbols; 1509 1510 CVSymbolArray result = symbols; 1511 1512 while (!result.empty()) { 1513 if (params == 0) 1514 return result; 1515 1516 CVSymbol sym = *result.begin(); 1517 result.drop_front(); 1518 1519 if (!isLocalVariableType(sym.kind())) 1520 continue; 1521 1522 --params; 1523 } 1524 return result; 1525 } 1526 1527 void PdbAstBuilder::ParseBlockChildren(PdbCompilandSymId block_id) { 1528 CVSymbol sym = m_index.ReadSymbolRecord(block_id); 1529 lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 || 1530 sym.kind() == S_BLOCK32 || sym.kind() == S_INLINESITE); 1531 CompilandIndexItem &cii = 1532 m_index.compilands().GetOrCreateCompiland(block_id.modi); 1533 CVSymbolArray symbols = 1534 cii.m_debug_stream.getSymbolArrayForScope(block_id.offset); 1535 1536 // Function parameters should already have been created when the function was 1537 // parsed. 1538 if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32) 1539 symbols = 1540 skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols); 1541 1542 symbols.drop_front(); 1543 auto begin = symbols.begin(); 1544 while (begin != symbols.end()) { 1545 PdbCompilandSymId child_sym_id(block_id.modi, begin.offset()); 1546 GetOrCreateSymbolForId(child_sym_id); 1547 if (begin->kind() == S_BLOCK32 || begin->kind() == S_INLINESITE) { 1548 ParseBlockChildren(child_sym_id); 1549 begin = symbols.at(getScopeEndOffset(*begin)); 1550 } 1551 ++begin; 1552 } 1553 } 1554 1555 void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) { 1556 1557 clang::Decl *decl = clang::Decl::castFromDeclContext(&context); 1558 lldbassert(decl); 1559 1560 auto iter = m_decl_to_status.find(decl); 1561 lldbassert(iter != m_decl_to_status.end()); 1562 1563 if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) { 1564 CompleteTagDecl(*tag); 1565 return; 1566 } 1567 1568 if (isFunctionDecl(context) || isBlockDecl(context)) { 1569 PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym(); 1570 ParseBlockChildren(block_id); 1571 } 1572 } 1573 1574 void PdbAstBuilder::ParseDeclsForContext(clang::DeclContext &context) { 1575 // Namespaces aren't explicitly represented in the debug info, and the only 1576 // way to parse them is to parse all type info, demangling every single type 1577 // and trying to reconstruct the DeclContext hierarchy this way. Since this 1578 // is an expensive operation, we have to special case it so that we do other 1579 // work (such as parsing the items that appear within the namespaces) at the 1580 // same time. 1581 if (context.isTranslationUnit()) { 1582 ParseAllNamespacesPlusChildrenOf(llvm::None); 1583 return; 1584 } 1585 1586 if (context.isNamespace()) { 1587 clang::NamespaceDecl &ns = *llvm::dyn_cast<clang::NamespaceDecl>(&context); 1588 std::string qname = ns.getQualifiedNameAsString(); 1589 ParseAllNamespacesPlusChildrenOf(llvm::StringRef{qname}); 1590 return; 1591 } 1592 1593 if (isTagDecl(context) || isFunctionDecl(context) || isBlockDecl(context)) { 1594 ParseDeclsForSimpleContext(context); 1595 return; 1596 } 1597 } 1598 1599 CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) { 1600 return m_clang.GetCompilerDecl(&decl); 1601 } 1602 1603 CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) { 1604 return {&m_clang, qt.getAsOpaquePtr()}; 1605 } 1606 1607 CompilerDeclContext 1608 PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) { 1609 return m_clang.CreateDeclContext(&context); 1610 } 1611 1612 clang::Decl * PdbAstBuilder::FromCompilerDecl(CompilerDecl decl) { 1613 return ClangUtil::GetDecl(decl); 1614 } 1615 1616 clang::DeclContext * 1617 PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) { 1618 return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext()); 1619 } 1620 1621 void PdbAstBuilder::Dump(Stream &stream) { 1622 m_clang.Dump(stream.AsRawOstream()); 1623 } 1624