1 //===-- ClangASTSource.cpp ---------------------------------------*- C++-*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ClangASTSource.h"
12 #include "ASTDumper.h"
13 #include "ClangModulesDeclVendor.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleList.h"
17 #include "lldb/Symbol/ClangASTContext.h"
18 #include "lldb/Symbol/ClangUtil.h"
19 #include "lldb/Symbol/CompilerDeclContext.h"
20 #include "lldb/Symbol/Function.h"
21 #include "lldb/Symbol/SymbolFile.h"
22 #include "lldb/Symbol/SymbolVendor.h"
23 #include "lldb/Symbol/TaggedASTType.h"
24 #include "lldb/Target/ObjCLanguageRuntime.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Utility/Log.h"
27 #include "clang/AST/ASTContext.h"
28 #include "clang/AST/RecordLayout.h"
32 using namespace clang;
33 using namespace lldb_private;
35 //------------------------------------------------------------------
36 // Scoped class that will remove an active lexical decl from the set when it
38 //------------------------------------------------------------------
40 class ScopedLexicalDeclEraser {
42 ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls,
43 const clang::Decl *decl)
44 : m_active_lexical_decls(decls), m_decl(decl) {}
46 ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); }
49 std::set<const clang::Decl *> &m_active_lexical_decls;
50 const clang::Decl *m_decl;
54 ClangASTSource::ClangASTSource(const lldb::TargetSP &target)
55 : m_import_in_progress(false), m_lookups_enabled(false), m_target(target),
56 m_ast_context(NULL), m_active_lexical_decls(), m_active_lookups() {
57 if (!target->GetUseModernTypeLookup()) {
58 m_ast_importer_sp = m_target->GetClangASTImporter();
62 void ClangASTSource::InstallASTContext(clang::ASTContext &ast_context,
63 clang::FileManager &file_manager,
64 bool is_shared_context) {
65 m_ast_context = &ast_context;
66 m_file_manager = &file_manager;
67 if (m_target->GetUseModernTypeLookup()) {
68 // Configure the ExternalASTMerger. The merger needs to be able to import
69 // types from any source that we would do lookups in, which includes the
70 // persistent AST context as well as the modules and Objective-C runtime
73 lldbassert(!m_merger_up);
74 clang::ExternalASTMerger::ImporterTarget target = {ast_context,
76 std::vector<clang::ExternalASTMerger::ImporterSource> sources;
77 for (lldb::ModuleSP module_sp : m_target->GetImages().Modules()) {
78 if (auto *module_ast_ctx = llvm::cast_or_null<ClangASTContext>(
79 module_sp->GetTypeSystemForLanguage(lldb::eLanguageTypeC))) {
80 lldbassert(module_ast_ctx->getASTContext());
81 lldbassert(module_ast_ctx->getFileManager());
82 sources.push_back({*module_ast_ctx->getASTContext(),
83 *module_ast_ctx->getFileManager(),
84 module_ast_ctx->GetOriginMap()
90 lldb::ProcessSP process(m_target->GetProcessSP());
95 ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
97 if (!language_runtime)
100 DeclVendor *runtime_decl_vendor = language_runtime->GetDeclVendor();
102 if (!runtime_decl_vendor)
105 sources.push_back(runtime_decl_vendor->GetImporterSource());
109 DeclVendor *modules_decl_vendor =
110 m_target->GetClangModulesDeclVendor();
112 if (!modules_decl_vendor)
115 sources.push_back(modules_decl_vendor->GetImporterSource());
118 if (!is_shared_context) {
119 // Update the scratch AST context's merger to reflect any new sources we
120 // might have come across since the last time an expression was parsed.
122 auto scratch_ast_context = static_cast<ClangASTContextForExpressions*>(
123 m_target->GetScratchClangASTContext());
125 scratch_ast_context->GetMergerUnchecked().AddSources(sources);
127 sources.push_back({*scratch_ast_context->getASTContext(),
128 *scratch_ast_context->getFileManager(),
129 scratch_ast_context->GetOriginMap()});
133 llvm::make_unique<clang::ExternalASTMerger>(target, sources);
135 m_ast_importer_sp->InstallMapCompleter(&ast_context, *this);
139 ClangASTSource::~ClangASTSource() {
140 if (m_ast_importer_sp)
141 m_ast_importer_sp->ForgetDestination(m_ast_context);
143 // We are in the process of destruction, don't create clang ast context on
144 // demand by passing false to
145 // Target::GetScratchClangASTContext(create_on_demand).
146 ClangASTContext *scratch_clang_ast_context =
147 m_target->GetScratchClangASTContext(false);
149 if (!scratch_clang_ast_context)
152 clang::ASTContext *scratch_ast_context =
153 scratch_clang_ast_context->getASTContext();
155 if (!scratch_ast_context)
158 if (m_ast_context != scratch_ast_context && m_ast_importer_sp)
159 m_ast_importer_sp->ForgetSource(scratch_ast_context, m_ast_context);
162 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) {
166 m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
167 m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
170 // The core lookup interface.
171 bool ClangASTSource::FindExternalVisibleDeclsByName(
172 const DeclContext *decl_ctx, DeclarationName clang_decl_name) {
173 if (!m_ast_context) {
174 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
178 if (GetImportInProgress()) {
179 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
183 std::string decl_name(clang_decl_name.getAsString());
185 // if (m_decl_map.DoingASTImport ())
186 // return DeclContext::lookup_result();
188 switch (clang_decl_name.getNameKind()) {
189 // Normal identifiers.
190 case DeclarationName::Identifier: {
191 clang::IdentifierInfo *identifier_info =
192 clang_decl_name.getAsIdentifierInfo();
194 if (!identifier_info || identifier_info->getBuiltinID() != 0) {
195 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
201 case DeclarationName::CXXOperatorName:
202 case DeclarationName::CXXLiteralOperatorName:
205 // Using directives found in this context.
206 // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
207 case DeclarationName::CXXUsingDirective:
208 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
211 case DeclarationName::ObjCZeroArgSelector:
212 case DeclarationName::ObjCOneArgSelector:
213 case DeclarationName::ObjCMultiArgSelector: {
214 llvm::SmallVector<NamedDecl *, 1> method_decls;
216 NameSearchContext method_search_context(*this, method_decls,
217 clang_decl_name, decl_ctx);
219 FindObjCMethodDecls(method_search_context);
221 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
222 return (method_decls.size() > 0);
224 // These aren't possible in the global context.
225 case DeclarationName::CXXConstructorName:
226 case DeclarationName::CXXDestructorName:
227 case DeclarationName::CXXConversionFunctionName:
228 case DeclarationName::CXXDeductionGuideName:
229 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
233 if (!GetLookupsEnabled()) {
234 // Wait until we see a '$' at the start of a name before we start doing any
235 // lookups so we can avoid lookup up all of the builtin types.
236 if (!decl_name.empty() && decl_name[0] == '$') {
237 SetLookupsEnabled(true);
239 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
244 ConstString const_decl_name(decl_name.c_str());
246 const char *uniqued_const_decl_name = const_decl_name.GetCString();
247 if (m_active_lookups.find(uniqued_const_decl_name) !=
248 m_active_lookups.end()) {
249 // We are currently looking up this name...
250 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
253 m_active_lookups.insert(uniqued_const_decl_name);
254 // static uint32_t g_depth = 0;
256 // printf("[%5u] FindExternalVisibleDeclsByName() \"%s\"\n", g_depth,
257 // uniqued_const_decl_name);
258 llvm::SmallVector<NamedDecl *, 4> name_decls;
259 NameSearchContext name_search_context(*this, name_decls, clang_decl_name,
261 FindExternalVisibleDecls(name_search_context);
262 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
264 m_active_lookups.erase(uniqued_const_decl_name);
265 return (name_decls.size() != 0);
268 void ClangASTSource::CompleteType(TagDecl *tag_decl) {
269 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
271 static unsigned int invocation_id = 0;
272 unsigned int current_id = invocation_id++;
275 log->Printf(" CompleteTagDecl[%u] on (ASTContext*)%p Completing "
276 "(TagDecl*)%p named %s",
277 current_id, static_cast<void *>(m_ast_context),
278 static_cast<void *>(tag_decl),
279 tag_decl->getName().str().c_str());
281 log->Printf(" CTD[%u] Before:", current_id);
282 ASTDumper dumper((Decl *)tag_decl);
283 dumper.ToLog(log, " [CTD] ");
286 auto iter = m_active_lexical_decls.find(tag_decl);
287 if (iter != m_active_lexical_decls.end())
289 m_active_lexical_decls.insert(tag_decl);
290 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
292 if (!m_ast_importer_sp) {
294 GetMergerUnchecked().CompleteType(tag_decl);
299 if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) {
300 // We couldn't complete the type. Maybe there's a definition somewhere
301 // else that can be completed.
304 log->Printf(" CTD[%u] Type could not be completed in the module in "
305 "which it was first found.",
310 DeclContext *decl_ctx = tag_decl->getDeclContext();
312 if (const NamespaceDecl *namespace_context =
313 dyn_cast<NamespaceDecl>(decl_ctx)) {
314 ClangASTImporter::NamespaceMapSP namespace_map =
315 m_ast_importer_sp->GetNamespaceMap(namespace_context);
317 if (log && log->GetVerbose())
318 log->Printf(" CTD[%u] Inspecting namespace map %p (%d entries)",
319 current_id, static_cast<void *>(namespace_map.get()),
320 static_cast<int>(namespace_map->size()));
325 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
326 e = namespace_map->end();
327 i != e && !found; ++i) {
329 log->Printf(" CTD[%u] Searching namespace %s in module %s",
330 current_id, i->second.GetName().AsCString(),
331 i->first->GetFileSpec().GetFilename().GetCString());
335 ConstString name(tag_decl->getName().str().c_str());
337 i->first->FindTypesInNamespace(name, &i->second, UINT32_MAX, types);
339 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
340 lldb::TypeSP type = types.GetTypeAtIndex(ti);
345 CompilerType clang_type(type->GetFullCompilerType());
347 if (!ClangUtil::IsClangType(clang_type))
350 const TagType *tag_type =
351 ClangUtil::GetQualType(clang_type)->getAs<TagType>();
356 TagDecl *candidate_tag_decl =
357 const_cast<TagDecl *>(tag_type->getDecl());
359 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
367 ConstString name(tag_decl->getName().str().c_str());
368 CompilerDeclContext namespace_decl;
370 const ModuleList &module_list = m_target->GetImages();
372 bool exact_match = false;
373 llvm::DenseSet<SymbolFile *> searched_symbol_files;
374 module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX,
375 searched_symbol_files, types);
377 for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
378 lldb::TypeSP type = types.GetTypeAtIndex(ti);
383 CompilerType clang_type(type->GetFullCompilerType());
385 if (!ClangUtil::IsClangType(clang_type))
388 const TagType *tag_type =
389 ClangUtil::GetQualType(clang_type)->getAs<TagType>();
394 TagDecl *candidate_tag_decl =
395 const_cast<TagDecl *>(tag_type->getDecl());
397 // We have found a type by basename and we need to make sure the decl
398 // contexts are the same before we can try to complete this type with
400 if (!ClangASTContext::DeclsAreEquivalent(tag_decl, candidate_tag_decl))
403 if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
411 log->Printf(" [CTD] After:");
412 ASTDumper dumper((Decl *)tag_decl);
413 dumper.ToLog(log, " [CTD] ");
417 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
418 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
421 log->Printf(" [CompleteObjCInterfaceDecl] on (ASTContext*)%p Completing "
422 "an ObjCInterfaceDecl named %s",
423 static_cast<void *>(m_ast_context),
424 interface_decl->getName().str().c_str());
425 log->Printf(" [COID] Before:");
426 ASTDumper dumper((Decl *)interface_decl);
427 dumper.ToLog(log, " [COID] ");
430 if (!m_ast_importer_sp) {
432 ObjCInterfaceDecl *complete_iface_decl =
433 GetCompleteObjCInterface(interface_decl);
435 if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
436 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()});
439 GetMergerUnchecked().CompleteType(interface_decl);
441 lldbassert(0 && "No mechanism for completing a type!");
446 Decl *original_decl = NULL;
447 ASTContext *original_ctx = NULL;
449 if (m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl,
451 if (ObjCInterfaceDecl *original_iface_decl =
452 dyn_cast<ObjCInterfaceDecl>(original_decl)) {
453 ObjCInterfaceDecl *complete_iface_decl =
454 GetCompleteObjCInterface(original_iface_decl);
456 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
457 m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
462 m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
464 if (interface_decl->getSuperClass() &&
465 interface_decl->getSuperClass() != interface_decl)
466 CompleteType(interface_decl->getSuperClass());
469 log->Printf(" [COID] After:");
470 ASTDumper dumper((Decl *)interface_decl);
471 dumper.ToLog(log, " [COID] ");
475 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
476 const clang::ObjCInterfaceDecl *interface_decl) {
477 lldb::ProcessSP process(m_target->GetProcessSP());
482 ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
484 if (!language_runtime)
487 ConstString class_name(interface_decl->getNameAsString().c_str());
489 lldb::TypeSP complete_type_sp(
490 language_runtime->LookupInCompleteClassCache(class_name));
492 if (!complete_type_sp)
495 TypeFromUser complete_type =
496 TypeFromUser(complete_type_sp->GetFullCompilerType());
497 lldb::opaque_compiler_type_t complete_opaque_type =
498 complete_type.GetOpaqueQualType();
500 if (!complete_opaque_type)
503 const clang::Type *complete_clang_type =
504 QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
505 const ObjCInterfaceType *complete_interface_type =
506 dyn_cast<ObjCInterfaceType>(complete_clang_type);
508 if (!complete_interface_type)
511 ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
513 return complete_iface_decl;
516 void ClangASTSource::FindExternalLexicalDecls(
517 const DeclContext *decl_context,
518 llvm::function_ref<bool(Decl::Kind)> predicate,
519 llvm::SmallVectorImpl<Decl *> &decls) {
522 if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(decl_context)) {
523 ObjCInterfaceDecl *complete_iface_decl =
524 GetCompleteObjCInterface(interface_decl);
526 if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
527 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()});
530 return GetMergerUnchecked().FindExternalLexicalDecls(decl_context,
533 } else if (!m_ast_importer_sp)
536 ClangASTMetrics::RegisterLexicalQuery();
538 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
540 const Decl *context_decl = dyn_cast<Decl>(decl_context);
545 auto iter = m_active_lexical_decls.find(context_decl);
546 if (iter != m_active_lexical_decls.end())
548 m_active_lexical_decls.insert(context_decl);
549 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
551 static unsigned int invocation_id = 0;
552 unsigned int current_id = invocation_id++;
555 if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
557 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in '%s' (%sDecl*)%p",
558 current_id, static_cast<void *>(m_ast_context),
559 context_named_decl->getNameAsString().c_str(),
560 context_decl->getDeclKindName(),
561 static_cast<const void *>(context_decl));
562 else if (context_decl)
564 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in (%sDecl*)%p",
565 current_id, static_cast<void *>(m_ast_context),
566 context_decl->getDeclKindName(),
567 static_cast<const void *>(context_decl));
570 "FindExternalLexicalDecls[%u] on (ASTContext*)%p in a NULL context",
571 current_id, static_cast<const void *>(m_ast_context));
574 Decl *original_decl = NULL;
575 ASTContext *original_ctx = NULL;
577 if (!m_ast_importer_sp->ResolveDeclOrigin(context_decl, &original_decl,
582 log->Printf(" FELD[%u] Original decl (ASTContext*)%p (Decl*)%p:",
583 current_id, static_cast<void *>(original_ctx),
584 static_cast<void *>(original_decl));
585 ASTDumper(original_decl).ToLog(log, " ");
588 if (ObjCInterfaceDecl *original_iface_decl =
589 dyn_cast<ObjCInterfaceDecl>(original_decl)) {
590 ObjCInterfaceDecl *complete_iface_decl =
591 GetCompleteObjCInterface(original_iface_decl);
593 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
594 original_decl = complete_iface_decl;
595 original_ctx = &complete_iface_decl->getASTContext();
597 m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
601 if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {
602 ExternalASTSource *external_source = original_ctx->getExternalSource();
605 external_source->CompleteType(original_tag_decl);
608 const DeclContext *original_decl_context =
609 dyn_cast<DeclContext>(original_decl);
611 if (!original_decl_context)
614 for (TagDecl::decl_iterator iter = original_decl_context->decls_begin();
615 iter != original_decl_context->decls_end(); ++iter) {
618 if (predicate(decl->getKind())) {
620 ASTDumper ast_dumper(decl);
621 if (const NamedDecl *context_named_decl =
622 dyn_cast<NamedDecl>(context_decl))
623 log->Printf(" FELD[%d] Adding [to %sDecl %s] lexical %sDecl %s",
624 current_id, context_named_decl->getDeclKindName(),
625 context_named_decl->getNameAsString().c_str(),
626 decl->getDeclKindName(), ast_dumper.GetCString());
628 log->Printf(" FELD[%d] Adding lexical %sDecl %s", current_id,
629 decl->getDeclKindName(), ast_dumper.GetCString());
632 Decl *copied_decl = CopyDecl(decl);
637 if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
638 QualType copied_field_type = copied_field->getType();
640 m_ast_importer_sp->RequireCompleteType(copied_field_type);
643 DeclContext *decl_context_non_const =
644 const_cast<DeclContext *>(decl_context);
646 if (copied_decl->getDeclContext() != decl_context) {
647 if (copied_decl->getDeclContext()->containsDecl(copied_decl))
648 copied_decl->getDeclContext()->removeDecl(copied_decl);
649 copied_decl->setDeclContext(decl_context_non_const);
652 if (!decl_context_non_const->containsDecl(copied_decl))
653 decl_context_non_const->addDeclInternal(copied_decl);
660 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
661 assert(m_ast_context);
663 ClangASTMetrics::RegisterVisibleQuery();
665 const ConstString name(context.m_decl_name.getAsString().c_str());
667 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
669 static unsigned int invocation_id = 0;
670 unsigned int current_id = invocation_id++;
673 if (!context.m_decl_context)
674 log->Printf("ClangASTSource::FindExternalVisibleDecls[%u] on "
675 "(ASTContext*)%p for '%s' in a NULL DeclContext",
676 current_id, static_cast<void *>(m_ast_context),
678 else if (const NamedDecl *context_named_decl =
679 dyn_cast<NamedDecl>(context.m_decl_context))
680 log->Printf("ClangASTSource::FindExternalVisibleDecls[%u] on "
681 "(ASTContext*)%p for '%s' in '%s'",
682 current_id, static_cast<void *>(m_ast_context),
684 context_named_decl->getNameAsString().c_str());
686 log->Printf("ClangASTSource::FindExternalVisibleDecls[%u] on "
687 "(ASTContext*)%p for '%s' in a '%s'",
688 current_id, static_cast<void *>(m_ast_context),
689 name.GetCString(), context.m_decl_context->getDeclKindName());
692 if (HasMerger() && !isa<TranslationUnitDecl>(context.m_decl_context)
693 /* possibly handle NamespaceDecls here? */) {
694 if (auto *interface_decl =
695 dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) {
696 ObjCInterfaceDecl *complete_iface_decl =
697 GetCompleteObjCInterface(interface_decl);
699 if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
700 GetMergerUnchecked().ForceRecordOrigin(
702 {complete_iface_decl, &complete_iface_decl->getASTContext()});
706 GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context,
707 context.m_decl_name);
708 return; // otherwise we may need to fall back
711 context.m_namespace_map.reset(new ClangASTImporter::NamespaceMap);
713 if (const NamespaceDecl *namespace_context =
714 dyn_cast<NamespaceDecl>(context.m_decl_context)) {
715 ClangASTImporter::NamespaceMapSP namespace_map = m_ast_importer_sp ?
716 m_ast_importer_sp->GetNamespaceMap(namespace_context) : nullptr;
718 if (log && log->GetVerbose())
719 log->Printf(" CAS::FEVD[%u] Inspecting namespace map %p (%d entries)",
720 current_id, static_cast<void *>(namespace_map.get()),
721 static_cast<int>(namespace_map->size()));
726 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
727 e = namespace_map->end();
730 log->Printf(" CAS::FEVD[%u] Searching namespace %s in module %s",
731 current_id, i->second.GetName().AsCString(),
732 i->first->GetFileSpec().GetFilename().GetCString());
734 FindExternalVisibleDecls(context, i->first, i->second, current_id);
736 } else if (isa<ObjCInterfaceDecl>(context.m_decl_context) && !HasMerger()) {
737 FindObjCPropertyAndIvarDecls(context);
738 } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) {
739 // we shouldn't be getting FindExternalVisibleDecls calls for these
742 CompilerDeclContext namespace_decl;
745 log->Printf(" CAS::FEVD[%u] Searching the root namespace", current_id);
747 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl,
751 if (!context.m_namespace_map->empty()) {
752 if (log && log->GetVerbose())
753 log->Printf(" CAS::FEVD[%u] Registering namespace map %p (%d entries)",
755 static_cast<void *>(context.m_namespace_map.get()),
756 static_cast<int>(context.m_namespace_map->size()));
758 NamespaceDecl *clang_namespace_decl =
759 AddNamespace(context, context.m_namespace_map);
761 if (clang_namespace_decl)
762 clang_namespace_decl->setHasExternalVisibleStorage();
766 bool ClangASTSource::IgnoreName(const ConstString name,
767 bool ignore_all_dollar_names) {
768 static const ConstString id_name("id");
769 static const ConstString Class_name("Class");
771 if (m_ast_context->getLangOpts().ObjC)
772 if (name == id_name || name == Class_name)
775 StringRef name_string_ref = name.GetStringRef();
777 // The ClangASTSource is not responsible for finding $-names.
778 return name_string_ref.empty() ||
779 (ignore_all_dollar_names && name_string_ref.startswith("$")) ||
780 name_string_ref.startswith("_$");
783 void ClangASTSource::FindExternalVisibleDecls(
784 NameSearchContext &context, lldb::ModuleSP module_sp,
785 CompilerDeclContext &namespace_decl, unsigned int current_id) {
786 assert(m_ast_context);
788 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
790 SymbolContextList sc_list;
792 const ConstString name(context.m_decl_name.getAsString().c_str());
793 if (IgnoreName(name, true))
796 if (module_sp && namespace_decl) {
797 CompilerDeclContext found_namespace_decl;
799 SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor();
802 found_namespace_decl =
803 symbol_vendor->FindNamespace(name, &namespace_decl);
805 if (found_namespace_decl) {
806 context.m_namespace_map->push_back(
807 std::pair<lldb::ModuleSP, CompilerDeclContext>(
808 module_sp, found_namespace_decl));
811 log->Printf(" CAS::FEVD[%u] Found namespace %s in module %s",
812 current_id, name.GetCString(),
813 module_sp->GetFileSpec().GetFilename().GetCString());
816 } else if (!HasMerger()) {
817 const ModuleList &target_images = m_target->GetImages();
818 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
820 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
821 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
826 CompilerDeclContext found_namespace_decl;
828 SymbolVendor *symbol_vendor = image->GetSymbolVendor();
833 found_namespace_decl =
834 symbol_vendor->FindNamespace(name, &namespace_decl);
836 if (found_namespace_decl) {
837 context.m_namespace_map->push_back(
838 std::pair<lldb::ModuleSP, CompilerDeclContext>(
839 image, found_namespace_decl));
842 log->Printf(" CAS::FEVD[%u] Found namespace %s in module %s",
843 current_id, name.GetCString(),
844 image->GetFileSpec().GetFilename().GetCString());
850 if (context.m_found.type)
854 const bool exact_match = true;
855 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
856 if (module_sp && namespace_decl)
857 module_sp->FindTypesInNamespace(name, &namespace_decl, 1, types);
859 m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1,
860 searched_symbol_files, types);
863 if (size_t num_types = types.GetSize()) {
864 for (size_t ti = 0; ti < num_types; ++ti) {
865 lldb::TypeSP type_sp = types.GetTypeAtIndex(ti);
868 const char *name_string = type_sp->GetName().GetCString();
870 log->Printf(" CAS::FEVD[%u] Matching type found for \"%s\": %s",
871 current_id, name.GetCString(),
872 (name_string ? name_string : "<anonymous>"));
875 CompilerType full_type = type_sp->GetFullCompilerType();
877 CompilerType copied_clang_type(GuardedCopyType(full_type));
879 if (!copied_clang_type) {
881 log->Printf(" CAS::FEVD[%u] - Couldn't export a type", current_id);
886 context.AddTypeDecl(copied_clang_type);
888 context.m_found.type = true;
893 if (!context.m_found.type) {
894 // Try the modules next.
897 if (ClangModulesDeclVendor *modules_decl_vendor =
898 m_target->GetClangModulesDeclVendor()) {
900 uint32_t max_matches = 1;
901 std::vector<clang::NamedDecl *> decls;
903 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
907 log->Printf(" CAS::FEVD[%u] Matching entity found for \"%s\" in "
909 current_id, name.GetCString());
912 clang::NamedDecl *const decl_from_modules = decls[0];
914 if (llvm::isa<clang::TypeDecl>(decl_from_modules) ||
915 llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) ||
916 llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) {
917 clang::Decl *copied_decl = CopyDecl(decl_from_modules);
918 clang::NamedDecl *copied_named_decl =
919 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
921 if (!copied_named_decl) {
924 " CAS::FEVD[%u] - Couldn't export a type from the modules",
930 context.AddNamedDecl(copied_named_decl);
932 context.m_found.type = true;
938 if (!context.m_found.type) {
940 // Couldn't find any types elsewhere. Try the Objective-C runtime if
943 lldb::ProcessSP process(m_target->GetProcessSP());
948 ObjCLanguageRuntime *language_runtime(
949 process->GetObjCLanguageRuntime());
951 if (!language_runtime)
954 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
960 uint32_t max_matches = 1;
961 std::vector<clang::NamedDecl *> decls;
963 if (!decl_vendor->FindDecls(name, append, max_matches, decls))
968 " CAS::FEVD[%u] Matching type found for \"%s\" in the runtime",
969 current_id, name.GetCString());
972 clang::Decl *copied_decl = CopyDecl(decls[0]);
973 clang::NamedDecl *copied_named_decl =
974 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
976 if (!copied_named_decl) {
979 " CAS::FEVD[%u] - Couldn't export a type from the runtime",
985 context.AddNamedDecl(copied_named_decl);
992 template <class D> class TaggedASTDecl {
994 TaggedASTDecl() : decl(NULL) {}
995 TaggedASTDecl(D *_decl) : decl(_decl) {}
996 bool IsValid() const { return (decl != NULL); }
997 bool IsInvalid() const { return !IsValid(); }
998 D *operator->() const { return decl; }
1002 template <class D2, template <class D> class TD, class D1>
1003 TD<D2> DynCast(TD<D1> source) {
1004 return TD<D2>(dyn_cast<D2>(source.decl));
1007 template <class D = Decl> class DeclFromParser;
1008 template <class D = Decl> class DeclFromUser;
1010 template <class D> class DeclFromParser : public TaggedASTDecl<D> {
1012 DeclFromParser() : TaggedASTDecl<D>() {}
1013 DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
1015 DeclFromUser<D> GetOrigin(ClangASTSource &source);
1018 template <class D> class DeclFromUser : public TaggedASTDecl<D> {
1020 DeclFromUser() : TaggedASTDecl<D>() {}
1021 DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
1023 DeclFromParser<D> Import(ClangASTSource &source);
1027 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) {
1028 DeclFromUser<> origin_decl;
1029 source.ResolveDeclOrigin(this->decl, &origin_decl.decl, NULL);
1030 if (origin_decl.IsInvalid())
1031 return DeclFromUser<D>();
1032 return DeclFromUser<D>(dyn_cast<D>(origin_decl.decl));
1036 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) {
1037 DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl));
1038 if (parser_generic_decl.IsInvalid())
1039 return DeclFromParser<D>();
1040 return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl));
1043 bool ClangASTSource::FindObjCMethodDeclsWithOrigin(
1044 unsigned int current_id, NameSearchContext &context,
1045 ObjCInterfaceDecl *original_interface_decl, const char *log_info) {
1046 const DeclarationName &decl_name(context.m_decl_name);
1047 clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
1049 Selector original_selector;
1051 if (decl_name.isObjCZeroArgSelector()) {
1052 IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
1053 original_selector = original_ctx->Selectors.getSelector(0, &ident);
1054 } else if (decl_name.isObjCOneArgSelector()) {
1055 const std::string &decl_name_string = decl_name.getAsString();
1056 std::string decl_name_string_without_colon(decl_name_string.c_str(),
1057 decl_name_string.length() - 1);
1058 IdentifierInfo *ident =
1059 &original_ctx->Idents.get(decl_name_string_without_colon);
1060 original_selector = original_ctx->Selectors.getSelector(1, &ident);
1062 SmallVector<IdentifierInfo *, 4> idents;
1064 clang::Selector sel = decl_name.getObjCSelector();
1066 unsigned num_args = sel.getNumArgs();
1068 for (unsigned i = 0; i != num_args; ++i) {
1069 idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
1073 original_ctx->Selectors.getSelector(num_args, idents.data());
1076 DeclarationName original_decl_name(original_selector);
1078 llvm::SmallVector<NamedDecl *, 1> methods;
1080 ClangASTContext::GetCompleteDecl(original_ctx, original_interface_decl);
1082 if (ObjCMethodDecl *instance_method_decl =
1083 original_interface_decl->lookupInstanceMethod(original_selector)) {
1084 methods.push_back(instance_method_decl);
1085 } else if (ObjCMethodDecl *class_method_decl =
1086 original_interface_decl->lookupClassMethod(
1087 original_selector)) {
1088 methods.push_back(class_method_decl);
1091 if (methods.empty()) {
1095 for (NamedDecl *named_decl : methods) {
1099 ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
1104 Decl *copied_decl = CopyDecl(result_method);
1109 ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
1111 if (!copied_method_decl)
1114 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1117 ASTDumper dumper((Decl *)copied_method_decl);
1118 log->Printf(" CAS::FOMD[%d] found (%s) %s", current_id, log_info,
1119 dumper.GetCString());
1122 context.AddNamedDecl(copied_method_decl);
1128 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
1129 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1132 if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) {
1133 ObjCInterfaceDecl *complete_iface_decl =
1134 GetCompleteObjCInterface(interface_decl);
1136 if (complete_iface_decl && (complete_iface_decl != context.m_decl_context)) {
1137 m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()});
1141 GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context,
1142 context.m_decl_name);
1146 static unsigned int invocation_id = 0;
1147 unsigned int current_id = invocation_id++;
1149 const DeclarationName &decl_name(context.m_decl_name);
1150 const DeclContext *decl_ctx(context.m_decl_context);
1152 const ObjCInterfaceDecl *interface_decl =
1153 dyn_cast<ObjCInterfaceDecl>(decl_ctx);
1155 if (!interface_decl)
1159 Decl *original_decl = NULL;
1160 ASTContext *original_ctx = NULL;
1162 m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl,
1168 ObjCInterfaceDecl *original_interface_decl =
1169 dyn_cast<ObjCInterfaceDecl>(original_decl);
1171 if (FindObjCMethodDeclsWithOrigin(current_id, context,
1172 original_interface_decl, "at origin"))
1173 return; // found it, no need to look any further
1178 if (decl_name.isObjCZeroArgSelector()) {
1179 ss.Printf("%s", decl_name.getAsString().c_str());
1180 } else if (decl_name.isObjCOneArgSelector()) {
1181 ss.Printf("%s", decl_name.getAsString().c_str());
1183 clang::Selector sel = decl_name.getObjCSelector();
1185 for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) {
1186 llvm::StringRef r = sel.getNameForSlot(i);
1187 ss.Printf("%s:", r.str().c_str());
1192 if (ss.GetString().contains("$__lldb"))
1193 return; // we don't need any results
1195 ConstString selector_name(ss.GetString());
1198 log->Printf("ClangASTSource::FindObjCMethodDecls[%d] on (ASTContext*)%p "
1199 "for selector [%s %s]",
1200 current_id, static_cast<void *>(m_ast_context),
1201 interface_decl->getNameAsString().c_str(),
1202 selector_name.AsCString());
1203 SymbolContextList sc_list;
1205 const bool include_symbols = false;
1206 const bool include_inlines = false;
1207 const bool append = false;
1209 std::string interface_name = interface_decl->getNameAsString();
1213 ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString());
1215 ConstString instance_method_name(ms.GetString());
1217 m_target->GetImages().FindFunctions(
1218 instance_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1219 include_inlines, append, sc_list);
1221 if (sc_list.GetSize())
1225 ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString());
1227 ConstString class_method_name(ms.GetString());
1229 m_target->GetImages().FindFunctions(
1230 class_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1231 include_inlines, append, sc_list);
1233 if (sc_list.GetSize())
1236 // Fall back and check for methods in categories. If we find methods this
1237 // way, we need to check that they're actually in categories on the desired
1240 SymbolContextList candidate_sc_list;
1242 m_target->GetImages().FindFunctions(
1243 selector_name, lldb::eFunctionNameTypeSelector, include_symbols,
1244 include_inlines, append, candidate_sc_list);
1246 for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) {
1247 SymbolContext candidate_sc;
1249 if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc))
1252 if (!candidate_sc.function)
1255 const char *candidate_name = candidate_sc.function->GetName().AsCString();
1257 const char *cursor = candidate_name;
1259 if (*cursor != '+' && *cursor != '-')
1269 size_t interface_len = interface_name.length();
1271 if (strncmp(cursor, interface_name.c_str(), interface_len))
1274 cursor += interface_len;
1276 if (*cursor == ' ' || *cursor == '(')
1277 sc_list.Append(candidate_sc);
1281 if (sc_list.GetSize()) {
1282 // We found a good function symbol. Use that.
1284 for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) {
1287 if (!sc_list.GetContextAtIndex(i, sc))
1293 CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext();
1294 if (!function_decl_ctx)
1297 ObjCMethodDecl *method_decl =
1298 ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1303 ObjCInterfaceDecl *found_interface_decl =
1304 method_decl->getClassInterface();
1306 if (!found_interface_decl)
1309 if (found_interface_decl->getName() == interface_decl->getName()) {
1310 Decl *copied_decl = CopyDecl(method_decl);
1315 ObjCMethodDecl *copied_method_decl =
1316 dyn_cast<ObjCMethodDecl>(copied_decl);
1318 if (!copied_method_decl)
1322 ASTDumper dumper((Decl *)copied_method_decl);
1323 log->Printf(" CAS::FOMD[%d] found (in symbols) %s", current_id,
1324 dumper.GetCString());
1327 context.AddNamedDecl(copied_method_decl);
1334 // Try the debug information.
1337 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1338 const_cast<ObjCInterfaceDecl *>(interface_decl));
1340 if (!complete_interface_decl)
1343 // We found the complete interface. The runtime never needs to be queried
1344 // in this scenario.
1346 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1347 complete_interface_decl);
1349 if (complete_interface_decl == interface_decl)
1350 break; // already checked this one
1353 log->Printf("CAS::FOPD[%d] trying origin "
1354 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1355 current_id, static_cast<void *>(complete_interface_decl),
1356 static_cast<void *>(&complete_iface_decl->getASTContext()));
1358 FindObjCMethodDeclsWithOrigin(current_id, context, complete_interface_decl,
1365 // Check the modules only if the debug information didn't have a complete
1368 if (ClangModulesDeclVendor *modules_decl_vendor =
1369 m_target->GetClangModulesDeclVendor()) {
1370 ConstString interface_name(interface_decl->getNameAsString().c_str());
1371 bool append = false;
1372 uint32_t max_matches = 1;
1373 std::vector<clang::NamedDecl *> decls;
1375 if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches,
1379 ObjCInterfaceDecl *interface_decl_from_modules =
1380 dyn_cast<ObjCInterfaceDecl>(decls[0]);
1382 if (!interface_decl_from_modules)
1385 if (FindObjCMethodDeclsWithOrigin(
1386 current_id, context, interface_decl_from_modules, "in modules"))
1392 // Check the runtime only if the debug information didn't have a complete
1393 // interface and the modules don't get us anywhere.
1395 lldb::ProcessSP process(m_target->GetProcessSP());
1400 ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
1402 if (!language_runtime)
1405 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1410 ConstString interface_name(interface_decl->getNameAsString().c_str());
1411 bool append = false;
1412 uint32_t max_matches = 1;
1413 std::vector<clang::NamedDecl *> decls;
1415 if (!decl_vendor->FindDecls(interface_name, append, max_matches, decls))
1418 ObjCInterfaceDecl *runtime_interface_decl =
1419 dyn_cast<ObjCInterfaceDecl>(decls[0]);
1421 if (!runtime_interface_decl)
1424 FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl,
1429 static bool FindObjCPropertyAndIvarDeclsWithOrigin(
1430 unsigned int current_id, NameSearchContext &context, ClangASTSource &source,
1431 DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) {
1432 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1434 if (origin_iface_decl.IsInvalid())
1437 std::string name_str = context.m_decl_name.getAsString();
1438 StringRef name(name_str);
1439 IdentifierInfo &name_identifier(
1440 origin_iface_decl->getASTContext().Idents.get(name));
1442 DeclFromUser<ObjCPropertyDecl> origin_property_decl(
1443 origin_iface_decl->FindPropertyDeclaration(
1444 &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance));
1448 if (origin_property_decl.IsValid()) {
1449 DeclFromParser<ObjCPropertyDecl> parser_property_decl(
1450 origin_property_decl.Import(source));
1451 if (parser_property_decl.IsValid()) {
1453 ASTDumper dumper((Decl *)parser_property_decl.decl);
1454 log->Printf(" CAS::FOPD[%d] found %s", current_id,
1455 dumper.GetCString());
1458 context.AddNamedDecl(parser_property_decl.decl);
1463 DeclFromUser<ObjCIvarDecl> origin_ivar_decl(
1464 origin_iface_decl->getIvarDecl(&name_identifier));
1466 if (origin_ivar_decl.IsValid()) {
1467 DeclFromParser<ObjCIvarDecl> parser_ivar_decl(
1468 origin_ivar_decl.Import(source));
1469 if (parser_ivar_decl.IsValid()) {
1471 ASTDumper dumper((Decl *)parser_ivar_decl.decl);
1472 log->Printf(" CAS::FOPD[%d] found %s", current_id,
1473 dumper.GetCString());
1476 context.AddNamedDecl(parser_ivar_decl.decl);
1484 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) {
1485 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1487 static unsigned int invocation_id = 0;
1488 unsigned int current_id = invocation_id++;
1490 DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl(
1491 cast<ObjCInterfaceDecl>(context.m_decl_context));
1492 DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl(
1493 parser_iface_decl.GetOrigin(*this));
1495 ConstString class_name(parser_iface_decl->getNameAsString().c_str());
1498 log->Printf("ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on "
1499 "(ASTContext*)%p for '%s.%s'",
1500 current_id, static_cast<void *>(m_ast_context),
1501 parser_iface_decl->getNameAsString().c_str(),
1502 context.m_decl_name.getAsString().c_str());
1504 if (FindObjCPropertyAndIvarDeclsWithOrigin(
1505 current_id, context, *this, origin_iface_decl))
1509 log->Printf("CAS::FOPD[%d] couldn't find the property on origin "
1510 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching "
1512 current_id, static_cast<const void *>(origin_iface_decl.decl),
1513 static_cast<void *>(&origin_iface_decl->getASTContext()));
1515 SymbolContext null_sc;
1519 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1520 const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl));
1522 if (!complete_interface_decl)
1525 // We found the complete interface. The runtime never needs to be queried
1526 // in this scenario.
1528 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1529 complete_interface_decl);
1531 if (complete_iface_decl.decl == origin_iface_decl.decl)
1532 break; // already checked this one
1535 log->Printf("CAS::FOPD[%d] trying origin "
1536 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1538 static_cast<const void *>(complete_iface_decl.decl),
1539 static_cast<void *>(&complete_iface_decl->getASTContext()));
1541 FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1542 complete_iface_decl);
1548 // Check the modules only if the debug information didn't have a complete
1551 ClangModulesDeclVendor *modules_decl_vendor =
1552 m_target->GetClangModulesDeclVendor();
1554 if (!modules_decl_vendor)
1557 bool append = false;
1558 uint32_t max_matches = 1;
1559 std::vector<clang::NamedDecl *> decls;
1561 if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1564 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules(
1565 dyn_cast<ObjCInterfaceDecl>(decls[0]));
1567 if (!interface_decl_from_modules.IsValid())
1572 "CAS::FOPD[%d] trying module "
1573 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1575 static_cast<const void *>(interface_decl_from_modules.decl),
1576 static_cast<void *>(&interface_decl_from_modules->getASTContext()));
1578 if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1579 interface_decl_from_modules))
1584 // Check the runtime only if the debug information didn't have a complete
1585 // interface and nothing was in the modules.
1587 lldb::ProcessSP process(m_target->GetProcessSP());
1592 ObjCLanguageRuntime *language_runtime(process->GetObjCLanguageRuntime());
1594 if (!language_runtime)
1597 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1602 bool append = false;
1603 uint32_t max_matches = 1;
1604 std::vector<clang::NamedDecl *> decls;
1606 if (!decl_vendor->FindDecls(class_name, append, max_matches, decls))
1609 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime(
1610 dyn_cast<ObjCInterfaceDecl>(decls[0]));
1612 if (!interface_decl_from_runtime.IsValid())
1617 "CAS::FOPD[%d] trying runtime "
1618 "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1620 static_cast<const void *>(interface_decl_from_runtime.decl),
1621 static_cast<void *>(&interface_decl_from_runtime->getASTContext()));
1623 if (FindObjCPropertyAndIvarDeclsWithOrigin(
1624 current_id, context, *this, interface_decl_from_runtime))
1629 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap;
1630 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap;
1632 template <class D, class O>
1633 static bool ImportOffsetMap(llvm::DenseMap<const D *, O> &destination_map,
1634 llvm::DenseMap<const D *, O> &source_map,
1635 ClangASTSource &source) {
1636 // When importing fields into a new record, clang has a hard requirement that
1637 // fields be imported in field offset order. Since they are stored in a
1638 // DenseMap with a pointer as the key type, this means we cannot simply
1639 // iterate over the map, as the order will be non-deterministic. Instead we
1640 // have to sort by the offset and then insert in sorted order.
1641 typedef llvm::DenseMap<const D *, O> MapType;
1642 typedef typename MapType::value_type PairType;
1643 std::vector<PairType> sorted_items;
1644 sorted_items.reserve(source_map.size());
1645 sorted_items.assign(source_map.begin(), source_map.end());
1646 llvm::sort(sorted_items.begin(), sorted_items.end(),
1647 [](const PairType &lhs, const PairType &rhs) {
1648 return lhs.second < rhs.second;
1651 for (const auto &item : sorted_items) {
1652 DeclFromUser<D> user_decl(const_cast<D *>(item.first));
1653 DeclFromParser<D> parser_decl(user_decl.Import(source));
1654 if (parser_decl.IsInvalid())
1656 destination_map.insert(
1657 std::pair<const D *, O>(parser_decl.decl, item.second));
1663 template <bool IsVirtual>
1664 bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
1665 DeclFromUser<const CXXRecordDecl> &record,
1666 BaseOffsetMap &base_offsets) {
1667 for (CXXRecordDecl::base_class_const_iterator
1668 bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
1669 be = (IsVirtual ? record->vbases_end() : record->bases_end());
1671 if (!IsVirtual && bi->isVirtual())
1674 const clang::Type *origin_base_type = bi->getType().getTypePtr();
1675 const clang::RecordType *origin_base_record_type =
1676 origin_base_type->getAs<RecordType>();
1678 if (!origin_base_record_type)
1681 DeclFromUser<RecordDecl> origin_base_record(
1682 origin_base_record_type->getDecl());
1684 if (origin_base_record.IsInvalid())
1687 DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
1688 DynCast<CXXRecordDecl>(origin_base_record));
1690 if (origin_base_cxx_record.IsInvalid())
1693 CharUnits base_offset;
1697 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
1700 record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
1702 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
1703 origin_base_cxx_record.decl, base_offset));
1709 bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size,
1710 uint64_t &alignment,
1711 FieldOffsetMap &field_offsets,
1712 BaseOffsetMap &base_offsets,
1713 BaseOffsetMap &virtual_base_offsets) {
1714 ClangASTMetrics::RegisterRecordLayout();
1716 static unsigned int invocation_id = 0;
1717 unsigned int current_id = invocation_id++;
1719 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1722 log->Printf("LayoutRecordType[%u] on (ASTContext*)%p for (RecordDecl*)%p "
1724 current_id, static_cast<void *>(m_ast_context),
1725 static_cast<const void *>(record),
1726 record->getNameAsString().c_str());
1728 DeclFromParser<const RecordDecl> parser_record(record);
1729 DeclFromUser<const RecordDecl> origin_record(
1730 parser_record.GetOrigin(*this));
1732 if (origin_record.IsInvalid())
1735 FieldOffsetMap origin_field_offsets;
1736 BaseOffsetMap origin_base_offsets;
1737 BaseOffsetMap origin_virtual_base_offsets;
1739 ClangASTContext::GetCompleteDecl(
1740 &origin_record->getASTContext(),
1741 const_cast<RecordDecl *>(origin_record.decl));
1743 clang::RecordDecl *definition = origin_record.decl->getDefinition();
1744 if (!definition || !definition->isCompleteDefinition())
1747 const ASTRecordLayout &record_layout(
1748 origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
1750 int field_idx = 0, field_count = record_layout.getFieldCount();
1752 for (RecordDecl::field_iterator fi = origin_record->field_begin(),
1753 fe = origin_record->field_end();
1755 if (field_idx >= field_count)
1756 return false; // Layout didn't go well. Bail out.
1758 uint64_t field_offset = record_layout.getFieldOffset(field_idx);
1760 origin_field_offsets.insert(
1761 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
1766 lldbassert(&record->getASTContext() == m_ast_context);
1768 DeclFromUser<const CXXRecordDecl> origin_cxx_record(
1769 DynCast<const CXXRecordDecl>(origin_record));
1771 if (origin_cxx_record.IsValid()) {
1772 if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
1773 origin_base_offsets) ||
1774 !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
1775 origin_virtual_base_offsets))
1779 if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) ||
1780 !ImportOffsetMap(base_offsets, origin_base_offsets, *this) ||
1781 !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets,
1785 size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth();
1786 alignment = record_layout.getAlignment().getQuantity() *
1787 m_ast_context->getCharWidth();
1790 log->Printf("LRT[%u] returned:", current_id);
1791 log->Printf("LRT[%u] Original = (RecordDecl*)%p", current_id,
1792 static_cast<const void *>(origin_record.decl));
1793 log->Printf("LRT[%u] Size = %" PRId64, current_id, size);
1794 log->Printf("LRT[%u] Alignment = %" PRId64, current_id, alignment);
1795 log->Printf("LRT[%u] Fields:", current_id);
1796 for (RecordDecl::field_iterator fi = record->field_begin(),
1797 fe = record->field_end();
1799 log->Printf("LRT[%u] (FieldDecl*)%p, Name = '%s', Offset = %" PRId64
1801 current_id, static_cast<void *>(*fi),
1802 fi->getNameAsString().c_str(), field_offsets[*fi]);
1804 DeclFromParser<const CXXRecordDecl> parser_cxx_record =
1805 DynCast<const CXXRecordDecl>(parser_record);
1806 if (parser_cxx_record.IsValid()) {
1807 log->Printf("LRT[%u] Bases:", current_id);
1808 for (CXXRecordDecl::base_class_const_iterator
1809 bi = parser_cxx_record->bases_begin(),
1810 be = parser_cxx_record->bases_end();
1812 bool is_virtual = bi->isVirtual();
1814 QualType base_type = bi->getType();
1815 const RecordType *base_record_type = base_type->getAs<RecordType>();
1816 DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
1817 DeclFromParser<CXXRecordDecl> base_cxx_record =
1818 DynCast<CXXRecordDecl>(base_record);
1821 "LRT[%u] %s(CXXRecordDecl*)%p, Name = '%s', Offset = %" PRId64
1823 current_id, (is_virtual ? "Virtual " : ""),
1824 static_cast<void *>(base_cxx_record.decl),
1825 base_cxx_record.decl->getNameAsString().c_str(),
1827 ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1828 : base_offsets[base_cxx_record.decl].getQuantity()));
1831 log->Printf("LRD[%u] Not a CXXRecord, so no bases", current_id);
1838 void ClangASTSource::CompleteNamespaceMap(
1839 ClangASTImporter::NamespaceMapSP &namespace_map, const ConstString &name,
1840 ClangASTImporter::NamespaceMapSP &parent_map) const {
1841 static unsigned int invocation_id = 0;
1842 unsigned int current_id = invocation_id++;
1844 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1847 if (parent_map && parent_map->size())
1848 log->Printf("CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1849 "namespace %s in namespace %s",
1850 current_id, static_cast<void *>(m_ast_context),
1852 parent_map->begin()->second.GetName().AsCString());
1854 log->Printf("CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1856 current_id, static_cast<void *>(m_ast_context),
1861 for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1862 e = parent_map->end();
1864 CompilerDeclContext found_namespace_decl;
1866 lldb::ModuleSP module_sp = i->first;
1867 CompilerDeclContext module_parent_namespace_decl = i->second;
1869 SymbolVendor *symbol_vendor = module_sp->GetSymbolVendor();
1874 found_namespace_decl =
1875 symbol_vendor->FindNamespace(name, &module_parent_namespace_decl);
1877 if (!found_namespace_decl)
1880 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1881 module_sp, found_namespace_decl));
1884 log->Printf(" CMN[%u] Found namespace %s in module %s", current_id,
1886 module_sp->GetFileSpec().GetFilename().GetCString());
1889 const ModuleList &target_images = m_target->GetImages();
1890 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
1892 CompilerDeclContext null_namespace_decl;
1894 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
1895 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
1900 CompilerDeclContext found_namespace_decl;
1902 SymbolVendor *symbol_vendor = image->GetSymbolVendor();
1907 found_namespace_decl =
1908 symbol_vendor->FindNamespace(name, &null_namespace_decl);
1910 if (!found_namespace_decl)
1913 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1914 image, found_namespace_decl));
1917 log->Printf(" CMN[%u] Found namespace %s in module %s", current_id,
1919 image->GetFileSpec().GetFilename().GetCString());
1924 NamespaceDecl *ClangASTSource::AddNamespace(
1925 NameSearchContext &context,
1926 ClangASTImporter::NamespaceMapSP &namespace_decls) {
1927 if (!namespace_decls)
1930 const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1932 clang::ASTContext *src_ast =
1933 ClangASTContext::DeclContextGetClangASTContext(namespace_decl);
1936 clang::NamespaceDecl *src_namespace_decl =
1937 ClangASTContext::DeclContextGetAsNamespaceDecl(namespace_decl);
1939 if (!src_namespace_decl)
1942 Decl *copied_decl = CopyDecl(src_namespace_decl);
1947 NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1949 if (!copied_namespace_decl)
1952 context.m_decls.push_back(copied_namespace_decl);
1954 m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1957 return dyn_cast<NamespaceDecl>(copied_decl);
1960 clang::QualType ClangASTSource::CopyTypeWithMerger(
1961 clang::ASTContext &from_context,
1962 clang::ExternalASTMerger &merger,
1963 clang::QualType type) {
1964 if (!merger.HasImporterForOrigin(from_context)) {
1965 lldbassert(0 && "Couldn't find the importer for a source context!");
1969 return merger.ImporterForOrigin(from_context).Import(type);
1972 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) {
1973 clang::ASTContext &from_context = src_decl->getASTContext();
1974 if (m_ast_importer_sp) {
1975 return m_ast_importer_sp->CopyDecl(m_ast_context, &from_context, src_decl);
1976 } else if (m_merger_up) {
1977 if (!m_merger_up->HasImporterForOrigin(from_context)) {
1978 lldbassert(0 && "Couldn't find the importer for a source context!");
1982 return m_merger_up->ImporterForOrigin(from_context).Import(src_decl);
1984 lldbassert(0 && "No mechanism for copying a decl!");
1989 bool ClangASTSource::ResolveDeclOrigin(const clang::Decl *decl,
1990 clang::Decl **original_decl,
1991 clang::ASTContext **original_ctx) {
1992 if (m_ast_importer_sp) {
1993 return m_ast_importer_sp->ResolveDeclOrigin(decl, original_decl,
1995 } else if (m_merger_up) {
1996 return false; // Implement this correctly in ExternalASTMerger
1998 // this can happen early enough that no ExternalASTSource is installed.
2003 clang::ExternalASTMerger &ClangASTSource::GetMergerUnchecked() {
2004 lldbassert(m_merger_up != nullptr);
2005 return *m_merger_up;
2008 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) {
2009 ClangASTContext *src_ast =
2010 llvm::dyn_cast_or_null<ClangASTContext>(src_type.GetTypeSystem());
2011 if (src_ast == nullptr)
2012 return CompilerType();
2014 ClangASTMetrics::RegisterLLDBImport();
2016 SetImportInProgress(true);
2018 QualType copied_qual_type;
2020 if (m_ast_importer_sp) {
2022 m_ast_importer_sp->CopyType(m_ast_context, src_ast->getASTContext(),
2023 ClangUtil::GetQualType(src_type));
2024 } else if (m_merger_up) {
2026 CopyTypeWithMerger(*src_ast->getASTContext(), *m_merger_up,
2027 ClangUtil::GetQualType(src_type));
2029 lldbassert(0 && "No mechanism for copying a type!");
2030 return CompilerType();
2033 SetImportInProgress(false);
2035 if (copied_qual_type.getAsOpaquePtr() &&
2036 copied_qual_type->getCanonicalTypeInternal().isNull())
2037 // this shouldn't happen, but we're hardening because the AST importer
2038 // seems to be generating bad types on occasion.
2039 return CompilerType();
2041 return CompilerType(m_ast_context, copied_qual_type);
2044 clang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) {
2045 assert(type && "Type for variable must be valid!");
2047 if (!type.IsValid())
2050 ClangASTContext *lldb_ast =
2051 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
2055 IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo();
2057 clang::ASTContext *ast = lldb_ast->getASTContext();
2059 clang::NamedDecl *Decl = VarDecl::Create(
2060 *ast, const_cast<DeclContext *>(m_decl_context), SourceLocation(),
2061 SourceLocation(), ii, ClangUtil::GetQualType(type), 0, SC_Static);
2062 m_decls.push_back(Decl);
2067 clang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type,
2069 assert(type && "Type for variable must be valid!");
2071 if (!type.IsValid())
2074 if (m_function_types.count(type))
2077 ClangASTContext *lldb_ast =
2078 llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
2082 m_function_types.insert(type);
2084 QualType qual_type(ClangUtil::GetQualType(type));
2086 clang::ASTContext *ast = lldb_ast->getASTContext();
2088 const bool isInlineSpecified = false;
2089 const bool hasWrittenPrototype = true;
2090 const bool isConstexprSpecified = false;
2092 clang::DeclContext *context = const_cast<DeclContext *>(m_decl_context);
2095 context = LinkageSpecDecl::Create(
2096 *ast, context, SourceLocation(), SourceLocation(),
2097 clang::LinkageSpecDecl::LanguageIDs::lang_c, false);
2100 // Pass the identifier info for functions the decl_name is needed for
2102 clang::DeclarationName decl_name =
2103 m_decl_name.getNameKind() == DeclarationName::Identifier
2104 ? m_decl_name.getAsIdentifierInfo()
2107 clang::FunctionDecl *func_decl = FunctionDecl::Create(
2108 *ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type,
2109 NULL, SC_Extern, isInlineSpecified, hasWrittenPrototype,
2110 isConstexprSpecified);
2112 // We have to do more than just synthesize the FunctionDecl. We have to
2113 // synthesize ParmVarDecls for all of the FunctionDecl's arguments. To do
2114 // this, we raid the function's FunctionProtoType for types.
2116 const FunctionProtoType *func_proto_type =
2117 qual_type.getTypePtr()->getAs<FunctionProtoType>();
2119 if (func_proto_type) {
2120 unsigned NumArgs = func_proto_type->getNumParams();
2123 SmallVector<ParmVarDecl *, 5> parm_var_decls;
2125 for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) {
2126 QualType arg_qual_type(func_proto_type->getParamType(ArgIndex));
2128 parm_var_decls.push_back(ParmVarDecl::Create(
2129 *ast, const_cast<DeclContext *>(context), SourceLocation(),
2130 SourceLocation(), NULL, arg_qual_type, NULL, SC_Static, NULL));
2133 func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls));
2135 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2138 log->Printf("Function type wasn't a FunctionProtoType");
2141 // If this is an operator (e.g. operator new or operator==), only insert the
2142 // declaration we inferred from the symbol if we can provide the correct
2143 // number of arguments. We shouldn't really inject random decl(s) for
2144 // functions that are analyzed semantically in a special way, otherwise we
2145 // will crash in clang.
2146 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
2147 if (func_proto_type &&
2148 ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) {
2149 if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
2150 false, op_kind, func_proto_type->getNumParams()))
2153 m_decls.push_back(func_decl);
2158 clang::NamedDecl *NameSearchContext::AddGenericFunDecl() {
2159 FunctionProtoType::ExtProtoInfo proto_info;
2161 proto_info.Variadic = true;
2163 QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType(
2164 m_ast_source.m_ast_context->UnknownAnyTy, // result
2165 ArrayRef<QualType>(), // argument types
2169 CompilerType(m_ast_source.m_ast_context, generic_function_type), true);
2173 NameSearchContext::AddTypeDecl(const CompilerType &clang_type) {
2174 if (ClangUtil::IsClangType(clang_type)) {
2175 QualType qual_type = ClangUtil::GetQualType(clang_type);
2177 if (const TypedefType *typedef_type =
2178 llvm::dyn_cast<TypedefType>(qual_type)) {
2179 TypedefNameDecl *typedef_name_decl = typedef_type->getDecl();
2181 m_decls.push_back(typedef_name_decl);
2183 return (NamedDecl *)typedef_name_decl;
2184 } else if (const TagType *tag_type = qual_type->getAs<TagType>()) {
2185 TagDecl *tag_decl = tag_type->getDecl();
2187 m_decls.push_back(tag_decl);
2190 } else if (const ObjCObjectType *objc_object_type =
2191 qual_type->getAs<ObjCObjectType>()) {
2192 ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface();
2194 m_decls.push_back((NamedDecl *)interface_decl);
2196 return (NamedDecl *)interface_decl;
2202 void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) {
2203 for (clang::NamedDecl *decl : result)
2204 m_decls.push_back(decl);
2207 void NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) {
2208 m_decls.push_back(decl);