1 //===-- ClangASTSource.cpp ------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "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/CompilerDeclContext.h"
17 #include "lldb/Symbol/Function.h"
18 #include "lldb/Symbol/SymbolFile.h"
19 #include "lldb/Symbol/TaggedASTType.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Utility/Log.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
26 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
27 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
28 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
33 using namespace clang;
34 using namespace lldb_private;
36 // Scoped class that will remove an active lexical decl from the set when it
39 class ScopedLexicalDeclEraser {
41 ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls,
42 const clang::Decl *decl)
43 : m_active_lexical_decls(decls), m_decl(decl) {}
45 ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); }
48 std::set<const clang::Decl *> &m_active_lexical_decls;
49 const clang::Decl *m_decl;
53 ClangASTSource::ClangASTSource(
54 const lldb::TargetSP &target,
55 const std::shared_ptr<ClangASTImporter> &importer)
56 : m_lookups_enabled(false), m_target(target), m_ast_context(nullptr),
57 m_ast_importer_sp(importer), m_active_lexical_decls(),
59 assert(m_ast_importer_sp && "No ClangASTImporter passed to ClangASTSource?");
62 void ClangASTSource::InstallASTContext(TypeSystemClang &clang_ast_context) {
63 m_ast_context = &clang_ast_context.getASTContext();
64 m_clang_ast_context = &clang_ast_context;
65 m_file_manager = &m_ast_context->getSourceManager().getFileManager();
66 m_ast_importer_sp->InstallMapCompleter(m_ast_context, *this);
69 ClangASTSource::~ClangASTSource() {
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::GetScratchTypeSystemClang(create_on_demand).
77 TypeSystemClang *scratch_clang_ast_context =
78 TypeSystemClang::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 std::string decl_name(clang_decl_name.getAsString());
108 switch (clang_decl_name.getNameKind()) {
109 // Normal identifiers.
110 case DeclarationName::Identifier: {
111 clang::IdentifierInfo *identifier_info =
112 clang_decl_name.getAsIdentifierInfo();
114 if (!identifier_info || identifier_info->getBuiltinID() != 0) {
115 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
121 case DeclarationName::CXXOperatorName:
122 case DeclarationName::CXXLiteralOperatorName:
125 // Using directives found in this context.
126 // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
127 case DeclarationName::CXXUsingDirective:
128 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
131 case DeclarationName::ObjCZeroArgSelector:
132 case DeclarationName::ObjCOneArgSelector:
133 case DeclarationName::ObjCMultiArgSelector: {
134 llvm::SmallVector<NamedDecl *, 1> method_decls;
136 NameSearchContext method_search_context(*m_clang_ast_context, method_decls,
137 clang_decl_name, decl_ctx);
139 FindObjCMethodDecls(method_search_context);
141 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
142 return (method_decls.size() > 0);
144 // These aren't possible in the global context.
145 case DeclarationName::CXXConstructorName:
146 case DeclarationName::CXXDestructorName:
147 case DeclarationName::CXXConversionFunctionName:
148 case DeclarationName::CXXDeductionGuideName:
149 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
153 if (!GetLookupsEnabled()) {
154 // Wait until we see a '$' at the start of a name before we start doing any
155 // lookups so we can avoid lookup up all of the builtin types.
156 if (!decl_name.empty() && decl_name[0] == '$') {
157 SetLookupsEnabled(true);
159 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
164 ConstString const_decl_name(decl_name.c_str());
166 const char *uniqued_const_decl_name = const_decl_name.GetCString();
167 if (m_active_lookups.find(uniqued_const_decl_name) !=
168 m_active_lookups.end()) {
169 // We are currently looking up this name...
170 SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
173 m_active_lookups.insert(uniqued_const_decl_name);
174 llvm::SmallVector<NamedDecl *, 4> name_decls;
175 NameSearchContext name_search_context(*m_clang_ast_context, name_decls,
176 clang_decl_name, decl_ctx);
177 FindExternalVisibleDecls(name_search_context);
178 SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
179 m_active_lookups.erase(uniqued_const_decl_name);
180 return (name_decls.size() != 0);
183 TagDecl *ClangASTSource::FindCompleteType(const TagDecl *decl) {
184 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
186 if (const NamespaceDecl *namespace_context =
187 dyn_cast<NamespaceDecl>(decl->getDeclContext())) {
188 ClangASTImporter::NamespaceMapSP namespace_map =
189 m_ast_importer_sp->GetNamespaceMap(namespace_context);
191 LLDB_LOGV(log, " CTD Inspecting namespace map{0} ({1} entries)",
192 namespace_map.get(), namespace_map->size());
197 for (const ClangASTImporter::NamespaceMapItem &item : *namespace_map) {
198 LLDB_LOG(log, " CTD Searching namespace {0} in module {1}",
199 item.second.GetName(), item.first->GetFileSpec().GetFilename());
203 ConstString name(decl->getName());
205 item.first->FindTypesInNamespace(name, item.second, UINT32_MAX, types);
207 for (uint32_t ti = 0, te = types.GetSize(); ti != te; ++ti) {
208 lldb::TypeSP type = types.GetTypeAtIndex(ti);
213 CompilerType clang_type(type->GetFullCompilerType());
215 if (!ClangUtil::IsClangType(clang_type))
218 const TagType *tag_type =
219 ClangUtil::GetQualType(clang_type)->getAs<TagType>();
224 TagDecl *candidate_tag_decl =
225 const_cast<TagDecl *>(tag_type->getDecl());
227 if (TypeSystemClang::GetCompleteDecl(
228 &candidate_tag_decl->getASTContext(), candidate_tag_decl))
229 return candidate_tag_decl;
235 ConstString name(decl->getName());
237 const ModuleList &module_list = m_target->GetImages();
239 bool exact_match = false;
240 llvm::DenseSet<SymbolFile *> searched_symbol_files;
241 module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX,
242 searched_symbol_files, types);
244 for (uint32_t ti = 0, te = types.GetSize(); ti != te; ++ti) {
245 lldb::TypeSP type = types.GetTypeAtIndex(ti);
250 CompilerType clang_type(type->GetFullCompilerType());
252 if (!ClangUtil::IsClangType(clang_type))
255 const TagType *tag_type =
256 ClangUtil::GetQualType(clang_type)->getAs<TagType>();
261 TagDecl *candidate_tag_decl = const_cast<TagDecl *>(tag_type->getDecl());
263 // We have found a type by basename and we need to make sure the decl
264 // contexts are the same before we can try to complete this type with
266 if (!TypeSystemClang::DeclsAreEquivalent(const_cast<TagDecl *>(decl),
270 if (TypeSystemClang::GetCompleteDecl(&candidate_tag_decl->getASTContext(),
272 return candidate_tag_decl;
278 void ClangASTSource::CompleteType(TagDecl *tag_decl) {
279 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
283 " CompleteTagDecl on (ASTContext*){0} Completing "
284 "(TagDecl*){1} named {2}",
285 m_clang_ast_context->getDisplayName(), tag_decl,
286 tag_decl->getName());
288 LLDB_LOG(log, " CTD Before:\n{0}", ClangUtil::DumpDecl(tag_decl));
291 auto iter = m_active_lexical_decls.find(tag_decl);
292 if (iter != m_active_lexical_decls.end())
294 m_active_lexical_decls.insert(tag_decl);
295 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
297 if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) {
298 // We couldn't complete the type. Maybe there's a definition somewhere
299 // else that can be completed.
300 if (TagDecl *alternate = FindCompleteType(tag_decl))
301 m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl, alternate);
304 LLDB_LOG(log, " [CTD] After:\n{0}", ClangUtil::DumpDecl(tag_decl));
307 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
308 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
311 " [CompleteObjCInterfaceDecl] on (ASTContext*){0} '{1}' "
312 "Completing an ObjCInterfaceDecl named {1}",
313 m_ast_context, m_clang_ast_context->getDisplayName(),
314 interface_decl->getName());
315 LLDB_LOG(log, " [COID] Before:\n{0}",
316 ClangUtil::DumpDecl(interface_decl));
318 ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
320 if (original.Valid()) {
321 if (ObjCInterfaceDecl *original_iface_decl =
322 dyn_cast<ObjCInterfaceDecl>(original.decl)) {
323 ObjCInterfaceDecl *complete_iface_decl =
324 GetCompleteObjCInterface(original_iface_decl);
326 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
327 m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
332 m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
334 if (interface_decl->getSuperClass() &&
335 interface_decl->getSuperClass() != interface_decl)
336 CompleteType(interface_decl->getSuperClass());
338 LLDB_LOG(log, " [COID] After:");
339 LLDB_LOG(log, " [COID] {0}", ClangUtil::DumpDecl(interface_decl));
342 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
343 const clang::ObjCInterfaceDecl *interface_decl) {
344 lldb::ProcessSP process(m_target->GetProcessSP());
349 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
351 if (!language_runtime)
354 ConstString class_name(interface_decl->getNameAsString().c_str());
356 lldb::TypeSP complete_type_sp(
357 language_runtime->LookupInCompleteClassCache(class_name));
359 if (!complete_type_sp)
362 TypeFromUser complete_type =
363 TypeFromUser(complete_type_sp->GetFullCompilerType());
364 lldb::opaque_compiler_type_t complete_opaque_type =
365 complete_type.GetOpaqueQualType();
367 if (!complete_opaque_type)
370 const clang::Type *complete_clang_type =
371 QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
372 const ObjCInterfaceType *complete_interface_type =
373 dyn_cast<ObjCInterfaceType>(complete_clang_type);
375 if (!complete_interface_type)
378 ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
380 return complete_iface_decl;
383 void ClangASTSource::FindExternalLexicalDecls(
384 const DeclContext *decl_context,
385 llvm::function_ref<bool(Decl::Kind)> predicate,
386 llvm::SmallVectorImpl<Decl *> &decls) {
388 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
390 const Decl *context_decl = dyn_cast<Decl>(decl_context);
395 auto iter = m_active_lexical_decls.find(context_decl);
396 if (iter != m_active_lexical_decls.end())
398 m_active_lexical_decls.insert(context_decl);
399 ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
402 if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
404 "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in "
405 "'{2}' (%sDecl*){3}",
406 m_ast_context, m_clang_ast_context->getDisplayName(),
407 context_named_decl->getNameAsString().c_str(),
408 context_decl->getDeclKindName(),
409 static_cast<const void *>(context_decl));
410 else if (context_decl)
412 "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in "
414 m_ast_context, m_clang_ast_context->getDisplayName(),
415 context_decl->getDeclKindName(),
416 static_cast<const void *>(context_decl));
419 "FindExternalLexicalDecls on (ASTContext*){0} '{1}' in a "
421 m_ast_context, m_clang_ast_context->getDisplayName());
424 ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(context_decl);
426 if (!original.Valid())
429 LLDB_LOG(log, " FELD Original decl {0} (Decl*){1:x}:\n{2}",
430 static_cast<void *>(original.ctx),
431 static_cast<void *>(original.decl),
432 ClangUtil::DumpDecl(original.decl));
434 if (ObjCInterfaceDecl *original_iface_decl =
435 dyn_cast<ObjCInterfaceDecl>(original.decl)) {
436 ObjCInterfaceDecl *complete_iface_decl =
437 GetCompleteObjCInterface(original_iface_decl);
439 if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
440 original.decl = complete_iface_decl;
441 original.ctx = &complete_iface_decl->getASTContext();
443 m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
447 if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original.decl)) {
448 ExternalASTSource *external_source = original.ctx->getExternalSource();
451 external_source->CompleteType(original_tag_decl);
454 const DeclContext *original_decl_context =
455 dyn_cast<DeclContext>(original.decl);
457 if (!original_decl_context)
460 // Indicates whether we skipped any Decls of the original DeclContext.
461 bool SkippedDecls = false;
462 for (Decl *decl : original_decl_context->decls()) {
463 // The predicate function returns true if the passed declaration kind is
464 // the one we are looking for.
465 // See clang::ExternalASTSource::FindExternalLexicalDecls()
466 if (predicate(decl->getKind())) {
468 std::string ast_dump = ClangUtil::DumpDecl(decl);
469 if (const NamedDecl *context_named_decl =
470 dyn_cast<NamedDecl>(context_decl))
471 LLDB_LOG(log, " FELD Adding [to {0}Decl {1}] lexical {2}Decl {3}",
472 context_named_decl->getDeclKindName(),
473 context_named_decl->getName(), decl->getDeclKindName(),
476 LLDB_LOG(log, " FELD Adding lexical {0}Decl {1}",
477 decl->getDeclKindName(), ast_dump);
480 Decl *copied_decl = CopyDecl(decl);
485 if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
486 QualType copied_field_type = copied_field->getType();
488 m_ast_importer_sp->RequireCompleteType(copied_field_type);
495 // CopyDecl may build a lookup table which may set up ExternalLexicalStorage
496 // to false. However, since we skipped some of the external Decls we must
499 decl_context->setHasExternalLexicalStorage(true);
500 // This sets HasLazyExternalLexicalLookups to true. By setting this bit we
501 // ensure that the lookup table is rebuilt, which means the external source
502 // is consulted again when a clang::DeclContext::lookup is called.
503 const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable();
509 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
510 assert(m_ast_context);
512 const ConstString name(context.m_decl_name.getAsString().c_str());
514 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
517 if (!context.m_decl_context)
519 "ClangASTSource::FindExternalVisibleDecls on "
520 "(ASTContext*){0} '{1}' for '{2}' in a NULL DeclContext",
521 m_ast_context, m_clang_ast_context->getDisplayName(), name);
522 else if (const NamedDecl *context_named_decl =
523 dyn_cast<NamedDecl>(context.m_decl_context))
525 "ClangASTSource::FindExternalVisibleDecls on "
526 "(ASTContext*){0} '{1}' for '{2}' in '{3}'",
527 m_ast_context, m_clang_ast_context->getDisplayName(), name,
528 context_named_decl->getName());
531 "ClangASTSource::FindExternalVisibleDecls on "
532 "(ASTContext*){0} '{1}' for '{2}' in a '{3}'",
533 m_ast_context, m_clang_ast_context->getDisplayName(), name,
534 context.m_decl_context->getDeclKindName());
537 if (isa<NamespaceDecl>(context.m_decl_context)) {
538 LookupInNamespace(context);
539 } else if (isa<ObjCInterfaceDecl>(context.m_decl_context)) {
540 FindObjCPropertyAndIvarDecls(context);
541 } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) {
542 // we shouldn't be getting FindExternalVisibleDecls calls for these
545 CompilerDeclContext namespace_decl;
547 LLDB_LOG(log, " CAS::FEVD Searching the root namespace");
549 FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl);
552 if (!context.m_namespace_map->empty()) {
553 if (log && log->GetVerbose())
554 LLDB_LOG(log, " CAS::FEVD Registering namespace map {0} ({1} entries)",
555 context.m_namespace_map.get(), context.m_namespace_map->size());
557 NamespaceDecl *clang_namespace_decl =
558 AddNamespace(context, context.m_namespace_map);
560 if (clang_namespace_decl)
561 clang_namespace_decl->setHasExternalVisibleStorage();
565 clang::Sema *ClangASTSource::getSema() {
566 return m_clang_ast_context->getSema();
569 bool ClangASTSource::IgnoreName(const ConstString name,
570 bool ignore_all_dollar_names) {
571 static const ConstString id_name("id");
572 static const ConstString Class_name("Class");
574 if (m_ast_context->getLangOpts().ObjC)
575 if (name == id_name || name == Class_name)
578 StringRef name_string_ref = name.GetStringRef();
580 // The ClangASTSource is not responsible for finding $-names.
581 return name_string_ref.empty() ||
582 (ignore_all_dollar_names && name_string_ref.startswith("$")) ||
583 name_string_ref.startswith("_$");
586 void ClangASTSource::FindExternalVisibleDecls(
587 NameSearchContext &context, lldb::ModuleSP module_sp,
588 CompilerDeclContext &namespace_decl) {
589 assert(m_ast_context);
591 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
593 SymbolContextList sc_list;
595 const ConstString name(context.m_decl_name.getAsString().c_str());
596 if (IgnoreName(name, true))
602 FillNamespaceMap(context, module_sp, namespace_decl);
604 if (context.m_found_type)
608 const bool exact_match = true;
609 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
610 if (module_sp && namespace_decl)
611 module_sp->FindTypesInNamespace(name, namespace_decl, 1, types);
613 m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1,
614 searched_symbol_files, types);
617 if (size_t num_types = types.GetSize()) {
618 for (size_t ti = 0; ti < num_types; ++ti) {
619 lldb::TypeSP type_sp = types.GetTypeAtIndex(ti);
622 const char *name_string = type_sp->GetName().GetCString();
624 LLDB_LOG(log, " CAS::FEVD Matching type found for \"{0}\": {1}", name,
625 (name_string ? name_string : "<anonymous>"));
628 CompilerType full_type = type_sp->GetFullCompilerType();
630 CompilerType copied_clang_type(GuardedCopyType(full_type));
632 if (!copied_clang_type) {
633 LLDB_LOG(log, " CAS::FEVD - Couldn't export a type");
638 context.AddTypeDecl(copied_clang_type);
640 context.m_found_type = true;
645 if (!context.m_found_type) {
646 // Try the modules next.
647 FindDeclInModules(context, name);
650 if (!context.m_found_type) {
651 FindDeclInObjCRuntime(context, name);
655 void ClangASTSource::FillNamespaceMap(
656 NameSearchContext &context, lldb::ModuleSP module_sp,
657 const CompilerDeclContext &namespace_decl) {
658 const ConstString name(context.m_decl_name.getAsString().c_str());
659 if (IgnoreName(name, true))
662 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
664 if (module_sp && namespace_decl) {
665 CompilerDeclContext found_namespace_decl;
667 if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) {
668 found_namespace_decl = symbol_file->FindNamespace(name, namespace_decl);
670 if (found_namespace_decl) {
671 context.m_namespace_map->push_back(
672 std::pair<lldb::ModuleSP, CompilerDeclContext>(
673 module_sp, found_namespace_decl));
675 LLDB_LOG(log, " CAS::FEVD Found namespace {0} in module {1}", name,
676 module_sp->GetFileSpec().GetFilename());
682 const ModuleList &target_images = m_target->GetImages();
683 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
685 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
686 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
691 CompilerDeclContext found_namespace_decl;
693 SymbolFile *symbol_file = image->GetSymbolFile();
698 found_namespace_decl = symbol_file->FindNamespace(name, namespace_decl);
700 if (found_namespace_decl) {
701 context.m_namespace_map->push_back(
702 std::pair<lldb::ModuleSP, CompilerDeclContext>(image,
703 found_namespace_decl));
705 LLDB_LOG(log, " CAS::FEVD Found namespace {0} in module {1}", name,
706 image->GetFileSpec().GetFilename());
711 template <class D> class TaggedASTDecl {
713 TaggedASTDecl() : decl(nullptr) {}
714 TaggedASTDecl(D *_decl) : decl(_decl) {}
715 bool IsValid() const { return (decl != nullptr); }
716 bool IsInvalid() const { return !IsValid(); }
717 D *operator->() const { return decl; }
721 template <class D2, template <class D> class TD, class D1>
722 TD<D2> DynCast(TD<D1> source) {
723 return TD<D2>(dyn_cast<D2>(source.decl));
726 template <class D = Decl> class DeclFromParser;
727 template <class D = Decl> class DeclFromUser;
729 template <class D> class DeclFromParser : public TaggedASTDecl<D> {
731 DeclFromParser() : TaggedASTDecl<D>() {}
732 DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
734 DeclFromUser<D> GetOrigin(ClangASTSource &source);
737 template <class D> class DeclFromUser : public TaggedASTDecl<D> {
739 DeclFromUser() : TaggedASTDecl<D>() {}
740 DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
742 DeclFromParser<D> Import(ClangASTSource &source);
746 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) {
747 ClangASTImporter::DeclOrigin origin = source.GetDeclOrigin(this->decl);
749 return DeclFromUser<D>();
750 return DeclFromUser<D>(dyn_cast<D>(origin.decl));
754 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) {
755 DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl));
756 if (parser_generic_decl.IsInvalid())
757 return DeclFromParser<D>();
758 return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl));
761 bool ClangASTSource::FindObjCMethodDeclsWithOrigin(
762 NameSearchContext &context, ObjCInterfaceDecl *original_interface_decl,
763 const char *log_info) {
764 const DeclarationName &decl_name(context.m_decl_name);
765 clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
767 Selector original_selector;
769 if (decl_name.isObjCZeroArgSelector()) {
770 IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
771 original_selector = original_ctx->Selectors.getSelector(0, &ident);
772 } else if (decl_name.isObjCOneArgSelector()) {
773 const std::string &decl_name_string = decl_name.getAsString();
774 std::string decl_name_string_without_colon(decl_name_string.c_str(),
775 decl_name_string.length() - 1);
776 IdentifierInfo *ident =
777 &original_ctx->Idents.get(decl_name_string_without_colon);
778 original_selector = original_ctx->Selectors.getSelector(1, &ident);
780 SmallVector<IdentifierInfo *, 4> idents;
782 clang::Selector sel = decl_name.getObjCSelector();
784 unsigned num_args = sel.getNumArgs();
786 for (unsigned i = 0; i != num_args; ++i) {
787 idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
791 original_ctx->Selectors.getSelector(num_args, idents.data());
794 DeclarationName original_decl_name(original_selector);
796 llvm::SmallVector<NamedDecl *, 1> methods;
798 TypeSystemClang::GetCompleteDecl(original_ctx, original_interface_decl);
800 if (ObjCMethodDecl *instance_method_decl =
801 original_interface_decl->lookupInstanceMethod(original_selector)) {
802 methods.push_back(instance_method_decl);
803 } else if (ObjCMethodDecl *class_method_decl =
804 original_interface_decl->lookupClassMethod(
805 original_selector)) {
806 methods.push_back(class_method_decl);
809 if (methods.empty()) {
813 for (NamedDecl *named_decl : methods) {
817 ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
822 Decl *copied_decl = CopyDecl(result_method);
827 ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
829 if (!copied_method_decl)
832 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
834 LLDB_LOG(log, " CAS::FOMD found ({0}) {1}", log_info,
835 ClangUtil::DumpDecl(copied_method_decl));
837 context.AddNamedDecl(copied_method_decl);
843 void ClangASTSource::FindDeclInModules(NameSearchContext &context,
845 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
847 ClangModulesDeclVendor *modules_decl_vendor =
848 m_target->GetClangModulesDeclVendor();
849 if (!modules_decl_vendor)
853 uint32_t max_matches = 1;
854 std::vector<clang::NamedDecl *> decls;
856 if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
859 LLDB_LOG(log, " CAS::FEVD Matching entity found for \"{0}\" in the modules",
862 clang::NamedDecl *const decl_from_modules = decls[0];
864 if (llvm::isa<clang::TypeDecl>(decl_from_modules) ||
865 llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) ||
866 llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) {
867 clang::Decl *copied_decl = CopyDecl(decl_from_modules);
868 clang::NamedDecl *copied_named_decl =
869 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
871 if (!copied_named_decl) {
872 LLDB_LOG(log, " CAS::FEVD - Couldn't export a type from the modules");
877 context.AddNamedDecl(copied_named_decl);
879 context.m_found_type = true;
883 void ClangASTSource::FindDeclInObjCRuntime(NameSearchContext &context,
885 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
887 lldb::ProcessSP process(m_target->GetProcessSP());
892 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
894 if (!language_runtime)
897 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
903 uint32_t max_matches = 1;
904 std::vector<clang::NamedDecl *> decls;
906 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
907 if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls))
910 LLDB_LOG(log, " CAS::FEVD Matching type found for \"{0}\" in the runtime",
913 clang::Decl *copied_decl = CopyDecl(decls[0]);
914 clang::NamedDecl *copied_named_decl =
915 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
917 if (!copied_named_decl) {
918 LLDB_LOG(log, " CAS::FEVD - Couldn't export a type from the runtime");
923 context.AddNamedDecl(copied_named_decl);
926 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
927 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
929 const DeclarationName &decl_name(context.m_decl_name);
930 const DeclContext *decl_ctx(context.m_decl_context);
932 const ObjCInterfaceDecl *interface_decl =
933 dyn_cast<ObjCInterfaceDecl>(decl_ctx);
939 ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
941 if (!original.Valid())
944 ObjCInterfaceDecl *original_interface_decl =
945 dyn_cast<ObjCInterfaceDecl>(original.decl);
947 if (FindObjCMethodDeclsWithOrigin(context, original_interface_decl,
949 return; // found it, no need to look any further
954 if (decl_name.isObjCZeroArgSelector()) {
955 ss.Printf("%s", decl_name.getAsString().c_str());
956 } else if (decl_name.isObjCOneArgSelector()) {
957 ss.Printf("%s", decl_name.getAsString().c_str());
959 clang::Selector sel = decl_name.getObjCSelector();
961 for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) {
962 llvm::StringRef r = sel.getNameForSlot(i);
963 ss.Printf("%s:", r.str().c_str());
968 if (ss.GetString().contains("$__lldb"))
969 return; // we don't need any results
971 ConstString selector_name(ss.GetString());
974 "ClangASTSource::FindObjCMethodDecls on (ASTContext*){0} '{1}' "
975 "for selector [{2} {3}]",
976 m_ast_context, m_clang_ast_context->getDisplayName(),
977 interface_decl->getName(), selector_name);
978 SymbolContextList sc_list;
980 const bool include_symbols = false;
981 const bool include_inlines = false;
983 std::string interface_name = interface_decl->getNameAsString();
987 ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString());
989 ConstString instance_method_name(ms.GetString());
992 m_target->GetImages().FindFunctions(
993 instance_method_name, lldb::eFunctionNameTypeFull, include_symbols,
994 include_inlines, sc_list);
996 if (sc_list.GetSize())
1000 ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString());
1002 ConstString class_method_name(ms.GetString());
1005 m_target->GetImages().FindFunctions(
1006 class_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1007 include_inlines, sc_list);
1009 if (sc_list.GetSize())
1012 // Fall back and check for methods in categories. If we find methods this
1013 // way, we need to check that they're actually in categories on the desired
1016 SymbolContextList candidate_sc_list;
1018 m_target->GetImages().FindFunctions(
1019 selector_name, lldb::eFunctionNameTypeSelector, include_symbols,
1020 include_inlines, candidate_sc_list);
1022 for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) {
1023 SymbolContext candidate_sc;
1025 if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc))
1028 if (!candidate_sc.function)
1031 const char *candidate_name = candidate_sc.function->GetName().AsCString();
1033 const char *cursor = candidate_name;
1035 if (*cursor != '+' && *cursor != '-')
1045 size_t interface_len = interface_name.length();
1047 if (strncmp(cursor, interface_name.c_str(), interface_len))
1050 cursor += interface_len;
1052 if (*cursor == ' ' || *cursor == '(')
1053 sc_list.Append(candidate_sc);
1057 if (sc_list.GetSize()) {
1058 // We found a good function symbol. Use that.
1060 for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) {
1063 if (!sc_list.GetContextAtIndex(i, sc))
1069 CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext();
1070 if (!function_decl_ctx)
1073 ObjCMethodDecl *method_decl =
1074 TypeSystemClang::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1079 ObjCInterfaceDecl *found_interface_decl =
1080 method_decl->getClassInterface();
1082 if (!found_interface_decl)
1085 if (found_interface_decl->getName() == interface_decl->getName()) {
1086 Decl *copied_decl = CopyDecl(method_decl);
1091 ObjCMethodDecl *copied_method_decl =
1092 dyn_cast<ObjCMethodDecl>(copied_decl);
1094 if (!copied_method_decl)
1097 LLDB_LOG(log, " CAS::FOMD found (in symbols)\n{0}",
1098 ClangUtil::DumpDecl(copied_method_decl));
1100 context.AddNamedDecl(copied_method_decl);
1107 // Try the debug information.
1110 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1111 const_cast<ObjCInterfaceDecl *>(interface_decl));
1113 if (!complete_interface_decl)
1116 // We found the complete interface. The runtime never needs to be queried
1117 // in this scenario.
1119 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1120 complete_interface_decl);
1122 if (complete_interface_decl == interface_decl)
1123 break; // already checked this one
1126 "CAS::FOPD trying origin "
1127 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1128 complete_interface_decl, &complete_iface_decl->getASTContext());
1130 FindObjCMethodDeclsWithOrigin(context, complete_interface_decl,
1137 // Check the modules only if the debug information didn't have a complete
1140 if (ClangModulesDeclVendor *modules_decl_vendor =
1141 m_target->GetClangModulesDeclVendor()) {
1142 ConstString interface_name(interface_decl->getNameAsString().c_str());
1143 bool append = false;
1144 uint32_t max_matches = 1;
1145 std::vector<clang::NamedDecl *> decls;
1147 if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches,
1151 ObjCInterfaceDecl *interface_decl_from_modules =
1152 dyn_cast<ObjCInterfaceDecl>(decls[0]);
1154 if (!interface_decl_from_modules)
1157 if (FindObjCMethodDeclsWithOrigin(context, interface_decl_from_modules,
1164 // Check the runtime only if the debug information didn't have a complete
1165 // interface and the modules don't get us anywhere.
1167 lldb::ProcessSP process(m_target->GetProcessSP());
1172 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1174 if (!language_runtime)
1177 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1182 ConstString interface_name(interface_decl->getNameAsString().c_str());
1183 bool append = false;
1184 uint32_t max_matches = 1;
1185 std::vector<clang::NamedDecl *> decls;
1187 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1188 if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches,
1192 ObjCInterfaceDecl *runtime_interface_decl =
1193 dyn_cast<ObjCInterfaceDecl>(decls[0]);
1195 if (!runtime_interface_decl)
1198 FindObjCMethodDeclsWithOrigin(context, runtime_interface_decl,
1203 static bool FindObjCPropertyAndIvarDeclsWithOrigin(
1204 NameSearchContext &context, ClangASTSource &source,
1205 DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) {
1206 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1208 if (origin_iface_decl.IsInvalid())
1211 std::string name_str = context.m_decl_name.getAsString();
1212 StringRef name(name_str);
1213 IdentifierInfo &name_identifier(
1214 origin_iface_decl->getASTContext().Idents.get(name));
1216 DeclFromUser<ObjCPropertyDecl> origin_property_decl(
1217 origin_iface_decl->FindPropertyDeclaration(
1218 &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance));
1222 if (origin_property_decl.IsValid()) {
1223 DeclFromParser<ObjCPropertyDecl> parser_property_decl(
1224 origin_property_decl.Import(source));
1225 if (parser_property_decl.IsValid()) {
1226 LLDB_LOG(log, " CAS::FOPD found\n{0}",
1227 ClangUtil::DumpDecl(parser_property_decl.decl));
1229 context.AddNamedDecl(parser_property_decl.decl);
1234 DeclFromUser<ObjCIvarDecl> origin_ivar_decl(
1235 origin_iface_decl->getIvarDecl(&name_identifier));
1237 if (origin_ivar_decl.IsValid()) {
1238 DeclFromParser<ObjCIvarDecl> parser_ivar_decl(
1239 origin_ivar_decl.Import(source));
1240 if (parser_ivar_decl.IsValid()) {
1241 LLDB_LOG(log, " CAS::FOPD found\n{0}",
1242 ClangUtil::DumpDecl(parser_ivar_decl.decl));
1244 context.AddNamedDecl(parser_ivar_decl.decl);
1252 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) {
1253 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1255 DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl(
1256 cast<ObjCInterfaceDecl>(context.m_decl_context));
1257 DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl(
1258 parser_iface_decl.GetOrigin(*this));
1260 ConstString class_name(parser_iface_decl->getNameAsString().c_str());
1263 "ClangASTSource::FindObjCPropertyAndIvarDecls on "
1264 "(ASTContext*){0} '{1}' for '{2}.{3}'",
1265 m_ast_context, m_clang_ast_context->getDisplayName(),
1266 parser_iface_decl->getName(), context.m_decl_name.getAsString());
1268 if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this, origin_iface_decl))
1272 "CAS::FOPD couldn't find the property on origin "
1273 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}, searching "
1275 origin_iface_decl.decl, &origin_iface_decl->getASTContext());
1277 SymbolContext null_sc;
1281 ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1282 const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl));
1284 if (!complete_interface_decl)
1287 // We found the complete interface. The runtime never needs to be queried
1288 // in this scenario.
1290 DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1291 complete_interface_decl);
1293 if (complete_iface_decl.decl == origin_iface_decl.decl)
1294 break; // already checked this one
1297 "CAS::FOPD trying origin "
1298 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1299 complete_iface_decl.decl, &complete_iface_decl->getASTContext());
1301 FindObjCPropertyAndIvarDeclsWithOrigin(context, *this, complete_iface_decl);
1307 // Check the modules only if the debug information didn't have a complete
1310 ClangModulesDeclVendor *modules_decl_vendor =
1311 m_target->GetClangModulesDeclVendor();
1313 if (!modules_decl_vendor)
1316 bool append = false;
1317 uint32_t max_matches = 1;
1318 std::vector<clang::NamedDecl *> decls;
1320 if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1323 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules(
1324 dyn_cast<ObjCInterfaceDecl>(decls[0]));
1326 if (!interface_decl_from_modules.IsValid())
1330 "CAS::FOPD[{0}] trying module "
1331 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1332 interface_decl_from_modules.decl,
1333 &interface_decl_from_modules->getASTContext());
1335 if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this,
1336 interface_decl_from_modules))
1341 // Check the runtime only if the debug information didn't have a complete
1342 // interface and nothing was in the modules.
1344 lldb::ProcessSP process(m_target->GetProcessSP());
1349 ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1351 if (!language_runtime)
1354 DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1359 bool append = false;
1360 uint32_t max_matches = 1;
1361 std::vector<clang::NamedDecl *> decls;
1363 auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1364 if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1367 DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime(
1368 dyn_cast<ObjCInterfaceDecl>(decls[0]));
1370 if (!interface_decl_from_runtime.IsValid())
1374 "CAS::FOPD[{0}] trying runtime "
1375 "(ObjCInterfaceDecl*){0}/(ASTContext*){1}...",
1376 interface_decl_from_runtime.decl,
1377 &interface_decl_from_runtime->getASTContext());
1379 if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this,
1380 interface_decl_from_runtime))
1385 void ClangASTSource::LookupInNamespace(NameSearchContext &context) {
1386 const NamespaceDecl *namespace_context =
1387 dyn_cast<NamespaceDecl>(context.m_decl_context);
1389 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1391 ClangASTImporter::NamespaceMapSP namespace_map =
1392 m_ast_importer_sp->GetNamespaceMap(namespace_context);
1394 LLDB_LOGV(log, " CAS::FEVD Inspecting namespace map {0} ({1} entries)",
1395 namespace_map.get(), namespace_map->size());
1400 for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
1401 e = namespace_map->end();
1403 LLDB_LOG(log, " CAS::FEVD Searching namespace {0} in module {1}",
1404 i->second.GetName(), i->first->GetFileSpec().GetFilename());
1406 FindExternalVisibleDecls(context, i->first, i->second);
1410 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap;
1411 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap;
1413 template <class D, class O>
1414 static bool ImportOffsetMap(llvm::DenseMap<const D *, O> &destination_map,
1415 llvm::DenseMap<const D *, O> &source_map,
1416 ClangASTSource &source) {
1417 // When importing fields into a new record, clang has a hard requirement that
1418 // fields be imported in field offset order. Since they are stored in a
1419 // DenseMap with a pointer as the key type, this means we cannot simply
1420 // iterate over the map, as the order will be non-deterministic. Instead we
1421 // have to sort by the offset and then insert in sorted order.
1422 typedef llvm::DenseMap<const D *, O> MapType;
1423 typedef typename MapType::value_type PairType;
1424 std::vector<PairType> sorted_items;
1425 sorted_items.reserve(source_map.size());
1426 sorted_items.assign(source_map.begin(), source_map.end());
1427 llvm::sort(sorted_items.begin(), sorted_items.end(),
1428 [](const PairType &lhs, const PairType &rhs) {
1429 return lhs.second < rhs.second;
1432 for (const auto &item : sorted_items) {
1433 DeclFromUser<D> user_decl(const_cast<D *>(item.first));
1434 DeclFromParser<D> parser_decl(user_decl.Import(source));
1435 if (parser_decl.IsInvalid())
1437 destination_map.insert(
1438 std::pair<const D *, O>(parser_decl.decl, item.second));
1444 template <bool IsVirtual>
1445 bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
1446 DeclFromUser<const CXXRecordDecl> &record,
1447 BaseOffsetMap &base_offsets) {
1448 for (CXXRecordDecl::base_class_const_iterator
1449 bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
1450 be = (IsVirtual ? record->vbases_end() : record->bases_end());
1452 if (!IsVirtual && bi->isVirtual())
1455 const clang::Type *origin_base_type = bi->getType().getTypePtr();
1456 const clang::RecordType *origin_base_record_type =
1457 origin_base_type->getAs<RecordType>();
1459 if (!origin_base_record_type)
1462 DeclFromUser<RecordDecl> origin_base_record(
1463 origin_base_record_type->getDecl());
1465 if (origin_base_record.IsInvalid())
1468 DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
1469 DynCast<CXXRecordDecl>(origin_base_record));
1471 if (origin_base_cxx_record.IsInvalid())
1474 CharUnits base_offset;
1478 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
1481 record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
1483 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
1484 origin_base_cxx_record.decl, base_offset));
1490 bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size,
1491 uint64_t &alignment,
1492 FieldOffsetMap &field_offsets,
1493 BaseOffsetMap &base_offsets,
1494 BaseOffsetMap &virtual_base_offsets) {
1496 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1499 "LayoutRecordType on (ASTContext*){0} '{1}' for (RecordDecl*)"
1500 "{3} [name = '{4}']",
1501 m_ast_context, m_clang_ast_context->getDisplayName(), record,
1504 DeclFromParser<const RecordDecl> parser_record(record);
1505 DeclFromUser<const RecordDecl> origin_record(
1506 parser_record.GetOrigin(*this));
1508 if (origin_record.IsInvalid())
1511 FieldOffsetMap origin_field_offsets;
1512 BaseOffsetMap origin_base_offsets;
1513 BaseOffsetMap origin_virtual_base_offsets;
1515 TypeSystemClang::GetCompleteDecl(
1516 &origin_record->getASTContext(),
1517 const_cast<RecordDecl *>(origin_record.decl));
1519 clang::RecordDecl *definition = origin_record.decl->getDefinition();
1520 if (!definition || !definition->isCompleteDefinition())
1523 const ASTRecordLayout &record_layout(
1524 origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
1526 int field_idx = 0, field_count = record_layout.getFieldCount();
1528 for (RecordDecl::field_iterator fi = origin_record->field_begin(),
1529 fe = origin_record->field_end();
1531 if (field_idx >= field_count)
1532 return false; // Layout didn't go well. Bail out.
1534 uint64_t field_offset = record_layout.getFieldOffset(field_idx);
1536 origin_field_offsets.insert(
1537 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
1542 lldbassert(&record->getASTContext() == m_ast_context);
1544 DeclFromUser<const CXXRecordDecl> origin_cxx_record(
1545 DynCast<const CXXRecordDecl>(origin_record));
1547 if (origin_cxx_record.IsValid()) {
1548 if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
1549 origin_base_offsets) ||
1550 !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
1551 origin_virtual_base_offsets))
1555 if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) ||
1556 !ImportOffsetMap(base_offsets, origin_base_offsets, *this) ||
1557 !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets,
1561 size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth();
1562 alignment = record_layout.getAlignment().getQuantity() *
1563 m_ast_context->getCharWidth();
1566 LLDB_LOG(log, "LRT returned:");
1567 LLDB_LOG(log, "LRT Original = (RecordDecl*)%p",
1568 static_cast<const void *>(origin_record.decl));
1569 LLDB_LOG(log, "LRT Size = %" PRId64, size);
1570 LLDB_LOG(log, "LRT Alignment = %" PRId64, alignment);
1571 LLDB_LOG(log, "LRT Fields:");
1572 for (RecordDecl::field_iterator fi = record->field_begin(),
1573 fe = record->field_end();
1576 "LRT (FieldDecl*){0}, Name = '{1}', Offset = {2} bits",
1577 *fi, fi->getName(), field_offsets[*fi]);
1579 DeclFromParser<const CXXRecordDecl> parser_cxx_record =
1580 DynCast<const CXXRecordDecl>(parser_record);
1581 if (parser_cxx_record.IsValid()) {
1582 LLDB_LOG(log, "LRT Bases:");
1583 for (CXXRecordDecl::base_class_const_iterator
1584 bi = parser_cxx_record->bases_begin(),
1585 be = parser_cxx_record->bases_end();
1587 bool is_virtual = bi->isVirtual();
1589 QualType base_type = bi->getType();
1590 const RecordType *base_record_type = base_type->getAs<RecordType>();
1591 DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
1592 DeclFromParser<CXXRecordDecl> base_cxx_record =
1593 DynCast<CXXRecordDecl>(base_record);
1596 "LRT {0}(CXXRecordDecl*){1}, Name = '{2}', Offset = "
1598 (is_virtual ? "Virtual " : ""), base_cxx_record.decl,
1599 base_cxx_record.decl->getName(),
1601 ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1602 : base_offsets[base_cxx_record.decl].getQuantity()));
1605 LLDB_LOG(log, "LRD Not a CXXRecord, so no bases");
1612 void ClangASTSource::CompleteNamespaceMap(
1613 ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name,
1614 ClangASTImporter::NamespaceMapSP &parent_map) const {
1616 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1619 if (parent_map && parent_map->size())
1621 "CompleteNamespaceMap on (ASTContext*){0} '{1}' Searching "
1622 "for namespace {2} in namespace {3}",
1623 m_ast_context, m_clang_ast_context->getDisplayName(), name,
1624 parent_map->begin()->second.GetName());
1627 "CompleteNamespaceMap on (ASTContext*){0} '{1}' Searching "
1628 "for namespace {2}",
1629 m_ast_context, m_clang_ast_context->getDisplayName(), name);
1633 for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1634 e = parent_map->end();
1636 CompilerDeclContext found_namespace_decl;
1638 lldb::ModuleSP module_sp = i->first;
1639 CompilerDeclContext module_parent_namespace_decl = i->second;
1641 SymbolFile *symbol_file = module_sp->GetSymbolFile();
1646 found_namespace_decl =
1647 symbol_file->FindNamespace(name, module_parent_namespace_decl);
1649 if (!found_namespace_decl)
1652 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1653 module_sp, found_namespace_decl));
1655 LLDB_LOG(log, " CMN Found namespace {0} in module {1}", name,
1656 module_sp->GetFileSpec().GetFilename());
1659 const ModuleList &target_images = m_target->GetImages();
1660 std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
1662 CompilerDeclContext null_namespace_decl;
1664 for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
1665 lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
1670 CompilerDeclContext found_namespace_decl;
1672 SymbolFile *symbol_file = image->GetSymbolFile();
1677 found_namespace_decl =
1678 symbol_file->FindNamespace(name, null_namespace_decl);
1680 if (!found_namespace_decl)
1683 namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1684 image, found_namespace_decl));
1686 LLDB_LOG(log, " CMN[{0}] Found namespace {0} in module {1}", name,
1687 image->GetFileSpec().GetFilename());
1692 NamespaceDecl *ClangASTSource::AddNamespace(
1693 NameSearchContext &context,
1694 ClangASTImporter::NamespaceMapSP &namespace_decls) {
1695 if (!namespace_decls)
1698 const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1700 clang::ASTContext *src_ast =
1701 TypeSystemClang::DeclContextGetTypeSystemClang(namespace_decl);
1704 clang::NamespaceDecl *src_namespace_decl =
1705 TypeSystemClang::DeclContextGetAsNamespaceDecl(namespace_decl);
1707 if (!src_namespace_decl)
1710 Decl *copied_decl = CopyDecl(src_namespace_decl);
1715 NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1717 if (!copied_namespace_decl)
1720 context.m_decls.push_back(copied_namespace_decl);
1722 m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1725 return dyn_cast<NamespaceDecl>(copied_decl);
1728 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) {
1729 return m_ast_importer_sp->CopyDecl(m_ast_context, src_decl);
1732 ClangASTImporter::DeclOrigin ClangASTSource::GetDeclOrigin(const clang::Decl *decl) {
1733 return m_ast_importer_sp->GetDeclOrigin(decl);
1736 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) {
1737 TypeSystemClang *src_ast =
1738 llvm::dyn_cast_or_null<TypeSystemClang>(src_type.GetTypeSystem());
1739 if (src_ast == nullptr)
1740 return CompilerType();
1742 QualType copied_qual_type = ClangUtil::GetQualType(
1743 m_ast_importer_sp->CopyType(*m_clang_ast_context, src_type));
1745 if (copied_qual_type.getAsOpaquePtr() &&
1746 copied_qual_type->getCanonicalTypeInternal().isNull())
1747 // this shouldn't happen, but we're hardening because the AST importer
1748 // seems to be generating bad types on occasion.
1749 return CompilerType();
1751 return m_clang_ast_context->GetType(copied_qual_type);