1//===-- DWARFASTParserClang.cpp -------------------------------------------===// 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6// 7//===----------------------------------------------------------------------===// 8 9#include <cstdlib> 10 11#include "DWARFASTParser.h" 12#include "DWARFASTParserClang.h" 13#include "DWARFDebugInfo.h" 14#include "DWARFDeclContext.h" 15#include "DWARFDefines.h" 16#include "SymbolFileDWARF.h" 17#include "SymbolFileDWARFDebugMap.h" 18#include "SymbolFileDWARFDwo.h" 19#include "UniqueDWARFASTType.h" 20 21#include "Plugins/ExpressionParser/Clang/ClangASTImporter.h" 22#include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h" 23#include "Plugins/ExpressionParser/Clang/ClangUtil.h" 24#include "Plugins/Language/ObjC/ObjCLanguage.h" 25#include "lldb/Core/Module.h" 26#include "lldb/Core/Value.h" 27#include "lldb/Host/Host.h" 28#include "lldb/Symbol/CompileUnit.h" 29#include "lldb/Symbol/Function.h" 30#include "lldb/Symbol/ObjectFile.h" 31#include "lldb/Symbol/SymbolFile.h" 32#include "lldb/Symbol/TypeList.h" 33#include "lldb/Symbol/TypeMap.h" 34#include "lldb/Symbol/VariableList.h" 35#include "lldb/Target/Language.h" 36#include "lldb/Utility/LLDBAssert.h" 37#include "lldb/Utility/Log.h" 38#include "lldb/Utility/StreamString.h" 39 40#include "clang/AST/CXXInheritance.h" 41#include "clang/AST/DeclCXX.h" 42#include "clang/AST/DeclObjC.h" 43#include "clang/AST/DeclTemplate.h" 44#include "clang/AST/Type.h" 45#include "llvm/Demangle/Demangle.h" 46 47#include <map> 48#include <memory> 49#include <optional> 50#include <vector> 51 52//#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN 53 54#ifdef ENABLE_DEBUG_PRINTF 55#include <cstdio> 56#define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__) 57#else 58#define DEBUG_PRINTF(fmt, ...) 59#endif 60 61using namespace lldb; 62using namespace lldb_private; 63using namespace lldb_private::dwarf; 64using namespace lldb_private::plugin::dwarf; 65 66DWARFASTParserClang::DWARFASTParserClang(TypeSystemClang &ast) 67 : DWARFASTParser(Kind::DWARFASTParserClang), m_ast(ast), 68 m_die_to_decl_ctx(), m_decl_ctx_to_die() {} 69 70DWARFASTParserClang::~DWARFASTParserClang() = default; 71 72static bool DeclKindIsCXXClass(clang::Decl::Kind decl_kind) { 73 switch (decl_kind) { 74 case clang::Decl::CXXRecord: 75 case clang::Decl::ClassTemplateSpecialization: 76 return true; 77 default: 78 break; 79 } 80 return false; 81} 82 83 84ClangASTImporter &DWARFASTParserClang::GetClangASTImporter() { 85 if (!m_clang_ast_importer_up) { 86 m_clang_ast_importer_up = std::make_unique<ClangASTImporter>(); 87 } 88 return *m_clang_ast_importer_up; 89} 90 91/// Detect a forward declaration that is nested in a DW_TAG_module. 92static bool IsClangModuleFwdDecl(const DWARFDIE &Die) { 93 if (!Die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0)) 94 return false; 95 auto Parent = Die.GetParent(); 96 while (Parent.IsValid()) { 97 if (Parent.Tag() == DW_TAG_module) 98 return true; 99 Parent = Parent.GetParent(); 100 } 101 return false; 102} 103 104static DWARFDIE GetContainingClangModuleDIE(const DWARFDIE &die) { 105 if (die.IsValid()) { 106 DWARFDIE top_module_die; 107 // Now make sure this DIE is scoped in a DW_TAG_module tag and return true 108 // if so 109 for (DWARFDIE parent = die.GetParent(); parent.IsValid(); 110 parent = parent.GetParent()) { 111 const dw_tag_t tag = parent.Tag(); 112 if (tag == DW_TAG_module) 113 top_module_die = parent; 114 else if (tag == DW_TAG_compile_unit || tag == DW_TAG_partial_unit) 115 break; 116 } 117 118 return top_module_die; 119 } 120 return DWARFDIE(); 121} 122 123static lldb::ModuleSP GetContainingClangModule(const DWARFDIE &die) { 124 if (die.IsValid()) { 125 DWARFDIE clang_module_die = GetContainingClangModuleDIE(die); 126 127 if (clang_module_die) { 128 const char *module_name = clang_module_die.GetName(); 129 if (module_name) 130 return die.GetDWARF()->GetExternalModule( 131 lldb_private::ConstString(module_name)); 132 } 133 } 134 return lldb::ModuleSP(); 135} 136 137// Returns true if the given artificial field name should be ignored when 138// parsing the DWARF. 139static bool ShouldIgnoreArtificialField(llvm::StringRef FieldName) { 140 return FieldName.starts_with("_vptr$") 141 // gdb emit vtable pointer as "_vptr.classname" 142 || FieldName.starts_with("_vptr."); 143} 144 145/// Returns true for C++ constructs represented by clang::CXXRecordDecl 146static bool TagIsRecordType(dw_tag_t tag) { 147 switch (tag) { 148 case DW_TAG_class_type: 149 case DW_TAG_structure_type: 150 case DW_TAG_union_type: 151 return true; 152 default: 153 return false; 154 } 155} 156 157TypeSP DWARFASTParserClang::ParseTypeFromClangModule(const SymbolContext &sc, 158 const DWARFDIE &die, 159 Log *log) { 160 ModuleSP clang_module_sp = GetContainingClangModule(die); 161 if (!clang_module_sp) 162 return TypeSP(); 163 164 // If this type comes from a Clang module, recursively look in the 165 // DWARF section of the .pcm file in the module cache. Clang 166 // generates DWO skeleton units as breadcrumbs to find them. 167 std::vector<lldb_private::CompilerContext> die_context = die.GetDeclContext(); 168 TypeQuery query(die_context, TypeQueryOptions::e_module_search | 169 TypeQueryOptions::e_find_one); 170 TypeResults results; 171 172 // The type in the Clang module must have the same language as the current CU. 173 query.AddLanguage(SymbolFileDWARF::GetLanguageFamily(*die.GetCU())); 174 clang_module_sp->FindTypes(query, results); 175 TypeSP pcm_type_sp = results.GetTypeMap().FirstType(); 176 if (!pcm_type_sp) { 177 // Since this type is defined in one of the Clang modules imported 178 // by this symbol file, search all of them. Instead of calling 179 // sym_file->FindTypes(), which would return this again, go straight 180 // to the imported modules. 181 auto &sym_file = die.GetCU()->GetSymbolFileDWARF(); 182 183 // Well-formed clang modules never form cycles; guard against corrupted 184 // ones by inserting the current file. 185 results.AlreadySearched(&sym_file); 186 sym_file.ForEachExternalModule( 187 *sc.comp_unit, results.GetSearchedSymbolFiles(), [&](Module &module) { 188 module.FindTypes(query, results); 189 pcm_type_sp = results.GetTypeMap().FirstType(); 190 return (bool)pcm_type_sp; 191 }); 192 } 193 194 if (!pcm_type_sp) 195 return TypeSP(); 196 197 // We found a real definition for this type in the Clang module, so lets use 198 // it and cache the fact that we found a complete type for this die. 199 lldb_private::CompilerType pcm_type = pcm_type_sp->GetForwardCompilerType(); 200 lldb_private::CompilerType type = 201 GetClangASTImporter().CopyType(m_ast, pcm_type); 202 203 if (!type) 204 return TypeSP(); 205 206 // Under normal operation pcm_type is a shallow forward declaration 207 // that gets completed later. This is necessary to support cyclic 208 // data structures. If, however, pcm_type is already complete (for 209 // example, because it was loaded for a different target before), 210 // the definition needs to be imported right away, too. 211 // Type::ResolveClangType() effectively ignores the ResolveState 212 // inside type_sp and only looks at IsDefined(), so it never calls 213 // ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo(), 214 // which does extra work for Objective-C classes. This would result 215 // in only the forward declaration to be visible. 216 if (pcm_type.IsDefined()) 217 GetClangASTImporter().RequireCompleteType(ClangUtil::GetQualType(type)); 218 219 SymbolFileDWARF *dwarf = die.GetDWARF(); 220 auto type_sp = dwarf->MakeType( 221 die.GetID(), pcm_type_sp->GetName(), pcm_type_sp->GetByteSize(nullptr), 222 nullptr, LLDB_INVALID_UID, Type::eEncodingInvalid, 223 &pcm_type_sp->GetDeclaration(), type, Type::ResolveState::Forward, 224 TypePayloadClang(GetOwningClangModule(die))); 225 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); 226 clang::TagDecl *tag_decl = TypeSystemClang::GetAsTagDecl(type); 227 if (tag_decl) { 228 LinkDeclContextToDIE(tag_decl, die); 229 } else { 230 clang::DeclContext *defn_decl_ctx = GetCachedClangDeclContextForDIE(die); 231 if (defn_decl_ctx) 232 LinkDeclContextToDIE(defn_decl_ctx, die); 233 } 234 235 return type_sp; 236} 237 238static void ForcefullyCompleteType(CompilerType type) { 239 bool started = TypeSystemClang::StartTagDeclarationDefinition(type); 240 lldbassert(started && "Unable to start a class type definition."); 241 TypeSystemClang::CompleteTagDeclarationDefinition(type); 242 const clang::TagDecl *td = ClangUtil::GetAsTagDecl(type); 243 auto ts_sp = type.GetTypeSystem(); 244 auto ts = ts_sp.dyn_cast_or_null<TypeSystemClang>(); 245 if (ts) 246 ts->SetDeclIsForcefullyCompleted(td); 247} 248 249/// This function serves a similar purpose as RequireCompleteType above, but it 250/// avoids completing the type if it is not immediately necessary. It only 251/// ensures we _can_ complete the type later. 252static void PrepareContextToReceiveMembers(TypeSystemClang &ast, 253 ClangASTImporter &ast_importer, 254 clang::DeclContext *decl_ctx, 255 DWARFDIE die, 256 const char *type_name_cstr) { 257 auto *tag_decl_ctx = clang::dyn_cast<clang::TagDecl>(decl_ctx); 258 if (!tag_decl_ctx) 259 return; // Non-tag context are always ready. 260 261 // We have already completed the type, or we have found its definition and are 262 // ready to complete it later (cf. ParseStructureLikeDIE). 263 if (tag_decl_ctx->isCompleteDefinition() || tag_decl_ctx->isBeingDefined()) 264 return; 265 266 // We reach this point of the tag was present in the debug info as a 267 // declaration only. If it was imported from another AST context (in the 268 // gmodules case), we can complete the type by doing a full import. 269 270 // If this type was not imported from an external AST, there's nothing to do. 271 CompilerType type = ast.GetTypeForDecl(tag_decl_ctx); 272 if (type && ast_importer.CanImport(type)) { 273 auto qual_type = ClangUtil::GetQualType(type); 274 if (ast_importer.RequireCompleteType(qual_type)) 275 return; 276 die.GetDWARF()->GetObjectFile()->GetModule()->ReportError( 277 "Unable to complete the Decl context for DIE {0} at offset " 278 "{1:x16}.\nPlease file a bug report.", 279 type_name_cstr ? type_name_cstr : "", die.GetOffset()); 280 } 281 282 // We don't have a type definition and/or the import failed. We must 283 // forcefully complete the type to avoid crashes. 284 ForcefullyCompleteType(type); 285} 286 287ParsedDWARFTypeAttributes::ParsedDWARFTypeAttributes(const DWARFDIE &die) { 288 DWARFAttributes attributes = die.GetAttributes(); 289 for (size_t i = 0; i < attributes.Size(); ++i) { 290 dw_attr_t attr = attributes.AttributeAtIndex(i); 291 DWARFFormValue form_value; 292 if (!attributes.ExtractFormValueAtIndex(i, form_value)) 293 continue; 294 switch (attr) { 295 default: 296 break; 297 case DW_AT_abstract_origin: 298 abstract_origin = form_value; 299 break; 300 301 case DW_AT_accessibility: 302 accessibility = 303 DWARFASTParser::GetAccessTypeFromDWARF(form_value.Unsigned()); 304 break; 305 306 case DW_AT_artificial: 307 is_artificial = form_value.Boolean(); 308 break; 309 310 case DW_AT_bit_stride: 311 bit_stride = form_value.Unsigned(); 312 break; 313 314 case DW_AT_byte_size: 315 byte_size = form_value.Unsigned(); 316 break; 317 318 case DW_AT_alignment: 319 alignment = form_value.Unsigned(); 320 break; 321 322 case DW_AT_byte_stride: 323 byte_stride = form_value.Unsigned(); 324 break; 325 326 case DW_AT_calling_convention: 327 calling_convention = form_value.Unsigned(); 328 break; 329 330 case DW_AT_containing_type: 331 containing_type = form_value; 332 break; 333 334 case DW_AT_decl_file: 335 // die.GetCU() can differ if DW_AT_specification uses DW_FORM_ref_addr. 336 decl.SetFile( 337 attributes.CompileUnitAtIndex(i)->GetFile(form_value.Unsigned())); 338 break; 339 case DW_AT_decl_line: 340 decl.SetLine(form_value.Unsigned()); 341 break; 342 case DW_AT_decl_column: 343 decl.SetColumn(form_value.Unsigned()); 344 break; 345 346 case DW_AT_declaration: 347 is_forward_declaration = form_value.Boolean(); 348 break; 349 350 case DW_AT_encoding: 351 encoding = form_value.Unsigned(); 352 break; 353 354 case DW_AT_enum_class: 355 is_scoped_enum = form_value.Boolean(); 356 break; 357 358 case DW_AT_explicit: 359 is_explicit = form_value.Boolean(); 360 break; 361 362 case DW_AT_external: 363 if (form_value.Unsigned()) 364 storage = clang::SC_Extern; 365 break; 366 367 case DW_AT_inline: 368 is_inline = form_value.Boolean(); 369 break; 370 371 case DW_AT_linkage_name: 372 case DW_AT_MIPS_linkage_name: 373 mangled_name = form_value.AsCString(); 374 break; 375 376 case DW_AT_name: 377 name.SetCString(form_value.AsCString()); 378 break; 379 380 case DW_AT_object_pointer: 381 object_pointer = form_value.Reference(); 382 break; 383 384 case DW_AT_signature: 385 signature = form_value; 386 break; 387 388 case DW_AT_specification: 389 specification = form_value; 390 break; 391 392 case DW_AT_type: 393 type = form_value; 394 break; 395 396 case DW_AT_virtuality: 397 is_virtual = form_value.Boolean(); 398 break; 399 400 case DW_AT_APPLE_objc_complete_type: 401 is_complete_objc_class = form_value.Signed(); 402 break; 403 404 case DW_AT_APPLE_objc_direct: 405 is_objc_direct_call = true; 406 break; 407 408 case DW_AT_APPLE_runtime_class: 409 class_language = (LanguageType)form_value.Signed(); 410 break; 411 412 case DW_AT_GNU_vector: 413 is_vector = form_value.Boolean(); 414 break; 415 case DW_AT_export_symbols: 416 exports_symbols = form_value.Boolean(); 417 break; 418 case DW_AT_rvalue_reference: 419 ref_qual = clang::RQ_RValue; 420 break; 421 case DW_AT_reference: 422 ref_qual = clang::RQ_LValue; 423 break; 424 } 425 } 426} 427 428static std::string GetUnitName(const DWARFDIE &die) { 429 if (DWARFUnit *unit = die.GetCU()) 430 return unit->GetAbsolutePath().GetPath(); 431 return "<missing DWARF unit path>"; 432} 433 434TypeSP DWARFASTParserClang::ParseTypeFromDWARF(const SymbolContext &sc, 435 const DWARFDIE &die, 436 bool *type_is_new_ptr) { 437 if (type_is_new_ptr) 438 *type_is_new_ptr = false; 439 440 if (!die) 441 return nullptr; 442 443 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups); 444 445 SymbolFileDWARF *dwarf = die.GetDWARF(); 446 if (log) { 447 DWARFDIE context_die; 448 clang::DeclContext *context = 449 GetClangDeclContextContainingDIE(die, &context_die); 450 451 dwarf->GetObjectFile()->GetModule()->LogMessage( 452 log, 453 "DWARFASTParserClang::ParseTypeFromDWARF " 454 "(die = {0:x16}, decl_ctx = {1:p} (die " 455 "{2:x16})) {3} name = '{4}')", 456 die.GetOffset(), static_cast<void *>(context), context_die.GetOffset(), 457 die.GetTagAsCString(), die.GetName()); 458 } 459 460 Type *type_ptr = dwarf->GetDIEToType().lookup(die.GetDIE()); 461 if (type_ptr == DIE_IS_BEING_PARSED) 462 return nullptr; 463 if (type_ptr) 464 return type_ptr->shared_from_this(); 465 // Set a bit that lets us know that we are currently parsing this 466 dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED; 467 468 ParsedDWARFTypeAttributes attrs(die); 469 470 if (DWARFDIE signature_die = attrs.signature.Reference()) { 471 if (TypeSP type_sp = 472 ParseTypeFromDWARF(sc, signature_die, type_is_new_ptr)) { 473 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); 474 if (clang::DeclContext *decl_ctx = 475 GetCachedClangDeclContextForDIE(signature_die)) 476 LinkDeclContextToDIE(decl_ctx, die); 477 return type_sp; 478 } 479 return nullptr; 480 } 481 482 if (type_is_new_ptr) 483 *type_is_new_ptr = true; 484 485 const dw_tag_t tag = die.Tag(); 486 487 TypeSP type_sp; 488 489 switch (tag) { 490 case DW_TAG_typedef: 491 case DW_TAG_base_type: 492 case DW_TAG_pointer_type: 493 case DW_TAG_reference_type: 494 case DW_TAG_rvalue_reference_type: 495 case DW_TAG_const_type: 496 case DW_TAG_restrict_type: 497 case DW_TAG_volatile_type: 498 case DW_TAG_atomic_type: 499 case DW_TAG_unspecified_type: { 500 type_sp = ParseTypeModifier(sc, die, attrs); 501 break; 502 } 503 504 case DW_TAG_structure_type: 505 case DW_TAG_union_type: 506 case DW_TAG_class_type: { 507 type_sp = ParseStructureLikeDIE(sc, die, attrs); 508 break; 509 } 510 511 case DW_TAG_enumeration_type: { 512 type_sp = ParseEnum(sc, die, attrs); 513 break; 514 } 515 516 case DW_TAG_inlined_subroutine: 517 case DW_TAG_subprogram: 518 case DW_TAG_subroutine_type: { 519 type_sp = ParseSubroutine(die, attrs); 520 break; 521 } 522 case DW_TAG_array_type: { 523 type_sp = ParseArrayType(die, attrs); 524 break; 525 } 526 case DW_TAG_ptr_to_member_type: { 527 type_sp = ParsePointerToMemberType(die, attrs); 528 break; 529 } 530 default: 531 dwarf->GetObjectFile()->GetModule()->ReportError( 532 "[{0:x16}]: unhandled type tag {1:x4} ({2}), " 533 "please file a bug and " 534 "attach the file at the start of this error message", 535 die.GetOffset(), tag, DW_TAG_value_to_name(tag)); 536 break; 537 } 538 539 // TODO: We should consider making the switch above exhaustive to simplify 540 // control flow in ParseTypeFromDWARF. Then, we could simply replace this 541 // return statement with a call to llvm_unreachable. 542 return UpdateSymbolContextScopeForType(sc, die, type_sp); 543} 544 545static std::optional<uint32_t> 546ExtractDataMemberLocation(DWARFDIE const &die, DWARFFormValue const &form_value, 547 ModuleSP module_sp) { 548 // With DWARF 3 and later, if the value is an integer constant, 549 // this form value is the offset in bytes from the beginning of 550 // the containing entity. 551 if (!form_value.BlockData()) 552 return form_value.Unsigned(); 553 554 Value initialValue(0); 555 Value memberOffset(0); 556 const DWARFDataExtractor &debug_info_data = die.GetData(); 557 uint32_t block_length = form_value.Unsigned(); 558 uint32_t block_offset = 559 form_value.BlockData() - debug_info_data.GetDataStart(); 560 if (!DWARFExpression::Evaluate( 561 nullptr, // ExecutionContext * 562 nullptr, // RegisterContext * 563 module_sp, DataExtractor(debug_info_data, block_offset, block_length), 564 die.GetCU(), eRegisterKindDWARF, &initialValue, nullptr, memberOffset, 565 nullptr)) { 566 return {}; 567 } 568 569 return memberOffset.ResolveValue(nullptr).UInt(); 570} 571 572lldb::TypeSP 573DWARFASTParserClang::ParseTypeModifier(const SymbolContext &sc, 574 const DWARFDIE &die, 575 ParsedDWARFTypeAttributes &attrs) { 576 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups); 577 SymbolFileDWARF *dwarf = die.GetDWARF(); 578 const dw_tag_t tag = die.Tag(); 579 LanguageType cu_language = SymbolFileDWARF::GetLanguage(*die.GetCU()); 580 Type::ResolveState resolve_state = Type::ResolveState::Unresolved; 581 Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID; 582 TypeSP type_sp; 583 CompilerType clang_type; 584 585 if (tag == DW_TAG_typedef) { 586 // DeclContext will be populated when the clang type is materialized in 587 // Type::ResolveCompilerType. 588 PrepareContextToReceiveMembers( 589 m_ast, GetClangASTImporter(), 590 GetClangDeclContextContainingDIE(die, nullptr), die, 591 attrs.name.GetCString()); 592 593 if (attrs.type.IsValid()) { 594 // Try to parse a typedef from the (DWARF embedded in the) Clang 595 // module file first as modules can contain typedef'ed 596 // structures that have no names like: 597 // 598 // typedef struct { int a; } Foo; 599 // 600 // In this case we will have a structure with no name and a 601 // typedef named "Foo" that points to this unnamed 602 // structure. The name in the typedef is the only identifier for 603 // the struct, so always try to get typedefs from Clang modules 604 // if possible. 605 // 606 // The type_sp returned will be empty if the typedef doesn't 607 // exist in a module file, so it is cheap to call this function 608 // just to check. 609 // 610 // If we don't do this we end up creating a TypeSP that says 611 // this is a typedef to type 0x123 (the DW_AT_type value would 612 // be 0x123 in the DW_TAG_typedef), and this is the unnamed 613 // structure type. We will have a hard time tracking down an 614 // unnammed structure type in the module debug info, so we make 615 // sure we don't get into this situation by always resolving 616 // typedefs from the module. 617 const DWARFDIE encoding_die = attrs.type.Reference(); 618 619 // First make sure that the die that this is typedef'ed to _is_ 620 // just a declaration (DW_AT_declaration == 1), not a full 621 // definition since template types can't be represented in 622 // modules since only concrete instances of templates are ever 623 // emitted and modules won't contain those 624 if (encoding_die && 625 encoding_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) { 626 type_sp = ParseTypeFromClangModule(sc, die, log); 627 if (type_sp) 628 return type_sp; 629 } 630 } 631 } 632 633 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n", die.GetID(), 634 DW_TAG_value_to_name(tag), type_name_cstr, 635 encoding_uid.Reference()); 636 637 switch (tag) { 638 default: 639 break; 640 641 case DW_TAG_unspecified_type: 642 if (attrs.name == "nullptr_t" || attrs.name == "decltype(nullptr)") { 643 resolve_state = Type::ResolveState::Full; 644 clang_type = m_ast.GetBasicType(eBasicTypeNullPtr); 645 break; 646 } 647 // Fall through to base type below in case we can handle the type 648 // there... 649 [[fallthrough]]; 650 651 case DW_TAG_base_type: 652 resolve_state = Type::ResolveState::Full; 653 clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize( 654 attrs.name.GetStringRef(), attrs.encoding, 655 attrs.byte_size.value_or(0) * 8); 656 break; 657 658 case DW_TAG_pointer_type: 659 encoding_data_type = Type::eEncodingIsPointerUID; 660 break; 661 case DW_TAG_reference_type: 662 encoding_data_type = Type::eEncodingIsLValueReferenceUID; 663 break; 664 case DW_TAG_rvalue_reference_type: 665 encoding_data_type = Type::eEncodingIsRValueReferenceUID; 666 break; 667 case DW_TAG_typedef: 668 encoding_data_type = Type::eEncodingIsTypedefUID; 669 break; 670 case DW_TAG_const_type: 671 encoding_data_type = Type::eEncodingIsConstUID; 672 break; 673 case DW_TAG_restrict_type: 674 encoding_data_type = Type::eEncodingIsRestrictUID; 675 break; 676 case DW_TAG_volatile_type: 677 encoding_data_type = Type::eEncodingIsVolatileUID; 678 break; 679 case DW_TAG_atomic_type: 680 encoding_data_type = Type::eEncodingIsAtomicUID; 681 break; 682 } 683 684 if (!clang_type && (encoding_data_type == Type::eEncodingIsPointerUID || 685 encoding_data_type == Type::eEncodingIsTypedefUID)) { 686 if (tag == DW_TAG_pointer_type) { 687 DWARFDIE target_die = die.GetReferencedDIE(DW_AT_type); 688 689 if (target_die.GetAttributeValueAsUnsigned(DW_AT_APPLE_block, 0)) { 690 // Blocks have a __FuncPtr inside them which is a pointer to a 691 // function of the proper type. 692 693 for (DWARFDIE child_die : target_die.children()) { 694 if (!strcmp(child_die.GetAttributeValueAsString(DW_AT_name, ""), 695 "__FuncPtr")) { 696 DWARFDIE function_pointer_type = 697 child_die.GetReferencedDIE(DW_AT_type); 698 699 if (function_pointer_type) { 700 DWARFDIE function_type = 701 function_pointer_type.GetReferencedDIE(DW_AT_type); 702 703 bool function_type_is_new_pointer; 704 TypeSP lldb_function_type_sp = ParseTypeFromDWARF( 705 sc, function_type, &function_type_is_new_pointer); 706 707 if (lldb_function_type_sp) { 708 clang_type = m_ast.CreateBlockPointerType( 709 lldb_function_type_sp->GetForwardCompilerType()); 710 encoding_data_type = Type::eEncodingIsUID; 711 attrs.type.Clear(); 712 resolve_state = Type::ResolveState::Full; 713 } 714 } 715 716 break; 717 } 718 } 719 } 720 } 721 722 if (cu_language == eLanguageTypeObjC || 723 cu_language == eLanguageTypeObjC_plus_plus) { 724 if (attrs.name) { 725 if (attrs.name == "id") { 726 if (log) 727 dwarf->GetObjectFile()->GetModule()->LogMessage( 728 log, 729 "SymbolFileDWARF::ParseType (die = {0:x16}) {1} '{2}' " 730 "is Objective-C 'id' built-in type.", 731 die.GetOffset(), die.GetTagAsCString(), die.GetName()); 732 clang_type = m_ast.GetBasicType(eBasicTypeObjCID); 733 encoding_data_type = Type::eEncodingIsUID; 734 attrs.type.Clear(); 735 resolve_state = Type::ResolveState::Full; 736 } else if (attrs.name == "Class") { 737 if (log) 738 dwarf->GetObjectFile()->GetModule()->LogMessage( 739 log, 740 "SymbolFileDWARF::ParseType (die = {0:x16}) {1} '{2}' " 741 "is Objective-C 'Class' built-in type.", 742 die.GetOffset(), die.GetTagAsCString(), die.GetName()); 743 clang_type = m_ast.GetBasicType(eBasicTypeObjCClass); 744 encoding_data_type = Type::eEncodingIsUID; 745 attrs.type.Clear(); 746 resolve_state = Type::ResolveState::Full; 747 } else if (attrs.name == "SEL") { 748 if (log) 749 dwarf->GetObjectFile()->GetModule()->LogMessage( 750 log, 751 "SymbolFileDWARF::ParseType (die = {0:x16}) {1} '{2}' " 752 "is Objective-C 'selector' built-in type.", 753 die.GetOffset(), die.GetTagAsCString(), die.GetName()); 754 clang_type = m_ast.GetBasicType(eBasicTypeObjCSel); 755 encoding_data_type = Type::eEncodingIsUID; 756 attrs.type.Clear(); 757 resolve_state = Type::ResolveState::Full; 758 } 759 } else if (encoding_data_type == Type::eEncodingIsPointerUID && 760 attrs.type.IsValid()) { 761 // Clang sometimes erroneously emits id as objc_object*. In that 762 // case we fix up the type to "id". 763 764 const DWARFDIE encoding_die = attrs.type.Reference(); 765 766 if (encoding_die && encoding_die.Tag() == DW_TAG_structure_type) { 767 llvm::StringRef struct_name = encoding_die.GetName(); 768 if (struct_name == "objc_object") { 769 if (log) 770 dwarf->GetObjectFile()->GetModule()->LogMessage( 771 log, 772 "SymbolFileDWARF::ParseType (die = {0:x16}) {1} " 773 "'{2}' is 'objc_object*', which we overrode to " 774 "'id'.", 775 die.GetOffset(), die.GetTagAsCString(), die.GetName()); 776 clang_type = m_ast.GetBasicType(eBasicTypeObjCID); 777 encoding_data_type = Type::eEncodingIsUID; 778 attrs.type.Clear(); 779 resolve_state = Type::ResolveState::Full; 780 } 781 } 782 } 783 } 784 } 785 786 type_sp = dwarf->MakeType(die.GetID(), attrs.name, attrs.byte_size, nullptr, 787 attrs.type.Reference().GetID(), encoding_data_type, 788 &attrs.decl, clang_type, resolve_state, 789 TypePayloadClang(GetOwningClangModule(die))); 790 791 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); 792 return type_sp; 793} 794 795ConstString 796DWARFASTParserClang::GetDIEClassTemplateParams(const DWARFDIE &die) { 797 if (llvm::StringRef(die.GetName()).contains("<")) 798 return ConstString(); 799 800 TypeSystemClang::TemplateParameterInfos template_param_infos; 801 if (ParseTemplateParameterInfos(die, template_param_infos)) { 802 return ConstString(m_ast.PrintTemplateParams(template_param_infos)); 803 } 804 return ConstString(); 805} 806 807TypeSP DWARFASTParserClang::ParseEnum(const SymbolContext &sc, 808 const DWARFDIE &die, 809 ParsedDWARFTypeAttributes &attrs) { 810 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups); 811 SymbolFileDWARF *dwarf = die.GetDWARF(); 812 const dw_tag_t tag = die.Tag(); 813 TypeSP type_sp; 814 815 if (attrs.is_forward_declaration) { 816 type_sp = ParseTypeFromClangModule(sc, die, log); 817 if (type_sp) 818 return type_sp; 819 820 type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die); 821 822 if (!type_sp) { 823 SymbolFileDWARFDebugMap *debug_map_symfile = dwarf->GetDebugMapSymfile(); 824 if (debug_map_symfile) { 825 // We weren't able to find a full declaration in this DWARF, 826 // see if we have a declaration anywhere else... 827 type_sp = debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(die); 828 } 829 } 830 831 if (type_sp) { 832 if (log) { 833 dwarf->GetObjectFile()->GetModule()->LogMessage( 834 log, 835 "SymbolFileDWARF({0:p}) - {1:x16}}: {2} type \"{3}\" is a " 836 "forward declaration, complete type is {4:x8}", 837 static_cast<void *>(this), die.GetOffset(), 838 DW_TAG_value_to_name(tag), attrs.name.GetCString(), 839 type_sp->GetID()); 840 } 841 842 // We found a real definition for this type elsewhere so lets use 843 // it and cache the fact that we found a complete type for this 844 // die 845 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); 846 clang::DeclContext *defn_decl_ctx = 847 GetCachedClangDeclContextForDIE(dwarf->GetDIE(type_sp->GetID())); 848 if (defn_decl_ctx) 849 LinkDeclContextToDIE(defn_decl_ctx, die); 850 return type_sp; 851 } 852 } 853 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), 854 DW_TAG_value_to_name(tag), type_name_cstr); 855 856 CompilerType enumerator_clang_type; 857 CompilerType clang_type; 858 clang_type = CompilerType( 859 m_ast.weak_from_this(), 860 dwarf->GetForwardDeclDIEToCompilerType().lookup(die.GetDIE())); 861 if (!clang_type) { 862 if (attrs.type.IsValid()) { 863 Type *enumerator_type = 864 dwarf->ResolveTypeUID(attrs.type.Reference(), true); 865 if (enumerator_type) 866 enumerator_clang_type = enumerator_type->GetFullCompilerType(); 867 } 868 869 if (!enumerator_clang_type) { 870 if (attrs.byte_size) { 871 enumerator_clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize( 872 "", DW_ATE_signed, *attrs.byte_size * 8); 873 } else { 874 enumerator_clang_type = m_ast.GetBasicType(eBasicTypeInt); 875 } 876 } 877 878 clang_type = m_ast.CreateEnumerationType( 879 attrs.name.GetStringRef(), 880 GetClangDeclContextContainingDIE(die, nullptr), 881 GetOwningClangModule(die), attrs.decl, enumerator_clang_type, 882 attrs.is_scoped_enum); 883 } else { 884 enumerator_clang_type = m_ast.GetEnumerationIntegerType(clang_type); 885 } 886 887 LinkDeclContextToDIE(TypeSystemClang::GetDeclContextForType(clang_type), die); 888 889 type_sp = 890 dwarf->MakeType(die.GetID(), attrs.name, attrs.byte_size, nullptr, 891 attrs.type.Reference().GetID(), Type::eEncodingIsUID, 892 &attrs.decl, clang_type, Type::ResolveState::Forward, 893 TypePayloadClang(GetOwningClangModule(die))); 894 895 if (TypeSystemClang::StartTagDeclarationDefinition(clang_type)) { 896 if (die.HasChildren()) { 897 bool is_signed = false; 898 enumerator_clang_type.IsIntegerType(is_signed); 899 ParseChildEnumerators(clang_type, is_signed, 900 type_sp->GetByteSize(nullptr).value_or(0), die); 901 } 902 TypeSystemClang::CompleteTagDeclarationDefinition(clang_type); 903 } else { 904 dwarf->GetObjectFile()->GetModule()->ReportError( 905 "DWARF DIE at {0:x16} named \"{1}\" was not able to start its " 906 "definition.\nPlease file a bug and attach the file at the " 907 "start of this error message", 908 die.GetOffset(), attrs.name.GetCString()); 909 } 910 return type_sp; 911} 912 913static clang::CallingConv 914ConvertDWARFCallingConventionToClang(const ParsedDWARFTypeAttributes &attrs) { 915 switch (attrs.calling_convention) { 916 case llvm::dwarf::DW_CC_normal: 917 return clang::CC_C; 918 case llvm::dwarf::DW_CC_BORLAND_stdcall: 919 return clang::CC_X86StdCall; 920 case llvm::dwarf::DW_CC_BORLAND_msfastcall: 921 return clang::CC_X86FastCall; 922 case llvm::dwarf::DW_CC_LLVM_vectorcall: 923 return clang::CC_X86VectorCall; 924 case llvm::dwarf::DW_CC_BORLAND_pascal: 925 return clang::CC_X86Pascal; 926 case llvm::dwarf::DW_CC_LLVM_Win64: 927 return clang::CC_Win64; 928 case llvm::dwarf::DW_CC_LLVM_X86_64SysV: 929 return clang::CC_X86_64SysV; 930 case llvm::dwarf::DW_CC_LLVM_X86RegCall: 931 return clang::CC_X86RegCall; 932 default: 933 break; 934 } 935 936 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups); 937 LLDB_LOG(log, "Unsupported DW_AT_calling_convention value: {0}", 938 attrs.calling_convention); 939 // Use the default calling convention as a fallback. 940 return clang::CC_C; 941} 942 943TypeSP 944DWARFASTParserClang::ParseSubroutine(const DWARFDIE &die, 945 const ParsedDWARFTypeAttributes &attrs) { 946 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups); 947 948 SymbolFileDWARF *dwarf = die.GetDWARF(); 949 const dw_tag_t tag = die.Tag(); 950 951 bool is_variadic = false; 952 bool is_static = false; 953 bool has_template_params = false; 954 955 unsigned type_quals = 0; 956 957 std::string object_pointer_name; 958 if (attrs.object_pointer) { 959 const char *object_pointer_name_cstr = attrs.object_pointer.GetName(); 960 if (object_pointer_name_cstr) 961 object_pointer_name = object_pointer_name_cstr; 962 } 963 964 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), 965 DW_TAG_value_to_name(tag), type_name_cstr); 966 967 CompilerType return_clang_type; 968 Type *func_type = nullptr; 969 970 if (attrs.type.IsValid()) 971 func_type = dwarf->ResolveTypeUID(attrs.type.Reference(), true); 972 973 if (func_type) 974 return_clang_type = func_type->GetForwardCompilerType(); 975 else 976 return_clang_type = m_ast.GetBasicType(eBasicTypeVoid); 977 978 std::vector<CompilerType> function_param_types; 979 std::vector<clang::ParmVarDecl *> function_param_decls; 980 981 // Parse the function children for the parameters 982 983 DWARFDIE decl_ctx_die; 984 clang::DeclContext *containing_decl_ctx = 985 GetClangDeclContextContainingDIE(die, &decl_ctx_die); 986 const clang::Decl::Kind containing_decl_kind = 987 containing_decl_ctx->getDeclKind(); 988 989 bool is_cxx_method = DeclKindIsCXXClass(containing_decl_kind); 990 // Start off static. This will be set to false in 991 // ParseChildParameters(...) if we find a "this" parameters as the 992 // first parameter 993 if (is_cxx_method) { 994 is_static = true; 995 } 996 997 if (die.HasChildren()) { 998 bool skip_artificial = true; 999 ParseChildParameters(containing_decl_ctx, die, skip_artificial, is_static, 1000 is_variadic, has_template_params, 1001 function_param_types, function_param_decls, 1002 type_quals); 1003 } 1004 1005 bool ignore_containing_context = false; 1006 // Check for templatized class member functions. If we had any 1007 // DW_TAG_template_type_parameter or DW_TAG_template_value_parameter 1008 // the DW_TAG_subprogram DIE, then we can't let this become a method in 1009 // a class. Why? Because templatized functions are only emitted if one 1010 // of the templatized methods is used in the current compile unit and 1011 // we will end up with classes that may or may not include these member 1012 // functions and this means one class won't match another class 1013 // definition and it affects our ability to use a class in the clang 1014 // expression parser. So for the greater good, we currently must not 1015 // allow any template member functions in a class definition. 1016 if (is_cxx_method && has_template_params) { 1017 ignore_containing_context = true; 1018 is_cxx_method = false; 1019 } 1020 1021 clang::CallingConv calling_convention = 1022 ConvertDWARFCallingConventionToClang(attrs); 1023 1024 // clang_type will get the function prototype clang type after this 1025 // call 1026 CompilerType clang_type = 1027 m_ast.CreateFunctionType(return_clang_type, function_param_types.data(), 1028 function_param_types.size(), is_variadic, 1029 type_quals, calling_convention, attrs.ref_qual); 1030 1031 if (attrs.name) { 1032 bool type_handled = false; 1033 if (tag == DW_TAG_subprogram || tag == DW_TAG_inlined_subroutine) { 1034 std::optional<const ObjCLanguage::MethodName> objc_method = 1035 ObjCLanguage::MethodName::Create(attrs.name.GetStringRef(), true); 1036 if (objc_method) { 1037 CompilerType class_opaque_type; 1038 ConstString class_name(objc_method->GetClassName()); 1039 if (class_name) { 1040 TypeSP complete_objc_class_type_sp( 1041 dwarf->FindCompleteObjCDefinitionTypeForDIE(DWARFDIE(), 1042 class_name, false)); 1043 1044 if (complete_objc_class_type_sp) { 1045 CompilerType type_clang_forward_type = 1046 complete_objc_class_type_sp->GetForwardCompilerType(); 1047 if (TypeSystemClang::IsObjCObjectOrInterfaceType( 1048 type_clang_forward_type)) 1049 class_opaque_type = type_clang_forward_type; 1050 } 1051 } 1052 1053 if (class_opaque_type) { 1054 clang::ObjCMethodDecl *objc_method_decl = 1055 m_ast.AddMethodToObjCObjectType( 1056 class_opaque_type, attrs.name.GetCString(), clang_type, 1057 attrs.is_artificial, is_variadic, attrs.is_objc_direct_call); 1058 type_handled = objc_method_decl != nullptr; 1059 if (type_handled) { 1060 LinkDeclContextToDIE(objc_method_decl, die); 1061 m_ast.SetMetadataAsUserID(objc_method_decl, die.GetID()); 1062 } else { 1063 dwarf->GetObjectFile()->GetModule()->ReportError( 1064 "[{0:x16}]: invalid Objective-C method {1:x4} ({2}), " 1065 "please file a bug and attach the file at the start of " 1066 "this error message", 1067 die.GetOffset(), tag, DW_TAG_value_to_name(tag)); 1068 } 1069 } 1070 } else if (is_cxx_method) { 1071 // Look at the parent of this DIE and see if it is a class or 1072 // struct and see if this is actually a C++ method 1073 Type *class_type = dwarf->ResolveType(decl_ctx_die); 1074 if (class_type) { 1075 if (class_type->GetID() != decl_ctx_die.GetID() || 1076 IsClangModuleFwdDecl(decl_ctx_die)) { 1077 1078 // We uniqued the parent class of this function to another 1079 // class so we now need to associate all dies under 1080 // "decl_ctx_die" to DIEs in the DIE for "class_type"... 1081 DWARFDIE class_type_die = dwarf->GetDIE(class_type->GetID()); 1082 1083 if (class_type_die) { 1084 std::vector<DWARFDIE> failures; 1085 1086 CopyUniqueClassMethodTypes(decl_ctx_die, class_type_die, 1087 class_type, failures); 1088 1089 // FIXME do something with these failures that's 1090 // smarter than just dropping them on the ground. 1091 // Unfortunately classes don't like having stuff added 1092 // to them after their definitions are complete... 1093 1094 Type *type_ptr = dwarf->GetDIEToType()[die.GetDIE()]; 1095 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) { 1096 return type_ptr->shared_from_this(); 1097 } 1098 } 1099 } 1100 1101 if (attrs.specification.IsValid()) { 1102 // We have a specification which we are going to base our 1103 // function prototype off of, so we need this type to be 1104 // completed so that the m_die_to_decl_ctx for the method in 1105 // the specification has a valid clang decl context. 1106 class_type->GetForwardCompilerType(); 1107 // If we have a specification, then the function type should 1108 // have been made with the specification and not with this 1109 // die. 1110 DWARFDIE spec_die = attrs.specification.Reference(); 1111 clang::DeclContext *spec_clang_decl_ctx = 1112 GetClangDeclContextForDIE(spec_die); 1113 if (spec_clang_decl_ctx) { 1114 LinkDeclContextToDIE(spec_clang_decl_ctx, die); 1115 } else { 1116 dwarf->GetObjectFile()->GetModule()->ReportWarning( 1117 "{0:x8}: DW_AT_specification({1:x16}" 1118 ") has no decl\n", 1119 die.GetID(), spec_die.GetOffset()); 1120 } 1121 type_handled = true; 1122 } else if (attrs.abstract_origin.IsValid()) { 1123 // We have a specification which we are going to base our 1124 // function prototype off of, so we need this type to be 1125 // completed so that the m_die_to_decl_ctx for the method in 1126 // the abstract origin has a valid clang decl context. 1127 class_type->GetForwardCompilerType(); 1128 1129 DWARFDIE abs_die = attrs.abstract_origin.Reference(); 1130 clang::DeclContext *abs_clang_decl_ctx = 1131 GetClangDeclContextForDIE(abs_die); 1132 if (abs_clang_decl_ctx) { 1133 LinkDeclContextToDIE(abs_clang_decl_ctx, die); 1134 } else { 1135 dwarf->GetObjectFile()->GetModule()->ReportWarning( 1136 "{0:x8}: DW_AT_abstract_origin({1:x16}" 1137 ") has no decl\n", 1138 die.GetID(), abs_die.GetOffset()); 1139 } 1140 type_handled = true; 1141 } else { 1142 CompilerType class_opaque_type = 1143 class_type->GetForwardCompilerType(); 1144 if (TypeSystemClang::IsCXXClassType(class_opaque_type)) { 1145 if (class_opaque_type.IsBeingDefined()) { 1146 if (!is_static && !die.HasChildren()) { 1147 // We have a C++ member function with no children (this 1148 // pointer!) and clang will get mad if we try and make 1149 // a function that isn't well formed in the DWARF, so 1150 // we will just skip it... 1151 type_handled = true; 1152 } else { 1153 llvm::PrettyStackTraceFormat stack_trace( 1154 "SymbolFileDWARF::ParseType() is adding a method " 1155 "%s to class %s in DIE 0x%8.8" PRIx64 " from %s", 1156 attrs.name.GetCString(), 1157 class_type->GetName().GetCString(), die.GetID(), 1158 dwarf->GetObjectFile()->GetFileSpec().GetPath().c_str()); 1159 1160 const bool is_attr_used = false; 1161 // Neither GCC 4.2 nor clang++ currently set a valid 1162 // accessibility in the DWARF for C++ methods... 1163 // Default to public for now... 1164 const auto accessibility = attrs.accessibility == eAccessNone 1165 ? eAccessPublic 1166 : attrs.accessibility; 1167 1168 clang::CXXMethodDecl *cxx_method_decl = 1169 m_ast.AddMethodToCXXRecordType( 1170 class_opaque_type.GetOpaqueQualType(), 1171 attrs.name.GetCString(), attrs.mangled_name, 1172 clang_type, accessibility, attrs.is_virtual, 1173 is_static, attrs.is_inline, attrs.is_explicit, 1174 is_attr_used, attrs.is_artificial); 1175 1176 type_handled = cxx_method_decl != nullptr; 1177 // Artificial methods are always handled even when we 1178 // don't create a new declaration for them. 1179 type_handled |= attrs.is_artificial; 1180 1181 if (cxx_method_decl) { 1182 LinkDeclContextToDIE(cxx_method_decl, die); 1183 1184 ClangASTMetadata metadata; 1185 metadata.SetUserID(die.GetID()); 1186 1187 if (!object_pointer_name.empty()) { 1188 metadata.SetObjectPtrName(object_pointer_name.c_str()); 1189 LLDB_LOGF(log, 1190 "Setting object pointer name: %s on method " 1191 "object %p.\n", 1192 object_pointer_name.c_str(), 1193 static_cast<void *>(cxx_method_decl)); 1194 } 1195 m_ast.SetMetadata(cxx_method_decl, metadata); 1196 } else { 1197 ignore_containing_context = true; 1198 } 1199 } 1200 } else { 1201 // We were asked to parse the type for a method in a 1202 // class, yet the class hasn't been asked to complete 1203 // itself through the clang::ExternalASTSource protocol, 1204 // so we need to just have the class complete itself and 1205 // do things the right way, then our 1206 // DIE should then have an entry in the 1207 // dwarf->GetDIEToType() map. First 1208 // we need to modify the dwarf->GetDIEToType() so it 1209 // doesn't think we are trying to parse this DIE 1210 // anymore... 1211 dwarf->GetDIEToType()[die.GetDIE()] = NULL; 1212 1213 // Now we get the full type to force our class type to 1214 // complete itself using the clang::ExternalASTSource 1215 // protocol which will parse all base classes and all 1216 // methods (including the method for this DIE). 1217 class_type->GetFullCompilerType(); 1218 1219 // The type for this DIE should have been filled in the 1220 // function call above. 1221 Type *type_ptr = dwarf->GetDIEToType()[die.GetDIE()]; 1222 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) { 1223 return type_ptr->shared_from_this(); 1224 } 1225 1226 // The previous comment isn't actually true if the class wasn't 1227 // resolved using the current method's parent DIE as source 1228 // data. We need to ensure that we look up the method correctly 1229 // in the class and then link the method's DIE to the unique 1230 // CXXMethodDecl appropriately. 1231 type_handled = true; 1232 } 1233 } 1234 } 1235 } 1236 } 1237 } 1238 1239 if (!type_handled) { 1240 clang::FunctionDecl *function_decl = nullptr; 1241 clang::FunctionDecl *template_function_decl = nullptr; 1242 1243 if (attrs.abstract_origin.IsValid()) { 1244 DWARFDIE abs_die = attrs.abstract_origin.Reference(); 1245 1246 if (dwarf->ResolveType(abs_die)) { 1247 function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>( 1248 GetCachedClangDeclContextForDIE(abs_die)); 1249 1250 if (function_decl) { 1251 LinkDeclContextToDIE(function_decl, die); 1252 } 1253 } 1254 } 1255 1256 if (!function_decl) { 1257 char *name_buf = nullptr; 1258 llvm::StringRef name = attrs.name.GetStringRef(); 1259 1260 // We currently generate function templates with template parameters in 1261 // their name. In order to get closer to the AST that clang generates 1262 // we want to strip these from the name when creating the AST. 1263 if (attrs.mangled_name) { 1264 llvm::ItaniumPartialDemangler D; 1265 if (!D.partialDemangle(attrs.mangled_name)) { 1266 name_buf = D.getFunctionBaseName(nullptr, nullptr); 1267 name = name_buf; 1268 } 1269 } 1270 1271 // We just have a function that isn't part of a class 1272 function_decl = m_ast.CreateFunctionDeclaration( 1273 ignore_containing_context ? m_ast.GetTranslationUnitDecl() 1274 : containing_decl_ctx, 1275 GetOwningClangModule(die), name, clang_type, attrs.storage, 1276 attrs.is_inline); 1277 std::free(name_buf); 1278 1279 if (has_template_params) { 1280 TypeSystemClang::TemplateParameterInfos template_param_infos; 1281 ParseTemplateParameterInfos(die, template_param_infos); 1282 template_function_decl = m_ast.CreateFunctionDeclaration( 1283 ignore_containing_context ? m_ast.GetTranslationUnitDecl() 1284 : containing_decl_ctx, 1285 GetOwningClangModule(die), attrs.name.GetStringRef(), clang_type, 1286 attrs.storage, attrs.is_inline); 1287 clang::FunctionTemplateDecl *func_template_decl = 1288 m_ast.CreateFunctionTemplateDecl( 1289 containing_decl_ctx, GetOwningClangModule(die), 1290 template_function_decl, template_param_infos); 1291 m_ast.CreateFunctionTemplateSpecializationInfo( 1292 template_function_decl, func_template_decl, template_param_infos); 1293 } 1294 1295 lldbassert(function_decl); 1296 1297 if (function_decl) { 1298 // Attach an asm(<mangled_name>) label to the FunctionDecl. 1299 // This ensures that clang::CodeGen emits function calls 1300 // using symbols that are mangled according to the DW_AT_linkage_name. 1301 // If we didn't do this, the external symbols wouldn't exactly 1302 // match the mangled name LLDB knows about and the IRExecutionUnit 1303 // would have to fall back to searching object files for 1304 // approximately matching function names. The motivating 1305 // example is generating calls to ABI-tagged template functions. 1306 // This is done separately for member functions in 1307 // AddMethodToCXXRecordType. 1308 if (attrs.mangled_name) 1309 function_decl->addAttr(clang::AsmLabelAttr::CreateImplicit( 1310 m_ast.getASTContext(), attrs.mangled_name, /*literal=*/false)); 1311 1312 LinkDeclContextToDIE(function_decl, die); 1313 1314 if (!function_param_decls.empty()) { 1315 m_ast.SetFunctionParameters(function_decl, function_param_decls); 1316 if (template_function_decl) 1317 m_ast.SetFunctionParameters(template_function_decl, 1318 function_param_decls); 1319 } 1320 1321 ClangASTMetadata metadata; 1322 metadata.SetUserID(die.GetID()); 1323 1324 if (!object_pointer_name.empty()) { 1325 metadata.SetObjectPtrName(object_pointer_name.c_str()); 1326 LLDB_LOGF(log, 1327 "Setting object pointer name: %s on function " 1328 "object %p.", 1329 object_pointer_name.c_str(), 1330 static_cast<void *>(function_decl)); 1331 } 1332 m_ast.SetMetadata(function_decl, metadata); 1333 } 1334 } 1335 } 1336 } 1337 return dwarf->MakeType( 1338 die.GetID(), attrs.name, std::nullopt, nullptr, LLDB_INVALID_UID, 1339 Type::eEncodingIsUID, &attrs.decl, clang_type, Type::ResolveState::Full); 1340} 1341 1342TypeSP 1343DWARFASTParserClang::ParseArrayType(const DWARFDIE &die, 1344 const ParsedDWARFTypeAttributes &attrs) { 1345 SymbolFileDWARF *dwarf = die.GetDWARF(); 1346 1347 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), 1348 DW_TAG_value_to_name(tag), type_name_cstr); 1349 1350 DWARFDIE type_die = attrs.type.Reference(); 1351 Type *element_type = dwarf->ResolveTypeUID(type_die, true); 1352 1353 if (!element_type) 1354 return nullptr; 1355 1356 std::optional<SymbolFile::ArrayInfo> array_info = ParseChildArrayInfo(die); 1357 uint32_t byte_stride = attrs.byte_stride; 1358 uint32_t bit_stride = attrs.bit_stride; 1359 if (array_info) { 1360 byte_stride = array_info->byte_stride; 1361 bit_stride = array_info->bit_stride; 1362 } 1363 if (byte_stride == 0 && bit_stride == 0) 1364 byte_stride = element_type->GetByteSize(nullptr).value_or(0); 1365 CompilerType array_element_type = element_type->GetForwardCompilerType(); 1366 TypeSystemClang::RequireCompleteType(array_element_type); 1367 1368 uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride; 1369 CompilerType clang_type; 1370 if (array_info && array_info->element_orders.size() > 0) { 1371 uint64_t num_elements = 0; 1372 auto end = array_info->element_orders.rend(); 1373 for (auto pos = array_info->element_orders.rbegin(); pos != end; ++pos) { 1374 num_elements = *pos; 1375 clang_type = m_ast.CreateArrayType(array_element_type, num_elements, 1376 attrs.is_vector); 1377 array_element_type = clang_type; 1378 array_element_bit_stride = num_elements 1379 ? array_element_bit_stride * num_elements 1380 : array_element_bit_stride; 1381 } 1382 } else { 1383 clang_type = 1384 m_ast.CreateArrayType(array_element_type, 0, attrs.is_vector); 1385 } 1386 ConstString empty_name; 1387 TypeSP type_sp = 1388 dwarf->MakeType(die.GetID(), empty_name, array_element_bit_stride / 8, 1389 nullptr, type_die.GetID(), Type::eEncodingIsUID, 1390 &attrs.decl, clang_type, Type::ResolveState::Full); 1391 type_sp->SetEncodingType(element_type); 1392 const clang::Type *type = ClangUtil::GetQualType(clang_type).getTypePtr(); 1393 m_ast.SetMetadataAsUserID(type, die.GetID()); 1394 return type_sp; 1395} 1396 1397TypeSP DWARFASTParserClang::ParsePointerToMemberType( 1398 const DWARFDIE &die, const ParsedDWARFTypeAttributes &attrs) { 1399 SymbolFileDWARF *dwarf = die.GetDWARF(); 1400 Type *pointee_type = dwarf->ResolveTypeUID(attrs.type.Reference(), true); 1401 Type *class_type = 1402 dwarf->ResolveTypeUID(attrs.containing_type.Reference(), true); 1403 1404 // Check to make sure pointers are not NULL before attempting to 1405 // dereference them. 1406 if ((class_type == nullptr) || (pointee_type == nullptr)) 1407 return nullptr; 1408 1409 CompilerType pointee_clang_type = pointee_type->GetForwardCompilerType(); 1410 CompilerType class_clang_type = class_type->GetForwardCompilerType(); 1411 1412 CompilerType clang_type = TypeSystemClang::CreateMemberPointerType( 1413 class_clang_type, pointee_clang_type); 1414 1415 if (std::optional<uint64_t> clang_type_size = 1416 clang_type.GetByteSize(nullptr)) { 1417 return dwarf->MakeType(die.GetID(), attrs.name, *clang_type_size, nullptr, 1418 LLDB_INVALID_UID, Type::eEncodingIsUID, nullptr, 1419 clang_type, Type::ResolveState::Forward); 1420 } 1421 return nullptr; 1422} 1423 1424void DWARFASTParserClang::ParseInheritance( 1425 const DWARFDIE &die, const DWARFDIE &parent_die, 1426 const CompilerType class_clang_type, const AccessType default_accessibility, 1427 const lldb::ModuleSP &module_sp, 1428 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes, 1429 ClangASTImporter::LayoutInfo &layout_info) { 1430 auto ast = 1431 class_clang_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>(); 1432 if (ast == nullptr) 1433 return; 1434 1435 // TODO: implement DW_TAG_inheritance type parsing. 1436 DWARFAttributes attributes = die.GetAttributes(); 1437 if (attributes.Size() == 0) 1438 return; 1439 1440 DWARFFormValue encoding_form; 1441 AccessType accessibility = default_accessibility; 1442 bool is_virtual = false; 1443 bool is_base_of_class = true; 1444 off_t member_byte_offset = 0; 1445 1446 for (uint32_t i = 0; i < attributes.Size(); ++i) { 1447 const dw_attr_t attr = attributes.AttributeAtIndex(i); 1448 DWARFFormValue form_value; 1449 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 1450 switch (attr) { 1451 case DW_AT_type: 1452 encoding_form = form_value; 1453 break; 1454 case DW_AT_data_member_location: 1455 if (auto maybe_offset = 1456 ExtractDataMemberLocation(die, form_value, module_sp)) 1457 member_byte_offset = *maybe_offset; 1458 break; 1459 1460 case DW_AT_accessibility: 1461 accessibility = 1462 DWARFASTParser::GetAccessTypeFromDWARF(form_value.Unsigned()); 1463 break; 1464 1465 case DW_AT_virtuality: 1466 is_virtual = form_value.Boolean(); 1467 break; 1468 1469 default: 1470 break; 1471 } 1472 } 1473 } 1474 1475 Type *base_class_type = die.ResolveTypeUID(encoding_form.Reference()); 1476 if (base_class_type == nullptr) { 1477 module_sp->ReportError("{0:x16}: DW_TAG_inheritance failed to " 1478 "resolve the base class at {1:x16}" 1479 " from enclosing type {2:x16}. \nPlease file " 1480 "a bug and attach the file at the start of " 1481 "this error message", 1482 die.GetOffset(), 1483 encoding_form.Reference().GetOffset(), 1484 parent_die.GetOffset()); 1485 return; 1486 } 1487 1488 CompilerType base_class_clang_type = base_class_type->GetFullCompilerType(); 1489 assert(base_class_clang_type); 1490 if (TypeSystemClang::IsObjCObjectOrInterfaceType(class_clang_type)) { 1491 ast->SetObjCSuperClass(class_clang_type, base_class_clang_type); 1492 return; 1493 } 1494 std::unique_ptr<clang::CXXBaseSpecifier> result = 1495 ast->CreateBaseClassSpecifier(base_class_clang_type.GetOpaqueQualType(), 1496 accessibility, is_virtual, 1497 is_base_of_class); 1498 if (!result) 1499 return; 1500 1501 base_classes.push_back(std::move(result)); 1502 1503 if (is_virtual) { 1504 // Do not specify any offset for virtual inheritance. The DWARF 1505 // produced by clang doesn't give us a constant offset, but gives 1506 // us a DWARF expressions that requires an actual object in memory. 1507 // the DW_AT_data_member_location for a virtual base class looks 1508 // like: 1509 // DW_AT_data_member_location( DW_OP_dup, DW_OP_deref, 1510 // DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref, 1511 // DW_OP_plus ) 1512 // Given this, there is really no valid response we can give to 1513 // clang for virtual base class offsets, and this should eventually 1514 // be removed from LayoutRecordType() in the external 1515 // AST source in clang. 1516 } else { 1517 layout_info.base_offsets.insert(std::make_pair( 1518 ast->GetAsCXXRecordDecl(base_class_clang_type.GetOpaqueQualType()), 1519 clang::CharUnits::fromQuantity(member_byte_offset))); 1520 } 1521} 1522 1523TypeSP DWARFASTParserClang::UpdateSymbolContextScopeForType( 1524 const SymbolContext &sc, const DWARFDIE &die, TypeSP type_sp) { 1525 if (!type_sp) 1526 return type_sp; 1527 1528 SymbolFileDWARF *dwarf = die.GetDWARF(); 1529 DWARFDIE sc_parent_die = SymbolFileDWARF::GetParentSymbolContextDIE(die); 1530 dw_tag_t sc_parent_tag = sc_parent_die.Tag(); 1531 1532 SymbolContextScope *symbol_context_scope = nullptr; 1533 if (sc_parent_tag == DW_TAG_compile_unit || 1534 sc_parent_tag == DW_TAG_partial_unit) { 1535 symbol_context_scope = sc.comp_unit; 1536 } else if (sc.function != nullptr && sc_parent_die) { 1537 symbol_context_scope = 1538 sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID()); 1539 if (symbol_context_scope == nullptr) 1540 symbol_context_scope = sc.function; 1541 } else { 1542 symbol_context_scope = sc.module_sp.get(); 1543 } 1544 1545 if (symbol_context_scope != nullptr) 1546 type_sp->SetSymbolContextScope(symbol_context_scope); 1547 1548 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); 1549 return type_sp; 1550} 1551 1552std::string 1553DWARFASTParserClang::GetCPlusPlusQualifiedName(const DWARFDIE &die) { 1554 if (!die.IsValid()) 1555 return ""; 1556 const char *name = die.GetName(); 1557 if (!name) 1558 return ""; 1559 std::string qualified_name; 1560 DWARFDIE parent_decl_ctx_die = die.GetParentDeclContextDIE(); 1561 // TODO: change this to get the correct decl context parent.... 1562 while (parent_decl_ctx_die) { 1563 // The name may not contain template parameters due to 1564 // -gsimple-template-names; we must reconstruct the full name from child 1565 // template parameter dies via GetDIEClassTemplateParams(). 1566 const dw_tag_t parent_tag = parent_decl_ctx_die.Tag(); 1567 switch (parent_tag) { 1568 case DW_TAG_namespace: { 1569 if (const char *namespace_name = parent_decl_ctx_die.GetName()) { 1570 qualified_name.insert(0, "::"); 1571 qualified_name.insert(0, namespace_name); 1572 } else { 1573 qualified_name.insert(0, "(anonymous namespace)::"); 1574 } 1575 parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE(); 1576 break; 1577 } 1578 1579 case DW_TAG_class_type: 1580 case DW_TAG_structure_type: 1581 case DW_TAG_union_type: { 1582 if (const char *class_union_struct_name = parent_decl_ctx_die.GetName()) { 1583 qualified_name.insert( 1584 0, GetDIEClassTemplateParams(parent_decl_ctx_die).AsCString("")); 1585 qualified_name.insert(0, "::"); 1586 qualified_name.insert(0, class_union_struct_name); 1587 } 1588 parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE(); 1589 break; 1590 } 1591 1592 default: 1593 parent_decl_ctx_die.Clear(); 1594 break; 1595 } 1596 } 1597 1598 if (qualified_name.empty()) 1599 qualified_name.append("::"); 1600 1601 qualified_name.append(name); 1602 qualified_name.append(GetDIEClassTemplateParams(die).AsCString("")); 1603 1604 return qualified_name; 1605} 1606 1607TypeSP 1608DWARFASTParserClang::ParseStructureLikeDIE(const SymbolContext &sc, 1609 const DWARFDIE &die, 1610 ParsedDWARFTypeAttributes &attrs) { 1611 TypeSP type_sp; 1612 CompilerType clang_type; 1613 const dw_tag_t tag = die.Tag(); 1614 SymbolFileDWARF *dwarf = die.GetDWARF(); 1615 LanguageType cu_language = SymbolFileDWARF::GetLanguage(*die.GetCU()); 1616 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups); 1617 1618 // UniqueDWARFASTType is large, so don't create a local variables on the 1619 // stack, put it on the heap. This function is often called recursively and 1620 // clang isn't good at sharing the stack space for variables in different 1621 // blocks. 1622 auto unique_ast_entry_up = std::make_unique<UniqueDWARFASTType>(); 1623 1624 ConstString unique_typename(attrs.name); 1625 Declaration unique_decl(attrs.decl); 1626 1627 if (attrs.name) { 1628 if (Language::LanguageIsCPlusPlus(cu_language)) { 1629 // For C++, we rely solely upon the one definition rule that says 1630 // only one thing can exist at a given decl context. We ignore the 1631 // file and line that things are declared on. 1632 std::string qualified_name = GetCPlusPlusQualifiedName(die); 1633 if (!qualified_name.empty()) 1634 unique_typename = ConstString(qualified_name); 1635 unique_decl.Clear(); 1636 } 1637 1638 if (dwarf->GetUniqueDWARFASTTypeMap().Find( 1639 unique_typename, die, unique_decl, attrs.byte_size.value_or(-1), 1640 *unique_ast_entry_up)) { 1641 type_sp = unique_ast_entry_up->m_type_sp; 1642 if (type_sp) { 1643 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); 1644 LinkDeclContextToDIE( 1645 GetCachedClangDeclContextForDIE(unique_ast_entry_up->m_die), die); 1646 return type_sp; 1647 } 1648 } 1649 } 1650 1651 DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(), 1652 DW_TAG_value_to_name(tag), type_name_cstr); 1653 1654 int tag_decl_kind = -1; 1655 AccessType default_accessibility = eAccessNone; 1656 if (tag == DW_TAG_structure_type) { 1657 tag_decl_kind = llvm::to_underlying(clang::TagTypeKind::Struct); 1658 default_accessibility = eAccessPublic; 1659 } else if (tag == DW_TAG_union_type) { 1660 tag_decl_kind = llvm::to_underlying(clang::TagTypeKind::Union); 1661 default_accessibility = eAccessPublic; 1662 } else if (tag == DW_TAG_class_type) { 1663 tag_decl_kind = llvm::to_underlying(clang::TagTypeKind::Class); 1664 default_accessibility = eAccessPrivate; 1665 } 1666 1667 if (attrs.byte_size && *attrs.byte_size == 0 && attrs.name && 1668 !die.HasChildren() && cu_language == eLanguageTypeObjC) { 1669 // Work around an issue with clang at the moment where forward 1670 // declarations for objective C classes are emitted as: 1671 // DW_TAG_structure_type [2] 1672 // DW_AT_name( "ForwardObjcClass" ) 1673 // DW_AT_byte_size( 0x00 ) 1674 // DW_AT_decl_file( "..." ) 1675 // DW_AT_decl_line( 1 ) 1676 // 1677 // Note that there is no DW_AT_declaration and there are no children, 1678 // and the byte size is zero. 1679 attrs.is_forward_declaration = true; 1680 } 1681 1682 if (attrs.class_language == eLanguageTypeObjC || 1683 attrs.class_language == eLanguageTypeObjC_plus_plus) { 1684 if (!attrs.is_complete_objc_class && 1685 die.Supports_DW_AT_APPLE_objc_complete_type()) { 1686 // We have a valid eSymbolTypeObjCClass class symbol whose name 1687 // matches the current objective C class that we are trying to find 1688 // and this DIE isn't the complete definition (we checked 1689 // is_complete_objc_class above and know it is false), so the real 1690 // definition is in here somewhere 1691 type_sp = 1692 dwarf->FindCompleteObjCDefinitionTypeForDIE(die, attrs.name, true); 1693 1694 if (!type_sp) { 1695 SymbolFileDWARFDebugMap *debug_map_symfile = 1696 dwarf->GetDebugMapSymfile(); 1697 if (debug_map_symfile) { 1698 // We weren't able to find a full declaration in this DWARF, 1699 // see if we have a declaration anywhere else... 1700 type_sp = debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE( 1701 die, attrs.name, true); 1702 } 1703 } 1704 1705 if (type_sp) { 1706 if (log) { 1707 dwarf->GetObjectFile()->GetModule()->LogMessage( 1708 log, 1709 "SymbolFileDWARF({0:p}) - {1:x16}: {2} type " 1710 "\"{3}\" is an " 1711 "incomplete objc type, complete type is {4:x8}", 1712 static_cast<void *>(this), die.GetOffset(), 1713 DW_TAG_value_to_name(tag), attrs.name.GetCString(), 1714 type_sp->GetID()); 1715 } 1716 1717 // We found a real definition for this type elsewhere so lets use 1718 // it and cache the fact that we found a complete type for this 1719 // die 1720 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); 1721 return type_sp; 1722 } 1723 } 1724 } 1725 1726 if (attrs.is_forward_declaration) { 1727 // We have a forward declaration to a type and we need to try and 1728 // find a full declaration. We look in the current type index just in 1729 // case we have a forward declaration followed by an actual 1730 // declarations in the DWARF. If this fails, we need to look 1731 // elsewhere... 1732 if (log) { 1733 dwarf->GetObjectFile()->GetModule()->LogMessage( 1734 log, 1735 "SymbolFileDWARF({0:p}) - {1:x16}: {2} type \"{3}\" is a " 1736 "forward declaration, trying to find complete type", 1737 static_cast<void *>(this), die.GetOffset(), DW_TAG_value_to_name(tag), 1738 attrs.name.GetCString()); 1739 } 1740 1741 // See if the type comes from a Clang module and if so, track down 1742 // that type. 1743 type_sp = ParseTypeFromClangModule(sc, die, log); 1744 if (type_sp) 1745 return type_sp; 1746 1747 // type_sp = FindDefinitionTypeForDIE (dwarf_cu, die, 1748 // type_name_const_str); 1749 type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die); 1750 1751 if (!type_sp) { 1752 SymbolFileDWARFDebugMap *debug_map_symfile = dwarf->GetDebugMapSymfile(); 1753 if (debug_map_symfile) { 1754 // We weren't able to find a full declaration in this DWARF, see 1755 // if we have a declaration anywhere else... 1756 type_sp = debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(die); 1757 } 1758 } 1759 1760 if (type_sp) { 1761 if (log) { 1762 dwarf->GetObjectFile()->GetModule()->LogMessage( 1763 log, 1764 "SymbolFileDWARF({0:p}) - {1:x16}: {2} type \"{3}\" is a " 1765 "forward declaration, complete type is {4:x8}", 1766 static_cast<void *>(this), die.GetOffset(), 1767 DW_TAG_value_to_name(tag), attrs.name.GetCString(), 1768 type_sp->GetID()); 1769 } 1770 1771 // We found a real definition for this type elsewhere so lets use 1772 // it and cache the fact that we found a complete type for this die 1773 dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get(); 1774 clang::DeclContext *defn_decl_ctx = 1775 GetCachedClangDeclContextForDIE(dwarf->GetDIE(type_sp->GetID())); 1776 if (defn_decl_ctx) 1777 LinkDeclContextToDIE(defn_decl_ctx, die); 1778 return type_sp; 1779 } 1780 } 1781 assert(tag_decl_kind != -1); 1782 UNUSED_IF_ASSERT_DISABLED(tag_decl_kind); 1783 bool clang_type_was_created = false; 1784 clang_type = CompilerType( 1785 m_ast.weak_from_this(), 1786 dwarf->GetForwardDeclDIEToCompilerType().lookup(die.GetDIE())); 1787 if (!clang_type) { 1788 clang::DeclContext *decl_ctx = 1789 GetClangDeclContextContainingDIE(die, nullptr); 1790 1791 PrepareContextToReceiveMembers(m_ast, GetClangASTImporter(), decl_ctx, die, 1792 attrs.name.GetCString()); 1793 1794 if (attrs.accessibility == eAccessNone && decl_ctx) { 1795 // Check the decl context that contains this class/struct/union. If 1796 // it is a class we must give it an accessibility. 1797 const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind(); 1798 if (DeclKindIsCXXClass(containing_decl_kind)) 1799 attrs.accessibility = default_accessibility; 1800 } 1801 1802 ClangASTMetadata metadata; 1803 metadata.SetUserID(die.GetID()); 1804 metadata.SetIsDynamicCXXType(dwarf->ClassOrStructIsVirtual(die)); 1805 1806 TypeSystemClang::TemplateParameterInfos template_param_infos; 1807 if (ParseTemplateParameterInfos(die, template_param_infos)) { 1808 clang::ClassTemplateDecl *class_template_decl = 1809 m_ast.ParseClassTemplateDecl( 1810 decl_ctx, GetOwningClangModule(die), attrs.accessibility, 1811 attrs.name.GetCString(), tag_decl_kind, template_param_infos); 1812 if (!class_template_decl) { 1813 if (log) { 1814 dwarf->GetObjectFile()->GetModule()->LogMessage( 1815 log, 1816 "SymbolFileDWARF({0:p}) - {1:x16}: {2} type \"{3}\" " 1817 "clang::ClassTemplateDecl failed to return a decl.", 1818 static_cast<void *>(this), die.GetOffset(), 1819 DW_TAG_value_to_name(tag), attrs.name.GetCString()); 1820 } 1821 return TypeSP(); 1822 } 1823 1824 clang::ClassTemplateSpecializationDecl *class_specialization_decl = 1825 m_ast.CreateClassTemplateSpecializationDecl( 1826 decl_ctx, GetOwningClangModule(die), class_template_decl, 1827 tag_decl_kind, template_param_infos); 1828 clang_type = m_ast.CreateClassTemplateSpecializationType( 1829 class_specialization_decl); 1830 clang_type_was_created = true; 1831 1832 m_ast.SetMetadata(class_template_decl, metadata); 1833 m_ast.SetMetadata(class_specialization_decl, metadata); 1834 } 1835 1836 if (!clang_type_was_created) { 1837 clang_type_was_created = true; 1838 clang_type = m_ast.CreateRecordType( 1839 decl_ctx, GetOwningClangModule(die), attrs.accessibility, 1840 attrs.name.GetCString(), tag_decl_kind, attrs.class_language, 1841 &metadata, attrs.exports_symbols); 1842 } 1843 } 1844 1845 // Store a forward declaration to this class type in case any 1846 // parameters in any class methods need it for the clang types for 1847 // function prototypes. 1848 LinkDeclContextToDIE(m_ast.GetDeclContextForType(clang_type), die); 1849 type_sp = dwarf->MakeType( 1850 die.GetID(), attrs.name, attrs.byte_size, nullptr, LLDB_INVALID_UID, 1851 Type::eEncodingIsUID, &attrs.decl, clang_type, 1852 Type::ResolveState::Forward, 1853 TypePayloadClang(OptionalClangModuleID(), attrs.is_complete_objc_class)); 1854 1855 // Add our type to the unique type map so we don't end up creating many 1856 // copies of the same type over and over in the ASTContext for our 1857 // module 1858 unique_ast_entry_up->m_type_sp = type_sp; 1859 unique_ast_entry_up->m_die = die; 1860 unique_ast_entry_up->m_declaration = unique_decl; 1861 unique_ast_entry_up->m_byte_size = attrs.byte_size.value_or(0); 1862 dwarf->GetUniqueDWARFASTTypeMap().Insert(unique_typename, 1863 *unique_ast_entry_up); 1864 1865 if (!attrs.is_forward_declaration) { 1866 // Always start the definition for a class type so that if the class 1867 // has child classes or types that require the class to be created 1868 // for use as their decl contexts the class will be ready to accept 1869 // these child definitions. 1870 if (!die.HasChildren()) { 1871 // No children for this struct/union/class, lets finish it 1872 if (TypeSystemClang::StartTagDeclarationDefinition(clang_type)) { 1873 TypeSystemClang::CompleteTagDeclarationDefinition(clang_type); 1874 } else { 1875 dwarf->GetObjectFile()->GetModule()->ReportError( 1876 1877 "DWARF DIE at {0:x16} named \"{1}\" was not able to start " 1878 "its " 1879 "definition.\nPlease file a bug and attach the file at the " 1880 "start of this error message", 1881 die.GetOffset(), attrs.name.GetCString()); 1882 } 1883 1884 // Setting authority byte size and alignment for empty structures. 1885 // 1886 // If the byte size or alignmenet of the record is specified then 1887 // overwrite the ones that would be computed by Clang. 1888 // This is only needed as LLDB's TypeSystemClang is always in C++ mode, 1889 // but some compilers such as GCC and Clang give empty structs a size of 0 1890 // in C mode (in contrast to the size of 1 for empty structs that would be 1891 // computed in C++ mode). 1892 if (attrs.byte_size || attrs.alignment) { 1893 clang::RecordDecl *record_decl = 1894 TypeSystemClang::GetAsRecordDecl(clang_type); 1895 if (record_decl) { 1896 ClangASTImporter::LayoutInfo layout; 1897 layout.bit_size = attrs.byte_size.value_or(0) * 8; 1898 layout.alignment = attrs.alignment.value_or(0) * 8; 1899 GetClangASTImporter().SetRecordLayout(record_decl, layout); 1900 } 1901 } 1902 } else if (clang_type_was_created) { 1903 // Start the definition if the class is not objective C since the 1904 // underlying decls respond to isCompleteDefinition(). Objective 1905 // C decls don't respond to isCompleteDefinition() so we can't 1906 // start the declaration definition right away. For C++ 1907 // class/union/structs we want to start the definition in case the 1908 // class is needed as the declaration context for a contained class 1909 // or type without the need to complete that type.. 1910 1911 if (attrs.class_language != eLanguageTypeObjC && 1912 attrs.class_language != eLanguageTypeObjC_plus_plus) 1913 TypeSystemClang::StartTagDeclarationDefinition(clang_type); 1914 1915 // Leave this as a forward declaration until we need to know the 1916 // details of the type. lldb_private::Type will automatically call 1917 // the SymbolFile virtual function 1918 // "SymbolFileDWARF::CompleteType(Type *)" When the definition 1919 // needs to be defined. 1920 assert(!dwarf->GetForwardDeclCompilerTypeToDIE().count( 1921 ClangUtil::RemoveFastQualifiers(clang_type) 1922 .GetOpaqueQualType()) && 1923 "Type already in the forward declaration map!"); 1924 // Can't assume m_ast.GetSymbolFile() is actually a 1925 // SymbolFileDWARF, it can be a SymbolFileDWARFDebugMap for Apple 1926 // binaries. 1927 dwarf->GetForwardDeclDIEToCompilerType()[die.GetDIE()] = 1928 clang_type.GetOpaqueQualType(); 1929 dwarf->GetForwardDeclCompilerTypeToDIE().try_emplace( 1930 ClangUtil::RemoveFastQualifiers(clang_type).GetOpaqueQualType(), 1931 *die.GetDIERef()); 1932 m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true); 1933 } 1934 } 1935 1936 // If we made a clang type, set the trivial abi if applicable: We only 1937 // do this for pass by value - which implies the Trivial ABI. There 1938 // isn't a way to assert that something that would normally be pass by 1939 // value is pass by reference, so we ignore that attribute if set. 1940 if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_value) { 1941 clang::CXXRecordDecl *record_decl = 1942 m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType()); 1943 if (record_decl && record_decl->getDefinition()) { 1944 record_decl->setHasTrivialSpecialMemberForCall(); 1945 } 1946 } 1947 1948 if (attrs.calling_convention == llvm::dwarf::DW_CC_pass_by_reference) { 1949 clang::CXXRecordDecl *record_decl = 1950 m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType()); 1951 if (record_decl) 1952 record_decl->setArgPassingRestrictions( 1953 clang::RecordArgPassingKind::CannotPassInRegs); 1954 } 1955 return type_sp; 1956} 1957 1958// DWARF parsing functions 1959 1960class DWARFASTParserClang::DelayedAddObjCClassProperty { 1961public: 1962 DelayedAddObjCClassProperty( 1963 const CompilerType &class_opaque_type, const char *property_name, 1964 const CompilerType &property_opaque_type, // The property type is only 1965 // required if you don't have an 1966 // ivar decl 1967 const char *property_setter_name, const char *property_getter_name, 1968 uint32_t property_attributes, const ClangASTMetadata *metadata) 1969 : m_class_opaque_type(class_opaque_type), m_property_name(property_name), 1970 m_property_opaque_type(property_opaque_type), 1971 m_property_setter_name(property_setter_name), 1972 m_property_getter_name(property_getter_name), 1973 m_property_attributes(property_attributes) { 1974 if (metadata != nullptr) { 1975 m_metadata_up = std::make_unique<ClangASTMetadata>(); 1976 *m_metadata_up = *metadata; 1977 } 1978 } 1979 1980 DelayedAddObjCClassProperty(const DelayedAddObjCClassProperty &rhs) { 1981 *this = rhs; 1982 } 1983 1984 DelayedAddObjCClassProperty & 1985 operator=(const DelayedAddObjCClassProperty &rhs) { 1986 m_class_opaque_type = rhs.m_class_opaque_type; 1987 m_property_name = rhs.m_property_name; 1988 m_property_opaque_type = rhs.m_property_opaque_type; 1989 m_property_setter_name = rhs.m_property_setter_name; 1990 m_property_getter_name = rhs.m_property_getter_name; 1991 m_property_attributes = rhs.m_property_attributes; 1992 1993 if (rhs.m_metadata_up) { 1994 m_metadata_up = std::make_unique<ClangASTMetadata>(); 1995 *m_metadata_up = *rhs.m_metadata_up; 1996 } 1997 return *this; 1998 } 1999 2000 bool Finalize() { 2001 return TypeSystemClang::AddObjCClassProperty( 2002 m_class_opaque_type, m_property_name, m_property_opaque_type, 2003 /*ivar_decl=*/nullptr, m_property_setter_name, m_property_getter_name, 2004 m_property_attributes, m_metadata_up.get()); 2005 } 2006 2007private: 2008 CompilerType m_class_opaque_type; 2009 const char *m_property_name; 2010 CompilerType m_property_opaque_type; 2011 const char *m_property_setter_name; 2012 const char *m_property_getter_name; 2013 uint32_t m_property_attributes; 2014 std::unique_ptr<ClangASTMetadata> m_metadata_up; 2015}; 2016 2017bool DWARFASTParserClang::ParseTemplateDIE( 2018 const DWARFDIE &die, 2019 TypeSystemClang::TemplateParameterInfos &template_param_infos) { 2020 const dw_tag_t tag = die.Tag(); 2021 bool is_template_template_argument = false; 2022 2023 switch (tag) { 2024 case DW_TAG_GNU_template_parameter_pack: { 2025 template_param_infos.SetParameterPack( 2026 std::make_unique<TypeSystemClang::TemplateParameterInfos>()); 2027 for (DWARFDIE child_die : die.children()) { 2028 if (!ParseTemplateDIE(child_die, template_param_infos.GetParameterPack())) 2029 return false; 2030 } 2031 if (const char *name = die.GetName()) { 2032 template_param_infos.SetPackName(name); 2033 } 2034 return true; 2035 } 2036 case DW_TAG_GNU_template_template_param: 2037 is_template_template_argument = true; 2038 [[fallthrough]]; 2039 case DW_TAG_template_type_parameter: 2040 case DW_TAG_template_value_parameter: { 2041 DWARFAttributes attributes = die.GetAttributes(); 2042 if (attributes.Size() == 0) 2043 return true; 2044 2045 const char *name = nullptr; 2046 const char *template_name = nullptr; 2047 CompilerType clang_type; 2048 uint64_t uval64 = 0; 2049 bool uval64_valid = false; 2050 bool is_default_template_arg = false; 2051 DWARFFormValue form_value; 2052 for (size_t i = 0; i < attributes.Size(); ++i) { 2053 const dw_attr_t attr = attributes.AttributeAtIndex(i); 2054 2055 switch (attr) { 2056 case DW_AT_name: 2057 if (attributes.ExtractFormValueAtIndex(i, form_value)) 2058 name = form_value.AsCString(); 2059 break; 2060 2061 case DW_AT_GNU_template_name: 2062 if (attributes.ExtractFormValueAtIndex(i, form_value)) 2063 template_name = form_value.AsCString(); 2064 break; 2065 2066 case DW_AT_type: 2067 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 2068 Type *lldb_type = die.ResolveTypeUID(form_value.Reference()); 2069 if (lldb_type) 2070 clang_type = lldb_type->GetForwardCompilerType(); 2071 } 2072 break; 2073 2074 case DW_AT_const_value: 2075 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 2076 uval64_valid = true; 2077 uval64 = form_value.Unsigned(); 2078 } 2079 break; 2080 case DW_AT_default_value: 2081 if (attributes.ExtractFormValueAtIndex(i, form_value)) 2082 is_default_template_arg = form_value.Boolean(); 2083 break; 2084 default: 2085 break; 2086 } 2087 } 2088 2089 clang::ASTContext &ast = m_ast.getASTContext(); 2090 if (!clang_type) 2091 clang_type = m_ast.GetBasicType(eBasicTypeVoid); 2092 2093 if (!is_template_template_argument) { 2094 bool is_signed = false; 2095 // Get the signed value for any integer or enumeration if available 2096 clang_type.IsIntegerOrEnumerationType(is_signed); 2097 2098 if (name && !name[0]) 2099 name = nullptr; 2100 2101 if (tag == DW_TAG_template_value_parameter && uval64_valid) { 2102 std::optional<uint64_t> size = clang_type.GetBitSize(nullptr); 2103 if (!size) 2104 return false; 2105 llvm::APInt apint(*size, uval64, is_signed); 2106 template_param_infos.InsertArg( 2107 name, clang::TemplateArgument(ast, llvm::APSInt(apint, !is_signed), 2108 ClangUtil::GetQualType(clang_type), 2109 is_default_template_arg)); 2110 } else { 2111 template_param_infos.InsertArg( 2112 name, clang::TemplateArgument(ClangUtil::GetQualType(clang_type), 2113 /*isNullPtr*/ false, 2114 is_default_template_arg)); 2115 } 2116 } else { 2117 auto *tplt_type = m_ast.CreateTemplateTemplateParmDecl(template_name); 2118 template_param_infos.InsertArg( 2119 name, clang::TemplateArgument(clang::TemplateName(tplt_type), 2120 is_default_template_arg)); 2121 } 2122 } 2123 return true; 2124 2125 default: 2126 break; 2127 } 2128 return false; 2129} 2130 2131bool DWARFASTParserClang::ParseTemplateParameterInfos( 2132 const DWARFDIE &parent_die, 2133 TypeSystemClang::TemplateParameterInfos &template_param_infos) { 2134 2135 if (!parent_die) 2136 return false; 2137 2138 for (DWARFDIE die : parent_die.children()) { 2139 const dw_tag_t tag = die.Tag(); 2140 2141 switch (tag) { 2142 case DW_TAG_template_type_parameter: 2143 case DW_TAG_template_value_parameter: 2144 case DW_TAG_GNU_template_parameter_pack: 2145 case DW_TAG_GNU_template_template_param: 2146 ParseTemplateDIE(die, template_param_infos); 2147 break; 2148 2149 default: 2150 break; 2151 } 2152 } 2153 2154 return !template_param_infos.IsEmpty() || 2155 template_param_infos.hasParameterPack(); 2156} 2157 2158bool DWARFASTParserClang::CompleteRecordType(const DWARFDIE &die, 2159 lldb_private::Type *type, 2160 CompilerType &clang_type) { 2161 const dw_tag_t tag = die.Tag(); 2162 SymbolFileDWARF *dwarf = die.GetDWARF(); 2163 2164 ClangASTImporter::LayoutInfo layout_info; 2165 std::vector<DWARFDIE> contained_type_dies; 2166 2167 if (die.HasChildren()) { 2168 const bool type_is_objc_object_or_interface = 2169 TypeSystemClang::IsObjCObjectOrInterfaceType(clang_type); 2170 if (type_is_objc_object_or_interface) { 2171 // For objective C we don't start the definition when the class is 2172 // created. 2173 TypeSystemClang::StartTagDeclarationDefinition(clang_type); 2174 } 2175 2176 AccessType default_accessibility = eAccessNone; 2177 if (tag == DW_TAG_structure_type) { 2178 default_accessibility = eAccessPublic; 2179 } else if (tag == DW_TAG_union_type) { 2180 default_accessibility = eAccessPublic; 2181 } else if (tag == DW_TAG_class_type) { 2182 default_accessibility = eAccessPrivate; 2183 } 2184 2185 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases; 2186 // Parse members and base classes first 2187 std::vector<DWARFDIE> member_function_dies; 2188 2189 DelayedPropertyList delayed_properties; 2190 ParseChildMembers(die, clang_type, bases, member_function_dies, 2191 contained_type_dies, delayed_properties, 2192 default_accessibility, layout_info); 2193 2194 // Now parse any methods if there were any... 2195 for (const DWARFDIE &die : member_function_dies) 2196 dwarf->ResolveType(die); 2197 2198 if (type_is_objc_object_or_interface) { 2199 ConstString class_name(clang_type.GetTypeName()); 2200 if (class_name) { 2201 dwarf->GetObjCMethods(class_name, [&](DWARFDIE method_die) { 2202 method_die.ResolveType(); 2203 return true; 2204 }); 2205 2206 for (DelayedAddObjCClassProperty &property : delayed_properties) 2207 property.Finalize(); 2208 } 2209 } 2210 2211 if (!bases.empty()) { 2212 // Make sure all base classes refer to complete types and not forward 2213 // declarations. If we don't do this, clang will crash with an 2214 // assertion in the call to clang_type.TransferBaseClasses() 2215 for (const auto &base_class : bases) { 2216 clang::TypeSourceInfo *type_source_info = 2217 base_class->getTypeSourceInfo(); 2218 if (type_source_info) 2219 TypeSystemClang::RequireCompleteType( 2220 m_ast.GetType(type_source_info->getType())); 2221 } 2222 2223 m_ast.TransferBaseClasses(clang_type.GetOpaqueQualType(), 2224 std::move(bases)); 2225 } 2226 } 2227 2228 m_ast.AddMethodOverridesForCXXRecordType(clang_type.GetOpaqueQualType()); 2229 TypeSystemClang::BuildIndirectFields(clang_type); 2230 TypeSystemClang::CompleteTagDeclarationDefinition(clang_type); 2231 2232 if (!layout_info.field_offsets.empty() || !layout_info.base_offsets.empty() || 2233 !layout_info.vbase_offsets.empty()) { 2234 if (type) 2235 layout_info.bit_size = type->GetByteSize(nullptr).value_or(0) * 8; 2236 if (layout_info.bit_size == 0) 2237 layout_info.bit_size = 2238 die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8; 2239 if (layout_info.alignment == 0) 2240 layout_info.alignment = 2241 die.GetAttributeValueAsUnsigned(llvm::dwarf::DW_AT_alignment, 0) * 8; 2242 2243 clang::CXXRecordDecl *record_decl = 2244 m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType()); 2245 if (record_decl) 2246 GetClangASTImporter().SetRecordLayout(record_decl, layout_info); 2247 } 2248 // Now parse all contained types inside of the class. We make forward 2249 // declarations to all classes, but we need the CXXRecordDecl to have decls 2250 // for all contained types because we don't get asked for them via the 2251 // external AST support. 2252 for (const DWARFDIE &die : contained_type_dies) 2253 dwarf->ResolveType(die); 2254 2255 return (bool)clang_type; 2256} 2257 2258bool DWARFASTParserClang::CompleteEnumType(const DWARFDIE &die, 2259 lldb_private::Type *type, 2260 CompilerType &clang_type) { 2261 if (TypeSystemClang::StartTagDeclarationDefinition(clang_type)) { 2262 if (die.HasChildren()) { 2263 bool is_signed = false; 2264 clang_type.IsIntegerType(is_signed); 2265 ParseChildEnumerators(clang_type, is_signed, 2266 type->GetByteSize(nullptr).value_or(0), die); 2267 } 2268 TypeSystemClang::CompleteTagDeclarationDefinition(clang_type); 2269 } 2270 return (bool)clang_type; 2271} 2272 2273bool DWARFASTParserClang::CompleteTypeFromDWARF(const DWARFDIE &die, 2274 lldb_private::Type *type, 2275 CompilerType &clang_type) { 2276 SymbolFileDWARF *dwarf = die.GetDWARF(); 2277 2278 std::lock_guard<std::recursive_mutex> guard( 2279 dwarf->GetObjectFile()->GetModule()->GetMutex()); 2280 2281 // Disable external storage for this type so we don't get anymore 2282 // clang::ExternalASTSource queries for this type. 2283 m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), false); 2284 2285 if (!die) 2286 return false; 2287 2288 const dw_tag_t tag = die.Tag(); 2289 2290 assert(clang_type); 2291 switch (tag) { 2292 case DW_TAG_structure_type: 2293 case DW_TAG_union_type: 2294 case DW_TAG_class_type: 2295 return CompleteRecordType(die, type, clang_type); 2296 case DW_TAG_enumeration_type: 2297 return CompleteEnumType(die, type, clang_type); 2298 default: 2299 assert(false && "not a forward clang type decl!"); 2300 break; 2301 } 2302 2303 return false; 2304} 2305 2306void DWARFASTParserClang::EnsureAllDIEsInDeclContextHaveBeenParsed( 2307 lldb_private::CompilerDeclContext decl_context) { 2308 auto opaque_decl_ctx = 2309 (clang::DeclContext *)decl_context.GetOpaqueDeclContext(); 2310 for (auto it = m_decl_ctx_to_die.find(opaque_decl_ctx); 2311 it != m_decl_ctx_to_die.end() && it->first == opaque_decl_ctx; 2312 it = m_decl_ctx_to_die.erase(it)) 2313 for (DWARFDIE decl : it->second.children()) 2314 GetClangDeclForDIE(decl); 2315} 2316 2317CompilerDecl DWARFASTParserClang::GetDeclForUIDFromDWARF(const DWARFDIE &die) { 2318 clang::Decl *clang_decl = GetClangDeclForDIE(die); 2319 if (clang_decl != nullptr) 2320 return m_ast.GetCompilerDecl(clang_decl); 2321 return {}; 2322} 2323 2324CompilerDeclContext 2325DWARFASTParserClang::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) { 2326 clang::DeclContext *clang_decl_ctx = GetClangDeclContextForDIE(die); 2327 if (clang_decl_ctx) 2328 return m_ast.CreateDeclContext(clang_decl_ctx); 2329 return {}; 2330} 2331 2332CompilerDeclContext 2333DWARFASTParserClang::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) { 2334 clang::DeclContext *clang_decl_ctx = 2335 GetClangDeclContextContainingDIE(die, nullptr); 2336 if (clang_decl_ctx) 2337 return m_ast.CreateDeclContext(clang_decl_ctx); 2338 return {}; 2339} 2340 2341size_t DWARFASTParserClang::ParseChildEnumerators( 2342 lldb_private::CompilerType &clang_type, bool is_signed, 2343 uint32_t enumerator_byte_size, const DWARFDIE &parent_die) { 2344 if (!parent_die) 2345 return 0; 2346 2347 size_t enumerators_added = 0; 2348 2349 for (DWARFDIE die : parent_die.children()) { 2350 const dw_tag_t tag = die.Tag(); 2351 if (tag != DW_TAG_enumerator) 2352 continue; 2353 2354 DWARFAttributes attributes = die.GetAttributes(); 2355 if (attributes.Size() == 0) 2356 continue; 2357 2358 const char *name = nullptr; 2359 bool got_value = false; 2360 int64_t enum_value = 0; 2361 Declaration decl; 2362 2363 for (size_t i = 0; i < attributes.Size(); ++i) { 2364 const dw_attr_t attr = attributes.AttributeAtIndex(i); 2365 DWARFFormValue form_value; 2366 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 2367 switch (attr) { 2368 case DW_AT_const_value: 2369 got_value = true; 2370 if (is_signed) 2371 enum_value = form_value.Signed(); 2372 else 2373 enum_value = form_value.Unsigned(); 2374 break; 2375 2376 case DW_AT_name: 2377 name = form_value.AsCString(); 2378 break; 2379 2380 case DW_AT_description: 2381 default: 2382 case DW_AT_decl_file: 2383 decl.SetFile( 2384 attributes.CompileUnitAtIndex(i)->GetFile(form_value.Unsigned())); 2385 break; 2386 case DW_AT_decl_line: 2387 decl.SetLine(form_value.Unsigned()); 2388 break; 2389 case DW_AT_decl_column: 2390 decl.SetColumn(form_value.Unsigned()); 2391 break; 2392 case DW_AT_sibling: 2393 break; 2394 } 2395 } 2396 } 2397 2398 if (name && name[0] && got_value) { 2399 m_ast.AddEnumerationValueToEnumerationType( 2400 clang_type, decl, name, enum_value, enumerator_byte_size * 8); 2401 ++enumerators_added; 2402 } 2403 } 2404 return enumerators_added; 2405} 2406 2407ConstString 2408DWARFASTParserClang::ConstructDemangledNameFromDWARF(const DWARFDIE &die) { 2409 bool is_static = false; 2410 bool is_variadic = false; 2411 bool has_template_params = false; 2412 unsigned type_quals = 0; 2413 std::vector<CompilerType> param_types; 2414 std::vector<clang::ParmVarDecl *> param_decls; 2415 StreamString sstr; 2416 2417 DWARFDeclContext decl_ctx = SymbolFileDWARF::GetDWARFDeclContext(die); 2418 sstr << decl_ctx.GetQualifiedName(); 2419 2420 clang::DeclContext *containing_decl_ctx = 2421 GetClangDeclContextContainingDIE(die, nullptr); 2422 ParseChildParameters(containing_decl_ctx, die, true, is_static, is_variadic, 2423 has_template_params, param_types, param_decls, 2424 type_quals); 2425 sstr << "("; 2426 for (size_t i = 0; i < param_types.size(); i++) { 2427 if (i > 0) 2428 sstr << ", "; 2429 sstr << param_types[i].GetTypeName(); 2430 } 2431 if (is_variadic) 2432 sstr << ", ..."; 2433 sstr << ")"; 2434 if (type_quals & clang::Qualifiers::Const) 2435 sstr << " const"; 2436 2437 return ConstString(sstr.GetString()); 2438} 2439 2440Function * 2441DWARFASTParserClang::ParseFunctionFromDWARF(CompileUnit &comp_unit, 2442 const DWARFDIE &die, 2443 const AddressRange &func_range) { 2444 assert(func_range.GetBaseAddress().IsValid()); 2445 DWARFRangeList func_ranges; 2446 const char *name = nullptr; 2447 const char *mangled = nullptr; 2448 std::optional<int> decl_file; 2449 std::optional<int> decl_line; 2450 std::optional<int> decl_column; 2451 std::optional<int> call_file; 2452 std::optional<int> call_line; 2453 std::optional<int> call_column; 2454 DWARFExpressionList frame_base; 2455 2456 const dw_tag_t tag = die.Tag(); 2457 2458 if (tag != DW_TAG_subprogram) 2459 return nullptr; 2460 2461 if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line, 2462 decl_column, call_file, call_line, call_column, 2463 &frame_base)) { 2464 Mangled func_name; 2465 if (mangled) 2466 func_name.SetValue(ConstString(mangled)); 2467 else if ((die.GetParent().Tag() == DW_TAG_compile_unit || 2468 die.GetParent().Tag() == DW_TAG_partial_unit) && 2469 Language::LanguageIsCPlusPlus( 2470 SymbolFileDWARF::GetLanguage(*die.GetCU())) && 2471 !Language::LanguageIsObjC( 2472 SymbolFileDWARF::GetLanguage(*die.GetCU())) && 2473 name && strcmp(name, "main") != 0) { 2474 // If the mangled name is not present in the DWARF, generate the 2475 // demangled name using the decl context. We skip if the function is 2476 // "main" as its name is never mangled. 2477 func_name.SetValue(ConstructDemangledNameFromDWARF(die)); 2478 } else 2479 func_name.SetValue(ConstString(name)); 2480 2481 FunctionSP func_sp; 2482 std::unique_ptr<Declaration> decl_up; 2483 if (decl_file || decl_line || decl_column) 2484 decl_up = std::make_unique<Declaration>( 2485 die.GetCU()->GetFile(decl_file ? *decl_file : 0), 2486 decl_line ? *decl_line : 0, decl_column ? *decl_column : 0); 2487 2488 SymbolFileDWARF *dwarf = die.GetDWARF(); 2489 // Supply the type _only_ if it has already been parsed 2490 Type *func_type = dwarf->GetDIEToType().lookup(die.GetDIE()); 2491 2492 assert(func_type == nullptr || func_type != DIE_IS_BEING_PARSED); 2493 2494 const user_id_t func_user_id = die.GetID(); 2495 func_sp = 2496 std::make_shared<Function>(&comp_unit, 2497 func_user_id, // UserID is the DIE offset 2498 func_user_id, func_name, func_type, 2499 func_range); // first address range 2500 2501 if (func_sp.get() != nullptr) { 2502 if (frame_base.IsValid()) 2503 func_sp->GetFrameBaseExpression() = frame_base; 2504 comp_unit.AddFunction(func_sp); 2505 return func_sp.get(); 2506 } 2507 } 2508 return nullptr; 2509} 2510 2511namespace { 2512/// Parsed form of all attributes that are relevant for parsing Objective-C 2513/// properties. 2514struct PropertyAttributes { 2515 explicit PropertyAttributes(const DWARFDIE &die); 2516 const char *prop_name = nullptr; 2517 const char *prop_getter_name = nullptr; 2518 const char *prop_setter_name = nullptr; 2519 /// \see clang::ObjCPropertyAttribute 2520 uint32_t prop_attributes = 0; 2521}; 2522 2523struct DiscriminantValue { 2524 explicit DiscriminantValue(const DWARFDIE &die, ModuleSP module_sp); 2525 2526 uint32_t byte_offset; 2527 uint32_t byte_size; 2528 DWARFFormValue type_ref; 2529}; 2530 2531struct VariantMember { 2532 explicit VariantMember(DWARFDIE &die, ModuleSP module_sp); 2533 bool IsDefault() const; 2534 2535 std::optional<uint32_t> discr_value; 2536 DWARFFormValue type_ref; 2537 ConstString variant_name; 2538 uint32_t byte_offset; 2539 ConstString GetName() const; 2540}; 2541 2542struct VariantPart { 2543 explicit VariantPart(const DWARFDIE &die, const DWARFDIE &parent_die, 2544 ModuleSP module_sp); 2545 2546 std::vector<VariantMember> &members(); 2547 2548 DiscriminantValue &discriminant(); 2549 2550private: 2551 std::vector<VariantMember> _members; 2552 DiscriminantValue _discriminant; 2553}; 2554 2555} // namespace 2556 2557ConstString VariantMember::GetName() const { return this->variant_name; } 2558 2559bool VariantMember::IsDefault() const { return !discr_value; } 2560 2561VariantMember::VariantMember(DWARFDIE &die, lldb::ModuleSP module_sp) { 2562 assert(die.Tag() == llvm::dwarf::DW_TAG_variant); 2563 this->discr_value = 2564 die.GetAttributeValueAsOptionalUnsigned(DW_AT_discr_value); 2565 2566 for (auto child_die : die.children()) { 2567 switch (child_die.Tag()) { 2568 case llvm::dwarf::DW_TAG_member: { 2569 DWARFAttributes attributes = child_die.GetAttributes(); 2570 for (std::size_t i = 0; i < attributes.Size(); ++i) { 2571 DWARFFormValue form_value; 2572 const dw_attr_t attr = attributes.AttributeAtIndex(i); 2573 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 2574 switch (attr) { 2575 case DW_AT_name: 2576 variant_name = ConstString(form_value.AsCString()); 2577 break; 2578 case DW_AT_type: 2579 type_ref = form_value; 2580 break; 2581 2582 case DW_AT_data_member_location: 2583 if (auto maybe_offset = 2584 ExtractDataMemberLocation(die, form_value, module_sp)) 2585 byte_offset = *maybe_offset; 2586 break; 2587 2588 default: 2589 break; 2590 } 2591 } 2592 } 2593 break; 2594 } 2595 default: 2596 break; 2597 } 2598 break; 2599 } 2600} 2601 2602DiscriminantValue::DiscriminantValue(const DWARFDIE &die, ModuleSP module_sp) { 2603 auto referenced_die = die.GetReferencedDIE(DW_AT_discr); 2604 DWARFAttributes attributes = referenced_die.GetAttributes(); 2605 for (std::size_t i = 0; i < attributes.Size(); ++i) { 2606 const dw_attr_t attr = attributes.AttributeAtIndex(i); 2607 DWARFFormValue form_value; 2608 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 2609 switch (attr) { 2610 case DW_AT_type: 2611 type_ref = form_value; 2612 break; 2613 case DW_AT_data_member_location: 2614 if (auto maybe_offset = 2615 ExtractDataMemberLocation(die, form_value, module_sp)) 2616 byte_offset = *maybe_offset; 2617 break; 2618 default: 2619 break; 2620 } 2621 } 2622 } 2623} 2624 2625VariantPart::VariantPart(const DWARFDIE &die, const DWARFDIE &parent_die, 2626 lldb::ModuleSP module_sp) 2627 : _members(), _discriminant(die, module_sp) { 2628 2629 for (auto child : die.children()) { 2630 if (child.Tag() == llvm::dwarf::DW_TAG_variant) { 2631 _members.push_back(VariantMember(child, module_sp)); 2632 } 2633 } 2634} 2635 2636std::vector<VariantMember> &VariantPart::members() { return this->_members; } 2637 2638DiscriminantValue &VariantPart::discriminant() { return this->_discriminant; } 2639 2640DWARFASTParserClang::MemberAttributes::MemberAttributes( 2641 const DWARFDIE &die, const DWARFDIE &parent_die, ModuleSP module_sp) { 2642 DWARFAttributes attributes = die.GetAttributes(); 2643 for (size_t i = 0; i < attributes.Size(); ++i) { 2644 const dw_attr_t attr = attributes.AttributeAtIndex(i); 2645 DWARFFormValue form_value; 2646 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 2647 switch (attr) { 2648 case DW_AT_name: 2649 name = form_value.AsCString(); 2650 break; 2651 case DW_AT_type: 2652 encoding_form = form_value; 2653 break; 2654 case DW_AT_bit_offset: 2655 bit_offset = form_value.Signed(); 2656 break; 2657 case DW_AT_bit_size: 2658 bit_size = form_value.Unsigned(); 2659 break; 2660 case DW_AT_byte_size: 2661 byte_size = form_value.Unsigned(); 2662 break; 2663 case DW_AT_const_value: 2664 const_value_form = form_value; 2665 break; 2666 case DW_AT_data_bit_offset: 2667 data_bit_offset = form_value.Unsigned(); 2668 break; 2669 case DW_AT_data_member_location: 2670 if (auto maybe_offset = 2671 ExtractDataMemberLocation(die, form_value, module_sp)) 2672 member_byte_offset = *maybe_offset; 2673 break; 2674 2675 case DW_AT_accessibility: 2676 accessibility = 2677 DWARFASTParser::GetAccessTypeFromDWARF(form_value.Unsigned()); 2678 break; 2679 case DW_AT_artificial: 2680 is_artificial = form_value.Boolean(); 2681 break; 2682 case DW_AT_declaration: 2683 is_declaration = form_value.Boolean(); 2684 break; 2685 default: 2686 break; 2687 } 2688 } 2689 } 2690 2691 // Clang has a DWARF generation bug where sometimes it represents 2692 // fields that are references with bad byte size and bit size/offset 2693 // information such as: 2694 // 2695 // DW_AT_byte_size( 0x00 ) 2696 // DW_AT_bit_size( 0x40 ) 2697 // DW_AT_bit_offset( 0xffffffffffffffc0 ) 2698 // 2699 // So check the bit offset to make sure it is sane, and if the values 2700 // are not sane, remove them. If we don't do this then we will end up 2701 // with a crash if we try to use this type in an expression when clang 2702 // becomes unhappy with its recycled debug info. 2703 if (byte_size.value_or(0) == 0 && bit_offset < 0) { 2704 bit_size = 0; 2705 bit_offset = 0; 2706 } 2707} 2708 2709PropertyAttributes::PropertyAttributes(const DWARFDIE &die) { 2710 2711 DWARFAttributes attributes = die.GetAttributes(); 2712 for (size_t i = 0; i < attributes.Size(); ++i) { 2713 const dw_attr_t attr = attributes.AttributeAtIndex(i); 2714 DWARFFormValue form_value; 2715 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 2716 switch (attr) { 2717 case DW_AT_APPLE_property_name: 2718 prop_name = form_value.AsCString(); 2719 break; 2720 case DW_AT_APPLE_property_getter: 2721 prop_getter_name = form_value.AsCString(); 2722 break; 2723 case DW_AT_APPLE_property_setter: 2724 prop_setter_name = form_value.AsCString(); 2725 break; 2726 case DW_AT_APPLE_property_attribute: 2727 prop_attributes = form_value.Unsigned(); 2728 break; 2729 default: 2730 break; 2731 } 2732 } 2733 } 2734 2735 if (!prop_name) 2736 return; 2737 ConstString fixed_setter; 2738 2739 // Check if the property getter/setter were provided as full names. 2740 // We want basenames, so we extract them. 2741 if (prop_getter_name && prop_getter_name[0] == '-') { 2742 std::optional<const ObjCLanguage::MethodName> prop_getter_method = 2743 ObjCLanguage::MethodName::Create(prop_getter_name, true); 2744 if (prop_getter_method) 2745 prop_getter_name = 2746 ConstString(prop_getter_method->GetSelector()).GetCString(); 2747 } 2748 2749 if (prop_setter_name && prop_setter_name[0] == '-') { 2750 std::optional<const ObjCLanguage::MethodName> prop_setter_method = 2751 ObjCLanguage::MethodName::Create(prop_setter_name, true); 2752 if (prop_setter_method) 2753 prop_setter_name = 2754 ConstString(prop_setter_method->GetSelector()).GetCString(); 2755 } 2756 2757 // If the names haven't been provided, they need to be filled in. 2758 if (!prop_getter_name) 2759 prop_getter_name = prop_name; 2760 if (!prop_setter_name && prop_name[0] && 2761 !(prop_attributes & DW_APPLE_PROPERTY_readonly)) { 2762 StreamString ss; 2763 2764 ss.Printf("set%c%s:", toupper(prop_name[0]), &prop_name[1]); 2765 2766 fixed_setter.SetString(ss.GetString()); 2767 prop_setter_name = fixed_setter.GetCString(); 2768 } 2769} 2770 2771void DWARFASTParserClang::ParseObjCProperty( 2772 const DWARFDIE &die, const DWARFDIE &parent_die, 2773 const lldb_private::CompilerType &class_clang_type, 2774 DelayedPropertyList &delayed_properties) { 2775 // This function can only parse DW_TAG_APPLE_property. 2776 assert(die.Tag() == DW_TAG_APPLE_property); 2777 2778 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule(); 2779 2780 const MemberAttributes attrs(die, parent_die, module_sp); 2781 const PropertyAttributes propAttrs(die); 2782 2783 if (!propAttrs.prop_name) { 2784 module_sp->ReportError("{0:x8}: DW_TAG_APPLE_property has no name.", 2785 die.GetID()); 2786 return; 2787 } 2788 2789 Type *member_type = die.ResolveTypeUID(attrs.encoding_form.Reference()); 2790 if (!member_type) { 2791 module_sp->ReportError( 2792 "{0:x8}: DW_TAG_APPLE_property '{1}' refers to type {2:x16}" 2793 " which was unable to be parsed", 2794 die.GetID(), propAttrs.prop_name, 2795 attrs.encoding_form.Reference().GetOffset()); 2796 return; 2797 } 2798 2799 ClangASTMetadata metadata; 2800 metadata.SetUserID(die.GetID()); 2801 delayed_properties.push_back(DelayedAddObjCClassProperty( 2802 class_clang_type, propAttrs.prop_name, 2803 member_type->GetLayoutCompilerType(), propAttrs.prop_setter_name, 2804 propAttrs.prop_getter_name, propAttrs.prop_attributes, &metadata)); 2805} 2806 2807llvm::Expected<llvm::APInt> DWARFASTParserClang::ExtractIntFromFormValue( 2808 const CompilerType &int_type, const DWARFFormValue &form_value) const { 2809 clang::QualType qt = ClangUtil::GetQualType(int_type); 2810 assert(qt->isIntegralOrEnumerationType()); 2811 auto ts_ptr = int_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>(); 2812 if (!ts_ptr) 2813 return llvm::createStringError(llvm::inconvertibleErrorCode(), 2814 "TypeSystem not clang"); 2815 TypeSystemClang &ts = *ts_ptr; 2816 clang::ASTContext &ast = ts.getASTContext(); 2817 2818 const unsigned type_bits = ast.getIntWidth(qt); 2819 const bool is_unsigned = qt->isUnsignedIntegerType(); 2820 2821 // The maximum int size supported at the moment by this function. Limited 2822 // by the uint64_t return type of DWARFFormValue::Signed/Unsigned. 2823 constexpr std::size_t max_bit_size = 64; 2824 2825 // For values bigger than 64 bit (e.g. __int128_t values), 2826 // DWARFFormValue's Signed/Unsigned functions will return wrong results so 2827 // emit an error for now. 2828 if (type_bits > max_bit_size) { 2829 auto msg = llvm::formatv("Can only parse integers with up to {0} bits, but " 2830 "given integer has {1} bits.", 2831 max_bit_size, type_bits); 2832 return llvm::createStringError(llvm::inconvertibleErrorCode(), msg.str()); 2833 } 2834 2835 // Construct an APInt with the maximum bit size and the given integer. 2836 llvm::APInt result(max_bit_size, form_value.Unsigned(), !is_unsigned); 2837 2838 // Calculate how many bits are required to represent the input value. 2839 // For unsigned types, take the number of active bits in the APInt. 2840 // For signed types, ask APInt how many bits are required to represent the 2841 // signed integer. 2842 const unsigned required_bits = 2843 is_unsigned ? result.getActiveBits() : result.getSignificantBits(); 2844 2845 // If the input value doesn't fit into the integer type, return an error. 2846 if (required_bits > type_bits) { 2847 std::string value_as_str = is_unsigned 2848 ? std::to_string(form_value.Unsigned()) 2849 : std::to_string(form_value.Signed()); 2850 auto msg = llvm::formatv("Can't store {0} value {1} in integer with {2} " 2851 "bits.", 2852 (is_unsigned ? "unsigned" : "signed"), 2853 value_as_str, type_bits); 2854 return llvm::createStringError(llvm::inconvertibleErrorCode(), msg.str()); 2855 } 2856 2857 // Trim the result to the bit width our the int type. 2858 if (result.getBitWidth() > type_bits) 2859 result = result.trunc(type_bits); 2860 return result; 2861} 2862 2863void DWARFASTParserClang::CreateStaticMemberVariable( 2864 const DWARFDIE &die, const MemberAttributes &attrs, 2865 const lldb_private::CompilerType &class_clang_type) { 2866 Log *log = GetLog(DWARFLog::TypeCompletion | DWARFLog::Lookups); 2867 assert(die.Tag() == DW_TAG_member || die.Tag() == DW_TAG_variable); 2868 2869 Type *var_type = die.ResolveTypeUID(attrs.encoding_form.Reference()); 2870 2871 if (!var_type) 2872 return; 2873 2874 auto accessibility = 2875 attrs.accessibility == eAccessNone ? eAccessPublic : attrs.accessibility; 2876 2877 CompilerType ct = var_type->GetForwardCompilerType(); 2878 clang::VarDecl *v = TypeSystemClang::AddVariableToRecordType( 2879 class_clang_type, attrs.name, ct, accessibility); 2880 if (!v) { 2881 LLDB_LOG(log, "Failed to add variable to the record type"); 2882 return; 2883 } 2884 2885 bool unused; 2886 // TODO: Support float/double static members as well. 2887 if (!ct.IsIntegerOrEnumerationType(unused) || !attrs.const_value_form) 2888 return; 2889 2890 llvm::Expected<llvm::APInt> const_value_or_err = 2891 ExtractIntFromFormValue(ct, *attrs.const_value_form); 2892 if (!const_value_or_err) { 2893 LLDB_LOG_ERROR(log, const_value_or_err.takeError(), 2894 "Failed to add const value to variable {1}: {0}", 2895 v->getQualifiedNameAsString()); 2896 return; 2897 } 2898 2899 TypeSystemClang::SetIntegerInitializerForVariable(v, *const_value_or_err); 2900} 2901 2902void DWARFASTParserClang::ParseSingleMember( 2903 const DWARFDIE &die, const DWARFDIE &parent_die, 2904 const lldb_private::CompilerType &class_clang_type, 2905 lldb::AccessType default_accessibility, 2906 lldb_private::ClangASTImporter::LayoutInfo &layout_info, 2907 FieldInfo &last_field_info) { 2908 // This function can only parse DW_TAG_member. 2909 assert(die.Tag() == DW_TAG_member); 2910 2911 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule(); 2912 const dw_tag_t tag = die.Tag(); 2913 // Get the parent byte size so we can verify any members will fit 2914 const uint64_t parent_byte_size = 2915 parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size, UINT64_MAX); 2916 const uint64_t parent_bit_size = 2917 parent_byte_size == UINT64_MAX ? UINT64_MAX : parent_byte_size * 8; 2918 2919 const MemberAttributes attrs(die, parent_die, module_sp); 2920 2921 // Handle static members, which are typically members without 2922 // locations. However, GCC doesn't emit DW_AT_data_member_location 2923 // for any union members (regardless of linkage). 2924 // Non-normative text pre-DWARFv5 recommends marking static 2925 // data members with an DW_AT_external flag. Clang emits this consistently 2926 // whereas GCC emits it only for static data members if not part of an 2927 // anonymous namespace. The flag that is consistently emitted for static 2928 // data members is DW_AT_declaration, so we check it instead. 2929 // The following block is only necessary to support DWARFv4 and earlier. 2930 // Starting with DWARFv5, static data members are marked DW_AT_variable so we 2931 // can consistently detect them on both GCC and Clang without below heuristic. 2932 if (attrs.member_byte_offset == UINT32_MAX && 2933 attrs.data_bit_offset == UINT64_MAX && attrs.is_declaration) { 2934 CreateStaticMemberVariable(die, attrs, class_clang_type); 2935 return; 2936 } 2937 2938 Type *member_type = die.ResolveTypeUID(attrs.encoding_form.Reference()); 2939 if (!member_type) { 2940 if (attrs.name) 2941 module_sp->ReportError( 2942 "{0:x8}: DW_TAG_member '{1}' refers to type {2:x16}" 2943 " which was unable to be parsed", 2944 die.GetID(), attrs.name, attrs.encoding_form.Reference().GetOffset()); 2945 else 2946 module_sp->ReportError("{0:x8}: DW_TAG_member refers to type {1:x16}" 2947 " which was unable to be parsed", 2948 die.GetID(), 2949 attrs.encoding_form.Reference().GetOffset()); 2950 return; 2951 } 2952 2953 const uint64_t character_width = 8; 2954 const uint64_t word_width = 32; 2955 CompilerType member_clang_type = member_type->GetLayoutCompilerType(); 2956 2957 const auto accessibility = attrs.accessibility == eAccessNone 2958 ? default_accessibility 2959 : attrs.accessibility; 2960 2961 uint64_t field_bit_offset = (attrs.member_byte_offset == UINT32_MAX 2962 ? 0 2963 : (attrs.member_byte_offset * 8ULL)); 2964 2965 if (attrs.bit_size > 0) { 2966 FieldInfo this_field_info; 2967 this_field_info.bit_offset = field_bit_offset; 2968 this_field_info.bit_size = attrs.bit_size; 2969 2970 if (attrs.data_bit_offset != UINT64_MAX) { 2971 this_field_info.bit_offset = attrs.data_bit_offset; 2972 } else { 2973 auto byte_size = attrs.byte_size; 2974 if (!byte_size) 2975 byte_size = member_type->GetByteSize(nullptr); 2976 2977 ObjectFile *objfile = die.GetDWARF()->GetObjectFile(); 2978 if (objfile->GetByteOrder() == eByteOrderLittle) { 2979 this_field_info.bit_offset += byte_size.value_or(0) * 8; 2980 this_field_info.bit_offset -= (attrs.bit_offset + attrs.bit_size); 2981 } else { 2982 this_field_info.bit_offset += attrs.bit_offset; 2983 } 2984 } 2985 2986 // The ObjC runtime knows the byte offset but we still need to provide 2987 // the bit-offset in the layout. It just means something different then 2988 // what it does in C and C++. So we skip this check for ObjC types. 2989 // 2990 // We also skip this for fields of a union since they will all have a 2991 // zero offset. 2992 if (!TypeSystemClang::IsObjCObjectOrInterfaceType(class_clang_type) && 2993 !(parent_die.Tag() == DW_TAG_union_type && 2994 this_field_info.bit_offset == 0) && 2995 ((this_field_info.bit_offset >= parent_bit_size) || 2996 (last_field_info.IsBitfield() && 2997 !last_field_info.NextBitfieldOffsetIsValid( 2998 this_field_info.bit_offset)))) { 2999 ObjectFile *objfile = die.GetDWARF()->GetObjectFile(); 3000 objfile->GetModule()->ReportWarning( 3001 "{0:x16}: {1} bitfield named \"{2}\" has invalid " 3002 "bit offset ({3:x8}) member will be ignored. Please file a bug " 3003 "against the " 3004 "compiler and include the preprocessed output for {4}\n", 3005 die.GetID(), DW_TAG_value_to_name(tag), attrs.name, 3006 this_field_info.bit_offset, GetUnitName(parent_die).c_str()); 3007 return; 3008 } 3009 3010 // Update the field bit offset we will report for layout 3011 field_bit_offset = this_field_info.bit_offset; 3012 3013 // Objective-C has invalid DW_AT_bit_offset values in older 3014 // versions of clang, so we have to be careful and only insert 3015 // unnamed bitfields if we have a new enough clang. 3016 bool detect_unnamed_bitfields = true; 3017 3018 if (TypeSystemClang::IsObjCObjectOrInterfaceType(class_clang_type)) 3019 detect_unnamed_bitfields = 3020 die.GetCU()->Supports_unnamed_objc_bitfields(); 3021 3022 if (detect_unnamed_bitfields) { 3023 std::optional<FieldInfo> unnamed_field_info; 3024 uint64_t last_field_end = 3025 last_field_info.bit_offset + last_field_info.bit_size; 3026 3027 if (!last_field_info.IsBitfield()) { 3028 // The last field was not a bit-field... 3029 // but if it did take up the entire word then we need to extend 3030 // last_field_end so the bit-field does not step into the last 3031 // fields padding. 3032 if (last_field_end != 0 && ((last_field_end % word_width) != 0)) 3033 last_field_end += word_width - (last_field_end % word_width); 3034 } 3035 3036 if (ShouldCreateUnnamedBitfield(last_field_info, last_field_end, 3037 this_field_info, layout_info)) { 3038 unnamed_field_info = FieldInfo{}; 3039 unnamed_field_info->bit_size = 3040 this_field_info.bit_offset - last_field_end; 3041 unnamed_field_info->bit_offset = last_field_end; 3042 } 3043 3044 if (unnamed_field_info) { 3045 clang::FieldDecl *unnamed_bitfield_decl = 3046 TypeSystemClang::AddFieldToRecordType( 3047 class_clang_type, llvm::StringRef(), 3048 m_ast.GetBuiltinTypeForEncodingAndBitSize(eEncodingSint, 3049 word_width), 3050 accessibility, unnamed_field_info->bit_size); 3051 3052 layout_info.field_offsets.insert(std::make_pair( 3053 unnamed_bitfield_decl, unnamed_field_info->bit_offset)); 3054 } 3055 } 3056 3057 last_field_info = this_field_info; 3058 last_field_info.SetIsBitfield(true); 3059 } else { 3060 last_field_info.bit_offset = field_bit_offset; 3061 3062 if (std::optional<uint64_t> clang_type_size = 3063 member_type->GetByteSize(nullptr)) { 3064 last_field_info.bit_size = *clang_type_size * character_width; 3065 } 3066 3067 last_field_info.SetIsBitfield(false); 3068 } 3069 3070 // Don't turn artificial members such as vtable pointers into real FieldDecls 3071 // in our AST. Clang will re-create those articial members and they would 3072 // otherwise just overlap in the layout with the FieldDecls we add here. 3073 // This needs to be done after updating FieldInfo which keeps track of where 3074 // field start/end so we don't later try to fill the space of this 3075 // artificial member with (unnamed bitfield) padding. 3076 if (attrs.is_artificial && ShouldIgnoreArtificialField(attrs.name)) { 3077 last_field_info.SetIsArtificial(true); 3078 return; 3079 } 3080 3081 if (!member_clang_type.IsCompleteType()) 3082 member_clang_type.GetCompleteType(); 3083 3084 { 3085 // Older versions of clang emit the same DWARF for array[0] and array[1]. If 3086 // the current field is at the end of the structure, then there is 3087 // definitely no room for extra elements and we override the type to 3088 // array[0]. This was fixed by f454dfb6b5af. 3089 CompilerType member_array_element_type; 3090 uint64_t member_array_size; 3091 bool member_array_is_incomplete; 3092 3093 if (member_clang_type.IsArrayType(&member_array_element_type, 3094 &member_array_size, 3095 &member_array_is_incomplete) && 3096 !member_array_is_incomplete) { 3097 uint64_t parent_byte_size = 3098 parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size, UINT64_MAX); 3099 3100 if (attrs.member_byte_offset >= parent_byte_size) { 3101 if (member_array_size != 1 && 3102 (member_array_size != 0 || 3103 attrs.member_byte_offset > parent_byte_size)) { 3104 module_sp->ReportError( 3105 "{0:x8}: DW_TAG_member '{1}' refers to type {2:x16}" 3106 " which extends beyond the bounds of {3:x8}", 3107 die.GetID(), attrs.name, 3108 attrs.encoding_form.Reference().GetOffset(), parent_die.GetID()); 3109 } 3110 3111 member_clang_type = 3112 m_ast.CreateArrayType(member_array_element_type, 0, false); 3113 } 3114 } 3115 } 3116 3117 TypeSystemClang::RequireCompleteType(member_clang_type); 3118 3119 clang::FieldDecl *field_decl = TypeSystemClang::AddFieldToRecordType( 3120 class_clang_type, attrs.name, member_clang_type, accessibility, 3121 attrs.bit_size); 3122 3123 m_ast.SetMetadataAsUserID(field_decl, die.GetID()); 3124 3125 layout_info.field_offsets.insert( 3126 std::make_pair(field_decl, field_bit_offset)); 3127} 3128 3129bool DWARFASTParserClang::ParseChildMembers( 3130 const DWARFDIE &parent_die, CompilerType &class_clang_type, 3131 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes, 3132 std::vector<DWARFDIE> &member_function_dies, 3133 std::vector<DWARFDIE> &contained_type_dies, 3134 DelayedPropertyList &delayed_properties, 3135 const AccessType default_accessibility, 3136 ClangASTImporter::LayoutInfo &layout_info) { 3137 if (!parent_die) 3138 return false; 3139 3140 FieldInfo last_field_info; 3141 3142 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule(); 3143 auto ts = class_clang_type.GetTypeSystem(); 3144 auto ast = ts.dyn_cast_or_null<TypeSystemClang>(); 3145 if (ast == nullptr) 3146 return false; 3147 3148 for (DWARFDIE die : parent_die.children()) { 3149 dw_tag_t tag = die.Tag(); 3150 3151 switch (tag) { 3152 case DW_TAG_APPLE_property: 3153 ParseObjCProperty(die, parent_die, class_clang_type, delayed_properties); 3154 break; 3155 3156 case DW_TAG_variant_part: 3157 if (die.GetCU()->GetDWARFLanguageType() == eLanguageTypeRust) { 3158 ParseRustVariantPart(die, parent_die, class_clang_type, 3159 default_accessibility, layout_info); 3160 } 3161 break; 3162 3163 case DW_TAG_variable: { 3164 const MemberAttributes attrs(die, parent_die, module_sp); 3165 CreateStaticMemberVariable(die, attrs, class_clang_type); 3166 } break; 3167 case DW_TAG_member: 3168 ParseSingleMember(die, parent_die, class_clang_type, 3169 default_accessibility, layout_info, last_field_info); 3170 break; 3171 3172 case DW_TAG_subprogram: 3173 // Let the type parsing code handle this one for us. 3174 member_function_dies.push_back(die); 3175 break; 3176 3177 case DW_TAG_inheritance: 3178 ParseInheritance(die, parent_die, class_clang_type, default_accessibility, 3179 module_sp, base_classes, layout_info); 3180 break; 3181 3182 default: 3183 if (llvm::dwarf::isType(tag)) 3184 contained_type_dies.push_back(die); 3185 break; 3186 } 3187 } 3188 3189 return true; 3190} 3191 3192size_t DWARFASTParserClang::ParseChildParameters( 3193 clang::DeclContext *containing_decl_ctx, const DWARFDIE &parent_die, 3194 bool skip_artificial, bool &is_static, bool &is_variadic, 3195 bool &has_template_params, std::vector<CompilerType> &function_param_types, 3196 std::vector<clang::ParmVarDecl *> &function_param_decls, 3197 unsigned &type_quals) { 3198 if (!parent_die) 3199 return 0; 3200 3201 size_t arg_idx = 0; 3202 for (DWARFDIE die : parent_die.children()) { 3203 const dw_tag_t tag = die.Tag(); 3204 switch (tag) { 3205 case DW_TAG_formal_parameter: { 3206 DWARFAttributes attributes = die.GetAttributes(); 3207 if (attributes.Size() == 0) { 3208 arg_idx++; 3209 break; 3210 } 3211 3212 const char *name = nullptr; 3213 DWARFFormValue param_type_die_form; 3214 bool is_artificial = false; 3215 // one of None, Auto, Register, Extern, Static, PrivateExtern 3216 3217 clang::StorageClass storage = clang::SC_None; 3218 uint32_t i; 3219 for (i = 0; i < attributes.Size(); ++i) { 3220 const dw_attr_t attr = attributes.AttributeAtIndex(i); 3221 DWARFFormValue form_value; 3222 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 3223 switch (attr) { 3224 case DW_AT_name: 3225 name = form_value.AsCString(); 3226 break; 3227 case DW_AT_type: 3228 param_type_die_form = form_value; 3229 break; 3230 case DW_AT_artificial: 3231 is_artificial = form_value.Boolean(); 3232 break; 3233 case DW_AT_location: 3234 case DW_AT_const_value: 3235 case DW_AT_default_value: 3236 case DW_AT_description: 3237 case DW_AT_endianity: 3238 case DW_AT_is_optional: 3239 case DW_AT_segment: 3240 case DW_AT_variable_parameter: 3241 default: 3242 case DW_AT_abstract_origin: 3243 case DW_AT_sibling: 3244 break; 3245 } 3246 } 3247 } 3248 3249 bool skip = false; 3250 if (skip_artificial && is_artificial) { 3251 // In order to determine if a C++ member function is "const" we 3252 // have to look at the const-ness of "this"... 3253 if (arg_idx == 0 && 3254 DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()) && 3255 // Often times compilers omit the "this" name for the 3256 // specification DIEs, so we can't rely upon the name being in 3257 // the formal parameter DIE... 3258 (name == nullptr || ::strcmp(name, "this") == 0)) { 3259 Type *this_type = die.ResolveTypeUID(param_type_die_form.Reference()); 3260 if (this_type) { 3261 uint32_t encoding_mask = this_type->GetEncodingMask(); 3262 if (encoding_mask & Type::eEncodingIsPointerUID) { 3263 is_static = false; 3264 3265 if (encoding_mask & (1u << Type::eEncodingIsConstUID)) 3266 type_quals |= clang::Qualifiers::Const; 3267 if (encoding_mask & (1u << Type::eEncodingIsVolatileUID)) 3268 type_quals |= clang::Qualifiers::Volatile; 3269 } 3270 } 3271 } 3272 skip = true; 3273 } 3274 3275 if (!skip) { 3276 Type *type = die.ResolveTypeUID(param_type_die_form.Reference()); 3277 if (type) { 3278 function_param_types.push_back(type->GetForwardCompilerType()); 3279 3280 clang::ParmVarDecl *param_var_decl = m_ast.CreateParameterDeclaration( 3281 containing_decl_ctx, GetOwningClangModule(die), name, 3282 type->GetForwardCompilerType(), storage); 3283 assert(param_var_decl); 3284 function_param_decls.push_back(param_var_decl); 3285 3286 m_ast.SetMetadataAsUserID(param_var_decl, die.GetID()); 3287 } 3288 } 3289 arg_idx++; 3290 } break; 3291 3292 case DW_TAG_unspecified_parameters: 3293 is_variadic = true; 3294 break; 3295 3296 case DW_TAG_template_type_parameter: 3297 case DW_TAG_template_value_parameter: 3298 case DW_TAG_GNU_template_parameter_pack: 3299 // The one caller of this was never using the template_param_infos, and 3300 // the local variable was taking up a large amount of stack space in 3301 // SymbolFileDWARF::ParseType() so this was removed. If we ever need the 3302 // template params back, we can add them back. 3303 // ParseTemplateDIE (dwarf_cu, die, template_param_infos); 3304 has_template_params = true; 3305 break; 3306 3307 default: 3308 break; 3309 } 3310 } 3311 return arg_idx; 3312} 3313 3314clang::Decl *DWARFASTParserClang::GetClangDeclForDIE(const DWARFDIE &die) { 3315 if (!die) 3316 return nullptr; 3317 3318 switch (die.Tag()) { 3319 case DW_TAG_constant: 3320 case DW_TAG_formal_parameter: 3321 case DW_TAG_imported_declaration: 3322 case DW_TAG_imported_module: 3323 break; 3324 case DW_TAG_variable: 3325 // This means 'die' is a C++ static data member. 3326 // We don't want to create decls for such members 3327 // here. 3328 if (auto parent = die.GetParent(); 3329 parent.IsValid() && TagIsRecordType(parent.Tag())) 3330 return nullptr; 3331 break; 3332 default: 3333 return nullptr; 3334 } 3335 3336 DIEToDeclMap::iterator cache_pos = m_die_to_decl.find(die.GetDIE()); 3337 if (cache_pos != m_die_to_decl.end()) 3338 return cache_pos->second; 3339 3340 if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification)) { 3341 clang::Decl *decl = GetClangDeclForDIE(spec_die); 3342 m_die_to_decl[die.GetDIE()] = decl; 3343 return decl; 3344 } 3345 3346 if (DWARFDIE abstract_origin_die = 3347 die.GetReferencedDIE(DW_AT_abstract_origin)) { 3348 clang::Decl *decl = GetClangDeclForDIE(abstract_origin_die); 3349 m_die_to_decl[die.GetDIE()] = decl; 3350 return decl; 3351 } 3352 3353 clang::Decl *decl = nullptr; 3354 switch (die.Tag()) { 3355 case DW_TAG_variable: 3356 case DW_TAG_constant: 3357 case DW_TAG_formal_parameter: { 3358 SymbolFileDWARF *dwarf = die.GetDWARF(); 3359 Type *type = GetTypeForDIE(die); 3360 if (dwarf && type) { 3361 const char *name = die.GetName(); 3362 clang::DeclContext *decl_context = 3363 TypeSystemClang::DeclContextGetAsDeclContext( 3364 dwarf->GetDeclContextContainingUID(die.GetID())); 3365 decl = m_ast.CreateVariableDeclaration( 3366 decl_context, GetOwningClangModule(die), name, 3367 ClangUtil::GetQualType(type->GetForwardCompilerType())); 3368 } 3369 break; 3370 } 3371 case DW_TAG_imported_declaration: { 3372 SymbolFileDWARF *dwarf = die.GetDWARF(); 3373 DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import); 3374 if (imported_uid) { 3375 CompilerDecl imported_decl = SymbolFileDWARF::GetDecl(imported_uid); 3376 if (imported_decl) { 3377 clang::DeclContext *decl_context = 3378 TypeSystemClang::DeclContextGetAsDeclContext( 3379 dwarf->GetDeclContextContainingUID(die.GetID())); 3380 if (clang::NamedDecl *clang_imported_decl = 3381 llvm::dyn_cast<clang::NamedDecl>( 3382 (clang::Decl *)imported_decl.GetOpaqueDecl())) 3383 decl = m_ast.CreateUsingDeclaration( 3384 decl_context, OptionalClangModuleID(), clang_imported_decl); 3385 } 3386 } 3387 break; 3388 } 3389 case DW_TAG_imported_module: { 3390 SymbolFileDWARF *dwarf = die.GetDWARF(); 3391 DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import); 3392 3393 if (imported_uid) { 3394 CompilerDeclContext imported_decl_ctx = 3395 SymbolFileDWARF::GetDeclContext(imported_uid); 3396 if (imported_decl_ctx) { 3397 clang::DeclContext *decl_context = 3398 TypeSystemClang::DeclContextGetAsDeclContext( 3399 dwarf->GetDeclContextContainingUID(die.GetID())); 3400 if (clang::NamespaceDecl *ns_decl = 3401 TypeSystemClang::DeclContextGetAsNamespaceDecl( 3402 imported_decl_ctx)) 3403 decl = m_ast.CreateUsingDirectiveDeclaration( 3404 decl_context, OptionalClangModuleID(), ns_decl); 3405 } 3406 } 3407 break; 3408 } 3409 default: 3410 break; 3411 } 3412 3413 m_die_to_decl[die.GetDIE()] = decl; 3414 3415 return decl; 3416} 3417 3418clang::DeclContext * 3419DWARFASTParserClang::GetClangDeclContextForDIE(const DWARFDIE &die) { 3420 if (die) { 3421 clang::DeclContext *decl_ctx = GetCachedClangDeclContextForDIE(die); 3422 if (decl_ctx) 3423 return decl_ctx; 3424 3425 bool try_parsing_type = true; 3426 switch (die.Tag()) { 3427 case DW_TAG_compile_unit: 3428 case DW_TAG_partial_unit: 3429 decl_ctx = m_ast.GetTranslationUnitDecl(); 3430 try_parsing_type = false; 3431 break; 3432 3433 case DW_TAG_namespace: 3434 decl_ctx = ResolveNamespaceDIE(die); 3435 try_parsing_type = false; 3436 break; 3437 3438 case DW_TAG_imported_declaration: 3439 decl_ctx = ResolveImportedDeclarationDIE(die); 3440 try_parsing_type = false; 3441 break; 3442 3443 case DW_TAG_lexical_block: 3444 decl_ctx = GetDeclContextForBlock(die); 3445 try_parsing_type = false; 3446 break; 3447 3448 default: 3449 break; 3450 } 3451 3452 if (decl_ctx == nullptr && try_parsing_type) { 3453 Type *type = die.GetDWARF()->ResolveType(die); 3454 if (type) 3455 decl_ctx = GetCachedClangDeclContextForDIE(die); 3456 } 3457 3458 if (decl_ctx) { 3459 LinkDeclContextToDIE(decl_ctx, die); 3460 return decl_ctx; 3461 } 3462 } 3463 return nullptr; 3464} 3465 3466OptionalClangModuleID 3467DWARFASTParserClang::GetOwningClangModule(const DWARFDIE &die) { 3468 if (!die.IsValid()) 3469 return {}; 3470 3471 for (DWARFDIE parent = die.GetParent(); parent.IsValid(); 3472 parent = parent.GetParent()) { 3473 const dw_tag_t tag = parent.Tag(); 3474 if (tag == DW_TAG_module) { 3475 DWARFDIE module_die = parent; 3476 auto it = m_die_to_module.find(module_die.GetDIE()); 3477 if (it != m_die_to_module.end()) 3478 return it->second; 3479 const char *name = 3480 module_die.GetAttributeValueAsString(DW_AT_name, nullptr); 3481 if (!name) 3482 return {}; 3483 3484 OptionalClangModuleID id = 3485 m_ast.GetOrCreateClangModule(name, GetOwningClangModule(module_die)); 3486 m_die_to_module.insert({module_die.GetDIE(), id}); 3487 return id; 3488 } 3489 } 3490 return {}; 3491} 3492 3493static bool IsSubroutine(const DWARFDIE &die) { 3494 switch (die.Tag()) { 3495 case DW_TAG_subprogram: 3496 case DW_TAG_inlined_subroutine: 3497 return true; 3498 default: 3499 return false; 3500 } 3501} 3502 3503static DWARFDIE GetContainingFunctionWithAbstractOrigin(const DWARFDIE &die) { 3504 for (DWARFDIE candidate = die; candidate; candidate = candidate.GetParent()) { 3505 if (IsSubroutine(candidate)) { 3506 if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) { 3507 return candidate; 3508 } else { 3509 return DWARFDIE(); 3510 } 3511 } 3512 } 3513 assert(0 && "Shouldn't call GetContainingFunctionWithAbstractOrigin on " 3514 "something not in a function"); 3515 return DWARFDIE(); 3516} 3517 3518static DWARFDIE FindAnyChildWithAbstractOrigin(const DWARFDIE &context) { 3519 for (DWARFDIE candidate : context.children()) { 3520 if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) { 3521 return candidate; 3522 } 3523 } 3524 return DWARFDIE(); 3525} 3526 3527static DWARFDIE FindFirstChildWithAbstractOrigin(const DWARFDIE &block, 3528 const DWARFDIE &function) { 3529 assert(IsSubroutine(function)); 3530 for (DWARFDIE context = block; context != function.GetParent(); 3531 context = context.GetParent()) { 3532 assert(!IsSubroutine(context) || context == function); 3533 if (DWARFDIE child = FindAnyChildWithAbstractOrigin(context)) { 3534 return child; 3535 } 3536 } 3537 return DWARFDIE(); 3538} 3539 3540clang::DeclContext * 3541DWARFASTParserClang::GetDeclContextForBlock(const DWARFDIE &die) { 3542 assert(die.Tag() == DW_TAG_lexical_block); 3543 DWARFDIE containing_function_with_abstract_origin = 3544 GetContainingFunctionWithAbstractOrigin(die); 3545 if (!containing_function_with_abstract_origin) { 3546 return (clang::DeclContext *)ResolveBlockDIE(die); 3547 } 3548 DWARFDIE child = FindFirstChildWithAbstractOrigin( 3549 die, containing_function_with_abstract_origin); 3550 CompilerDeclContext decl_context = 3551 GetDeclContextContainingUIDFromDWARF(child); 3552 return (clang::DeclContext *)decl_context.GetOpaqueDeclContext(); 3553} 3554 3555clang::BlockDecl *DWARFASTParserClang::ResolveBlockDIE(const DWARFDIE &die) { 3556 if (die && die.Tag() == DW_TAG_lexical_block) { 3557 clang::BlockDecl *decl = 3558 llvm::cast_or_null<clang::BlockDecl>(m_die_to_decl_ctx[die.GetDIE()]); 3559 3560 if (!decl) { 3561 DWARFDIE decl_context_die; 3562 clang::DeclContext *decl_context = 3563 GetClangDeclContextContainingDIE(die, &decl_context_die); 3564 decl = 3565 m_ast.CreateBlockDeclaration(decl_context, GetOwningClangModule(die)); 3566 3567 if (decl) 3568 LinkDeclContextToDIE((clang::DeclContext *)decl, die); 3569 } 3570 3571 return decl; 3572 } 3573 return nullptr; 3574} 3575 3576clang::NamespaceDecl * 3577DWARFASTParserClang::ResolveNamespaceDIE(const DWARFDIE &die) { 3578 if (die && die.Tag() == DW_TAG_namespace) { 3579 // See if we already parsed this namespace DIE and associated it with a 3580 // uniqued namespace declaration 3581 clang::NamespaceDecl *namespace_decl = 3582 static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die.GetDIE()]); 3583 if (namespace_decl) 3584 return namespace_decl; 3585 else { 3586 const char *namespace_name = die.GetName(); 3587 clang::DeclContext *containing_decl_ctx = 3588 GetClangDeclContextContainingDIE(die, nullptr); 3589 bool is_inline = 3590 die.GetAttributeValueAsUnsigned(DW_AT_export_symbols, 0) != 0; 3591 3592 namespace_decl = m_ast.GetUniqueNamespaceDeclaration( 3593 namespace_name, containing_decl_ctx, GetOwningClangModule(die), 3594 is_inline); 3595 3596 if (namespace_decl) 3597 LinkDeclContextToDIE((clang::DeclContext *)namespace_decl, die); 3598 return namespace_decl; 3599 } 3600 } 3601 return nullptr; 3602} 3603 3604clang::NamespaceDecl * 3605DWARFASTParserClang::ResolveImportedDeclarationDIE(const DWARFDIE &die) { 3606 assert(die && die.Tag() == DW_TAG_imported_declaration); 3607 3608 // See if we cached a NamespaceDecl for this imported declaration 3609 // already 3610 auto it = m_die_to_decl_ctx.find(die.GetDIE()); 3611 if (it != m_die_to_decl_ctx.end()) 3612 return static_cast<clang::NamespaceDecl *>(it->getSecond()); 3613 3614 clang::NamespaceDecl *namespace_decl = nullptr; 3615 3616 const DWARFDIE imported_uid = 3617 die.GetAttributeValueAsReferenceDIE(DW_AT_import); 3618 if (!imported_uid) 3619 return nullptr; 3620 3621 switch (imported_uid.Tag()) { 3622 case DW_TAG_imported_declaration: 3623 namespace_decl = ResolveImportedDeclarationDIE(imported_uid); 3624 break; 3625 case DW_TAG_namespace: 3626 namespace_decl = ResolveNamespaceDIE(imported_uid); 3627 break; 3628 default: 3629 return nullptr; 3630 } 3631 3632 if (!namespace_decl) 3633 return nullptr; 3634 3635 LinkDeclContextToDIE(namespace_decl, die); 3636 3637 return namespace_decl; 3638} 3639 3640clang::DeclContext *DWARFASTParserClang::GetClangDeclContextContainingDIE( 3641 const DWARFDIE &die, DWARFDIE *decl_ctx_die_copy) { 3642 SymbolFileDWARF *dwarf = die.GetDWARF(); 3643 3644 DWARFDIE decl_ctx_die = dwarf->GetDeclContextDIEContainingDIE(die); 3645 3646 if (decl_ctx_die_copy) 3647 *decl_ctx_die_copy = decl_ctx_die; 3648 3649 if (decl_ctx_die) { 3650 clang::DeclContext *clang_decl_ctx = 3651 GetClangDeclContextForDIE(decl_ctx_die); 3652 if (clang_decl_ctx) 3653 return clang_decl_ctx; 3654 } 3655 return m_ast.GetTranslationUnitDecl(); 3656} 3657 3658clang::DeclContext * 3659DWARFASTParserClang::GetCachedClangDeclContextForDIE(const DWARFDIE &die) { 3660 if (die) { 3661 DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find(die.GetDIE()); 3662 if (pos != m_die_to_decl_ctx.end()) 3663 return pos->second; 3664 } 3665 return nullptr; 3666} 3667 3668void DWARFASTParserClang::LinkDeclContextToDIE(clang::DeclContext *decl_ctx, 3669 const DWARFDIE &die) { 3670 m_die_to_decl_ctx[die.GetDIE()] = decl_ctx; 3671 // There can be many DIEs for a single decl context 3672 // m_decl_ctx_to_die[decl_ctx].insert(die.GetDIE()); 3673 m_decl_ctx_to_die.insert(std::make_pair(decl_ctx, die)); 3674} 3675 3676bool DWARFASTParserClang::CopyUniqueClassMethodTypes( 3677 const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die, 3678 lldb_private::Type *class_type, std::vector<DWARFDIE> &failures) { 3679 if (!class_type || !src_class_die || !dst_class_die) 3680 return false; 3681 if (src_class_die.Tag() != dst_class_die.Tag()) 3682 return false; 3683 3684 // We need to complete the class type so we can get all of the method types 3685 // parsed so we can then unique those types to their equivalent counterparts 3686 // in "dst_cu" and "dst_class_die" 3687 class_type->GetFullCompilerType(); 3688 3689 auto gather = [](DWARFDIE die, UniqueCStringMap<DWARFDIE> &map, 3690 UniqueCStringMap<DWARFDIE> &map_artificial) { 3691 if (die.Tag() != DW_TAG_subprogram) 3692 return; 3693 // Make sure this is a declaration and not a concrete instance by looking 3694 // for DW_AT_declaration set to 1. Sometimes concrete function instances are 3695 // placed inside the class definitions and shouldn't be included in the list 3696 // of things that are tracking here. 3697 if (die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) != 1) 3698 return; 3699 3700 if (const char *name = die.GetMangledName()) { 3701 ConstString const_name(name); 3702 if (die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0)) 3703 map_artificial.Append(const_name, die); 3704 else 3705 map.Append(const_name, die); 3706 } 3707 }; 3708 3709 UniqueCStringMap<DWARFDIE> src_name_to_die; 3710 UniqueCStringMap<DWARFDIE> dst_name_to_die; 3711 UniqueCStringMap<DWARFDIE> src_name_to_die_artificial; 3712 UniqueCStringMap<DWARFDIE> dst_name_to_die_artificial; 3713 for (DWARFDIE src_die = src_class_die.GetFirstChild(); src_die.IsValid(); 3714 src_die = src_die.GetSibling()) { 3715 gather(src_die, src_name_to_die, src_name_to_die_artificial); 3716 } 3717 for (DWARFDIE dst_die = dst_class_die.GetFirstChild(); dst_die.IsValid(); 3718 dst_die = dst_die.GetSibling()) { 3719 gather(dst_die, dst_name_to_die, dst_name_to_die_artificial); 3720 } 3721 const uint32_t src_size = src_name_to_die.GetSize(); 3722 const uint32_t dst_size = dst_name_to_die.GetSize(); 3723 3724 // Is everything kosher so we can go through the members at top speed? 3725 bool fast_path = true; 3726 3727 if (src_size != dst_size) 3728 fast_path = false; 3729 3730 uint32_t idx; 3731 3732 if (fast_path) { 3733 for (idx = 0; idx < src_size; ++idx) { 3734 DWARFDIE src_die = src_name_to_die.GetValueAtIndexUnchecked(idx); 3735 DWARFDIE dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx); 3736 3737 if (src_die.Tag() != dst_die.Tag()) 3738 fast_path = false; 3739 3740 const char *src_name = src_die.GetMangledName(); 3741 const char *dst_name = dst_die.GetMangledName(); 3742 3743 // Make sure the names match 3744 if (src_name == dst_name || (strcmp(src_name, dst_name) == 0)) 3745 continue; 3746 3747 fast_path = false; 3748 } 3749 } 3750 3751 DWARFASTParserClang *src_dwarf_ast_parser = 3752 static_cast<DWARFASTParserClang *>( 3753 SymbolFileDWARF::GetDWARFParser(*src_class_die.GetCU())); 3754 DWARFASTParserClang *dst_dwarf_ast_parser = 3755 static_cast<DWARFASTParserClang *>( 3756 SymbolFileDWARF::GetDWARFParser(*dst_class_die.GetCU())); 3757 auto link = [&](DWARFDIE src, DWARFDIE dst) { 3758 SymbolFileDWARF::DIEToTypePtr &die_to_type = 3759 dst_class_die.GetDWARF()->GetDIEToType(); 3760 clang::DeclContext *dst_decl_ctx = 3761 dst_dwarf_ast_parser->m_die_to_decl_ctx[dst.GetDIE()]; 3762 if (dst_decl_ctx) 3763 src_dwarf_ast_parser->LinkDeclContextToDIE(dst_decl_ctx, src); 3764 3765 if (Type *src_child_type = die_to_type[src.GetDIE()]) 3766 die_to_type[dst.GetDIE()] = src_child_type; 3767 }; 3768 3769 // Now do the work of linking the DeclContexts and Types. 3770 if (fast_path) { 3771 // We can do this quickly. Just run across the tables index-for-index 3772 // since we know each node has matching names and tags. 3773 for (idx = 0; idx < src_size; ++idx) { 3774 link(src_name_to_die.GetValueAtIndexUnchecked(idx), 3775 dst_name_to_die.GetValueAtIndexUnchecked(idx)); 3776 } 3777 } else { 3778 // We must do this slowly. For each member of the destination, look up a 3779 // member in the source with the same name, check its tag, and unique them 3780 // if everything matches up. Report failures. 3781 3782 if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty()) { 3783 src_name_to_die.Sort(); 3784 3785 for (idx = 0; idx < dst_size; ++idx) { 3786 ConstString dst_name = dst_name_to_die.GetCStringAtIndex(idx); 3787 DWARFDIE dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx); 3788 DWARFDIE src_die = src_name_to_die.Find(dst_name, DWARFDIE()); 3789 3790 if (src_die && (src_die.Tag() == dst_die.Tag())) 3791 link(src_die, dst_die); 3792 else 3793 failures.push_back(dst_die); 3794 } 3795 } 3796 } 3797 3798 const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize(); 3799 const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize(); 3800 3801 if (src_size_artificial && dst_size_artificial) { 3802 dst_name_to_die_artificial.Sort(); 3803 3804 for (idx = 0; idx < src_size_artificial; ++idx) { 3805 ConstString src_name_artificial = 3806 src_name_to_die_artificial.GetCStringAtIndex(idx); 3807 DWARFDIE src_die = 3808 src_name_to_die_artificial.GetValueAtIndexUnchecked(idx); 3809 DWARFDIE dst_die = 3810 dst_name_to_die_artificial.Find(src_name_artificial, DWARFDIE()); 3811 3812 // Both classes have the artificial types, link them 3813 if (dst_die) 3814 link(src_die, dst_die); 3815 } 3816 } 3817 3818 if (dst_size_artificial) { 3819 for (idx = 0; idx < dst_size_artificial; ++idx) { 3820 failures.push_back( 3821 dst_name_to_die_artificial.GetValueAtIndexUnchecked(idx)); 3822 } 3823 } 3824 3825 return !failures.empty(); 3826} 3827 3828bool DWARFASTParserClang::ShouldCreateUnnamedBitfield( 3829 FieldInfo const &last_field_info, uint64_t last_field_end, 3830 FieldInfo const &this_field_info, 3831 lldb_private::ClangASTImporter::LayoutInfo const &layout_info) const { 3832 // If we have a gap between the last_field_end and the current 3833 // field we have an unnamed bit-field. 3834 if (this_field_info.bit_offset <= last_field_end) 3835 return false; 3836 3837 // If we have a base class, we assume there is no unnamed 3838 // bit-field if either of the following is true: 3839 // (a) this is the first field since the gap can be 3840 // attributed to the members from the base class. 3841 // FIXME: This assumption is not correct if the first field of 3842 // the derived class is indeed an unnamed bit-field. We currently 3843 // do not have the machinary to track the offset of the last field 3844 // of classes we have seen before, so we are not handling this case. 3845 // (b) Or, the first member of the derived class was a vtable pointer. 3846 // In this case we don't want to create an unnamed bitfield either 3847 // since those will be inserted by clang later. 3848 const bool have_base = layout_info.base_offsets.size() != 0; 3849 const bool this_is_first_field = 3850 last_field_info.bit_offset == 0 && last_field_info.bit_size == 0; 3851 const bool first_field_is_vptr = 3852 last_field_info.bit_offset == 0 && last_field_info.IsArtificial(); 3853 3854 if (have_base && (this_is_first_field || first_field_is_vptr)) 3855 return false; 3856 3857 return true; 3858} 3859 3860void DWARFASTParserClang::ParseRustVariantPart( 3861 DWARFDIE &die, const DWARFDIE &parent_die, CompilerType &class_clang_type, 3862 const lldb::AccessType default_accesibility, 3863 ClangASTImporter::LayoutInfo &layout_info) { 3864 assert(die.Tag() == llvm::dwarf::DW_TAG_variant_part); 3865 assert(SymbolFileDWARF::GetLanguage(*die.GetCU()) == 3866 LanguageType::eLanguageTypeRust); 3867 3868 ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule(); 3869 3870 VariantPart variants(die, parent_die, module_sp); 3871 3872 auto discriminant_type = 3873 die.ResolveTypeUID(variants.discriminant().type_ref.Reference()); 3874 3875 auto decl_context = m_ast.GetDeclContextForType(class_clang_type); 3876 3877 auto inner_holder = m_ast.CreateRecordType( 3878 decl_context, OptionalClangModuleID(), lldb::eAccessPublic, 3879 std::string( 3880 llvm::formatv("{0}$Inner", class_clang_type.GetTypeName(false))), 3881 llvm::to_underlying(clang::TagTypeKind::Union), lldb::eLanguageTypeRust); 3882 m_ast.StartTagDeclarationDefinition(inner_holder); 3883 m_ast.SetIsPacked(inner_holder); 3884 3885 for (auto member : variants.members()) { 3886 3887 auto has_discriminant = !member.IsDefault(); 3888 3889 auto member_type = die.ResolveTypeUID(member.type_ref.Reference()); 3890 3891 auto field_type = m_ast.CreateRecordType( 3892 m_ast.GetDeclContextForType(inner_holder), OptionalClangModuleID(), 3893 lldb::eAccessPublic, 3894 std::string(llvm::formatv("{0}$Variant", member.GetName())), 3895 llvm::to_underlying(clang::TagTypeKind::Struct), 3896 lldb::eLanguageTypeRust); 3897 3898 m_ast.StartTagDeclarationDefinition(field_type); 3899 auto offset = member.byte_offset; 3900 3901 if (has_discriminant) { 3902 m_ast.AddFieldToRecordType( 3903 field_type, "$discr$", discriminant_type->GetFullCompilerType(), 3904 lldb::eAccessPublic, variants.discriminant().byte_offset); 3905 offset += discriminant_type->GetByteSize(nullptr).value_or(0); 3906 } 3907 3908 m_ast.AddFieldToRecordType(field_type, "value", 3909 member_type->GetFullCompilerType(), 3910 lldb::eAccessPublic, offset * 8); 3911 3912 m_ast.CompleteTagDeclarationDefinition(field_type); 3913 3914 auto name = has_discriminant 3915 ? llvm::formatv("$variant${0}", member.discr_value.value()) 3916 : std::string("$variant$"); 3917 3918 auto variant_decl = 3919 m_ast.AddFieldToRecordType(inner_holder, llvm::StringRef(name), 3920 field_type, default_accesibility, 0); 3921 3922 layout_info.field_offsets.insert({variant_decl, 0}); 3923 } 3924 3925 auto inner_field = m_ast.AddFieldToRecordType(class_clang_type, 3926 llvm::StringRef("$variants$"), 3927 inner_holder, eAccessPublic, 0); 3928 3929 m_ast.CompleteTagDeclarationDefinition(inner_holder); 3930 3931 layout_info.field_offsets.insert({inner_field, 0}); 3932} 3933