1 //===-- ClangASTSource.cpp ---------------------------------------*- C++-*-===//
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 "ClangASTSource.h"
11 #include "ClangDeclVendor.h"
12 #include "ClangModulesDeclVendor.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleList.h"
16 #include "lldb/Symbol/ClangASTContext.h"
17 #include "lldb/Symbol/ClangUtil.h"
18 #include "lldb/Symbol/CompilerDeclContext.h"
19 #include "lldb/Symbol/Function.h"
20 #include "lldb/Symbol/SymbolFile.h"
21 #include "lldb/Symbol/TaggedASTType.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Utility/Log.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/RecordLayout.h"
27 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
32 using namespace clang;
33 using namespace lldb_private;
35 // Scoped class that will remove an active lexical decl from the set when it
38 class ScopedLexicalDeclEraser {
40 ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls,
41 const clang::Decl *decl)
42 : m_active_lexical_decls(decls), m_decl(decl) {}
44 ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); }
47 std::set<const clang::Decl *> &m_active_lexical_decls;
48 const clang::Decl *m_decl;
52 ClangASTSource::ClangASTSource(const lldb::TargetSP &target,
53 const lldb::ClangASTImporterSP &importer)
54 : m_import_in_progress(false), m_lookups_enabled(false), m_target(target),
55 m_ast_context(nullptr), m_active_lexical_decls(), m_active_lookups() {
56 m_ast_importer_sp = importer;
59 void ClangASTSource::InstallASTContext(ClangASTContext &clang_ast_context) {
60 m_ast_context = &clang_ast_context.getASTContext();
61 m_clang_ast_context = &clang_ast_context;
62 m_file_manager = &m_ast_context->getSourceManager().getFileManager();
63 m_ast_importer_sp->InstallMapCompleter(m_ast_context, *this);
66 ClangASTSource::~ClangASTSource() {
67 if (!m_ast_importer_sp)
70 m_ast_importer_sp->ForgetDestination(m_ast_context);
74 // We are in the process of destruction, don't create clang ast context on
75 // demand by passing false to
76 // Target::GetScratchClangASTContext(create_on_demand).
77 ClangASTContext *scratch_clang_ast_context =
78 ClangASTContext::GetScratch(*m_target, false);
80 if (!scratch_clang_ast_context)
83 clang::ASTContext &scratch_ast_context =
84 scratch_clang_ast_context->getASTContext();
86 if (m_ast_context != &scratch_ast_context && m_ast_importer_sp)
87 m_ast_importer_sp->ForgetSource(&scratch_ast_context, m_ast_context);
90 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) {
94 m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
95 m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
98 // The core lookup interface.
99 bool ClangASTSource::FindExternalVisibleDeclsByName(
100 const DeclContext *decl_ctx, DeclarationName clang_decl_name) {
101 if (!m_ast_context) {
102 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
106 if (GetImportInProgress()) {
107 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
111 std::string decl_name(clang_decl_name.getAsString());
113 // if (m_decl_map.DoingASTImport ())
114 // return DeclContext::lookup_result();
116 switch (clang_decl_name.getNameKind()) {
117 // Normal identifiers.
118 case DeclarationName::Identifier: {
119 clang::IdentifierInfo *identifier_info =
120 clang_decl_name.getAsIdentifierInfo();
122 if (!identifier_info || identifier_info->getBuiltinID() != 0) {
123 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
129 case DeclarationName::CXXOperatorName:
130 case DeclarationName::CXXLiteralOperatorName:
133 // Using directives found in this context.
134 // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
135 case DeclarationName::CXXUsingDirective:
136 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
139 case DeclarationName::ObjCZeroArgSelector:
140 case DeclarationName::ObjCOneArgSelector:
141 case DeclarationName::ObjCMultiArgSelector: {
142 llvm::SmallVector<NamedDecl *, 1> method_decls;
144 NameSearchContext method_search_context(*this, method_decls,
145 clang_decl_name, decl_ctx);
147 FindObjCMethodDecls(method_search_context);
149 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
150 return (method_decls.size() > 0);
152 // These aren't possible in the global context.
153 case DeclarationName::CXXConstructorName:
154 case DeclarationName::CXXDestructorName:
155 case DeclarationName::CXXConversionFunctionName:
156 case DeclarationName::CXXDeductionGuideName:
157 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
161 if (!GetLookupsEnabled()) {
162 // Wait until we see a '$' at the start of a name before we start doing any
163 // lookups so we can avoid lookup up all of the builtin types.
164 if (!decl_name.empty() && decl_name[0] == '$') {
165 SetLookupsEnabled(true);
167 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
172 ConstString const_decl_name(decl_name.c_str());
174 const char *uniqued_const_decl_name = const_decl_name.GetCString();
175 if (m_active_lookups.find(uniqued_const_decl_name) !=
176 m_active_lookups.end()) {
177 // We are currently looking up this name...
178 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
181 m_active_lookups.insert(uniqued_const_decl_name);
182 // static uint32_t g_depth = 0;
184 // printf("[%5u] FindExternalVisibleDeclsByName() \"%s\"\n", g_depth,
185 // uniqued_const_decl_name);
186 llvm::SmallVector<NamedDecl *, 4> name_decls;
187 NameSearchContext name_search_context(*this, name_decls, clang_decl_name,
189 FindExternalVisibleDecls(name_search_context);
190 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
192 m_active_lookups.erase(uniqued_const_decl_name);
193 return (name_decls.size() != 0);
196 void ClangASTSource::CompleteType(TagDecl *tag_decl) {
197 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
199 static unsigned int invocation_id = 0;
200 unsigned int current_id = invocation_id++;
204 " CompleteTagDecl[%u] on (ASTContext*)%p Completing "
205 "(TagDecl*)%p named %s",
206 current_id, static_cast<void *>(m_ast_context),
207 static_cast<void *>(tag_decl), tag_decl->getName().str().c_str());
209 LLDB_LOG(log, " CTD[%u] Before:\n{0}", current_id,
210 ClangUtil::DumpDecl(tag_decl));
213 auto iter = m_active_lexical_decls.find(tag_decl);
214 if (iter != m_active_lexical_decls.end())
216 m_active_lexical_decls.insert(tag_decl);
217 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
219 if (!m_ast_importer_sp) {
223 if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) {
224 // We couldn't complete the type. Maybe there's a definition somewhere
225 // else that can be completed.
228 " CTD[%u] Type could not be completed in the module in "
229 "which it was first found.",
234 DeclContext *decl_ctx = tag_decl->getDeclContext();
236 if (const NamespaceDecl *namespace_context =
237 dyn_cast<NamespaceDecl>(decl_ctx)) {
238 ClangASTImporter::NamespaceMapSP namespace_map =
239 m_ast_importer_sp->GetNamespaceMap(namespace_context);
241 if (log && log->GetVerbose())
242 LLDB_LOGF(log, " CTD[%u] Inspecting namespace map %p (%d entries)",
243 current_id, static_cast<void *>(namespace_map.get()),
244 static_cast<int>(namespace_map->size()));
249 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
250 e = namespace_map->end();
251 i != e && !found; ++i) {
252 LLDB_LOGF(log, " CTD[%u] Searching namespace %s in module %s",
253 current_id, i->second.GetName().AsCString(),
254 i->first->GetFileSpec().GetFilename().GetCString());
258 ConstString name(tag_decl->getName().str().c_str());
260 i->first->FindTypesInNamespace(name, &i->second, UINT32_MAX, types);
262 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
263 lldb::TypeSP type = types.GetTypeAtIndex(ti);
268 CompilerType clang_type(type->GetFullCompilerType());
270 if (!ClangUtil::IsClangType(clang_type))
273 const TagType *tag_type =
274 ClangUtil::GetQualType(clang_type)->getAs<TagType>();
279 TagDecl *candidate_tag_decl =
280 const_cast<TagDecl *>(tag_type->getDecl());
282 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
290 ConstString name(tag_decl->getName().str().c_str());
292 const ModuleList &module_list = m_target->GetImages();
294 bool exact_match = false;
295 llvm::DenseSet<SymbolFile *> searched_symbol_files;
296 module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX,
297 searched_symbol_files, types);
299 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
300 lldb::TypeSP type = types.GetTypeAtIndex(ti);
305 CompilerType clang_type(type->GetFullCompilerType());
307 if (!ClangUtil::IsClangType(clang_type))
310 const TagType *tag_type =
311 ClangUtil::GetQualType(clang_type)->getAs<TagType>();
316 TagDecl *candidate_tag_decl =
317 const_cast<TagDecl *>(tag_type->getDecl());
319 // We have found a type by basename and we need to make sure the decl
320 // contexts are the same before we can try to complete this type with
322 if (!ClangASTContext::DeclsAreEquivalent(tag_decl, candidate_tag_decl))
325 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
332 LLDB_LOG(log, " [CTD] After:\n{0}", ClangUtil::DumpDecl(tag_decl));
335 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
336 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
339 " [CompleteObjCInterfaceDecl] on (ASTContext*)%p Completing "
340 "an ObjCInterfaceDecl named %s",
341 static_cast<void *>(m_ast_context),
342 interface_decl->getName().str().c_str());
343 LLDB_LOG(log, " [COID] Before:\n{0}",
344 ClangUtil::DumpDecl(interface_decl));
346 if (!m_ast_importer_sp) {
347 lldbassert(0 && "No mechanism for completing a type!");
351 ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
353 if (original.Valid()) {
354 if (ObjCInterfaceDecl *original_iface_decl =
355 dyn_cast<ObjCInterfaceDecl>(original.decl)) {
356 ObjCInterfaceDecl *complete_iface_decl =
357 GetCompleteObjCInterface(original_iface_decl);
359 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
360 m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
365 m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
367 if (interface_decl->getSuperClass() &&
368 interface_decl->getSuperClass() != interface_decl)
369 CompleteType(interface_decl->getSuperClass());
372 LLDB_LOGF(log, " [COID] After:");
373 LLDB_LOG(log, " [COID] {0}", ClangUtil::DumpDecl(interface_decl));
377 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
378 const clang::ObjCInterfaceDecl *interface_decl) {
379 lldb::ProcessSP process(m_target->GetProcessSP());
384 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
386 if (!language_runtime)
389 ConstString class_name(interface_decl->getNameAsString().c_str());
391 lldb::TypeSP complete_type_sp(
392 language_runtime->LookupInCompleteClassCache(class_name));
394 if (!complete_type_sp)
397 TypeFromUser complete_type =
398 TypeFromUser(complete_type_sp->GetFullCompilerType());
399 lldb::opaque_compiler_type_t complete_opaque_type =
400 complete_type.GetOpaqueQualType();
402 if (!complete_opaque_type)
405 const clang::Type *complete_clang_type =
406 QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
407 const ObjCInterfaceType *complete_interface_type =
408 dyn_cast<ObjCInterfaceType>(complete_clang_type);
410 if (!complete_interface_type)
413 ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
415 return complete_iface_decl;
418 void ClangASTSource::FindExternalLexicalDecls(
419 const DeclContext *decl_context,
420 llvm::function_ref<bool(Decl::Kind)> predicate,
421 llvm::SmallVectorImpl<Decl *> &decls) {
423 if (!m_ast_importer_sp)
426 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
428 const Decl *context_decl = dyn_cast<Decl>(decl_context);
433 auto iter = m_active_lexical_decls.find(context_decl);
434 if (iter != m_active_lexical_decls.end())
436 m_active_lexical_decls.insert(context_decl);
437 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
439 static unsigned int invocation_id = 0;
440 unsigned int current_id = invocation_id++;
443 if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
446 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in '%s' (%sDecl*)%p",
447 current_id, static_cast<void *>(m_ast_context),
448 context_named_decl->getNameAsString().c_str(),
449 context_decl->getDeclKindName(),
450 static_cast<const void *>(context_decl));
451 else if (context_decl)
453 log, "FindExternalLexicalDecls[%u] on (ASTContext*)%p in (%sDecl*)%p",
454 current_id, static_cast<void *>(m_ast_context),
455 context_decl->getDeclKindName(),
456 static_cast<const void *>(context_decl));
460 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in a NULL context",
461 current_id, static_cast<const void *>(m_ast_context));
464 ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(context_decl);
466 if (!original.Valid())
470 log, " FELD[{0}] Original decl (ASTContext*){1:x} (Decl*){2:x}:\n{3}",
471 current_id, static_cast<void *>(original.ctx),
472 static_cast<void *>(original.decl), ClangUtil::DumpDecl(original.decl));
474 if (ObjCInterfaceDecl *original_iface_decl =
475 dyn_cast<ObjCInterfaceDecl>(original.decl)) {
476 ObjCInterfaceDecl *complete_iface_decl =
477 GetCompleteObjCInterface(original_iface_decl);
479 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
480 original.decl = complete_iface_decl;
481 original.ctx = &complete_iface_decl->getASTContext();
483 m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
487 if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original.decl)) {
488 ExternalASTSource *external_source = original.ctx->getExternalSource();
491 external_source->CompleteType(original_tag_decl);
494 const DeclContext *original_decl_context =
495 dyn_cast<DeclContext>(original.decl);
497 if (!original_decl_context)
500 // Indicates whether we skipped any Decls of the original DeclContext.
501 bool SkippedDecls = false;
502 for (TagDecl::decl_iterator iter = original_decl_context->decls_begin();
503 iter != original_decl_context->decls_end(); ++iter) {
506 // The predicate function returns true if the passed declaration kind is
507 // the one we are looking for.
508 // See clang::ExternalASTSource::FindExternalLexicalDecls()
509 if (predicate(decl->getKind())) {
511 std::string ast_dump = ClangUtil::DumpDecl(decl);
512 if (const NamedDecl *context_named_decl =
513 dyn_cast<NamedDecl>(context_decl))
514 LLDB_LOGF(log, " FELD[%d] Adding [to %sDecl %s] lexical %sDecl %s",
515 current_id, context_named_decl->getDeclKindName(),
516 context_named_decl->getNameAsString().c_str(),
517 decl->getDeclKindName(), ast_dump.c_str());
519 LLDB_LOGF(log, " FELD[%d] Adding lexical %sDecl %s", current_id,
520 decl->getDeclKindName(), ast_dump.c_str());
523 Decl *copied_decl = CopyDecl(decl);
528 if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
529 QualType copied_field_type = copied_field->getType();
531 m_ast_importer_sp->RequireCompleteType(copied_field_type);
538 // CopyDecl may build a lookup table which may set up ExternalLexicalStorage
539 // to false. However, since we skipped some of the external Decls we must
542 decl_context->setHasExternalLexicalStorage(true);
543 // This sets HasLazyExternalLexicalLookups to true. By setting this bit we
544 // ensure that the lookup table is rebuilt, which means the external source
545 // is consulted again when a clang::DeclContext::lookup is called.
546 const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable();
552 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
553 assert(m_ast_context);
555 const ConstString name(context.m_decl_name.getAsString().c_str());
557 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
559 static unsigned int invocation_id = 0;
560 unsigned int current_id = invocation_id++;
563 if (!context.m_decl_context)
565 "ClangASTSource::FindExternalVisibleDecls[%u] on "
566 "(ASTContext*)%p for '%s' in a NULL DeclContext",
567 current_id, static_cast<void *>(m_ast_context),
569 else if (const NamedDecl *context_named_decl =
570 dyn_cast<NamedDecl>(context.m_decl_context))
572 "ClangASTSource::FindExternalVisibleDecls[%u] on "
573 "(ASTContext*)%p for '%s' in '%s'",
574 current_id, static_cast<void *>(m_ast_context),
576 context_named_decl->getNameAsString().c_str());
579 "ClangASTSource::FindExternalVisibleDecls[%u] on "
580 "(ASTContext*)%p for '%s' in a '%s'",
581 current_id, static_cast<void *>(m_ast_context),
582 name.GetCString(), context.m_decl_context->getDeclKindName());
585 context.m_namespace_map = std::make_shared<ClangASTImporter::NamespaceMap>();
587 if (const NamespaceDecl *namespace_context =
588 dyn_cast<NamespaceDecl>(context.m_decl_context)) {
589 ClangASTImporter::NamespaceMapSP namespace_map = m_ast_importer_sp ?
590 m_ast_importer_sp->GetNamespaceMap(namespace_context) : nullptr;
592 if (log && log->GetVerbose())
593 LLDB_LOGF(log, " CAS::FEVD[%u] Inspecting namespace map %p (%d entries)",
594 current_id, static_cast<void *>(namespace_map.get()),
595 static_cast<int>(namespace_map->size()));
600 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
601 e = namespace_map->end();
603 LLDB_LOGF(log, " CAS::FEVD[%u] Searching namespace %s in module %s",
604 current_id, i->second.GetName().AsCString(),
605 i->first->GetFileSpec().GetFilename().GetCString());
607 FindExternalVisibleDecls(context, i->first, i->second, current_id);
609 } else if (isa<ObjCInterfaceDecl>(context.m_decl_context)) {
610 FindObjCPropertyAndIvarDecls(context);
611 } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) {
612 // we shouldn't be getting FindExternalVisibleDecls calls for these
615 CompilerDeclContext namespace_decl;
617 LLDB_LOGF(log, " CAS::FEVD[%u] Searching the root namespace", current_id);
619 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl,
623 if (!context.m_namespace_map->empty()) {
624 if (log && log->GetVerbose())
626 " CAS::FEVD[%u] Registering namespace map %p (%d entries)",
627 current_id, static_cast<void *>(context.m_namespace_map.get()),
628 static_cast<int>(context.m_namespace_map->size()));
630 NamespaceDecl *clang_namespace_decl =
631 AddNamespace(context, context.m_namespace_map);
633 if (clang_namespace_decl)
634 clang_namespace_decl->setHasExternalVisibleStorage();
638 clang::Sema *ClangASTSource::getSema() {
639 return m_clang_ast_context->getSema();
642 bool ClangASTSource::IgnoreName(const ConstString name,
643 bool ignore_all_dollar_names) {
644 static const ConstString id_name("id");
645 static const ConstString Class_name("Class");
647 if (m_ast_context->getLangOpts().ObjC)
648 if (name == id_name || name == Class_name)
651 StringRef name_string_ref = name.GetStringRef();
653 // The ClangASTSource is not responsible for finding $-names.
654 return name_string_ref.empty() ||
655 (ignore_all_dollar_names && name_string_ref.startswith("$")) ||
656 name_string_ref.startswith("_$");
659 void ClangASTSource::FindExternalVisibleDecls(
660 NameSearchContext &context, lldb::ModuleSP module_sp,
661 CompilerDeclContext &namespace_decl, unsigned int current_id) {
662 assert(m_ast_context);
664 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
666 SymbolContextList sc_list;
668 const ConstString name(context.m_decl_name.getAsString().c_str());
669 if (IgnoreName(name, true))
675 if (module_sp && namespace_decl) {
676 CompilerDeclContext found_namespace_decl;
678 if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) {
679 found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl);
681 if (found_namespace_decl) {
682 context.m_namespace_map->push_back(
683 std::pair<lldb::ModuleSP, CompilerDeclContext>(
684 module_sp, found_namespace_decl));
686 LLDB_LOGF(log, " CAS::FEVD[%u] Found namespace %s in module %s",
687 current_id, name.GetCString(),
688 module_sp->GetFileSpec().GetFilename().GetCString());
692 const ModuleList &target_images = m_target->GetImages();
693 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
695 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
696 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
701 CompilerDeclContext found_namespace_decl;
703 SymbolFile *symbol_file = image->GetSymbolFile();
708 found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl);
710 if (found_namespace_decl) {
711 context.m_namespace_map->push_back(
712 std::pair<lldb::ModuleSP, CompilerDeclContext>(
713 image, found_namespace_decl));
715 LLDB_LOGF(log, " CAS::FEVD[%u] Found namespace %s in module %s",
716 current_id, name.GetCString(),
717 image->GetFileSpec().GetFilename().GetCString());
723 if (context.m_found.type)
727 const bool exact_match = true;
728 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
729 if (module_sp && namespace_decl)
730 module_sp->FindTypesInNamespace(name, &namespace_decl, 1, types);
732 m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1,
733 searched_symbol_files, types);
736 if (size_t num_types = types.GetSize()) {
737 for (size_t ti = 0; ti < num_types; ++ti) {
738 lldb::TypeSP type_sp = types.GetTypeAtIndex(ti);
741 const char *name_string = type_sp->GetName().GetCString();
743 LLDB_LOGF(log, " CAS::FEVD[%u] Matching type found for \"%s\": %s",
744 current_id, name.GetCString(),
745 (name_string ? name_string : "<anonymous>"));
748 CompilerType full_type = type_sp->GetFullCompilerType();
750 CompilerType copied_clang_type(GuardedCopyType(full_type));
752 if (!copied_clang_type) {
753 LLDB_LOGF(log, " CAS::FEVD[%u] - Couldn't export a type",
759 context.AddTypeDecl(copied_clang_type);
761 context.m_found.type = true;
766 if (!context.m_found.type) {
767 // Try the modules next.
770 if (ClangModulesDeclVendor *modules_decl_vendor =
771 m_target->GetClangModulesDeclVendor()) {
773 uint32_t max_matches = 1;
774 std::vector<clang::NamedDecl *> decls;
776 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
781 " CAS::FEVD[%u] Matching entity found for \"%s\" in "
783 current_id, name.GetCString());
786 clang::NamedDecl *const decl_from_modules = decls[0];
788 if (llvm::isa<clang::TypeDecl>(decl_from_modules) ||
789 llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) ||
790 llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) {
791 clang::Decl *copied_decl = CopyDecl(decl_from_modules);
792 clang::NamedDecl *copied_named_decl =
793 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
795 if (!copied_named_decl) {
798 " CAS::FEVD[%u] - Couldn't export a type from the modules",
804 context.AddNamedDecl(copied_named_decl);
806 context.m_found.type = true;
812 if (!context.m_found.type) {
814 // Couldn't find any types elsewhere. Try the Objective-C runtime if
817 lldb::ProcessSP process(m_target->GetProcessSP());
822 ObjCLanguageRuntime *language_runtime(
823 ObjCLanguageRuntime::Get(*process));
825 if (!language_runtime)
828 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
834 uint32_t max_matches = 1;
835 std::vector<clang::NamedDecl *> decls;
837 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
838 if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls))
844 " CAS::FEVD[%u] Matching type found for \"%s\" in the runtime",
845 current_id, name.GetCString());
848 clang::Decl *copied_decl = CopyDecl(decls[0]);
849 clang::NamedDecl *copied_named_decl =
850 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
852 if (!copied_named_decl) {
854 " CAS::FEVD[%u] - Couldn't export a type from the runtime",
860 context.AddNamedDecl(copied_named_decl);
867 template <class D> class TaggedASTDecl {
869 TaggedASTDecl() : decl(nullptr) {}
870 TaggedASTDecl(D *_decl) : decl(_decl) {}
871 bool IsValid() const { return (decl != nullptr); }
872 bool IsInvalid() const { return !IsValid(); }
873 D *operator->() const { return decl; }
877 template <class D2, template <class D> class TD, class D1>
878 TD<D2> DynCast(TD<D1> source) {
879 return TD<D2>(dyn_cast<D2>(source.decl));
882 template <class D = Decl> class DeclFromParser;
883 template <class D = Decl> class DeclFromUser;
885 template <class D> class DeclFromParser : public TaggedASTDecl<D> {
887 DeclFromParser() : TaggedASTDecl<D>() {}
888 DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
890 DeclFromUser<D> GetOrigin(ClangASTSource &source);
893 template <class D> class DeclFromUser : public TaggedASTDecl<D> {
895 DeclFromUser() : TaggedASTDecl<D>() {}
896 DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
898 DeclFromParser<D> Import(ClangASTSource &source);
902 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) {
903 ClangASTImporter::DeclOrigin origin = source.GetDeclOrigin(this->decl);
905 return DeclFromUser<D>();
906 return DeclFromUser<D>(dyn_cast<D>(origin.decl));
910 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) {
911 DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl));
912 if (parser_generic_decl.IsInvalid())
913 return DeclFromParser<D>();
914 return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl));
917 bool ClangASTSource::FindObjCMethodDeclsWithOrigin(
918 unsigned int current_id, NameSearchContext &context,
919 ObjCInterfaceDecl *original_interface_decl, const char *log_info) {
920 const DeclarationName &decl_name(context.m_decl_name);
921 clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
923 Selector original_selector;
925 if (decl_name.isObjCZeroArgSelector()) {
926 IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
927 original_selector = original_ctx->Selectors.getSelector(0, &ident);
928 } else if (decl_name.isObjCOneArgSelector()) {
929 const std::string &decl_name_string = decl_name.getAsString();
930 std::string decl_name_string_without_colon(decl_name_string.c_str(),
931 decl_name_string.length() - 1);
932 IdentifierInfo *ident =
933 &original_ctx->Idents.get(decl_name_string_without_colon);
934 original_selector = original_ctx->Selectors.getSelector(1, &ident);
936 SmallVector<IdentifierInfo *, 4> idents;
938 clang::Selector sel = decl_name.getObjCSelector();
940 unsigned num_args = sel.getNumArgs();
942 for (unsigned i = 0; i != num_args; ++i) {
943 idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
947 original_ctx->Selectors.getSelector(num_args, idents.data());
950 DeclarationName original_decl_name(original_selector);
952 llvm::SmallVector<NamedDecl *, 1> methods;
954 ClangASTContext::GetCompleteDecl(original_ctx, original_interface_decl);
956 if (ObjCMethodDecl *instance_method_decl =
957 original_interface_decl->lookupInstanceMethod(original_selector)) {
958 methods.push_back(instance_method_decl);
959 } else if (ObjCMethodDecl *class_method_decl =
960 original_interface_decl->lookupClassMethod(
961 original_selector)) {
962 methods.push_back(class_method_decl);
965 if (methods.empty()) {
969 for (NamedDecl *named_decl : methods) {
973 ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
978 Decl *copied_decl = CopyDecl(result_method);
983 ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
985 if (!copied_method_decl)
988 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
990 LLDB_LOG(log, " CAS::FOMD[{0}] found ({1}) {2}", current_id, log_info,
991 ClangUtil::DumpDecl(copied_method_decl));
993 context.AddNamedDecl(copied_method_decl);
999 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
1000 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1002 static unsigned int invocation_id = 0;
1003 unsigned int current_id = invocation_id++;
1005 const DeclarationName &decl_name(context.m_decl_name);
1006 const DeclContext *decl_ctx(context.m_decl_context);
1008 const ObjCInterfaceDecl *interface_decl =
1009 dyn_cast<ObjCInterfaceDecl>(decl_ctx);
1011 if (!interface_decl)
1015 ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
1017 if (!original.Valid())
1020 ObjCInterfaceDecl *original_interface_decl =
1021 dyn_cast<ObjCInterfaceDecl>(original.decl);
1023 if (FindObjCMethodDeclsWithOrigin(current_id, context,
1024 original_interface_decl, "at origin"))
1025 return; // found it, no need to look any further
1030 if (decl_name.isObjCZeroArgSelector()) {
1031 ss.Printf("%s", decl_name.getAsString().c_str());
1032 } else if (decl_name.isObjCOneArgSelector()) {
1033 ss.Printf("%s", decl_name.getAsString().c_str());
1035 clang::Selector sel = decl_name.getObjCSelector();
1037 for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) {
1038 llvm::StringRef r = sel.getNameForSlot(i);
1039 ss.Printf("%s:", r.str().c_str());
1044 if (ss.GetString().contains("$__lldb"))
1045 return; // we don't need any results
1047 ConstString selector_name(ss.GetString());
1050 "ClangASTSource::FindObjCMethodDecls[%d] on (ASTContext*)%p "
1051 "for selector [%s %s]",
1052 current_id, static_cast<void *>(m_ast_context),
1053 interface_decl->getNameAsString().c_str(),
1054 selector_name.AsCString());
1055 SymbolContextList sc_list;
1057 const bool include_symbols = false;
1058 const bool include_inlines = false;
1060 std::string interface_name = interface_decl->getNameAsString();
1064 ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString());
1066 ConstString instance_method_name(ms.GetString());
1069 m_target->GetImages().FindFunctions(
1070 instance_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1071 include_inlines, sc_list);
1073 if (sc_list.GetSize())
1077 ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString());
1079 ConstString class_method_name(ms.GetString());
1082 m_target->GetImages().FindFunctions(
1083 class_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1084 include_inlines, sc_list);
1086 if (sc_list.GetSize())
1089 // Fall back and check for methods in categories. If we find methods this
1090 // way, we need to check that they're actually in categories on the desired
1093 SymbolContextList candidate_sc_list;
1095 m_target->GetImages().FindFunctions(
1096 selector_name, lldb::eFunctionNameTypeSelector, include_symbols,
1097 include_inlines, candidate_sc_list);
1099 for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) {
1100 SymbolContext candidate_sc;
1102 if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc))
1105 if (!candidate_sc.function)
1108 const char *candidate_name = candidate_sc.function->GetName().AsCString();
1110 const char *cursor = candidate_name;
1112 if (*cursor != '+' && *cursor != '-')
1122 size_t interface_len = interface_name.length();
1124 if (strncmp(cursor, interface_name.c_str(), interface_len))
1127 cursor += interface_len;
1129 if (*cursor == ' ' || *cursor == '(')
1130 sc_list.Append(candidate_sc);
1134 if (sc_list.GetSize()) {
1135 // We found a good function symbol. Use that.
1137 for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) {
1140 if (!sc_list.GetContextAtIndex(i, sc))
1146 CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext();
1147 if (!function_decl_ctx)
1150 ObjCMethodDecl *method_decl =
1151 ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1156 ObjCInterfaceDecl *found_interface_decl =
1157 method_decl->getClassInterface();
1159 if (!found_interface_decl)
1162 if (found_interface_decl->getName() == interface_decl->getName()) {
1163 Decl *copied_decl = CopyDecl(method_decl);
1168 ObjCMethodDecl *copied_method_decl =
1169 dyn_cast<ObjCMethodDecl>(copied_decl);
1171 if (!copied_method_decl)
1174 LLDB_LOG(log, " CAS::FOMD[{0}] found (in symbols)\n{1}", current_id,
1175 ClangUtil::DumpDecl(copied_method_decl));
1177 context.AddNamedDecl(copied_method_decl);
1184 // Try the debug information.
1187 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1188 const_cast<ObjCInterfaceDecl *>(interface_decl));
1190 if (!complete_interface_decl)
1193 // We found the complete interface. The runtime never needs to be queried
1194 // in this scenario.
1196 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1197 complete_interface_decl);
1199 if (complete_interface_decl == interface_decl)
1200 break; // already checked this one
1203 "CAS::FOPD[%d] trying origin "
1204 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1205 current_id, static_cast<void *>(complete_interface_decl),
1206 static_cast<void *>(&complete_iface_decl->getASTContext()));
1208 FindObjCMethodDeclsWithOrigin(current_id, context, complete_interface_decl,
1215 // Check the modules only if the debug information didn't have a complete
1218 if (ClangModulesDeclVendor *modules_decl_vendor =
1219 m_target->GetClangModulesDeclVendor()) {
1220 ConstString interface_name(interface_decl->getNameAsString().c_str());
1221 bool append = false;
1222 uint32_t max_matches = 1;
1223 std::vector<clang::NamedDecl *> decls;
1225 if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches,
1229 ObjCInterfaceDecl *interface_decl_from_modules =
1230 dyn_cast<ObjCInterfaceDecl>(decls[0]);
1232 if (!interface_decl_from_modules)
1235 if (FindObjCMethodDeclsWithOrigin(
1236 current_id, context, interface_decl_from_modules, "in modules"))
1242 // Check the runtime only if the debug information didn't have a complete
1243 // interface and the modules don't get us anywhere.
1245 lldb::ProcessSP process(m_target->GetProcessSP());
1250 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1252 if (!language_runtime)
1255 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1260 ConstString interface_name(interface_decl->getNameAsString().c_str());
1261 bool append = false;
1262 uint32_t max_matches = 1;
1263 std::vector<clang::NamedDecl *> decls;
1265 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1266 if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches,
1270 ObjCInterfaceDecl *runtime_interface_decl =
1271 dyn_cast<ObjCInterfaceDecl>(decls[0]);
1273 if (!runtime_interface_decl)
1276 FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl,
1281 static bool FindObjCPropertyAndIvarDeclsWithOrigin(
1282 unsigned int current_id, NameSearchContext &context, ClangASTSource &source,
1283 DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) {
1284 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1286 if (origin_iface_decl.IsInvalid())
1289 std::string name_str = context.m_decl_name.getAsString();
1290 StringRef name(name_str);
1291 IdentifierInfo &name_identifier(
1292 origin_iface_decl->getASTContext().Idents.get(name));
1294 DeclFromUser<ObjCPropertyDecl> origin_property_decl(
1295 origin_iface_decl->FindPropertyDeclaration(
1296 &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance));
1300 if (origin_property_decl.IsValid()) {
1301 DeclFromParser<ObjCPropertyDecl> parser_property_decl(
1302 origin_property_decl.Import(source));
1303 if (parser_property_decl.IsValid()) {
1304 LLDB_LOG(log, " CAS::FOPD[{0}] found\n{1}", current_id,
1305 ClangUtil::DumpDecl(parser_property_decl.decl));
1307 context.AddNamedDecl(parser_property_decl.decl);
1312 DeclFromUser<ObjCIvarDecl> origin_ivar_decl(
1313 origin_iface_decl->getIvarDecl(&name_identifier));
1315 if (origin_ivar_decl.IsValid()) {
1316 DeclFromParser<ObjCIvarDecl> parser_ivar_decl(
1317 origin_ivar_decl.Import(source));
1318 if (parser_ivar_decl.IsValid()) {
1320 LLDB_LOG(log, " CAS::FOPD[{0}] found\n{1}", current_id,
1321 ClangUtil::DumpDecl(parser_ivar_decl.decl));
1324 context.AddNamedDecl(parser_ivar_decl.decl);
1332 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) {
1333 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1335 static unsigned int invocation_id = 0;
1336 unsigned int current_id = invocation_id++;
1338 DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl(
1339 cast<ObjCInterfaceDecl>(context.m_decl_context));
1340 DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl(
1341 parser_iface_decl.GetOrigin(*this));
1343 ConstString class_name(parser_iface_decl->getNameAsString().c_str());
1346 "ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on "
1347 "(ASTContext*)%p for '%s.%s'",
1348 current_id, static_cast<void *>(m_ast_context),
1349 parser_iface_decl->getNameAsString().c_str(),
1350 context.m_decl_name.getAsString().c_str());
1352 if (FindObjCPropertyAndIvarDeclsWithOrigin(
1353 current_id, context, *this, origin_iface_decl))
1357 "CAS::FOPD[%d] couldn't find the property on origin "
1358 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching "
1360 current_id, static_cast<const void *>(origin_iface_decl.decl),
1361 static_cast<void *>(&origin_iface_decl->getASTContext()));
1363 SymbolContext null_sc;
1367 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1368 const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl));
1370 if (!complete_interface_decl)
1373 // We found the complete interface. The runtime never needs to be queried
1374 // in this scenario.
1376 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1377 complete_interface_decl);
1379 if (complete_iface_decl.decl == origin_iface_decl.decl)
1380 break; // already checked this one
1383 "CAS::FOPD[%d] trying origin "
1384 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1385 current_id, static_cast<const void *>(complete_iface_decl.decl),
1386 static_cast<void *>(&complete_iface_decl->getASTContext()));
1388 FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1389 complete_iface_decl);
1395 // Check the modules only if the debug information didn't have a complete
1398 ClangModulesDeclVendor *modules_decl_vendor =
1399 m_target->GetClangModulesDeclVendor();
1401 if (!modules_decl_vendor)
1404 bool append = false;
1405 uint32_t max_matches = 1;
1406 std::vector<clang::NamedDecl *> decls;
1408 if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1411 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules(
1412 dyn_cast<ObjCInterfaceDecl>(decls[0]));
1414 if (!interface_decl_from_modules.IsValid())
1419 "CAS::FOPD[%d] trying module "
1420 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1421 current_id, static_cast<const void *>(interface_decl_from_modules.decl),
1422 static_cast<void *>(&interface_decl_from_modules->getASTContext()));
1424 if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1425 interface_decl_from_modules))
1430 // Check the runtime only if the debug information didn't have a complete
1431 // interface and nothing was in the modules.
1433 lldb::ProcessSP process(m_target->GetProcessSP());
1438 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1440 if (!language_runtime)
1443 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1448 bool append = false;
1449 uint32_t max_matches = 1;
1450 std::vector<clang::NamedDecl *> decls;
1452 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1453 if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1456 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime(
1457 dyn_cast<ObjCInterfaceDecl>(decls[0]));
1459 if (!interface_decl_from_runtime.IsValid())
1464 "CAS::FOPD[%d] trying runtime "
1465 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1466 current_id, static_cast<const void *>(interface_decl_from_runtime.decl),
1467 static_cast<void *>(&interface_decl_from_runtime->getASTContext()));
1469 if (FindObjCPropertyAndIvarDeclsWithOrigin(
1470 current_id, context, *this, interface_decl_from_runtime))
1475 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap;
1476 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap;
1478 template <class D, class O>
1479 static bool ImportOffsetMap(llvm::DenseMap<const D *, O> &destination_map,
1480 llvm::DenseMap<const D *, O> &source_map,
1481 ClangASTSource &source) {
1482 // When importing fields into a new record, clang has a hard requirement that
1483 // fields be imported in field offset order. Since they are stored in a
1484 // DenseMap with a pointer as the key type, this means we cannot simply
1485 // iterate over the map, as the order will be non-deterministic. Instead we
1486 // have to sort by the offset and then insert in sorted order.
1487 typedef llvm::DenseMap<const D *, O> MapType;
1488 typedef typename MapType::value_type PairType;
1489 std::vector<PairType> sorted_items;
1490 sorted_items.reserve(source_map.size());
1491 sorted_items.assign(source_map.begin(), source_map.end());
1492 llvm::sort(sorted_items.begin(), sorted_items.end(),
1493 [](const PairType &lhs, const PairType &rhs) {
1494 return lhs.second < rhs.second;
1497 for (const auto &item : sorted_items) {
1498 DeclFromUser<D> user_decl(const_cast<D *>(item.first));
1499 DeclFromParser<D> parser_decl(user_decl.Import(source));
1500 if (parser_decl.IsInvalid())
1502 destination_map.insert(
1503 std::pair<const D *, O>(parser_decl.decl, item.second));
1509 template <bool IsVirtual>
1510 bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
1511 DeclFromUser<const CXXRecordDecl> &record,
1512 BaseOffsetMap &base_offsets) {
1513 for (CXXRecordDecl::base_class_const_iterator
1514 bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
1515 be = (IsVirtual ? record->vbases_end() : record->bases_end());
1517 if (!IsVirtual && bi->isVirtual())
1520 const clang::Type *origin_base_type = bi->getType().getTypePtr();
1521 const clang::RecordType *origin_base_record_type =
1522 origin_base_type->getAs<RecordType>();
1524 if (!origin_base_record_type)
1527 DeclFromUser<RecordDecl> origin_base_record(
1528 origin_base_record_type->getDecl());
1530 if (origin_base_record.IsInvalid())
1533 DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
1534 DynCast<CXXRecordDecl>(origin_base_record));
1536 if (origin_base_cxx_record.IsInvalid())
1539 CharUnits base_offset;
1543 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
1546 record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
1548 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
1549 origin_base_cxx_record.decl, base_offset));
1555 bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size,
1556 uint64_t &alignment,
1557 FieldOffsetMap &field_offsets,
1558 BaseOffsetMap &base_offsets,
1559 BaseOffsetMap &virtual_base_offsets) {
1560 static unsigned int invocation_id = 0;
1561 unsigned int current_id = invocation_id++;
1563 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1566 "LayoutRecordType[%u] on (ASTContext*)%p for (RecordDecl*)%p "
1568 current_id, static_cast<void *>(m_ast_context),
1569 static_cast<const void *>(record),
1570 record->getNameAsString().c_str());
1572 DeclFromParser<const RecordDecl> parser_record(record);
1573 DeclFromUser<const RecordDecl> origin_record(
1574 parser_record.GetOrigin(*this));
1576 if (origin_record.IsInvalid())
1579 FieldOffsetMap origin_field_offsets;
1580 BaseOffsetMap origin_base_offsets;
1581 BaseOffsetMap origin_virtual_base_offsets;
1583 ClangASTContext::GetCompleteDecl(
1584 &origin_record->getASTContext(),
1585 const_cast<RecordDecl *>(origin_record.decl));
1587 clang::RecordDecl *definition = origin_record.decl->getDefinition();
1588 if (!definition || !definition->isCompleteDefinition())
1591 const ASTRecordLayout &record_layout(
1592 origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
1594 int field_idx = 0, field_count = record_layout.getFieldCount();
1596 for (RecordDecl::field_iterator fi = origin_record->field_begin(),
1597 fe = origin_record->field_end();
1599 if (field_idx >= field_count)
1600 return false; // Layout didn't go well. Bail out.
1602 uint64_t field_offset = record_layout.getFieldOffset(field_idx);
1604 origin_field_offsets.insert(
1605 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
1610 lldbassert(&record->getASTContext() == m_ast_context);
1612 DeclFromUser<const CXXRecordDecl> origin_cxx_record(
1613 DynCast<const CXXRecordDecl>(origin_record));
1615 if (origin_cxx_record.IsValid()) {
1616 if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
1617 origin_base_offsets) ||
1618 !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
1619 origin_virtual_base_offsets))
1623 if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) ||
1624 !ImportOffsetMap(base_offsets, origin_base_offsets, *this) ||
1625 !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets,
1629 size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth();
1630 alignment = record_layout.getAlignment().getQuantity() *
1631 m_ast_context->getCharWidth();
1634 LLDB_LOGF(log, "LRT[%u] returned:", current_id);
1635 LLDB_LOGF(log, "LRT[%u] Original = (RecordDecl*)%p", current_id,
1636 static_cast<const void *>(origin_record.decl));
1637 LLDB_LOGF(log, "LRT[%u] Size = %" PRId64, current_id, size);
1638 LLDB_LOGF(log, "LRT[%u] Alignment = %" PRId64, current_id, alignment);
1639 LLDB_LOGF(log, "LRT[%u] Fields:", current_id);
1640 for (RecordDecl::field_iterator fi = record->field_begin(),
1641 fe = record->field_end();
1644 "LRT[%u] (FieldDecl*)%p, Name = '%s', Offset = %" PRId64
1646 current_id, static_cast<void *>(*fi),
1647 fi->getNameAsString().c_str(), field_offsets[*fi]);
1649 DeclFromParser<const CXXRecordDecl> parser_cxx_record =
1650 DynCast<const CXXRecordDecl>(parser_record);
1651 if (parser_cxx_record.IsValid()) {
1652 LLDB_LOGF(log, "LRT[%u] Bases:", current_id);
1653 for (CXXRecordDecl::base_class_const_iterator
1654 bi = parser_cxx_record->bases_begin(),
1655 be = parser_cxx_record->bases_end();
1657 bool is_virtual = bi->isVirtual();
1659 QualType base_type = bi->getType();
1660 const RecordType *base_record_type = base_type->getAs<RecordType>();
1661 DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
1662 DeclFromParser<CXXRecordDecl> base_cxx_record =
1663 DynCast<CXXRecordDecl>(base_record);
1667 "LRT[%u] %s(CXXRecordDecl*)%p, Name = '%s', Offset = %" PRId64
1669 current_id, (is_virtual ? "Virtual " : ""),
1670 static_cast<void *>(base_cxx_record.decl),
1671 base_cxx_record.decl->getNameAsString().c_str(),
1673 ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1674 : base_offsets[base_cxx_record.decl].getQuantity()));
1677 LLDB_LOGF(log, "LRD[%u] Not a CXXRecord, so no bases", current_id);
1684 void ClangASTSource::CompleteNamespaceMap(
1685 ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name,
1686 ClangASTImporter::NamespaceMapSP &parent_map) const {
1687 static unsigned int invocation_id = 0;
1688 unsigned int current_id = invocation_id++;
1690 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1693 if (parent_map && parent_map->size())
1695 "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1696 "namespace %s in namespace %s",
1697 current_id, static_cast<void *>(m_ast_context),
1699 parent_map->begin()->second.GetName().AsCString());
1702 "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1704 current_id, static_cast<void *>(m_ast_context),
1709 for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1710 e = parent_map->end();
1712 CompilerDeclContext found_namespace_decl;
1714 lldb::ModuleSP module_sp = i->first;
1715 CompilerDeclContext module_parent_namespace_decl = i->second;
1717 SymbolFile *symbol_file = module_sp->GetSymbolFile();
1722 found_namespace_decl =
1723 symbol_file->FindNamespace(name, &module_parent_namespace_decl);
1725 if (!found_namespace_decl)
1728 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1729 module_sp, found_namespace_decl));
1731 LLDB_LOGF(log, " CMN[%u] Found namespace %s in module %s", current_id,
1733 module_sp->GetFileSpec().GetFilename().GetCString());
1736 const ModuleList &target_images = m_target->GetImages();
1737 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
1739 CompilerDeclContext null_namespace_decl;
1741 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
1742 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
1747 CompilerDeclContext found_namespace_decl;
1749 SymbolFile *symbol_file = image->GetSymbolFile();
1754 found_namespace_decl =
1755 symbol_file->FindNamespace(name, &null_namespace_decl);
1757 if (!found_namespace_decl)
1760 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1761 image, found_namespace_decl));
1763 LLDB_LOGF(log, " CMN[%u] Found namespace %s in module %s", current_id,
1765 image->GetFileSpec().GetFilename().GetCString());
1770 NamespaceDecl *ClangASTSource::AddNamespace(
1771 NameSearchContext &context,
1772 ClangASTImporter::NamespaceMapSP &namespace_decls) {
1773 if (!namespace_decls)
1776 const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1778 clang::ASTContext *src_ast =
1779 ClangASTContext::DeclContextGetClangASTContext(namespace_decl);
1782 clang::NamespaceDecl *src_namespace_decl =
1783 ClangASTContext::DeclContextGetAsNamespaceDecl(namespace_decl);
1785 if (!src_namespace_decl)
1788 Decl *copied_decl = CopyDecl(src_namespace_decl);
1793 NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1795 if (!copied_namespace_decl)
1798 context.m_decls.push_back(copied_namespace_decl);
1800 m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1803 return dyn_cast<NamespaceDecl>(copied_decl);
1806 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) {
1807 if (m_ast_importer_sp) {
1808 return m_ast_importer_sp->CopyDecl(m_ast_context, src_decl);
1810 lldbassert(0 && "No mechanism for copying a decl!");
1815 ClangASTImporter::DeclOrigin ClangASTSource::GetDeclOrigin(const clang::Decl *decl) {
1816 if (m_ast_importer_sp) {
1817 return m_ast_importer_sp->GetDeclOrigin(decl);
1819 // this can happen early enough that no ExternalASTSource is installed.
1820 return ClangASTImporter::DeclOrigin();
1824 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) {
1825 ClangASTContext *src_ast =
1826 llvm::dyn_cast_or_null<ClangASTContext>(src_type.GetTypeSystem());
1827 if (src_ast == nullptr)
1828 return CompilerType();
1830 SetImportInProgress(true);
1832 QualType copied_qual_type;
1834 if (m_ast_importer_sp) {
1835 copied_qual_type = ClangUtil::GetQualType(
1836 m_ast_importer_sp->CopyType(*m_clang_ast_context, src_type));
1838 lldbassert(0 && "No mechanism for copying a type!");
1839 return CompilerType();
1842 SetImportInProgress(false);
1844 if (copied_qual_type.getAsOpaquePtr() &&
1845 copied_qual_type->getCanonicalTypeInternal().isNull())
1846 // this shouldn't happen, but we're hardening because the AST importer
1847 // seems to be generating bad types on occasion.
1848 return CompilerType();
1850 return m_clang_ast_context->GetType(copied_qual_type);
1853 clang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) {
1854 assert(type && "Type for variable must be valid!");
1856 if (!type.IsValid())
1859 ClangASTContext *lldb_ast =
1860 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
1864 IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo();
1866 clang::ASTContext &ast = lldb_ast->getASTContext();
1868 clang::NamedDecl *Decl = VarDecl::Create(
1869 ast, const_cast<DeclContext *>(m_decl_context), SourceLocation(),
1870 SourceLocation(), ii, ClangUtil::GetQualType(type), nullptr, SC_Static);
1871 m_decls.push_back(Decl);
1876 clang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type,
1878 assert(type && "Type for variable must be valid!");
1880 if (!type.IsValid())
1883 if (m_function_types.count(type))
1886 ClangASTContext *lldb_ast =
1887 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
1891 m_function_types.insert(type);
1893 QualType qual_type(ClangUtil::GetQualType(type));
1895 clang::ASTContext &ast = lldb_ast->getASTContext();
1897 const bool isInlineSpecified = false;
1898 const bool hasWrittenPrototype = true;
1899 const bool isConstexprSpecified = false;
1901 clang::DeclContext *context = const_cast<DeclContext *>(m_decl_context);
1904 context = LinkageSpecDecl::Create(
1905 ast, context, SourceLocation(), SourceLocation(),
1906 clang::LinkageSpecDecl::LanguageIDs::lang_c, false);
1909 // Pass the identifier info for functions the decl_name is needed for
1911 clang::DeclarationName decl_name =
1912 m_decl_name.getNameKind() == DeclarationName::Identifier
1913 ? m_decl_name.getAsIdentifierInfo()
1916 clang::FunctionDecl *func_decl = FunctionDecl::Create(
1917 ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type,
1918 nullptr, SC_Extern, isInlineSpecified, hasWrittenPrototype,
1919 isConstexprSpecified ? CSK_constexpr : CSK_unspecified);
1921 // We have to do more than just synthesize the FunctionDecl. We have to
1922 // synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do
1923 // this, we raid the function's FunctionProtoType for types.
1925 const FunctionProtoType *func_proto_type =
1926 qual_type.getTypePtr()->getAs<FunctionProtoType>();
1928 if (func_proto_type) {
1929 unsigned NumArgs = func_proto_type->getNumParams();
1932 SmallVector<ParmVarDecl *, 5> parm_var_decls;
1934 for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) {
1935 QualType arg_qual_type(func_proto_type->getParamType(ArgIndex));
1937 parm_var_decls.push_back(
1938 ParmVarDecl::Create(ast, const_cast<DeclContext *>(context),
1939 SourceLocation(), SourceLocation(), nullptr,
1940 arg_qual_type, nullptr, SC_Static, nullptr));
1943 func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls));
1945 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1947 LLDB_LOGF(log, "Function type wasn't a FunctionProtoType");
1950 // If this is an operator (e.g. operator new or operator==), only insert the
1951 // declaration we inferred from the symbol if we can provide the correct
1952 // number of arguments. We shouldn't really inject random decl(s) for
1953 // functions that are analyzed semantically in a special way, otherwise we
1954 // will crash in clang.
1955 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
1956 if (func_proto_type &&
1957 ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) {
1958 if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
1959 false, op_kind, func_proto_type->getNumParams()))
1962 m_decls.push_back(func_decl);
1967 clang::NamedDecl *NameSearchContext::AddGenericFunDecl() {
1968 FunctionProtoType::ExtProtoInfo proto_info;
1970 proto_info.Variadic = true;
1972 QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType(
1973 m_ast_source.m_ast_context->UnknownAnyTy, // result
1974 ArrayRef<QualType>(), // argument types
1978 m_ast_source.m_clang_ast_context->GetType(generic_function_type), true);
1982 NameSearchContext::AddTypeDecl(const CompilerType &clang_type) {
1983 if (ClangUtil::IsClangType(clang_type)) {
1984 QualType qual_type = ClangUtil::GetQualType(clang_type);
1986 if (const TypedefType *typedef_type =
1987 llvm::dyn_cast<TypedefType>(qual_type)) {
1988 TypedefNameDecl *typedef_name_decl = typedef_type->getDecl();
1990 m_decls.push_back(typedef_name_decl);
1992 return (NamedDecl *)typedef_name_decl;
1993 } else if (const TagType *tag_type = qual_type->getAs<TagType>()) {
1994 TagDecl *tag_decl = tag_type->getDecl();
1996 m_decls.push_back(tag_decl);
1999 } else if (const ObjCObjectType *objc_object_type =
2000 qual_type->getAs<ObjCObjectType>()) {
2001 ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface();
2003 m_decls.push_back((NamedDecl *)interface_decl);
2005 return (NamedDecl *)interface_decl;
2011 void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) {
2012 for (clang::NamedDecl *decl : result)
2013 m_decls.push_back(decl);
2016 void NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) {
2017 m_decls.push_back(decl);