1 //===-- AppleObjCDeclVendor.cpp -------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "AppleObjCDeclVendor.h"
11 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
12 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
13 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Target/Process.h"
16 #include "lldb/Target/Target.h"
17 #include "lldb/Utility/Log.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExternalASTSource.h"
23 using namespace lldb_private;
25 class lldb_private::AppleObjCExternalASTSource
26 : public clang::ExternalASTSource {
28 AppleObjCExternalASTSource(AppleObjCDeclVendor &decl_vendor)
29 : m_decl_vendor(decl_vendor) {}
31 bool FindExternalVisibleDeclsByName(const clang::DeclContext *decl_ctx,
32 clang::DeclarationName name) override {
34 Log *log(GetLogIfAllCategoriesSet(
35 LIBLLDB_LOG_EXPRESSIONS)); // FIXME - a more appropriate log channel?
39 "AppleObjCExternalASTSource::FindExternalVisibleDeclsByName"
40 " on (ASTContext*)%p Looking for %s in (%sDecl*)%p",
41 static_cast<void *>(&decl_ctx->getParentASTContext()),
42 name.getAsString().c_str(), decl_ctx->getDeclKindName(),
43 static_cast<const void *>(decl_ctx));
47 const clang::ObjCInterfaceDecl *interface_decl =
48 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
53 clang::ObjCInterfaceDecl *non_const_interface_decl =
54 const_cast<clang::ObjCInterfaceDecl *>(interface_decl);
56 if (!m_decl_vendor.FinishDecl(non_const_interface_decl))
59 clang::DeclContext::lookup_result result =
60 non_const_interface_decl->lookup(name);
62 return (result.size() != 0);
65 SetNoExternalVisibleDeclsForName(decl_ctx, name);
69 void CompleteType(clang::TagDecl *tag_decl) override {
71 Log *log(GetLogIfAllCategoriesSet(
72 LIBLLDB_LOG_EXPRESSIONS)); // FIXME - a more appropriate log channel?
75 "AppleObjCExternalASTSource::CompleteType on "
76 "(ASTContext*)%p Completing (TagDecl*)%p named %s",
77 static_cast<void *>(&tag_decl->getASTContext()),
78 static_cast<void *>(tag_decl), tag_decl->getName().str().c_str());
80 LLDB_LOG(log, " AOEAS::CT Before:\n{1}", ClangUtil::DumpDecl(tag_decl));
82 LLDB_LOG(log, " AOEAS::CT After:{1}", ClangUtil::DumpDecl(tag_decl));
87 void CompleteType(clang::ObjCInterfaceDecl *interface_decl) override {
89 Log *log(GetLogIfAllCategoriesSet(
90 LIBLLDB_LOG_EXPRESSIONS)); // FIXME - a more appropriate log channel?
94 "AppleObjCExternalASTSource::CompleteType on "
95 "(ASTContext*)%p Completing (ObjCInterfaceDecl*)%p named %s",
96 static_cast<void *>(&interface_decl->getASTContext()),
97 static_cast<void *>(interface_decl),
98 interface_decl->getName().str().c_str());
100 LLDB_LOGF(log, " AOEAS::CT Before:");
101 LLDB_LOG(log, " [CT] {0}", ClangUtil::DumpDecl(interface_decl));
104 m_decl_vendor.FinishDecl(interface_decl);
107 LLDB_LOGF(log, " [CT] After:");
108 LLDB_LOG(log, " [CT] {0}", ClangUtil::DumpDecl(interface_decl));
113 bool layoutRecordType(
114 const clang::RecordDecl *Record, uint64_t &Size, uint64_t &Alignment,
115 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &FieldOffsets,
116 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
118 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
119 &VirtualBaseOffsets) override {
123 void StartTranslationUnit(clang::ASTConsumer *Consumer) override {
124 clang::TranslationUnitDecl *translation_unit_decl =
125 m_decl_vendor.m_ast_ctx.getASTContext().getTranslationUnitDecl();
126 translation_unit_decl->setHasExternalVisibleStorage();
127 translation_unit_decl->setHasExternalLexicalStorage();
131 AppleObjCDeclVendor &m_decl_vendor;
134 AppleObjCDeclVendor::AppleObjCDeclVendor(ObjCLanguageRuntime &runtime)
135 : ClangDeclVendor(eAppleObjCDeclVendor), m_runtime(runtime),
137 "AppleObjCDeclVendor AST",
138 runtime.GetProcess()->GetTarget().GetArchitecture().GetTriple()),
139 m_type_realizer_sp(m_runtime.GetEncodingToType()) {
140 m_external_source = new AppleObjCExternalASTSource(*this);
141 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> external_source_owning_ptr(
143 m_ast_ctx.getASTContext().setExternalSource(external_source_owning_ptr);
146 clang::ObjCInterfaceDecl *
147 AppleObjCDeclVendor::GetDeclForISA(ObjCLanguageRuntime::ObjCISA isa) {
148 ISAToInterfaceMap::const_iterator iter = m_isa_to_interface.find(isa);
150 if (iter != m_isa_to_interface.end())
153 clang::ASTContext &ast_ctx = m_ast_ctx.getASTContext();
155 ObjCLanguageRuntime::ClassDescriptorSP descriptor =
156 m_runtime.GetClassDescriptorFromISA(isa);
161 ConstString name(descriptor->GetClassName());
163 clang::IdentifierInfo &identifier_info =
164 ast_ctx.Idents.get(name.GetStringRef());
166 clang::ObjCInterfaceDecl *new_iface_decl = clang::ObjCInterfaceDecl::Create(
167 ast_ctx, ast_ctx.getTranslationUnitDecl(), clang::SourceLocation(),
168 &identifier_info, nullptr, nullptr);
170 ClangASTMetadata meta_data;
171 meta_data.SetISAPtr(isa);
172 m_ast_ctx.SetMetadata(new_iface_decl, meta_data);
174 new_iface_decl->setHasExternalVisibleStorage();
175 new_iface_decl->setHasExternalLexicalStorage();
177 ast_ctx.getTranslationUnitDecl()->addDecl(new_iface_decl);
179 m_isa_to_interface[isa] = new_iface_decl;
181 return new_iface_decl;
184 class ObjCRuntimeMethodType {
186 ObjCRuntimeMethodType(const char *types) : m_is_valid(false) {
187 const char *cursor = types;
188 enum ParserState { Start = 0, InType, InPos } state = Start;
189 const char *type = nullptr;
192 uint32_t stepsLeft = 256;
195 if (--stepsLeft == 0) {
242 m_type_vector.push_back(std::string(type, (cursor - type)));
300 clang::ObjCMethodDecl *
301 BuildMethod(TypeSystemClang &clang_ast_ctxt,
302 clang::ObjCInterfaceDecl *interface_decl, const char *name,
304 ObjCLanguageRuntime::EncodingToTypeSP type_realizer_sp) {
305 if (!m_is_valid || m_type_vector.size() < 3)
308 clang::ASTContext &ast_ctx(interface_decl->getASTContext());
310 const bool isInstance = instance;
311 const bool isVariadic = false;
312 const bool isPropertyAccessor = false;
313 const bool isSynthesizedAccessorStub = false;
314 const bool isImplicitlyDeclared = true;
315 const bool isDefined = false;
316 const clang::ObjCMethodDecl::ImplementationControl impControl =
317 clang::ObjCMethodDecl::None;
318 const bool HasRelatedResultType = false;
319 const bool for_expression = true;
321 std::vector<clang::IdentifierInfo *> selector_components;
323 const char *name_cursor = name;
324 bool is_zero_argument = true;
326 while (*name_cursor != '\0') {
327 const char *colon_loc = strchr(name_cursor, ':');
329 selector_components.push_back(
330 &ast_ctx.Idents.get(llvm::StringRef(name_cursor)));
333 is_zero_argument = false;
334 selector_components.push_back(&ast_ctx.Idents.get(
335 llvm::StringRef(name_cursor, colon_loc - name_cursor)));
336 name_cursor = colon_loc + 1;
340 clang::IdentifierInfo **identifier_infos = selector_components.data();
341 if (!identifier_infos) {
345 clang::Selector sel = ast_ctx.Selectors.getSelector(
346 is_zero_argument ? 0 : selector_components.size(),
349 clang::QualType ret_type =
350 ClangUtil::GetQualType(type_realizer_sp->RealizeType(
351 clang_ast_ctxt, m_type_vector[0].c_str(), for_expression));
353 if (ret_type.isNull())
356 clang::ObjCMethodDecl *ret = clang::ObjCMethodDecl::Create(
357 ast_ctx, clang::SourceLocation(), clang::SourceLocation(), sel,
358 ret_type, nullptr, interface_decl, isInstance, isVariadic,
359 isPropertyAccessor, isSynthesizedAccessorStub, isImplicitlyDeclared,
360 isDefined, impControl, HasRelatedResultType);
362 std::vector<clang::ParmVarDecl *> parm_vars;
364 for (size_t ai = 3, ae = m_type_vector.size(); ai != ae; ++ai) {
365 const bool for_expression = true;
366 clang::QualType arg_type =
367 ClangUtil::GetQualType(type_realizer_sp->RealizeType(
368 clang_ast_ctxt, m_type_vector[ai].c_str(), for_expression));
370 if (arg_type.isNull())
371 return nullptr; // well, we just wasted a bunch of time. Wish we could
372 // delete the stuff we'd just made!
374 parm_vars.push_back(clang::ParmVarDecl::Create(
375 ast_ctx, ret, clang::SourceLocation(), clang::SourceLocation(),
376 nullptr, arg_type, nullptr, clang::SC_None, nullptr));
379 ret->setMethodParams(ast_ctx,
380 llvm::ArrayRef<clang::ParmVarDecl *>(parm_vars),
381 llvm::ArrayRef<clang::SourceLocation>());
386 explicit operator bool() { return m_is_valid; }
388 size_t GetNumTypes() { return m_type_vector.size(); }
390 const char *GetTypeAtIndex(size_t idx) { return m_type_vector[idx].c_str(); }
393 typedef std::vector<std::string> TypeVector;
395 TypeVector m_type_vector;
399 bool AppleObjCDeclVendor::FinishDecl(clang::ObjCInterfaceDecl *interface_decl) {
400 Log *log(GetLogIfAllCategoriesSet(
401 LIBLLDB_LOG_EXPRESSIONS)); // FIXME - a more appropriate log channel?
403 ClangASTMetadata *metadata = m_ast_ctx.GetMetadata(interface_decl);
404 ObjCLanguageRuntime::ObjCISA objc_isa = 0;
406 objc_isa = metadata->GetISAPtr();
411 if (!interface_decl->hasExternalVisibleStorage())
414 interface_decl->startDefinition();
416 interface_decl->setHasExternalVisibleStorage(false);
417 interface_decl->setHasExternalLexicalStorage(false);
419 ObjCLanguageRuntime::ClassDescriptorSP descriptor =
420 m_runtime.GetClassDescriptorFromISA(objc_isa);
425 auto superclass_func = [interface_decl,
426 this](ObjCLanguageRuntime::ObjCISA isa) {
427 clang::ObjCInterfaceDecl *superclass_decl = GetDeclForISA(isa);
429 if (!superclass_decl)
432 FinishDecl(superclass_decl);
433 clang::ASTContext &context = m_ast_ctx.getASTContext();
434 interface_decl->setSuperClass(context.getTrivialTypeSourceInfo(
435 context.getObjCInterfaceType(superclass_decl)));
438 auto instance_method_func =
439 [log, interface_decl, this](const char *name, const char *types) -> bool {
441 return false; // skip this one
443 ObjCRuntimeMethodType method_type(types);
445 clang::ObjCMethodDecl *method_decl = method_type.BuildMethod(
446 m_ast_ctx, interface_decl, name, true, m_type_realizer_sp);
448 LLDB_LOGF(log, "[ AOTV::FD] Instance method [%s] [%s]", name, types);
451 interface_decl->addDecl(method_decl);
456 auto class_method_func = [log, interface_decl,
457 this](const char *name, const char *types) -> bool {
459 return false; // skip this one
461 ObjCRuntimeMethodType method_type(types);
463 clang::ObjCMethodDecl *method_decl = method_type.BuildMethod(
464 m_ast_ctx, interface_decl, name, false, m_type_realizer_sp);
466 LLDB_LOGF(log, "[ AOTV::FD] Class method [%s] [%s]", name, types);
469 interface_decl->addDecl(method_decl);
474 auto ivar_func = [log, interface_decl,
475 this](const char *name, const char *type,
476 lldb::addr_t offset_ptr, uint64_t size) -> bool {
480 const bool for_expression = false;
483 "[ AOTV::FD] Instance variable [%s] [%s], offset at %" PRIx64,
484 name, type, offset_ptr);
486 CompilerType ivar_type = m_runtime.GetEncodingToType()->RealizeType(
487 m_ast_ctx, type, for_expression);
489 if (ivar_type.IsValid()) {
490 clang::TypeSourceInfo *const type_source_info = nullptr;
491 const bool is_synthesized = false;
492 clang::ObjCIvarDecl *ivar_decl = clang::ObjCIvarDecl::Create(
493 m_ast_ctx.getASTContext(), interface_decl, clang::SourceLocation(),
494 clang::SourceLocation(), &m_ast_ctx.getASTContext().Idents.get(name),
495 ClangUtil::GetQualType(ivar_type),
496 type_source_info, // TypeSourceInfo *
497 clang::ObjCIvarDecl::Public, nullptr, is_synthesized);
500 interface_decl->addDecl(ivar_decl);
508 "[AppleObjCDeclVendor::FinishDecl] Finishing Objective-C "
510 descriptor->GetClassName().AsCString());
512 if (!descriptor->Describe(superclass_func, instance_method_func,
513 class_method_func, ivar_func))
519 "[AppleObjCDeclVendor::FinishDecl] Finished Objective-C interface");
521 LLDB_LOG(log, " [AOTV::FD] {0}", ClangUtil::DumpDecl(interface_decl));
527 uint32_t AppleObjCDeclVendor::FindDecls(ConstString name, bool append,
528 uint32_t max_matches,
529 std::vector<CompilerDecl> &decls) {
531 Log *log(GetLogIfAllCategoriesSet(
532 LIBLLDB_LOG_EXPRESSIONS)); // FIXME - a more appropriate log channel?
534 LLDB_LOGF(log, "AppleObjCDeclVendor::FindDecls ('%s', %s, %u, )",
535 (const char *)name.AsCString(), append ? "true" : "false",
544 // See if the type is already in our ASTContext.
546 clang::ASTContext &ast_ctx = m_ast_ctx.getASTContext();
548 clang::IdentifierInfo &identifier_info =
549 ast_ctx.Idents.get(name.GetStringRef());
550 clang::DeclarationName decl_name =
551 ast_ctx.DeclarationNames.getIdentifier(&identifier_info);
553 clang::DeclContext::lookup_result lookup_result =
554 ast_ctx.getTranslationUnitDecl()->lookup(decl_name);
556 if (!lookup_result.empty()) {
557 if (clang::ObjCInterfaceDecl *result_iface_decl =
558 llvm::dyn_cast<clang::ObjCInterfaceDecl>(lookup_result[0])) {
560 clang::QualType result_iface_type =
561 ast_ctx.getObjCInterfaceType(result_iface_decl);
563 uint64_t isa_value = LLDB_INVALID_ADDRESS;
564 ClangASTMetadata *metadata = m_ast_ctx.GetMetadata(result_iface_decl);
566 isa_value = metadata->GetISAPtr();
569 "AOCTV::FT Found %s (isa 0x%" PRIx64 ") in the ASTContext",
570 result_iface_type.getAsString(), isa_value);
573 decls.push_back(m_ast_ctx.GetCompilerDecl(result_iface_decl));
577 LLDB_LOGF(log, "AOCTV::FT There's something in the ASTContext, but "
578 "it's not something we know about");
582 LLDB_LOGF(log, "AOCTV::FT Couldn't find %s in the ASTContext",
586 // It's not. If it exists, we have to put it into our ASTContext.
588 ObjCLanguageRuntime::ObjCISA isa = m_runtime.GetISA(name);
591 LLDB_LOGF(log, "AOCTV::FT Couldn't find the isa");
596 clang::ObjCInterfaceDecl *iface_decl = GetDeclForISA(isa);
600 "AOCTV::FT Couldn't get the Objective-C interface for "
608 clang::QualType new_iface_type = ast_ctx.getObjCInterfaceType(iface_decl);
610 LLDB_LOG(log, "AOCTV::FT Created {1} (isa 0x{2:x})",
611 new_iface_type.getAsString(), (uint64_t)isa);
614 decls.push_back(m_ast_ctx.GetCompilerDecl(iface_decl));