1 //===-- TypeSystemClang.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 "TypeSystemClang.h" 10 11 #include "clang/AST/DeclBase.h" 12 #include "llvm/Support/Casting.h" 13 #include "llvm/Support/FormatAdapters.h" 14 #include "llvm/Support/FormatVariadic.h" 15 16 #include <mutex> 17 #include <memory> 18 #include <string> 19 #include <vector> 20 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/ASTImporter.h" 23 #include "clang/AST/Attr.h" 24 #include "clang/AST/CXXInheritance.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/AST/DeclTemplate.h" 27 #include "clang/AST/Mangle.h" 28 #include "clang/AST/RecordLayout.h" 29 #include "clang/AST/Type.h" 30 #include "clang/AST/VTableBuilder.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/Diagnostic.h" 33 #include "clang/Basic/FileManager.h" 34 #include "clang/Basic/FileSystemOptions.h" 35 #include "clang/Basic/LangStandard.h" 36 #include "clang/Basic/SourceManager.h" 37 #include "clang/Basic/TargetInfo.h" 38 #include "clang/Basic/TargetOptions.h" 39 #include "clang/Frontend/FrontendOptions.h" 40 #include "clang/Lex/HeaderSearch.h" 41 #include "clang/Lex/HeaderSearchOptions.h" 42 #include "clang/Lex/ModuleMap.h" 43 #include "clang/Sema/Sema.h" 44 45 #include "llvm/Support/Signals.h" 46 #include "llvm/Support/Threading.h" 47 48 #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h" 49 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h" 50 #include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h" 51 #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h" 52 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" 53 #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h" 54 #include "Plugins/ExpressionParser/Clang/ClangUtil.h" 55 #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h" 56 #include "lldb/Core/DumpDataExtractor.h" 57 #include "lldb/Core/Module.h" 58 #include "lldb/Core/PluginManager.h" 59 #include "lldb/Core/StreamFile.h" 60 #include "lldb/Core/UniqueCStringMap.h" 61 #include "lldb/Symbol/ObjectFile.h" 62 #include "lldb/Symbol/SymbolFile.h" 63 #include "lldb/Target/ExecutionContext.h" 64 #include "lldb/Target/Language.h" 65 #include "lldb/Target/Process.h" 66 #include "lldb/Target/Target.h" 67 #include "lldb/Utility/ArchSpec.h" 68 #include "lldb/Utility/DataExtractor.h" 69 #include "lldb/Utility/Flags.h" 70 #include "lldb/Utility/LLDBAssert.h" 71 #include "lldb/Utility/LLDBLog.h" 72 #include "lldb/Utility/RegularExpression.h" 73 #include "lldb/Utility/Scalar.h" 74 #include "lldb/Utility/ThreadSafeDenseMap.h" 75 76 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h" 77 #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h" 78 #include "Plugins/SymbolFile/PDB/PDBASTParser.h" 79 #include "Plugins/SymbolFile/NativePDB/PdbAstBuilder.h" 80 81 #include <cstdio> 82 83 #include <mutex> 84 #include <optional> 85 86 using namespace lldb; 87 using namespace lldb_private; 88 using namespace lldb_private::dwarf; 89 using namespace clang; 90 using llvm::StringSwitch; 91 92 LLDB_PLUGIN_DEFINE(TypeSystemClang) 93 94 namespace { 95 static void VerifyDecl(clang::Decl *decl) { 96 assert(decl && "VerifyDecl called with nullptr?"); 97 #ifndef NDEBUG 98 // We don't care about the actual access value here but only want to trigger 99 // that Clang calls its internal Decl::AccessDeclContextCheck validation. 100 decl->getAccess(); 101 #endif 102 } 103 104 static inline bool 105 TypeSystemClangSupportsLanguage(lldb::LanguageType language) { 106 return language == eLanguageTypeUnknown || // Clang is the default type system 107 lldb_private::Language::LanguageIsC(language) || 108 lldb_private::Language::LanguageIsCPlusPlus(language) || 109 lldb_private::Language::LanguageIsObjC(language) || 110 lldb_private::Language::LanguageIsPascal(language) || 111 // Use Clang for Rust until there is a proper language plugin for it 112 language == eLanguageTypeRust || 113 // Use Clang for D until there is a proper language plugin for it 114 language == eLanguageTypeD || 115 // Open Dylan compiler debug info is designed to be Clang-compatible 116 language == eLanguageTypeDylan; 117 } 118 119 // Checks whether m1 is an overload of m2 (as opposed to an override). This is 120 // called by addOverridesForMethod to distinguish overrides (which share a 121 // vtable entry) from overloads (which require distinct entries). 122 bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) { 123 // FIXME: This should detect covariant return types, but currently doesn't. 124 lldbassert(&m1->getASTContext() == &m2->getASTContext() && 125 "Methods should have the same AST context"); 126 clang::ASTContext &context = m1->getASTContext(); 127 128 const auto *m1Type = llvm::cast<clang::FunctionProtoType>( 129 context.getCanonicalType(m1->getType())); 130 131 const auto *m2Type = llvm::cast<clang::FunctionProtoType>( 132 context.getCanonicalType(m2->getType())); 133 134 auto compareArgTypes = [&context](const clang::QualType &m1p, 135 const clang::QualType &m2p) { 136 return context.hasSameType(m1p.getUnqualifiedType(), 137 m2p.getUnqualifiedType()); 138 }; 139 140 // FIXME: In C++14 and later, we can just pass m2Type->param_type_end() 141 // as a fourth parameter to std::equal(). 142 return (m1->getNumParams() != m2->getNumParams()) || 143 !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(), 144 m2Type->param_type_begin(), compareArgTypes); 145 } 146 147 // If decl is a virtual method, walk the base classes looking for methods that 148 // decl overrides. This table of overridden methods is used by IRGen to 149 // determine the vtable layout for decl's parent class. 150 void addOverridesForMethod(clang::CXXMethodDecl *decl) { 151 if (!decl->isVirtual()) 152 return; 153 154 clang::CXXBasePaths paths; 155 llvm::SmallVector<clang::NamedDecl *, 4> decls; 156 157 auto find_overridden_methods = 158 [&decls, decl](const clang::CXXBaseSpecifier *specifier, 159 clang::CXXBasePath &path) { 160 if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>( 161 specifier->getType()->castAs<clang::RecordType>()->getDecl())) { 162 163 clang::DeclarationName name = decl->getDeclName(); 164 165 // If this is a destructor, check whether the base class destructor is 166 // virtual. 167 if (name.getNameKind() == clang::DeclarationName::CXXDestructorName) 168 if (auto *baseDtorDecl = base_record->getDestructor()) { 169 if (baseDtorDecl->isVirtual()) { 170 decls.push_back(baseDtorDecl); 171 return true; 172 } else 173 return false; 174 } 175 176 // Otherwise, search for name in the base class. 177 for (path.Decls = base_record->lookup(name).begin(); 178 path.Decls != path.Decls.end(); ++path.Decls) { 179 if (auto *method_decl = 180 llvm::dyn_cast<clang::CXXMethodDecl>(*path.Decls)) 181 if (method_decl->isVirtual() && !isOverload(decl, method_decl)) { 182 decls.push_back(method_decl); 183 return true; 184 } 185 } 186 } 187 188 return false; 189 }; 190 191 if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) { 192 for (auto *overridden_decl : decls) 193 decl->addOverriddenMethod( 194 llvm::cast<clang::CXXMethodDecl>(overridden_decl)); 195 } 196 } 197 } 198 199 static lldb::addr_t GetVTableAddress(Process &process, 200 VTableContextBase &vtable_ctx, 201 ValueObject &valobj, 202 const ASTRecordLayout &record_layout) { 203 // Retrieve type info 204 CompilerType pointee_type; 205 CompilerType this_type(valobj.GetCompilerType()); 206 uint32_t type_info = this_type.GetTypeInfo(&pointee_type); 207 if (!type_info) 208 return LLDB_INVALID_ADDRESS; 209 210 // Check if it's a pointer or reference 211 bool ptr_or_ref = false; 212 if (type_info & (eTypeIsPointer | eTypeIsReference)) { 213 ptr_or_ref = true; 214 type_info = pointee_type.GetTypeInfo(); 215 } 216 217 // We process only C++ classes 218 const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus; 219 if ((type_info & cpp_class) != cpp_class) 220 return LLDB_INVALID_ADDRESS; 221 222 // Calculate offset to VTable pointer 223 lldb::offset_t vbtable_ptr_offset = 224 vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity() 225 : 0; 226 227 if (ptr_or_ref) { 228 // We have a pointer / ref to object, so read 229 // VTable pointer from process memory 230 231 if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad) 232 return LLDB_INVALID_ADDRESS; 233 234 auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS); 235 if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS) 236 return LLDB_INVALID_ADDRESS; 237 238 vbtable_ptr_addr += vbtable_ptr_offset; 239 240 Status err; 241 return process.ReadPointerFromMemory(vbtable_ptr_addr, err); 242 } 243 244 // We have an object already read from process memory, 245 // so just extract VTable pointer from it 246 247 DataExtractor data; 248 Status err; 249 auto size = valobj.GetData(data, err); 250 if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size) 251 return LLDB_INVALID_ADDRESS; 252 253 return data.GetAddress(&vbtable_ptr_offset); 254 } 255 256 static int64_t ReadVBaseOffsetFromVTable(Process &process, 257 VTableContextBase &vtable_ctx, 258 lldb::addr_t vtable_ptr, 259 const CXXRecordDecl *cxx_record_decl, 260 const CXXRecordDecl *base_class_decl) { 261 if (vtable_ctx.isMicrosoft()) { 262 clang::MicrosoftVTableContext &msoft_vtable_ctx = 263 static_cast<clang::MicrosoftVTableContext &>(vtable_ctx); 264 265 // Get the index into the virtual base table. The 266 // index is the index in uint32_t from vbtable_ptr 267 const unsigned vbtable_index = 268 msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl); 269 const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4; 270 Status err; 271 return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX, 272 err); 273 } 274 275 clang::ItaniumVTableContext &itanium_vtable_ctx = 276 static_cast<clang::ItaniumVTableContext &>(vtable_ctx); 277 278 clang::CharUnits base_offset_offset = 279 itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl, 280 base_class_decl); 281 const lldb::addr_t base_offset_addr = 282 vtable_ptr + base_offset_offset.getQuantity(); 283 const uint32_t base_offset_size = process.GetAddressByteSize(); 284 Status err; 285 return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size, 286 INT64_MAX, err); 287 } 288 289 static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx, 290 ValueObject &valobj, 291 const ASTRecordLayout &record_layout, 292 const CXXRecordDecl *cxx_record_decl, 293 const CXXRecordDecl *base_class_decl, 294 int32_t &bit_offset) { 295 ExecutionContext exe_ctx(valobj.GetExecutionContextRef()); 296 Process *process = exe_ctx.GetProcessPtr(); 297 if (!process) 298 return false; 299 300 lldb::addr_t vtable_ptr = 301 GetVTableAddress(*process, vtable_ctx, valobj, record_layout); 302 if (vtable_ptr == LLDB_INVALID_ADDRESS) 303 return false; 304 305 auto base_offset = ReadVBaseOffsetFromVTable( 306 *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl); 307 if (base_offset == INT64_MAX) 308 return false; 309 310 bit_offset = base_offset * 8; 311 312 return true; 313 } 314 315 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, TypeSystemClang *> 316 ClangASTMap; 317 318 static ClangASTMap &GetASTMap() { 319 static ClangASTMap *g_map_ptr = nullptr; 320 static llvm::once_flag g_once_flag; 321 llvm::call_once(g_once_flag, []() { 322 g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins 323 }); 324 return *g_map_ptr; 325 } 326 327 TypePayloadClang::TypePayloadClang(OptionalClangModuleID owning_module, 328 bool is_complete_objc_class) 329 : m_payload(owning_module.GetValue()) { 330 SetIsCompleteObjCClass(is_complete_objc_class); 331 } 332 333 void TypePayloadClang::SetOwningModule(OptionalClangModuleID id) { 334 assert(id.GetValue() < ObjCClassBit); 335 bool is_complete = IsCompleteObjCClass(); 336 m_payload = id.GetValue(); 337 SetIsCompleteObjCClass(is_complete); 338 } 339 340 static void SetMemberOwningModule(clang::Decl *member, 341 const clang::Decl *parent) { 342 if (!member || !parent) 343 return; 344 345 OptionalClangModuleID id(parent->getOwningModuleID()); 346 if (!id.HasValue()) 347 return; 348 349 member->setFromASTFile(); 350 member->setOwningModuleID(id.GetValue()); 351 member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible); 352 if (llvm::isa<clang::NamedDecl>(member)) 353 if (auto *dc = llvm::dyn_cast<clang::DeclContext>(parent)) { 354 dc->setHasExternalVisibleStorage(true); 355 // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be 356 // called when searching for members. 357 dc->setHasExternalLexicalStorage(true); 358 } 359 } 360 361 char TypeSystemClang::ID; 362 363 bool TypeSystemClang::IsOperator(llvm::StringRef name, 364 clang::OverloadedOperatorKind &op_kind) { 365 // All operators have to start with "operator". 366 if (!name.consume_front("operator")) 367 return false; 368 369 // Remember if there was a space after "operator". This is necessary to 370 // check for collisions with strangely named functions like "operatorint()". 371 bool space_after_operator = name.consume_front(" "); 372 373 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name) 374 .Case("+", clang::OO_Plus) 375 .Case("+=", clang::OO_PlusEqual) 376 .Case("++", clang::OO_PlusPlus) 377 .Case("-", clang::OO_Minus) 378 .Case("-=", clang::OO_MinusEqual) 379 .Case("--", clang::OO_MinusMinus) 380 .Case("->", clang::OO_Arrow) 381 .Case("->*", clang::OO_ArrowStar) 382 .Case("*", clang::OO_Star) 383 .Case("*=", clang::OO_StarEqual) 384 .Case("/", clang::OO_Slash) 385 .Case("/=", clang::OO_SlashEqual) 386 .Case("%", clang::OO_Percent) 387 .Case("%=", clang::OO_PercentEqual) 388 .Case("^", clang::OO_Caret) 389 .Case("^=", clang::OO_CaretEqual) 390 .Case("&", clang::OO_Amp) 391 .Case("&=", clang::OO_AmpEqual) 392 .Case("&&", clang::OO_AmpAmp) 393 .Case("|", clang::OO_Pipe) 394 .Case("|=", clang::OO_PipeEqual) 395 .Case("||", clang::OO_PipePipe) 396 .Case("~", clang::OO_Tilde) 397 .Case("!", clang::OO_Exclaim) 398 .Case("!=", clang::OO_ExclaimEqual) 399 .Case("=", clang::OO_Equal) 400 .Case("==", clang::OO_EqualEqual) 401 .Case("<", clang::OO_Less) 402 .Case("<=>", clang::OO_Spaceship) 403 .Case("<<", clang::OO_LessLess) 404 .Case("<<=", clang::OO_LessLessEqual) 405 .Case("<=", clang::OO_LessEqual) 406 .Case(">", clang::OO_Greater) 407 .Case(">>", clang::OO_GreaterGreater) 408 .Case(">>=", clang::OO_GreaterGreaterEqual) 409 .Case(">=", clang::OO_GreaterEqual) 410 .Case("()", clang::OO_Call) 411 .Case("[]", clang::OO_Subscript) 412 .Case(",", clang::OO_Comma) 413 .Default(clang::NUM_OVERLOADED_OPERATORS); 414 415 // We found a fitting operator, so we can exit now. 416 if (op_kind != clang::NUM_OVERLOADED_OPERATORS) 417 return true; 418 419 // After the "operator " or "operator" part is something unknown. This means 420 // it's either one of the named operators (new/delete), a conversion operator 421 // (e.g. operator bool) or a function which name starts with "operator" 422 // (e.g. void operatorbool). 423 424 // If it's a function that starts with operator it can't have a space after 425 // "operator" because identifiers can't contain spaces. 426 // E.g. "operator int" (conversion operator) 427 // vs. "operatorint" (function with colliding name). 428 if (!space_after_operator) 429 return false; // not an operator. 430 431 // Now the operator is either one of the named operators or a conversion 432 // operator. 433 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name) 434 .Case("new", clang::OO_New) 435 .Case("new[]", clang::OO_Array_New) 436 .Case("delete", clang::OO_Delete) 437 .Case("delete[]", clang::OO_Array_Delete) 438 // conversion operators hit this case. 439 .Default(clang::NUM_OVERLOADED_OPERATORS); 440 441 return true; 442 } 443 444 clang::AccessSpecifier 445 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(AccessType access) { 446 switch (access) { 447 default: 448 break; 449 case eAccessNone: 450 return AS_none; 451 case eAccessPublic: 452 return AS_public; 453 case eAccessPrivate: 454 return AS_private; 455 case eAccessProtected: 456 return AS_protected; 457 } 458 return AS_none; 459 } 460 461 static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) { 462 // FIXME: Cleanup per-file based stuff. 463 464 // Set some properties which depend solely on the input kind; it would be 465 // nice to move these to the language standard, and have the driver resolve 466 // the input kind + language standard. 467 if (IK.getLanguage() == clang::Language::Asm) { 468 Opts.AsmPreprocessor = 1; 469 } else if (IK.isObjectiveC()) { 470 Opts.ObjC = 1; 471 } 472 473 LangStandard::Kind LangStd = LangStandard::lang_unspecified; 474 475 if (LangStd == LangStandard::lang_unspecified) { 476 // Based on the base language, pick one. 477 switch (IK.getLanguage()) { 478 case clang::Language::Unknown: 479 case clang::Language::LLVM_IR: 480 case clang::Language::RenderScript: 481 llvm_unreachable("Invalid input kind!"); 482 case clang::Language::OpenCL: 483 LangStd = LangStandard::lang_opencl10; 484 break; 485 case clang::Language::OpenCLCXX: 486 LangStd = LangStandard::lang_openclcpp10; 487 break; 488 case clang::Language::Asm: 489 case clang::Language::C: 490 case clang::Language::ObjC: 491 LangStd = LangStandard::lang_gnu99; 492 break; 493 case clang::Language::CXX: 494 case clang::Language::ObjCXX: 495 LangStd = LangStandard::lang_gnucxx98; 496 break; 497 case clang::Language::CUDA: 498 case clang::Language::HIP: 499 LangStd = LangStandard::lang_gnucxx17; 500 break; 501 case clang::Language::HLSL: 502 LangStd = LangStandard::lang_hlsl; 503 break; 504 } 505 } 506 507 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 508 Opts.LineComment = Std.hasLineComments(); 509 Opts.C99 = Std.isC99(); 510 Opts.CPlusPlus = Std.isCPlusPlus(); 511 Opts.CPlusPlus11 = Std.isCPlusPlus11(); 512 Opts.CPlusPlus14 = Std.isCPlusPlus14(); 513 Opts.CPlusPlus17 = Std.isCPlusPlus17(); 514 Opts.CPlusPlus20 = Std.isCPlusPlus20(); 515 Opts.Digraphs = Std.hasDigraphs(); 516 Opts.GNUMode = Std.isGNUMode(); 517 Opts.GNUInline = !Std.isC99(); 518 Opts.HexFloats = Std.hasHexFloats(); 519 520 Opts.WChar = true; 521 522 // OpenCL has some additional defaults. 523 if (LangStd == LangStandard::lang_opencl10) { 524 Opts.OpenCL = 1; 525 Opts.AltiVec = 1; 526 Opts.CXXOperatorNames = 1; 527 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::All); 528 } 529 530 // OpenCL and C++ both have bool, true, false keywords. 531 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; 532 533 Opts.setValueVisibilityMode(DefaultVisibility); 534 535 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is 536 // specified, or -std is set to a conforming mode. 537 Opts.Trigraphs = !Opts.GNUMode; 538 Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault(); 539 Opts.OptimizeSize = 0; 540 541 // FIXME: Eliminate this dependency. 542 // unsigned Opt = 543 // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags); 544 // Opts.Optimize = Opt != 0; 545 unsigned Opt = 0; 546 547 // This is the __NO_INLINE__ define, which just depends on things like the 548 // optimization level and -fno-inline, not actually whether the backend has 549 // inlining enabled. 550 // 551 // FIXME: This is affected by other options (-fno-inline). 552 Opts.NoInlineDefine = !Opt; 553 554 // This is needed to allocate the extra space for the owning module 555 // on each decl. 556 Opts.ModulesLocalVisibility = 1; 557 } 558 559 TypeSystemClang::TypeSystemClang(llvm::StringRef name, 560 llvm::Triple target_triple) { 561 m_display_name = name.str(); 562 if (!target_triple.str().empty()) 563 SetTargetTriple(target_triple.str()); 564 // The caller didn't pass an ASTContext so create a new one for this 565 // TypeSystemClang. 566 CreateASTContext(); 567 } 568 569 TypeSystemClang::TypeSystemClang(llvm::StringRef name, 570 ASTContext &existing_ctxt) { 571 m_display_name = name.str(); 572 SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str()); 573 574 m_ast_up.reset(&existing_ctxt); 575 GetASTMap().Insert(&existing_ctxt, this); 576 } 577 578 // Destructor 579 TypeSystemClang::~TypeSystemClang() { Finalize(); } 580 581 lldb::TypeSystemSP TypeSystemClang::CreateInstance(lldb::LanguageType language, 582 lldb_private::Module *module, 583 Target *target) { 584 if (!TypeSystemClangSupportsLanguage(language)) 585 return lldb::TypeSystemSP(); 586 ArchSpec arch; 587 if (module) 588 arch = module->GetArchitecture(); 589 else if (target) 590 arch = target->GetArchitecture(); 591 592 if (!arch.IsValid()) 593 return lldb::TypeSystemSP(); 594 595 llvm::Triple triple = arch.GetTriple(); 596 // LLVM wants this to be set to iOS or MacOSX; if we're working on 597 // a bare-boards type image, change the triple for llvm's benefit. 598 if (triple.getVendor() == llvm::Triple::Apple && 599 triple.getOS() == llvm::Triple::UnknownOS) { 600 if (triple.getArch() == llvm::Triple::arm || 601 triple.getArch() == llvm::Triple::aarch64 || 602 triple.getArch() == llvm::Triple::aarch64_32 || 603 triple.getArch() == llvm::Triple::thumb) { 604 triple.setOS(llvm::Triple::IOS); 605 } else { 606 triple.setOS(llvm::Triple::MacOSX); 607 } 608 } 609 610 if (module) { 611 std::string ast_name = 612 "ASTContext for '" + module->GetFileSpec().GetPath() + "'"; 613 return std::make_shared<TypeSystemClang>(ast_name, triple); 614 } else if (target && target->IsValid()) 615 return std::make_shared<ScratchTypeSystemClang>(*target, triple); 616 return lldb::TypeSystemSP(); 617 } 618 619 LanguageSet TypeSystemClang::GetSupportedLanguagesForTypes() { 620 LanguageSet languages; 621 languages.Insert(lldb::eLanguageTypeC89); 622 languages.Insert(lldb::eLanguageTypeC); 623 languages.Insert(lldb::eLanguageTypeC11); 624 languages.Insert(lldb::eLanguageTypeC_plus_plus); 625 languages.Insert(lldb::eLanguageTypeC99); 626 languages.Insert(lldb::eLanguageTypeObjC); 627 languages.Insert(lldb::eLanguageTypeObjC_plus_plus); 628 languages.Insert(lldb::eLanguageTypeC_plus_plus_03); 629 languages.Insert(lldb::eLanguageTypeC_plus_plus_11); 630 languages.Insert(lldb::eLanguageTypeC11); 631 languages.Insert(lldb::eLanguageTypeC_plus_plus_14); 632 languages.Insert(lldb::eLanguageTypeC_plus_plus_17); 633 languages.Insert(lldb::eLanguageTypeC_plus_plus_20); 634 return languages; 635 } 636 637 LanguageSet TypeSystemClang::GetSupportedLanguagesForExpressions() { 638 LanguageSet languages; 639 languages.Insert(lldb::eLanguageTypeC_plus_plus); 640 languages.Insert(lldb::eLanguageTypeObjC_plus_plus); 641 languages.Insert(lldb::eLanguageTypeC_plus_plus_03); 642 languages.Insert(lldb::eLanguageTypeC_plus_plus_11); 643 languages.Insert(lldb::eLanguageTypeC_plus_plus_14); 644 languages.Insert(lldb::eLanguageTypeC_plus_plus_17); 645 languages.Insert(lldb::eLanguageTypeC_plus_plus_20); 646 return languages; 647 } 648 649 void TypeSystemClang::Initialize() { 650 PluginManager::RegisterPlugin( 651 GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance, 652 GetSupportedLanguagesForTypes(), GetSupportedLanguagesForExpressions()); 653 } 654 655 void TypeSystemClang::Terminate() { 656 PluginManager::UnregisterPlugin(CreateInstance); 657 } 658 659 void TypeSystemClang::Finalize() { 660 assert(m_ast_up); 661 GetASTMap().Erase(m_ast_up.get()); 662 if (!m_ast_owned) 663 m_ast_up.release(); 664 665 m_builtins_up.reset(); 666 m_selector_table_up.reset(); 667 m_identifier_table_up.reset(); 668 m_target_info_up.reset(); 669 m_target_options_rp.reset(); 670 m_diagnostics_engine_up.reset(); 671 m_source_manager_up.reset(); 672 m_language_options_up.reset(); 673 } 674 675 void TypeSystemClang::setSema(Sema *s) { 676 // Ensure that the new sema actually belongs to our ASTContext. 677 assert(s == nullptr || &s->getASTContext() == m_ast_up.get()); 678 m_sema = s; 679 } 680 681 const char *TypeSystemClang::GetTargetTriple() { 682 return m_target_triple.c_str(); 683 } 684 685 void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) { 686 m_target_triple = target_triple.str(); 687 } 688 689 void TypeSystemClang::SetExternalSource( 690 llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) { 691 ASTContext &ast = getASTContext(); 692 ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true); 693 ast.setExternalSource(ast_source_up); 694 } 695 696 ASTContext &TypeSystemClang::getASTContext() { 697 assert(m_ast_up); 698 return *m_ast_up; 699 } 700 701 class NullDiagnosticConsumer : public DiagnosticConsumer { 702 public: 703 NullDiagnosticConsumer() { m_log = GetLog(LLDBLog::Expressions); } 704 705 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 706 const clang::Diagnostic &info) override { 707 if (m_log) { 708 llvm::SmallVector<char, 32> diag_str(10); 709 info.FormatDiagnostic(diag_str); 710 diag_str.push_back('\0'); 711 LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data()); 712 } 713 } 714 715 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const { 716 return new NullDiagnosticConsumer(); 717 } 718 719 private: 720 Log *m_log; 721 }; 722 723 void TypeSystemClang::CreateASTContext() { 724 assert(!m_ast_up); 725 m_ast_owned = true; 726 727 m_language_options_up = std::make_unique<LangOptions>(); 728 ParseLangArgs(*m_language_options_up, clang::Language::ObjCXX, 729 GetTargetTriple()); 730 731 m_identifier_table_up = 732 std::make_unique<IdentifierTable>(*m_language_options_up, nullptr); 733 m_builtins_up = std::make_unique<Builtin::Context>(); 734 735 m_selector_table_up = std::make_unique<SelectorTable>(); 736 737 clang::FileSystemOptions file_system_options; 738 m_file_manager_up = std::make_unique<clang::FileManager>( 739 file_system_options, FileSystem::Instance().GetVirtualFileSystem()); 740 741 llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs()); 742 m_diagnostics_engine_up = 743 std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions()); 744 745 m_source_manager_up = std::make_unique<clang::SourceManager>( 746 *m_diagnostics_engine_up, *m_file_manager_up); 747 m_ast_up = std::make_unique<ASTContext>( 748 *m_language_options_up, *m_source_manager_up, *m_identifier_table_up, 749 *m_selector_table_up, *m_builtins_up, TU_Complete); 750 751 m_diagnostic_consumer_up = std::make_unique<NullDiagnosticConsumer>(); 752 m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), false); 753 754 // This can be NULL if we don't know anything about the architecture or if 755 // the target for an architecture isn't enabled in the llvm/clang that we 756 // built 757 TargetInfo *target_info = getTargetInfo(); 758 if (target_info) 759 m_ast_up->InitBuiltinTypes(*target_info); 760 761 GetASTMap().Insert(m_ast_up.get(), this); 762 763 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up( 764 new ClangExternalASTSourceCallbacks(*this)); 765 SetExternalSource(ast_source_up); 766 } 767 768 TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) { 769 TypeSystemClang *clang_ast = GetASTMap().Lookup(ast); 770 return clang_ast; 771 } 772 773 clang::MangleContext *TypeSystemClang::getMangleContext() { 774 if (m_mangle_ctx_up == nullptr) 775 m_mangle_ctx_up.reset(getASTContext().createMangleContext()); 776 return m_mangle_ctx_up.get(); 777 } 778 779 std::shared_ptr<clang::TargetOptions> &TypeSystemClang::getTargetOptions() { 780 if (m_target_options_rp == nullptr && !m_target_triple.empty()) { 781 m_target_options_rp = std::make_shared<clang::TargetOptions>(); 782 if (m_target_options_rp != nullptr) 783 m_target_options_rp->Triple = m_target_triple; 784 } 785 return m_target_options_rp; 786 } 787 788 TargetInfo *TypeSystemClang::getTargetInfo() { 789 // target_triple should be something like "x86_64-apple-macosx" 790 if (m_target_info_up == nullptr && !m_target_triple.empty()) 791 m_target_info_up.reset(TargetInfo::CreateTargetInfo( 792 getASTContext().getDiagnostics(), getTargetOptions())); 793 return m_target_info_up.get(); 794 } 795 796 #pragma mark Basic Types 797 798 static inline bool QualTypeMatchesBitSize(const uint64_t bit_size, 799 ASTContext &ast, QualType qual_type) { 800 uint64_t qual_type_bit_size = ast.getTypeSize(qual_type); 801 return qual_type_bit_size == bit_size; 802 } 803 804 CompilerType 805 TypeSystemClang::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding, 806 size_t bit_size) { 807 ASTContext &ast = getASTContext(); 808 switch (encoding) { 809 case eEncodingInvalid: 810 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy)) 811 return GetType(ast.VoidPtrTy); 812 break; 813 814 case eEncodingUint: 815 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) 816 return GetType(ast.UnsignedCharTy); 817 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) 818 return GetType(ast.UnsignedShortTy); 819 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) 820 return GetType(ast.UnsignedIntTy); 821 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) 822 return GetType(ast.UnsignedLongTy); 823 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) 824 return GetType(ast.UnsignedLongLongTy); 825 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) 826 return GetType(ast.UnsignedInt128Ty); 827 break; 828 829 case eEncodingSint: 830 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) 831 return GetType(ast.SignedCharTy); 832 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) 833 return GetType(ast.ShortTy); 834 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) 835 return GetType(ast.IntTy); 836 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) 837 return GetType(ast.LongTy); 838 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) 839 return GetType(ast.LongLongTy); 840 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) 841 return GetType(ast.Int128Ty); 842 break; 843 844 case eEncodingIEEE754: 845 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) 846 return GetType(ast.FloatTy); 847 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) 848 return GetType(ast.DoubleTy); 849 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) 850 return GetType(ast.LongDoubleTy); 851 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy)) 852 return GetType(ast.HalfTy); 853 break; 854 855 case eEncodingVector: 856 // Sanity check that bit_size is a multiple of 8's. 857 if (bit_size && !(bit_size & 0x7u)) 858 return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8)); 859 break; 860 } 861 862 return CompilerType(); 863 } 864 865 lldb::BasicType TypeSystemClang::GetBasicTypeEnumeration(llvm::StringRef name) { 866 static const llvm::StringMap<lldb::BasicType> g_type_map = { 867 // "void" 868 {"void", eBasicTypeVoid}, 869 870 // "char" 871 {"char", eBasicTypeChar}, 872 {"signed char", eBasicTypeSignedChar}, 873 {"unsigned char", eBasicTypeUnsignedChar}, 874 {"wchar_t", eBasicTypeWChar}, 875 {"signed wchar_t", eBasicTypeSignedWChar}, 876 {"unsigned wchar_t", eBasicTypeUnsignedWChar}, 877 878 // "short" 879 {"short", eBasicTypeShort}, 880 {"short int", eBasicTypeShort}, 881 {"unsigned short", eBasicTypeUnsignedShort}, 882 {"unsigned short int", eBasicTypeUnsignedShort}, 883 884 // "int" 885 {"int", eBasicTypeInt}, 886 {"signed int", eBasicTypeInt}, 887 {"unsigned int", eBasicTypeUnsignedInt}, 888 {"unsigned", eBasicTypeUnsignedInt}, 889 890 // "long" 891 {"long", eBasicTypeLong}, 892 {"long int", eBasicTypeLong}, 893 {"unsigned long", eBasicTypeUnsignedLong}, 894 {"unsigned long int", eBasicTypeUnsignedLong}, 895 896 // "long long" 897 {"long long", eBasicTypeLongLong}, 898 {"long long int", eBasicTypeLongLong}, 899 {"unsigned long long", eBasicTypeUnsignedLongLong}, 900 {"unsigned long long int", eBasicTypeUnsignedLongLong}, 901 902 // "int128" 903 {"__int128_t", eBasicTypeInt128}, 904 {"__uint128_t", eBasicTypeUnsignedInt128}, 905 906 // Miscellaneous 907 {"bool", eBasicTypeBool}, 908 {"float", eBasicTypeFloat}, 909 {"double", eBasicTypeDouble}, 910 {"long double", eBasicTypeLongDouble}, 911 {"id", eBasicTypeObjCID}, 912 {"SEL", eBasicTypeObjCSel}, 913 {"nullptr", eBasicTypeNullPtr}, 914 }; 915 916 auto iter = g_type_map.find(name); 917 if (iter == g_type_map.end()) 918 return eBasicTypeInvalid; 919 920 return iter->second; 921 } 922 923 uint32_t TypeSystemClang::GetPointerByteSize() { 924 if (m_pointer_byte_size == 0) 925 if (auto size = GetBasicType(lldb::eBasicTypeVoid) 926 .GetPointerType() 927 .GetByteSize(nullptr)) 928 m_pointer_byte_size = *size; 929 return m_pointer_byte_size; 930 } 931 932 CompilerType TypeSystemClang::GetBasicType(lldb::BasicType basic_type) { 933 clang::ASTContext &ast = getASTContext(); 934 935 lldb::opaque_compiler_type_t clang_type = 936 GetOpaqueCompilerType(&ast, basic_type); 937 938 if (clang_type) 939 return CompilerType(weak_from_this(), clang_type); 940 return CompilerType(); 941 } 942 943 CompilerType TypeSystemClang::GetBuiltinTypeForDWARFEncodingAndBitSize( 944 llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) { 945 ASTContext &ast = getASTContext(); 946 947 switch (dw_ate) { 948 default: 949 break; 950 951 case DW_ATE_address: 952 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy)) 953 return GetType(ast.VoidPtrTy); 954 break; 955 956 case DW_ATE_boolean: 957 if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy)) 958 return GetType(ast.BoolTy); 959 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) 960 return GetType(ast.UnsignedCharTy); 961 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) 962 return GetType(ast.UnsignedShortTy); 963 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) 964 return GetType(ast.UnsignedIntTy); 965 break; 966 967 case DW_ATE_lo_user: 968 // This has been seen to mean DW_AT_complex_integer 969 if (type_name.contains("complex")) { 970 CompilerType complex_int_clang_type = 971 GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed, 972 bit_size / 2); 973 return GetType( 974 ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type))); 975 } 976 break; 977 978 case DW_ATE_complex_float: { 979 CanQualType FloatComplexTy = ast.getComplexType(ast.FloatTy); 980 if (QualTypeMatchesBitSize(bit_size, ast, FloatComplexTy)) 981 return GetType(FloatComplexTy); 982 983 CanQualType DoubleComplexTy = ast.getComplexType(ast.DoubleTy); 984 if (QualTypeMatchesBitSize(bit_size, ast, DoubleComplexTy)) 985 return GetType(DoubleComplexTy); 986 987 CanQualType LongDoubleComplexTy = ast.getComplexType(ast.LongDoubleTy); 988 if (QualTypeMatchesBitSize(bit_size, ast, LongDoubleComplexTy)) 989 return GetType(LongDoubleComplexTy); 990 991 CompilerType complex_float_clang_type = 992 GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float, 993 bit_size / 2); 994 return GetType( 995 ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type))); 996 } 997 998 case DW_ATE_float: 999 if (type_name == "float" && 1000 QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) 1001 return GetType(ast.FloatTy); 1002 if (type_name == "double" && 1003 QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) 1004 return GetType(ast.DoubleTy); 1005 if (type_name == "long double" && 1006 QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) 1007 return GetType(ast.LongDoubleTy); 1008 // Fall back to not requiring a name match 1009 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) 1010 return GetType(ast.FloatTy); 1011 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) 1012 return GetType(ast.DoubleTy); 1013 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) 1014 return GetType(ast.LongDoubleTy); 1015 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy)) 1016 return GetType(ast.HalfTy); 1017 break; 1018 1019 case DW_ATE_signed: 1020 if (!type_name.empty()) { 1021 if (type_name == "wchar_t" && 1022 QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) && 1023 (getTargetInfo() && 1024 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType()))) 1025 return GetType(ast.WCharTy); 1026 if (type_name == "void" && 1027 QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy)) 1028 return GetType(ast.VoidTy); 1029 if (type_name.contains("long long") && 1030 QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) 1031 return GetType(ast.LongLongTy); 1032 if (type_name.contains("long") && 1033 QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) 1034 return GetType(ast.LongTy); 1035 if (type_name.contains("short") && 1036 QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) 1037 return GetType(ast.ShortTy); 1038 if (type_name.contains("char")) { 1039 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) 1040 return GetType(ast.CharTy); 1041 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) 1042 return GetType(ast.SignedCharTy); 1043 } 1044 if (type_name.contains("int")) { 1045 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) 1046 return GetType(ast.IntTy); 1047 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) 1048 return GetType(ast.Int128Ty); 1049 } 1050 } 1051 // We weren't able to match up a type name, just search by size 1052 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) 1053 return GetType(ast.CharTy); 1054 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) 1055 return GetType(ast.ShortTy); 1056 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) 1057 return GetType(ast.IntTy); 1058 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) 1059 return GetType(ast.LongTy); 1060 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) 1061 return GetType(ast.LongLongTy); 1062 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) 1063 return GetType(ast.Int128Ty); 1064 break; 1065 1066 case DW_ATE_signed_char: 1067 if (type_name == "char") { 1068 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) 1069 return GetType(ast.CharTy); 1070 } 1071 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) 1072 return GetType(ast.SignedCharTy); 1073 break; 1074 1075 case DW_ATE_unsigned: 1076 if (!type_name.empty()) { 1077 if (type_name == "wchar_t") { 1078 if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) { 1079 if (!(getTargetInfo() && 1080 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType()))) 1081 return GetType(ast.WCharTy); 1082 } 1083 } 1084 if (type_name.contains("long long")) { 1085 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) 1086 return GetType(ast.UnsignedLongLongTy); 1087 } else if (type_name.contains("long")) { 1088 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) 1089 return GetType(ast.UnsignedLongTy); 1090 } else if (type_name.contains("short")) { 1091 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) 1092 return GetType(ast.UnsignedShortTy); 1093 } else if (type_name.contains("char")) { 1094 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) 1095 return GetType(ast.UnsignedCharTy); 1096 } else if (type_name.contains("int")) { 1097 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) 1098 return GetType(ast.UnsignedIntTy); 1099 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) 1100 return GetType(ast.UnsignedInt128Ty); 1101 } 1102 } 1103 // We weren't able to match up a type name, just search by size 1104 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) 1105 return GetType(ast.UnsignedCharTy); 1106 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) 1107 return GetType(ast.UnsignedShortTy); 1108 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) 1109 return GetType(ast.UnsignedIntTy); 1110 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) 1111 return GetType(ast.UnsignedLongTy); 1112 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) 1113 return GetType(ast.UnsignedLongLongTy); 1114 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) 1115 return GetType(ast.UnsignedInt128Ty); 1116 break; 1117 1118 case DW_ATE_unsigned_char: 1119 if (type_name == "char") { 1120 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) 1121 return GetType(ast.CharTy); 1122 } 1123 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) 1124 return GetType(ast.UnsignedCharTy); 1125 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) 1126 return GetType(ast.UnsignedShortTy); 1127 break; 1128 1129 case DW_ATE_imaginary_float: 1130 break; 1131 1132 case DW_ATE_UTF: 1133 switch (bit_size) { 1134 case 8: 1135 return GetType(ast.Char8Ty); 1136 case 16: 1137 return GetType(ast.Char16Ty); 1138 case 32: 1139 return GetType(ast.Char32Ty); 1140 default: 1141 if (!type_name.empty()) { 1142 if (type_name == "char16_t") 1143 return GetType(ast.Char16Ty); 1144 if (type_name == "char32_t") 1145 return GetType(ast.Char32Ty); 1146 if (type_name == "char8_t") 1147 return GetType(ast.Char8Ty); 1148 } 1149 } 1150 break; 1151 } 1152 1153 Log *log = GetLog(LLDBLog::Types); 1154 LLDB_LOG(log, 1155 "error: need to add support for DW_TAG_base_type '{0}' " 1156 "encoded with DW_ATE = {1:x}, bit_size = {2}", 1157 type_name, dw_ate, bit_size); 1158 return CompilerType(); 1159 } 1160 1161 CompilerType TypeSystemClang::GetCStringType(bool is_const) { 1162 ASTContext &ast = getASTContext(); 1163 QualType char_type(ast.CharTy); 1164 1165 if (is_const) 1166 char_type.addConst(); 1167 1168 return GetType(ast.getPointerType(char_type)); 1169 } 1170 1171 bool TypeSystemClang::AreTypesSame(CompilerType type1, CompilerType type2, 1172 bool ignore_qualifiers) { 1173 auto ast = type1.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>(); 1174 if (!ast || type1.GetTypeSystem() != type2.GetTypeSystem()) 1175 return false; 1176 1177 if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType()) 1178 return true; 1179 1180 QualType type1_qual = ClangUtil::GetQualType(type1); 1181 QualType type2_qual = ClangUtil::GetQualType(type2); 1182 1183 if (ignore_qualifiers) { 1184 type1_qual = type1_qual.getUnqualifiedType(); 1185 type2_qual = type2_qual.getUnqualifiedType(); 1186 } 1187 1188 return ast->getASTContext().hasSameType(type1_qual, type2_qual); 1189 } 1190 1191 CompilerType TypeSystemClang::GetTypeForDecl(void *opaque_decl) { 1192 if (!opaque_decl) 1193 return CompilerType(); 1194 1195 clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl); 1196 if (auto *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl)) 1197 return GetTypeForDecl(named_decl); 1198 return CompilerType(); 1199 } 1200 1201 CompilerDeclContext TypeSystemClang::CreateDeclContext(DeclContext *ctx) { 1202 // Check that the DeclContext actually belongs to this ASTContext. 1203 assert(&ctx->getParentASTContext() == &getASTContext()); 1204 return CompilerDeclContext(this, ctx); 1205 } 1206 1207 CompilerType TypeSystemClang::GetTypeForDecl(clang::NamedDecl *decl) { 1208 if (clang::ObjCInterfaceDecl *interface_decl = 1209 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) 1210 return GetTypeForDecl(interface_decl); 1211 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) 1212 return GetTypeForDecl(tag_decl); 1213 return CompilerType(); 1214 } 1215 1216 CompilerType TypeSystemClang::GetTypeForDecl(TagDecl *decl) { 1217 return GetType(getASTContext().getTagDeclType(decl)); 1218 } 1219 1220 CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) { 1221 return GetType(getASTContext().getObjCInterfaceType(decl)); 1222 } 1223 1224 #pragma mark Structure, Unions, Classes 1225 1226 void TypeSystemClang::SetOwningModule(clang::Decl *decl, 1227 OptionalClangModuleID owning_module) { 1228 if (!decl || !owning_module.HasValue()) 1229 return; 1230 1231 decl->setFromASTFile(); 1232 decl->setOwningModuleID(owning_module.GetValue()); 1233 decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible); 1234 } 1235 1236 OptionalClangModuleID 1237 TypeSystemClang::GetOrCreateClangModule(llvm::StringRef name, 1238 OptionalClangModuleID parent, 1239 bool is_framework, bool is_explicit) { 1240 // Get the external AST source which holds the modules. 1241 auto *ast_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>( 1242 getASTContext().getExternalSource()); 1243 assert(ast_source && "external ast source was lost"); 1244 if (!ast_source) 1245 return {}; 1246 1247 // Lazily initialize the module map. 1248 if (!m_header_search_up) { 1249 auto HSOpts = std::make_shared<clang::HeaderSearchOptions>(); 1250 m_header_search_up = std::make_unique<clang::HeaderSearch>( 1251 HSOpts, *m_source_manager_up, *m_diagnostics_engine_up, 1252 *m_language_options_up, m_target_info_up.get()); 1253 m_module_map_up = std::make_unique<clang::ModuleMap>( 1254 *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up, 1255 m_target_info_up.get(), *m_header_search_up); 1256 } 1257 1258 // Get or create the module context. 1259 bool created; 1260 clang::Module *module; 1261 auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue()); 1262 std::tie(module, created) = m_module_map_up->findOrCreateModule( 1263 name, parent_desc ? parent_desc->getModuleOrNull() : nullptr, 1264 is_framework, is_explicit); 1265 if (!created) 1266 return ast_source->GetIDForModule(module); 1267 1268 return ast_source->RegisterModule(module); 1269 } 1270 1271 CompilerType TypeSystemClang::CreateRecordType( 1272 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, 1273 AccessType access_type, llvm::StringRef name, int kind, 1274 LanguageType language, ClangASTMetadata *metadata, bool exports_symbols) { 1275 ASTContext &ast = getASTContext(); 1276 1277 if (decl_ctx == nullptr) 1278 decl_ctx = ast.getTranslationUnitDecl(); 1279 1280 if (language == eLanguageTypeObjC || 1281 language == eLanguageTypeObjC_plus_plus) { 1282 bool isForwardDecl = true; 1283 bool isInternal = false; 1284 return CreateObjCClass(name, decl_ctx, owning_module, isForwardDecl, 1285 isInternal, metadata); 1286 } 1287 1288 // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and 1289 // we will need to update this code. I was told to currently always use the 1290 // CXXRecordDecl class since we often don't know from debug information if 1291 // something is struct or a class, so we default to always use the more 1292 // complete definition just in case. 1293 1294 bool has_name = !name.empty(); 1295 CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, 0); 1296 decl->setTagKind(static_cast<TagDecl::TagKind>(kind)); 1297 decl->setDeclContext(decl_ctx); 1298 if (has_name) 1299 decl->setDeclName(&ast.Idents.get(name)); 1300 SetOwningModule(decl, owning_module); 1301 1302 if (!has_name) { 1303 // In C++ a lambda is also represented as an unnamed class. This is 1304 // different from an *anonymous class* that the user wrote: 1305 // 1306 // struct A { 1307 // // anonymous class (GNU/MSVC extension) 1308 // struct { 1309 // int x; 1310 // }; 1311 // // unnamed class within a class 1312 // struct { 1313 // int y; 1314 // } B; 1315 // }; 1316 // 1317 // void f() { 1318 // // unammed class outside of a class 1319 // struct { 1320 // int z; 1321 // } C; 1322 // } 1323 // 1324 // Anonymous classes is a GNU/MSVC extension that clang supports. It 1325 // requires the anonymous class be embedded within a class. So the new 1326 // heuristic verifies this condition. 1327 if (isa<CXXRecordDecl>(decl_ctx) && exports_symbols) 1328 decl->setAnonymousStructOrUnion(true); 1329 } 1330 1331 if (metadata) 1332 SetMetadata(decl, *metadata); 1333 1334 if (access_type != eAccessNone) 1335 decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type)); 1336 1337 if (decl_ctx) 1338 decl_ctx->addDecl(decl); 1339 1340 return GetType(ast.getTagDeclType(decl)); 1341 } 1342 1343 namespace { 1344 /// Returns true iff the given TemplateArgument should be represented as an 1345 /// NonTypeTemplateParmDecl in the AST. 1346 bool IsValueParam(const clang::TemplateArgument &argument) { 1347 return argument.getKind() == TemplateArgument::Integral; 1348 } 1349 1350 void AddAccessSpecifierDecl(clang::CXXRecordDecl *cxx_record_decl, 1351 ASTContext &ct, 1352 clang::AccessSpecifier previous_access, 1353 clang::AccessSpecifier access_specifier) { 1354 if (!cxx_record_decl->isClass() && !cxx_record_decl->isStruct()) 1355 return; 1356 if (previous_access != access_specifier) { 1357 // For struct, don't add AS_public if it's the first AccessSpecDecl. 1358 // For class, don't add AS_private if it's the first AccessSpecDecl. 1359 if ((cxx_record_decl->isStruct() && 1360 previous_access == clang::AccessSpecifier::AS_none && 1361 access_specifier == clang::AccessSpecifier::AS_public) || 1362 (cxx_record_decl->isClass() && 1363 previous_access == clang::AccessSpecifier::AS_none && 1364 access_specifier == clang::AccessSpecifier::AS_private)) { 1365 return; 1366 } 1367 cxx_record_decl->addDecl( 1368 AccessSpecDecl::Create(ct, access_specifier, cxx_record_decl, 1369 SourceLocation(), SourceLocation())); 1370 } 1371 } 1372 } // namespace 1373 1374 static TemplateParameterList *CreateTemplateParameterList( 1375 ASTContext &ast, 1376 const TypeSystemClang::TemplateParameterInfos &template_param_infos, 1377 llvm::SmallVector<NamedDecl *, 8> &template_param_decls) { 1378 const bool parameter_pack = false; 1379 const bool is_typename = false; 1380 const unsigned depth = 0; 1381 const size_t num_template_params = template_param_infos.Size(); 1382 DeclContext *const decl_context = 1383 ast.getTranslationUnitDecl(); // Is this the right decl context?, 1384 1385 auto const &args = template_param_infos.GetArgs(); 1386 auto const &names = template_param_infos.GetNames(); 1387 for (size_t i = 0; i < num_template_params; ++i) { 1388 const char *name = names[i]; 1389 1390 IdentifierInfo *identifier_info = nullptr; 1391 if (name && name[0]) 1392 identifier_info = &ast.Idents.get(name); 1393 TemplateArgument const &targ = args[i]; 1394 if (IsValueParam(targ)) { 1395 QualType template_param_type = targ.getIntegralType(); 1396 template_param_decls.push_back(NonTypeTemplateParmDecl::Create( 1397 ast, decl_context, SourceLocation(), SourceLocation(), depth, i, 1398 identifier_info, template_param_type, parameter_pack, 1399 ast.getTrivialTypeSourceInfo(template_param_type))); 1400 } else { 1401 template_param_decls.push_back(TemplateTypeParmDecl::Create( 1402 ast, decl_context, SourceLocation(), SourceLocation(), depth, i, 1403 identifier_info, is_typename, parameter_pack)); 1404 } 1405 } 1406 1407 if (template_param_infos.hasParameterPack()) { 1408 IdentifierInfo *identifier_info = nullptr; 1409 if (template_param_infos.HasPackName()) 1410 identifier_info = &ast.Idents.get(template_param_infos.GetPackName()); 1411 const bool parameter_pack_true = true; 1412 1413 if (!template_param_infos.GetParameterPack().IsEmpty() && 1414 IsValueParam(template_param_infos.GetParameterPack().Front())) { 1415 QualType template_param_type = 1416 template_param_infos.GetParameterPack().Front().getIntegralType(); 1417 template_param_decls.push_back(NonTypeTemplateParmDecl::Create( 1418 ast, decl_context, SourceLocation(), SourceLocation(), depth, 1419 num_template_params, identifier_info, template_param_type, 1420 parameter_pack_true, 1421 ast.getTrivialTypeSourceInfo(template_param_type))); 1422 } else { 1423 template_param_decls.push_back(TemplateTypeParmDecl::Create( 1424 ast, decl_context, SourceLocation(), SourceLocation(), depth, 1425 num_template_params, identifier_info, is_typename, 1426 parameter_pack_true)); 1427 } 1428 } 1429 clang::Expr *const requires_clause = nullptr; // TODO: Concepts 1430 TemplateParameterList *template_param_list = TemplateParameterList::Create( 1431 ast, SourceLocation(), SourceLocation(), template_param_decls, 1432 SourceLocation(), requires_clause); 1433 return template_param_list; 1434 } 1435 1436 std::string TypeSystemClang::PrintTemplateParams( 1437 const TemplateParameterInfos &template_param_infos) { 1438 llvm::SmallVector<NamedDecl *, 8> ignore; 1439 clang::TemplateParameterList *template_param_list = 1440 CreateTemplateParameterList(getASTContext(), template_param_infos, 1441 ignore); 1442 llvm::SmallVector<clang::TemplateArgument, 2> args( 1443 template_param_infos.GetArgs()); 1444 if (template_param_infos.hasParameterPack()) { 1445 llvm::ArrayRef<TemplateArgument> pack_args = 1446 template_param_infos.GetParameterPackArgs(); 1447 args.append(pack_args.begin(), pack_args.end()); 1448 } 1449 std::string str; 1450 llvm::raw_string_ostream os(str); 1451 clang::printTemplateArgumentList(os, args, GetTypePrintingPolicy(), 1452 template_param_list); 1453 return str; 1454 } 1455 1456 clang::FunctionTemplateDecl *TypeSystemClang::CreateFunctionTemplateDecl( 1457 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, 1458 clang::FunctionDecl *func_decl, 1459 const TemplateParameterInfos &template_param_infos) { 1460 // /// Create a function template node. 1461 ASTContext &ast = getASTContext(); 1462 1463 llvm::SmallVector<NamedDecl *, 8> template_param_decls; 1464 TemplateParameterList *template_param_list = CreateTemplateParameterList( 1465 ast, template_param_infos, template_param_decls); 1466 FunctionTemplateDecl *func_tmpl_decl = 1467 FunctionTemplateDecl::CreateDeserialized(ast, 0); 1468 func_tmpl_decl->setDeclContext(decl_ctx); 1469 func_tmpl_decl->setLocation(func_decl->getLocation()); 1470 func_tmpl_decl->setDeclName(func_decl->getDeclName()); 1471 func_tmpl_decl->setTemplateParameters(template_param_list); 1472 func_tmpl_decl->init(func_decl); 1473 SetOwningModule(func_tmpl_decl, owning_module); 1474 1475 for (size_t i = 0, template_param_decl_count = template_param_decls.size(); 1476 i < template_param_decl_count; ++i) { 1477 // TODO: verify which decl context we should put template_param_decls into.. 1478 template_param_decls[i]->setDeclContext(func_decl); 1479 } 1480 // Function templates inside a record need to have an access specifier. 1481 // It doesn't matter what access specifier we give the template as LLDB 1482 // anyway allows accessing everything inside a record. 1483 if (decl_ctx->isRecord()) 1484 func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public); 1485 1486 return func_tmpl_decl; 1487 } 1488 1489 void TypeSystemClang::CreateFunctionTemplateSpecializationInfo( 1490 FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl, 1491 const TemplateParameterInfos &infos) { 1492 TemplateArgumentList *template_args_ptr = TemplateArgumentList::CreateCopy( 1493 func_decl->getASTContext(), infos.GetArgs()); 1494 1495 func_decl->setFunctionTemplateSpecialization(func_tmpl_decl, 1496 template_args_ptr, nullptr); 1497 } 1498 1499 /// Returns true if the given template parameter can represent the given value. 1500 /// For example, `typename T` can represent `int` but not integral values such 1501 /// as `int I = 3`. 1502 static bool TemplateParameterAllowsValue(NamedDecl *param, 1503 const TemplateArgument &value) { 1504 if (llvm::isa<TemplateTypeParmDecl>(param)) { 1505 // Compare the argument kind, i.e. ensure that <typename> != <int>. 1506 if (value.getKind() != TemplateArgument::Type) 1507 return false; 1508 } else if (auto *type_param = 1509 llvm::dyn_cast<NonTypeTemplateParmDecl>(param)) { 1510 // Compare the argument kind, i.e. ensure that <typename> != <int>. 1511 if (!IsValueParam(value)) 1512 return false; 1513 // Compare the integral type, i.e. ensure that <int> != <char>. 1514 if (type_param->getType() != value.getIntegralType()) 1515 return false; 1516 } else { 1517 // There is no way to create other parameter decls at the moment, so we 1518 // can't reach this case during normal LLDB usage. Log that this happened 1519 // and assert. 1520 Log *log = GetLog(LLDBLog::Expressions); 1521 LLDB_LOG(log, 1522 "Don't know how to compare template parameter to passed" 1523 " value. Decl kind of parameter is: {0}", 1524 param->getDeclKindName()); 1525 lldbassert(false && "Can't compare this TemplateParmDecl subclass"); 1526 // In release builds just fall back to marking the parameter as not 1527 // accepting the value so that we don't try to fit an instantiation to a 1528 // template that doesn't fit. E.g., avoid that `S<1>` is being connected to 1529 // `template<typename T> struct S;`. 1530 return false; 1531 } 1532 return true; 1533 } 1534 1535 /// Returns true if the given class template declaration could produce an 1536 /// instantiation with the specified values. 1537 /// For example, `<typename T>` allows the arguments `float`, but not for 1538 /// example `bool, float` or `3` (as an integer parameter value). 1539 static bool ClassTemplateAllowsToInstantiationArgs( 1540 ClassTemplateDecl *class_template_decl, 1541 const TypeSystemClang::TemplateParameterInfos &instantiation_values) { 1542 1543 TemplateParameterList ¶ms = *class_template_decl->getTemplateParameters(); 1544 1545 // Save some work by iterating only once over the found parameters and 1546 // calculate the information related to parameter packs. 1547 1548 // Contains the first pack parameter (or non if there are none). 1549 std::optional<NamedDecl *> pack_parameter; 1550 // Contains the number of non-pack parameters. 1551 size_t non_pack_params = params.size(); 1552 for (size_t i = 0; i < params.size(); ++i) { 1553 NamedDecl *param = params.getParam(i); 1554 if (param->isParameterPack()) { 1555 pack_parameter = param; 1556 non_pack_params = i; 1557 break; 1558 } 1559 } 1560 1561 // The found template needs to have compatible non-pack template arguments. 1562 // E.g., ensure that <typename, typename> != <typename>. 1563 // The pack parameters are compared later. 1564 if (non_pack_params != instantiation_values.Size()) 1565 return false; 1566 1567 // Ensure that <typename...> != <typename>. 1568 if (pack_parameter.has_value() != instantiation_values.hasParameterPack()) 1569 return false; 1570 1571 // Compare the first pack parameter that was found with the first pack 1572 // parameter value. The special case of having an empty parameter pack value 1573 // always fits to a pack parameter. 1574 // E.g., ensure that <int...> != <typename...>. 1575 if (pack_parameter && !instantiation_values.GetParameterPack().IsEmpty() && 1576 !TemplateParameterAllowsValue( 1577 *pack_parameter, instantiation_values.GetParameterPack().Front())) 1578 return false; 1579 1580 // Compare all the non-pack parameters now. 1581 // E.g., ensure that <int> != <long>. 1582 for (const auto pair : 1583 llvm::zip_first(instantiation_values.GetArgs(), params)) { 1584 const TemplateArgument &passed_arg = std::get<0>(pair); 1585 NamedDecl *found_param = std::get<1>(pair); 1586 if (!TemplateParameterAllowsValue(found_param, passed_arg)) 1587 return false; 1588 } 1589 1590 return class_template_decl; 1591 } 1592 1593 ClassTemplateDecl *TypeSystemClang::CreateClassTemplateDecl( 1594 DeclContext *decl_ctx, OptionalClangModuleID owning_module, 1595 lldb::AccessType access_type, llvm::StringRef class_name, int kind, 1596 const TemplateParameterInfos &template_param_infos) { 1597 ASTContext &ast = getASTContext(); 1598 1599 ClassTemplateDecl *class_template_decl = nullptr; 1600 if (decl_ctx == nullptr) 1601 decl_ctx = ast.getTranslationUnitDecl(); 1602 1603 IdentifierInfo &identifier_info = ast.Idents.get(class_name); 1604 DeclarationName decl_name(&identifier_info); 1605 1606 // Search the AST for an existing ClassTemplateDecl that could be reused. 1607 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); 1608 for (NamedDecl *decl : result) { 1609 class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl); 1610 if (!class_template_decl) 1611 continue; 1612 // The class template has to be able to represents the instantiation 1613 // values we received. Without this we might end up putting an instantiation 1614 // with arguments such as <int, int> to a template such as: 1615 // template<typename T> struct S; 1616 // Connecting the instantiation to an incompatible template could cause 1617 // problems later on. 1618 if (!ClassTemplateAllowsToInstantiationArgs(class_template_decl, 1619 template_param_infos)) 1620 continue; 1621 return class_template_decl; 1622 } 1623 1624 llvm::SmallVector<NamedDecl *, 8> template_param_decls; 1625 1626 TemplateParameterList *template_param_list = CreateTemplateParameterList( 1627 ast, template_param_infos, template_param_decls); 1628 1629 CXXRecordDecl *template_cxx_decl = CXXRecordDecl::CreateDeserialized(ast, 0); 1630 template_cxx_decl->setTagKind(static_cast<TagDecl::TagKind>(kind)); 1631 // What decl context do we use here? TU? The actual decl context? 1632 template_cxx_decl->setDeclContext(decl_ctx); 1633 template_cxx_decl->setDeclName(decl_name); 1634 SetOwningModule(template_cxx_decl, owning_module); 1635 1636 for (size_t i = 0, template_param_decl_count = template_param_decls.size(); 1637 i < template_param_decl_count; ++i) { 1638 template_param_decls[i]->setDeclContext(template_cxx_decl); 1639 } 1640 1641 // With templated classes, we say that a class is templated with 1642 // specializations, but that the bare class has no functions. 1643 // template_cxx_decl->startDefinition(); 1644 // template_cxx_decl->completeDefinition(); 1645 1646 class_template_decl = ClassTemplateDecl::CreateDeserialized(ast, 0); 1647 // What decl context do we use here? TU? The actual decl context? 1648 class_template_decl->setDeclContext(decl_ctx); 1649 class_template_decl->setDeclName(decl_name); 1650 class_template_decl->setTemplateParameters(template_param_list); 1651 class_template_decl->init(template_cxx_decl); 1652 template_cxx_decl->setDescribedClassTemplate(class_template_decl); 1653 SetOwningModule(class_template_decl, owning_module); 1654 1655 if (access_type != eAccessNone) 1656 class_template_decl->setAccess( 1657 ConvertAccessTypeToAccessSpecifier(access_type)); 1658 1659 decl_ctx->addDecl(class_template_decl); 1660 1661 VerifyDecl(class_template_decl); 1662 1663 return class_template_decl; 1664 } 1665 1666 TemplateTemplateParmDecl * 1667 TypeSystemClang::CreateTemplateTemplateParmDecl(const char *template_name) { 1668 ASTContext &ast = getASTContext(); 1669 1670 auto *decl_ctx = ast.getTranslationUnitDecl(); 1671 1672 IdentifierInfo &identifier_info = ast.Idents.get(template_name); 1673 llvm::SmallVector<NamedDecl *, 8> template_param_decls; 1674 1675 TypeSystemClang::TemplateParameterInfos template_param_infos; 1676 TemplateParameterList *template_param_list = CreateTemplateParameterList( 1677 ast, template_param_infos, template_param_decls); 1678 1679 // LLDB needs to create those decls only to be able to display a 1680 // type that includes a template template argument. Only the name matters for 1681 // this purpose, so we use dummy values for the other characteristics of the 1682 // type. 1683 return TemplateTemplateParmDecl::Create( 1684 ast, decl_ctx, SourceLocation(), 1685 /*Depth*/ 0, /*Position*/ 0, 1686 /*IsParameterPack*/ false, &identifier_info, template_param_list); 1687 } 1688 1689 ClassTemplateSpecializationDecl * 1690 TypeSystemClang::CreateClassTemplateSpecializationDecl( 1691 DeclContext *decl_ctx, OptionalClangModuleID owning_module, 1692 ClassTemplateDecl *class_template_decl, int kind, 1693 const TemplateParameterInfos &template_param_infos) { 1694 ASTContext &ast = getASTContext(); 1695 llvm::SmallVector<clang::TemplateArgument, 2> args( 1696 template_param_infos.Size() + 1697 (template_param_infos.hasParameterPack() ? 1 : 0)); 1698 1699 auto const &orig_args = template_param_infos.GetArgs(); 1700 std::copy(orig_args.begin(), orig_args.end(), args.begin()); 1701 if (template_param_infos.hasParameterPack()) { 1702 args[args.size() - 1] = TemplateArgument::CreatePackCopy( 1703 ast, template_param_infos.GetParameterPackArgs()); 1704 } 1705 ClassTemplateSpecializationDecl *class_template_specialization_decl = 1706 ClassTemplateSpecializationDecl::CreateDeserialized(ast, 0); 1707 class_template_specialization_decl->setTagKind( 1708 static_cast<TagDecl::TagKind>(kind)); 1709 class_template_specialization_decl->setDeclContext(decl_ctx); 1710 class_template_specialization_decl->setInstantiationOf(class_template_decl); 1711 class_template_specialization_decl->setTemplateArgs( 1712 TemplateArgumentList::CreateCopy(ast, args)); 1713 ast.getTypeDeclType(class_template_specialization_decl, nullptr); 1714 class_template_specialization_decl->setDeclName( 1715 class_template_decl->getDeclName()); 1716 SetOwningModule(class_template_specialization_decl, owning_module); 1717 decl_ctx->addDecl(class_template_specialization_decl); 1718 1719 class_template_specialization_decl->setSpecializationKind( 1720 TSK_ExplicitSpecialization); 1721 1722 return class_template_specialization_decl; 1723 } 1724 1725 CompilerType TypeSystemClang::CreateClassTemplateSpecializationType( 1726 ClassTemplateSpecializationDecl *class_template_specialization_decl) { 1727 if (class_template_specialization_decl) { 1728 ASTContext &ast = getASTContext(); 1729 return GetType(ast.getTagDeclType(class_template_specialization_decl)); 1730 } 1731 return CompilerType(); 1732 } 1733 1734 static inline bool check_op_param(bool is_method, 1735 clang::OverloadedOperatorKind op_kind, 1736 bool unary, bool binary, 1737 uint32_t num_params) { 1738 // Special-case call since it can take any number of operands 1739 if (op_kind == OO_Call) 1740 return true; 1741 1742 // The parameter count doesn't include "this" 1743 if (is_method) 1744 ++num_params; 1745 if (num_params == 1) 1746 return unary; 1747 if (num_params == 2) 1748 return binary; 1749 else 1750 return false; 1751 } 1752 1753 bool TypeSystemClang::CheckOverloadedOperatorKindParameterCount( 1754 bool is_method, clang::OverloadedOperatorKind op_kind, 1755 uint32_t num_params) { 1756 switch (op_kind) { 1757 default: 1758 break; 1759 // C++ standard allows any number of arguments to new/delete 1760 case OO_New: 1761 case OO_Array_New: 1762 case OO_Delete: 1763 case OO_Array_Delete: 1764 return true; 1765 } 1766 1767 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 1768 case OO_##Name: \ 1769 return check_op_param(is_method, op_kind, Unary, Binary, num_params); 1770 switch (op_kind) { 1771 #include "clang/Basic/OperatorKinds.def" 1772 default: 1773 break; 1774 } 1775 return false; 1776 } 1777 1778 clang::AccessSpecifier 1779 TypeSystemClang::UnifyAccessSpecifiers(clang::AccessSpecifier lhs, 1780 clang::AccessSpecifier rhs) { 1781 // Make the access equal to the stricter of the field and the nested field's 1782 // access 1783 if (lhs == AS_none || rhs == AS_none) 1784 return AS_none; 1785 if (lhs == AS_private || rhs == AS_private) 1786 return AS_private; 1787 if (lhs == AS_protected || rhs == AS_protected) 1788 return AS_protected; 1789 return AS_public; 1790 } 1791 1792 bool TypeSystemClang::FieldIsBitfield(FieldDecl *field, 1793 uint32_t &bitfield_bit_size) { 1794 ASTContext &ast = getASTContext(); 1795 if (field == nullptr) 1796 return false; 1797 1798 if (field->isBitField()) { 1799 Expr *bit_width_expr = field->getBitWidth(); 1800 if (bit_width_expr) { 1801 if (std::optional<llvm::APSInt> bit_width_apsint = 1802 bit_width_expr->getIntegerConstantExpr(ast)) { 1803 bitfield_bit_size = bit_width_apsint->getLimitedValue(UINT32_MAX); 1804 return true; 1805 } 1806 } 1807 } 1808 return false; 1809 } 1810 1811 bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) { 1812 if (record_decl == nullptr) 1813 return false; 1814 1815 if (!record_decl->field_empty()) 1816 return true; 1817 1818 // No fields, lets check this is a CXX record and check the base classes 1819 const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl); 1820 if (cxx_record_decl) { 1821 CXXRecordDecl::base_class_const_iterator base_class, base_class_end; 1822 for (base_class = cxx_record_decl->bases_begin(), 1823 base_class_end = cxx_record_decl->bases_end(); 1824 base_class != base_class_end; ++base_class) { 1825 const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>( 1826 base_class->getType()->getAs<RecordType>()->getDecl()); 1827 if (RecordHasFields(base_class_decl)) 1828 return true; 1829 } 1830 } 1831 1832 // We always want forcefully completed types to show up so we can print a 1833 // message in the summary that indicates that the type is incomplete. 1834 // This will help users know when they are running into issues with 1835 // -flimit-debug-info instead of just seeing nothing if this is a base class 1836 // (since we were hiding empty base classes), or nothing when you turn open 1837 // an valiable whose type was incomplete. 1838 ClangASTMetadata *meta_data = GetMetadata(record_decl); 1839 if (meta_data && meta_data->IsForcefullyCompleted()) 1840 return true; 1841 1842 return false; 1843 } 1844 1845 #pragma mark Objective-C Classes 1846 1847 CompilerType TypeSystemClang::CreateObjCClass( 1848 llvm::StringRef name, clang::DeclContext *decl_ctx, 1849 OptionalClangModuleID owning_module, bool isForwardDecl, bool isInternal, 1850 ClangASTMetadata *metadata) { 1851 ASTContext &ast = getASTContext(); 1852 assert(!name.empty()); 1853 if (!decl_ctx) 1854 decl_ctx = ast.getTranslationUnitDecl(); 1855 1856 ObjCInterfaceDecl *decl = ObjCInterfaceDecl::CreateDeserialized(ast, 0); 1857 decl->setDeclContext(decl_ctx); 1858 decl->setDeclName(&ast.Idents.get(name)); 1859 /*isForwardDecl,*/ 1860 decl->setImplicit(isInternal); 1861 SetOwningModule(decl, owning_module); 1862 1863 if (metadata) 1864 SetMetadata(decl, *metadata); 1865 1866 return GetType(ast.getObjCInterfaceType(decl)); 1867 } 1868 1869 bool TypeSystemClang::BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) { 1870 return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl()); 1871 } 1872 1873 uint32_t 1874 TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl, 1875 bool omit_empty_base_classes) { 1876 uint32_t num_bases = 0; 1877 if (cxx_record_decl) { 1878 if (omit_empty_base_classes) { 1879 CXXRecordDecl::base_class_const_iterator base_class, base_class_end; 1880 for (base_class = cxx_record_decl->bases_begin(), 1881 base_class_end = cxx_record_decl->bases_end(); 1882 base_class != base_class_end; ++base_class) { 1883 // Skip empty base classes 1884 if (BaseSpecifierIsEmpty(base_class)) 1885 continue; 1886 ++num_bases; 1887 } 1888 } else 1889 num_bases = cxx_record_decl->getNumBases(); 1890 } 1891 return num_bases; 1892 } 1893 1894 #pragma mark Namespace Declarations 1895 1896 NamespaceDecl *TypeSystemClang::GetUniqueNamespaceDeclaration( 1897 const char *name, clang::DeclContext *decl_ctx, 1898 OptionalClangModuleID owning_module, bool is_inline) { 1899 NamespaceDecl *namespace_decl = nullptr; 1900 ASTContext &ast = getASTContext(); 1901 TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl(); 1902 if (!decl_ctx) 1903 decl_ctx = translation_unit_decl; 1904 1905 if (name) { 1906 IdentifierInfo &identifier_info = ast.Idents.get(name); 1907 DeclarationName decl_name(&identifier_info); 1908 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); 1909 for (NamedDecl *decl : result) { 1910 namespace_decl = dyn_cast<clang::NamespaceDecl>(decl); 1911 if (namespace_decl) 1912 return namespace_decl; 1913 } 1914 1915 namespace_decl = NamespaceDecl::Create(ast, decl_ctx, is_inline, 1916 SourceLocation(), SourceLocation(), 1917 &identifier_info, nullptr, false); 1918 1919 decl_ctx->addDecl(namespace_decl); 1920 } else { 1921 if (decl_ctx == translation_unit_decl) { 1922 namespace_decl = translation_unit_decl->getAnonymousNamespace(); 1923 if (namespace_decl) 1924 return namespace_decl; 1925 1926 namespace_decl = 1927 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(), 1928 SourceLocation(), nullptr, nullptr, false); 1929 translation_unit_decl->setAnonymousNamespace(namespace_decl); 1930 translation_unit_decl->addDecl(namespace_decl); 1931 assert(namespace_decl == translation_unit_decl->getAnonymousNamespace()); 1932 } else { 1933 NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx); 1934 if (parent_namespace_decl) { 1935 namespace_decl = parent_namespace_decl->getAnonymousNamespace(); 1936 if (namespace_decl) 1937 return namespace_decl; 1938 namespace_decl = 1939 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(), 1940 SourceLocation(), nullptr, nullptr, false); 1941 parent_namespace_decl->setAnonymousNamespace(namespace_decl); 1942 parent_namespace_decl->addDecl(namespace_decl); 1943 assert(namespace_decl == 1944 parent_namespace_decl->getAnonymousNamespace()); 1945 } else { 1946 assert(false && "GetUniqueNamespaceDeclaration called with no name and " 1947 "no namespace as decl_ctx"); 1948 } 1949 } 1950 } 1951 // Note: namespaces can span multiple modules, so perhaps this isn't a good 1952 // idea. 1953 SetOwningModule(namespace_decl, owning_module); 1954 1955 VerifyDecl(namespace_decl); 1956 return namespace_decl; 1957 } 1958 1959 clang::BlockDecl * 1960 TypeSystemClang::CreateBlockDeclaration(clang::DeclContext *ctx, 1961 OptionalClangModuleID owning_module) { 1962 if (ctx) { 1963 clang::BlockDecl *decl = 1964 clang::BlockDecl::CreateDeserialized(getASTContext(), 0); 1965 decl->setDeclContext(ctx); 1966 ctx->addDecl(decl); 1967 SetOwningModule(decl, owning_module); 1968 return decl; 1969 } 1970 return nullptr; 1971 } 1972 1973 clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left, 1974 clang::DeclContext *right, 1975 clang::DeclContext *root) { 1976 if (root == nullptr) 1977 return nullptr; 1978 1979 std::set<clang::DeclContext *> path_left; 1980 for (clang::DeclContext *d = left; d != nullptr; d = d->getParent()) 1981 path_left.insert(d); 1982 1983 for (clang::DeclContext *d = right; d != nullptr; d = d->getParent()) 1984 if (path_left.find(d) != path_left.end()) 1985 return d; 1986 1987 return nullptr; 1988 } 1989 1990 clang::UsingDirectiveDecl *TypeSystemClang::CreateUsingDirectiveDeclaration( 1991 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, 1992 clang::NamespaceDecl *ns_decl) { 1993 if (decl_ctx && ns_decl) { 1994 auto *translation_unit = getASTContext().getTranslationUnitDecl(); 1995 clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create( 1996 getASTContext(), decl_ctx, clang::SourceLocation(), 1997 clang::SourceLocation(), clang::NestedNameSpecifierLoc(), 1998 clang::SourceLocation(), ns_decl, 1999 FindLCABetweenDecls(decl_ctx, ns_decl, 2000 translation_unit)); 2001 decl_ctx->addDecl(using_decl); 2002 SetOwningModule(using_decl, owning_module); 2003 return using_decl; 2004 } 2005 return nullptr; 2006 } 2007 2008 clang::UsingDecl * 2009 TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx, 2010 OptionalClangModuleID owning_module, 2011 clang::NamedDecl *target) { 2012 if (current_decl_ctx && target) { 2013 clang::UsingDecl *using_decl = clang::UsingDecl::Create( 2014 getASTContext(), current_decl_ctx, clang::SourceLocation(), 2015 clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false); 2016 SetOwningModule(using_decl, owning_module); 2017 clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create( 2018 getASTContext(), current_decl_ctx, clang::SourceLocation(), 2019 target->getDeclName(), using_decl, target); 2020 SetOwningModule(shadow_decl, owning_module); 2021 using_decl->addShadowDecl(shadow_decl); 2022 current_decl_ctx->addDecl(using_decl); 2023 return using_decl; 2024 } 2025 return nullptr; 2026 } 2027 2028 clang::VarDecl *TypeSystemClang::CreateVariableDeclaration( 2029 clang::DeclContext *decl_context, OptionalClangModuleID owning_module, 2030 const char *name, clang::QualType type) { 2031 if (decl_context) { 2032 clang::VarDecl *var_decl = 2033 clang::VarDecl::CreateDeserialized(getASTContext(), 0); 2034 var_decl->setDeclContext(decl_context); 2035 if (name && name[0]) 2036 var_decl->setDeclName(&getASTContext().Idents.getOwn(name)); 2037 var_decl->setType(type); 2038 SetOwningModule(var_decl, owning_module); 2039 var_decl->setAccess(clang::AS_public); 2040 decl_context->addDecl(var_decl); 2041 return var_decl; 2042 } 2043 return nullptr; 2044 } 2045 2046 lldb::opaque_compiler_type_t 2047 TypeSystemClang::GetOpaqueCompilerType(clang::ASTContext *ast, 2048 lldb::BasicType basic_type) { 2049 switch (basic_type) { 2050 case eBasicTypeVoid: 2051 return ast->VoidTy.getAsOpaquePtr(); 2052 case eBasicTypeChar: 2053 return ast->CharTy.getAsOpaquePtr(); 2054 case eBasicTypeSignedChar: 2055 return ast->SignedCharTy.getAsOpaquePtr(); 2056 case eBasicTypeUnsignedChar: 2057 return ast->UnsignedCharTy.getAsOpaquePtr(); 2058 case eBasicTypeWChar: 2059 return ast->getWCharType().getAsOpaquePtr(); 2060 case eBasicTypeSignedWChar: 2061 return ast->getSignedWCharType().getAsOpaquePtr(); 2062 case eBasicTypeUnsignedWChar: 2063 return ast->getUnsignedWCharType().getAsOpaquePtr(); 2064 case eBasicTypeChar8: 2065 return ast->Char8Ty.getAsOpaquePtr(); 2066 case eBasicTypeChar16: 2067 return ast->Char16Ty.getAsOpaquePtr(); 2068 case eBasicTypeChar32: 2069 return ast->Char32Ty.getAsOpaquePtr(); 2070 case eBasicTypeShort: 2071 return ast->ShortTy.getAsOpaquePtr(); 2072 case eBasicTypeUnsignedShort: 2073 return ast->UnsignedShortTy.getAsOpaquePtr(); 2074 case eBasicTypeInt: 2075 return ast->IntTy.getAsOpaquePtr(); 2076 case eBasicTypeUnsignedInt: 2077 return ast->UnsignedIntTy.getAsOpaquePtr(); 2078 case eBasicTypeLong: 2079 return ast->LongTy.getAsOpaquePtr(); 2080 case eBasicTypeUnsignedLong: 2081 return ast->UnsignedLongTy.getAsOpaquePtr(); 2082 case eBasicTypeLongLong: 2083 return ast->LongLongTy.getAsOpaquePtr(); 2084 case eBasicTypeUnsignedLongLong: 2085 return ast->UnsignedLongLongTy.getAsOpaquePtr(); 2086 case eBasicTypeInt128: 2087 return ast->Int128Ty.getAsOpaquePtr(); 2088 case eBasicTypeUnsignedInt128: 2089 return ast->UnsignedInt128Ty.getAsOpaquePtr(); 2090 case eBasicTypeBool: 2091 return ast->BoolTy.getAsOpaquePtr(); 2092 case eBasicTypeHalf: 2093 return ast->HalfTy.getAsOpaquePtr(); 2094 case eBasicTypeFloat: 2095 return ast->FloatTy.getAsOpaquePtr(); 2096 case eBasicTypeDouble: 2097 return ast->DoubleTy.getAsOpaquePtr(); 2098 case eBasicTypeLongDouble: 2099 return ast->LongDoubleTy.getAsOpaquePtr(); 2100 case eBasicTypeFloatComplex: 2101 return ast->getComplexType(ast->FloatTy).getAsOpaquePtr(); 2102 case eBasicTypeDoubleComplex: 2103 return ast->getComplexType(ast->DoubleTy).getAsOpaquePtr(); 2104 case eBasicTypeLongDoubleComplex: 2105 return ast->getComplexType(ast->LongDoubleTy).getAsOpaquePtr(); 2106 case eBasicTypeObjCID: 2107 return ast->getObjCIdType().getAsOpaquePtr(); 2108 case eBasicTypeObjCClass: 2109 return ast->getObjCClassType().getAsOpaquePtr(); 2110 case eBasicTypeObjCSel: 2111 return ast->getObjCSelType().getAsOpaquePtr(); 2112 case eBasicTypeNullPtr: 2113 return ast->NullPtrTy.getAsOpaquePtr(); 2114 default: 2115 return nullptr; 2116 } 2117 } 2118 2119 #pragma mark Function Types 2120 2121 clang::DeclarationName 2122 TypeSystemClang::GetDeclarationName(llvm::StringRef name, 2123 const CompilerType &function_clang_type) { 2124 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; 2125 if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS) 2126 return DeclarationName(&getASTContext().Idents.get( 2127 name)); // Not operator, but a regular function. 2128 2129 // Check the number of operator parameters. Sometimes we have seen bad DWARF 2130 // that doesn't correctly describe operators and if we try to create a method 2131 // and add it to the class, clang will assert and crash, so we need to make 2132 // sure things are acceptable. 2133 clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type)); 2134 const clang::FunctionProtoType *function_type = 2135 llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr()); 2136 if (function_type == nullptr) 2137 return clang::DeclarationName(); 2138 2139 const bool is_method = false; 2140 const unsigned int num_params = function_type->getNumParams(); 2141 if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount( 2142 is_method, op_kind, num_params)) 2143 return clang::DeclarationName(); 2144 2145 return getASTContext().DeclarationNames.getCXXOperatorName(op_kind); 2146 } 2147 2148 PrintingPolicy TypeSystemClang::GetTypePrintingPolicy() { 2149 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy()); 2150 printing_policy.SuppressTagKeyword = true; 2151 // Inline namespaces are important for some type formatters (e.g., libc++ 2152 // and libstdc++ are differentiated by their inline namespaces). 2153 printing_policy.SuppressInlineNamespace = false; 2154 printing_policy.SuppressUnwrittenScope = false; 2155 // Default arguments are also always important for type formatters. Otherwise 2156 // we would need to always specify two type names for the setups where we do 2157 // know the default arguments and where we don't know default arguments. 2158 // 2159 // For example, without this we would need to have formatters for both: 2160 // std::basic_string<char> 2161 // and 2162 // std::basic_string<char, std::char_traits<char>, std::allocator<char> > 2163 // to support setups where LLDB was able to reconstruct default arguments 2164 // (and we then would have suppressed them from the type name) and also setups 2165 // where LLDB wasn't able to reconstruct the default arguments. 2166 printing_policy.SuppressDefaultTemplateArgs = false; 2167 return printing_policy; 2168 } 2169 2170 std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl, 2171 bool qualified) { 2172 clang::PrintingPolicy printing_policy = GetTypePrintingPolicy(); 2173 std::string result; 2174 llvm::raw_string_ostream os(result); 2175 named_decl->getNameForDiagnostic(os, printing_policy, qualified); 2176 return result; 2177 } 2178 2179 FunctionDecl *TypeSystemClang::CreateFunctionDeclaration( 2180 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, 2181 llvm::StringRef name, const CompilerType &function_clang_type, 2182 clang::StorageClass storage, bool is_inline) { 2183 FunctionDecl *func_decl = nullptr; 2184 ASTContext &ast = getASTContext(); 2185 if (!decl_ctx) 2186 decl_ctx = ast.getTranslationUnitDecl(); 2187 2188 const bool hasWrittenPrototype = true; 2189 const bool isConstexprSpecified = false; 2190 2191 clang::DeclarationName declarationName = 2192 GetDeclarationName(name, function_clang_type); 2193 func_decl = FunctionDecl::CreateDeserialized(ast, 0); 2194 func_decl->setDeclContext(decl_ctx); 2195 func_decl->setDeclName(declarationName); 2196 func_decl->setType(ClangUtil::GetQualType(function_clang_type)); 2197 func_decl->setStorageClass(storage); 2198 func_decl->setInlineSpecified(is_inline); 2199 func_decl->setHasWrittenPrototype(hasWrittenPrototype); 2200 func_decl->setConstexprKind(isConstexprSpecified 2201 ? ConstexprSpecKind::Constexpr 2202 : ConstexprSpecKind::Unspecified); 2203 SetOwningModule(func_decl, owning_module); 2204 decl_ctx->addDecl(func_decl); 2205 2206 VerifyDecl(func_decl); 2207 2208 return func_decl; 2209 } 2210 2211 CompilerType TypeSystemClang::CreateFunctionType( 2212 const CompilerType &result_type, const CompilerType *args, 2213 unsigned num_args, bool is_variadic, unsigned type_quals, 2214 clang::CallingConv cc, clang::RefQualifierKind ref_qual) { 2215 if (!result_type || !ClangUtil::IsClangType(result_type)) 2216 return CompilerType(); // invalid return type 2217 2218 std::vector<QualType> qual_type_args; 2219 if (num_args > 0 && args == nullptr) 2220 return CompilerType(); // invalid argument array passed in 2221 2222 // Verify that all arguments are valid and the right type 2223 for (unsigned i = 0; i < num_args; ++i) { 2224 if (args[i]) { 2225 // Make sure we have a clang type in args[i] and not a type from another 2226 // language whose name might match 2227 const bool is_clang_type = ClangUtil::IsClangType(args[i]); 2228 lldbassert(is_clang_type); 2229 if (is_clang_type) 2230 qual_type_args.push_back(ClangUtil::GetQualType(args[i])); 2231 else 2232 return CompilerType(); // invalid argument type (must be a clang type) 2233 } else 2234 return CompilerType(); // invalid argument type (empty) 2235 } 2236 2237 // TODO: Detect calling convention in DWARF? 2238 FunctionProtoType::ExtProtoInfo proto_info; 2239 proto_info.ExtInfo = cc; 2240 proto_info.Variadic = is_variadic; 2241 proto_info.ExceptionSpec = EST_None; 2242 proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals); 2243 proto_info.RefQualifier = ref_qual; 2244 2245 return GetType(getASTContext().getFunctionType( 2246 ClangUtil::GetQualType(result_type), qual_type_args, proto_info)); 2247 } 2248 2249 ParmVarDecl *TypeSystemClang::CreateParameterDeclaration( 2250 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, 2251 const char *name, const CompilerType ¶m_type, int storage, 2252 bool add_decl) { 2253 ASTContext &ast = getASTContext(); 2254 auto *decl = ParmVarDecl::CreateDeserialized(ast, 0); 2255 decl->setDeclContext(decl_ctx); 2256 if (name && name[0]) 2257 decl->setDeclName(&ast.Idents.get(name)); 2258 decl->setType(ClangUtil::GetQualType(param_type)); 2259 decl->setStorageClass(static_cast<clang::StorageClass>(storage)); 2260 SetOwningModule(decl, owning_module); 2261 if (add_decl) 2262 decl_ctx->addDecl(decl); 2263 2264 return decl; 2265 } 2266 2267 void TypeSystemClang::SetFunctionParameters( 2268 FunctionDecl *function_decl, llvm::ArrayRef<ParmVarDecl *> params) { 2269 if (function_decl) 2270 function_decl->setParams(params); 2271 } 2272 2273 CompilerType 2274 TypeSystemClang::CreateBlockPointerType(const CompilerType &function_type) { 2275 QualType block_type = m_ast_up->getBlockPointerType( 2276 clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType())); 2277 2278 return GetType(block_type); 2279 } 2280 2281 #pragma mark Array Types 2282 2283 CompilerType TypeSystemClang::CreateArrayType(const CompilerType &element_type, 2284 size_t element_count, 2285 bool is_vector) { 2286 if (element_type.IsValid()) { 2287 ASTContext &ast = getASTContext(); 2288 2289 if (is_vector) { 2290 return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type), 2291 element_count)); 2292 } else { 2293 2294 llvm::APInt ap_element_count(64, element_count); 2295 if (element_count == 0) { 2296 return GetType(ast.getIncompleteArrayType( 2297 ClangUtil::GetQualType(element_type), clang::ArrayType::Normal, 0)); 2298 } else { 2299 return GetType(ast.getConstantArrayType( 2300 ClangUtil::GetQualType(element_type), ap_element_count, nullptr, 2301 clang::ArrayType::Normal, 0)); 2302 } 2303 } 2304 } 2305 return CompilerType(); 2306 } 2307 2308 CompilerType TypeSystemClang::CreateStructForIdentifier( 2309 llvm::StringRef type_name, 2310 const std::initializer_list<std::pair<const char *, CompilerType>> 2311 &type_fields, 2312 bool packed) { 2313 CompilerType type; 2314 if (!type_name.empty() && 2315 (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)) 2316 .IsValid()) { 2317 lldbassert(0 && "Trying to create a type for an existing name"); 2318 return type; 2319 } 2320 2321 type = CreateRecordType(nullptr, OptionalClangModuleID(), lldb::eAccessPublic, 2322 type_name, clang::TTK_Struct, lldb::eLanguageTypeC); 2323 StartTagDeclarationDefinition(type); 2324 for (const auto &field : type_fields) 2325 AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic, 2326 0); 2327 if (packed) 2328 SetIsPacked(type); 2329 CompleteTagDeclarationDefinition(type); 2330 return type; 2331 } 2332 2333 CompilerType TypeSystemClang::GetOrCreateStructForIdentifier( 2334 llvm::StringRef type_name, 2335 const std::initializer_list<std::pair<const char *, CompilerType>> 2336 &type_fields, 2337 bool packed) { 2338 CompilerType type; 2339 if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid()) 2340 return type; 2341 2342 return CreateStructForIdentifier(type_name, type_fields, packed); 2343 } 2344 2345 #pragma mark Enumeration Types 2346 2347 CompilerType TypeSystemClang::CreateEnumerationType( 2348 llvm::StringRef name, clang::DeclContext *decl_ctx, 2349 OptionalClangModuleID owning_module, const Declaration &decl, 2350 const CompilerType &integer_clang_type, bool is_scoped) { 2351 // TODO: Do something intelligent with the Declaration object passed in 2352 // like maybe filling in the SourceLocation with it... 2353 ASTContext &ast = getASTContext(); 2354 2355 // TODO: ask about these... 2356 // const bool IsFixed = false; 2357 EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, 0); 2358 enum_decl->setDeclContext(decl_ctx); 2359 if (!name.empty()) 2360 enum_decl->setDeclName(&ast.Idents.get(name)); 2361 enum_decl->setScoped(is_scoped); 2362 enum_decl->setScopedUsingClassTag(is_scoped); 2363 enum_decl->setFixed(false); 2364 SetOwningModule(enum_decl, owning_module); 2365 if (decl_ctx) 2366 decl_ctx->addDecl(enum_decl); 2367 2368 // TODO: check if we should be setting the promotion type too? 2369 enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type)); 2370 2371 enum_decl->setAccess(AS_public); // TODO respect what's in the debug info 2372 2373 return GetType(ast.getTagDeclType(enum_decl)); 2374 } 2375 2376 CompilerType TypeSystemClang::GetIntTypeFromBitSize(size_t bit_size, 2377 bool is_signed) { 2378 clang::ASTContext &ast = getASTContext(); 2379 2380 if (is_signed) { 2381 if (bit_size == ast.getTypeSize(ast.SignedCharTy)) 2382 return GetType(ast.SignedCharTy); 2383 2384 if (bit_size == ast.getTypeSize(ast.ShortTy)) 2385 return GetType(ast.ShortTy); 2386 2387 if (bit_size == ast.getTypeSize(ast.IntTy)) 2388 return GetType(ast.IntTy); 2389 2390 if (bit_size == ast.getTypeSize(ast.LongTy)) 2391 return GetType(ast.LongTy); 2392 2393 if (bit_size == ast.getTypeSize(ast.LongLongTy)) 2394 return GetType(ast.LongLongTy); 2395 2396 if (bit_size == ast.getTypeSize(ast.Int128Ty)) 2397 return GetType(ast.Int128Ty); 2398 } else { 2399 if (bit_size == ast.getTypeSize(ast.UnsignedCharTy)) 2400 return GetType(ast.UnsignedCharTy); 2401 2402 if (bit_size == ast.getTypeSize(ast.UnsignedShortTy)) 2403 return GetType(ast.UnsignedShortTy); 2404 2405 if (bit_size == ast.getTypeSize(ast.UnsignedIntTy)) 2406 return GetType(ast.UnsignedIntTy); 2407 2408 if (bit_size == ast.getTypeSize(ast.UnsignedLongTy)) 2409 return GetType(ast.UnsignedLongTy); 2410 2411 if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy)) 2412 return GetType(ast.UnsignedLongLongTy); 2413 2414 if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty)) 2415 return GetType(ast.UnsignedInt128Ty); 2416 } 2417 return CompilerType(); 2418 } 2419 2420 CompilerType TypeSystemClang::GetPointerSizedIntType(bool is_signed) { 2421 return GetIntTypeFromBitSize( 2422 getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed); 2423 } 2424 2425 void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) { 2426 if (decl_ctx) { 2427 DumpDeclContextHiearchy(decl_ctx->getParent()); 2428 2429 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx); 2430 if (named_decl) { 2431 printf("%20s: %s\n", decl_ctx->getDeclKindName(), 2432 named_decl->getDeclName().getAsString().c_str()); 2433 } else { 2434 printf("%20s\n", decl_ctx->getDeclKindName()); 2435 } 2436 } 2437 } 2438 2439 void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) { 2440 if (decl == nullptr) 2441 return; 2442 DumpDeclContextHiearchy(decl->getDeclContext()); 2443 2444 clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl); 2445 if (record_decl) { 2446 printf("%20s: %s%s\n", decl->getDeclKindName(), 2447 record_decl->getDeclName().getAsString().c_str(), 2448 record_decl->isInjectedClassName() ? " (injected class name)" : ""); 2449 2450 } else { 2451 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl); 2452 if (named_decl) { 2453 printf("%20s: %s\n", decl->getDeclKindName(), 2454 named_decl->getDeclName().getAsString().c_str()); 2455 } else { 2456 printf("%20s\n", decl->getDeclKindName()); 2457 } 2458 } 2459 } 2460 2461 bool TypeSystemClang::DeclsAreEquivalent(clang::Decl *lhs_decl, 2462 clang::Decl *rhs_decl) { 2463 if (lhs_decl && rhs_decl) { 2464 // Make sure the decl kinds match first 2465 const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind(); 2466 const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind(); 2467 2468 if (lhs_decl_kind == rhs_decl_kind) { 2469 // Now check that the decl contexts kinds are all equivalent before we 2470 // have to check any names of the decl contexts... 2471 clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext(); 2472 clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext(); 2473 if (lhs_decl_ctx && rhs_decl_ctx) { 2474 while (true) { 2475 if (lhs_decl_ctx && rhs_decl_ctx) { 2476 const clang::Decl::Kind lhs_decl_ctx_kind = 2477 lhs_decl_ctx->getDeclKind(); 2478 const clang::Decl::Kind rhs_decl_ctx_kind = 2479 rhs_decl_ctx->getDeclKind(); 2480 if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) { 2481 lhs_decl_ctx = lhs_decl_ctx->getParent(); 2482 rhs_decl_ctx = rhs_decl_ctx->getParent(); 2483 2484 if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr) 2485 break; 2486 } else 2487 return false; 2488 } else 2489 return false; 2490 } 2491 2492 // Now make sure the name of the decls match 2493 clang::NamedDecl *lhs_named_decl = 2494 llvm::dyn_cast<clang::NamedDecl>(lhs_decl); 2495 clang::NamedDecl *rhs_named_decl = 2496 llvm::dyn_cast<clang::NamedDecl>(rhs_decl); 2497 if (lhs_named_decl && rhs_named_decl) { 2498 clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName(); 2499 clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName(); 2500 if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) { 2501 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString()) 2502 return false; 2503 } else 2504 return false; 2505 } else 2506 return false; 2507 2508 // We know that the decl context kinds all match, so now we need to 2509 // make sure the names match as well 2510 lhs_decl_ctx = lhs_decl->getDeclContext(); 2511 rhs_decl_ctx = rhs_decl->getDeclContext(); 2512 while (true) { 2513 switch (lhs_decl_ctx->getDeclKind()) { 2514 case clang::Decl::TranslationUnit: 2515 // We don't care about the translation unit names 2516 return true; 2517 default: { 2518 clang::NamedDecl *lhs_named_decl = 2519 llvm::dyn_cast<clang::NamedDecl>(lhs_decl_ctx); 2520 clang::NamedDecl *rhs_named_decl = 2521 llvm::dyn_cast<clang::NamedDecl>(rhs_decl_ctx); 2522 if (lhs_named_decl && rhs_named_decl) { 2523 clang::DeclarationName lhs_decl_name = 2524 lhs_named_decl->getDeclName(); 2525 clang::DeclarationName rhs_decl_name = 2526 rhs_named_decl->getDeclName(); 2527 if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) { 2528 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString()) 2529 return false; 2530 } else 2531 return false; 2532 } else 2533 return false; 2534 } break; 2535 } 2536 lhs_decl_ctx = lhs_decl_ctx->getParent(); 2537 rhs_decl_ctx = rhs_decl_ctx->getParent(); 2538 } 2539 } 2540 } 2541 } 2542 return false; 2543 } 2544 bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast, 2545 clang::Decl *decl) { 2546 if (!decl) 2547 return false; 2548 2549 ExternalASTSource *ast_source = ast->getExternalSource(); 2550 2551 if (!ast_source) 2552 return false; 2553 2554 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) { 2555 if (tag_decl->isCompleteDefinition()) 2556 return true; 2557 2558 if (!tag_decl->hasExternalLexicalStorage()) 2559 return false; 2560 2561 ast_source->CompleteType(tag_decl); 2562 2563 return !tag_decl->getTypeForDecl()->isIncompleteType(); 2564 } else if (clang::ObjCInterfaceDecl *objc_interface_decl = 2565 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) { 2566 if (objc_interface_decl->getDefinition()) 2567 return true; 2568 2569 if (!objc_interface_decl->hasExternalLexicalStorage()) 2570 return false; 2571 2572 ast_source->CompleteType(objc_interface_decl); 2573 2574 return !objc_interface_decl->getTypeForDecl()->isIncompleteType(); 2575 } else { 2576 return false; 2577 } 2578 } 2579 2580 void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl, 2581 user_id_t user_id) { 2582 ClangASTMetadata meta_data; 2583 meta_data.SetUserID(user_id); 2584 SetMetadata(decl, meta_data); 2585 } 2586 2587 void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type, 2588 user_id_t user_id) { 2589 ClangASTMetadata meta_data; 2590 meta_data.SetUserID(user_id); 2591 SetMetadata(type, meta_data); 2592 } 2593 2594 void TypeSystemClang::SetMetadata(const clang::Decl *object, 2595 ClangASTMetadata &metadata) { 2596 m_decl_metadata[object] = metadata; 2597 } 2598 2599 void TypeSystemClang::SetMetadata(const clang::Type *object, 2600 ClangASTMetadata &metadata) { 2601 m_type_metadata[object] = metadata; 2602 } 2603 2604 ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Decl *object) { 2605 auto It = m_decl_metadata.find(object); 2606 if (It != m_decl_metadata.end()) 2607 return &It->second; 2608 return nullptr; 2609 } 2610 2611 ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Type *object) { 2612 auto It = m_type_metadata.find(object); 2613 if (It != m_type_metadata.end()) 2614 return &It->second; 2615 return nullptr; 2616 } 2617 2618 void TypeSystemClang::SetCXXRecordDeclAccess(const clang::CXXRecordDecl *object, 2619 clang::AccessSpecifier access) { 2620 if (access == clang::AccessSpecifier::AS_none) 2621 m_cxx_record_decl_access.erase(object); 2622 else 2623 m_cxx_record_decl_access[object] = access; 2624 } 2625 2626 clang::AccessSpecifier 2627 TypeSystemClang::GetCXXRecordDeclAccess(const clang::CXXRecordDecl *object) { 2628 auto It = m_cxx_record_decl_access.find(object); 2629 if (It != m_cxx_record_decl_access.end()) 2630 return It->second; 2631 return clang::AccessSpecifier::AS_none; 2632 } 2633 2634 clang::DeclContext * 2635 TypeSystemClang::GetDeclContextForType(const CompilerType &type) { 2636 return GetDeclContextForType(ClangUtil::GetQualType(type)); 2637 } 2638 2639 /// Aggressively desugar the provided type, skipping past various kinds of 2640 /// syntactic sugar and other constructs one typically wants to ignore. 2641 /// The \p mask argument allows one to skip certain kinds of simplifications, 2642 /// when one wishes to handle a certain kind of type directly. 2643 static QualType 2644 RemoveWrappingTypes(QualType type, ArrayRef<clang::Type::TypeClass> mask = {}) { 2645 while (true) { 2646 if (find(mask, type->getTypeClass()) != mask.end()) 2647 return type; 2648 switch (type->getTypeClass()) { 2649 // This is not fully correct as _Atomic is more than sugar, but it is 2650 // sufficient for the purposes we care about. 2651 case clang::Type::Atomic: 2652 type = cast<clang::AtomicType>(type)->getValueType(); 2653 break; 2654 case clang::Type::Auto: 2655 case clang::Type::Decltype: 2656 case clang::Type::Elaborated: 2657 case clang::Type::Paren: 2658 case clang::Type::SubstTemplateTypeParm: 2659 case clang::Type::TemplateSpecialization: 2660 case clang::Type::Typedef: 2661 case clang::Type::TypeOf: 2662 case clang::Type::TypeOfExpr: 2663 case clang::Type::Using: 2664 type = type->getLocallyUnqualifiedSingleStepDesugaredType(); 2665 break; 2666 default: 2667 return type; 2668 } 2669 } 2670 } 2671 2672 clang::DeclContext * 2673 TypeSystemClang::GetDeclContextForType(clang::QualType type) { 2674 if (type.isNull()) 2675 return nullptr; 2676 2677 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType()); 2678 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 2679 switch (type_class) { 2680 case clang::Type::ObjCInterface: 2681 return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr()) 2682 ->getInterface(); 2683 case clang::Type::ObjCObjectPointer: 2684 return GetDeclContextForType( 2685 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr()) 2686 ->getPointeeType()); 2687 case clang::Type::Record: 2688 return llvm::cast<clang::RecordType>(qual_type)->getDecl(); 2689 case clang::Type::Enum: 2690 return llvm::cast<clang::EnumType>(qual_type)->getDecl(); 2691 default: 2692 break; 2693 } 2694 // No DeclContext in this type... 2695 return nullptr; 2696 } 2697 2698 static bool GetCompleteQualType(clang::ASTContext *ast, 2699 clang::QualType qual_type, 2700 bool allow_completion = true) { 2701 qual_type = RemoveWrappingTypes(qual_type); 2702 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 2703 switch (type_class) { 2704 case clang::Type::ConstantArray: 2705 case clang::Type::IncompleteArray: 2706 case clang::Type::VariableArray: { 2707 const clang::ArrayType *array_type = 2708 llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr()); 2709 2710 if (array_type) 2711 return GetCompleteQualType(ast, array_type->getElementType(), 2712 allow_completion); 2713 } break; 2714 case clang::Type::Record: { 2715 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); 2716 if (cxx_record_decl) { 2717 if (cxx_record_decl->hasExternalLexicalStorage()) { 2718 const bool is_complete = cxx_record_decl->isCompleteDefinition(); 2719 const bool fields_loaded = 2720 cxx_record_decl->hasLoadedFieldsFromExternalStorage(); 2721 if (is_complete && fields_loaded) 2722 return true; 2723 2724 if (!allow_completion) 2725 return false; 2726 2727 // Call the field_begin() accessor to for it to use the external source 2728 // to load the fields... 2729 clang::ExternalASTSource *external_ast_source = 2730 ast->getExternalSource(); 2731 if (external_ast_source) { 2732 external_ast_source->CompleteType(cxx_record_decl); 2733 if (cxx_record_decl->isCompleteDefinition()) { 2734 cxx_record_decl->field_begin(); 2735 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true); 2736 } 2737 } 2738 } 2739 } 2740 const clang::TagType *tag_type = 2741 llvm::cast<clang::TagType>(qual_type.getTypePtr()); 2742 return !tag_type->isIncompleteType(); 2743 } break; 2744 2745 case clang::Type::Enum: { 2746 const clang::TagType *tag_type = 2747 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr()); 2748 if (tag_type) { 2749 clang::TagDecl *tag_decl = tag_type->getDecl(); 2750 if (tag_decl) { 2751 if (tag_decl->getDefinition()) 2752 return true; 2753 2754 if (!allow_completion) 2755 return false; 2756 2757 if (tag_decl->hasExternalLexicalStorage()) { 2758 if (ast) { 2759 clang::ExternalASTSource *external_ast_source = 2760 ast->getExternalSource(); 2761 if (external_ast_source) { 2762 external_ast_source->CompleteType(tag_decl); 2763 return !tag_type->isIncompleteType(); 2764 } 2765 } 2766 } 2767 return false; 2768 } 2769 } 2770 2771 } break; 2772 case clang::Type::ObjCObject: 2773 case clang::Type::ObjCInterface: { 2774 const clang::ObjCObjectType *objc_class_type = 2775 llvm::dyn_cast<clang::ObjCObjectType>(qual_type); 2776 if (objc_class_type) { 2777 clang::ObjCInterfaceDecl *class_interface_decl = 2778 objc_class_type->getInterface(); 2779 // We currently can't complete objective C types through the newly added 2780 // ASTContext because it only supports TagDecl objects right now... 2781 if (class_interface_decl) { 2782 if (class_interface_decl->getDefinition()) 2783 return true; 2784 2785 if (!allow_completion) 2786 return false; 2787 2788 if (class_interface_decl->hasExternalLexicalStorage()) { 2789 if (ast) { 2790 clang::ExternalASTSource *external_ast_source = 2791 ast->getExternalSource(); 2792 if (external_ast_source) { 2793 external_ast_source->CompleteType(class_interface_decl); 2794 return !objc_class_type->isIncompleteType(); 2795 } 2796 } 2797 } 2798 return false; 2799 } 2800 } 2801 } break; 2802 2803 case clang::Type::Attributed: 2804 return GetCompleteQualType( 2805 ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(), 2806 allow_completion); 2807 2808 default: 2809 break; 2810 } 2811 2812 return true; 2813 } 2814 2815 static clang::ObjCIvarDecl::AccessControl 2816 ConvertAccessTypeToObjCIvarAccessControl(AccessType access) { 2817 switch (access) { 2818 case eAccessNone: 2819 return clang::ObjCIvarDecl::None; 2820 case eAccessPublic: 2821 return clang::ObjCIvarDecl::Public; 2822 case eAccessPrivate: 2823 return clang::ObjCIvarDecl::Private; 2824 case eAccessProtected: 2825 return clang::ObjCIvarDecl::Protected; 2826 case eAccessPackage: 2827 return clang::ObjCIvarDecl::Package; 2828 } 2829 return clang::ObjCIvarDecl::None; 2830 } 2831 2832 // Tests 2833 2834 #ifndef NDEBUG 2835 bool TypeSystemClang::Verify(lldb::opaque_compiler_type_t type) { 2836 return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr()); 2837 } 2838 #endif 2839 2840 bool TypeSystemClang::IsAggregateType(lldb::opaque_compiler_type_t type) { 2841 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); 2842 2843 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 2844 switch (type_class) { 2845 case clang::Type::IncompleteArray: 2846 case clang::Type::VariableArray: 2847 case clang::Type::ConstantArray: 2848 case clang::Type::ExtVector: 2849 case clang::Type::Vector: 2850 case clang::Type::Record: 2851 case clang::Type::ObjCObject: 2852 case clang::Type::ObjCInterface: 2853 return true; 2854 default: 2855 break; 2856 } 2857 // The clang type does have a value 2858 return false; 2859 } 2860 2861 bool TypeSystemClang::IsAnonymousType(lldb::opaque_compiler_type_t type) { 2862 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); 2863 2864 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 2865 switch (type_class) { 2866 case clang::Type::Record: { 2867 if (const clang::RecordType *record_type = 2868 llvm::dyn_cast_or_null<clang::RecordType>( 2869 qual_type.getTypePtrOrNull())) { 2870 if (const clang::RecordDecl *record_decl = record_type->getDecl()) { 2871 return record_decl->isAnonymousStructOrUnion(); 2872 } 2873 } 2874 break; 2875 } 2876 default: 2877 break; 2878 } 2879 // The clang type does have a value 2880 return false; 2881 } 2882 2883 bool TypeSystemClang::IsArrayType(lldb::opaque_compiler_type_t type, 2884 CompilerType *element_type_ptr, 2885 uint64_t *size, bool *is_incomplete) { 2886 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); 2887 2888 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 2889 switch (type_class) { 2890 default: 2891 break; 2892 2893 case clang::Type::ConstantArray: 2894 if (element_type_ptr) 2895 element_type_ptr->SetCompilerType( 2896 weak_from_this(), llvm::cast<clang::ConstantArrayType>(qual_type) 2897 ->getElementType() 2898 .getAsOpaquePtr()); 2899 if (size) 2900 *size = llvm::cast<clang::ConstantArrayType>(qual_type) 2901 ->getSize() 2902 .getLimitedValue(ULLONG_MAX); 2903 if (is_incomplete) 2904 *is_incomplete = false; 2905 return true; 2906 2907 case clang::Type::IncompleteArray: 2908 if (element_type_ptr) 2909 element_type_ptr->SetCompilerType( 2910 weak_from_this(), llvm::cast<clang::IncompleteArrayType>(qual_type) 2911 ->getElementType() 2912 .getAsOpaquePtr()); 2913 if (size) 2914 *size = 0; 2915 if (is_incomplete) 2916 *is_incomplete = true; 2917 return true; 2918 2919 case clang::Type::VariableArray: 2920 if (element_type_ptr) 2921 element_type_ptr->SetCompilerType( 2922 weak_from_this(), llvm::cast<clang::VariableArrayType>(qual_type) 2923 ->getElementType() 2924 .getAsOpaquePtr()); 2925 if (size) 2926 *size = 0; 2927 if (is_incomplete) 2928 *is_incomplete = false; 2929 return true; 2930 2931 case clang::Type::DependentSizedArray: 2932 if (element_type_ptr) 2933 element_type_ptr->SetCompilerType( 2934 weak_from_this(), 2935 llvm::cast<clang::DependentSizedArrayType>(qual_type) 2936 ->getElementType() 2937 .getAsOpaquePtr()); 2938 if (size) 2939 *size = 0; 2940 if (is_incomplete) 2941 *is_incomplete = false; 2942 return true; 2943 } 2944 if (element_type_ptr) 2945 element_type_ptr->Clear(); 2946 if (size) 2947 *size = 0; 2948 if (is_incomplete) 2949 *is_incomplete = false; 2950 return false; 2951 } 2952 2953 bool TypeSystemClang::IsVectorType(lldb::opaque_compiler_type_t type, 2954 CompilerType *element_type, uint64_t *size) { 2955 clang::QualType qual_type(GetCanonicalQualType(type)); 2956 2957 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 2958 switch (type_class) { 2959 case clang::Type::Vector: { 2960 const clang::VectorType *vector_type = 2961 qual_type->getAs<clang::VectorType>(); 2962 if (vector_type) { 2963 if (size) 2964 *size = vector_type->getNumElements(); 2965 if (element_type) 2966 *element_type = GetType(vector_type->getElementType()); 2967 } 2968 return true; 2969 } break; 2970 case clang::Type::ExtVector: { 2971 const clang::ExtVectorType *ext_vector_type = 2972 qual_type->getAs<clang::ExtVectorType>(); 2973 if (ext_vector_type) { 2974 if (size) 2975 *size = ext_vector_type->getNumElements(); 2976 if (element_type) 2977 *element_type = 2978 CompilerType(weak_from_this(), 2979 ext_vector_type->getElementType().getAsOpaquePtr()); 2980 } 2981 return true; 2982 } 2983 default: 2984 break; 2985 } 2986 return false; 2987 } 2988 2989 bool TypeSystemClang::IsRuntimeGeneratedType( 2990 lldb::opaque_compiler_type_t type) { 2991 clang::DeclContext *decl_ctx = GetDeclContextForType(GetQualType(type)); 2992 if (!decl_ctx) 2993 return false; 2994 2995 if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx)) 2996 return false; 2997 2998 clang::ObjCInterfaceDecl *result_iface_decl = 2999 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx); 3000 3001 ClangASTMetadata *ast_metadata = GetMetadata(result_iface_decl); 3002 if (!ast_metadata) 3003 return false; 3004 return (ast_metadata->GetISAPtr() != 0); 3005 } 3006 3007 bool TypeSystemClang::IsCharType(lldb::opaque_compiler_type_t type) { 3008 return GetQualType(type).getUnqualifiedType()->isCharType(); 3009 } 3010 3011 bool TypeSystemClang::IsCompleteType(lldb::opaque_compiler_type_t type) { 3012 // If the type hasn't been lazily completed yet, complete it now so that we 3013 // can give the caller an accurate answer whether the type actually has a 3014 // definition. Without completing the type now we would just tell the user 3015 // the current (internal) completeness state of the type and most users don't 3016 // care (or even know) about this behavior. 3017 const bool allow_completion = true; 3018 return GetCompleteQualType(&getASTContext(), GetQualType(type), 3019 allow_completion); 3020 } 3021 3022 bool TypeSystemClang::IsConst(lldb::opaque_compiler_type_t type) { 3023 return GetQualType(type).isConstQualified(); 3024 } 3025 3026 bool TypeSystemClang::IsCStringType(lldb::opaque_compiler_type_t type, 3027 uint32_t &length) { 3028 CompilerType pointee_or_element_clang_type; 3029 length = 0; 3030 Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type)); 3031 3032 if (!pointee_or_element_clang_type.IsValid()) 3033 return false; 3034 3035 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) { 3036 if (pointee_or_element_clang_type.IsCharType()) { 3037 if (type_flags.Test(eTypeIsArray)) { 3038 // We know the size of the array and it could be a C string since it is 3039 // an array of characters 3040 length = llvm::cast<clang::ConstantArrayType>( 3041 GetCanonicalQualType(type).getTypePtr()) 3042 ->getSize() 3043 .getLimitedValue(); 3044 } 3045 return true; 3046 } 3047 } 3048 return false; 3049 } 3050 3051 bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) { 3052 auto isFunctionType = [&](clang::QualType qual_type) { 3053 return qual_type->isFunctionType(); 3054 }; 3055 3056 return IsTypeImpl(type, isFunctionType); 3057 } 3058 3059 // Used to detect "Homogeneous Floating-point Aggregates" 3060 uint32_t 3061 TypeSystemClang::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type, 3062 CompilerType *base_type_ptr) { 3063 if (!type) 3064 return 0; 3065 3066 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); 3067 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3068 switch (type_class) { 3069 case clang::Type::Record: 3070 if (GetCompleteType(type)) { 3071 const clang::CXXRecordDecl *cxx_record_decl = 3072 qual_type->getAsCXXRecordDecl(); 3073 if (cxx_record_decl) { 3074 if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass()) 3075 return 0; 3076 } 3077 const clang::RecordType *record_type = 3078 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 3079 if (record_type) { 3080 const clang::RecordDecl *record_decl = record_type->getDecl(); 3081 if (record_decl) { 3082 // We are looking for a structure that contains only floating point 3083 // types 3084 clang::RecordDecl::field_iterator field_pos, 3085 field_end = record_decl->field_end(); 3086 uint32_t num_fields = 0; 3087 bool is_hva = false; 3088 bool is_hfa = false; 3089 clang::QualType base_qual_type; 3090 uint64_t base_bitwidth = 0; 3091 for (field_pos = record_decl->field_begin(); field_pos != field_end; 3092 ++field_pos) { 3093 clang::QualType field_qual_type = field_pos->getType(); 3094 uint64_t field_bitwidth = getASTContext().getTypeSize(qual_type); 3095 if (field_qual_type->isFloatingType()) { 3096 if (field_qual_type->isComplexType()) 3097 return 0; 3098 else { 3099 if (num_fields == 0) 3100 base_qual_type = field_qual_type; 3101 else { 3102 if (is_hva) 3103 return 0; 3104 is_hfa = true; 3105 if (field_qual_type.getTypePtr() != 3106 base_qual_type.getTypePtr()) 3107 return 0; 3108 } 3109 } 3110 } else if (field_qual_type->isVectorType() || 3111 field_qual_type->isExtVectorType()) { 3112 if (num_fields == 0) { 3113 base_qual_type = field_qual_type; 3114 base_bitwidth = field_bitwidth; 3115 } else { 3116 if (is_hfa) 3117 return 0; 3118 is_hva = true; 3119 if (base_bitwidth != field_bitwidth) 3120 return 0; 3121 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr()) 3122 return 0; 3123 } 3124 } else 3125 return 0; 3126 ++num_fields; 3127 } 3128 if (base_type_ptr) 3129 *base_type_ptr = 3130 CompilerType(weak_from_this(), base_qual_type.getAsOpaquePtr()); 3131 return num_fields; 3132 } 3133 } 3134 } 3135 break; 3136 3137 default: 3138 break; 3139 } 3140 return 0; 3141 } 3142 3143 size_t TypeSystemClang::GetNumberOfFunctionArguments( 3144 lldb::opaque_compiler_type_t type) { 3145 if (type) { 3146 clang::QualType qual_type(GetCanonicalQualType(type)); 3147 const clang::FunctionProtoType *func = 3148 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr()); 3149 if (func) 3150 return func->getNumParams(); 3151 } 3152 return 0; 3153 } 3154 3155 CompilerType 3156 TypeSystemClang::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type, 3157 const size_t index) { 3158 if (type) { 3159 clang::QualType qual_type(GetQualType(type)); 3160 const clang::FunctionProtoType *func = 3161 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr()); 3162 if (func) { 3163 if (index < func->getNumParams()) 3164 return CompilerType(weak_from_this(), func->getParamType(index).getAsOpaquePtr()); 3165 } 3166 } 3167 return CompilerType(); 3168 } 3169 3170 bool TypeSystemClang::IsTypeImpl( 3171 lldb::opaque_compiler_type_t type, 3172 llvm::function_ref<bool(clang::QualType)> predicate) const { 3173 if (type) { 3174 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 3175 3176 if (predicate(qual_type)) 3177 return true; 3178 3179 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3180 switch (type_class) { 3181 default: 3182 break; 3183 3184 case clang::Type::LValueReference: 3185 case clang::Type::RValueReference: { 3186 const clang::ReferenceType *reference_type = 3187 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr()); 3188 if (reference_type) 3189 return IsTypeImpl(reference_type->getPointeeType().getAsOpaquePtr(), predicate); 3190 } break; 3191 } 3192 } 3193 return false; 3194 } 3195 3196 bool TypeSystemClang::IsMemberFunctionPointerType( 3197 lldb::opaque_compiler_type_t type) { 3198 auto isMemberFunctionPointerType = [](clang::QualType qual_type) { 3199 return qual_type->isMemberFunctionPointerType(); 3200 }; 3201 3202 return IsTypeImpl(type, isMemberFunctionPointerType); 3203 } 3204 3205 bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) { 3206 auto isFunctionPointerType = [](clang::QualType qual_type) { 3207 return qual_type->isFunctionPointerType(); 3208 }; 3209 3210 return IsTypeImpl(type, isFunctionPointerType); 3211 } 3212 3213 bool TypeSystemClang::IsBlockPointerType( 3214 lldb::opaque_compiler_type_t type, 3215 CompilerType *function_pointer_type_ptr) { 3216 auto isBlockPointerType = [&](clang::QualType qual_type) { 3217 if (qual_type->isBlockPointerType()) { 3218 if (function_pointer_type_ptr) { 3219 const clang::BlockPointerType *block_pointer_type = 3220 qual_type->castAs<clang::BlockPointerType>(); 3221 QualType pointee_type = block_pointer_type->getPointeeType(); 3222 QualType function_pointer_type = m_ast_up->getPointerType(pointee_type); 3223 *function_pointer_type_ptr = CompilerType( 3224 weak_from_this(), function_pointer_type.getAsOpaquePtr()); 3225 } 3226 return true; 3227 } 3228 3229 return false; 3230 }; 3231 3232 return IsTypeImpl(type, isBlockPointerType); 3233 } 3234 3235 bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type, 3236 bool &is_signed) { 3237 if (!type) 3238 return false; 3239 3240 clang::QualType qual_type(GetCanonicalQualType(type)); 3241 const clang::BuiltinType *builtin_type = 3242 llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal()); 3243 3244 if (builtin_type) { 3245 if (builtin_type->isInteger()) { 3246 is_signed = builtin_type->isSignedInteger(); 3247 return true; 3248 } 3249 } 3250 3251 return false; 3252 } 3253 3254 bool TypeSystemClang::IsEnumerationType(lldb::opaque_compiler_type_t type, 3255 bool &is_signed) { 3256 if (type) { 3257 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>( 3258 GetCanonicalQualType(type)->getCanonicalTypeInternal()); 3259 3260 if (enum_type) { 3261 IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(), 3262 is_signed); 3263 return true; 3264 } 3265 } 3266 3267 return false; 3268 } 3269 3270 bool TypeSystemClang::IsScopedEnumerationType( 3271 lldb::opaque_compiler_type_t type) { 3272 if (type) { 3273 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>( 3274 GetCanonicalQualType(type)->getCanonicalTypeInternal()); 3275 3276 if (enum_type) { 3277 return enum_type->isScopedEnumeralType(); 3278 } 3279 } 3280 3281 return false; 3282 } 3283 3284 bool TypeSystemClang::IsPointerType(lldb::opaque_compiler_type_t type, 3285 CompilerType *pointee_type) { 3286 if (type) { 3287 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 3288 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3289 switch (type_class) { 3290 case clang::Type::Builtin: 3291 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) { 3292 default: 3293 break; 3294 case clang::BuiltinType::ObjCId: 3295 case clang::BuiltinType::ObjCClass: 3296 return true; 3297 } 3298 return false; 3299 case clang::Type::ObjCObjectPointer: 3300 if (pointee_type) 3301 pointee_type->SetCompilerType( 3302 weak_from_this(), 3303 llvm::cast<clang::ObjCObjectPointerType>(qual_type) 3304 ->getPointeeType() 3305 .getAsOpaquePtr()); 3306 return true; 3307 case clang::Type::BlockPointer: 3308 if (pointee_type) 3309 pointee_type->SetCompilerType( 3310 weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type) 3311 ->getPointeeType() 3312 .getAsOpaquePtr()); 3313 return true; 3314 case clang::Type::Pointer: 3315 if (pointee_type) 3316 pointee_type->SetCompilerType(weak_from_this(), 3317 llvm::cast<clang::PointerType>(qual_type) 3318 ->getPointeeType() 3319 .getAsOpaquePtr()); 3320 return true; 3321 case clang::Type::MemberPointer: 3322 if (pointee_type) 3323 pointee_type->SetCompilerType( 3324 weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type) 3325 ->getPointeeType() 3326 .getAsOpaquePtr()); 3327 return true; 3328 default: 3329 break; 3330 } 3331 } 3332 if (pointee_type) 3333 pointee_type->Clear(); 3334 return false; 3335 } 3336 3337 bool TypeSystemClang::IsPointerOrReferenceType( 3338 lldb::opaque_compiler_type_t type, CompilerType *pointee_type) { 3339 if (type) { 3340 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 3341 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3342 switch (type_class) { 3343 case clang::Type::Builtin: 3344 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) { 3345 default: 3346 break; 3347 case clang::BuiltinType::ObjCId: 3348 case clang::BuiltinType::ObjCClass: 3349 return true; 3350 } 3351 return false; 3352 case clang::Type::ObjCObjectPointer: 3353 if (pointee_type) 3354 pointee_type->SetCompilerType( 3355 weak_from_this(), 3356 llvm::cast<clang::ObjCObjectPointerType>(qual_type) 3357 ->getPointeeType() 3358 .getAsOpaquePtr()); 3359 return true; 3360 case clang::Type::BlockPointer: 3361 if (pointee_type) 3362 pointee_type->SetCompilerType( 3363 weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type) 3364 ->getPointeeType() 3365 .getAsOpaquePtr()); 3366 return true; 3367 case clang::Type::Pointer: 3368 if (pointee_type) 3369 pointee_type->SetCompilerType(weak_from_this(), 3370 llvm::cast<clang::PointerType>(qual_type) 3371 ->getPointeeType() 3372 .getAsOpaquePtr()); 3373 return true; 3374 case clang::Type::MemberPointer: 3375 if (pointee_type) 3376 pointee_type->SetCompilerType( 3377 weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type) 3378 ->getPointeeType() 3379 .getAsOpaquePtr()); 3380 return true; 3381 case clang::Type::LValueReference: 3382 if (pointee_type) 3383 pointee_type->SetCompilerType( 3384 weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type) 3385 ->desugar() 3386 .getAsOpaquePtr()); 3387 return true; 3388 case clang::Type::RValueReference: 3389 if (pointee_type) 3390 pointee_type->SetCompilerType( 3391 weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type) 3392 ->desugar() 3393 .getAsOpaquePtr()); 3394 return true; 3395 default: 3396 break; 3397 } 3398 } 3399 if (pointee_type) 3400 pointee_type->Clear(); 3401 return false; 3402 } 3403 3404 bool TypeSystemClang::IsReferenceType(lldb::opaque_compiler_type_t type, 3405 CompilerType *pointee_type, 3406 bool *is_rvalue) { 3407 if (type) { 3408 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 3409 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3410 3411 switch (type_class) { 3412 case clang::Type::LValueReference: 3413 if (pointee_type) 3414 pointee_type->SetCompilerType( 3415 weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type) 3416 ->desugar() 3417 .getAsOpaquePtr()); 3418 if (is_rvalue) 3419 *is_rvalue = false; 3420 return true; 3421 case clang::Type::RValueReference: 3422 if (pointee_type) 3423 pointee_type->SetCompilerType( 3424 weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type) 3425 ->desugar() 3426 .getAsOpaquePtr()); 3427 if (is_rvalue) 3428 *is_rvalue = true; 3429 return true; 3430 3431 default: 3432 break; 3433 } 3434 } 3435 if (pointee_type) 3436 pointee_type->Clear(); 3437 return false; 3438 } 3439 3440 bool TypeSystemClang::IsFloatingPointType(lldb::opaque_compiler_type_t type, 3441 uint32_t &count, bool &is_complex) { 3442 if (type) { 3443 clang::QualType qual_type(GetCanonicalQualType(type)); 3444 3445 if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>( 3446 qual_type->getCanonicalTypeInternal())) { 3447 clang::BuiltinType::Kind kind = BT->getKind(); 3448 if (kind >= clang::BuiltinType::Float && 3449 kind <= clang::BuiltinType::LongDouble) { 3450 count = 1; 3451 is_complex = false; 3452 return true; 3453 } 3454 } else if (const clang::ComplexType *CT = 3455 llvm::dyn_cast<clang::ComplexType>( 3456 qual_type->getCanonicalTypeInternal())) { 3457 if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, 3458 is_complex)) { 3459 count = 2; 3460 is_complex = true; 3461 return true; 3462 } 3463 } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>( 3464 qual_type->getCanonicalTypeInternal())) { 3465 if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, 3466 is_complex)) { 3467 count = VT->getNumElements(); 3468 is_complex = false; 3469 return true; 3470 } 3471 } 3472 } 3473 count = 0; 3474 is_complex = false; 3475 return false; 3476 } 3477 3478 bool TypeSystemClang::IsDefined(lldb::opaque_compiler_type_t type) { 3479 if (!type) 3480 return false; 3481 3482 clang::QualType qual_type(GetQualType(type)); 3483 const clang::TagType *tag_type = 3484 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr()); 3485 if (tag_type) { 3486 clang::TagDecl *tag_decl = tag_type->getDecl(); 3487 if (tag_decl) 3488 return tag_decl->isCompleteDefinition(); 3489 return false; 3490 } else { 3491 const clang::ObjCObjectType *objc_class_type = 3492 llvm::dyn_cast<clang::ObjCObjectType>(qual_type); 3493 if (objc_class_type) { 3494 clang::ObjCInterfaceDecl *class_interface_decl = 3495 objc_class_type->getInterface(); 3496 if (class_interface_decl) 3497 return class_interface_decl->getDefinition() != nullptr; 3498 return false; 3499 } 3500 } 3501 return true; 3502 } 3503 3504 bool TypeSystemClang::IsObjCClassType(const CompilerType &type) { 3505 if (ClangUtil::IsClangType(type)) { 3506 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type)); 3507 3508 const clang::ObjCObjectPointerType *obj_pointer_type = 3509 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type); 3510 3511 if (obj_pointer_type) 3512 return obj_pointer_type->isObjCClassType(); 3513 } 3514 return false; 3515 } 3516 3517 bool TypeSystemClang::IsObjCObjectOrInterfaceType(const CompilerType &type) { 3518 if (ClangUtil::IsClangType(type)) 3519 return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType(); 3520 return false; 3521 } 3522 3523 bool TypeSystemClang::IsClassType(lldb::opaque_compiler_type_t type) { 3524 if (!type) 3525 return false; 3526 clang::QualType qual_type(GetCanonicalQualType(type)); 3527 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3528 return (type_class == clang::Type::Record); 3529 } 3530 3531 bool TypeSystemClang::IsEnumType(lldb::opaque_compiler_type_t type) { 3532 if (!type) 3533 return false; 3534 clang::QualType qual_type(GetCanonicalQualType(type)); 3535 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3536 return (type_class == clang::Type::Enum); 3537 } 3538 3539 bool TypeSystemClang::IsPolymorphicClass(lldb::opaque_compiler_type_t type) { 3540 if (type) { 3541 clang::QualType qual_type(GetCanonicalQualType(type)); 3542 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3543 switch (type_class) { 3544 case clang::Type::Record: 3545 if (GetCompleteType(type)) { 3546 const clang::RecordType *record_type = 3547 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 3548 const clang::RecordDecl *record_decl = record_type->getDecl(); 3549 if (record_decl) { 3550 const clang::CXXRecordDecl *cxx_record_decl = 3551 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 3552 if (cxx_record_decl) 3553 return cxx_record_decl->isPolymorphic(); 3554 } 3555 } 3556 break; 3557 3558 default: 3559 break; 3560 } 3561 } 3562 return false; 3563 } 3564 3565 bool TypeSystemClang::IsPossibleDynamicType(lldb::opaque_compiler_type_t type, 3566 CompilerType *dynamic_pointee_type, 3567 bool check_cplusplus, 3568 bool check_objc) { 3569 clang::QualType pointee_qual_type; 3570 if (type) { 3571 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 3572 bool success = false; 3573 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3574 switch (type_class) { 3575 case clang::Type::Builtin: 3576 if (check_objc && 3577 llvm::cast<clang::BuiltinType>(qual_type)->getKind() == 3578 clang::BuiltinType::ObjCId) { 3579 if (dynamic_pointee_type) 3580 dynamic_pointee_type->SetCompilerType(weak_from_this(), type); 3581 return true; 3582 } 3583 break; 3584 3585 case clang::Type::ObjCObjectPointer: 3586 if (check_objc) { 3587 if (const auto *objc_pointee_type = 3588 qual_type->getPointeeType().getTypePtrOrNull()) { 3589 if (const auto *objc_object_type = 3590 llvm::dyn_cast_or_null<clang::ObjCObjectType>( 3591 objc_pointee_type)) { 3592 if (objc_object_type->isObjCClass()) 3593 return false; 3594 } 3595 } 3596 if (dynamic_pointee_type) 3597 dynamic_pointee_type->SetCompilerType( 3598 weak_from_this(), 3599 llvm::cast<clang::ObjCObjectPointerType>(qual_type) 3600 ->getPointeeType() 3601 .getAsOpaquePtr()); 3602 return true; 3603 } 3604 break; 3605 3606 case clang::Type::Pointer: 3607 pointee_qual_type = 3608 llvm::cast<clang::PointerType>(qual_type)->getPointeeType(); 3609 success = true; 3610 break; 3611 3612 case clang::Type::LValueReference: 3613 case clang::Type::RValueReference: 3614 pointee_qual_type = 3615 llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType(); 3616 success = true; 3617 break; 3618 3619 default: 3620 break; 3621 } 3622 3623 if (success) { 3624 // Check to make sure what we are pointing too is a possible dynamic C++ 3625 // type We currently accept any "void *" (in case we have a class that 3626 // has been watered down to an opaque pointer) and virtual C++ classes. 3627 const clang::Type::TypeClass pointee_type_class = 3628 pointee_qual_type.getCanonicalType()->getTypeClass(); 3629 switch (pointee_type_class) { 3630 case clang::Type::Builtin: 3631 switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) { 3632 case clang::BuiltinType::UnknownAny: 3633 case clang::BuiltinType::Void: 3634 if (dynamic_pointee_type) 3635 dynamic_pointee_type->SetCompilerType( 3636 weak_from_this(), pointee_qual_type.getAsOpaquePtr()); 3637 return true; 3638 default: 3639 break; 3640 } 3641 break; 3642 3643 case clang::Type::Record: 3644 if (check_cplusplus) { 3645 clang::CXXRecordDecl *cxx_record_decl = 3646 pointee_qual_type->getAsCXXRecordDecl(); 3647 if (cxx_record_decl) { 3648 bool is_complete = cxx_record_decl->isCompleteDefinition(); 3649 3650 if (is_complete) 3651 success = cxx_record_decl->isDynamicClass(); 3652 else { 3653 ClangASTMetadata *metadata = GetMetadata(cxx_record_decl); 3654 if (metadata) 3655 success = metadata->GetIsDynamicCXXType(); 3656 else { 3657 is_complete = GetType(pointee_qual_type).GetCompleteType(); 3658 if (is_complete) 3659 success = cxx_record_decl->isDynamicClass(); 3660 else 3661 success = false; 3662 } 3663 } 3664 3665 if (success) { 3666 if (dynamic_pointee_type) 3667 dynamic_pointee_type->SetCompilerType( 3668 weak_from_this(), pointee_qual_type.getAsOpaquePtr()); 3669 return true; 3670 } 3671 } 3672 } 3673 break; 3674 3675 case clang::Type::ObjCObject: 3676 case clang::Type::ObjCInterface: 3677 if (check_objc) { 3678 if (dynamic_pointee_type) 3679 dynamic_pointee_type->SetCompilerType( 3680 weak_from_this(), pointee_qual_type.getAsOpaquePtr()); 3681 return true; 3682 } 3683 break; 3684 3685 default: 3686 break; 3687 } 3688 } 3689 } 3690 if (dynamic_pointee_type) 3691 dynamic_pointee_type->Clear(); 3692 return false; 3693 } 3694 3695 bool TypeSystemClang::IsScalarType(lldb::opaque_compiler_type_t type) { 3696 if (!type) 3697 return false; 3698 3699 return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0; 3700 } 3701 3702 bool TypeSystemClang::IsTypedefType(lldb::opaque_compiler_type_t type) { 3703 if (!type) 3704 return false; 3705 return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}) 3706 ->getTypeClass() == clang::Type::Typedef; 3707 } 3708 3709 bool TypeSystemClang::IsVoidType(lldb::opaque_compiler_type_t type) { 3710 if (!type) 3711 return false; 3712 return GetCanonicalQualType(type)->isVoidType(); 3713 } 3714 3715 bool TypeSystemClang::CanPassInRegisters(const CompilerType &type) { 3716 if (auto *record_decl = 3717 TypeSystemClang::GetAsRecordDecl(type)) { 3718 return record_decl->canPassInRegisters(); 3719 } 3720 return false; 3721 } 3722 3723 bool TypeSystemClang::SupportsLanguage(lldb::LanguageType language) { 3724 return TypeSystemClangSupportsLanguage(language); 3725 } 3726 3727 std::optional<std::string> 3728 TypeSystemClang::GetCXXClassName(const CompilerType &type) { 3729 if (!type) 3730 return std::nullopt; 3731 3732 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type)); 3733 if (qual_type.isNull()) 3734 return std::nullopt; 3735 3736 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); 3737 if (!cxx_record_decl) 3738 return std::nullopt; 3739 3740 return std::string(cxx_record_decl->getIdentifier()->getNameStart()); 3741 } 3742 3743 bool TypeSystemClang::IsCXXClassType(const CompilerType &type) { 3744 if (!type) 3745 return false; 3746 3747 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type)); 3748 return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr; 3749 } 3750 3751 bool TypeSystemClang::IsBeingDefined(lldb::opaque_compiler_type_t type) { 3752 if (!type) 3753 return false; 3754 clang::QualType qual_type(GetCanonicalQualType(type)); 3755 const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type); 3756 if (tag_type) 3757 return tag_type->isBeingDefined(); 3758 return false; 3759 } 3760 3761 bool TypeSystemClang::IsObjCObjectPointerType(const CompilerType &type, 3762 CompilerType *class_type_ptr) { 3763 if (!ClangUtil::IsClangType(type)) 3764 return false; 3765 3766 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type)); 3767 3768 if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) { 3769 if (class_type_ptr) { 3770 if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) { 3771 const clang::ObjCObjectPointerType *obj_pointer_type = 3772 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type); 3773 if (obj_pointer_type == nullptr) 3774 class_type_ptr->Clear(); 3775 else 3776 class_type_ptr->SetCompilerType( 3777 type.GetTypeSystem(), 3778 clang::QualType(obj_pointer_type->getInterfaceType(), 0) 3779 .getAsOpaquePtr()); 3780 } 3781 } 3782 return true; 3783 } 3784 if (class_type_ptr) 3785 class_type_ptr->Clear(); 3786 return false; 3787 } 3788 3789 // Type Completion 3790 3791 bool TypeSystemClang::GetCompleteType(lldb::opaque_compiler_type_t type) { 3792 if (!type) 3793 return false; 3794 const bool allow_completion = true; 3795 return GetCompleteQualType(&getASTContext(), GetQualType(type), 3796 allow_completion); 3797 } 3798 3799 ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type, 3800 bool base_only) { 3801 if (!type) 3802 return ConstString(); 3803 3804 clang::QualType qual_type(GetQualType(type)); 3805 3806 // Remove certain type sugar from the name. Sugar such as elaborated types 3807 // or template types which only serve to improve diagnostics shouldn't 3808 // act as their own types from the user's perspective (e.g., formatter 3809 // shouldn't format a variable differently depending on how the ser has 3810 // specified the type. '::Type' and 'Type' should behave the same). 3811 // Typedefs and atomic derived types are not removed as they are actually 3812 // useful for identifiying specific types. 3813 qual_type = RemoveWrappingTypes(qual_type, 3814 {clang::Type::Typedef, clang::Type::Atomic}); 3815 3816 // For a typedef just return the qualified name. 3817 if (const auto *typedef_type = qual_type->getAs<clang::TypedefType>()) { 3818 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl(); 3819 return ConstString(GetTypeNameForDecl(typedef_decl)); 3820 } 3821 3822 // For consistency, this follows the same code path that clang uses to emit 3823 // debug info. This also handles when we don't want any scopes preceding the 3824 // name. 3825 if (auto *named_decl = qual_type->getAsTagDecl()) 3826 return ConstString(GetTypeNameForDecl(named_decl, !base_only)); 3827 3828 return ConstString(qual_type.getAsString(GetTypePrintingPolicy())); 3829 } 3830 3831 ConstString 3832 TypeSystemClang::GetDisplayTypeName(lldb::opaque_compiler_type_t type) { 3833 if (!type) 3834 return ConstString(); 3835 3836 clang::QualType qual_type(GetQualType(type)); 3837 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy()); 3838 printing_policy.SuppressTagKeyword = true; 3839 printing_policy.SuppressScope = false; 3840 printing_policy.SuppressUnwrittenScope = true; 3841 printing_policy.SuppressInlineNamespace = true; 3842 return ConstString(qual_type.getAsString(printing_policy)); 3843 } 3844 3845 uint32_t 3846 TypeSystemClang::GetTypeInfo(lldb::opaque_compiler_type_t type, 3847 CompilerType *pointee_or_element_clang_type) { 3848 if (!type) 3849 return 0; 3850 3851 if (pointee_or_element_clang_type) 3852 pointee_or_element_clang_type->Clear(); 3853 3854 clang::QualType qual_type = 3855 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}); 3856 3857 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 3858 switch (type_class) { 3859 case clang::Type::Attributed: 3860 return GetTypeInfo(qual_type->castAs<clang::AttributedType>() 3861 ->getModifiedType() 3862 .getAsOpaquePtr(), 3863 pointee_or_element_clang_type); 3864 case clang::Type::Builtin: { 3865 const clang::BuiltinType *builtin_type = 3866 llvm::cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal()); 3867 3868 uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue; 3869 switch (builtin_type->getKind()) { 3870 case clang::BuiltinType::ObjCId: 3871 case clang::BuiltinType::ObjCClass: 3872 if (pointee_or_element_clang_type) 3873 pointee_or_element_clang_type->SetCompilerType( 3874 weak_from_this(), 3875 getASTContext().ObjCBuiltinClassTy.getAsOpaquePtr()); 3876 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC; 3877 break; 3878 3879 case clang::BuiltinType::ObjCSel: 3880 if (pointee_or_element_clang_type) 3881 pointee_or_element_clang_type->SetCompilerType( 3882 weak_from_this(), getASTContext().CharTy.getAsOpaquePtr()); 3883 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC; 3884 break; 3885 3886 case clang::BuiltinType::Bool: 3887 case clang::BuiltinType::Char_U: 3888 case clang::BuiltinType::UChar: 3889 case clang::BuiltinType::WChar_U: 3890 case clang::BuiltinType::Char16: 3891 case clang::BuiltinType::Char32: 3892 case clang::BuiltinType::UShort: 3893 case clang::BuiltinType::UInt: 3894 case clang::BuiltinType::ULong: 3895 case clang::BuiltinType::ULongLong: 3896 case clang::BuiltinType::UInt128: 3897 case clang::BuiltinType::Char_S: 3898 case clang::BuiltinType::SChar: 3899 case clang::BuiltinType::WChar_S: 3900 case clang::BuiltinType::Short: 3901 case clang::BuiltinType::Int: 3902 case clang::BuiltinType::Long: 3903 case clang::BuiltinType::LongLong: 3904 case clang::BuiltinType::Int128: 3905 case clang::BuiltinType::Float: 3906 case clang::BuiltinType::Double: 3907 case clang::BuiltinType::LongDouble: 3908 builtin_type_flags |= eTypeIsScalar; 3909 if (builtin_type->isInteger()) { 3910 builtin_type_flags |= eTypeIsInteger; 3911 if (builtin_type->isSignedInteger()) 3912 builtin_type_flags |= eTypeIsSigned; 3913 } else if (builtin_type->isFloatingPoint()) 3914 builtin_type_flags |= eTypeIsFloat; 3915 break; 3916 default: 3917 break; 3918 } 3919 return builtin_type_flags; 3920 } 3921 3922 case clang::Type::BlockPointer: 3923 if (pointee_or_element_clang_type) 3924 pointee_or_element_clang_type->SetCompilerType( 3925 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr()); 3926 return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock; 3927 3928 case clang::Type::Complex: { 3929 uint32_t complex_type_flags = 3930 eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex; 3931 const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>( 3932 qual_type->getCanonicalTypeInternal()); 3933 if (complex_type) { 3934 clang::QualType complex_element_type(complex_type->getElementType()); 3935 if (complex_element_type->isIntegerType()) 3936 complex_type_flags |= eTypeIsFloat; 3937 else if (complex_element_type->isFloatingType()) 3938 complex_type_flags |= eTypeIsInteger; 3939 } 3940 return complex_type_flags; 3941 } break; 3942 3943 case clang::Type::ConstantArray: 3944 case clang::Type::DependentSizedArray: 3945 case clang::Type::IncompleteArray: 3946 case clang::Type::VariableArray: 3947 if (pointee_or_element_clang_type) 3948 pointee_or_element_clang_type->SetCompilerType( 3949 weak_from_this(), llvm::cast<clang::ArrayType>(qual_type.getTypePtr()) 3950 ->getElementType() 3951 .getAsOpaquePtr()); 3952 return eTypeHasChildren | eTypeIsArray; 3953 3954 case clang::Type::DependentName: 3955 return 0; 3956 case clang::Type::DependentSizedExtVector: 3957 return eTypeHasChildren | eTypeIsVector; 3958 case clang::Type::DependentTemplateSpecialization: 3959 return eTypeIsTemplate; 3960 3961 case clang::Type::Enum: 3962 if (pointee_or_element_clang_type) 3963 pointee_or_element_clang_type->SetCompilerType( 3964 weak_from_this(), llvm::cast<clang::EnumType>(qual_type) 3965 ->getDecl() 3966 ->getIntegerType() 3967 .getAsOpaquePtr()); 3968 return eTypeIsEnumeration | eTypeHasValue; 3969 3970 case clang::Type::FunctionProto: 3971 return eTypeIsFuncPrototype | eTypeHasValue; 3972 case clang::Type::FunctionNoProto: 3973 return eTypeIsFuncPrototype | eTypeHasValue; 3974 case clang::Type::InjectedClassName: 3975 return 0; 3976 3977 case clang::Type::LValueReference: 3978 case clang::Type::RValueReference: 3979 if (pointee_or_element_clang_type) 3980 pointee_or_element_clang_type->SetCompilerType( 3981 weak_from_this(), 3982 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr()) 3983 ->getPointeeType() 3984 .getAsOpaquePtr()); 3985 return eTypeHasChildren | eTypeIsReference | eTypeHasValue; 3986 3987 case clang::Type::MemberPointer: 3988 return eTypeIsPointer | eTypeIsMember | eTypeHasValue; 3989 3990 case clang::Type::ObjCObjectPointer: 3991 if (pointee_or_element_clang_type) 3992 pointee_or_element_clang_type->SetCompilerType( 3993 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr()); 3994 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | 3995 eTypeHasValue; 3996 3997 case clang::Type::ObjCObject: 3998 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass; 3999 case clang::Type::ObjCInterface: 4000 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass; 4001 4002 case clang::Type::Pointer: 4003 if (pointee_or_element_clang_type) 4004 pointee_or_element_clang_type->SetCompilerType( 4005 weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr()); 4006 return eTypeHasChildren | eTypeIsPointer | eTypeHasValue; 4007 4008 case clang::Type::Record: 4009 if (qual_type->getAsCXXRecordDecl()) 4010 return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus; 4011 else 4012 return eTypeHasChildren | eTypeIsStructUnion; 4013 break; 4014 case clang::Type::SubstTemplateTypeParm: 4015 return eTypeIsTemplate; 4016 case clang::Type::TemplateTypeParm: 4017 return eTypeIsTemplate; 4018 case clang::Type::TemplateSpecialization: 4019 return eTypeIsTemplate; 4020 4021 case clang::Type::Typedef: 4022 return eTypeIsTypedef | GetType(llvm::cast<clang::TypedefType>(qual_type) 4023 ->getDecl() 4024 ->getUnderlyingType()) 4025 .GetTypeInfo(pointee_or_element_clang_type); 4026 case clang::Type::UnresolvedUsing: 4027 return 0; 4028 4029 case clang::Type::ExtVector: 4030 case clang::Type::Vector: { 4031 uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector; 4032 const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>( 4033 qual_type->getCanonicalTypeInternal()); 4034 if (vector_type) { 4035 if (vector_type->isIntegerType()) 4036 vector_type_flags |= eTypeIsFloat; 4037 else if (vector_type->isFloatingType()) 4038 vector_type_flags |= eTypeIsInteger; 4039 } 4040 return vector_type_flags; 4041 } 4042 default: 4043 return 0; 4044 } 4045 return 0; 4046 } 4047 4048 lldb::LanguageType 4049 TypeSystemClang::GetMinimumLanguage(lldb::opaque_compiler_type_t type) { 4050 if (!type) 4051 return lldb::eLanguageTypeC; 4052 4053 // If the type is a reference, then resolve it to what it refers to first: 4054 clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType()); 4055 if (qual_type->isAnyPointerType()) { 4056 if (qual_type->isObjCObjectPointerType()) 4057 return lldb::eLanguageTypeObjC; 4058 if (qual_type->getPointeeCXXRecordDecl()) 4059 return lldb::eLanguageTypeC_plus_plus; 4060 4061 clang::QualType pointee_type(qual_type->getPointeeType()); 4062 if (pointee_type->getPointeeCXXRecordDecl()) 4063 return lldb::eLanguageTypeC_plus_plus; 4064 if (pointee_type->isObjCObjectOrInterfaceType()) 4065 return lldb::eLanguageTypeObjC; 4066 if (pointee_type->isObjCClassType()) 4067 return lldb::eLanguageTypeObjC; 4068 if (pointee_type.getTypePtr() == 4069 getASTContext().ObjCBuiltinIdTy.getTypePtr()) 4070 return lldb::eLanguageTypeObjC; 4071 } else { 4072 if (qual_type->isObjCObjectOrInterfaceType()) 4073 return lldb::eLanguageTypeObjC; 4074 if (qual_type->getAsCXXRecordDecl()) 4075 return lldb::eLanguageTypeC_plus_plus; 4076 switch (qual_type->getTypeClass()) { 4077 default: 4078 break; 4079 case clang::Type::Builtin: 4080 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) { 4081 default: 4082 case clang::BuiltinType::Void: 4083 case clang::BuiltinType::Bool: 4084 case clang::BuiltinType::Char_U: 4085 case clang::BuiltinType::UChar: 4086 case clang::BuiltinType::WChar_U: 4087 case clang::BuiltinType::Char16: 4088 case clang::BuiltinType::Char32: 4089 case clang::BuiltinType::UShort: 4090 case clang::BuiltinType::UInt: 4091 case clang::BuiltinType::ULong: 4092 case clang::BuiltinType::ULongLong: 4093 case clang::BuiltinType::UInt128: 4094 case clang::BuiltinType::Char_S: 4095 case clang::BuiltinType::SChar: 4096 case clang::BuiltinType::WChar_S: 4097 case clang::BuiltinType::Short: 4098 case clang::BuiltinType::Int: 4099 case clang::BuiltinType::Long: 4100 case clang::BuiltinType::LongLong: 4101 case clang::BuiltinType::Int128: 4102 case clang::BuiltinType::Float: 4103 case clang::BuiltinType::Double: 4104 case clang::BuiltinType::LongDouble: 4105 break; 4106 4107 case clang::BuiltinType::NullPtr: 4108 return eLanguageTypeC_plus_plus; 4109 4110 case clang::BuiltinType::ObjCId: 4111 case clang::BuiltinType::ObjCClass: 4112 case clang::BuiltinType::ObjCSel: 4113 return eLanguageTypeObjC; 4114 4115 case clang::BuiltinType::Dependent: 4116 case clang::BuiltinType::Overload: 4117 case clang::BuiltinType::BoundMember: 4118 case clang::BuiltinType::UnknownAny: 4119 break; 4120 } 4121 break; 4122 case clang::Type::Typedef: 4123 return GetType(llvm::cast<clang::TypedefType>(qual_type) 4124 ->getDecl() 4125 ->getUnderlyingType()) 4126 .GetMinimumLanguage(); 4127 } 4128 } 4129 return lldb::eLanguageTypeC; 4130 } 4131 4132 lldb::TypeClass 4133 TypeSystemClang::GetTypeClass(lldb::opaque_compiler_type_t type) { 4134 if (!type) 4135 return lldb::eTypeClassInvalid; 4136 4137 clang::QualType qual_type = 4138 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}); 4139 4140 switch (qual_type->getTypeClass()) { 4141 case clang::Type::Atomic: 4142 case clang::Type::Auto: 4143 case clang::Type::Decltype: 4144 case clang::Type::Elaborated: 4145 case clang::Type::Paren: 4146 case clang::Type::TypeOf: 4147 case clang::Type::TypeOfExpr: 4148 case clang::Type::Using: 4149 llvm_unreachable("Handled in RemoveWrappingTypes!"); 4150 case clang::Type::UnaryTransform: 4151 break; 4152 case clang::Type::FunctionNoProto: 4153 return lldb::eTypeClassFunction; 4154 case clang::Type::FunctionProto: 4155 return lldb::eTypeClassFunction; 4156 case clang::Type::IncompleteArray: 4157 return lldb::eTypeClassArray; 4158 case clang::Type::VariableArray: 4159 return lldb::eTypeClassArray; 4160 case clang::Type::ConstantArray: 4161 return lldb::eTypeClassArray; 4162 case clang::Type::DependentSizedArray: 4163 return lldb::eTypeClassArray; 4164 case clang::Type::DependentSizedExtVector: 4165 return lldb::eTypeClassVector; 4166 case clang::Type::DependentVector: 4167 return lldb::eTypeClassVector; 4168 case clang::Type::ExtVector: 4169 return lldb::eTypeClassVector; 4170 case clang::Type::Vector: 4171 return lldb::eTypeClassVector; 4172 case clang::Type::Builtin: 4173 // Ext-Int is just an integer type. 4174 case clang::Type::BitInt: 4175 case clang::Type::DependentBitInt: 4176 return lldb::eTypeClassBuiltin; 4177 case clang::Type::ObjCObjectPointer: 4178 return lldb::eTypeClassObjCObjectPointer; 4179 case clang::Type::BlockPointer: 4180 return lldb::eTypeClassBlockPointer; 4181 case clang::Type::Pointer: 4182 return lldb::eTypeClassPointer; 4183 case clang::Type::LValueReference: 4184 return lldb::eTypeClassReference; 4185 case clang::Type::RValueReference: 4186 return lldb::eTypeClassReference; 4187 case clang::Type::MemberPointer: 4188 return lldb::eTypeClassMemberPointer; 4189 case clang::Type::Complex: 4190 if (qual_type->isComplexType()) 4191 return lldb::eTypeClassComplexFloat; 4192 else 4193 return lldb::eTypeClassComplexInteger; 4194 case clang::Type::ObjCObject: 4195 return lldb::eTypeClassObjCObject; 4196 case clang::Type::ObjCInterface: 4197 return lldb::eTypeClassObjCInterface; 4198 case clang::Type::Record: { 4199 const clang::RecordType *record_type = 4200 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 4201 const clang::RecordDecl *record_decl = record_type->getDecl(); 4202 if (record_decl->isUnion()) 4203 return lldb::eTypeClassUnion; 4204 else if (record_decl->isStruct()) 4205 return lldb::eTypeClassStruct; 4206 else 4207 return lldb::eTypeClassClass; 4208 } break; 4209 case clang::Type::Enum: 4210 return lldb::eTypeClassEnumeration; 4211 case clang::Type::Typedef: 4212 return lldb::eTypeClassTypedef; 4213 case clang::Type::UnresolvedUsing: 4214 break; 4215 4216 case clang::Type::Attributed: 4217 case clang::Type::BTFTagAttributed: 4218 break; 4219 case clang::Type::TemplateTypeParm: 4220 break; 4221 case clang::Type::SubstTemplateTypeParm: 4222 break; 4223 case clang::Type::SubstTemplateTypeParmPack: 4224 break; 4225 case clang::Type::InjectedClassName: 4226 break; 4227 case clang::Type::DependentName: 4228 break; 4229 case clang::Type::DependentTemplateSpecialization: 4230 break; 4231 case clang::Type::PackExpansion: 4232 break; 4233 4234 case clang::Type::TemplateSpecialization: 4235 break; 4236 case clang::Type::DeducedTemplateSpecialization: 4237 break; 4238 case clang::Type::Pipe: 4239 break; 4240 4241 // pointer type decayed from an array or function type. 4242 case clang::Type::Decayed: 4243 break; 4244 case clang::Type::Adjusted: 4245 break; 4246 case clang::Type::ObjCTypeParam: 4247 break; 4248 4249 case clang::Type::DependentAddressSpace: 4250 break; 4251 case clang::Type::MacroQualified: 4252 break; 4253 4254 // Matrix types that we're not sure how to display at the moment. 4255 case clang::Type::ConstantMatrix: 4256 case clang::Type::DependentSizedMatrix: 4257 break; 4258 } 4259 // We don't know hot to display this type... 4260 return lldb::eTypeClassOther; 4261 } 4262 4263 unsigned TypeSystemClang::GetTypeQualifiers(lldb::opaque_compiler_type_t type) { 4264 if (type) 4265 return GetQualType(type).getQualifiers().getCVRQualifiers(); 4266 return 0; 4267 } 4268 4269 // Creating related types 4270 4271 CompilerType 4272 TypeSystemClang::GetArrayElementType(lldb::opaque_compiler_type_t type, 4273 ExecutionContextScope *exe_scope) { 4274 if (type) { 4275 clang::QualType qual_type(GetQualType(type)); 4276 4277 const clang::Type *array_eletype = 4278 qual_type.getTypePtr()->getArrayElementTypeNoTypeQual(); 4279 4280 if (!array_eletype) 4281 return CompilerType(); 4282 4283 return GetType(clang::QualType(array_eletype, 0)); 4284 } 4285 return CompilerType(); 4286 } 4287 4288 CompilerType TypeSystemClang::GetArrayType(lldb::opaque_compiler_type_t type, 4289 uint64_t size) { 4290 if (type) { 4291 clang::QualType qual_type(GetCanonicalQualType(type)); 4292 clang::ASTContext &ast_ctx = getASTContext(); 4293 if (size != 0) 4294 return GetType(ast_ctx.getConstantArrayType( 4295 qual_type, llvm::APInt(64, size), nullptr, 4296 clang::ArrayType::ArraySizeModifier::Normal, 0)); 4297 else 4298 return GetType(ast_ctx.getIncompleteArrayType( 4299 qual_type, clang::ArrayType::ArraySizeModifier::Normal, 0)); 4300 } 4301 4302 return CompilerType(); 4303 } 4304 4305 CompilerType 4306 TypeSystemClang::GetCanonicalType(lldb::opaque_compiler_type_t type) { 4307 if (type) 4308 return GetType(GetCanonicalQualType(type)); 4309 return CompilerType(); 4310 } 4311 4312 static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast, 4313 clang::QualType qual_type) { 4314 if (qual_type->isPointerType()) 4315 qual_type = ast->getPointerType( 4316 GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType())); 4317 else if (const ConstantArrayType *arr = 4318 ast->getAsConstantArrayType(qual_type)) { 4319 qual_type = ast->getConstantArrayType( 4320 GetFullyUnqualifiedType_Impl(ast, arr->getElementType()), 4321 arr->getSize(), arr->getSizeExpr(), arr->getSizeModifier(), 4322 arr->getIndexTypeQualifiers().getAsOpaqueValue()); 4323 } else 4324 qual_type = qual_type.getUnqualifiedType(); 4325 qual_type.removeLocalConst(); 4326 qual_type.removeLocalRestrict(); 4327 qual_type.removeLocalVolatile(); 4328 return qual_type; 4329 } 4330 4331 CompilerType 4332 TypeSystemClang::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) { 4333 if (type) 4334 return GetType( 4335 GetFullyUnqualifiedType_Impl(&getASTContext(), GetQualType(type))); 4336 return CompilerType(); 4337 } 4338 4339 CompilerType 4340 TypeSystemClang::GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) { 4341 if (type) 4342 return GetEnumerationIntegerType(GetType(GetCanonicalQualType(type))); 4343 return CompilerType(); 4344 } 4345 4346 int TypeSystemClang::GetFunctionArgumentCount( 4347 lldb::opaque_compiler_type_t type) { 4348 if (type) { 4349 const clang::FunctionProtoType *func = 4350 llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type)); 4351 if (func) 4352 return func->getNumParams(); 4353 } 4354 return -1; 4355 } 4356 4357 CompilerType TypeSystemClang::GetFunctionArgumentTypeAtIndex( 4358 lldb::opaque_compiler_type_t type, size_t idx) { 4359 if (type) { 4360 const clang::FunctionProtoType *func = 4361 llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type)); 4362 if (func) { 4363 const uint32_t num_args = func->getNumParams(); 4364 if (idx < num_args) 4365 return GetType(func->getParamType(idx)); 4366 } 4367 } 4368 return CompilerType(); 4369 } 4370 4371 CompilerType 4372 TypeSystemClang::GetFunctionReturnType(lldb::opaque_compiler_type_t type) { 4373 if (type) { 4374 clang::QualType qual_type(GetQualType(type)); 4375 const clang::FunctionProtoType *func = 4376 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr()); 4377 if (func) 4378 return GetType(func->getReturnType()); 4379 } 4380 return CompilerType(); 4381 } 4382 4383 size_t 4384 TypeSystemClang::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) { 4385 size_t num_functions = 0; 4386 if (type) { 4387 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 4388 switch (qual_type->getTypeClass()) { 4389 case clang::Type::Record: 4390 if (GetCompleteQualType(&getASTContext(), qual_type)) { 4391 const clang::RecordType *record_type = 4392 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 4393 const clang::RecordDecl *record_decl = record_type->getDecl(); 4394 assert(record_decl); 4395 const clang::CXXRecordDecl *cxx_record_decl = 4396 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 4397 if (cxx_record_decl) 4398 num_functions = std::distance(cxx_record_decl->method_begin(), 4399 cxx_record_decl->method_end()); 4400 } 4401 break; 4402 4403 case clang::Type::ObjCObjectPointer: { 4404 const clang::ObjCObjectPointerType *objc_class_type = 4405 qual_type->castAs<clang::ObjCObjectPointerType>(); 4406 const clang::ObjCInterfaceType *objc_interface_type = 4407 objc_class_type->getInterfaceType(); 4408 if (objc_interface_type && 4409 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>( 4410 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) { 4411 clang::ObjCInterfaceDecl *class_interface_decl = 4412 objc_interface_type->getDecl(); 4413 if (class_interface_decl) { 4414 num_functions = std::distance(class_interface_decl->meth_begin(), 4415 class_interface_decl->meth_end()); 4416 } 4417 } 4418 break; 4419 } 4420 4421 case clang::Type::ObjCObject: 4422 case clang::Type::ObjCInterface: 4423 if (GetCompleteType(type)) { 4424 const clang::ObjCObjectType *objc_class_type = 4425 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 4426 if (objc_class_type) { 4427 clang::ObjCInterfaceDecl *class_interface_decl = 4428 objc_class_type->getInterface(); 4429 if (class_interface_decl) 4430 num_functions = std::distance(class_interface_decl->meth_begin(), 4431 class_interface_decl->meth_end()); 4432 } 4433 } 4434 break; 4435 4436 default: 4437 break; 4438 } 4439 } 4440 return num_functions; 4441 } 4442 4443 TypeMemberFunctionImpl 4444 TypeSystemClang::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type, 4445 size_t idx) { 4446 std::string name; 4447 MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown); 4448 CompilerType clang_type; 4449 CompilerDecl clang_decl; 4450 if (type) { 4451 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 4452 switch (qual_type->getTypeClass()) { 4453 case clang::Type::Record: 4454 if (GetCompleteQualType(&getASTContext(), qual_type)) { 4455 const clang::RecordType *record_type = 4456 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 4457 const clang::RecordDecl *record_decl = record_type->getDecl(); 4458 assert(record_decl); 4459 const clang::CXXRecordDecl *cxx_record_decl = 4460 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 4461 if (cxx_record_decl) { 4462 auto method_iter = cxx_record_decl->method_begin(); 4463 auto method_end = cxx_record_decl->method_end(); 4464 if (idx < 4465 static_cast<size_t>(std::distance(method_iter, method_end))) { 4466 std::advance(method_iter, idx); 4467 clang::CXXMethodDecl *cxx_method_decl = 4468 method_iter->getCanonicalDecl(); 4469 if (cxx_method_decl) { 4470 name = cxx_method_decl->getDeclName().getAsString(); 4471 if (cxx_method_decl->isStatic()) 4472 kind = lldb::eMemberFunctionKindStaticMethod; 4473 else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl)) 4474 kind = lldb::eMemberFunctionKindConstructor; 4475 else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl)) 4476 kind = lldb::eMemberFunctionKindDestructor; 4477 else 4478 kind = lldb::eMemberFunctionKindInstanceMethod; 4479 clang_type = GetType(cxx_method_decl->getType()); 4480 clang_decl = GetCompilerDecl(cxx_method_decl); 4481 } 4482 } 4483 } 4484 } 4485 break; 4486 4487 case clang::Type::ObjCObjectPointer: { 4488 const clang::ObjCObjectPointerType *objc_class_type = 4489 qual_type->castAs<clang::ObjCObjectPointerType>(); 4490 const clang::ObjCInterfaceType *objc_interface_type = 4491 objc_class_type->getInterfaceType(); 4492 if (objc_interface_type && 4493 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>( 4494 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) { 4495 clang::ObjCInterfaceDecl *class_interface_decl = 4496 objc_interface_type->getDecl(); 4497 if (class_interface_decl) { 4498 auto method_iter = class_interface_decl->meth_begin(); 4499 auto method_end = class_interface_decl->meth_end(); 4500 if (idx < 4501 static_cast<size_t>(std::distance(method_iter, method_end))) { 4502 std::advance(method_iter, idx); 4503 clang::ObjCMethodDecl *objc_method_decl = 4504 method_iter->getCanonicalDecl(); 4505 if (objc_method_decl) { 4506 clang_decl = GetCompilerDecl(objc_method_decl); 4507 name = objc_method_decl->getSelector().getAsString(); 4508 if (objc_method_decl->isClassMethod()) 4509 kind = lldb::eMemberFunctionKindStaticMethod; 4510 else 4511 kind = lldb::eMemberFunctionKindInstanceMethod; 4512 } 4513 } 4514 } 4515 } 4516 break; 4517 } 4518 4519 case clang::Type::ObjCObject: 4520 case clang::Type::ObjCInterface: 4521 if (GetCompleteType(type)) { 4522 const clang::ObjCObjectType *objc_class_type = 4523 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 4524 if (objc_class_type) { 4525 clang::ObjCInterfaceDecl *class_interface_decl = 4526 objc_class_type->getInterface(); 4527 if (class_interface_decl) { 4528 auto method_iter = class_interface_decl->meth_begin(); 4529 auto method_end = class_interface_decl->meth_end(); 4530 if (idx < 4531 static_cast<size_t>(std::distance(method_iter, method_end))) { 4532 std::advance(method_iter, idx); 4533 clang::ObjCMethodDecl *objc_method_decl = 4534 method_iter->getCanonicalDecl(); 4535 if (objc_method_decl) { 4536 clang_decl = GetCompilerDecl(objc_method_decl); 4537 name = objc_method_decl->getSelector().getAsString(); 4538 if (objc_method_decl->isClassMethod()) 4539 kind = lldb::eMemberFunctionKindStaticMethod; 4540 else 4541 kind = lldb::eMemberFunctionKindInstanceMethod; 4542 } 4543 } 4544 } 4545 } 4546 } 4547 break; 4548 4549 default: 4550 break; 4551 } 4552 } 4553 4554 if (kind == eMemberFunctionKindUnknown) 4555 return TypeMemberFunctionImpl(); 4556 else 4557 return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind); 4558 } 4559 4560 CompilerType 4561 TypeSystemClang::GetNonReferenceType(lldb::opaque_compiler_type_t type) { 4562 if (type) 4563 return GetType(GetQualType(type).getNonReferenceType()); 4564 return CompilerType(); 4565 } 4566 4567 CompilerType 4568 TypeSystemClang::GetPointeeType(lldb::opaque_compiler_type_t type) { 4569 if (type) { 4570 clang::QualType qual_type(GetQualType(type)); 4571 return GetType(qual_type.getTypePtr()->getPointeeType()); 4572 } 4573 return CompilerType(); 4574 } 4575 4576 CompilerType 4577 TypeSystemClang::GetPointerType(lldb::opaque_compiler_type_t type) { 4578 if (type) { 4579 clang::QualType qual_type(GetQualType(type)); 4580 4581 switch (qual_type.getDesugaredType(getASTContext())->getTypeClass()) { 4582 case clang::Type::ObjCObject: 4583 case clang::Type::ObjCInterface: 4584 return GetType(getASTContext().getObjCObjectPointerType(qual_type)); 4585 4586 default: 4587 return GetType(getASTContext().getPointerType(qual_type)); 4588 } 4589 } 4590 return CompilerType(); 4591 } 4592 4593 CompilerType 4594 TypeSystemClang::GetLValueReferenceType(lldb::opaque_compiler_type_t type) { 4595 if (type) 4596 return GetType(getASTContext().getLValueReferenceType(GetQualType(type))); 4597 else 4598 return CompilerType(); 4599 } 4600 4601 CompilerType 4602 TypeSystemClang::GetRValueReferenceType(lldb::opaque_compiler_type_t type) { 4603 if (type) 4604 return GetType(getASTContext().getRValueReferenceType(GetQualType(type))); 4605 else 4606 return CompilerType(); 4607 } 4608 4609 CompilerType TypeSystemClang::GetAtomicType(lldb::opaque_compiler_type_t type) { 4610 if (!type) 4611 return CompilerType(); 4612 return GetType(getASTContext().getAtomicType(GetQualType(type))); 4613 } 4614 4615 CompilerType 4616 TypeSystemClang::AddConstModifier(lldb::opaque_compiler_type_t type) { 4617 if (type) { 4618 clang::QualType result(GetQualType(type)); 4619 result.addConst(); 4620 return GetType(result); 4621 } 4622 return CompilerType(); 4623 } 4624 4625 CompilerType 4626 TypeSystemClang::AddVolatileModifier(lldb::opaque_compiler_type_t type) { 4627 if (type) { 4628 clang::QualType result(GetQualType(type)); 4629 result.addVolatile(); 4630 return GetType(result); 4631 } 4632 return CompilerType(); 4633 } 4634 4635 CompilerType 4636 TypeSystemClang::AddRestrictModifier(lldb::opaque_compiler_type_t type) { 4637 if (type) { 4638 clang::QualType result(GetQualType(type)); 4639 result.addRestrict(); 4640 return GetType(result); 4641 } 4642 return CompilerType(); 4643 } 4644 4645 CompilerType TypeSystemClang::CreateTypedef( 4646 lldb::opaque_compiler_type_t type, const char *typedef_name, 4647 const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) { 4648 if (type && typedef_name && typedef_name[0]) { 4649 clang::ASTContext &clang_ast = getASTContext(); 4650 clang::QualType qual_type(GetQualType(type)); 4651 4652 clang::DeclContext *decl_ctx = 4653 TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx); 4654 if (!decl_ctx) 4655 decl_ctx = getASTContext().getTranslationUnitDecl(); 4656 4657 clang::TypedefDecl *decl = 4658 clang::TypedefDecl::CreateDeserialized(clang_ast, 0); 4659 decl->setDeclContext(decl_ctx); 4660 decl->setDeclName(&clang_ast.Idents.get(typedef_name)); 4661 decl->setTypeSourceInfo(clang_ast.getTrivialTypeSourceInfo(qual_type)); 4662 decl_ctx->addDecl(decl); 4663 SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule()); 4664 4665 clang::TagDecl *tdecl = nullptr; 4666 if (!qual_type.isNull()) { 4667 if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>()) 4668 tdecl = rt->getDecl(); 4669 if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>()) 4670 tdecl = et->getDecl(); 4671 } 4672 4673 // Check whether this declaration is an anonymous struct, union, or enum, 4674 // hidden behind a typedef. If so, we try to check whether we have a 4675 // typedef tag to attach to the original record declaration 4676 if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl()) 4677 tdecl->setTypedefNameForAnonDecl(decl); 4678 4679 decl->setAccess(clang::AS_public); // TODO respect proper access specifier 4680 4681 // Get a uniqued clang::QualType for the typedef decl type 4682 return GetType(clang_ast.getTypedefType(decl)); 4683 } 4684 return CompilerType(); 4685 } 4686 4687 CompilerType 4688 TypeSystemClang::GetTypedefedType(lldb::opaque_compiler_type_t type) { 4689 if (type) { 4690 const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>( 4691 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})); 4692 if (typedef_type) 4693 return GetType(typedef_type->getDecl()->getUnderlyingType()); 4694 } 4695 return CompilerType(); 4696 } 4697 4698 // Create related types using the current type's AST 4699 4700 CompilerType TypeSystemClang::GetBasicTypeFromAST(lldb::BasicType basic_type) { 4701 return TypeSystemClang::GetBasicType(basic_type); 4702 } 4703 // Exploring the type 4704 4705 const llvm::fltSemantics & 4706 TypeSystemClang::GetFloatTypeSemantics(size_t byte_size) { 4707 clang::ASTContext &ast = getASTContext(); 4708 const size_t bit_size = byte_size * 8; 4709 if (bit_size == ast.getTypeSize(ast.FloatTy)) 4710 return ast.getFloatTypeSemantics(ast.FloatTy); 4711 else if (bit_size == ast.getTypeSize(ast.DoubleTy)) 4712 return ast.getFloatTypeSemantics(ast.DoubleTy); 4713 else if (bit_size == ast.getTypeSize(ast.LongDoubleTy) || 4714 bit_size == llvm::APFloat::semanticsSizeInBits( 4715 ast.getFloatTypeSemantics(ast.LongDoubleTy))) 4716 return ast.getFloatTypeSemantics(ast.LongDoubleTy); 4717 else if (bit_size == ast.getTypeSize(ast.HalfTy)) 4718 return ast.getFloatTypeSemantics(ast.HalfTy); 4719 return llvm::APFloatBase::Bogus(); 4720 } 4721 4722 std::optional<uint64_t> 4723 TypeSystemClang::GetBitSize(lldb::opaque_compiler_type_t type, 4724 ExecutionContextScope *exe_scope) { 4725 if (GetCompleteType(type)) { 4726 clang::QualType qual_type(GetCanonicalQualType(type)); 4727 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 4728 switch (type_class) { 4729 case clang::Type::Record: 4730 if (GetCompleteType(type)) 4731 return getASTContext().getTypeSize(qual_type); 4732 else 4733 return std::nullopt; 4734 break; 4735 4736 case clang::Type::ObjCInterface: 4737 case clang::Type::ObjCObject: { 4738 ExecutionContext exe_ctx(exe_scope); 4739 Process *process = exe_ctx.GetProcessPtr(); 4740 if (process) { 4741 ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process); 4742 if (objc_runtime) { 4743 uint64_t bit_size = 0; 4744 if (objc_runtime->GetTypeBitSize(GetType(qual_type), bit_size)) 4745 return bit_size; 4746 } 4747 } else { 4748 static bool g_printed = false; 4749 if (!g_printed) { 4750 StreamString s; 4751 DumpTypeDescription(type, s); 4752 4753 llvm::outs() << "warning: trying to determine the size of type "; 4754 llvm::outs() << s.GetString() << "\n"; 4755 llvm::outs() << "without a valid ExecutionContext. this is not " 4756 "reliable. please file a bug against LLDB.\n"; 4757 llvm::outs() << "backtrace:\n"; 4758 llvm::sys::PrintStackTrace(llvm::outs()); 4759 llvm::outs() << "\n"; 4760 g_printed = true; 4761 } 4762 } 4763 } 4764 [[fallthrough]]; 4765 default: 4766 const uint32_t bit_size = getASTContext().getTypeSize(qual_type); 4767 if (bit_size == 0) { 4768 if (qual_type->isIncompleteArrayType()) 4769 return getASTContext().getTypeSize( 4770 qual_type->getArrayElementTypeNoTypeQual() 4771 ->getCanonicalTypeUnqualified()); 4772 } 4773 if (qual_type->isObjCObjectOrInterfaceType()) 4774 return bit_size + 4775 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy); 4776 // Function types actually have a size of 0, that's not an error. 4777 if (qual_type->isFunctionProtoType()) 4778 return bit_size; 4779 if (bit_size) 4780 return bit_size; 4781 } 4782 } 4783 return std::nullopt; 4784 } 4785 4786 std::optional<size_t> 4787 TypeSystemClang::GetTypeBitAlign(lldb::opaque_compiler_type_t type, 4788 ExecutionContextScope *exe_scope) { 4789 if (GetCompleteType(type)) 4790 return getASTContext().getTypeAlign(GetQualType(type)); 4791 return {}; 4792 } 4793 4794 lldb::Encoding TypeSystemClang::GetEncoding(lldb::opaque_compiler_type_t type, 4795 uint64_t &count) { 4796 if (!type) 4797 return lldb::eEncodingInvalid; 4798 4799 count = 1; 4800 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 4801 4802 switch (qual_type->getTypeClass()) { 4803 case clang::Type::Atomic: 4804 case clang::Type::Auto: 4805 case clang::Type::Decltype: 4806 case clang::Type::Elaborated: 4807 case clang::Type::Paren: 4808 case clang::Type::Typedef: 4809 case clang::Type::TypeOf: 4810 case clang::Type::TypeOfExpr: 4811 case clang::Type::Using: 4812 llvm_unreachable("Handled in RemoveWrappingTypes!"); 4813 4814 case clang::Type::UnaryTransform: 4815 break; 4816 4817 case clang::Type::FunctionNoProto: 4818 case clang::Type::FunctionProto: 4819 break; 4820 4821 case clang::Type::IncompleteArray: 4822 case clang::Type::VariableArray: 4823 break; 4824 4825 case clang::Type::ConstantArray: 4826 break; 4827 4828 case clang::Type::DependentVector: 4829 case clang::Type::ExtVector: 4830 case clang::Type::Vector: 4831 // TODO: Set this to more than one??? 4832 break; 4833 4834 case clang::Type::BitInt: 4835 case clang::Type::DependentBitInt: 4836 return qual_type->isUnsignedIntegerType() ? lldb::eEncodingUint 4837 : lldb::eEncodingSint; 4838 4839 case clang::Type::Builtin: 4840 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) { 4841 case clang::BuiltinType::Void: 4842 break; 4843 4844 case clang::BuiltinType::Char_S: 4845 case clang::BuiltinType::SChar: 4846 case clang::BuiltinType::WChar_S: 4847 case clang::BuiltinType::Short: 4848 case clang::BuiltinType::Int: 4849 case clang::BuiltinType::Long: 4850 case clang::BuiltinType::LongLong: 4851 case clang::BuiltinType::Int128: 4852 return lldb::eEncodingSint; 4853 4854 case clang::BuiltinType::Bool: 4855 case clang::BuiltinType::Char_U: 4856 case clang::BuiltinType::UChar: 4857 case clang::BuiltinType::WChar_U: 4858 case clang::BuiltinType::Char8: 4859 case clang::BuiltinType::Char16: 4860 case clang::BuiltinType::Char32: 4861 case clang::BuiltinType::UShort: 4862 case clang::BuiltinType::UInt: 4863 case clang::BuiltinType::ULong: 4864 case clang::BuiltinType::ULongLong: 4865 case clang::BuiltinType::UInt128: 4866 return lldb::eEncodingUint; 4867 4868 // Fixed point types. Note that they are currently ignored. 4869 case clang::BuiltinType::ShortAccum: 4870 case clang::BuiltinType::Accum: 4871 case clang::BuiltinType::LongAccum: 4872 case clang::BuiltinType::UShortAccum: 4873 case clang::BuiltinType::UAccum: 4874 case clang::BuiltinType::ULongAccum: 4875 case clang::BuiltinType::ShortFract: 4876 case clang::BuiltinType::Fract: 4877 case clang::BuiltinType::LongFract: 4878 case clang::BuiltinType::UShortFract: 4879 case clang::BuiltinType::UFract: 4880 case clang::BuiltinType::ULongFract: 4881 case clang::BuiltinType::SatShortAccum: 4882 case clang::BuiltinType::SatAccum: 4883 case clang::BuiltinType::SatLongAccum: 4884 case clang::BuiltinType::SatUShortAccum: 4885 case clang::BuiltinType::SatUAccum: 4886 case clang::BuiltinType::SatULongAccum: 4887 case clang::BuiltinType::SatShortFract: 4888 case clang::BuiltinType::SatFract: 4889 case clang::BuiltinType::SatLongFract: 4890 case clang::BuiltinType::SatUShortFract: 4891 case clang::BuiltinType::SatUFract: 4892 case clang::BuiltinType::SatULongFract: 4893 break; 4894 4895 case clang::BuiltinType::Half: 4896 case clang::BuiltinType::Float: 4897 case clang::BuiltinType::Float16: 4898 case clang::BuiltinType::Float128: 4899 case clang::BuiltinType::Double: 4900 case clang::BuiltinType::LongDouble: 4901 case clang::BuiltinType::BFloat16: 4902 case clang::BuiltinType::Ibm128: 4903 return lldb::eEncodingIEEE754; 4904 4905 case clang::BuiltinType::ObjCClass: 4906 case clang::BuiltinType::ObjCId: 4907 case clang::BuiltinType::ObjCSel: 4908 return lldb::eEncodingUint; 4909 4910 case clang::BuiltinType::NullPtr: 4911 return lldb::eEncodingUint; 4912 4913 case clang::BuiltinType::Kind::ARCUnbridgedCast: 4914 case clang::BuiltinType::Kind::BoundMember: 4915 case clang::BuiltinType::Kind::BuiltinFn: 4916 case clang::BuiltinType::Kind::Dependent: 4917 case clang::BuiltinType::Kind::OCLClkEvent: 4918 case clang::BuiltinType::Kind::OCLEvent: 4919 case clang::BuiltinType::Kind::OCLImage1dRO: 4920 case clang::BuiltinType::Kind::OCLImage1dWO: 4921 case clang::BuiltinType::Kind::OCLImage1dRW: 4922 case clang::BuiltinType::Kind::OCLImage1dArrayRO: 4923 case clang::BuiltinType::Kind::OCLImage1dArrayWO: 4924 case clang::BuiltinType::Kind::OCLImage1dArrayRW: 4925 case clang::BuiltinType::Kind::OCLImage1dBufferRO: 4926 case clang::BuiltinType::Kind::OCLImage1dBufferWO: 4927 case clang::BuiltinType::Kind::OCLImage1dBufferRW: 4928 case clang::BuiltinType::Kind::OCLImage2dRO: 4929 case clang::BuiltinType::Kind::OCLImage2dWO: 4930 case clang::BuiltinType::Kind::OCLImage2dRW: 4931 case clang::BuiltinType::Kind::OCLImage2dArrayRO: 4932 case clang::BuiltinType::Kind::OCLImage2dArrayWO: 4933 case clang::BuiltinType::Kind::OCLImage2dArrayRW: 4934 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO: 4935 case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO: 4936 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW: 4937 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO: 4938 case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO: 4939 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW: 4940 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO: 4941 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO: 4942 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW: 4943 case clang::BuiltinType::Kind::OCLImage2dDepthRO: 4944 case clang::BuiltinType::Kind::OCLImage2dDepthWO: 4945 case clang::BuiltinType::Kind::OCLImage2dDepthRW: 4946 case clang::BuiltinType::Kind::OCLImage2dMSAARO: 4947 case clang::BuiltinType::Kind::OCLImage2dMSAAWO: 4948 case clang::BuiltinType::Kind::OCLImage2dMSAARW: 4949 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO: 4950 case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO: 4951 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW: 4952 case clang::BuiltinType::Kind::OCLImage3dRO: 4953 case clang::BuiltinType::Kind::OCLImage3dWO: 4954 case clang::BuiltinType::Kind::OCLImage3dRW: 4955 case clang::BuiltinType::Kind::OCLQueue: 4956 case clang::BuiltinType::Kind::OCLReserveID: 4957 case clang::BuiltinType::Kind::OCLSampler: 4958 case clang::BuiltinType::Kind::OMPArraySection: 4959 case clang::BuiltinType::Kind::OMPArrayShaping: 4960 case clang::BuiltinType::Kind::OMPIterator: 4961 case clang::BuiltinType::Kind::Overload: 4962 case clang::BuiltinType::Kind::PseudoObject: 4963 case clang::BuiltinType::Kind::UnknownAny: 4964 break; 4965 4966 case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload: 4967 case clang::BuiltinType::OCLIntelSubgroupAVCImePayload: 4968 case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload: 4969 case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload: 4970 case clang::BuiltinType::OCLIntelSubgroupAVCMceResult: 4971 case clang::BuiltinType::OCLIntelSubgroupAVCImeResult: 4972 case clang::BuiltinType::OCLIntelSubgroupAVCRefResult: 4973 case clang::BuiltinType::OCLIntelSubgroupAVCSicResult: 4974 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleReferenceStreamout: 4975 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualReferenceStreamout: 4976 case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleReferenceStreamin: 4977 case clang::BuiltinType::OCLIntelSubgroupAVCImeDualReferenceStreamin: 4978 break; 4979 4980 // PowerPC -- Matrix Multiply Assist 4981 case clang::BuiltinType::VectorPair: 4982 case clang::BuiltinType::VectorQuad: 4983 break; 4984 4985 // ARM -- Scalable Vector Extension 4986 case clang::BuiltinType::SveBool: 4987 case clang::BuiltinType::SveBoolx2: 4988 case clang::BuiltinType::SveBoolx4: 4989 case clang::BuiltinType::SveCount: 4990 case clang::BuiltinType::SveInt8: 4991 case clang::BuiltinType::SveInt8x2: 4992 case clang::BuiltinType::SveInt8x3: 4993 case clang::BuiltinType::SveInt8x4: 4994 case clang::BuiltinType::SveInt16: 4995 case clang::BuiltinType::SveInt16x2: 4996 case clang::BuiltinType::SveInt16x3: 4997 case clang::BuiltinType::SveInt16x4: 4998 case clang::BuiltinType::SveInt32: 4999 case clang::BuiltinType::SveInt32x2: 5000 case clang::BuiltinType::SveInt32x3: 5001 case clang::BuiltinType::SveInt32x4: 5002 case clang::BuiltinType::SveInt64: 5003 case clang::BuiltinType::SveInt64x2: 5004 case clang::BuiltinType::SveInt64x3: 5005 case clang::BuiltinType::SveInt64x4: 5006 case clang::BuiltinType::SveUint8: 5007 case clang::BuiltinType::SveUint8x2: 5008 case clang::BuiltinType::SveUint8x3: 5009 case clang::BuiltinType::SveUint8x4: 5010 case clang::BuiltinType::SveUint16: 5011 case clang::BuiltinType::SveUint16x2: 5012 case clang::BuiltinType::SveUint16x3: 5013 case clang::BuiltinType::SveUint16x4: 5014 case clang::BuiltinType::SveUint32: 5015 case clang::BuiltinType::SveUint32x2: 5016 case clang::BuiltinType::SveUint32x3: 5017 case clang::BuiltinType::SveUint32x4: 5018 case clang::BuiltinType::SveUint64: 5019 case clang::BuiltinType::SveUint64x2: 5020 case clang::BuiltinType::SveUint64x3: 5021 case clang::BuiltinType::SveUint64x4: 5022 case clang::BuiltinType::SveFloat16: 5023 case clang::BuiltinType::SveBFloat16: 5024 case clang::BuiltinType::SveBFloat16x2: 5025 case clang::BuiltinType::SveBFloat16x3: 5026 case clang::BuiltinType::SveBFloat16x4: 5027 case clang::BuiltinType::SveFloat16x2: 5028 case clang::BuiltinType::SveFloat16x3: 5029 case clang::BuiltinType::SveFloat16x4: 5030 case clang::BuiltinType::SveFloat32: 5031 case clang::BuiltinType::SveFloat32x2: 5032 case clang::BuiltinType::SveFloat32x3: 5033 case clang::BuiltinType::SveFloat32x4: 5034 case clang::BuiltinType::SveFloat64: 5035 case clang::BuiltinType::SveFloat64x2: 5036 case clang::BuiltinType::SveFloat64x3: 5037 case clang::BuiltinType::SveFloat64x4: 5038 break; 5039 5040 // RISC-V V builtin types. 5041 #define RVV_TYPE(Name, Id, SingletonId) case clang::BuiltinType::Id: 5042 #include "clang/Basic/RISCVVTypes.def" 5043 break; 5044 5045 // WebAssembly builtin types. 5046 case clang::BuiltinType::WasmExternRef: 5047 break; 5048 5049 case clang::BuiltinType::IncompleteMatrixIdx: 5050 break; 5051 } 5052 break; 5053 // All pointer types are represented as unsigned integer encodings. We may 5054 // nee to add a eEncodingPointer if we ever need to know the difference 5055 case clang::Type::ObjCObjectPointer: 5056 case clang::Type::BlockPointer: 5057 case clang::Type::Pointer: 5058 case clang::Type::LValueReference: 5059 case clang::Type::RValueReference: 5060 case clang::Type::MemberPointer: 5061 return lldb::eEncodingUint; 5062 case clang::Type::Complex: { 5063 lldb::Encoding encoding = lldb::eEncodingIEEE754; 5064 if (qual_type->isComplexType()) 5065 encoding = lldb::eEncodingIEEE754; 5066 else { 5067 const clang::ComplexType *complex_type = 5068 qual_type->getAsComplexIntegerType(); 5069 if (complex_type) 5070 encoding = GetType(complex_type->getElementType()).GetEncoding(count); 5071 else 5072 encoding = lldb::eEncodingSint; 5073 } 5074 count = 2; 5075 return encoding; 5076 } 5077 5078 case clang::Type::ObjCInterface: 5079 break; 5080 case clang::Type::Record: 5081 break; 5082 case clang::Type::Enum: 5083 return qual_type->isUnsignedIntegerOrEnumerationType() 5084 ? lldb::eEncodingUint 5085 : lldb::eEncodingSint; 5086 case clang::Type::DependentSizedArray: 5087 case clang::Type::DependentSizedExtVector: 5088 case clang::Type::UnresolvedUsing: 5089 case clang::Type::Attributed: 5090 case clang::Type::BTFTagAttributed: 5091 case clang::Type::TemplateTypeParm: 5092 case clang::Type::SubstTemplateTypeParm: 5093 case clang::Type::SubstTemplateTypeParmPack: 5094 case clang::Type::InjectedClassName: 5095 case clang::Type::DependentName: 5096 case clang::Type::DependentTemplateSpecialization: 5097 case clang::Type::PackExpansion: 5098 case clang::Type::ObjCObject: 5099 5100 case clang::Type::TemplateSpecialization: 5101 case clang::Type::DeducedTemplateSpecialization: 5102 case clang::Type::Adjusted: 5103 case clang::Type::Pipe: 5104 break; 5105 5106 // pointer type decayed from an array or function type. 5107 case clang::Type::Decayed: 5108 break; 5109 case clang::Type::ObjCTypeParam: 5110 break; 5111 5112 case clang::Type::DependentAddressSpace: 5113 break; 5114 case clang::Type::MacroQualified: 5115 break; 5116 5117 case clang::Type::ConstantMatrix: 5118 case clang::Type::DependentSizedMatrix: 5119 break; 5120 } 5121 count = 0; 5122 return lldb::eEncodingInvalid; 5123 } 5124 5125 lldb::Format TypeSystemClang::GetFormat(lldb::opaque_compiler_type_t type) { 5126 if (!type) 5127 return lldb::eFormatDefault; 5128 5129 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 5130 5131 switch (qual_type->getTypeClass()) { 5132 case clang::Type::Atomic: 5133 case clang::Type::Auto: 5134 case clang::Type::Decltype: 5135 case clang::Type::Elaborated: 5136 case clang::Type::Paren: 5137 case clang::Type::Typedef: 5138 case clang::Type::TypeOf: 5139 case clang::Type::TypeOfExpr: 5140 case clang::Type::Using: 5141 llvm_unreachable("Handled in RemoveWrappingTypes!"); 5142 case clang::Type::UnaryTransform: 5143 break; 5144 5145 case clang::Type::FunctionNoProto: 5146 case clang::Type::FunctionProto: 5147 break; 5148 5149 case clang::Type::IncompleteArray: 5150 case clang::Type::VariableArray: 5151 break; 5152 5153 case clang::Type::ConstantArray: 5154 return lldb::eFormatVoid; // no value 5155 5156 case clang::Type::DependentVector: 5157 case clang::Type::ExtVector: 5158 case clang::Type::Vector: 5159 break; 5160 5161 case clang::Type::BitInt: 5162 case clang::Type::DependentBitInt: 5163 return qual_type->isUnsignedIntegerType() ? lldb::eFormatUnsigned 5164 : lldb::eFormatDecimal; 5165 5166 case clang::Type::Builtin: 5167 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) { 5168 case clang::BuiltinType::UnknownAny: 5169 case clang::BuiltinType::Void: 5170 case clang::BuiltinType::BoundMember: 5171 break; 5172 5173 case clang::BuiltinType::Bool: 5174 return lldb::eFormatBoolean; 5175 case clang::BuiltinType::Char_S: 5176 case clang::BuiltinType::SChar: 5177 case clang::BuiltinType::WChar_S: 5178 case clang::BuiltinType::Char_U: 5179 case clang::BuiltinType::UChar: 5180 case clang::BuiltinType::WChar_U: 5181 return lldb::eFormatChar; 5182 case clang::BuiltinType::Char8: 5183 return lldb::eFormatUnicode8; 5184 case clang::BuiltinType::Char16: 5185 return lldb::eFormatUnicode16; 5186 case clang::BuiltinType::Char32: 5187 return lldb::eFormatUnicode32; 5188 case clang::BuiltinType::UShort: 5189 return lldb::eFormatUnsigned; 5190 case clang::BuiltinType::Short: 5191 return lldb::eFormatDecimal; 5192 case clang::BuiltinType::UInt: 5193 return lldb::eFormatUnsigned; 5194 case clang::BuiltinType::Int: 5195 return lldb::eFormatDecimal; 5196 case clang::BuiltinType::ULong: 5197 return lldb::eFormatUnsigned; 5198 case clang::BuiltinType::Long: 5199 return lldb::eFormatDecimal; 5200 case clang::BuiltinType::ULongLong: 5201 return lldb::eFormatUnsigned; 5202 case clang::BuiltinType::LongLong: 5203 return lldb::eFormatDecimal; 5204 case clang::BuiltinType::UInt128: 5205 return lldb::eFormatUnsigned; 5206 case clang::BuiltinType::Int128: 5207 return lldb::eFormatDecimal; 5208 case clang::BuiltinType::Half: 5209 case clang::BuiltinType::Float: 5210 case clang::BuiltinType::Double: 5211 case clang::BuiltinType::LongDouble: 5212 return lldb::eFormatFloat; 5213 default: 5214 return lldb::eFormatHex; 5215 } 5216 break; 5217 case clang::Type::ObjCObjectPointer: 5218 return lldb::eFormatHex; 5219 case clang::Type::BlockPointer: 5220 return lldb::eFormatHex; 5221 case clang::Type::Pointer: 5222 return lldb::eFormatHex; 5223 case clang::Type::LValueReference: 5224 case clang::Type::RValueReference: 5225 return lldb::eFormatHex; 5226 case clang::Type::MemberPointer: 5227 return lldb::eFormatHex; 5228 case clang::Type::Complex: { 5229 if (qual_type->isComplexType()) 5230 return lldb::eFormatComplex; 5231 else 5232 return lldb::eFormatComplexInteger; 5233 } 5234 case clang::Type::ObjCInterface: 5235 break; 5236 case clang::Type::Record: 5237 break; 5238 case clang::Type::Enum: 5239 return lldb::eFormatEnum; 5240 case clang::Type::DependentSizedArray: 5241 case clang::Type::DependentSizedExtVector: 5242 case clang::Type::UnresolvedUsing: 5243 case clang::Type::Attributed: 5244 case clang::Type::BTFTagAttributed: 5245 case clang::Type::TemplateTypeParm: 5246 case clang::Type::SubstTemplateTypeParm: 5247 case clang::Type::SubstTemplateTypeParmPack: 5248 case clang::Type::InjectedClassName: 5249 case clang::Type::DependentName: 5250 case clang::Type::DependentTemplateSpecialization: 5251 case clang::Type::PackExpansion: 5252 case clang::Type::ObjCObject: 5253 5254 case clang::Type::TemplateSpecialization: 5255 case clang::Type::DeducedTemplateSpecialization: 5256 case clang::Type::Adjusted: 5257 case clang::Type::Pipe: 5258 break; 5259 5260 // pointer type decayed from an array or function type. 5261 case clang::Type::Decayed: 5262 break; 5263 case clang::Type::ObjCTypeParam: 5264 break; 5265 5266 case clang::Type::DependentAddressSpace: 5267 break; 5268 case clang::Type::MacroQualified: 5269 break; 5270 5271 // Matrix types we're not sure how to display yet. 5272 case clang::Type::ConstantMatrix: 5273 case clang::Type::DependentSizedMatrix: 5274 break; 5275 } 5276 // We don't know hot to display this type... 5277 return lldb::eFormatBytes; 5278 } 5279 5280 static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl, 5281 bool check_superclass) { 5282 while (class_interface_decl) { 5283 if (class_interface_decl->ivar_size() > 0) 5284 return true; 5285 5286 if (check_superclass) 5287 class_interface_decl = class_interface_decl->getSuperClass(); 5288 else 5289 break; 5290 } 5291 return false; 5292 } 5293 5294 static std::optional<SymbolFile::ArrayInfo> 5295 GetDynamicArrayInfo(TypeSystemClang &ast, SymbolFile *sym_file, 5296 clang::QualType qual_type, 5297 const ExecutionContext *exe_ctx) { 5298 if (qual_type->isIncompleteArrayType()) 5299 if (auto *metadata = ast.GetMetadata(qual_type.getTypePtr())) 5300 return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(), 5301 exe_ctx); 5302 return std::nullopt; 5303 } 5304 5305 uint32_t TypeSystemClang::GetNumChildren(lldb::opaque_compiler_type_t type, 5306 bool omit_empty_base_classes, 5307 const ExecutionContext *exe_ctx) { 5308 if (!type) 5309 return 0; 5310 5311 uint32_t num_children = 0; 5312 clang::QualType qual_type(RemoveWrappingTypes(GetQualType(type))); 5313 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 5314 switch (type_class) { 5315 case clang::Type::Builtin: 5316 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) { 5317 case clang::BuiltinType::ObjCId: // child is Class 5318 case clang::BuiltinType::ObjCClass: // child is Class 5319 num_children = 1; 5320 break; 5321 5322 default: 5323 break; 5324 } 5325 break; 5326 5327 case clang::Type::Complex: 5328 return 0; 5329 case clang::Type::Record: 5330 if (GetCompleteQualType(&getASTContext(), qual_type)) { 5331 const clang::RecordType *record_type = 5332 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 5333 const clang::RecordDecl *record_decl = record_type->getDecl(); 5334 assert(record_decl); 5335 const clang::CXXRecordDecl *cxx_record_decl = 5336 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 5337 if (cxx_record_decl) { 5338 if (omit_empty_base_classes) { 5339 // Check each base classes to see if it or any of its base classes 5340 // contain any fields. This can help limit the noise in variable 5341 // views by not having to show base classes that contain no members. 5342 clang::CXXRecordDecl::base_class_const_iterator base_class, 5343 base_class_end; 5344 for (base_class = cxx_record_decl->bases_begin(), 5345 base_class_end = cxx_record_decl->bases_end(); 5346 base_class != base_class_end; ++base_class) { 5347 const clang::CXXRecordDecl *base_class_decl = 5348 llvm::cast<clang::CXXRecordDecl>( 5349 base_class->getType() 5350 ->getAs<clang::RecordType>() 5351 ->getDecl()); 5352 5353 // Skip empty base classes 5354 if (!TypeSystemClang::RecordHasFields(base_class_decl)) 5355 continue; 5356 5357 num_children++; 5358 } 5359 } else { 5360 // Include all base classes 5361 num_children += cxx_record_decl->getNumBases(); 5362 } 5363 } 5364 clang::RecordDecl::field_iterator field, field_end; 5365 for (field = record_decl->field_begin(), 5366 field_end = record_decl->field_end(); 5367 field != field_end; ++field) 5368 ++num_children; 5369 } 5370 break; 5371 5372 case clang::Type::ObjCObject: 5373 case clang::Type::ObjCInterface: 5374 if (GetCompleteQualType(&getASTContext(), qual_type)) { 5375 const clang::ObjCObjectType *objc_class_type = 5376 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 5377 assert(objc_class_type); 5378 if (objc_class_type) { 5379 clang::ObjCInterfaceDecl *class_interface_decl = 5380 objc_class_type->getInterface(); 5381 5382 if (class_interface_decl) { 5383 5384 clang::ObjCInterfaceDecl *superclass_interface_decl = 5385 class_interface_decl->getSuperClass(); 5386 if (superclass_interface_decl) { 5387 if (omit_empty_base_classes) { 5388 if (ObjCDeclHasIVars(superclass_interface_decl, true)) 5389 ++num_children; 5390 } else 5391 ++num_children; 5392 } 5393 5394 num_children += class_interface_decl->ivar_size(); 5395 } 5396 } 5397 } 5398 break; 5399 5400 case clang::Type::LValueReference: 5401 case clang::Type::RValueReference: 5402 case clang::Type::ObjCObjectPointer: { 5403 CompilerType pointee_clang_type(GetPointeeType(type)); 5404 5405 uint32_t num_pointee_children = 0; 5406 if (pointee_clang_type.IsAggregateType()) 5407 num_pointee_children = 5408 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx); 5409 // If this type points to a simple type, then it has 1 child 5410 if (num_pointee_children == 0) 5411 num_children = 1; 5412 else 5413 num_children = num_pointee_children; 5414 } break; 5415 5416 case clang::Type::Vector: 5417 case clang::Type::ExtVector: 5418 num_children = 5419 llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements(); 5420 break; 5421 5422 case clang::Type::ConstantArray: 5423 num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr()) 5424 ->getSize() 5425 .getLimitedValue(); 5426 break; 5427 case clang::Type::IncompleteArray: 5428 if (auto array_info = 5429 GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx)) 5430 // Only 1-dimensional arrays are supported. 5431 num_children = array_info->element_orders.size() 5432 ? array_info->element_orders.back() 5433 : 0; 5434 break; 5435 5436 case clang::Type::Pointer: { 5437 const clang::PointerType *pointer_type = 5438 llvm::cast<clang::PointerType>(qual_type.getTypePtr()); 5439 clang::QualType pointee_type(pointer_type->getPointeeType()); 5440 CompilerType pointee_clang_type(GetType(pointee_type)); 5441 uint32_t num_pointee_children = 0; 5442 if (pointee_clang_type.IsAggregateType()) 5443 num_pointee_children = 5444 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx); 5445 if (num_pointee_children == 0) { 5446 // We have a pointer to a pointee type that claims it has no children. We 5447 // will want to look at 5448 num_children = GetNumPointeeChildren(pointee_type); 5449 } else 5450 num_children = num_pointee_children; 5451 } break; 5452 5453 default: 5454 break; 5455 } 5456 return num_children; 5457 } 5458 5459 CompilerType TypeSystemClang::GetBuiltinTypeByName(ConstString name) { 5460 return GetBasicType(GetBasicTypeEnumeration(name)); 5461 } 5462 5463 lldb::BasicType 5464 TypeSystemClang::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) { 5465 if (type) { 5466 clang::QualType qual_type(GetQualType(type)); 5467 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 5468 if (type_class == clang::Type::Builtin) { 5469 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) { 5470 case clang::BuiltinType::Void: 5471 return eBasicTypeVoid; 5472 case clang::BuiltinType::Bool: 5473 return eBasicTypeBool; 5474 case clang::BuiltinType::Char_S: 5475 return eBasicTypeSignedChar; 5476 case clang::BuiltinType::Char_U: 5477 return eBasicTypeUnsignedChar; 5478 case clang::BuiltinType::Char8: 5479 return eBasicTypeChar8; 5480 case clang::BuiltinType::Char16: 5481 return eBasicTypeChar16; 5482 case clang::BuiltinType::Char32: 5483 return eBasicTypeChar32; 5484 case clang::BuiltinType::UChar: 5485 return eBasicTypeUnsignedChar; 5486 case clang::BuiltinType::SChar: 5487 return eBasicTypeSignedChar; 5488 case clang::BuiltinType::WChar_S: 5489 return eBasicTypeSignedWChar; 5490 case clang::BuiltinType::WChar_U: 5491 return eBasicTypeUnsignedWChar; 5492 case clang::BuiltinType::Short: 5493 return eBasicTypeShort; 5494 case clang::BuiltinType::UShort: 5495 return eBasicTypeUnsignedShort; 5496 case clang::BuiltinType::Int: 5497 return eBasicTypeInt; 5498 case clang::BuiltinType::UInt: 5499 return eBasicTypeUnsignedInt; 5500 case clang::BuiltinType::Long: 5501 return eBasicTypeLong; 5502 case clang::BuiltinType::ULong: 5503 return eBasicTypeUnsignedLong; 5504 case clang::BuiltinType::LongLong: 5505 return eBasicTypeLongLong; 5506 case clang::BuiltinType::ULongLong: 5507 return eBasicTypeUnsignedLongLong; 5508 case clang::BuiltinType::Int128: 5509 return eBasicTypeInt128; 5510 case clang::BuiltinType::UInt128: 5511 return eBasicTypeUnsignedInt128; 5512 5513 case clang::BuiltinType::Half: 5514 return eBasicTypeHalf; 5515 case clang::BuiltinType::Float: 5516 return eBasicTypeFloat; 5517 case clang::BuiltinType::Double: 5518 return eBasicTypeDouble; 5519 case clang::BuiltinType::LongDouble: 5520 return eBasicTypeLongDouble; 5521 5522 case clang::BuiltinType::NullPtr: 5523 return eBasicTypeNullPtr; 5524 case clang::BuiltinType::ObjCId: 5525 return eBasicTypeObjCID; 5526 case clang::BuiltinType::ObjCClass: 5527 return eBasicTypeObjCClass; 5528 case clang::BuiltinType::ObjCSel: 5529 return eBasicTypeObjCSel; 5530 default: 5531 return eBasicTypeOther; 5532 } 5533 } 5534 } 5535 return eBasicTypeInvalid; 5536 } 5537 5538 void TypeSystemClang::ForEachEnumerator( 5539 lldb::opaque_compiler_type_t type, 5540 std::function<bool(const CompilerType &integer_type, 5541 ConstString name, 5542 const llvm::APSInt &value)> const &callback) { 5543 const clang::EnumType *enum_type = 5544 llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type)); 5545 if (enum_type) { 5546 const clang::EnumDecl *enum_decl = enum_type->getDecl(); 5547 if (enum_decl) { 5548 CompilerType integer_type = GetType(enum_decl->getIntegerType()); 5549 5550 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos; 5551 for (enum_pos = enum_decl->enumerator_begin(), 5552 enum_end_pos = enum_decl->enumerator_end(); 5553 enum_pos != enum_end_pos; ++enum_pos) { 5554 ConstString name(enum_pos->getNameAsString().c_str()); 5555 if (!callback(integer_type, name, enum_pos->getInitVal())) 5556 break; 5557 } 5558 } 5559 } 5560 } 5561 5562 #pragma mark Aggregate Types 5563 5564 uint32_t TypeSystemClang::GetNumFields(lldb::opaque_compiler_type_t type) { 5565 if (!type) 5566 return 0; 5567 5568 uint32_t count = 0; 5569 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); 5570 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 5571 switch (type_class) { 5572 case clang::Type::Record: 5573 if (GetCompleteType(type)) { 5574 const clang::RecordType *record_type = 5575 llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr()); 5576 if (record_type) { 5577 clang::RecordDecl *record_decl = record_type->getDecl(); 5578 if (record_decl) { 5579 uint32_t field_idx = 0; 5580 clang::RecordDecl::field_iterator field, field_end; 5581 for (field = record_decl->field_begin(), 5582 field_end = record_decl->field_end(); 5583 field != field_end; ++field) 5584 ++field_idx; 5585 count = field_idx; 5586 } 5587 } 5588 } 5589 break; 5590 5591 case clang::Type::ObjCObjectPointer: { 5592 const clang::ObjCObjectPointerType *objc_class_type = 5593 qual_type->castAs<clang::ObjCObjectPointerType>(); 5594 const clang::ObjCInterfaceType *objc_interface_type = 5595 objc_class_type->getInterfaceType(); 5596 if (objc_interface_type && 5597 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>( 5598 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) { 5599 clang::ObjCInterfaceDecl *class_interface_decl = 5600 objc_interface_type->getDecl(); 5601 if (class_interface_decl) { 5602 count = class_interface_decl->ivar_size(); 5603 } 5604 } 5605 break; 5606 } 5607 5608 case clang::Type::ObjCObject: 5609 case clang::Type::ObjCInterface: 5610 if (GetCompleteType(type)) { 5611 const clang::ObjCObjectType *objc_class_type = 5612 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 5613 if (objc_class_type) { 5614 clang::ObjCInterfaceDecl *class_interface_decl = 5615 objc_class_type->getInterface(); 5616 5617 if (class_interface_decl) 5618 count = class_interface_decl->ivar_size(); 5619 } 5620 } 5621 break; 5622 5623 default: 5624 break; 5625 } 5626 return count; 5627 } 5628 5629 static lldb::opaque_compiler_type_t 5630 GetObjCFieldAtIndex(clang::ASTContext *ast, 5631 clang::ObjCInterfaceDecl *class_interface_decl, size_t idx, 5632 std::string &name, uint64_t *bit_offset_ptr, 5633 uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) { 5634 if (class_interface_decl) { 5635 if (idx < (class_interface_decl->ivar_size())) { 5636 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos, 5637 ivar_end = class_interface_decl->ivar_end(); 5638 uint32_t ivar_idx = 0; 5639 5640 for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; 5641 ++ivar_pos, ++ivar_idx) { 5642 if (ivar_idx == idx) { 5643 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos; 5644 5645 clang::QualType ivar_qual_type(ivar_decl->getType()); 5646 5647 name.assign(ivar_decl->getNameAsString()); 5648 5649 if (bit_offset_ptr) { 5650 const clang::ASTRecordLayout &interface_layout = 5651 ast->getASTObjCInterfaceLayout(class_interface_decl); 5652 *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx); 5653 } 5654 5655 const bool is_bitfield = ivar_pos->isBitField(); 5656 5657 if (bitfield_bit_size_ptr) { 5658 *bitfield_bit_size_ptr = 0; 5659 5660 if (is_bitfield && ast) { 5661 clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth(); 5662 clang::Expr::EvalResult result; 5663 if (bitfield_bit_size_expr && 5664 bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) { 5665 llvm::APSInt bitfield_apsint = result.Val.getInt(); 5666 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue(); 5667 } 5668 } 5669 } 5670 if (is_bitfield_ptr) 5671 *is_bitfield_ptr = is_bitfield; 5672 5673 return ivar_qual_type.getAsOpaquePtr(); 5674 } 5675 } 5676 } 5677 } 5678 return nullptr; 5679 } 5680 5681 CompilerType TypeSystemClang::GetFieldAtIndex(lldb::opaque_compiler_type_t type, 5682 size_t idx, std::string &name, 5683 uint64_t *bit_offset_ptr, 5684 uint32_t *bitfield_bit_size_ptr, 5685 bool *is_bitfield_ptr) { 5686 if (!type) 5687 return CompilerType(); 5688 5689 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); 5690 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 5691 switch (type_class) { 5692 case clang::Type::Record: 5693 if (GetCompleteType(type)) { 5694 const clang::RecordType *record_type = 5695 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 5696 const clang::RecordDecl *record_decl = record_type->getDecl(); 5697 uint32_t field_idx = 0; 5698 clang::RecordDecl::field_iterator field, field_end; 5699 for (field = record_decl->field_begin(), 5700 field_end = record_decl->field_end(); 5701 field != field_end; ++field, ++field_idx) { 5702 if (idx == field_idx) { 5703 // Print the member type if requested 5704 // Print the member name and equal sign 5705 name.assign(field->getNameAsString()); 5706 5707 // Figure out the type byte size (field_type_info.first) and 5708 // alignment (field_type_info.second) from the AST context. 5709 if (bit_offset_ptr) { 5710 const clang::ASTRecordLayout &record_layout = 5711 getASTContext().getASTRecordLayout(record_decl); 5712 *bit_offset_ptr = record_layout.getFieldOffset(field_idx); 5713 } 5714 5715 const bool is_bitfield = field->isBitField(); 5716 5717 if (bitfield_bit_size_ptr) { 5718 *bitfield_bit_size_ptr = 0; 5719 5720 if (is_bitfield) { 5721 clang::Expr *bitfield_bit_size_expr = field->getBitWidth(); 5722 clang::Expr::EvalResult result; 5723 if (bitfield_bit_size_expr && 5724 bitfield_bit_size_expr->EvaluateAsInt(result, 5725 getASTContext())) { 5726 llvm::APSInt bitfield_apsint = result.Val.getInt(); 5727 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue(); 5728 } 5729 } 5730 } 5731 if (is_bitfield_ptr) 5732 *is_bitfield_ptr = is_bitfield; 5733 5734 return GetType(field->getType()); 5735 } 5736 } 5737 } 5738 break; 5739 5740 case clang::Type::ObjCObjectPointer: { 5741 const clang::ObjCObjectPointerType *objc_class_type = 5742 qual_type->castAs<clang::ObjCObjectPointerType>(); 5743 const clang::ObjCInterfaceType *objc_interface_type = 5744 objc_class_type->getInterfaceType(); 5745 if (objc_interface_type && 5746 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>( 5747 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) { 5748 clang::ObjCInterfaceDecl *class_interface_decl = 5749 objc_interface_type->getDecl(); 5750 if (class_interface_decl) { 5751 return CompilerType( 5752 weak_from_this(), 5753 GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx, 5754 name, bit_offset_ptr, bitfield_bit_size_ptr, 5755 is_bitfield_ptr)); 5756 } 5757 } 5758 break; 5759 } 5760 5761 case clang::Type::ObjCObject: 5762 case clang::Type::ObjCInterface: 5763 if (GetCompleteType(type)) { 5764 const clang::ObjCObjectType *objc_class_type = 5765 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 5766 assert(objc_class_type); 5767 if (objc_class_type) { 5768 clang::ObjCInterfaceDecl *class_interface_decl = 5769 objc_class_type->getInterface(); 5770 return CompilerType( 5771 weak_from_this(), 5772 GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx, 5773 name, bit_offset_ptr, bitfield_bit_size_ptr, 5774 is_bitfield_ptr)); 5775 } 5776 } 5777 break; 5778 5779 default: 5780 break; 5781 } 5782 return CompilerType(); 5783 } 5784 5785 uint32_t 5786 TypeSystemClang::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) { 5787 uint32_t count = 0; 5788 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 5789 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 5790 switch (type_class) { 5791 case clang::Type::Record: 5792 if (GetCompleteType(type)) { 5793 const clang::CXXRecordDecl *cxx_record_decl = 5794 qual_type->getAsCXXRecordDecl(); 5795 if (cxx_record_decl) 5796 count = cxx_record_decl->getNumBases(); 5797 } 5798 break; 5799 5800 case clang::Type::ObjCObjectPointer: 5801 count = GetPointeeType(type).GetNumDirectBaseClasses(); 5802 break; 5803 5804 case clang::Type::ObjCObject: 5805 if (GetCompleteType(type)) { 5806 const clang::ObjCObjectType *objc_class_type = 5807 qual_type->getAsObjCQualifiedInterfaceType(); 5808 if (objc_class_type) { 5809 clang::ObjCInterfaceDecl *class_interface_decl = 5810 objc_class_type->getInterface(); 5811 5812 if (class_interface_decl && class_interface_decl->getSuperClass()) 5813 count = 1; 5814 } 5815 } 5816 break; 5817 case clang::Type::ObjCInterface: 5818 if (GetCompleteType(type)) { 5819 const clang::ObjCInterfaceType *objc_interface_type = 5820 qual_type->getAs<clang::ObjCInterfaceType>(); 5821 if (objc_interface_type) { 5822 clang::ObjCInterfaceDecl *class_interface_decl = 5823 objc_interface_type->getInterface(); 5824 5825 if (class_interface_decl && class_interface_decl->getSuperClass()) 5826 count = 1; 5827 } 5828 } 5829 break; 5830 5831 default: 5832 break; 5833 } 5834 return count; 5835 } 5836 5837 uint32_t 5838 TypeSystemClang::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) { 5839 uint32_t count = 0; 5840 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 5841 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 5842 switch (type_class) { 5843 case clang::Type::Record: 5844 if (GetCompleteType(type)) { 5845 const clang::CXXRecordDecl *cxx_record_decl = 5846 qual_type->getAsCXXRecordDecl(); 5847 if (cxx_record_decl) 5848 count = cxx_record_decl->getNumVBases(); 5849 } 5850 break; 5851 5852 default: 5853 break; 5854 } 5855 return count; 5856 } 5857 5858 CompilerType TypeSystemClang::GetDirectBaseClassAtIndex( 5859 lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) { 5860 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 5861 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 5862 switch (type_class) { 5863 case clang::Type::Record: 5864 if (GetCompleteType(type)) { 5865 const clang::CXXRecordDecl *cxx_record_decl = 5866 qual_type->getAsCXXRecordDecl(); 5867 if (cxx_record_decl) { 5868 uint32_t curr_idx = 0; 5869 clang::CXXRecordDecl::base_class_const_iterator base_class, 5870 base_class_end; 5871 for (base_class = cxx_record_decl->bases_begin(), 5872 base_class_end = cxx_record_decl->bases_end(); 5873 base_class != base_class_end; ++base_class, ++curr_idx) { 5874 if (curr_idx == idx) { 5875 if (bit_offset_ptr) { 5876 const clang::ASTRecordLayout &record_layout = 5877 getASTContext().getASTRecordLayout(cxx_record_decl); 5878 const clang::CXXRecordDecl *base_class_decl = 5879 llvm::cast<clang::CXXRecordDecl>( 5880 base_class->getType() 5881 ->castAs<clang::RecordType>() 5882 ->getDecl()); 5883 if (base_class->isVirtual()) 5884 *bit_offset_ptr = 5885 record_layout.getVBaseClassOffset(base_class_decl) 5886 .getQuantity() * 5887 8; 5888 else 5889 *bit_offset_ptr = 5890 record_layout.getBaseClassOffset(base_class_decl) 5891 .getQuantity() * 5892 8; 5893 } 5894 return GetType(base_class->getType()); 5895 } 5896 } 5897 } 5898 } 5899 break; 5900 5901 case clang::Type::ObjCObjectPointer: 5902 return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr); 5903 5904 case clang::Type::ObjCObject: 5905 if (idx == 0 && GetCompleteType(type)) { 5906 const clang::ObjCObjectType *objc_class_type = 5907 qual_type->getAsObjCQualifiedInterfaceType(); 5908 if (objc_class_type) { 5909 clang::ObjCInterfaceDecl *class_interface_decl = 5910 objc_class_type->getInterface(); 5911 5912 if (class_interface_decl) { 5913 clang::ObjCInterfaceDecl *superclass_interface_decl = 5914 class_interface_decl->getSuperClass(); 5915 if (superclass_interface_decl) { 5916 if (bit_offset_ptr) 5917 *bit_offset_ptr = 0; 5918 return GetType(getASTContext().getObjCInterfaceType( 5919 superclass_interface_decl)); 5920 } 5921 } 5922 } 5923 } 5924 break; 5925 case clang::Type::ObjCInterface: 5926 if (idx == 0 && GetCompleteType(type)) { 5927 const clang::ObjCObjectType *objc_interface_type = 5928 qual_type->getAs<clang::ObjCInterfaceType>(); 5929 if (objc_interface_type) { 5930 clang::ObjCInterfaceDecl *class_interface_decl = 5931 objc_interface_type->getInterface(); 5932 5933 if (class_interface_decl) { 5934 clang::ObjCInterfaceDecl *superclass_interface_decl = 5935 class_interface_decl->getSuperClass(); 5936 if (superclass_interface_decl) { 5937 if (bit_offset_ptr) 5938 *bit_offset_ptr = 0; 5939 return GetType(getASTContext().getObjCInterfaceType( 5940 superclass_interface_decl)); 5941 } 5942 } 5943 } 5944 } 5945 break; 5946 5947 default: 5948 break; 5949 } 5950 return CompilerType(); 5951 } 5952 5953 CompilerType TypeSystemClang::GetVirtualBaseClassAtIndex( 5954 lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) { 5955 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 5956 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 5957 switch (type_class) { 5958 case clang::Type::Record: 5959 if (GetCompleteType(type)) { 5960 const clang::CXXRecordDecl *cxx_record_decl = 5961 qual_type->getAsCXXRecordDecl(); 5962 if (cxx_record_decl) { 5963 uint32_t curr_idx = 0; 5964 clang::CXXRecordDecl::base_class_const_iterator base_class, 5965 base_class_end; 5966 for (base_class = cxx_record_decl->vbases_begin(), 5967 base_class_end = cxx_record_decl->vbases_end(); 5968 base_class != base_class_end; ++base_class, ++curr_idx) { 5969 if (curr_idx == idx) { 5970 if (bit_offset_ptr) { 5971 const clang::ASTRecordLayout &record_layout = 5972 getASTContext().getASTRecordLayout(cxx_record_decl); 5973 const clang::CXXRecordDecl *base_class_decl = 5974 llvm::cast<clang::CXXRecordDecl>( 5975 base_class->getType() 5976 ->castAs<clang::RecordType>() 5977 ->getDecl()); 5978 *bit_offset_ptr = 5979 record_layout.getVBaseClassOffset(base_class_decl) 5980 .getQuantity() * 5981 8; 5982 } 5983 return GetType(base_class->getType()); 5984 } 5985 } 5986 } 5987 } 5988 break; 5989 5990 default: 5991 break; 5992 } 5993 return CompilerType(); 5994 } 5995 5996 // If a pointer to a pointee type (the clang_type arg) says that it has no 5997 // children, then we either need to trust it, or override it and return a 5998 // different result. For example, an "int *" has one child that is an integer, 5999 // but a function pointer doesn't have any children. Likewise if a Record type 6000 // claims it has no children, then there really is nothing to show. 6001 uint32_t TypeSystemClang::GetNumPointeeChildren(clang::QualType type) { 6002 if (type.isNull()) 6003 return 0; 6004 6005 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType()); 6006 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 6007 switch (type_class) { 6008 case clang::Type::Builtin: 6009 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) { 6010 case clang::BuiltinType::UnknownAny: 6011 case clang::BuiltinType::Void: 6012 case clang::BuiltinType::NullPtr: 6013 case clang::BuiltinType::OCLEvent: 6014 case clang::BuiltinType::OCLImage1dRO: 6015 case clang::BuiltinType::OCLImage1dWO: 6016 case clang::BuiltinType::OCLImage1dRW: 6017 case clang::BuiltinType::OCLImage1dArrayRO: 6018 case clang::BuiltinType::OCLImage1dArrayWO: 6019 case clang::BuiltinType::OCLImage1dArrayRW: 6020 case clang::BuiltinType::OCLImage1dBufferRO: 6021 case clang::BuiltinType::OCLImage1dBufferWO: 6022 case clang::BuiltinType::OCLImage1dBufferRW: 6023 case clang::BuiltinType::OCLImage2dRO: 6024 case clang::BuiltinType::OCLImage2dWO: 6025 case clang::BuiltinType::OCLImage2dRW: 6026 case clang::BuiltinType::OCLImage2dArrayRO: 6027 case clang::BuiltinType::OCLImage2dArrayWO: 6028 case clang::BuiltinType::OCLImage2dArrayRW: 6029 case clang::BuiltinType::OCLImage3dRO: 6030 case clang::BuiltinType::OCLImage3dWO: 6031 case clang::BuiltinType::OCLImage3dRW: 6032 case clang::BuiltinType::OCLSampler: 6033 return 0; 6034 case clang::BuiltinType::Bool: 6035 case clang::BuiltinType::Char_U: 6036 case clang::BuiltinType::UChar: 6037 case clang::BuiltinType::WChar_U: 6038 case clang::BuiltinType::Char16: 6039 case clang::BuiltinType::Char32: 6040 case clang::BuiltinType::UShort: 6041 case clang::BuiltinType::UInt: 6042 case clang::BuiltinType::ULong: 6043 case clang::BuiltinType::ULongLong: 6044 case clang::BuiltinType::UInt128: 6045 case clang::BuiltinType::Char_S: 6046 case clang::BuiltinType::SChar: 6047 case clang::BuiltinType::WChar_S: 6048 case clang::BuiltinType::Short: 6049 case clang::BuiltinType::Int: 6050 case clang::BuiltinType::Long: 6051 case clang::BuiltinType::LongLong: 6052 case clang::BuiltinType::Int128: 6053 case clang::BuiltinType::Float: 6054 case clang::BuiltinType::Double: 6055 case clang::BuiltinType::LongDouble: 6056 case clang::BuiltinType::Dependent: 6057 case clang::BuiltinType::Overload: 6058 case clang::BuiltinType::ObjCId: 6059 case clang::BuiltinType::ObjCClass: 6060 case clang::BuiltinType::ObjCSel: 6061 case clang::BuiltinType::BoundMember: 6062 case clang::BuiltinType::Half: 6063 case clang::BuiltinType::ARCUnbridgedCast: 6064 case clang::BuiltinType::PseudoObject: 6065 case clang::BuiltinType::BuiltinFn: 6066 case clang::BuiltinType::OMPArraySection: 6067 return 1; 6068 default: 6069 return 0; 6070 } 6071 break; 6072 6073 case clang::Type::Complex: 6074 return 1; 6075 case clang::Type::Pointer: 6076 return 1; 6077 case clang::Type::BlockPointer: 6078 return 0; // If block pointers don't have debug info, then no children for 6079 // them 6080 case clang::Type::LValueReference: 6081 return 1; 6082 case clang::Type::RValueReference: 6083 return 1; 6084 case clang::Type::MemberPointer: 6085 return 0; 6086 case clang::Type::ConstantArray: 6087 return 0; 6088 case clang::Type::IncompleteArray: 6089 return 0; 6090 case clang::Type::VariableArray: 6091 return 0; 6092 case clang::Type::DependentSizedArray: 6093 return 0; 6094 case clang::Type::DependentSizedExtVector: 6095 return 0; 6096 case clang::Type::Vector: 6097 return 0; 6098 case clang::Type::ExtVector: 6099 return 0; 6100 case clang::Type::FunctionProto: 6101 return 0; // When we function pointers, they have no children... 6102 case clang::Type::FunctionNoProto: 6103 return 0; // When we function pointers, they have no children... 6104 case clang::Type::UnresolvedUsing: 6105 return 0; 6106 case clang::Type::Record: 6107 return 0; 6108 case clang::Type::Enum: 6109 return 1; 6110 case clang::Type::TemplateTypeParm: 6111 return 1; 6112 case clang::Type::SubstTemplateTypeParm: 6113 return 1; 6114 case clang::Type::TemplateSpecialization: 6115 return 1; 6116 case clang::Type::InjectedClassName: 6117 return 0; 6118 case clang::Type::DependentName: 6119 return 1; 6120 case clang::Type::DependentTemplateSpecialization: 6121 return 1; 6122 case clang::Type::ObjCObject: 6123 return 0; 6124 case clang::Type::ObjCInterface: 6125 return 0; 6126 case clang::Type::ObjCObjectPointer: 6127 return 1; 6128 default: 6129 break; 6130 } 6131 return 0; 6132 } 6133 6134 CompilerType TypeSystemClang::GetChildCompilerTypeAtIndex( 6135 lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx, 6136 bool transparent_pointers, bool omit_empty_base_classes, 6137 bool ignore_array_bounds, std::string &child_name, 6138 uint32_t &child_byte_size, int32_t &child_byte_offset, 6139 uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset, 6140 bool &child_is_base_class, bool &child_is_deref_of_parent, 6141 ValueObject *valobj, uint64_t &language_flags) { 6142 if (!type) 6143 return CompilerType(); 6144 6145 auto get_exe_scope = [&exe_ctx]() { 6146 return exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr; 6147 }; 6148 6149 clang::QualType parent_qual_type( 6150 RemoveWrappingTypes(GetCanonicalQualType(type))); 6151 const clang::Type::TypeClass parent_type_class = 6152 parent_qual_type->getTypeClass(); 6153 child_bitfield_bit_size = 0; 6154 child_bitfield_bit_offset = 0; 6155 child_is_base_class = false; 6156 language_flags = 0; 6157 6158 const bool idx_is_valid = 6159 idx < GetNumChildren(type, omit_empty_base_classes, exe_ctx); 6160 int32_t bit_offset; 6161 switch (parent_type_class) { 6162 case clang::Type::Builtin: 6163 if (idx_is_valid) { 6164 switch (llvm::cast<clang::BuiltinType>(parent_qual_type)->getKind()) { 6165 case clang::BuiltinType::ObjCId: 6166 case clang::BuiltinType::ObjCClass: 6167 child_name = "isa"; 6168 child_byte_size = 6169 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy) / 6170 CHAR_BIT; 6171 return GetType(getASTContext().ObjCBuiltinClassTy); 6172 6173 default: 6174 break; 6175 } 6176 } 6177 break; 6178 6179 case clang::Type::Record: 6180 if (idx_is_valid && GetCompleteType(type)) { 6181 const clang::RecordType *record_type = 6182 llvm::cast<clang::RecordType>(parent_qual_type.getTypePtr()); 6183 const clang::RecordDecl *record_decl = record_type->getDecl(); 6184 assert(record_decl); 6185 const clang::ASTRecordLayout &record_layout = 6186 getASTContext().getASTRecordLayout(record_decl); 6187 uint32_t child_idx = 0; 6188 6189 const clang::CXXRecordDecl *cxx_record_decl = 6190 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 6191 if (cxx_record_decl) { 6192 // We might have base classes to print out first 6193 clang::CXXRecordDecl::base_class_const_iterator base_class, 6194 base_class_end; 6195 for (base_class = cxx_record_decl->bases_begin(), 6196 base_class_end = cxx_record_decl->bases_end(); 6197 base_class != base_class_end; ++base_class) { 6198 const clang::CXXRecordDecl *base_class_decl = nullptr; 6199 6200 // Skip empty base classes 6201 if (omit_empty_base_classes) { 6202 base_class_decl = llvm::cast<clang::CXXRecordDecl>( 6203 base_class->getType()->getAs<clang::RecordType>()->getDecl()); 6204 if (!TypeSystemClang::RecordHasFields(base_class_decl)) 6205 continue; 6206 } 6207 6208 if (idx == child_idx) { 6209 if (base_class_decl == nullptr) 6210 base_class_decl = llvm::cast<clang::CXXRecordDecl>( 6211 base_class->getType()->getAs<clang::RecordType>()->getDecl()); 6212 6213 if (base_class->isVirtual()) { 6214 bool handled = false; 6215 if (valobj) { 6216 clang::VTableContextBase *vtable_ctx = 6217 getASTContext().getVTableContext(); 6218 if (vtable_ctx) 6219 handled = GetVBaseBitOffset(*vtable_ctx, *valobj, 6220 record_layout, cxx_record_decl, 6221 base_class_decl, bit_offset); 6222 } 6223 if (!handled) 6224 bit_offset = record_layout.getVBaseClassOffset(base_class_decl) 6225 .getQuantity() * 6226 8; 6227 } else 6228 bit_offset = record_layout.getBaseClassOffset(base_class_decl) 6229 .getQuantity() * 6230 8; 6231 6232 // Base classes should be a multiple of 8 bits in size 6233 child_byte_offset = bit_offset / 8; 6234 CompilerType base_class_clang_type = GetType(base_class->getType()); 6235 child_name = base_class_clang_type.GetTypeName().AsCString(""); 6236 std::optional<uint64_t> size = 6237 base_class_clang_type.GetBitSize(get_exe_scope()); 6238 if (!size) 6239 return {}; 6240 uint64_t base_class_clang_type_bit_size = *size; 6241 6242 // Base classes bit sizes should be a multiple of 8 bits in size 6243 assert(base_class_clang_type_bit_size % 8 == 0); 6244 child_byte_size = base_class_clang_type_bit_size / 8; 6245 child_is_base_class = true; 6246 return base_class_clang_type; 6247 } 6248 // We don't increment the child index in the for loop since we might 6249 // be skipping empty base classes 6250 ++child_idx; 6251 } 6252 } 6253 // Make sure index is in range... 6254 uint32_t field_idx = 0; 6255 clang::RecordDecl::field_iterator field, field_end; 6256 for (field = record_decl->field_begin(), 6257 field_end = record_decl->field_end(); 6258 field != field_end; ++field, ++field_idx, ++child_idx) { 6259 if (idx == child_idx) { 6260 // Print the member type if requested 6261 // Print the member name and equal sign 6262 child_name.assign(field->getNameAsString()); 6263 6264 // Figure out the type byte size (field_type_info.first) and 6265 // alignment (field_type_info.second) from the AST context. 6266 CompilerType field_clang_type = GetType(field->getType()); 6267 assert(field_idx < record_layout.getFieldCount()); 6268 std::optional<uint64_t> size = 6269 field_clang_type.GetByteSize(get_exe_scope()); 6270 if (!size) 6271 return {}; 6272 child_byte_size = *size; 6273 const uint32_t child_bit_size = child_byte_size * 8; 6274 6275 // Figure out the field offset within the current struct/union/class 6276 // type 6277 bit_offset = record_layout.getFieldOffset(field_idx); 6278 if (FieldIsBitfield(*field, child_bitfield_bit_size)) { 6279 child_bitfield_bit_offset = bit_offset % child_bit_size; 6280 const uint32_t child_bit_offset = 6281 bit_offset - child_bitfield_bit_offset; 6282 child_byte_offset = child_bit_offset / 8; 6283 } else { 6284 child_byte_offset = bit_offset / 8; 6285 } 6286 6287 return field_clang_type; 6288 } 6289 } 6290 } 6291 break; 6292 6293 case clang::Type::ObjCObject: 6294 case clang::Type::ObjCInterface: 6295 if (idx_is_valid && GetCompleteType(type)) { 6296 const clang::ObjCObjectType *objc_class_type = 6297 llvm::dyn_cast<clang::ObjCObjectType>(parent_qual_type.getTypePtr()); 6298 assert(objc_class_type); 6299 if (objc_class_type) { 6300 uint32_t child_idx = 0; 6301 clang::ObjCInterfaceDecl *class_interface_decl = 6302 objc_class_type->getInterface(); 6303 6304 if (class_interface_decl) { 6305 6306 const clang::ASTRecordLayout &interface_layout = 6307 getASTContext().getASTObjCInterfaceLayout(class_interface_decl); 6308 clang::ObjCInterfaceDecl *superclass_interface_decl = 6309 class_interface_decl->getSuperClass(); 6310 if (superclass_interface_decl) { 6311 if (omit_empty_base_classes) { 6312 CompilerType base_class_clang_type = 6313 GetType(getASTContext().getObjCInterfaceType( 6314 superclass_interface_decl)); 6315 if (base_class_clang_type.GetNumChildren(omit_empty_base_classes, 6316 exe_ctx) > 0) { 6317 if (idx == 0) { 6318 clang::QualType ivar_qual_type( 6319 getASTContext().getObjCInterfaceType( 6320 superclass_interface_decl)); 6321 6322 child_name.assign( 6323 superclass_interface_decl->getNameAsString()); 6324 6325 clang::TypeInfo ivar_type_info = 6326 getASTContext().getTypeInfo(ivar_qual_type.getTypePtr()); 6327 6328 child_byte_size = ivar_type_info.Width / 8; 6329 child_byte_offset = 0; 6330 child_is_base_class = true; 6331 6332 return GetType(ivar_qual_type); 6333 } 6334 6335 ++child_idx; 6336 } 6337 } else 6338 ++child_idx; 6339 } 6340 6341 const uint32_t superclass_idx = child_idx; 6342 6343 if (idx < (child_idx + class_interface_decl->ivar_size())) { 6344 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos, 6345 ivar_end = class_interface_decl->ivar_end(); 6346 6347 for (ivar_pos = class_interface_decl->ivar_begin(); 6348 ivar_pos != ivar_end; ++ivar_pos) { 6349 if (child_idx == idx) { 6350 clang::ObjCIvarDecl *ivar_decl = *ivar_pos; 6351 6352 clang::QualType ivar_qual_type(ivar_decl->getType()); 6353 6354 child_name.assign(ivar_decl->getNameAsString()); 6355 6356 clang::TypeInfo ivar_type_info = 6357 getASTContext().getTypeInfo(ivar_qual_type.getTypePtr()); 6358 6359 child_byte_size = ivar_type_info.Width / 8; 6360 6361 // Figure out the field offset within the current 6362 // struct/union/class type For ObjC objects, we can't trust the 6363 // bit offset we get from the Clang AST, since that doesn't 6364 // account for the space taken up by unbacked properties, or 6365 // from the changing size of base classes that are newer than 6366 // this class. So if we have a process around that we can ask 6367 // about this object, do so. 6368 child_byte_offset = LLDB_INVALID_IVAR_OFFSET; 6369 Process *process = nullptr; 6370 if (exe_ctx) 6371 process = exe_ctx->GetProcessPtr(); 6372 if (process) { 6373 ObjCLanguageRuntime *objc_runtime = 6374 ObjCLanguageRuntime::Get(*process); 6375 if (objc_runtime != nullptr) { 6376 CompilerType parent_ast_type = GetType(parent_qual_type); 6377 child_byte_offset = objc_runtime->GetByteOffsetForIvar( 6378 parent_ast_type, ivar_decl->getNameAsString().c_str()); 6379 } 6380 } 6381 6382 // Setting this to INT32_MAX to make sure we don't compute it 6383 // twice... 6384 bit_offset = INT32_MAX; 6385 6386 if (child_byte_offset == 6387 static_cast<int32_t>(LLDB_INVALID_IVAR_OFFSET)) { 6388 bit_offset = interface_layout.getFieldOffset(child_idx - 6389 superclass_idx); 6390 child_byte_offset = bit_offset / 8; 6391 } 6392 6393 // Note, the ObjC Ivar Byte offset is just that, it doesn't 6394 // account for the bit offset of a bitfield within its 6395 // containing object. So regardless of where we get the byte 6396 // offset from, we still need to get the bit offset for 6397 // bitfields from the layout. 6398 6399 if (FieldIsBitfield(ivar_decl, child_bitfield_bit_size)) { 6400 if (bit_offset == INT32_MAX) 6401 bit_offset = interface_layout.getFieldOffset( 6402 child_idx - superclass_idx); 6403 6404 child_bitfield_bit_offset = bit_offset % 8; 6405 } 6406 return GetType(ivar_qual_type); 6407 } 6408 ++child_idx; 6409 } 6410 } 6411 } 6412 } 6413 } 6414 break; 6415 6416 case clang::Type::ObjCObjectPointer: 6417 if (idx_is_valid) { 6418 CompilerType pointee_clang_type(GetPointeeType(type)); 6419 6420 if (transparent_pointers && pointee_clang_type.IsAggregateType()) { 6421 child_is_deref_of_parent = false; 6422 bool tmp_child_is_deref_of_parent = false; 6423 return pointee_clang_type.GetChildCompilerTypeAtIndex( 6424 exe_ctx, idx, transparent_pointers, omit_empty_base_classes, 6425 ignore_array_bounds, child_name, child_byte_size, child_byte_offset, 6426 child_bitfield_bit_size, child_bitfield_bit_offset, 6427 child_is_base_class, tmp_child_is_deref_of_parent, valobj, 6428 language_flags); 6429 } else { 6430 child_is_deref_of_parent = true; 6431 const char *parent_name = 6432 valobj ? valobj->GetName().GetCString() : nullptr; 6433 if (parent_name) { 6434 child_name.assign(1, '*'); 6435 child_name += parent_name; 6436 } 6437 6438 // We have a pointer to an simple type 6439 if (idx == 0 && pointee_clang_type.GetCompleteType()) { 6440 if (std::optional<uint64_t> size = 6441 pointee_clang_type.GetByteSize(get_exe_scope())) { 6442 child_byte_size = *size; 6443 child_byte_offset = 0; 6444 return pointee_clang_type; 6445 } 6446 } 6447 } 6448 } 6449 break; 6450 6451 case clang::Type::Vector: 6452 case clang::Type::ExtVector: 6453 if (idx_is_valid) { 6454 const clang::VectorType *array = 6455 llvm::cast<clang::VectorType>(parent_qual_type.getTypePtr()); 6456 if (array) { 6457 CompilerType element_type = GetType(array->getElementType()); 6458 if (element_type.GetCompleteType()) { 6459 char element_name[64]; 6460 ::snprintf(element_name, sizeof(element_name), "[%" PRIu64 "]", 6461 static_cast<uint64_t>(idx)); 6462 child_name.assign(element_name); 6463 if (std::optional<uint64_t> size = 6464 element_type.GetByteSize(get_exe_scope())) { 6465 child_byte_size = *size; 6466 child_byte_offset = (int32_t)idx * (int32_t)child_byte_size; 6467 return element_type; 6468 } 6469 } 6470 } 6471 } 6472 break; 6473 6474 case clang::Type::ConstantArray: 6475 case clang::Type::IncompleteArray: 6476 if (ignore_array_bounds || idx_is_valid) { 6477 const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe(); 6478 if (array) { 6479 CompilerType element_type = GetType(array->getElementType()); 6480 if (element_type.GetCompleteType()) { 6481 child_name = std::string(llvm::formatv("[{0}]", idx)); 6482 if (std::optional<uint64_t> size = 6483 element_type.GetByteSize(get_exe_scope())) { 6484 child_byte_size = *size; 6485 child_byte_offset = (int32_t)idx * (int32_t)child_byte_size; 6486 return element_type; 6487 } 6488 } 6489 } 6490 } 6491 break; 6492 6493 case clang::Type::Pointer: { 6494 CompilerType pointee_clang_type(GetPointeeType(type)); 6495 6496 // Don't dereference "void *" pointers 6497 if (pointee_clang_type.IsVoidType()) 6498 return CompilerType(); 6499 6500 if (transparent_pointers && pointee_clang_type.IsAggregateType()) { 6501 child_is_deref_of_parent = false; 6502 bool tmp_child_is_deref_of_parent = false; 6503 return pointee_clang_type.GetChildCompilerTypeAtIndex( 6504 exe_ctx, idx, transparent_pointers, omit_empty_base_classes, 6505 ignore_array_bounds, child_name, child_byte_size, child_byte_offset, 6506 child_bitfield_bit_size, child_bitfield_bit_offset, 6507 child_is_base_class, tmp_child_is_deref_of_parent, valobj, 6508 language_flags); 6509 } else { 6510 child_is_deref_of_parent = true; 6511 6512 const char *parent_name = 6513 valobj ? valobj->GetName().GetCString() : nullptr; 6514 if (parent_name) { 6515 child_name.assign(1, '*'); 6516 child_name += parent_name; 6517 } 6518 6519 // We have a pointer to an simple type 6520 if (idx == 0) { 6521 if (std::optional<uint64_t> size = 6522 pointee_clang_type.GetByteSize(get_exe_scope())) { 6523 child_byte_size = *size; 6524 child_byte_offset = 0; 6525 return pointee_clang_type; 6526 } 6527 } 6528 } 6529 break; 6530 } 6531 6532 case clang::Type::LValueReference: 6533 case clang::Type::RValueReference: 6534 if (idx_is_valid) { 6535 const clang::ReferenceType *reference_type = 6536 llvm::cast<clang::ReferenceType>( 6537 RemoveWrappingTypes(GetQualType(type)).getTypePtr()); 6538 CompilerType pointee_clang_type = 6539 GetType(reference_type->getPointeeType()); 6540 if (transparent_pointers && pointee_clang_type.IsAggregateType()) { 6541 child_is_deref_of_parent = false; 6542 bool tmp_child_is_deref_of_parent = false; 6543 return pointee_clang_type.GetChildCompilerTypeAtIndex( 6544 exe_ctx, idx, transparent_pointers, omit_empty_base_classes, 6545 ignore_array_bounds, child_name, child_byte_size, child_byte_offset, 6546 child_bitfield_bit_size, child_bitfield_bit_offset, 6547 child_is_base_class, tmp_child_is_deref_of_parent, valobj, 6548 language_flags); 6549 } else { 6550 const char *parent_name = 6551 valobj ? valobj->GetName().GetCString() : nullptr; 6552 if (parent_name) { 6553 child_name.assign(1, '&'); 6554 child_name += parent_name; 6555 } 6556 6557 // We have a pointer to an simple type 6558 if (idx == 0) { 6559 if (std::optional<uint64_t> size = 6560 pointee_clang_type.GetByteSize(get_exe_scope())) { 6561 child_byte_size = *size; 6562 child_byte_offset = 0; 6563 return pointee_clang_type; 6564 } 6565 } 6566 } 6567 } 6568 break; 6569 6570 default: 6571 break; 6572 } 6573 return CompilerType(); 6574 } 6575 6576 uint32_t TypeSystemClang::GetIndexForRecordBase( 6577 const clang::RecordDecl *record_decl, 6578 const clang::CXXBaseSpecifier *base_spec, 6579 bool omit_empty_base_classes) { 6580 uint32_t child_idx = 0; 6581 6582 const clang::CXXRecordDecl *cxx_record_decl = 6583 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 6584 6585 if (cxx_record_decl) { 6586 clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end; 6587 for (base_class = cxx_record_decl->bases_begin(), 6588 base_class_end = cxx_record_decl->bases_end(); 6589 base_class != base_class_end; ++base_class) { 6590 if (omit_empty_base_classes) { 6591 if (BaseSpecifierIsEmpty(base_class)) 6592 continue; 6593 } 6594 6595 if (base_class == base_spec) 6596 return child_idx; 6597 ++child_idx; 6598 } 6599 } 6600 6601 return UINT32_MAX; 6602 } 6603 6604 uint32_t TypeSystemClang::GetIndexForRecordChild( 6605 const clang::RecordDecl *record_decl, clang::NamedDecl *canonical_decl, 6606 bool omit_empty_base_classes) { 6607 uint32_t child_idx = TypeSystemClang::GetNumBaseClasses( 6608 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl), 6609 omit_empty_base_classes); 6610 6611 clang::RecordDecl::field_iterator field, field_end; 6612 for (field = record_decl->field_begin(), field_end = record_decl->field_end(); 6613 field != field_end; ++field, ++child_idx) { 6614 if (field->getCanonicalDecl() == canonical_decl) 6615 return child_idx; 6616 } 6617 6618 return UINT32_MAX; 6619 } 6620 6621 // Look for a child member (doesn't include base classes, but it does include 6622 // their members) in the type hierarchy. Returns an index path into 6623 // "clang_type" on how to reach the appropriate member. 6624 // 6625 // class A 6626 // { 6627 // public: 6628 // int m_a; 6629 // int m_b; 6630 // }; 6631 // 6632 // class B 6633 // { 6634 // }; 6635 // 6636 // class C : 6637 // public B, 6638 // public A 6639 // { 6640 // }; 6641 // 6642 // If we have a clang type that describes "class C", and we wanted to looked 6643 // "m_b" in it: 6644 // 6645 // With omit_empty_base_classes == false we would get an integer array back 6646 // with: { 1, 1 } The first index 1 is the child index for "class A" within 6647 // class C The second index 1 is the child index for "m_b" within class A 6648 // 6649 // With omit_empty_base_classes == true we would get an integer array back 6650 // with: { 0, 1 } The first index 0 is the child index for "class A" within 6651 // class C (since class B doesn't have any members it doesn't count) The second 6652 // index 1 is the child index for "m_b" within class A 6653 6654 size_t TypeSystemClang::GetIndexOfChildMemberWithName( 6655 lldb::opaque_compiler_type_t type, llvm::StringRef name, 6656 bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) { 6657 if (type && !name.empty()) { 6658 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 6659 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 6660 switch (type_class) { 6661 case clang::Type::Record: 6662 if (GetCompleteType(type)) { 6663 const clang::RecordType *record_type = 6664 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 6665 const clang::RecordDecl *record_decl = record_type->getDecl(); 6666 6667 assert(record_decl); 6668 uint32_t child_idx = 0; 6669 6670 const clang::CXXRecordDecl *cxx_record_decl = 6671 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 6672 6673 // Try and find a field that matches NAME 6674 clang::RecordDecl::field_iterator field, field_end; 6675 for (field = record_decl->field_begin(), 6676 field_end = record_decl->field_end(); 6677 field != field_end; ++field, ++child_idx) { 6678 llvm::StringRef field_name = field->getName(); 6679 if (field_name.empty()) { 6680 CompilerType field_type = GetType(field->getType()); 6681 child_indexes.push_back(child_idx); 6682 if (field_type.GetIndexOfChildMemberWithName( 6683 name, omit_empty_base_classes, child_indexes)) 6684 return child_indexes.size(); 6685 child_indexes.pop_back(); 6686 6687 } else if (field_name.equals(name)) { 6688 // We have to add on the number of base classes to this index! 6689 child_indexes.push_back( 6690 child_idx + TypeSystemClang::GetNumBaseClasses( 6691 cxx_record_decl, omit_empty_base_classes)); 6692 return child_indexes.size(); 6693 } 6694 } 6695 6696 if (cxx_record_decl) { 6697 const clang::RecordDecl *parent_record_decl = cxx_record_decl; 6698 6699 // Didn't find things easily, lets let clang do its thang... 6700 clang::IdentifierInfo &ident_ref = getASTContext().Idents.get(name); 6701 clang::DeclarationName decl_name(&ident_ref); 6702 6703 clang::CXXBasePaths paths; 6704 if (cxx_record_decl->lookupInBases( 6705 [decl_name](const clang::CXXBaseSpecifier *specifier, 6706 clang::CXXBasePath &path) { 6707 CXXRecordDecl *record = 6708 specifier->getType()->getAsCXXRecordDecl(); 6709 auto r = record->lookup(decl_name); 6710 path.Decls = r.begin(); 6711 return !r.empty(); 6712 }, 6713 paths)) { 6714 clang::CXXBasePaths::const_paths_iterator path, 6715 path_end = paths.end(); 6716 for (path = paths.begin(); path != path_end; ++path) { 6717 const size_t num_path_elements = path->size(); 6718 for (size_t e = 0; e < num_path_elements; ++e) { 6719 clang::CXXBasePathElement elem = (*path)[e]; 6720 6721 child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base, 6722 omit_empty_base_classes); 6723 if (child_idx == UINT32_MAX) { 6724 child_indexes.clear(); 6725 return 0; 6726 } else { 6727 child_indexes.push_back(child_idx); 6728 parent_record_decl = llvm::cast<clang::RecordDecl>( 6729 elem.Base->getType() 6730 ->castAs<clang::RecordType>() 6731 ->getDecl()); 6732 } 6733 } 6734 for (clang::DeclContext::lookup_iterator I = path->Decls, E; 6735 I != E; ++I) { 6736 child_idx = GetIndexForRecordChild( 6737 parent_record_decl, *I, omit_empty_base_classes); 6738 if (child_idx == UINT32_MAX) { 6739 child_indexes.clear(); 6740 return 0; 6741 } else { 6742 child_indexes.push_back(child_idx); 6743 } 6744 } 6745 } 6746 return child_indexes.size(); 6747 } 6748 } 6749 } 6750 break; 6751 6752 case clang::Type::ObjCObject: 6753 case clang::Type::ObjCInterface: 6754 if (GetCompleteType(type)) { 6755 llvm::StringRef name_sref(name); 6756 const clang::ObjCObjectType *objc_class_type = 6757 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 6758 assert(objc_class_type); 6759 if (objc_class_type) { 6760 uint32_t child_idx = 0; 6761 clang::ObjCInterfaceDecl *class_interface_decl = 6762 objc_class_type->getInterface(); 6763 6764 if (class_interface_decl) { 6765 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos, 6766 ivar_end = class_interface_decl->ivar_end(); 6767 clang::ObjCInterfaceDecl *superclass_interface_decl = 6768 class_interface_decl->getSuperClass(); 6769 6770 for (ivar_pos = class_interface_decl->ivar_begin(); 6771 ivar_pos != ivar_end; ++ivar_pos, ++child_idx) { 6772 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos; 6773 6774 if (ivar_decl->getName().equals(name_sref)) { 6775 if ((!omit_empty_base_classes && superclass_interface_decl) || 6776 (omit_empty_base_classes && 6777 ObjCDeclHasIVars(superclass_interface_decl, true))) 6778 ++child_idx; 6779 6780 child_indexes.push_back(child_idx); 6781 return child_indexes.size(); 6782 } 6783 } 6784 6785 if (superclass_interface_decl) { 6786 // The super class index is always zero for ObjC classes, so we 6787 // push it onto the child indexes in case we find an ivar in our 6788 // superclass... 6789 child_indexes.push_back(0); 6790 6791 CompilerType superclass_clang_type = 6792 GetType(getASTContext().getObjCInterfaceType( 6793 superclass_interface_decl)); 6794 if (superclass_clang_type.GetIndexOfChildMemberWithName( 6795 name, omit_empty_base_classes, child_indexes)) { 6796 // We did find an ivar in a superclass so just return the 6797 // results! 6798 return child_indexes.size(); 6799 } 6800 6801 // We didn't find an ivar matching "name" in our superclass, pop 6802 // the superclass zero index that we pushed on above. 6803 child_indexes.pop_back(); 6804 } 6805 } 6806 } 6807 } 6808 break; 6809 6810 case clang::Type::ObjCObjectPointer: { 6811 CompilerType objc_object_clang_type = GetType( 6812 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr()) 6813 ->getPointeeType()); 6814 return objc_object_clang_type.GetIndexOfChildMemberWithName( 6815 name, omit_empty_base_classes, child_indexes); 6816 } break; 6817 6818 case clang::Type::ConstantArray: { 6819 // const clang::ConstantArrayType *array = 6820 // llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr()); 6821 // const uint64_t element_count = 6822 // array->getSize().getLimitedValue(); 6823 // 6824 // if (idx < element_count) 6825 // { 6826 // std::pair<uint64_t, unsigned> field_type_info = 6827 // ast->getTypeInfo(array->getElementType()); 6828 // 6829 // char element_name[32]; 6830 // ::snprintf (element_name, sizeof (element_name), 6831 // "%s[%u]", parent_name ? parent_name : "", idx); 6832 // 6833 // child_name.assign(element_name); 6834 // assert(field_type_info.first % 8 == 0); 6835 // child_byte_size = field_type_info.first / 8; 6836 // child_byte_offset = idx * child_byte_size; 6837 // return array->getElementType().getAsOpaquePtr(); 6838 // } 6839 } break; 6840 6841 // case clang::Type::MemberPointerType: 6842 // { 6843 // MemberPointerType *mem_ptr_type = 6844 // llvm::cast<MemberPointerType>(qual_type.getTypePtr()); 6845 // clang::QualType pointee_type = 6846 // mem_ptr_type->getPointeeType(); 6847 // 6848 // if (TypeSystemClang::IsAggregateType 6849 // (pointee_type.getAsOpaquePtr())) 6850 // { 6851 // return GetIndexOfChildWithName (ast, 6852 // mem_ptr_type->getPointeeType().getAsOpaquePtr(), 6853 // name); 6854 // } 6855 // } 6856 // break; 6857 // 6858 case clang::Type::LValueReference: 6859 case clang::Type::RValueReference: { 6860 const clang::ReferenceType *reference_type = 6861 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr()); 6862 clang::QualType pointee_type(reference_type->getPointeeType()); 6863 CompilerType pointee_clang_type = GetType(pointee_type); 6864 6865 if (pointee_clang_type.IsAggregateType()) { 6866 return pointee_clang_type.GetIndexOfChildMemberWithName( 6867 name, omit_empty_base_classes, child_indexes); 6868 } 6869 } break; 6870 6871 case clang::Type::Pointer: { 6872 CompilerType pointee_clang_type(GetPointeeType(type)); 6873 6874 if (pointee_clang_type.IsAggregateType()) { 6875 return pointee_clang_type.GetIndexOfChildMemberWithName( 6876 name, omit_empty_base_classes, child_indexes); 6877 } 6878 } break; 6879 6880 default: 6881 break; 6882 } 6883 } 6884 return 0; 6885 } 6886 6887 // Get the index of the child of "clang_type" whose name matches. This function 6888 // doesn't descend into the children, but only looks one level deep and name 6889 // matches can include base class names. 6890 6891 uint32_t 6892 TypeSystemClang::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type, 6893 llvm::StringRef name, 6894 bool omit_empty_base_classes) { 6895 if (type && !name.empty()) { 6896 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 6897 6898 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 6899 6900 switch (type_class) { 6901 case clang::Type::Record: 6902 if (GetCompleteType(type)) { 6903 const clang::RecordType *record_type = 6904 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 6905 const clang::RecordDecl *record_decl = record_type->getDecl(); 6906 6907 assert(record_decl); 6908 uint32_t child_idx = 0; 6909 6910 const clang::CXXRecordDecl *cxx_record_decl = 6911 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 6912 6913 if (cxx_record_decl) { 6914 clang::CXXRecordDecl::base_class_const_iterator base_class, 6915 base_class_end; 6916 for (base_class = cxx_record_decl->bases_begin(), 6917 base_class_end = cxx_record_decl->bases_end(); 6918 base_class != base_class_end; ++base_class) { 6919 // Skip empty base classes 6920 clang::CXXRecordDecl *base_class_decl = 6921 llvm::cast<clang::CXXRecordDecl>( 6922 base_class->getType() 6923 ->castAs<clang::RecordType>() 6924 ->getDecl()); 6925 if (omit_empty_base_classes && 6926 !TypeSystemClang::RecordHasFields(base_class_decl)) 6927 continue; 6928 6929 CompilerType base_class_clang_type = GetType(base_class->getType()); 6930 std::string base_class_type_name( 6931 base_class_clang_type.GetTypeName().AsCString("")); 6932 if (base_class_type_name == name) 6933 return child_idx; 6934 ++child_idx; 6935 } 6936 } 6937 6938 // Try and find a field that matches NAME 6939 clang::RecordDecl::field_iterator field, field_end; 6940 for (field = record_decl->field_begin(), 6941 field_end = record_decl->field_end(); 6942 field != field_end; ++field, ++child_idx) { 6943 if (field->getName().equals(name)) 6944 return child_idx; 6945 } 6946 } 6947 break; 6948 6949 case clang::Type::ObjCObject: 6950 case clang::Type::ObjCInterface: 6951 if (GetCompleteType(type)) { 6952 const clang::ObjCObjectType *objc_class_type = 6953 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 6954 assert(objc_class_type); 6955 if (objc_class_type) { 6956 uint32_t child_idx = 0; 6957 clang::ObjCInterfaceDecl *class_interface_decl = 6958 objc_class_type->getInterface(); 6959 6960 if (class_interface_decl) { 6961 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos, 6962 ivar_end = class_interface_decl->ivar_end(); 6963 clang::ObjCInterfaceDecl *superclass_interface_decl = 6964 class_interface_decl->getSuperClass(); 6965 6966 for (ivar_pos = class_interface_decl->ivar_begin(); 6967 ivar_pos != ivar_end; ++ivar_pos, ++child_idx) { 6968 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos; 6969 6970 if (ivar_decl->getName().equals(name)) { 6971 if ((!omit_empty_base_classes && superclass_interface_decl) || 6972 (omit_empty_base_classes && 6973 ObjCDeclHasIVars(superclass_interface_decl, true))) 6974 ++child_idx; 6975 6976 return child_idx; 6977 } 6978 } 6979 6980 if (superclass_interface_decl) { 6981 if (superclass_interface_decl->getName().equals(name)) 6982 return 0; 6983 } 6984 } 6985 } 6986 } 6987 break; 6988 6989 case clang::Type::ObjCObjectPointer: { 6990 CompilerType pointee_clang_type = GetType( 6991 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr()) 6992 ->getPointeeType()); 6993 return pointee_clang_type.GetIndexOfChildWithName( 6994 name, omit_empty_base_classes); 6995 } break; 6996 6997 case clang::Type::ConstantArray: { 6998 // const clang::ConstantArrayType *array = 6999 // llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr()); 7000 // const uint64_t element_count = 7001 // array->getSize().getLimitedValue(); 7002 // 7003 // if (idx < element_count) 7004 // { 7005 // std::pair<uint64_t, unsigned> field_type_info = 7006 // ast->getTypeInfo(array->getElementType()); 7007 // 7008 // char element_name[32]; 7009 // ::snprintf (element_name, sizeof (element_name), 7010 // "%s[%u]", parent_name ? parent_name : "", idx); 7011 // 7012 // child_name.assign(element_name); 7013 // assert(field_type_info.first % 8 == 0); 7014 // child_byte_size = field_type_info.first / 8; 7015 // child_byte_offset = idx * child_byte_size; 7016 // return array->getElementType().getAsOpaquePtr(); 7017 // } 7018 } break; 7019 7020 // case clang::Type::MemberPointerType: 7021 // { 7022 // MemberPointerType *mem_ptr_type = 7023 // llvm::cast<MemberPointerType>(qual_type.getTypePtr()); 7024 // clang::QualType pointee_type = 7025 // mem_ptr_type->getPointeeType(); 7026 // 7027 // if (TypeSystemClang::IsAggregateType 7028 // (pointee_type.getAsOpaquePtr())) 7029 // { 7030 // return GetIndexOfChildWithName (ast, 7031 // mem_ptr_type->getPointeeType().getAsOpaquePtr(), 7032 // name); 7033 // } 7034 // } 7035 // break; 7036 // 7037 case clang::Type::LValueReference: 7038 case clang::Type::RValueReference: { 7039 const clang::ReferenceType *reference_type = 7040 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr()); 7041 CompilerType pointee_type = GetType(reference_type->getPointeeType()); 7042 7043 if (pointee_type.IsAggregateType()) { 7044 return pointee_type.GetIndexOfChildWithName(name, 7045 omit_empty_base_classes); 7046 } 7047 } break; 7048 7049 case clang::Type::Pointer: { 7050 const clang::PointerType *pointer_type = 7051 llvm::cast<clang::PointerType>(qual_type.getTypePtr()); 7052 CompilerType pointee_type = GetType(pointer_type->getPointeeType()); 7053 7054 if (pointee_type.IsAggregateType()) { 7055 return pointee_type.GetIndexOfChildWithName(name, 7056 omit_empty_base_classes); 7057 } else { 7058 // if (parent_name) 7059 // { 7060 // child_name.assign(1, '*'); 7061 // child_name += parent_name; 7062 // } 7063 // 7064 // // We have a pointer to an simple type 7065 // if (idx == 0) 7066 // { 7067 // std::pair<uint64_t, unsigned> clang_type_info 7068 // = ast->getTypeInfo(pointee_type); 7069 // assert(clang_type_info.first % 8 == 0); 7070 // child_byte_size = clang_type_info.first / 8; 7071 // child_byte_offset = 0; 7072 // return pointee_type.getAsOpaquePtr(); 7073 // } 7074 } 7075 } break; 7076 7077 default: 7078 break; 7079 } 7080 } 7081 return UINT32_MAX; 7082 } 7083 7084 bool TypeSystemClang::IsTemplateType(lldb::opaque_compiler_type_t type) { 7085 if (!type) 7086 return false; 7087 CompilerType ct(weak_from_this(), type); 7088 const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr(); 7089 if (auto *cxx_record_decl = dyn_cast<clang::TagType>(clang_type)) 7090 return isa<clang::ClassTemplateSpecializationDecl>( 7091 cxx_record_decl->getDecl()); 7092 return false; 7093 } 7094 7095 size_t 7096 TypeSystemClang::GetNumTemplateArguments(lldb::opaque_compiler_type_t type, 7097 bool expand_pack) { 7098 if (!type) 7099 return 0; 7100 7101 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); 7102 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 7103 switch (type_class) { 7104 case clang::Type::Record: 7105 if (GetCompleteType(type)) { 7106 const clang::CXXRecordDecl *cxx_record_decl = 7107 qual_type->getAsCXXRecordDecl(); 7108 if (cxx_record_decl) { 7109 const clang::ClassTemplateSpecializationDecl *template_decl = 7110 llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>( 7111 cxx_record_decl); 7112 if (template_decl) { 7113 const auto &template_arg_list = template_decl->getTemplateArgs(); 7114 size_t num_args = template_arg_list.size(); 7115 assert(num_args && "template specialization without any args"); 7116 if (expand_pack && num_args) { 7117 const auto &pack = template_arg_list[num_args - 1]; 7118 if (pack.getKind() == clang::TemplateArgument::Pack) 7119 num_args += pack.pack_size() - 1; 7120 } 7121 return num_args; 7122 } 7123 } 7124 } 7125 break; 7126 7127 default: 7128 break; 7129 } 7130 7131 return 0; 7132 } 7133 7134 const clang::ClassTemplateSpecializationDecl * 7135 TypeSystemClang::GetAsTemplateSpecialization( 7136 lldb::opaque_compiler_type_t type) { 7137 if (!type) 7138 return nullptr; 7139 7140 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); 7141 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 7142 switch (type_class) { 7143 case clang::Type::Record: { 7144 if (! GetCompleteType(type)) 7145 return nullptr; 7146 const clang::CXXRecordDecl *cxx_record_decl = 7147 qual_type->getAsCXXRecordDecl(); 7148 if (!cxx_record_decl) 7149 return nullptr; 7150 return llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>( 7151 cxx_record_decl); 7152 } 7153 7154 default: 7155 return nullptr; 7156 } 7157 } 7158 7159 const TemplateArgument * 7160 GetNthTemplateArgument(const clang::ClassTemplateSpecializationDecl *decl, 7161 size_t idx, bool expand_pack) { 7162 const auto &args = decl->getTemplateArgs(); 7163 const size_t args_size = args.size(); 7164 7165 assert(args_size && "template specialization without any args"); 7166 if (!args_size) 7167 return nullptr; 7168 7169 const size_t last_idx = args_size - 1; 7170 7171 // We're asked for a template argument that can't be a parameter pack, so 7172 // return it without worrying about 'expand_pack'. 7173 if (idx < last_idx) 7174 return &args[idx]; 7175 7176 // We're asked for the last template argument but we don't want/need to 7177 // expand it. 7178 if (!expand_pack || args[last_idx].getKind() != clang::TemplateArgument::Pack) 7179 return idx >= args.size() ? nullptr : &args[idx]; 7180 7181 // Index into the expanded pack. 7182 // Note that 'idx' counts from the beginning of all template arguments 7183 // (including the ones preceding the parameter pack). 7184 const auto &pack = args[last_idx]; 7185 const size_t pack_idx = idx - last_idx; 7186 assert(pack_idx < pack.pack_size() && "parameter pack index out-of-bounds"); 7187 return &pack.pack_elements()[pack_idx]; 7188 } 7189 7190 lldb::TemplateArgumentKind 7191 TypeSystemClang::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type, 7192 size_t arg_idx, bool expand_pack) { 7193 const clang::ClassTemplateSpecializationDecl *template_decl = 7194 GetAsTemplateSpecialization(type); 7195 if (!template_decl) 7196 return eTemplateArgumentKindNull; 7197 7198 const auto *arg = GetNthTemplateArgument(template_decl, arg_idx, expand_pack); 7199 if (!arg) 7200 return eTemplateArgumentKindNull; 7201 7202 switch (arg->getKind()) { 7203 case clang::TemplateArgument::Null: 7204 return eTemplateArgumentKindNull; 7205 7206 case clang::TemplateArgument::NullPtr: 7207 return eTemplateArgumentKindNullPtr; 7208 7209 case clang::TemplateArgument::Type: 7210 return eTemplateArgumentKindType; 7211 7212 case clang::TemplateArgument::Declaration: 7213 return eTemplateArgumentKindDeclaration; 7214 7215 case clang::TemplateArgument::Integral: 7216 return eTemplateArgumentKindIntegral; 7217 7218 case clang::TemplateArgument::Template: 7219 return eTemplateArgumentKindTemplate; 7220 7221 case clang::TemplateArgument::TemplateExpansion: 7222 return eTemplateArgumentKindTemplateExpansion; 7223 7224 case clang::TemplateArgument::Expression: 7225 return eTemplateArgumentKindExpression; 7226 7227 case clang::TemplateArgument::Pack: 7228 return eTemplateArgumentKindPack; 7229 } 7230 llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind"); 7231 } 7232 7233 CompilerType 7234 TypeSystemClang::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type, 7235 size_t idx, bool expand_pack) { 7236 const clang::ClassTemplateSpecializationDecl *template_decl = 7237 GetAsTemplateSpecialization(type); 7238 if (!template_decl) 7239 return CompilerType(); 7240 7241 const auto *arg = GetNthTemplateArgument(template_decl, idx, expand_pack); 7242 if (!arg || arg->getKind() != clang::TemplateArgument::Type) 7243 return CompilerType(); 7244 7245 return GetType(arg->getAsType()); 7246 } 7247 7248 std::optional<CompilerType::IntegralTemplateArgument> 7249 TypeSystemClang::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type, 7250 size_t idx, bool expand_pack) { 7251 const clang::ClassTemplateSpecializationDecl *template_decl = 7252 GetAsTemplateSpecialization(type); 7253 if (!template_decl) 7254 return std::nullopt; 7255 7256 const auto *arg = GetNthTemplateArgument(template_decl, idx, expand_pack); 7257 if (!arg || arg->getKind() != clang::TemplateArgument::Integral) 7258 return std::nullopt; 7259 7260 return {{arg->getAsIntegral(), GetType(arg->getIntegralType())}}; 7261 } 7262 7263 CompilerType TypeSystemClang::GetTypeForFormatters(void *type) { 7264 if (type) 7265 return ClangUtil::RemoveFastQualifiers(CompilerType(weak_from_this(), type)); 7266 return CompilerType(); 7267 } 7268 7269 clang::EnumDecl *TypeSystemClang::GetAsEnumDecl(const CompilerType &type) { 7270 const clang::EnumType *enutype = 7271 llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type)); 7272 if (enutype) 7273 return enutype->getDecl(); 7274 return nullptr; 7275 } 7276 7277 clang::RecordDecl *TypeSystemClang::GetAsRecordDecl(const CompilerType &type) { 7278 const clang::RecordType *record_type = 7279 llvm::dyn_cast<clang::RecordType>(ClangUtil::GetCanonicalQualType(type)); 7280 if (record_type) 7281 return record_type->getDecl(); 7282 return nullptr; 7283 } 7284 7285 clang::TagDecl *TypeSystemClang::GetAsTagDecl(const CompilerType &type) { 7286 return ClangUtil::GetAsTagDecl(type); 7287 } 7288 7289 clang::TypedefNameDecl * 7290 TypeSystemClang::GetAsTypedefDecl(const CompilerType &type) { 7291 const clang::TypedefType *typedef_type = 7292 llvm::dyn_cast<clang::TypedefType>(ClangUtil::GetQualType(type)); 7293 if (typedef_type) 7294 return typedef_type->getDecl(); 7295 return nullptr; 7296 } 7297 7298 clang::CXXRecordDecl * 7299 TypeSystemClang::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) { 7300 return GetCanonicalQualType(type)->getAsCXXRecordDecl(); 7301 } 7302 7303 clang::ObjCInterfaceDecl * 7304 TypeSystemClang::GetAsObjCInterfaceDecl(const CompilerType &type) { 7305 const clang::ObjCObjectType *objc_class_type = 7306 llvm::dyn_cast<clang::ObjCObjectType>( 7307 ClangUtil::GetCanonicalQualType(type)); 7308 if (objc_class_type) 7309 return objc_class_type->getInterface(); 7310 return nullptr; 7311 } 7312 7313 clang::FieldDecl *TypeSystemClang::AddFieldToRecordType( 7314 const CompilerType &type, llvm::StringRef name, 7315 const CompilerType &field_clang_type, AccessType access, 7316 uint32_t bitfield_bit_size) { 7317 if (!type.IsValid() || !field_clang_type.IsValid()) 7318 return nullptr; 7319 auto ts = type.GetTypeSystem(); 7320 auto ast = ts.dyn_cast_or_null<TypeSystemClang>(); 7321 if (!ast) 7322 return nullptr; 7323 clang::ASTContext &clang_ast = ast->getASTContext(); 7324 clang::IdentifierInfo *ident = nullptr; 7325 if (!name.empty()) 7326 ident = &clang_ast.Idents.get(name); 7327 7328 clang::FieldDecl *field = nullptr; 7329 7330 clang::Expr *bit_width = nullptr; 7331 if (bitfield_bit_size != 0) { 7332 llvm::APInt bitfield_bit_size_apint(clang_ast.getTypeSize(clang_ast.IntTy), 7333 bitfield_bit_size); 7334 bit_width = new (clang_ast) 7335 clang::IntegerLiteral(clang_ast, bitfield_bit_size_apint, 7336 clang_ast.IntTy, clang::SourceLocation()); 7337 } 7338 7339 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type); 7340 if (record_decl) { 7341 field = clang::FieldDecl::CreateDeserialized(clang_ast, 0); 7342 field->setDeclContext(record_decl); 7343 field->setDeclName(ident); 7344 field->setType(ClangUtil::GetQualType(field_clang_type)); 7345 if (bit_width) 7346 field->setBitWidth(bit_width); 7347 SetMemberOwningModule(field, record_decl); 7348 7349 if (name.empty()) { 7350 // Determine whether this field corresponds to an anonymous struct or 7351 // union. 7352 if (const clang::TagType *TagT = 7353 field->getType()->getAs<clang::TagType>()) { 7354 if (clang::RecordDecl *Rec = 7355 llvm::dyn_cast<clang::RecordDecl>(TagT->getDecl())) 7356 if (!Rec->getDeclName()) { 7357 Rec->setAnonymousStructOrUnion(true); 7358 field->setImplicit(); 7359 } 7360 } 7361 } 7362 7363 if (field) { 7364 clang::AccessSpecifier access_specifier = 7365 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access); 7366 field->setAccess(access_specifier); 7367 7368 if (clang::CXXRecordDecl *cxx_record_decl = 7369 llvm::dyn_cast<CXXRecordDecl>(record_decl)) { 7370 AddAccessSpecifierDecl(cxx_record_decl, ast->getASTContext(), 7371 ast->GetCXXRecordDeclAccess(cxx_record_decl), 7372 access_specifier); 7373 ast->SetCXXRecordDeclAccess(cxx_record_decl, access_specifier); 7374 } 7375 record_decl->addDecl(field); 7376 7377 VerifyDecl(field); 7378 } 7379 } else { 7380 clang::ObjCInterfaceDecl *class_interface_decl = 7381 ast->GetAsObjCInterfaceDecl(type); 7382 7383 if (class_interface_decl) { 7384 const bool is_synthesized = false; 7385 7386 field_clang_type.GetCompleteType(); 7387 7388 auto *ivar = clang::ObjCIvarDecl::CreateDeserialized(clang_ast, 0); 7389 ivar->setDeclContext(class_interface_decl); 7390 ivar->setDeclName(ident); 7391 ivar->setType(ClangUtil::GetQualType(field_clang_type)); 7392 ivar->setAccessControl(ConvertAccessTypeToObjCIvarAccessControl(access)); 7393 if (bit_width) 7394 ivar->setBitWidth(bit_width); 7395 ivar->setSynthesize(is_synthesized); 7396 field = ivar; 7397 SetMemberOwningModule(field, class_interface_decl); 7398 7399 if (field) { 7400 class_interface_decl->addDecl(field); 7401 7402 VerifyDecl(field); 7403 } 7404 } 7405 } 7406 return field; 7407 } 7408 7409 void TypeSystemClang::BuildIndirectFields(const CompilerType &type) { 7410 if (!type) 7411 return; 7412 7413 auto ts = type.GetTypeSystem(); 7414 auto ast = ts.dyn_cast_or_null<TypeSystemClang>(); 7415 if (!ast) 7416 return; 7417 7418 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type); 7419 7420 if (!record_decl) 7421 return; 7422 7423 typedef llvm::SmallVector<clang::IndirectFieldDecl *, 1> IndirectFieldVector; 7424 7425 IndirectFieldVector indirect_fields; 7426 clang::RecordDecl::field_iterator field_pos; 7427 clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end(); 7428 clang::RecordDecl::field_iterator last_field_pos = field_end_pos; 7429 for (field_pos = record_decl->field_begin(); field_pos != field_end_pos; 7430 last_field_pos = field_pos++) { 7431 if (field_pos->isAnonymousStructOrUnion()) { 7432 clang::QualType field_qual_type = field_pos->getType(); 7433 7434 const clang::RecordType *field_record_type = 7435 field_qual_type->getAs<clang::RecordType>(); 7436 7437 if (!field_record_type) 7438 continue; 7439 7440 clang::RecordDecl *field_record_decl = field_record_type->getDecl(); 7441 7442 if (!field_record_decl) 7443 continue; 7444 7445 for (clang::RecordDecl::decl_iterator 7446 di = field_record_decl->decls_begin(), 7447 de = field_record_decl->decls_end(); 7448 di != de; ++di) { 7449 if (clang::FieldDecl *nested_field_decl = 7450 llvm::dyn_cast<clang::FieldDecl>(*di)) { 7451 clang::NamedDecl **chain = 7452 new (ast->getASTContext()) clang::NamedDecl *[2]; 7453 chain[0] = *field_pos; 7454 chain[1] = nested_field_decl; 7455 clang::IndirectFieldDecl *indirect_field = 7456 clang::IndirectFieldDecl::Create( 7457 ast->getASTContext(), record_decl, clang::SourceLocation(), 7458 nested_field_decl->getIdentifier(), 7459 nested_field_decl->getType(), {chain, 2}); 7460 SetMemberOwningModule(indirect_field, record_decl); 7461 7462 indirect_field->setImplicit(); 7463 7464 indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers( 7465 field_pos->getAccess(), nested_field_decl->getAccess())); 7466 7467 indirect_fields.push_back(indirect_field); 7468 } else if (clang::IndirectFieldDecl *nested_indirect_field_decl = 7469 llvm::dyn_cast<clang::IndirectFieldDecl>(*di)) { 7470 size_t nested_chain_size = 7471 nested_indirect_field_decl->getChainingSize(); 7472 clang::NamedDecl **chain = new (ast->getASTContext()) 7473 clang::NamedDecl *[nested_chain_size + 1]; 7474 chain[0] = *field_pos; 7475 7476 int chain_index = 1; 7477 for (clang::IndirectFieldDecl::chain_iterator 7478 nci = nested_indirect_field_decl->chain_begin(), 7479 nce = nested_indirect_field_decl->chain_end(); 7480 nci < nce; ++nci) { 7481 chain[chain_index] = *nci; 7482 chain_index++; 7483 } 7484 7485 clang::IndirectFieldDecl *indirect_field = 7486 clang::IndirectFieldDecl::Create( 7487 ast->getASTContext(), record_decl, clang::SourceLocation(), 7488 nested_indirect_field_decl->getIdentifier(), 7489 nested_indirect_field_decl->getType(), 7490 {chain, nested_chain_size + 1}); 7491 SetMemberOwningModule(indirect_field, record_decl); 7492 7493 indirect_field->setImplicit(); 7494 7495 indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers( 7496 field_pos->getAccess(), nested_indirect_field_decl->getAccess())); 7497 7498 indirect_fields.push_back(indirect_field); 7499 } 7500 } 7501 } 7502 } 7503 7504 // Check the last field to see if it has an incomplete array type as its last 7505 // member and if it does, the tell the record decl about it 7506 if (last_field_pos != field_end_pos) { 7507 if (last_field_pos->getType()->isIncompleteArrayType()) 7508 record_decl->hasFlexibleArrayMember(); 7509 } 7510 7511 for (IndirectFieldVector::iterator ifi = indirect_fields.begin(), 7512 ife = indirect_fields.end(); 7513 ifi < ife; ++ifi) { 7514 record_decl->addDecl(*ifi); 7515 } 7516 } 7517 7518 void TypeSystemClang::SetIsPacked(const CompilerType &type) { 7519 if (type) { 7520 auto ts = type.GetTypeSystem(); 7521 auto ast = ts.dyn_cast_or_null<TypeSystemClang>(); 7522 if (ast) { 7523 clang::RecordDecl *record_decl = GetAsRecordDecl(type); 7524 7525 if (!record_decl) 7526 return; 7527 7528 record_decl->addAttr( 7529 clang::PackedAttr::CreateImplicit(ast->getASTContext())); 7530 } 7531 } 7532 } 7533 7534 clang::VarDecl *TypeSystemClang::AddVariableToRecordType( 7535 const CompilerType &type, llvm::StringRef name, 7536 const CompilerType &var_type, AccessType access) { 7537 if (!type.IsValid() || !var_type.IsValid()) 7538 return nullptr; 7539 7540 auto ts = type.GetTypeSystem(); 7541 auto ast = ts.dyn_cast_or_null<TypeSystemClang>(); 7542 if (!ast) 7543 return nullptr; 7544 7545 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type); 7546 if (!record_decl) 7547 return nullptr; 7548 7549 clang::VarDecl *var_decl = nullptr; 7550 clang::IdentifierInfo *ident = nullptr; 7551 if (!name.empty()) 7552 ident = &ast->getASTContext().Idents.get(name); 7553 7554 var_decl = clang::VarDecl::CreateDeserialized(ast->getASTContext(), 0); 7555 var_decl->setDeclContext(record_decl); 7556 var_decl->setDeclName(ident); 7557 var_decl->setType(ClangUtil::GetQualType(var_type)); 7558 var_decl->setStorageClass(clang::SC_Static); 7559 SetMemberOwningModule(var_decl, record_decl); 7560 if (!var_decl) 7561 return nullptr; 7562 7563 var_decl->setAccess( 7564 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access)); 7565 record_decl->addDecl(var_decl); 7566 7567 VerifyDecl(var_decl); 7568 7569 return var_decl; 7570 } 7571 7572 void TypeSystemClang::SetIntegerInitializerForVariable( 7573 VarDecl *var, const llvm::APInt &init_value) { 7574 assert(!var->hasInit() && "variable already initialized"); 7575 7576 clang::ASTContext &ast = var->getASTContext(); 7577 QualType qt = var->getType(); 7578 assert(qt->isIntegralOrEnumerationType() && 7579 "only integer or enum types supported"); 7580 // If the variable is an enum type, take the underlying integer type as 7581 // the type of the integer literal. 7582 if (const EnumType *enum_type = qt->getAs<EnumType>()) { 7583 const EnumDecl *enum_decl = enum_type->getDecl(); 7584 qt = enum_decl->getIntegerType(); 7585 } 7586 // Bools are handled separately because the clang AST printer handles bools 7587 // separately from other integral types. 7588 if (qt->isSpecificBuiltinType(BuiltinType::Bool)) { 7589 var->setInit(CXXBoolLiteralExpr::Create( 7590 ast, !init_value.isZero(), qt.getUnqualifiedType(), SourceLocation())); 7591 } else { 7592 var->setInit(IntegerLiteral::Create( 7593 ast, init_value, qt.getUnqualifiedType(), SourceLocation())); 7594 } 7595 } 7596 7597 void TypeSystemClang::SetFloatingInitializerForVariable( 7598 clang::VarDecl *var, const llvm::APFloat &init_value) { 7599 assert(!var->hasInit() && "variable already initialized"); 7600 7601 clang::ASTContext &ast = var->getASTContext(); 7602 QualType qt = var->getType(); 7603 assert(qt->isFloatingType() && "only floating point types supported"); 7604 var->setInit(FloatingLiteral::Create( 7605 ast, init_value, true, qt.getUnqualifiedType(), SourceLocation())); 7606 } 7607 7608 clang::CXXMethodDecl *TypeSystemClang::AddMethodToCXXRecordType( 7609 lldb::opaque_compiler_type_t type, llvm::StringRef name, 7610 const char *mangled_name, const CompilerType &method_clang_type, 7611 lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline, 7612 bool is_explicit, bool is_attr_used, bool is_artificial) { 7613 if (!type || !method_clang_type.IsValid() || name.empty()) 7614 return nullptr; 7615 7616 clang::QualType record_qual_type(GetCanonicalQualType(type)); 7617 7618 clang::CXXRecordDecl *cxx_record_decl = 7619 record_qual_type->getAsCXXRecordDecl(); 7620 7621 if (cxx_record_decl == nullptr) 7622 return nullptr; 7623 7624 clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type)); 7625 7626 clang::CXXMethodDecl *cxx_method_decl = nullptr; 7627 7628 clang::DeclarationName decl_name(&getASTContext().Idents.get(name)); 7629 7630 const clang::FunctionType *function_type = 7631 llvm::dyn_cast<clang::FunctionType>(method_qual_type.getTypePtr()); 7632 7633 if (function_type == nullptr) 7634 return nullptr; 7635 7636 const clang::FunctionProtoType *method_function_prototype( 7637 llvm::dyn_cast<clang::FunctionProtoType>(function_type)); 7638 7639 if (!method_function_prototype) 7640 return nullptr; 7641 7642 unsigned int num_params = method_function_prototype->getNumParams(); 7643 7644 clang::CXXDestructorDecl *cxx_dtor_decl(nullptr); 7645 clang::CXXConstructorDecl *cxx_ctor_decl(nullptr); 7646 7647 if (is_artificial) 7648 return nullptr; // skip everything artificial 7649 7650 const clang::ExplicitSpecifier explicit_spec( 7651 nullptr /*expr*/, is_explicit ? clang::ExplicitSpecKind::ResolvedTrue 7652 : clang::ExplicitSpecKind::ResolvedFalse); 7653 7654 if (name.startswith("~")) { 7655 cxx_dtor_decl = 7656 clang::CXXDestructorDecl::CreateDeserialized(getASTContext(), 0); 7657 cxx_dtor_decl->setDeclContext(cxx_record_decl); 7658 cxx_dtor_decl->setDeclName( 7659 getASTContext().DeclarationNames.getCXXDestructorName( 7660 getASTContext().getCanonicalType(record_qual_type))); 7661 cxx_dtor_decl->setType(method_qual_type); 7662 cxx_dtor_decl->setImplicit(is_artificial); 7663 cxx_dtor_decl->setInlineSpecified(is_inline); 7664 cxx_dtor_decl->setConstexprKind(ConstexprSpecKind::Unspecified); 7665 cxx_method_decl = cxx_dtor_decl; 7666 } else if (decl_name == cxx_record_decl->getDeclName()) { 7667 cxx_ctor_decl = clang::CXXConstructorDecl::CreateDeserialized( 7668 getASTContext(), 0, 0); 7669 cxx_ctor_decl->setDeclContext(cxx_record_decl); 7670 cxx_ctor_decl->setDeclName( 7671 getASTContext().DeclarationNames.getCXXConstructorName( 7672 getASTContext().getCanonicalType(record_qual_type))); 7673 cxx_ctor_decl->setType(method_qual_type); 7674 cxx_ctor_decl->setImplicit(is_artificial); 7675 cxx_ctor_decl->setInlineSpecified(is_inline); 7676 cxx_ctor_decl->setConstexprKind(ConstexprSpecKind::Unspecified); 7677 cxx_ctor_decl->setNumCtorInitializers(0); 7678 cxx_ctor_decl->setExplicitSpecifier(explicit_spec); 7679 cxx_method_decl = cxx_ctor_decl; 7680 } else { 7681 clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None; 7682 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; 7683 7684 if (IsOperator(name, op_kind)) { 7685 if (op_kind != clang::NUM_OVERLOADED_OPERATORS) { 7686 // Check the number of operator parameters. Sometimes we have seen bad 7687 // DWARF that doesn't correctly describe operators and if we try to 7688 // create a method and add it to the class, clang will assert and 7689 // crash, so we need to make sure things are acceptable. 7690 const bool is_method = true; 7691 if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount( 7692 is_method, op_kind, num_params)) 7693 return nullptr; 7694 cxx_method_decl = 7695 clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0); 7696 cxx_method_decl->setDeclContext(cxx_record_decl); 7697 cxx_method_decl->setDeclName( 7698 getASTContext().DeclarationNames.getCXXOperatorName(op_kind)); 7699 cxx_method_decl->setType(method_qual_type); 7700 cxx_method_decl->setStorageClass(SC); 7701 cxx_method_decl->setInlineSpecified(is_inline); 7702 cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified); 7703 } else if (num_params == 0) { 7704 // Conversion operators don't take params... 7705 auto *cxx_conversion_decl = 7706 clang::CXXConversionDecl::CreateDeserialized(getASTContext(), 0); 7707 cxx_conversion_decl->setDeclContext(cxx_record_decl); 7708 cxx_conversion_decl->setDeclName( 7709 getASTContext().DeclarationNames.getCXXConversionFunctionName( 7710 getASTContext().getCanonicalType( 7711 function_type->getReturnType()))); 7712 cxx_conversion_decl->setType(method_qual_type); 7713 cxx_conversion_decl->setInlineSpecified(is_inline); 7714 cxx_conversion_decl->setExplicitSpecifier(explicit_spec); 7715 cxx_conversion_decl->setConstexprKind(ConstexprSpecKind::Unspecified); 7716 cxx_method_decl = cxx_conversion_decl; 7717 } 7718 } 7719 7720 if (cxx_method_decl == nullptr) { 7721 cxx_method_decl = 7722 clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0); 7723 cxx_method_decl->setDeclContext(cxx_record_decl); 7724 cxx_method_decl->setDeclName(decl_name); 7725 cxx_method_decl->setType(method_qual_type); 7726 cxx_method_decl->setInlineSpecified(is_inline); 7727 cxx_method_decl->setStorageClass(SC); 7728 cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified); 7729 } 7730 } 7731 SetMemberOwningModule(cxx_method_decl, cxx_record_decl); 7732 7733 clang::AccessSpecifier access_specifier = 7734 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access); 7735 7736 cxx_method_decl->setAccess(access_specifier); 7737 cxx_method_decl->setVirtualAsWritten(is_virtual); 7738 7739 if (is_attr_used) 7740 cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(getASTContext())); 7741 7742 if (mangled_name != nullptr) { 7743 cxx_method_decl->addAttr(clang::AsmLabelAttr::CreateImplicit( 7744 getASTContext(), mangled_name, /*literal=*/false)); 7745 } 7746 7747 // Populate the method decl with parameter decls 7748 7749 llvm::SmallVector<clang::ParmVarDecl *, 12> params; 7750 7751 for (unsigned param_index = 0; param_index < num_params; ++param_index) { 7752 params.push_back(clang::ParmVarDecl::Create( 7753 getASTContext(), cxx_method_decl, clang::SourceLocation(), 7754 clang::SourceLocation(), 7755 nullptr, // anonymous 7756 method_function_prototype->getParamType(param_index), nullptr, 7757 clang::SC_None, nullptr)); 7758 } 7759 7760 cxx_method_decl->setParams(llvm::ArrayRef<clang::ParmVarDecl *>(params)); 7761 7762 AddAccessSpecifierDecl(cxx_record_decl, getASTContext(), 7763 GetCXXRecordDeclAccess(cxx_record_decl), 7764 access_specifier); 7765 SetCXXRecordDeclAccess(cxx_record_decl, access_specifier); 7766 7767 cxx_record_decl->addDecl(cxx_method_decl); 7768 7769 // Sometimes the debug info will mention a constructor (default/copy/move), 7770 // destructor, or assignment operator (copy/move) but there won't be any 7771 // version of this in the code. So we check if the function was artificially 7772 // generated and if it is trivial and this lets the compiler/backend know 7773 // that it can inline the IR for these when it needs to and we can avoid a 7774 // "missing function" error when running expressions. 7775 7776 if (is_artificial) { 7777 if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() && 7778 cxx_record_decl->hasTrivialDefaultConstructor()) || 7779 (cxx_ctor_decl->isCopyConstructor() && 7780 cxx_record_decl->hasTrivialCopyConstructor()) || 7781 (cxx_ctor_decl->isMoveConstructor() && 7782 cxx_record_decl->hasTrivialMoveConstructor()))) { 7783 cxx_ctor_decl->setDefaulted(); 7784 cxx_ctor_decl->setTrivial(true); 7785 } else if (cxx_dtor_decl) { 7786 if (cxx_record_decl->hasTrivialDestructor()) { 7787 cxx_dtor_decl->setDefaulted(); 7788 cxx_dtor_decl->setTrivial(true); 7789 } 7790 } else if ((cxx_method_decl->isCopyAssignmentOperator() && 7791 cxx_record_decl->hasTrivialCopyAssignment()) || 7792 (cxx_method_decl->isMoveAssignmentOperator() && 7793 cxx_record_decl->hasTrivialMoveAssignment())) { 7794 cxx_method_decl->setDefaulted(); 7795 cxx_method_decl->setTrivial(true); 7796 } 7797 } 7798 7799 VerifyDecl(cxx_method_decl); 7800 7801 return cxx_method_decl; 7802 } 7803 7804 void TypeSystemClang::AddMethodOverridesForCXXRecordType( 7805 lldb::opaque_compiler_type_t type) { 7806 if (auto *record = GetAsCXXRecordDecl(type)) 7807 for (auto *method : record->methods()) 7808 addOverridesForMethod(method); 7809 } 7810 7811 #pragma mark C++ Base Classes 7812 7813 std::unique_ptr<clang::CXXBaseSpecifier> 7814 TypeSystemClang::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type, 7815 AccessType access, bool is_virtual, 7816 bool base_of_class) { 7817 if (!type) 7818 return nullptr; 7819 7820 return std::make_unique<clang::CXXBaseSpecifier>( 7821 clang::SourceRange(), is_virtual, base_of_class, 7822 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access), 7823 getASTContext().getTrivialTypeSourceInfo(GetQualType(type)), 7824 clang::SourceLocation()); 7825 } 7826 7827 bool TypeSystemClang::TransferBaseClasses( 7828 lldb::opaque_compiler_type_t type, 7829 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases) { 7830 if (!type) 7831 return false; 7832 clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type); 7833 if (!cxx_record_decl) 7834 return false; 7835 std::vector<clang::CXXBaseSpecifier *> raw_bases; 7836 raw_bases.reserve(bases.size()); 7837 7838 // Clang will make a copy of them, so it's ok that we pass pointers that we're 7839 // about to destroy. 7840 for (auto &b : bases) 7841 raw_bases.push_back(b.get()); 7842 cxx_record_decl->setBases(raw_bases.data(), raw_bases.size()); 7843 return true; 7844 } 7845 7846 bool TypeSystemClang::SetObjCSuperClass( 7847 const CompilerType &type, const CompilerType &superclass_clang_type) { 7848 auto ts = type.GetTypeSystem(); 7849 auto ast = ts.dyn_cast_or_null<TypeSystemClang>(); 7850 if (!ast) 7851 return false; 7852 clang::ASTContext &clang_ast = ast->getASTContext(); 7853 7854 if (type && superclass_clang_type.IsValid() && 7855 superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) { 7856 clang::ObjCInterfaceDecl *class_interface_decl = 7857 GetAsObjCInterfaceDecl(type); 7858 clang::ObjCInterfaceDecl *super_interface_decl = 7859 GetAsObjCInterfaceDecl(superclass_clang_type); 7860 if (class_interface_decl && super_interface_decl) { 7861 class_interface_decl->setSuperClass(clang_ast.getTrivialTypeSourceInfo( 7862 clang_ast.getObjCInterfaceType(super_interface_decl))); 7863 return true; 7864 } 7865 } 7866 return false; 7867 } 7868 7869 bool TypeSystemClang::AddObjCClassProperty( 7870 const CompilerType &type, const char *property_name, 7871 const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl, 7872 const char *property_setter_name, const char *property_getter_name, 7873 uint32_t property_attributes, ClangASTMetadata *metadata) { 7874 if (!type || !property_clang_type.IsValid() || property_name == nullptr || 7875 property_name[0] == '\0') 7876 return false; 7877 auto ts = type.GetTypeSystem(); 7878 auto ast = ts.dyn_cast_or_null<TypeSystemClang>(); 7879 if (!ast) 7880 return false; 7881 clang::ASTContext &clang_ast = ast->getASTContext(); 7882 7883 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type); 7884 if (!class_interface_decl) 7885 return false; 7886 7887 CompilerType property_clang_type_to_access; 7888 7889 if (property_clang_type.IsValid()) 7890 property_clang_type_to_access = property_clang_type; 7891 else if (ivar_decl) 7892 property_clang_type_to_access = ast->GetType(ivar_decl->getType()); 7893 7894 if (!class_interface_decl || !property_clang_type_to_access.IsValid()) 7895 return false; 7896 7897 clang::TypeSourceInfo *prop_type_source; 7898 if (ivar_decl) 7899 prop_type_source = clang_ast.getTrivialTypeSourceInfo(ivar_decl->getType()); 7900 else 7901 prop_type_source = clang_ast.getTrivialTypeSourceInfo( 7902 ClangUtil::GetQualType(property_clang_type)); 7903 7904 clang::ObjCPropertyDecl *property_decl = 7905 clang::ObjCPropertyDecl::CreateDeserialized(clang_ast, 0); 7906 property_decl->setDeclContext(class_interface_decl); 7907 property_decl->setDeclName(&clang_ast.Idents.get(property_name)); 7908 property_decl->setType(ivar_decl 7909 ? ivar_decl->getType() 7910 : ClangUtil::GetQualType(property_clang_type), 7911 prop_type_source); 7912 SetMemberOwningModule(property_decl, class_interface_decl); 7913 7914 if (!property_decl) 7915 return false; 7916 7917 if (metadata) 7918 ast->SetMetadata(property_decl, *metadata); 7919 7920 class_interface_decl->addDecl(property_decl); 7921 7922 clang::Selector setter_sel, getter_sel; 7923 7924 if (property_setter_name) { 7925 std::string property_setter_no_colon(property_setter_name, 7926 strlen(property_setter_name) - 1); 7927 clang::IdentifierInfo *setter_ident = 7928 &clang_ast.Idents.get(property_setter_no_colon); 7929 setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident); 7930 } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) { 7931 std::string setter_sel_string("set"); 7932 setter_sel_string.push_back(::toupper(property_name[0])); 7933 setter_sel_string.append(&property_name[1]); 7934 clang::IdentifierInfo *setter_ident = 7935 &clang_ast.Idents.get(setter_sel_string); 7936 setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident); 7937 } 7938 property_decl->setSetterName(setter_sel); 7939 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_setter); 7940 7941 if (property_getter_name != nullptr) { 7942 clang::IdentifierInfo *getter_ident = 7943 &clang_ast.Idents.get(property_getter_name); 7944 getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident); 7945 } else { 7946 clang::IdentifierInfo *getter_ident = &clang_ast.Idents.get(property_name); 7947 getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident); 7948 } 7949 property_decl->setGetterName(getter_sel); 7950 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_getter); 7951 7952 if (ivar_decl) 7953 property_decl->setPropertyIvarDecl(ivar_decl); 7954 7955 if (property_attributes & DW_APPLE_PROPERTY_readonly) 7956 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readonly); 7957 if (property_attributes & DW_APPLE_PROPERTY_readwrite) 7958 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite); 7959 if (property_attributes & DW_APPLE_PROPERTY_assign) 7960 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign); 7961 if (property_attributes & DW_APPLE_PROPERTY_retain) 7962 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_retain); 7963 if (property_attributes & DW_APPLE_PROPERTY_copy) 7964 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_copy); 7965 if (property_attributes & DW_APPLE_PROPERTY_nonatomic) 7966 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic); 7967 if (property_attributes & ObjCPropertyAttribute::kind_nullability) 7968 property_decl->setPropertyAttributes( 7969 ObjCPropertyAttribute::kind_nullability); 7970 if (property_attributes & ObjCPropertyAttribute::kind_null_resettable) 7971 property_decl->setPropertyAttributes( 7972 ObjCPropertyAttribute::kind_null_resettable); 7973 if (property_attributes & ObjCPropertyAttribute::kind_class) 7974 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_class); 7975 7976 const bool isInstance = 7977 (property_attributes & ObjCPropertyAttribute::kind_class) == 0; 7978 7979 clang::ObjCMethodDecl *getter = nullptr; 7980 if (!getter_sel.isNull()) 7981 getter = isInstance ? class_interface_decl->lookupInstanceMethod(getter_sel) 7982 : class_interface_decl->lookupClassMethod(getter_sel); 7983 if (!getter_sel.isNull() && !getter) { 7984 const bool isVariadic = false; 7985 const bool isPropertyAccessor = true; 7986 const bool isSynthesizedAccessorStub = false; 7987 const bool isImplicitlyDeclared = true; 7988 const bool isDefined = false; 7989 const clang::ObjCMethodDecl::ImplementationControl impControl = 7990 clang::ObjCMethodDecl::None; 7991 const bool HasRelatedResultType = false; 7992 7993 getter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0); 7994 getter->setDeclName(getter_sel); 7995 getter->setReturnType(ClangUtil::GetQualType(property_clang_type_to_access)); 7996 getter->setDeclContext(class_interface_decl); 7997 getter->setInstanceMethod(isInstance); 7998 getter->setVariadic(isVariadic); 7999 getter->setPropertyAccessor(isPropertyAccessor); 8000 getter->setSynthesizedAccessorStub(isSynthesizedAccessorStub); 8001 getter->setImplicit(isImplicitlyDeclared); 8002 getter->setDefined(isDefined); 8003 getter->setDeclImplementation(impControl); 8004 getter->setRelatedResultType(HasRelatedResultType); 8005 SetMemberOwningModule(getter, class_interface_decl); 8006 8007 if (getter) { 8008 if (metadata) 8009 ast->SetMetadata(getter, *metadata); 8010 8011 getter->setMethodParams(clang_ast, llvm::ArrayRef<clang::ParmVarDecl *>(), 8012 llvm::ArrayRef<clang::SourceLocation>()); 8013 class_interface_decl->addDecl(getter); 8014 } 8015 } 8016 if (getter) { 8017 getter->setPropertyAccessor(true); 8018 property_decl->setGetterMethodDecl(getter); 8019 } 8020 8021 clang::ObjCMethodDecl *setter = nullptr; 8022 setter = isInstance ? class_interface_decl->lookupInstanceMethod(setter_sel) 8023 : class_interface_decl->lookupClassMethod(setter_sel); 8024 if (!setter_sel.isNull() && !setter) { 8025 clang::QualType result_type = clang_ast.VoidTy; 8026 const bool isVariadic = false; 8027 const bool isPropertyAccessor = true; 8028 const bool isSynthesizedAccessorStub = false; 8029 const bool isImplicitlyDeclared = true; 8030 const bool isDefined = false; 8031 const clang::ObjCMethodDecl::ImplementationControl impControl = 8032 clang::ObjCMethodDecl::None; 8033 const bool HasRelatedResultType = false; 8034 8035 setter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0); 8036 setter->setDeclName(setter_sel); 8037 setter->setReturnType(result_type); 8038 setter->setDeclContext(class_interface_decl); 8039 setter->setInstanceMethod(isInstance); 8040 setter->setVariadic(isVariadic); 8041 setter->setPropertyAccessor(isPropertyAccessor); 8042 setter->setSynthesizedAccessorStub(isSynthesizedAccessorStub); 8043 setter->setImplicit(isImplicitlyDeclared); 8044 setter->setDefined(isDefined); 8045 setter->setDeclImplementation(impControl); 8046 setter->setRelatedResultType(HasRelatedResultType); 8047 SetMemberOwningModule(setter, class_interface_decl); 8048 8049 if (setter) { 8050 if (metadata) 8051 ast->SetMetadata(setter, *metadata); 8052 8053 llvm::SmallVector<clang::ParmVarDecl *, 1> params; 8054 params.push_back(clang::ParmVarDecl::Create( 8055 clang_ast, setter, clang::SourceLocation(), clang::SourceLocation(), 8056 nullptr, // anonymous 8057 ClangUtil::GetQualType(property_clang_type_to_access), nullptr, 8058 clang::SC_Auto, nullptr)); 8059 8060 setter->setMethodParams(clang_ast, 8061 llvm::ArrayRef<clang::ParmVarDecl *>(params), 8062 llvm::ArrayRef<clang::SourceLocation>()); 8063 8064 class_interface_decl->addDecl(setter); 8065 } 8066 } 8067 if (setter) { 8068 setter->setPropertyAccessor(true); 8069 property_decl->setSetterMethodDecl(setter); 8070 } 8071 8072 return true; 8073 } 8074 8075 bool TypeSystemClang::IsObjCClassTypeAndHasIVars(const CompilerType &type, 8076 bool check_superclass) { 8077 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type); 8078 if (class_interface_decl) 8079 return ObjCDeclHasIVars(class_interface_decl, check_superclass); 8080 return false; 8081 } 8082 8083 clang::ObjCMethodDecl *TypeSystemClang::AddMethodToObjCObjectType( 8084 const CompilerType &type, 8085 const char *name, // the full symbol name as seen in the symbol table 8086 // (lldb::opaque_compiler_type_t type, "-[NString 8087 // stringWithCString:]") 8088 const CompilerType &method_clang_type, lldb::AccessType access, 8089 bool is_artificial, bool is_variadic, bool is_objc_direct_call) { 8090 if (!type || !method_clang_type.IsValid()) 8091 return nullptr; 8092 8093 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type); 8094 8095 if (class_interface_decl == nullptr) 8096 return nullptr; 8097 auto ts = type.GetTypeSystem(); 8098 auto lldb_ast = ts.dyn_cast_or_null<TypeSystemClang>(); 8099 if (lldb_ast == nullptr) 8100 return nullptr; 8101 clang::ASTContext &ast = lldb_ast->getASTContext(); 8102 8103 const char *selector_start = ::strchr(name, ' '); 8104 if (selector_start == nullptr) 8105 return nullptr; 8106 8107 selector_start++; 8108 llvm::SmallVector<clang::IdentifierInfo *, 12> selector_idents; 8109 8110 size_t len = 0; 8111 const char *start; 8112 8113 unsigned num_selectors_with_args = 0; 8114 for (start = selector_start; start && *start != '\0' && *start != ']'; 8115 start += len) { 8116 len = ::strcspn(start, ":]"); 8117 bool has_arg = (start[len] == ':'); 8118 if (has_arg) 8119 ++num_selectors_with_args; 8120 selector_idents.push_back(&ast.Idents.get(llvm::StringRef(start, len))); 8121 if (has_arg) 8122 len += 1; 8123 } 8124 8125 if (selector_idents.size() == 0) 8126 return nullptr; 8127 8128 clang::Selector method_selector = ast.Selectors.getSelector( 8129 num_selectors_with_args ? selector_idents.size() : 0, 8130 selector_idents.data()); 8131 8132 clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type)); 8133 8134 // Populate the method decl with parameter decls 8135 const clang::Type *method_type(method_qual_type.getTypePtr()); 8136 8137 if (method_type == nullptr) 8138 return nullptr; 8139 8140 const clang::FunctionProtoType *method_function_prototype( 8141 llvm::dyn_cast<clang::FunctionProtoType>(method_type)); 8142 8143 if (!method_function_prototype) 8144 return nullptr; 8145 8146 const bool isInstance = (name[0] == '-'); 8147 const bool isVariadic = is_variadic; 8148 const bool isPropertyAccessor = false; 8149 const bool isSynthesizedAccessorStub = false; 8150 /// Force this to true because we don't have source locations. 8151 const bool isImplicitlyDeclared = true; 8152 const bool isDefined = false; 8153 const clang::ObjCMethodDecl::ImplementationControl impControl = 8154 clang::ObjCMethodDecl::None; 8155 const bool HasRelatedResultType = false; 8156 8157 const unsigned num_args = method_function_prototype->getNumParams(); 8158 8159 if (num_args != num_selectors_with_args) 8160 return nullptr; // some debug information is corrupt. We are not going to 8161 // deal with it. 8162 8163 auto *objc_method_decl = clang::ObjCMethodDecl::CreateDeserialized(ast, 0); 8164 objc_method_decl->setDeclName(method_selector); 8165 objc_method_decl->setReturnType(method_function_prototype->getReturnType()); 8166 objc_method_decl->setDeclContext( 8167 lldb_ast->GetDeclContextForType(ClangUtil::GetQualType(type))); 8168 objc_method_decl->setInstanceMethod(isInstance); 8169 objc_method_decl->setVariadic(isVariadic); 8170 objc_method_decl->setPropertyAccessor(isPropertyAccessor); 8171 objc_method_decl->setSynthesizedAccessorStub(isSynthesizedAccessorStub); 8172 objc_method_decl->setImplicit(isImplicitlyDeclared); 8173 objc_method_decl->setDefined(isDefined); 8174 objc_method_decl->setDeclImplementation(impControl); 8175 objc_method_decl->setRelatedResultType(HasRelatedResultType); 8176 SetMemberOwningModule(objc_method_decl, class_interface_decl); 8177 8178 if (objc_method_decl == nullptr) 8179 return nullptr; 8180 8181 if (num_args > 0) { 8182 llvm::SmallVector<clang::ParmVarDecl *, 12> params; 8183 8184 for (unsigned param_index = 0; param_index < num_args; ++param_index) { 8185 params.push_back(clang::ParmVarDecl::Create( 8186 ast, objc_method_decl, clang::SourceLocation(), 8187 clang::SourceLocation(), 8188 nullptr, // anonymous 8189 method_function_prototype->getParamType(param_index), nullptr, 8190 clang::SC_Auto, nullptr)); 8191 } 8192 8193 objc_method_decl->setMethodParams( 8194 ast, llvm::ArrayRef<clang::ParmVarDecl *>(params), 8195 llvm::ArrayRef<clang::SourceLocation>()); 8196 } 8197 8198 if (is_objc_direct_call) { 8199 // Add a the objc_direct attribute to the declaration we generate that 8200 // we generate a direct method call for this ObjCMethodDecl. 8201 objc_method_decl->addAttr( 8202 clang::ObjCDirectAttr::CreateImplicit(ast, SourceLocation())); 8203 // Usually Sema is creating implicit parameters (e.g., self) when it 8204 // parses the method. We don't have a parsing Sema when we build our own 8205 // AST here so we manually need to create these implicit parameters to 8206 // make the direct call code generation happy. 8207 objc_method_decl->createImplicitParams(ast, class_interface_decl); 8208 } 8209 8210 class_interface_decl->addDecl(objc_method_decl); 8211 8212 VerifyDecl(objc_method_decl); 8213 8214 return objc_method_decl; 8215 } 8216 8217 bool TypeSystemClang::SetHasExternalStorage(lldb::opaque_compiler_type_t type, 8218 bool has_extern) { 8219 if (!type) 8220 return false; 8221 8222 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); 8223 8224 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 8225 switch (type_class) { 8226 case clang::Type::Record: { 8227 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); 8228 if (cxx_record_decl) { 8229 cxx_record_decl->setHasExternalLexicalStorage(has_extern); 8230 cxx_record_decl->setHasExternalVisibleStorage(has_extern); 8231 return true; 8232 } 8233 } break; 8234 8235 case clang::Type::Enum: { 8236 clang::EnumDecl *enum_decl = 8237 llvm::cast<clang::EnumType>(qual_type)->getDecl(); 8238 if (enum_decl) { 8239 enum_decl->setHasExternalLexicalStorage(has_extern); 8240 enum_decl->setHasExternalVisibleStorage(has_extern); 8241 return true; 8242 } 8243 } break; 8244 8245 case clang::Type::ObjCObject: 8246 case clang::Type::ObjCInterface: { 8247 const clang::ObjCObjectType *objc_class_type = 8248 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 8249 assert(objc_class_type); 8250 if (objc_class_type) { 8251 clang::ObjCInterfaceDecl *class_interface_decl = 8252 objc_class_type->getInterface(); 8253 8254 if (class_interface_decl) { 8255 class_interface_decl->setHasExternalLexicalStorage(has_extern); 8256 class_interface_decl->setHasExternalVisibleStorage(has_extern); 8257 return true; 8258 } 8259 } 8260 } break; 8261 8262 default: 8263 break; 8264 } 8265 return false; 8266 } 8267 8268 #pragma mark TagDecl 8269 8270 bool TypeSystemClang::StartTagDeclarationDefinition(const CompilerType &type) { 8271 clang::QualType qual_type(ClangUtil::GetQualType(type)); 8272 if (!qual_type.isNull()) { 8273 const clang::TagType *tag_type = qual_type->getAs<clang::TagType>(); 8274 if (tag_type) { 8275 clang::TagDecl *tag_decl = tag_type->getDecl(); 8276 if (tag_decl) { 8277 tag_decl->startDefinition(); 8278 return true; 8279 } 8280 } 8281 8282 const clang::ObjCObjectType *object_type = 8283 qual_type->getAs<clang::ObjCObjectType>(); 8284 if (object_type) { 8285 clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface(); 8286 if (interface_decl) { 8287 interface_decl->startDefinition(); 8288 return true; 8289 } 8290 } 8291 } 8292 return false; 8293 } 8294 8295 bool TypeSystemClang::CompleteTagDeclarationDefinition( 8296 const CompilerType &type) { 8297 clang::QualType qual_type(ClangUtil::GetQualType(type)); 8298 if (qual_type.isNull()) 8299 return false; 8300 8301 auto ts = type.GetTypeSystem(); 8302 auto lldb_ast = ts.dyn_cast_or_null<TypeSystemClang>(); 8303 if (lldb_ast == nullptr) 8304 return false; 8305 8306 // Make sure we use the same methodology as 8307 // TypeSystemClang::StartTagDeclarationDefinition() as to how we start/end 8308 // the definition. 8309 const clang::TagType *tag_type = qual_type->getAs<clang::TagType>(); 8310 if (tag_type) { 8311 clang::TagDecl *tag_decl = tag_type->getDecl(); 8312 8313 if (auto *cxx_record_decl = llvm::dyn_cast<CXXRecordDecl>(tag_decl)) { 8314 // If we have a move constructor declared but no copy constructor we 8315 // need to explicitly mark it as deleted. Usually Sema would do this for 8316 // us in Sema::DeclareImplicitCopyConstructor but we don't have a Sema 8317 // when building an AST from debug information. 8318 // See also: 8319 // C++11 [class.copy]p7, p18: 8320 // If the class definition declares a move constructor or move assignment 8321 // operator, an implicitly declared copy constructor or copy assignment 8322 // operator is defined as deleted. 8323 if (cxx_record_decl->hasUserDeclaredMoveConstructor() || 8324 cxx_record_decl->hasUserDeclaredMoveAssignment()) { 8325 if (cxx_record_decl->needsImplicitCopyConstructor()) 8326 cxx_record_decl->setImplicitCopyConstructorIsDeleted(); 8327 if (cxx_record_decl->needsImplicitCopyAssignment()) 8328 cxx_record_decl->setImplicitCopyAssignmentIsDeleted(); 8329 } 8330 8331 if (!cxx_record_decl->isCompleteDefinition()) 8332 cxx_record_decl->completeDefinition(); 8333 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true); 8334 cxx_record_decl->setHasExternalLexicalStorage(false); 8335 cxx_record_decl->setHasExternalVisibleStorage(false); 8336 lldb_ast->SetCXXRecordDeclAccess(cxx_record_decl, 8337 clang::AccessSpecifier::AS_none); 8338 return true; 8339 } 8340 } 8341 8342 const clang::EnumType *enutype = qual_type->getAs<clang::EnumType>(); 8343 8344 if (!enutype) 8345 return false; 8346 clang::EnumDecl *enum_decl = enutype->getDecl(); 8347 8348 if (enum_decl->isCompleteDefinition()) 8349 return true; 8350 8351 clang::ASTContext &ast = lldb_ast->getASTContext(); 8352 8353 /// TODO This really needs to be fixed. 8354 8355 QualType integer_type(enum_decl->getIntegerType()); 8356 if (!integer_type.isNull()) { 8357 unsigned NumPositiveBits = 1; 8358 unsigned NumNegativeBits = 0; 8359 8360 clang::QualType promotion_qual_type; 8361 // If the enum integer type is less than an integer in bit width, 8362 // then we must promote it to an integer size. 8363 if (ast.getTypeSize(enum_decl->getIntegerType()) < 8364 ast.getTypeSize(ast.IntTy)) { 8365 if (enum_decl->getIntegerType()->isSignedIntegerType()) 8366 promotion_qual_type = ast.IntTy; 8367 else 8368 promotion_qual_type = ast.UnsignedIntTy; 8369 } else 8370 promotion_qual_type = enum_decl->getIntegerType(); 8371 8372 enum_decl->completeDefinition(enum_decl->getIntegerType(), 8373 promotion_qual_type, NumPositiveBits, 8374 NumNegativeBits); 8375 } 8376 return true; 8377 } 8378 8379 clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType( 8380 const CompilerType &enum_type, const Declaration &decl, const char *name, 8381 const llvm::APSInt &value) { 8382 8383 if (!enum_type || ConstString(name).IsEmpty()) 8384 return nullptr; 8385 8386 lldbassert(enum_type.GetTypeSystem().GetSharedPointer().get() == 8387 static_cast<TypeSystem *>(this)); 8388 8389 lldb::opaque_compiler_type_t enum_opaque_compiler_type = 8390 enum_type.GetOpaqueQualType(); 8391 8392 if (!enum_opaque_compiler_type) 8393 return nullptr; 8394 8395 clang::QualType enum_qual_type( 8396 GetCanonicalQualType(enum_opaque_compiler_type)); 8397 8398 const clang::Type *clang_type = enum_qual_type.getTypePtr(); 8399 8400 if (!clang_type) 8401 return nullptr; 8402 8403 const clang::EnumType *enutype = llvm::dyn_cast<clang::EnumType>(clang_type); 8404 8405 if (!enutype) 8406 return nullptr; 8407 8408 clang::EnumConstantDecl *enumerator_decl = 8409 clang::EnumConstantDecl::CreateDeserialized(getASTContext(), 0); 8410 enumerator_decl->setDeclContext(enutype->getDecl()); 8411 if (name && name[0]) 8412 enumerator_decl->setDeclName(&getASTContext().Idents.get(name)); 8413 enumerator_decl->setType(clang::QualType(enutype, 0)); 8414 enumerator_decl->setInitVal(value); 8415 SetMemberOwningModule(enumerator_decl, enutype->getDecl()); 8416 8417 if (!enumerator_decl) 8418 return nullptr; 8419 8420 enutype->getDecl()->addDecl(enumerator_decl); 8421 8422 VerifyDecl(enumerator_decl); 8423 return enumerator_decl; 8424 } 8425 8426 clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType( 8427 const CompilerType &enum_type, const Declaration &decl, const char *name, 8428 int64_t enum_value, uint32_t enum_value_bit_size) { 8429 CompilerType underlying_type = GetEnumerationIntegerType(enum_type); 8430 bool is_signed = false; 8431 underlying_type.IsIntegerType(is_signed); 8432 8433 llvm::APSInt value(enum_value_bit_size, is_signed); 8434 value = enum_value; 8435 8436 return AddEnumerationValueToEnumerationType(enum_type, decl, name, value); 8437 } 8438 8439 CompilerType TypeSystemClang::GetEnumerationIntegerType(CompilerType type) { 8440 clang::QualType qt(ClangUtil::GetQualType(type)); 8441 const clang::Type *clang_type = qt.getTypePtrOrNull(); 8442 const auto *enum_type = llvm::dyn_cast_or_null<clang::EnumType>(clang_type); 8443 if (!enum_type) 8444 return CompilerType(); 8445 8446 return GetType(enum_type->getDecl()->getIntegerType()); 8447 } 8448 8449 CompilerType 8450 TypeSystemClang::CreateMemberPointerType(const CompilerType &type, 8451 const CompilerType &pointee_type) { 8452 if (type && pointee_type.IsValid() && 8453 type.GetTypeSystem() == pointee_type.GetTypeSystem()) { 8454 auto ts = type.GetTypeSystem(); 8455 auto ast = ts.dyn_cast_or_null<TypeSystemClang>(); 8456 if (!ast) 8457 return CompilerType(); 8458 return ast->GetType(ast->getASTContext().getMemberPointerType( 8459 ClangUtil::GetQualType(pointee_type), 8460 ClangUtil::GetQualType(type).getTypePtr())); 8461 } 8462 return CompilerType(); 8463 } 8464 8465 // Dumping types 8466 #define DEPTH_INCREMENT 2 8467 8468 #ifndef NDEBUG 8469 LLVM_DUMP_METHOD void 8470 TypeSystemClang::dump(lldb::opaque_compiler_type_t type) const { 8471 if (!type) 8472 return; 8473 clang::QualType qual_type(GetQualType(type)); 8474 qual_type.dump(); 8475 } 8476 #endif 8477 8478 void TypeSystemClang::Dump(llvm::raw_ostream &output) { 8479 GetTranslationUnitDecl()->dump(output); 8480 } 8481 8482 void TypeSystemClang::DumpFromSymbolFile(Stream &s, 8483 llvm::StringRef symbol_name) { 8484 SymbolFile *symfile = GetSymbolFile(); 8485 8486 if (!symfile) 8487 return; 8488 8489 lldb_private::TypeList type_list; 8490 symfile->GetTypes(nullptr, eTypeClassAny, type_list); 8491 size_t ntypes = type_list.GetSize(); 8492 8493 for (size_t i = 0; i < ntypes; ++i) { 8494 TypeSP type = type_list.GetTypeAtIndex(i); 8495 8496 if (!symbol_name.empty()) 8497 if (symbol_name != type->GetName().GetStringRef()) 8498 continue; 8499 8500 s << type->GetName().AsCString() << "\n"; 8501 8502 CompilerType full_type = type->GetFullCompilerType(); 8503 if (clang::TagDecl *tag_decl = GetAsTagDecl(full_type)) { 8504 tag_decl->dump(s.AsRawOstream()); 8505 continue; 8506 } 8507 if (clang::TypedefNameDecl *typedef_decl = GetAsTypedefDecl(full_type)) { 8508 typedef_decl->dump(s.AsRawOstream()); 8509 continue; 8510 } 8511 if (auto *objc_obj = llvm::dyn_cast<clang::ObjCObjectType>( 8512 ClangUtil::GetQualType(full_type).getTypePtr())) { 8513 if (clang::ObjCInterfaceDecl *interface_decl = objc_obj->getInterface()) { 8514 interface_decl->dump(s.AsRawOstream()); 8515 continue; 8516 } 8517 } 8518 GetCanonicalQualType(full_type.GetOpaqueQualType()) 8519 .dump(s.AsRawOstream(), getASTContext()); 8520 } 8521 } 8522 8523 void TypeSystemClang::DumpValue( 8524 lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream &s, 8525 lldb::Format format, const lldb_private::DataExtractor &data, 8526 lldb::offset_t data_byte_offset, size_t data_byte_size, 8527 uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool show_types, 8528 bool show_summary, bool verbose, uint32_t depth) { 8529 if (!type) 8530 return; 8531 8532 clang::QualType qual_type(GetQualType(type)); 8533 switch (qual_type->getTypeClass()) { 8534 case clang::Type::Record: 8535 if (GetCompleteType(type)) { 8536 const clang::RecordType *record_type = 8537 llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 8538 const clang::RecordDecl *record_decl = record_type->getDecl(); 8539 assert(record_decl); 8540 uint32_t field_bit_offset = 0; 8541 uint32_t field_byte_offset = 0; 8542 const clang::ASTRecordLayout &record_layout = 8543 getASTContext().getASTRecordLayout(record_decl); 8544 uint32_t child_idx = 0; 8545 8546 const clang::CXXRecordDecl *cxx_record_decl = 8547 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl); 8548 if (cxx_record_decl) { 8549 // We might have base classes to print out first 8550 clang::CXXRecordDecl::base_class_const_iterator base_class, 8551 base_class_end; 8552 for (base_class = cxx_record_decl->bases_begin(), 8553 base_class_end = cxx_record_decl->bases_end(); 8554 base_class != base_class_end; ++base_class) { 8555 const clang::CXXRecordDecl *base_class_decl = 8556 llvm::cast<clang::CXXRecordDecl>( 8557 base_class->getType()->getAs<clang::RecordType>()->getDecl()); 8558 8559 // Skip empty base classes 8560 if (!verbose && !TypeSystemClang::RecordHasFields(base_class_decl)) 8561 continue; 8562 8563 if (base_class->isVirtual()) 8564 field_bit_offset = 8565 record_layout.getVBaseClassOffset(base_class_decl) 8566 .getQuantity() * 8567 8; 8568 else 8569 field_bit_offset = record_layout.getBaseClassOffset(base_class_decl) 8570 .getQuantity() * 8571 8; 8572 field_byte_offset = field_bit_offset / 8; 8573 assert(field_bit_offset % 8 == 0); 8574 if (child_idx == 0) 8575 s.PutChar('{'); 8576 else 8577 s.PutChar(','); 8578 8579 clang::QualType base_class_qual_type = base_class->getType(); 8580 std::string base_class_type_name(base_class_qual_type.getAsString()); 8581 8582 // Indent and print the base class type name 8583 s.Format("\n{0}{1}", llvm::fmt_repeat(" ", depth + DEPTH_INCREMENT), 8584 base_class_type_name); 8585 8586 clang::TypeInfo base_class_type_info = 8587 getASTContext().getTypeInfo(base_class_qual_type); 8588 8589 // Dump the value of the member 8590 CompilerType base_clang_type = GetType(base_class_qual_type); 8591 base_clang_type.DumpValue( 8592 exe_ctx, 8593 &s, // Stream to dump to 8594 base_clang_type 8595 .GetFormat(), // The format with which to display the member 8596 data, // Data buffer containing all bytes for this type 8597 data_byte_offset + field_byte_offset, // Offset into "data" where 8598 // to grab value from 8599 base_class_type_info.Width / 8, // Size of this type in bytes 8600 0, // Bitfield bit size 8601 0, // Bitfield bit offset 8602 show_types, // Boolean indicating if we should show the variable 8603 // types 8604 show_summary, // Boolean indicating if we should show a summary 8605 // for the current type 8606 verbose, // Verbose output? 8607 depth + DEPTH_INCREMENT); // Scope depth for any types that have 8608 // children 8609 8610 ++child_idx; 8611 } 8612 } 8613 uint32_t field_idx = 0; 8614 clang::RecordDecl::field_iterator field, field_end; 8615 for (field = record_decl->field_begin(), 8616 field_end = record_decl->field_end(); 8617 field != field_end; ++field, ++field_idx, ++child_idx) { 8618 // Print the starting squiggly bracket (if this is the first member) or 8619 // comma (for member 2 and beyond) for the struct/union/class member. 8620 if (child_idx == 0) 8621 s.PutChar('{'); 8622 else 8623 s.PutChar(','); 8624 8625 // Indent 8626 s.Printf("\n%*s", depth + DEPTH_INCREMENT, ""); 8627 8628 clang::QualType field_type = field->getType(); 8629 // Print the member type if requested 8630 // Figure out the type byte size (field_type_info.first) and alignment 8631 // (field_type_info.second) from the AST context. 8632 clang::TypeInfo field_type_info = 8633 getASTContext().getTypeInfo(field_type); 8634 assert(field_idx < record_layout.getFieldCount()); 8635 // Figure out the field offset within the current struct/union/class 8636 // type 8637 field_bit_offset = record_layout.getFieldOffset(field_idx); 8638 field_byte_offset = field_bit_offset / 8; 8639 uint32_t field_bitfield_bit_size = 0; 8640 uint32_t field_bitfield_bit_offset = 0; 8641 if (FieldIsBitfield(*field, field_bitfield_bit_size)) 8642 field_bitfield_bit_offset = field_bit_offset % 8; 8643 8644 if (show_types) { 8645 std::string field_type_name(field_type.getAsString()); 8646 if (field_bitfield_bit_size > 0) 8647 s.Printf("(%s:%u) ", field_type_name.c_str(), 8648 field_bitfield_bit_size); 8649 else 8650 s.Printf("(%s) ", field_type_name.c_str()); 8651 } 8652 // Print the member name and equal sign 8653 s.Printf("%s = ", field->getNameAsString().c_str()); 8654 8655 // Dump the value of the member 8656 CompilerType field_clang_type = GetType(field_type); 8657 field_clang_type.DumpValue( 8658 exe_ctx, 8659 &s, // Stream to dump to 8660 field_clang_type 8661 .GetFormat(), // The format with which to display the member 8662 data, // Data buffer containing all bytes for this type 8663 data_byte_offset + field_byte_offset, // Offset into "data" where to 8664 // grab value from 8665 field_type_info.Width / 8, // Size of this type in bytes 8666 field_bitfield_bit_size, // Bitfield bit size 8667 field_bitfield_bit_offset, // Bitfield bit offset 8668 show_types, // Boolean indicating if we should show the variable 8669 // types 8670 show_summary, // Boolean indicating if we should show a summary for 8671 // the current type 8672 verbose, // Verbose output? 8673 depth + DEPTH_INCREMENT); // Scope depth for any types that have 8674 // children 8675 } 8676 8677 // Indent the trailing squiggly bracket 8678 if (child_idx > 0) 8679 s.Printf("\n%*s}", depth, ""); 8680 } 8681 return; 8682 8683 case clang::Type::Enum: 8684 if (GetCompleteType(type)) { 8685 const clang::EnumType *enutype = 8686 llvm::cast<clang::EnumType>(qual_type.getTypePtr()); 8687 const clang::EnumDecl *enum_decl = enutype->getDecl(); 8688 assert(enum_decl); 8689 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos; 8690 lldb::offset_t offset = data_byte_offset; 8691 const int64_t enum_value = data.GetMaxU64Bitfield( 8692 &offset, data_byte_size, bitfield_bit_size, bitfield_bit_offset); 8693 for (enum_pos = enum_decl->enumerator_begin(), 8694 enum_end_pos = enum_decl->enumerator_end(); 8695 enum_pos != enum_end_pos; ++enum_pos) { 8696 if (enum_pos->getInitVal() == enum_value) { 8697 s.Printf("%s", enum_pos->getNameAsString().c_str()); 8698 return; 8699 } 8700 } 8701 // If we have gotten here we didn't get find the enumerator in the enum 8702 // decl, so just print the integer. 8703 s.Printf("%" PRIi64, enum_value); 8704 } 8705 return; 8706 8707 case clang::Type::ConstantArray: { 8708 const clang::ConstantArrayType *array = 8709 llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr()); 8710 bool is_array_of_characters = false; 8711 clang::QualType element_qual_type = array->getElementType(); 8712 8713 const clang::Type *canonical_type = 8714 element_qual_type->getCanonicalTypeInternal().getTypePtr(); 8715 if (canonical_type) 8716 is_array_of_characters = canonical_type->isCharType(); 8717 8718 const uint64_t element_count = array->getSize().getLimitedValue(); 8719 8720 clang::TypeInfo field_type_info = 8721 getASTContext().getTypeInfo(element_qual_type); 8722 8723 uint32_t element_idx = 0; 8724 uint32_t element_offset = 0; 8725 uint64_t element_byte_size = field_type_info.Width / 8; 8726 uint32_t element_stride = element_byte_size; 8727 8728 if (is_array_of_characters) { 8729 s.PutChar('"'); 8730 DumpDataExtractor(data, &s, data_byte_offset, lldb::eFormatChar, 8731 element_byte_size, element_count, UINT32_MAX, 8732 LLDB_INVALID_ADDRESS, 0, 0); 8733 s.PutChar('"'); 8734 return; 8735 } else { 8736 CompilerType element_clang_type = GetType(element_qual_type); 8737 lldb::Format element_format = element_clang_type.GetFormat(); 8738 8739 for (element_idx = 0; element_idx < element_count; ++element_idx) { 8740 // Print the starting squiggly bracket (if this is the first member) or 8741 // comman (for member 2 and beyong) for the struct/union/class member. 8742 if (element_idx == 0) 8743 s.PutChar('{'); 8744 else 8745 s.PutChar(','); 8746 8747 // Indent and print the index 8748 s.Printf("\n%*s[%u] ", depth + DEPTH_INCREMENT, "", element_idx); 8749 8750 // Figure out the field offset within the current struct/union/class 8751 // type 8752 element_offset = element_idx * element_stride; 8753 8754 // Dump the value of the member 8755 element_clang_type.DumpValue( 8756 exe_ctx, 8757 &s, // Stream to dump to 8758 element_format, // The format with which to display the element 8759 data, // Data buffer containing all bytes for this type 8760 data_byte_offset + 8761 element_offset, // Offset into "data" where to grab value from 8762 element_byte_size, // Size of this type in bytes 8763 0, // Bitfield bit size 8764 0, // Bitfield bit offset 8765 show_types, // Boolean indicating if we should show the variable 8766 // types 8767 show_summary, // Boolean indicating if we should show a summary for 8768 // the current type 8769 verbose, // Verbose output? 8770 depth + DEPTH_INCREMENT); // Scope depth for any types that have 8771 // children 8772 } 8773 8774 // Indent the trailing squiggly bracket 8775 if (element_idx > 0) 8776 s.Printf("\n%*s}", depth, ""); 8777 } 8778 } 8779 return; 8780 8781 case clang::Type::Typedef: { 8782 clang::QualType typedef_qual_type = 8783 llvm::cast<clang::TypedefType>(qual_type) 8784 ->getDecl() 8785 ->getUnderlyingType(); 8786 8787 CompilerType typedef_clang_type = GetType(typedef_qual_type); 8788 lldb::Format typedef_format = typedef_clang_type.GetFormat(); 8789 clang::TypeInfo typedef_type_info = 8790 getASTContext().getTypeInfo(typedef_qual_type); 8791 uint64_t typedef_byte_size = typedef_type_info.Width / 8; 8792 8793 return typedef_clang_type.DumpValue( 8794 exe_ctx, 8795 &s, // Stream to dump to 8796 typedef_format, // The format with which to display the element 8797 data, // Data buffer containing all bytes for this type 8798 data_byte_offset, // Offset into "data" where to grab value from 8799 typedef_byte_size, // Size of this type in bytes 8800 bitfield_bit_size, // Bitfield bit size 8801 bitfield_bit_offset, // Bitfield bit offset 8802 show_types, // Boolean indicating if we should show the variable types 8803 show_summary, // Boolean indicating if we should show a summary for the 8804 // current type 8805 verbose, // Verbose output? 8806 depth); // Scope depth for any types that have children 8807 } break; 8808 8809 case clang::Type::Auto: { 8810 clang::QualType elaborated_qual_type = 8811 llvm::cast<clang::AutoType>(qual_type)->getDeducedType(); 8812 CompilerType elaborated_clang_type = GetType(elaborated_qual_type); 8813 lldb::Format elaborated_format = elaborated_clang_type.GetFormat(); 8814 clang::TypeInfo elaborated_type_info = 8815 getASTContext().getTypeInfo(elaborated_qual_type); 8816 uint64_t elaborated_byte_size = elaborated_type_info.Width / 8; 8817 8818 return elaborated_clang_type.DumpValue( 8819 exe_ctx, 8820 &s, // Stream to dump to 8821 elaborated_format, // The format with which to display the element 8822 data, // Data buffer containing all bytes for this type 8823 data_byte_offset, // Offset into "data" where to grab value from 8824 elaborated_byte_size, // Size of this type in bytes 8825 bitfield_bit_size, // Bitfield bit size 8826 bitfield_bit_offset, // Bitfield bit offset 8827 show_types, // Boolean indicating if we should show the variable types 8828 show_summary, // Boolean indicating if we should show a summary for the 8829 // current type 8830 verbose, // Verbose output? 8831 depth); // Scope depth for any types that have children 8832 } break; 8833 8834 case clang::Type::Elaborated: { 8835 clang::QualType elaborated_qual_type = 8836 llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType(); 8837 CompilerType elaborated_clang_type = GetType(elaborated_qual_type); 8838 lldb::Format elaborated_format = elaborated_clang_type.GetFormat(); 8839 clang::TypeInfo elaborated_type_info = 8840 getASTContext().getTypeInfo(elaborated_qual_type); 8841 uint64_t elaborated_byte_size = elaborated_type_info.Width / 8; 8842 8843 return elaborated_clang_type.DumpValue( 8844 exe_ctx, 8845 &s, // Stream to dump to 8846 elaborated_format, // The format with which to display the element 8847 data, // Data buffer containing all bytes for this type 8848 data_byte_offset, // Offset into "data" where to grab value from 8849 elaborated_byte_size, // Size of this type in bytes 8850 bitfield_bit_size, // Bitfield bit size 8851 bitfield_bit_offset, // Bitfield bit offset 8852 show_types, // Boolean indicating if we should show the variable types 8853 show_summary, // Boolean indicating if we should show a summary for the 8854 // current type 8855 verbose, // Verbose output? 8856 depth); // Scope depth for any types that have children 8857 } break; 8858 8859 case clang::Type::Paren: { 8860 clang::QualType desugar_qual_type = 8861 llvm::cast<clang::ParenType>(qual_type)->desugar(); 8862 CompilerType desugar_clang_type = GetType(desugar_qual_type); 8863 8864 lldb::Format desugar_format = desugar_clang_type.GetFormat(); 8865 clang::TypeInfo desugar_type_info = 8866 getASTContext().getTypeInfo(desugar_qual_type); 8867 uint64_t desugar_byte_size = desugar_type_info.Width / 8; 8868 8869 return desugar_clang_type.DumpValue( 8870 exe_ctx, 8871 &s, // Stream to dump to 8872 desugar_format, // The format with which to display the element 8873 data, // Data buffer containing all bytes for this type 8874 data_byte_offset, // Offset into "data" where to grab value from 8875 desugar_byte_size, // Size of this type in bytes 8876 bitfield_bit_size, // Bitfield bit size 8877 bitfield_bit_offset, // Bitfield bit offset 8878 show_types, // Boolean indicating if we should show the variable types 8879 show_summary, // Boolean indicating if we should show a summary for the 8880 // current type 8881 verbose, // Verbose output? 8882 depth); // Scope depth for any types that have children 8883 } break; 8884 8885 default: 8886 // We are down to a scalar type that we just need to display. 8887 DumpDataExtractor(data, &s, data_byte_offset, format, data_byte_size, 1, 8888 UINT32_MAX, LLDB_INVALID_ADDRESS, bitfield_bit_size, 8889 bitfield_bit_offset); 8890 8891 if (show_summary) 8892 DumpSummary(type, exe_ctx, s, data, data_byte_offset, data_byte_size); 8893 break; 8894 } 8895 } 8896 8897 static bool DumpEnumValue(const clang::QualType &qual_type, Stream &s, 8898 const DataExtractor &data, lldb::offset_t byte_offset, 8899 size_t byte_size, uint32_t bitfield_bit_offset, 8900 uint32_t bitfield_bit_size) { 8901 const clang::EnumType *enutype = 8902 llvm::cast<clang::EnumType>(qual_type.getTypePtr()); 8903 const clang::EnumDecl *enum_decl = enutype->getDecl(); 8904 assert(enum_decl); 8905 lldb::offset_t offset = byte_offset; 8906 const uint64_t enum_svalue = data.GetMaxS64Bitfield( 8907 &offset, byte_size, bitfield_bit_size, bitfield_bit_offset); 8908 bool can_be_bitfield = true; 8909 uint64_t covered_bits = 0; 8910 int num_enumerators = 0; 8911 8912 // Try to find an exact match for the value. 8913 // At the same time, we're applying a heuristic to determine whether we want 8914 // to print this enum as a bitfield. We're likely dealing with a bitfield if 8915 // every enumerator is either a one bit value or a superset of the previous 8916 // enumerators. Also 0 doesn't make sense when the enumerators are used as 8917 // flags. 8918 for (auto *enumerator : enum_decl->enumerators()) { 8919 uint64_t val = enumerator->getInitVal().getSExtValue(); 8920 val = llvm::SignExtend64(val, 8*byte_size); 8921 if (llvm::popcount(val) != 1 && (val & ~covered_bits) != 0) 8922 can_be_bitfield = false; 8923 covered_bits |= val; 8924 ++num_enumerators; 8925 if (val == enum_svalue) { 8926 // Found an exact match, that's all we need to do. 8927 s.PutCString(enumerator->getNameAsString()); 8928 return true; 8929 } 8930 } 8931 8932 // Unsigned values make more sense for flags. 8933 offset = byte_offset; 8934 const uint64_t enum_uvalue = data.GetMaxU64Bitfield( 8935 &offset, byte_size, bitfield_bit_size, bitfield_bit_offset); 8936 8937 // No exact match, but we don't think this is a bitfield. Print the value as 8938 // decimal. 8939 if (!can_be_bitfield) { 8940 if (qual_type->isSignedIntegerOrEnumerationType()) 8941 s.Printf("%" PRIi64, enum_svalue); 8942 else 8943 s.Printf("%" PRIu64, enum_uvalue); 8944 return true; 8945 } 8946 8947 uint64_t remaining_value = enum_uvalue; 8948 std::vector<std::pair<uint64_t, llvm::StringRef>> values; 8949 values.reserve(num_enumerators); 8950 for (auto *enumerator : enum_decl->enumerators()) 8951 if (auto val = enumerator->getInitVal().getZExtValue()) 8952 values.emplace_back(val, enumerator->getName()); 8953 8954 // Sort in reverse order of the number of the population count, so that in 8955 // `enum {A, B, ALL = A|B }` we visit ALL first. Use a stable sort so that 8956 // A | C where A is declared before C is displayed in this order. 8957 std::stable_sort(values.begin(), values.end(), 8958 [](const auto &a, const auto &b) { 8959 return llvm::popcount(a.first) > llvm::popcount(b.first); 8960 }); 8961 8962 for (const auto &val : values) { 8963 if ((remaining_value & val.first) != val.first) 8964 continue; 8965 remaining_value &= ~val.first; 8966 s.PutCString(val.second); 8967 if (remaining_value) 8968 s.PutCString(" | "); 8969 } 8970 8971 // If there is a remainder that is not covered by the value, print it as hex. 8972 if (remaining_value) 8973 s.Printf("0x%" PRIx64, remaining_value); 8974 8975 return true; 8976 } 8977 8978 bool TypeSystemClang::DumpTypeValue( 8979 lldb::opaque_compiler_type_t type, Stream &s, lldb::Format format, 8980 const lldb_private::DataExtractor &data, lldb::offset_t byte_offset, 8981 size_t byte_size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, 8982 ExecutionContextScope *exe_scope) { 8983 if (!type) 8984 return false; 8985 if (IsAggregateType(type)) { 8986 return false; 8987 } else { 8988 clang::QualType qual_type(GetQualType(type)); 8989 8990 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 8991 8992 if (type_class == clang::Type::Elaborated) { 8993 qual_type = llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType(); 8994 return DumpTypeValue(qual_type.getAsOpaquePtr(), s, format, data, byte_offset, byte_size, 8995 bitfield_bit_size, bitfield_bit_offset, exe_scope); 8996 } 8997 8998 switch (type_class) { 8999 case clang::Type::Typedef: { 9000 clang::QualType typedef_qual_type = 9001 llvm::cast<clang::TypedefType>(qual_type) 9002 ->getDecl() 9003 ->getUnderlyingType(); 9004 CompilerType typedef_clang_type = GetType(typedef_qual_type); 9005 if (format == eFormatDefault) 9006 format = typedef_clang_type.GetFormat(); 9007 clang::TypeInfo typedef_type_info = 9008 getASTContext().getTypeInfo(typedef_qual_type); 9009 uint64_t typedef_byte_size = typedef_type_info.Width / 8; 9010 9011 return typedef_clang_type.DumpTypeValue( 9012 &s, 9013 format, // The format with which to display the element 9014 data, // Data buffer containing all bytes for this type 9015 byte_offset, // Offset into "data" where to grab value from 9016 typedef_byte_size, // Size of this type in bytes 9017 bitfield_bit_size, // Size in bits of a bitfield value, if zero don't 9018 // treat as a bitfield 9019 bitfield_bit_offset, // Offset in bits of a bitfield value if 9020 // bitfield_bit_size != 0 9021 exe_scope); 9022 } break; 9023 9024 case clang::Type::Enum: 9025 // If our format is enum or default, show the enumeration value as its 9026 // enumeration string value, else just display it as requested. 9027 if ((format == eFormatEnum || format == eFormatDefault) && 9028 GetCompleteType(type)) 9029 return DumpEnumValue(qual_type, s, data, byte_offset, byte_size, 9030 bitfield_bit_offset, bitfield_bit_size); 9031 // format was not enum, just fall through and dump the value as 9032 // requested.... 9033 [[fallthrough]]; 9034 9035 default: 9036 // We are down to a scalar type that we just need to display. 9037 { 9038 uint32_t item_count = 1; 9039 // A few formats, we might need to modify our size and count for 9040 // depending 9041 // on how we are trying to display the value... 9042 switch (format) { 9043 default: 9044 case eFormatBoolean: 9045 case eFormatBinary: 9046 case eFormatComplex: 9047 case eFormatCString: // NULL terminated C strings 9048 case eFormatDecimal: 9049 case eFormatEnum: 9050 case eFormatHex: 9051 case eFormatHexUppercase: 9052 case eFormatFloat: 9053 case eFormatOctal: 9054 case eFormatOSType: 9055 case eFormatUnsigned: 9056 case eFormatPointer: 9057 case eFormatVectorOfChar: 9058 case eFormatVectorOfSInt8: 9059 case eFormatVectorOfUInt8: 9060 case eFormatVectorOfSInt16: 9061 case eFormatVectorOfUInt16: 9062 case eFormatVectorOfSInt32: 9063 case eFormatVectorOfUInt32: 9064 case eFormatVectorOfSInt64: 9065 case eFormatVectorOfUInt64: 9066 case eFormatVectorOfFloat32: 9067 case eFormatVectorOfFloat64: 9068 case eFormatVectorOfUInt128: 9069 break; 9070 9071 case eFormatChar: 9072 case eFormatCharPrintable: 9073 case eFormatCharArray: 9074 case eFormatBytes: 9075 case eFormatUnicode8: 9076 case eFormatBytesWithASCII: 9077 item_count = byte_size; 9078 byte_size = 1; 9079 break; 9080 9081 case eFormatUnicode16: 9082 item_count = byte_size / 2; 9083 byte_size = 2; 9084 break; 9085 9086 case eFormatUnicode32: 9087 item_count = byte_size / 4; 9088 byte_size = 4; 9089 break; 9090 } 9091 return DumpDataExtractor(data, &s, byte_offset, format, byte_size, 9092 item_count, UINT32_MAX, LLDB_INVALID_ADDRESS, 9093 bitfield_bit_size, bitfield_bit_offset, 9094 exe_scope); 9095 } 9096 break; 9097 } 9098 } 9099 return false; 9100 } 9101 9102 void TypeSystemClang::DumpSummary(lldb::opaque_compiler_type_t type, 9103 ExecutionContext *exe_ctx, Stream &s, 9104 const lldb_private::DataExtractor &data, 9105 lldb::offset_t data_byte_offset, 9106 size_t data_byte_size) { 9107 uint32_t length = 0; 9108 if (IsCStringType(type, length)) { 9109 if (exe_ctx) { 9110 Process *process = exe_ctx->GetProcessPtr(); 9111 if (process) { 9112 lldb::offset_t offset = data_byte_offset; 9113 lldb::addr_t pointer_address = data.GetMaxU64(&offset, data_byte_size); 9114 std::vector<uint8_t> buf; 9115 if (length > 0) 9116 buf.resize(length); 9117 else 9118 buf.resize(256); 9119 9120 DataExtractor cstr_data(&buf.front(), buf.size(), 9121 process->GetByteOrder(), 4); 9122 buf.back() = '\0'; 9123 size_t bytes_read; 9124 size_t total_cstr_len = 0; 9125 Status error; 9126 while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(), 9127 buf.size(), error)) > 0) { 9128 const size_t len = strlen((const char *)&buf.front()); 9129 if (len == 0) 9130 break; 9131 if (total_cstr_len == 0) 9132 s.PutCString(" \""); 9133 DumpDataExtractor(cstr_data, &s, 0, lldb::eFormatChar, 1, len, 9134 UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0); 9135 total_cstr_len += len; 9136 if (len < buf.size()) 9137 break; 9138 pointer_address += total_cstr_len; 9139 } 9140 if (total_cstr_len > 0) 9141 s.PutChar('"'); 9142 } 9143 } 9144 } 9145 } 9146 9147 void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type, 9148 lldb::DescriptionLevel level) { 9149 StreamFile s(stdout, false); 9150 DumpTypeDescription(type, s, level); 9151 9152 CompilerType ct(weak_from_this(), type); 9153 const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr(); 9154 ClangASTMetadata *metadata = GetMetadata(clang_type); 9155 if (metadata) { 9156 metadata->Dump(&s); 9157 } 9158 } 9159 9160 void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type, 9161 Stream &s, 9162 lldb::DescriptionLevel level) { 9163 if (type) { 9164 clang::QualType qual_type = 9165 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}); 9166 9167 llvm::SmallVector<char, 1024> buf; 9168 llvm::raw_svector_ostream llvm_ostrm(buf); 9169 9170 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 9171 switch (type_class) { 9172 case clang::Type::ObjCObject: 9173 case clang::Type::ObjCInterface: { 9174 GetCompleteType(type); 9175 9176 auto *objc_class_type = 9177 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr()); 9178 assert(objc_class_type); 9179 if (!objc_class_type) 9180 break; 9181 clang::ObjCInterfaceDecl *class_interface_decl = 9182 objc_class_type->getInterface(); 9183 if (!class_interface_decl) 9184 break; 9185 if (level == eDescriptionLevelVerbose) 9186 class_interface_decl->dump(llvm_ostrm); 9187 else 9188 class_interface_decl->print(llvm_ostrm, 9189 getASTContext().getPrintingPolicy(), 9190 s.GetIndentLevel()); 9191 } break; 9192 9193 case clang::Type::Typedef: { 9194 auto *typedef_type = qual_type->getAs<clang::TypedefType>(); 9195 if (!typedef_type) 9196 break; 9197 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl(); 9198 if (level == eDescriptionLevelVerbose) 9199 typedef_decl->dump(llvm_ostrm); 9200 else { 9201 std::string clang_typedef_name(GetTypeNameForDecl(typedef_decl)); 9202 if (!clang_typedef_name.empty()) { 9203 s.PutCString("typedef "); 9204 s.PutCString(clang_typedef_name); 9205 } 9206 } 9207 } break; 9208 9209 case clang::Type::Record: { 9210 GetCompleteType(type); 9211 9212 auto *record_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr()); 9213 const clang::RecordDecl *record_decl = record_type->getDecl(); 9214 if (level == eDescriptionLevelVerbose) 9215 record_decl->dump(llvm_ostrm); 9216 else { 9217 record_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(), 9218 s.GetIndentLevel()); 9219 } 9220 } break; 9221 9222 default: { 9223 if (auto *tag_type = 9224 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr())) { 9225 if (clang::TagDecl *tag_decl = tag_type->getDecl()) { 9226 if (level == eDescriptionLevelVerbose) 9227 tag_decl->dump(llvm_ostrm); 9228 else 9229 tag_decl->print(llvm_ostrm, 0); 9230 } 9231 } else { 9232 if (level == eDescriptionLevelVerbose) 9233 qual_type->dump(llvm_ostrm, getASTContext()); 9234 else { 9235 std::string clang_type_name(qual_type.getAsString()); 9236 if (!clang_type_name.empty()) 9237 s.PutCString(clang_type_name); 9238 } 9239 } 9240 } 9241 } 9242 9243 if (buf.size() > 0) { 9244 s.Write(buf.data(), buf.size()); 9245 } 9246 } 9247 } 9248 9249 void TypeSystemClang::DumpTypeName(const CompilerType &type) { 9250 if (ClangUtil::IsClangType(type)) { 9251 clang::QualType qual_type( 9252 ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type))); 9253 9254 const clang::Type::TypeClass type_class = qual_type->getTypeClass(); 9255 switch (type_class) { 9256 case clang::Type::Record: { 9257 const clang::CXXRecordDecl *cxx_record_decl = 9258 qual_type->getAsCXXRecordDecl(); 9259 if (cxx_record_decl) 9260 printf("class %s", cxx_record_decl->getName().str().c_str()); 9261 } break; 9262 9263 case clang::Type::Enum: { 9264 clang::EnumDecl *enum_decl = 9265 llvm::cast<clang::EnumType>(qual_type)->getDecl(); 9266 if (enum_decl) { 9267 printf("enum %s", enum_decl->getName().str().c_str()); 9268 } 9269 } break; 9270 9271 case clang::Type::ObjCObject: 9272 case clang::Type::ObjCInterface: { 9273 const clang::ObjCObjectType *objc_class_type = 9274 llvm::dyn_cast<clang::ObjCObjectType>(qual_type); 9275 if (objc_class_type) { 9276 clang::ObjCInterfaceDecl *class_interface_decl = 9277 objc_class_type->getInterface(); 9278 // We currently can't complete objective C types through the newly 9279 // added ASTContext because it only supports TagDecl objects right 9280 // now... 9281 if (class_interface_decl) 9282 printf("@class %s", class_interface_decl->getName().str().c_str()); 9283 } 9284 } break; 9285 9286 case clang::Type::Typedef: 9287 printf("typedef %s", llvm::cast<clang::TypedefType>(qual_type) 9288 ->getDecl() 9289 ->getName() 9290 .str() 9291 .c_str()); 9292 break; 9293 9294 case clang::Type::Auto: 9295 printf("auto "); 9296 return DumpTypeName(CompilerType(type.GetTypeSystem(), 9297 llvm::cast<clang::AutoType>(qual_type) 9298 ->getDeducedType() 9299 .getAsOpaquePtr())); 9300 9301 case clang::Type::Elaborated: 9302 printf("elaborated "); 9303 return DumpTypeName(CompilerType( 9304 type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type) 9305 ->getNamedType() 9306 .getAsOpaquePtr())); 9307 9308 case clang::Type::Paren: 9309 printf("paren "); 9310 return DumpTypeName(CompilerType( 9311 type.GetTypeSystem(), 9312 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr())); 9313 9314 default: 9315 printf("TypeSystemClang::DumpTypeName() type_class = %u", type_class); 9316 break; 9317 } 9318 } 9319 } 9320 9321 clang::ClassTemplateDecl *TypeSystemClang::ParseClassTemplateDecl( 9322 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, 9323 lldb::AccessType access_type, const char *parent_name, int tag_decl_kind, 9324 const TypeSystemClang::TemplateParameterInfos &template_param_infos) { 9325 if (template_param_infos.IsValid()) { 9326 std::string template_basename(parent_name); 9327 // With -gsimple-template-names we may omit template parameters in the name. 9328 if (auto i = template_basename.find('<'); i != std::string::npos) 9329 template_basename.erase(i); 9330 9331 return CreateClassTemplateDecl(decl_ctx, owning_module, access_type, 9332 template_basename.c_str(), tag_decl_kind, 9333 template_param_infos); 9334 } 9335 return nullptr; 9336 } 9337 9338 void TypeSystemClang::CompleteTagDecl(clang::TagDecl *decl) { 9339 SymbolFile *sym_file = GetSymbolFile(); 9340 if (sym_file) { 9341 CompilerType clang_type = GetTypeForDecl(decl); 9342 if (clang_type) 9343 sym_file->CompleteType(clang_type); 9344 } 9345 } 9346 9347 void TypeSystemClang::CompleteObjCInterfaceDecl( 9348 clang::ObjCInterfaceDecl *decl) { 9349 SymbolFile *sym_file = GetSymbolFile(); 9350 if (sym_file) { 9351 CompilerType clang_type = GetTypeForDecl(decl); 9352 if (clang_type) 9353 sym_file->CompleteType(clang_type); 9354 } 9355 } 9356 9357 DWARFASTParser *TypeSystemClang::GetDWARFParser() { 9358 if (!m_dwarf_ast_parser_up) 9359 m_dwarf_ast_parser_up = std::make_unique<DWARFASTParserClang>(*this); 9360 return m_dwarf_ast_parser_up.get(); 9361 } 9362 9363 #ifdef LLDB_ENABLE_ALL 9364 PDBASTParser *TypeSystemClang::GetPDBParser() { 9365 if (!m_pdb_ast_parser_up) 9366 m_pdb_ast_parser_up = std::make_unique<PDBASTParser>(*this); 9367 return m_pdb_ast_parser_up.get(); 9368 } 9369 9370 npdb::PdbAstBuilder *TypeSystemClang::GetNativePDBParser() { 9371 if (!m_native_pdb_ast_parser_up) 9372 m_native_pdb_ast_parser_up = std::make_unique<npdb::PdbAstBuilder>(*this); 9373 return m_native_pdb_ast_parser_up.get(); 9374 } 9375 #endif // LLDB_ENABLE_ALL 9376 9377 bool TypeSystemClang::LayoutRecordType( 9378 const clang::RecordDecl *record_decl, uint64_t &bit_size, 9379 uint64_t &alignment, 9380 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets, 9381 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> 9382 &base_offsets, 9383 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> 9384 &vbase_offsets) { 9385 lldb_private::ClangASTImporter *importer = nullptr; 9386 if (m_dwarf_ast_parser_up) 9387 importer = &m_dwarf_ast_parser_up->GetClangASTImporter(); 9388 #ifdef LLDB_ENABLE_ALL 9389 if (!importer && m_pdb_ast_parser_up) 9390 importer = &m_pdb_ast_parser_up->GetClangASTImporter(); 9391 if (!importer && m_native_pdb_ast_parser_up) 9392 importer = &m_native_pdb_ast_parser_up->GetClangASTImporter(); 9393 #endif // LLDB_ENABLE_ALL 9394 if (!importer) 9395 return false; 9396 9397 return importer->LayoutRecordType(record_decl, bit_size, alignment, 9398 field_offsets, base_offsets, vbase_offsets); 9399 } 9400 9401 // CompilerDecl override functions 9402 9403 ConstString TypeSystemClang::DeclGetName(void *opaque_decl) { 9404 if (opaque_decl) { 9405 clang::NamedDecl *nd = 9406 llvm::dyn_cast<NamedDecl>((clang::Decl *)opaque_decl); 9407 if (nd != nullptr) 9408 return ConstString(nd->getDeclName().getAsString()); 9409 } 9410 return ConstString(); 9411 } 9412 9413 ConstString TypeSystemClang::DeclGetMangledName(void *opaque_decl) { 9414 if (opaque_decl) { 9415 clang::NamedDecl *nd = 9416 llvm::dyn_cast<clang::NamedDecl>((clang::Decl *)opaque_decl); 9417 if (nd != nullptr && !llvm::isa<clang::ObjCMethodDecl>(nd)) { 9418 clang::MangleContext *mc = getMangleContext(); 9419 if (mc && mc->shouldMangleCXXName(nd)) { 9420 llvm::SmallVector<char, 1024> buf; 9421 llvm::raw_svector_ostream llvm_ostrm(buf); 9422 if (llvm::isa<clang::CXXConstructorDecl>(nd)) { 9423 mc->mangleName( 9424 clang::GlobalDecl(llvm::dyn_cast<clang::CXXConstructorDecl>(nd), 9425 Ctor_Complete), 9426 llvm_ostrm); 9427 } else if (llvm::isa<clang::CXXDestructorDecl>(nd)) { 9428 mc->mangleName( 9429 clang::GlobalDecl(llvm::dyn_cast<clang::CXXDestructorDecl>(nd), 9430 Dtor_Complete), 9431 llvm_ostrm); 9432 } else { 9433 mc->mangleName(nd, llvm_ostrm); 9434 } 9435 if (buf.size() > 0) 9436 return ConstString(buf.data(), buf.size()); 9437 } 9438 } 9439 } 9440 return ConstString(); 9441 } 9442 9443 CompilerDeclContext TypeSystemClang::DeclGetDeclContext(void *opaque_decl) { 9444 if (opaque_decl) 9445 return CreateDeclContext(((clang::Decl *)opaque_decl)->getDeclContext()); 9446 return CompilerDeclContext(); 9447 } 9448 9449 CompilerType TypeSystemClang::DeclGetFunctionReturnType(void *opaque_decl) { 9450 if (clang::FunctionDecl *func_decl = 9451 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) 9452 return GetType(func_decl->getReturnType()); 9453 if (clang::ObjCMethodDecl *objc_method = 9454 llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl)) 9455 return GetType(objc_method->getReturnType()); 9456 else 9457 return CompilerType(); 9458 } 9459 9460 size_t TypeSystemClang::DeclGetFunctionNumArguments(void *opaque_decl) { 9461 if (clang::FunctionDecl *func_decl = 9462 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) 9463 return func_decl->param_size(); 9464 if (clang::ObjCMethodDecl *objc_method = 9465 llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl)) 9466 return objc_method->param_size(); 9467 else 9468 return 0; 9469 } 9470 9471 CompilerType TypeSystemClang::DeclGetFunctionArgumentType(void *opaque_decl, 9472 size_t idx) { 9473 if (clang::FunctionDecl *func_decl = 9474 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) { 9475 if (idx < func_decl->param_size()) { 9476 ParmVarDecl *var_decl = func_decl->getParamDecl(idx); 9477 if (var_decl) 9478 return GetType(var_decl->getOriginalType()); 9479 } 9480 } else if (clang::ObjCMethodDecl *objc_method = 9481 llvm::dyn_cast<clang::ObjCMethodDecl>( 9482 (clang::Decl *)opaque_decl)) { 9483 if (idx < objc_method->param_size()) 9484 return GetType(objc_method->parameters()[idx]->getOriginalType()); 9485 } 9486 return CompilerType(); 9487 } 9488 9489 // CompilerDeclContext functions 9490 9491 std::vector<CompilerDecl> TypeSystemClang::DeclContextFindDeclByName( 9492 void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) { 9493 std::vector<CompilerDecl> found_decls; 9494 SymbolFile *symbol_file = GetSymbolFile(); 9495 if (opaque_decl_ctx && symbol_file) { 9496 DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx; 9497 std::set<DeclContext *> searched; 9498 std::multimap<DeclContext *, DeclContext *> search_queue; 9499 9500 for (clang::DeclContext *decl_context = root_decl_ctx; 9501 decl_context != nullptr && found_decls.empty(); 9502 decl_context = decl_context->getParent()) { 9503 search_queue.insert(std::make_pair(decl_context, decl_context)); 9504 9505 for (auto it = search_queue.find(decl_context); it != search_queue.end(); 9506 it++) { 9507 if (!searched.insert(it->second).second) 9508 continue; 9509 symbol_file->ParseDeclsForContext( 9510 CreateDeclContext(it->second)); 9511 9512 for (clang::Decl *child : it->second->decls()) { 9513 if (clang::UsingDirectiveDecl *ud = 9514 llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) { 9515 if (ignore_using_decls) 9516 continue; 9517 clang::DeclContext *from = ud->getCommonAncestor(); 9518 if (searched.find(ud->getNominatedNamespace()) == searched.end()) 9519 search_queue.insert( 9520 std::make_pair(from, ud->getNominatedNamespace())); 9521 } else if (clang::UsingDecl *ud = 9522 llvm::dyn_cast<clang::UsingDecl>(child)) { 9523 if (ignore_using_decls) 9524 continue; 9525 for (clang::UsingShadowDecl *usd : ud->shadows()) { 9526 clang::Decl *target = usd->getTargetDecl(); 9527 if (clang::NamedDecl *nd = 9528 llvm::dyn_cast<clang::NamedDecl>(target)) { 9529 IdentifierInfo *ii = nd->getIdentifier(); 9530 if (ii != nullptr && 9531 ii->getName().equals(name.AsCString(nullptr))) 9532 found_decls.push_back(GetCompilerDecl(nd)); 9533 } 9534 } 9535 } else if (clang::NamedDecl *nd = 9536 llvm::dyn_cast<clang::NamedDecl>(child)) { 9537 IdentifierInfo *ii = nd->getIdentifier(); 9538 if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr))) 9539 found_decls.push_back(GetCompilerDecl(nd)); 9540 } 9541 } 9542 } 9543 } 9544 } 9545 return found_decls; 9546 } 9547 9548 // Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents, 9549 // and return the number of levels it took to find it, or 9550 // LLDB_INVALID_DECL_LEVEL if not found. If the decl was imported via a using 9551 // declaration, its name and/or type, if set, will be used to check that the 9552 // decl found in the scope is a match. 9553 // 9554 // The optional name is required by languages (like C++) to handle using 9555 // declarations like: 9556 // 9557 // void poo(); 9558 // namespace ns { 9559 // void foo(); 9560 // void goo(); 9561 // } 9562 // void bar() { 9563 // using ns::foo; 9564 // // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and 9565 // // LLDB_INVALID_DECL_LEVEL for 'goo'. 9566 // } 9567 // 9568 // The optional type is useful in the case that there's a specific overload 9569 // that we're looking for that might otherwise be shadowed, like: 9570 // 9571 // void foo(int); 9572 // namespace ns { 9573 // void foo(); 9574 // } 9575 // void bar() { 9576 // using ns::foo; 9577 // // CountDeclLevels returns 0 for { 'foo', void() }, 9578 // // 1 for { 'foo', void(int) }, and 9579 // // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }. 9580 // } 9581 // 9582 // NOTE: Because file statics are at the TranslationUnit along with globals, a 9583 // function at file scope will return the same level as a function at global 9584 // scope. Ideally we'd like to treat the file scope as an additional scope just 9585 // below the global scope. More work needs to be done to recognise that, if 9586 // the decl we're trying to look up is static, we should compare its source 9587 // file with that of the current scope and return a lower number for it. 9588 uint32_t TypeSystemClang::CountDeclLevels(clang::DeclContext *frame_decl_ctx, 9589 clang::DeclContext *child_decl_ctx, 9590 ConstString *child_name, 9591 CompilerType *child_type) { 9592 SymbolFile *symbol_file = GetSymbolFile(); 9593 if (frame_decl_ctx && symbol_file) { 9594 std::set<DeclContext *> searched; 9595 std::multimap<DeclContext *, DeclContext *> search_queue; 9596 9597 // Get the lookup scope for the decl we're trying to find. 9598 clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent(); 9599 9600 // Look for it in our scope's decl context and its parents. 9601 uint32_t level = 0; 9602 for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr; 9603 decl_ctx = decl_ctx->getParent()) { 9604 if (!decl_ctx->isLookupContext()) 9605 continue; 9606 if (decl_ctx == parent_decl_ctx) 9607 // Found it! 9608 return level; 9609 search_queue.insert(std::make_pair(decl_ctx, decl_ctx)); 9610 for (auto it = search_queue.find(decl_ctx); it != search_queue.end(); 9611 it++) { 9612 if (searched.find(it->second) != searched.end()) 9613 continue; 9614 9615 // Currently DWARF has one shared translation unit for all Decls at top 9616 // level, so this would erroneously find using statements anywhere. So 9617 // don't look at the top-level translation unit. 9618 // TODO fix this and add a testcase that depends on it. 9619 9620 if (llvm::isa<clang::TranslationUnitDecl>(it->second)) 9621 continue; 9622 9623 searched.insert(it->second); 9624 symbol_file->ParseDeclsForContext( 9625 CreateDeclContext(it->second)); 9626 9627 for (clang::Decl *child : it->second->decls()) { 9628 if (clang::UsingDirectiveDecl *ud = 9629 llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) { 9630 clang::DeclContext *ns = ud->getNominatedNamespace(); 9631 if (ns == parent_decl_ctx) 9632 // Found it! 9633 return level; 9634 clang::DeclContext *from = ud->getCommonAncestor(); 9635 if (searched.find(ns) == searched.end()) 9636 search_queue.insert(std::make_pair(from, ns)); 9637 } else if (child_name) { 9638 if (clang::UsingDecl *ud = 9639 llvm::dyn_cast<clang::UsingDecl>(child)) { 9640 for (clang::UsingShadowDecl *usd : ud->shadows()) { 9641 clang::Decl *target = usd->getTargetDecl(); 9642 clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(target); 9643 if (!nd) 9644 continue; 9645 // Check names. 9646 IdentifierInfo *ii = nd->getIdentifier(); 9647 if (ii == nullptr || 9648 !ii->getName().equals(child_name->AsCString(nullptr))) 9649 continue; 9650 // Check types, if one was provided. 9651 if (child_type) { 9652 CompilerType clang_type = GetTypeForDecl(nd); 9653 if (!AreTypesSame(clang_type, *child_type, 9654 /*ignore_qualifiers=*/true)) 9655 continue; 9656 } 9657 // Found it! 9658 return level; 9659 } 9660 } 9661 } 9662 } 9663 } 9664 ++level; 9665 } 9666 } 9667 return LLDB_INVALID_DECL_LEVEL; 9668 } 9669 9670 ConstString TypeSystemClang::DeclContextGetName(void *opaque_decl_ctx) { 9671 if (opaque_decl_ctx) { 9672 clang::NamedDecl *named_decl = 9673 llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx); 9674 if (named_decl) 9675 return ConstString(named_decl->getName()); 9676 } 9677 return ConstString(); 9678 } 9679 9680 ConstString 9681 TypeSystemClang::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) { 9682 if (opaque_decl_ctx) { 9683 clang::NamedDecl *named_decl = 9684 llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx); 9685 if (named_decl) 9686 return ConstString(GetTypeNameForDecl(named_decl)); 9687 } 9688 return ConstString(); 9689 } 9690 9691 bool TypeSystemClang::DeclContextIsClassMethod(void *opaque_decl_ctx) { 9692 if (!opaque_decl_ctx) 9693 return false; 9694 9695 clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx; 9696 if (llvm::isa<clang::ObjCMethodDecl>(decl_ctx)) { 9697 return true; 9698 } else if (llvm::isa<clang::CXXMethodDecl>(decl_ctx)) { 9699 return true; 9700 } else if (clang::FunctionDecl *fun_decl = 9701 llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) { 9702 if (ClangASTMetadata *metadata = GetMetadata(fun_decl)) 9703 return metadata->HasObjectPtr(); 9704 } 9705 9706 return false; 9707 } 9708 9709 bool TypeSystemClang::DeclContextIsContainedInLookup( 9710 void *opaque_decl_ctx, void *other_opaque_decl_ctx) { 9711 auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx; 9712 auto *other = (clang::DeclContext *)other_opaque_decl_ctx; 9713 9714 do { 9715 // A decl context always includes its own contents in its lookup. 9716 if (decl_ctx == other) 9717 return true; 9718 9719 // If we have an inline namespace, then the lookup of the parent context 9720 // also includes the inline namespace contents. 9721 } while (other->isInlineNamespace() && (other = other->getParent())); 9722 9723 return false; 9724 } 9725 9726 lldb::LanguageType 9727 TypeSystemClang::DeclContextGetLanguage(void *opaque_decl_ctx) { 9728 if (!opaque_decl_ctx) 9729 return eLanguageTypeUnknown; 9730 9731 auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx; 9732 if (llvm::isa<clang::ObjCMethodDecl>(decl_ctx)) { 9733 return eLanguageTypeObjC; 9734 } else if (llvm::isa<clang::CXXMethodDecl>(decl_ctx)) { 9735 return eLanguageTypeC_plus_plus; 9736 } else if (auto *fun_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) { 9737 if (ClangASTMetadata *metadata = GetMetadata(fun_decl)) 9738 return metadata->GetObjectPtrLanguage(); 9739 } 9740 9741 return eLanguageTypeUnknown; 9742 } 9743 9744 static bool IsClangDeclContext(const CompilerDeclContext &dc) { 9745 return dc.IsValid() && isa<TypeSystemClang>(dc.GetTypeSystem()); 9746 } 9747 9748 clang::DeclContext * 9749 TypeSystemClang::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) { 9750 if (IsClangDeclContext(dc)) 9751 return (clang::DeclContext *)dc.GetOpaqueDeclContext(); 9752 return nullptr; 9753 } 9754 9755 ObjCMethodDecl * 9756 TypeSystemClang::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) { 9757 if (IsClangDeclContext(dc)) 9758 return llvm::dyn_cast<clang::ObjCMethodDecl>( 9759 (clang::DeclContext *)dc.GetOpaqueDeclContext()); 9760 return nullptr; 9761 } 9762 9763 CXXMethodDecl * 9764 TypeSystemClang::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) { 9765 if (IsClangDeclContext(dc)) 9766 return llvm::dyn_cast<clang::CXXMethodDecl>( 9767 (clang::DeclContext *)dc.GetOpaqueDeclContext()); 9768 return nullptr; 9769 } 9770 9771 clang::FunctionDecl * 9772 TypeSystemClang::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) { 9773 if (IsClangDeclContext(dc)) 9774 return llvm::dyn_cast<clang::FunctionDecl>( 9775 (clang::DeclContext *)dc.GetOpaqueDeclContext()); 9776 return nullptr; 9777 } 9778 9779 clang::NamespaceDecl * 9780 TypeSystemClang::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) { 9781 if (IsClangDeclContext(dc)) 9782 return llvm::dyn_cast<clang::NamespaceDecl>( 9783 (clang::DeclContext *)dc.GetOpaqueDeclContext()); 9784 return nullptr; 9785 } 9786 9787 ClangASTMetadata * 9788 TypeSystemClang::DeclContextGetMetaData(const CompilerDeclContext &dc, 9789 const Decl *object) { 9790 TypeSystemClang *ast = llvm::cast<TypeSystemClang>(dc.GetTypeSystem()); 9791 return ast->GetMetadata(object); 9792 } 9793 9794 clang::ASTContext * 9795 TypeSystemClang::DeclContextGetTypeSystemClang(const CompilerDeclContext &dc) { 9796 TypeSystemClang *ast = 9797 llvm::dyn_cast_or_null<TypeSystemClang>(dc.GetTypeSystem()); 9798 if (ast) 9799 return &ast->getASTContext(); 9800 return nullptr; 9801 } 9802 9803 void TypeSystemClang::RequireCompleteType(CompilerType type) { 9804 // Technically, enums can be incomplete too, but we don't handle those as they 9805 // are emitted even under -flimit-debug-info. 9806 if (!TypeSystemClang::IsCXXClassType(type)) 9807 return; 9808 9809 if (type.GetCompleteType()) 9810 return; 9811 9812 // No complete definition in this module. Mark the class as complete to 9813 // satisfy local ast invariants, but make a note of the fact that 9814 // it is not _really_ complete so we can later search for a definition in a 9815 // different module. 9816 // Since we provide layout assistance, layouts of types containing this class 9817 // will be correct even if we are not able to find the definition elsewhere. 9818 bool started = TypeSystemClang::StartTagDeclarationDefinition(type); 9819 lldbassert(started && "Unable to start a class type definition."); 9820 TypeSystemClang::CompleteTagDeclarationDefinition(type); 9821 const clang::TagDecl *td = ClangUtil::GetAsTagDecl(type); 9822 auto ts = type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>(); 9823 if (ts) 9824 ts->SetDeclIsForcefullyCompleted(td); 9825 } 9826 9827 namespace { 9828 /// A specialized scratch AST used within ScratchTypeSystemClang. 9829 /// These are the ASTs backing the different IsolatedASTKinds. They behave 9830 /// like a normal ScratchTypeSystemClang but they don't own their own 9831 /// persistent storage or target reference. 9832 class SpecializedScratchAST : public TypeSystemClang { 9833 public: 9834 /// \param name The display name of the TypeSystemClang instance. 9835 /// \param triple The triple used for the TypeSystemClang instance. 9836 /// \param ast_source The ClangASTSource that should be used to complete 9837 /// type information. 9838 SpecializedScratchAST(llvm::StringRef name, llvm::Triple triple, 9839 std::unique_ptr<ClangASTSource> ast_source) 9840 : TypeSystemClang(name, triple), 9841 m_scratch_ast_source_up(std::move(ast_source)) { 9842 // Setup the ClangASTSource to complete this AST. 9843 m_scratch_ast_source_up->InstallASTContext(*this); 9844 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source( 9845 m_scratch_ast_source_up->CreateProxy()); 9846 SetExternalSource(proxy_ast_source); 9847 } 9848 9849 /// The ExternalASTSource that performs lookups and completes types. 9850 std::unique_ptr<ClangASTSource> m_scratch_ast_source_up; 9851 }; 9852 } // namespace 9853 9854 char ScratchTypeSystemClang::ID; 9855 const std::nullopt_t ScratchTypeSystemClang::DefaultAST = std::nullopt; 9856 9857 ScratchTypeSystemClang::ScratchTypeSystemClang(Target &target, 9858 llvm::Triple triple) 9859 : TypeSystemClang("scratch ASTContext", triple), m_triple(triple), 9860 m_target_wp(target.shared_from_this()), 9861 m_persistent_variables( 9862 new ClangPersistentVariables(target.shared_from_this())) { 9863 m_scratch_ast_source_up = CreateASTSource(); 9864 m_scratch_ast_source_up->InstallASTContext(*this); 9865 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source( 9866 m_scratch_ast_source_up->CreateProxy()); 9867 SetExternalSource(proxy_ast_source); 9868 } 9869 9870 void ScratchTypeSystemClang::Finalize() { 9871 TypeSystemClang::Finalize(); 9872 m_scratch_ast_source_up.reset(); 9873 } 9874 9875 TypeSystemClangSP 9876 ScratchTypeSystemClang::GetForTarget(Target &target, 9877 std::optional<IsolatedASTKind> ast_kind, 9878 bool create_on_demand) { 9879 auto type_system_or_err = target.GetScratchTypeSystemForLanguage( 9880 lldb::eLanguageTypeC, create_on_demand); 9881 if (auto err = type_system_or_err.takeError()) { 9882 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err), 9883 "Couldn't get scratch TypeSystemClang"); 9884 return nullptr; 9885 } 9886 auto ts_sp = *type_system_or_err; 9887 ScratchTypeSystemClang *scratch_ast = 9888 llvm::dyn_cast_or_null<ScratchTypeSystemClang>(ts_sp.get()); 9889 if (!scratch_ast) 9890 return nullptr; 9891 // If no dedicated sub-AST was requested, just return the main AST. 9892 if (ast_kind == DefaultAST) 9893 return std::static_pointer_cast<TypeSystemClang>(ts_sp); 9894 // Search the sub-ASTs. 9895 return std::static_pointer_cast<TypeSystemClang>( 9896 scratch_ast->GetIsolatedAST(*ast_kind).shared_from_this()); 9897 } 9898 9899 /// Returns a human-readable name that uniquely identifiers the sub-AST kind. 9900 static llvm::StringRef 9901 GetNameForIsolatedASTKind(ScratchTypeSystemClang::IsolatedASTKind kind) { 9902 switch (kind) { 9903 case ScratchTypeSystemClang::IsolatedASTKind::CppModules: 9904 return "C++ modules"; 9905 } 9906 llvm_unreachable("Unimplemented IsolatedASTKind?"); 9907 } 9908 9909 void ScratchTypeSystemClang::Dump(llvm::raw_ostream &output) { 9910 // First dump the main scratch AST. 9911 output << "State of scratch Clang type system:\n"; 9912 TypeSystemClang::Dump(output); 9913 9914 // Now sort the isolated sub-ASTs. 9915 typedef std::pair<IsolatedASTKey, TypeSystem *> KeyAndTS; 9916 std::vector<KeyAndTS> sorted_typesystems; 9917 for (const auto &a : m_isolated_asts) 9918 sorted_typesystems.emplace_back(a.first, a.second.get()); 9919 llvm::stable_sort(sorted_typesystems, llvm::less_first()); 9920 9921 // Dump each sub-AST too. 9922 for (const auto &a : sorted_typesystems) { 9923 IsolatedASTKind kind = 9924 static_cast<ScratchTypeSystemClang::IsolatedASTKind>(a.first); 9925 output << "State of scratch Clang type subsystem " 9926 << GetNameForIsolatedASTKind(kind) << ":\n"; 9927 a.second->Dump(output); 9928 } 9929 } 9930 9931 UserExpression *ScratchTypeSystemClang::GetUserExpression( 9932 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, 9933 Expression::ResultType desired_type, 9934 const EvaluateExpressionOptions &options, ValueObject *ctx_obj) { 9935 TargetSP target_sp = m_target_wp.lock(); 9936 if (!target_sp) 9937 return nullptr; 9938 9939 return new ClangUserExpression(*target_sp.get(), expr, prefix, language, 9940 desired_type, options, ctx_obj); 9941 } 9942 9943 FunctionCaller *ScratchTypeSystemClang::GetFunctionCaller( 9944 const CompilerType &return_type, const Address &function_address, 9945 const ValueList &arg_value_list, const char *name) { 9946 TargetSP target_sp = m_target_wp.lock(); 9947 if (!target_sp) 9948 return nullptr; 9949 9950 Process *process = target_sp->GetProcessSP().get(); 9951 if (!process) 9952 return nullptr; 9953 9954 return new ClangFunctionCaller(*process, return_type, function_address, 9955 arg_value_list, name); 9956 } 9957 9958 std::unique_ptr<UtilityFunction> 9959 ScratchTypeSystemClang::CreateUtilityFunction(std::string text, 9960 std::string name) { 9961 TargetSP target_sp = m_target_wp.lock(); 9962 if (!target_sp) 9963 return {}; 9964 9965 return std::make_unique<ClangUtilityFunction>( 9966 *target_sp.get(), std::move(text), std::move(name), 9967 target_sp->GetDebugUtilityExpression()); 9968 } 9969 9970 PersistentExpressionState * 9971 ScratchTypeSystemClang::GetPersistentExpressionState() { 9972 return m_persistent_variables.get(); 9973 } 9974 9975 void ScratchTypeSystemClang::ForgetSource(ASTContext *src_ctx, 9976 ClangASTImporter &importer) { 9977 // Remove it as a source from the main AST. 9978 importer.ForgetSource(&getASTContext(), src_ctx); 9979 // Remove it as a source from all created sub-ASTs. 9980 for (const auto &a : m_isolated_asts) 9981 importer.ForgetSource(&a.second->getASTContext(), src_ctx); 9982 } 9983 9984 std::unique_ptr<ClangASTSource> ScratchTypeSystemClang::CreateASTSource() { 9985 return std::make_unique<ClangASTSource>( 9986 m_target_wp.lock()->shared_from_this(), 9987 m_persistent_variables->GetClangASTImporter()); 9988 } 9989 9990 static llvm::StringRef 9991 GetSpecializedASTName(ScratchTypeSystemClang::IsolatedASTKind feature) { 9992 switch (feature) { 9993 case ScratchTypeSystemClang::IsolatedASTKind::CppModules: 9994 return "scratch ASTContext for C++ module types"; 9995 } 9996 llvm_unreachable("Unimplemented ASTFeature kind?"); 9997 } 9998 9999 TypeSystemClang &ScratchTypeSystemClang::GetIsolatedAST( 10000 ScratchTypeSystemClang::IsolatedASTKind feature) { 10001 auto found_ast = m_isolated_asts.find(feature); 10002 if (found_ast != m_isolated_asts.end()) 10003 return *found_ast->second; 10004 10005 // Couldn't find the requested sub-AST, so create it now. 10006 std::shared_ptr<TypeSystemClang> new_ast_sp = 10007 std::make_shared<SpecializedScratchAST>(GetSpecializedASTName(feature), 10008 m_triple, CreateASTSource()); 10009 m_isolated_asts.insert({feature, new_ast_sp}); 10010 return *new_ast_sp; 10011 } 10012 10013 bool TypeSystemClang::IsForcefullyCompleted(lldb::opaque_compiler_type_t type) { 10014 if (type) { 10015 clang::QualType qual_type(GetQualType(type)); 10016 const clang::RecordType *record_type = 10017 llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr()); 10018 if (record_type) { 10019 const clang::RecordDecl *record_decl = record_type->getDecl(); 10020 assert(record_decl); 10021 ClangASTMetadata *metadata = GetMetadata(record_decl); 10022 if (metadata) 10023 return metadata->IsForcefullyCompleted(); 10024 } 10025 } 10026 return false; 10027 } 10028 10029 bool TypeSystemClang::SetDeclIsForcefullyCompleted(const clang::TagDecl *td) { 10030 if (td == nullptr) 10031 return false; 10032 ClangASTMetadata *metadata = GetMetadata(td); 10033 if (metadata == nullptr) 10034 return false; 10035 m_has_forcefully_completed_types = true; 10036 metadata->SetIsForcefullyCompleted(); 10037 return true; 10038 } 10039