1 //===-- ClangASTSource.cpp ------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ClangASTSource.h"
10 
11 #include "ClangDeclVendor.h"
12 #include "ClangModulesDeclVendor.h"
13 
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 
25 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
26 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
27 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
28 
29 #include <memory>
30 #include <vector>
31 
32 using namespace clang;
33 using namespace lldb_private;
34 
35 // Scoped class that will remove an active lexical decl from the set when it
36 // goes out of scope.
37 namespace {
38 class ScopedLexicalDeclEraser {
39 public:
40   ScopedLexicalDeclEraser(std::set<const clang::Decl *> &decls,
41                           const clang::Decl *decl)
42       : m_active_lexical_decls(decls), m_decl(decl) {}
43 
44   ~ScopedLexicalDeclEraser() { m_active_lexical_decls.erase(m_decl); }
45 
46 private:
47   std::set<const clang::Decl *> &m_active_lexical_decls;
48   const clang::Decl *m_decl;
49 };
50 }
51 
52 ClangASTSource::ClangASTSource(
53     const lldb::TargetSP &target,
54     const std::shared_ptr<ClangASTImporter> &importer)
55     : m_import_in_progress(false), m_lookups_enabled(false), m_target(target),
56       m_ast_context(nullptr), m_ast_importer_sp(importer),
57       m_active_lexical_decls(), m_active_lookups() {
58   assert(m_ast_importer_sp && "No ClangASTImporter passed to ClangASTSource?");
59 }
60 
61 void ClangASTSource::InstallASTContext(TypeSystemClang &clang_ast_context) {
62   m_ast_context = &clang_ast_context.getASTContext();
63   m_clang_ast_context = &clang_ast_context;
64   m_file_manager = &m_ast_context->getSourceManager().getFileManager();
65   m_ast_importer_sp->InstallMapCompleter(m_ast_context, *this);
66 }
67 
68 ClangASTSource::~ClangASTSource() {
69   m_ast_importer_sp->ForgetDestination(m_ast_context);
70 
71   if (!m_target)
72     return;
73   // We are in the process of destruction, don't create clang ast context on
74   // demand by passing false to
75   // Target::GetScratchTypeSystemClang(create_on_demand).
76   TypeSystemClang *scratch_clang_ast_context =
77       TypeSystemClang::GetScratch(*m_target, false);
78 
79   if (!scratch_clang_ast_context)
80     return;
81 
82   clang::ASTContext &scratch_ast_context =
83       scratch_clang_ast_context->getASTContext();
84 
85   if (m_ast_context != &scratch_ast_context && m_ast_importer_sp)
86     m_ast_importer_sp->ForgetSource(&scratch_ast_context, m_ast_context);
87 }
88 
89 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) {
90   if (!m_ast_context)
91     return;
92 
93   m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
94   m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
95 }
96 
97 // The core lookup interface.
98 bool ClangASTSource::FindExternalVisibleDeclsByName(
99     const DeclContext *decl_ctx, DeclarationName clang_decl_name) {
100   if (!m_ast_context) {
101     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
102     return false;
103   }
104 
105   if (GetImportInProgress()) {
106     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
107     return false;
108   }
109 
110   std::string decl_name(clang_decl_name.getAsString());
111 
112   //    if (m_decl_map.DoingASTImport ())
113   //      return DeclContext::lookup_result();
114   //
115   switch (clang_decl_name.getNameKind()) {
116   // Normal identifiers.
117   case DeclarationName::Identifier: {
118     clang::IdentifierInfo *identifier_info =
119         clang_decl_name.getAsIdentifierInfo();
120 
121     if (!identifier_info || identifier_info->getBuiltinID() != 0) {
122       SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
123       return false;
124     }
125   } break;
126 
127   // Operator names.
128   case DeclarationName::CXXOperatorName:
129   case DeclarationName::CXXLiteralOperatorName:
130     break;
131 
132   // Using directives found in this context.
133   // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
134   case DeclarationName::CXXUsingDirective:
135     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
136     return false;
137 
138   case DeclarationName::ObjCZeroArgSelector:
139   case DeclarationName::ObjCOneArgSelector:
140   case DeclarationName::ObjCMultiArgSelector: {
141     llvm::SmallVector<NamedDecl *, 1> method_decls;
142 
143     NameSearchContext method_search_context(*m_clang_ast_context, method_decls,
144                                             clang_decl_name, decl_ctx);
145 
146     FindObjCMethodDecls(method_search_context);
147 
148     SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
149     return (method_decls.size() > 0);
150   }
151   // These aren't possible in the global context.
152   case DeclarationName::CXXConstructorName:
153   case DeclarationName::CXXDestructorName:
154   case DeclarationName::CXXConversionFunctionName:
155   case DeclarationName::CXXDeductionGuideName:
156     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
157     return false;
158   }
159 
160   if (!GetLookupsEnabled()) {
161     // Wait until we see a '$' at the start of a name before we start doing any
162     // lookups so we can avoid lookup up all of the builtin types.
163     if (!decl_name.empty() && decl_name[0] == '$') {
164       SetLookupsEnabled(true);
165     } else {
166       SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
167       return false;
168     }
169   }
170 
171   ConstString const_decl_name(decl_name.c_str());
172 
173   const char *uniqued_const_decl_name = const_decl_name.GetCString();
174   if (m_active_lookups.find(uniqued_const_decl_name) !=
175       m_active_lookups.end()) {
176     // We are currently looking up this name...
177     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
178     return false;
179   }
180   m_active_lookups.insert(uniqued_const_decl_name);
181   //  static uint32_t g_depth = 0;
182   //  ++g_depth;
183   //  printf("[%5u] FindExternalVisibleDeclsByName() \"%s\"\n", g_depth,
184   //  uniqued_const_decl_name);
185   llvm::SmallVector<NamedDecl *, 4> name_decls;
186   NameSearchContext name_search_context(*m_clang_ast_context, name_decls,
187                                         clang_decl_name, decl_ctx);
188   FindExternalVisibleDecls(name_search_context);
189   SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
190   //  --g_depth;
191   m_active_lookups.erase(uniqued_const_decl_name);
192   return (name_decls.size() != 0);
193 }
194 
195 void ClangASTSource::CompleteType(TagDecl *tag_decl) {
196   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
197 
198   if (log) {
199     LLDB_LOG(log,
200              "    CompleteTagDecl on (ASTContext*){1} Completing "
201              "(TagDecl*){2} named {3}",
202              m_clang_ast_context->getDisplayName(), tag_decl,
203              tag_decl->getName());
204 
205     LLDB_LOG(log, "      CTD Before:\n{0}", ClangUtil::DumpDecl(tag_decl));
206   }
207 
208   auto iter = m_active_lexical_decls.find(tag_decl);
209   if (iter != m_active_lexical_decls.end())
210     return;
211   m_active_lexical_decls.insert(tag_decl);
212   ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
213 
214   if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) {
215     // We couldn't complete the type.  Maybe there's a definition somewhere
216     // else that can be completed.
217 
218     LLDB_LOG(log, "      CTD Type could not be completed in the module in "
219                   "which it was first found.");
220 
221     bool found = false;
222 
223     DeclContext *decl_ctx = tag_decl->getDeclContext();
224 
225     if (const NamespaceDecl *namespace_context =
226             dyn_cast<NamespaceDecl>(decl_ctx)) {
227       ClangASTImporter::NamespaceMapSP namespace_map =
228           m_ast_importer_sp->GetNamespaceMap(namespace_context);
229 
230       LLDB_LOGV(log, "      CTD Inspecting namespace map{1} ({2} entries)",
231                 namespace_map.get(), namespace_map->size());
232 
233       if (!namespace_map)
234         return;
235 
236       for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
237                                                     e = namespace_map->end();
238            i != e && !found; ++i) {
239         LLDB_LOG(log, "      CTD Searching namespace {1} in module {2}",
240                  i->second.GetName(), i->first->GetFileSpec().GetFilename());
241 
242         TypeList types;
243 
244         ConstString name(tag_decl->getName().str().c_str());
245 
246         i->first->FindTypesInNamespace(name, i->second, UINT32_MAX, types);
247 
248         for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
249           lldb::TypeSP type = types.GetTypeAtIndex(ti);
250 
251           if (!type)
252             continue;
253 
254           CompilerType clang_type(type->GetFullCompilerType());
255 
256           if (!ClangUtil::IsClangType(clang_type))
257             continue;
258 
259           const TagType *tag_type =
260               ClangUtil::GetQualType(clang_type)->getAs<TagType>();
261 
262           if (!tag_type)
263             continue;
264 
265           TagDecl *candidate_tag_decl =
266               const_cast<TagDecl *>(tag_type->getDecl());
267 
268           if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
269                                                            candidate_tag_decl))
270             found = true;
271         }
272       }
273     } else {
274       TypeList types;
275 
276       ConstString name(tag_decl->getName().str().c_str());
277 
278       const ModuleList &module_list = m_target->GetImages();
279 
280       bool exact_match = false;
281       llvm::DenseSet<SymbolFile *> searched_symbol_files;
282       module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX,
283                             searched_symbol_files, types);
284 
285       for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
286         lldb::TypeSP type = types.GetTypeAtIndex(ti);
287 
288         if (!type)
289           continue;
290 
291         CompilerType clang_type(type->GetFullCompilerType());
292 
293         if (!ClangUtil::IsClangType(clang_type))
294           continue;
295 
296         const TagType *tag_type =
297             ClangUtil::GetQualType(clang_type)->getAs<TagType>();
298 
299         if (!tag_type)
300           continue;
301 
302         TagDecl *candidate_tag_decl =
303             const_cast<TagDecl *>(tag_type->getDecl());
304 
305         // We have found a type by basename and we need to make sure the decl
306         // contexts are the same before we can try to complete this type with
307         // another
308         if (!TypeSystemClang::DeclsAreEquivalent(tag_decl, candidate_tag_decl))
309           continue;
310 
311         if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
312                                                          candidate_tag_decl))
313           found = true;
314       }
315     }
316   }
317 
318   LLDB_LOG(log, "      [CTD] After:\n{0}", ClangUtil::DumpDecl(tag_decl));
319 }
320 
321 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
322   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
323 
324   LLDB_LOG(log,
325            "    [CompleteObjCInterfaceDecl] on (ASTContext*){0} '{1}' "
326            "Completing an ObjCInterfaceDecl named {1}",
327            m_ast_context, m_clang_ast_context->getDisplayName(),
328            interface_decl->getName());
329   LLDB_LOG(log, "      [COID] Before:\n{0}",
330            ClangUtil::DumpDecl(interface_decl));
331 
332   ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
333 
334   if (original.Valid()) {
335     if (ObjCInterfaceDecl *original_iface_decl =
336             dyn_cast<ObjCInterfaceDecl>(original.decl)) {
337       ObjCInterfaceDecl *complete_iface_decl =
338           GetCompleteObjCInterface(original_iface_decl);
339 
340       if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
341         m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
342       }
343     }
344   }
345 
346   m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
347 
348   if (interface_decl->getSuperClass() &&
349       interface_decl->getSuperClass() != interface_decl)
350     CompleteType(interface_decl->getSuperClass());
351 
352   LLDB_LOG(log, "      [COID] After:");
353   LLDB_LOG(log, "      [COID] {0}", ClangUtil::DumpDecl(interface_decl));
354 }
355 
356 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
357     const clang::ObjCInterfaceDecl *interface_decl) {
358   lldb::ProcessSP process(m_target->GetProcessSP());
359 
360   if (!process)
361     return nullptr;
362 
363   ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
364 
365   if (!language_runtime)
366     return nullptr;
367 
368   ConstString class_name(interface_decl->getNameAsString().c_str());
369 
370   lldb::TypeSP complete_type_sp(
371       language_runtime->LookupInCompleteClassCache(class_name));
372 
373   if (!complete_type_sp)
374     return nullptr;
375 
376   TypeFromUser complete_type =
377       TypeFromUser(complete_type_sp->GetFullCompilerType());
378   lldb::opaque_compiler_type_t complete_opaque_type =
379       complete_type.GetOpaqueQualType();
380 
381   if (!complete_opaque_type)
382     return nullptr;
383 
384   const clang::Type *complete_clang_type =
385       QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
386   const ObjCInterfaceType *complete_interface_type =
387       dyn_cast<ObjCInterfaceType>(complete_clang_type);
388 
389   if (!complete_interface_type)
390     return nullptr;
391 
392   ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
393 
394   return complete_iface_decl;
395 }
396 
397 void ClangASTSource::FindExternalLexicalDecls(
398     const DeclContext *decl_context,
399     llvm::function_ref<bool(Decl::Kind)> predicate,
400     llvm::SmallVectorImpl<Decl *> &decls) {
401 
402   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
403 
404   const Decl *context_decl = dyn_cast<Decl>(decl_context);
405 
406   if (!context_decl)
407     return;
408 
409   auto iter = m_active_lexical_decls.find(context_decl);
410   if (iter != m_active_lexical_decls.end())
411     return;
412   m_active_lexical_decls.insert(context_decl);
413   ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
414 
415   if (log) {
416     if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
417       LLDB_LOG(log,
418                "FindExternalLexicalDecls on (ASTContext*){1} '{2}' in "
419                "'{3}' (%sDecl*){4}",
420                m_ast_context, m_clang_ast_context->getDisplayName(),
421                context_named_decl->getNameAsString().c_str(),
422                context_decl->getDeclKindName(),
423                static_cast<const void *>(context_decl));
424     else if (context_decl)
425       LLDB_LOG(log,
426                "FindExternalLexicalDecls on (ASTContext*){1} '{2}' in "
427                "({3}Decl*){4}",
428                m_ast_context, m_clang_ast_context->getDisplayName(),
429                context_decl->getDeclKindName(),
430                static_cast<const void *>(context_decl));
431     else
432       LLDB_LOG(log,
433                "FindExternalLexicalDecls on (ASTContext*){1} '{2}' in a "
434                "NULL context",
435                m_ast_context, m_clang_ast_context->getDisplayName());
436   }
437 
438   ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(context_decl);
439 
440   if (!original.Valid())
441     return;
442 
443   LLDB_LOG(log, "  FELD Original decl {1} (Decl*){2:x}:\n{3}",
444            static_cast<void *>(original.ctx),
445            static_cast<void *>(original.decl),
446            ClangUtil::DumpDecl(original.decl));
447 
448   if (ObjCInterfaceDecl *original_iface_decl =
449           dyn_cast<ObjCInterfaceDecl>(original.decl)) {
450     ObjCInterfaceDecl *complete_iface_decl =
451         GetCompleteObjCInterface(original_iface_decl);
452 
453     if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
454       original.decl = complete_iface_decl;
455       original.ctx = &complete_iface_decl->getASTContext();
456 
457       m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
458     }
459   }
460 
461   if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original.decl)) {
462     ExternalASTSource *external_source = original.ctx->getExternalSource();
463 
464     if (external_source)
465       external_source->CompleteType(original_tag_decl);
466   }
467 
468   const DeclContext *original_decl_context =
469       dyn_cast<DeclContext>(original.decl);
470 
471   if (!original_decl_context)
472     return;
473 
474   // Indicates whether we skipped any Decls of the original DeclContext.
475   bool SkippedDecls = false;
476   for (DeclContext::decl_iterator iter = original_decl_context->decls_begin();
477        iter != original_decl_context->decls_end(); ++iter) {
478     Decl *decl = *iter;
479 
480     // The predicate function returns true if the passed declaration kind is
481     // the one we are looking for.
482     // See clang::ExternalASTSource::FindExternalLexicalDecls()
483     if (predicate(decl->getKind())) {
484       if (log) {
485         std::string ast_dump = ClangUtil::DumpDecl(decl);
486         if (const NamedDecl *context_named_decl =
487                 dyn_cast<NamedDecl>(context_decl))
488           LLDB_LOG(log, "  FELD Adding [to {1}Decl {2}] lexical {3}Decl {4}",
489                    context_named_decl->getDeclKindName(),
490                    context_named_decl->getName(), decl->getDeclKindName(),
491                    ast_dump);
492         else
493           LLDB_LOG(log, "  FELD Adding lexical {1}Decl {2}",
494                    decl->getDeclKindName(), ast_dump);
495       }
496 
497       Decl *copied_decl = CopyDecl(decl);
498 
499       if (!copied_decl)
500         continue;
501 
502       if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
503         QualType copied_field_type = copied_field->getType();
504 
505         m_ast_importer_sp->RequireCompleteType(copied_field_type);
506       }
507     } else {
508       SkippedDecls = true;
509     }
510   }
511 
512   // CopyDecl may build a lookup table which may set up ExternalLexicalStorage
513   // to false.  However, since we skipped some of the external Decls we must
514   // set it back!
515   if (SkippedDecls) {
516     decl_context->setHasExternalLexicalStorage(true);
517     // This sets HasLazyExternalLexicalLookups to true.  By setting this bit we
518     // ensure that the lookup table is rebuilt, which means the external source
519     // is consulted again when a clang::DeclContext::lookup is called.
520     const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable();
521   }
522 
523   return;
524 }
525 
526 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
527   assert(m_ast_context);
528 
529   const ConstString name(context.m_decl_name.getAsString().c_str());
530 
531   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
532 
533   if (log) {
534     if (!context.m_decl_context)
535       LLDB_LOG(log,
536                "ClangASTSource::FindExternalVisibleDecls on "
537                "(ASTContext*){1} '{2}' for '{3}' in a NULL DeclContext",
538                m_ast_context, m_clang_ast_context->getDisplayName(), name);
539     else if (const NamedDecl *context_named_decl =
540                  dyn_cast<NamedDecl>(context.m_decl_context))
541       LLDB_LOG(log,
542                "ClangASTSource::FindExternalVisibleDecls on "
543                "(ASTContext*){1} '{2}' for '{3}' in '{4}'",
544                m_ast_context, m_clang_ast_context->getDisplayName(), name,
545                context_named_decl->getName());
546     else
547       LLDB_LOG(log,
548                "ClangASTSource::FindExternalVisibleDecls on "
549                "(ASTContext*){1} '{2}' for '{3}' in a '{4}'",
550                m_ast_context, m_clang_ast_context->getDisplayName(), name,
551                context.m_decl_context->getDeclKindName());
552   }
553 
554   if (isa<NamespaceDecl>(context.m_decl_context)) {
555     LookupInNamespace(context);
556   } else if (isa<ObjCInterfaceDecl>(context.m_decl_context)) {
557     FindObjCPropertyAndIvarDecls(context);
558   } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) {
559     // we shouldn't be getting FindExternalVisibleDecls calls for these
560     return;
561   } else {
562     CompilerDeclContext namespace_decl;
563 
564     LLDB_LOG(log, "  CAS::FEVD Searching the root namespace");
565 
566     FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl);
567   }
568 
569   if (!context.m_namespace_map->empty()) {
570     if (log && log->GetVerbose())
571       LLDB_LOG(log, "  CAS::FEVD Registering namespace map {1} ({2} entries)",
572                context.m_namespace_map.get(), context.m_namespace_map->size());
573 
574     NamespaceDecl *clang_namespace_decl =
575         AddNamespace(context, context.m_namespace_map);
576 
577     if (clang_namespace_decl)
578       clang_namespace_decl->setHasExternalVisibleStorage();
579   }
580 }
581 
582 clang::Sema *ClangASTSource::getSema() {
583   return m_clang_ast_context->getSema();
584 }
585 
586 bool ClangASTSource::IgnoreName(const ConstString name,
587                                 bool ignore_all_dollar_names) {
588   static const ConstString id_name("id");
589   static const ConstString Class_name("Class");
590 
591   if (m_ast_context->getLangOpts().ObjC)
592     if (name == id_name || name == Class_name)
593       return true;
594 
595   StringRef name_string_ref = name.GetStringRef();
596 
597   // The ClangASTSource is not responsible for finding $-names.
598   return name_string_ref.empty() ||
599          (ignore_all_dollar_names && name_string_ref.startswith("$")) ||
600          name_string_ref.startswith("_$");
601 }
602 
603 void ClangASTSource::FindExternalVisibleDecls(
604     NameSearchContext &context, lldb::ModuleSP module_sp,
605     CompilerDeclContext &namespace_decl) {
606   assert(m_ast_context);
607 
608   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
609 
610   SymbolContextList sc_list;
611 
612   const ConstString name(context.m_decl_name.getAsString().c_str());
613   if (IgnoreName(name, true))
614     return;
615 
616   if (!m_target)
617     return;
618 
619   FillNamespaceMap(context, module_sp, namespace_decl);
620 
621   if (context.m_found_type)
622     return;
623 
624   TypeList types;
625   const bool exact_match = true;
626   llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
627   if (module_sp && namespace_decl)
628     module_sp->FindTypesInNamespace(name, namespace_decl, 1, types);
629   else {
630     m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1,
631                                     searched_symbol_files, types);
632   }
633 
634   if (size_t num_types = types.GetSize()) {
635     for (size_t ti = 0; ti < num_types; ++ti) {
636       lldb::TypeSP type_sp = types.GetTypeAtIndex(ti);
637 
638       if (log) {
639         const char *name_string = type_sp->GetName().GetCString();
640 
641         LLDB_LOG(log, "  CAS::FEVD Matching type found for \"{1}\": {2}", name,
642                  (name_string ? name_string : "<anonymous>"));
643       }
644 
645       CompilerType full_type = type_sp->GetFullCompilerType();
646 
647       CompilerType copied_clang_type(GuardedCopyType(full_type));
648 
649       if (!copied_clang_type) {
650         LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type");
651 
652         continue;
653       }
654 
655       context.AddTypeDecl(copied_clang_type);
656 
657       context.m_found_type = true;
658       break;
659     }
660   }
661 
662   if (!context.m_found_type) {
663     // Try the modules next.
664     FindDeclInModules(context, name);
665   }
666 
667   if (!context.m_found_type) {
668     FindDeclInObjCRuntime(context, name);
669   }
670 }
671 
672 void ClangASTSource::FillNamespaceMap(
673     NameSearchContext &context, lldb::ModuleSP module_sp,
674     const CompilerDeclContext &namespace_decl) {
675   const ConstString name(context.m_decl_name.getAsString().c_str());
676   if (IgnoreName(name, true))
677     return;
678 
679   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
680 
681   if (module_sp && namespace_decl) {
682     CompilerDeclContext found_namespace_decl;
683 
684     if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) {
685       found_namespace_decl = symbol_file->FindNamespace(name, namespace_decl);
686 
687       if (found_namespace_decl) {
688         context.m_namespace_map->push_back(
689             std::pair<lldb::ModuleSP, CompilerDeclContext>(
690                 module_sp, found_namespace_decl));
691 
692         LLDB_LOG(log, "  CAS::FEVD Found namespace {1} in module {2}", name,
693                  module_sp->GetFileSpec().GetFilename());
694       }
695     }
696     return;
697   }
698 
699   const ModuleList &target_images = m_target->GetImages();
700   std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
701 
702   for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
703     lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
704 
705     if (!image)
706       continue;
707 
708     CompilerDeclContext found_namespace_decl;
709 
710     SymbolFile *symbol_file = image->GetSymbolFile();
711 
712     if (!symbol_file)
713       continue;
714 
715     found_namespace_decl = symbol_file->FindNamespace(name, namespace_decl);
716 
717     if (found_namespace_decl) {
718       context.m_namespace_map->push_back(
719           std::pair<lldb::ModuleSP, CompilerDeclContext>(image,
720                                                          found_namespace_decl));
721 
722       LLDB_LOG(log, "  CAS::FEVD Found namespace {1} in module {2}", name,
723                image->GetFileSpec().GetFilename());
724     }
725   }
726 }
727 
728 template <class D> class TaggedASTDecl {
729 public:
730   TaggedASTDecl() : decl(nullptr) {}
731   TaggedASTDecl(D *_decl) : decl(_decl) {}
732   bool IsValid() const { return (decl != nullptr); }
733   bool IsInvalid() const { return !IsValid(); }
734   D *operator->() const { return decl; }
735   D *decl;
736 };
737 
738 template <class D2, template <class D> class TD, class D1>
739 TD<D2> DynCast(TD<D1> source) {
740   return TD<D2>(dyn_cast<D2>(source.decl));
741 }
742 
743 template <class D = Decl> class DeclFromParser;
744 template <class D = Decl> class DeclFromUser;
745 
746 template <class D> class DeclFromParser : public TaggedASTDecl<D> {
747 public:
748   DeclFromParser() : TaggedASTDecl<D>() {}
749   DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
750 
751   DeclFromUser<D> GetOrigin(ClangASTSource &source);
752 };
753 
754 template <class D> class DeclFromUser : public TaggedASTDecl<D> {
755 public:
756   DeclFromUser() : TaggedASTDecl<D>() {}
757   DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
758 
759   DeclFromParser<D> Import(ClangASTSource &source);
760 };
761 
762 template <class D>
763 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) {
764   ClangASTImporter::DeclOrigin origin = source.GetDeclOrigin(this->decl);
765   if (!origin.Valid())
766     return DeclFromUser<D>();
767   return DeclFromUser<D>(dyn_cast<D>(origin.decl));
768 }
769 
770 template <class D>
771 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) {
772   DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl));
773   if (parser_generic_decl.IsInvalid())
774     return DeclFromParser<D>();
775   return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl));
776 }
777 
778 bool ClangASTSource::FindObjCMethodDeclsWithOrigin(
779     NameSearchContext &context, ObjCInterfaceDecl *original_interface_decl,
780     const char *log_info) {
781   const DeclarationName &decl_name(context.m_decl_name);
782   clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
783 
784   Selector original_selector;
785 
786   if (decl_name.isObjCZeroArgSelector()) {
787     IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
788     original_selector = original_ctx->Selectors.getSelector(0, &ident);
789   } else if (decl_name.isObjCOneArgSelector()) {
790     const std::string &decl_name_string = decl_name.getAsString();
791     std::string decl_name_string_without_colon(decl_name_string.c_str(),
792                                                decl_name_string.length() - 1);
793     IdentifierInfo *ident =
794         &original_ctx->Idents.get(decl_name_string_without_colon);
795     original_selector = original_ctx->Selectors.getSelector(1, &ident);
796   } else {
797     SmallVector<IdentifierInfo *, 4> idents;
798 
799     clang::Selector sel = decl_name.getObjCSelector();
800 
801     unsigned num_args = sel.getNumArgs();
802 
803     for (unsigned i = 0; i != num_args; ++i) {
804       idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
805     }
806 
807     original_selector =
808         original_ctx->Selectors.getSelector(num_args, idents.data());
809   }
810 
811   DeclarationName original_decl_name(original_selector);
812 
813   llvm::SmallVector<NamedDecl *, 1> methods;
814 
815   TypeSystemClang::GetCompleteDecl(original_ctx, original_interface_decl);
816 
817   if (ObjCMethodDecl *instance_method_decl =
818           original_interface_decl->lookupInstanceMethod(original_selector)) {
819     methods.push_back(instance_method_decl);
820   } else if (ObjCMethodDecl *class_method_decl =
821                  original_interface_decl->lookupClassMethod(
822                      original_selector)) {
823     methods.push_back(class_method_decl);
824   }
825 
826   if (methods.empty()) {
827     return false;
828   }
829 
830   for (NamedDecl *named_decl : methods) {
831     if (!named_decl)
832       continue;
833 
834     ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
835 
836     if (!result_method)
837       continue;
838 
839     Decl *copied_decl = CopyDecl(result_method);
840 
841     if (!copied_decl)
842       continue;
843 
844     ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
845 
846     if (!copied_method_decl)
847       continue;
848 
849     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
850 
851     LLDB_LOG(log, "  CAS::FOMD found ({1}) {2}", log_info,
852              ClangUtil::DumpDecl(copied_method_decl));
853 
854     context.AddNamedDecl(copied_method_decl);
855   }
856 
857   return true;
858 }
859 
860 void ClangASTSource::FindDeclInModules(NameSearchContext &context,
861                                        ConstString name) {
862   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
863 
864   ClangModulesDeclVendor *modules_decl_vendor =
865       m_target->GetClangModulesDeclVendor();
866   if (!modules_decl_vendor)
867     return;
868 
869   bool append = false;
870   uint32_t max_matches = 1;
871   std::vector<clang::NamedDecl *> decls;
872 
873   if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
874     return;
875 
876   LLDB_LOG(log, "  CAS::FEVD Matching entity found for \"{1}\" in the modules",
877            name);
878 
879   clang::NamedDecl *const decl_from_modules = decls[0];
880 
881   if (llvm::isa<clang::TypeDecl>(decl_from_modules) ||
882       llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) ||
883       llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) {
884     clang::Decl *copied_decl = CopyDecl(decl_from_modules);
885     clang::NamedDecl *copied_named_decl =
886         copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
887 
888     if (!copied_named_decl) {
889       LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type from the modules");
890 
891       return;
892     }
893 
894     context.AddNamedDecl(copied_named_decl);
895 
896     context.m_found_type = true;
897   }
898 }
899 
900 void ClangASTSource::FindDeclInObjCRuntime(NameSearchContext &context,
901                                            ConstString name) {
902   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
903 
904   lldb::ProcessSP process(m_target->GetProcessSP());
905 
906   if (!process)
907     return;
908 
909   ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
910 
911   if (!language_runtime)
912     return;
913 
914   DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
915 
916   if (!decl_vendor)
917     return;
918 
919   bool append = false;
920   uint32_t max_matches = 1;
921   std::vector<clang::NamedDecl *> decls;
922 
923   auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
924   if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls))
925     return;
926 
927   LLDB_LOG(log, "  CAS::FEVD Matching type found for \"{0}\" in the runtime",
928            name);
929 
930   clang::Decl *copied_decl = CopyDecl(decls[0]);
931   clang::NamedDecl *copied_named_decl =
932       copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
933 
934   if (!copied_named_decl) {
935     LLDB_LOG(log, "  CAS::FEVD - Couldn't export a type from the runtime");
936 
937     return;
938   }
939 
940   context.AddNamedDecl(copied_named_decl);
941 }
942 
943 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
944   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
945 
946   const DeclarationName &decl_name(context.m_decl_name);
947   const DeclContext *decl_ctx(context.m_decl_context);
948 
949   const ObjCInterfaceDecl *interface_decl =
950       dyn_cast<ObjCInterfaceDecl>(decl_ctx);
951 
952   if (!interface_decl)
953     return;
954 
955   do {
956     ClangASTImporter::DeclOrigin original = m_ast_importer_sp->GetDeclOrigin(interface_decl);
957 
958     if (!original.Valid())
959       break;
960 
961     ObjCInterfaceDecl *original_interface_decl =
962         dyn_cast<ObjCInterfaceDecl>(original.decl);
963 
964     if (FindObjCMethodDeclsWithOrigin(context, original_interface_decl,
965                                       "at origin"))
966       return; // found it, no need to look any further
967   } while (false);
968 
969   StreamString ss;
970 
971   if (decl_name.isObjCZeroArgSelector()) {
972     ss.Printf("%s", decl_name.getAsString().c_str());
973   } else if (decl_name.isObjCOneArgSelector()) {
974     ss.Printf("%s", decl_name.getAsString().c_str());
975   } else {
976     clang::Selector sel = decl_name.getObjCSelector();
977 
978     for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) {
979       llvm::StringRef r = sel.getNameForSlot(i);
980       ss.Printf("%s:", r.str().c_str());
981     }
982   }
983   ss.Flush();
984 
985   if (ss.GetString().contains("$__lldb"))
986     return; // we don't need any results
987 
988   ConstString selector_name(ss.GetString());
989 
990   LLDB_LOG(log,
991            "ClangASTSource::FindObjCMethodDecls on (ASTContext*){1} '{2}' "
992            "for selector [{3} {4}]",
993            m_ast_context, m_clang_ast_context->getDisplayName(),
994            interface_decl->getName(), selector_name);
995   SymbolContextList sc_list;
996 
997   const bool include_symbols = false;
998   const bool include_inlines = false;
999 
1000   std::string interface_name = interface_decl->getNameAsString();
1001 
1002   do {
1003     StreamString ms;
1004     ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString());
1005     ms.Flush();
1006     ConstString instance_method_name(ms.GetString());
1007 
1008     sc_list.Clear();
1009     m_target->GetImages().FindFunctions(
1010         instance_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1011         include_inlines, sc_list);
1012 
1013     if (sc_list.GetSize())
1014       break;
1015 
1016     ms.Clear();
1017     ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString());
1018     ms.Flush();
1019     ConstString class_method_name(ms.GetString());
1020 
1021     sc_list.Clear();
1022     m_target->GetImages().FindFunctions(
1023         class_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1024         include_inlines, sc_list);
1025 
1026     if (sc_list.GetSize())
1027       break;
1028 
1029     // Fall back and check for methods in categories.  If we find methods this
1030     // way, we need to check that they're actually in categories on the desired
1031     // class.
1032 
1033     SymbolContextList candidate_sc_list;
1034 
1035     m_target->GetImages().FindFunctions(
1036         selector_name, lldb::eFunctionNameTypeSelector, include_symbols,
1037         include_inlines, candidate_sc_list);
1038 
1039     for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) {
1040       SymbolContext candidate_sc;
1041 
1042       if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc))
1043         continue;
1044 
1045       if (!candidate_sc.function)
1046         continue;
1047 
1048       const char *candidate_name = candidate_sc.function->GetName().AsCString();
1049 
1050       const char *cursor = candidate_name;
1051 
1052       if (*cursor != '+' && *cursor != '-')
1053         continue;
1054 
1055       ++cursor;
1056 
1057       if (*cursor != '[')
1058         continue;
1059 
1060       ++cursor;
1061 
1062       size_t interface_len = interface_name.length();
1063 
1064       if (strncmp(cursor, interface_name.c_str(), interface_len))
1065         continue;
1066 
1067       cursor += interface_len;
1068 
1069       if (*cursor == ' ' || *cursor == '(')
1070         sc_list.Append(candidate_sc);
1071     }
1072   } while (false);
1073 
1074   if (sc_list.GetSize()) {
1075     // We found a good function symbol.  Use that.
1076 
1077     for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) {
1078       SymbolContext sc;
1079 
1080       if (!sc_list.GetContextAtIndex(i, sc))
1081         continue;
1082 
1083       if (!sc.function)
1084         continue;
1085 
1086       CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext();
1087       if (!function_decl_ctx)
1088         continue;
1089 
1090       ObjCMethodDecl *method_decl =
1091           TypeSystemClang::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1092 
1093       if (!method_decl)
1094         continue;
1095 
1096       ObjCInterfaceDecl *found_interface_decl =
1097           method_decl->getClassInterface();
1098 
1099       if (!found_interface_decl)
1100         continue;
1101 
1102       if (found_interface_decl->getName() == interface_decl->getName()) {
1103         Decl *copied_decl = CopyDecl(method_decl);
1104 
1105         if (!copied_decl)
1106           continue;
1107 
1108         ObjCMethodDecl *copied_method_decl =
1109             dyn_cast<ObjCMethodDecl>(copied_decl);
1110 
1111         if (!copied_method_decl)
1112           continue;
1113 
1114         LLDB_LOG(log, "  CAS::FOMD found (in symbols)\n{1}",
1115                  ClangUtil::DumpDecl(copied_method_decl));
1116 
1117         context.AddNamedDecl(copied_method_decl);
1118       }
1119     }
1120 
1121     return;
1122   }
1123 
1124   // Try the debug information.
1125 
1126   do {
1127     ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1128         const_cast<ObjCInterfaceDecl *>(interface_decl));
1129 
1130     if (!complete_interface_decl)
1131       break;
1132 
1133     // We found the complete interface.  The runtime never needs to be queried
1134     // in this scenario.
1135 
1136     DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1137         complete_interface_decl);
1138 
1139     if (complete_interface_decl == interface_decl)
1140       break; // already checked this one
1141 
1142     LLDB_LOG(log,
1143              "CAS::FOPD trying origin "
1144              "(ObjCInterfaceDecl*){1}/(ASTContext*){2}...",
1145              complete_interface_decl, &complete_iface_decl->getASTContext());
1146 
1147     FindObjCMethodDeclsWithOrigin(context, complete_interface_decl,
1148                                   "in debug info");
1149 
1150     return;
1151   } while (false);
1152 
1153   do {
1154     // Check the modules only if the debug information didn't have a complete
1155     // interface.
1156 
1157     if (ClangModulesDeclVendor *modules_decl_vendor =
1158             m_target->GetClangModulesDeclVendor()) {
1159       ConstString interface_name(interface_decl->getNameAsString().c_str());
1160       bool append = false;
1161       uint32_t max_matches = 1;
1162       std::vector<clang::NamedDecl *> decls;
1163 
1164       if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches,
1165                                           decls))
1166         break;
1167 
1168       ObjCInterfaceDecl *interface_decl_from_modules =
1169           dyn_cast<ObjCInterfaceDecl>(decls[0]);
1170 
1171       if (!interface_decl_from_modules)
1172         break;
1173 
1174       if (FindObjCMethodDeclsWithOrigin(context, interface_decl_from_modules,
1175                                         "in modules"))
1176         return;
1177     }
1178   } while (false);
1179 
1180   do {
1181     // Check the runtime only if the debug information didn't have a complete
1182     // interface and the modules don't get us anywhere.
1183 
1184     lldb::ProcessSP process(m_target->GetProcessSP());
1185 
1186     if (!process)
1187       break;
1188 
1189     ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1190 
1191     if (!language_runtime)
1192       break;
1193 
1194     DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1195 
1196     if (!decl_vendor)
1197       break;
1198 
1199     ConstString interface_name(interface_decl->getNameAsString().c_str());
1200     bool append = false;
1201     uint32_t max_matches = 1;
1202     std::vector<clang::NamedDecl *> decls;
1203 
1204     auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1205     if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches,
1206                                       decls))
1207       break;
1208 
1209     ObjCInterfaceDecl *runtime_interface_decl =
1210         dyn_cast<ObjCInterfaceDecl>(decls[0]);
1211 
1212     if (!runtime_interface_decl)
1213       break;
1214 
1215     FindObjCMethodDeclsWithOrigin(context, runtime_interface_decl,
1216                                   "in runtime");
1217   } while (false);
1218 }
1219 
1220 static bool FindObjCPropertyAndIvarDeclsWithOrigin(
1221     NameSearchContext &context, ClangASTSource &source,
1222     DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) {
1223   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1224 
1225   if (origin_iface_decl.IsInvalid())
1226     return false;
1227 
1228   std::string name_str = context.m_decl_name.getAsString();
1229   StringRef name(name_str);
1230   IdentifierInfo &name_identifier(
1231       origin_iface_decl->getASTContext().Idents.get(name));
1232 
1233   DeclFromUser<ObjCPropertyDecl> origin_property_decl(
1234       origin_iface_decl->FindPropertyDeclaration(
1235           &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance));
1236 
1237   bool found = false;
1238 
1239   if (origin_property_decl.IsValid()) {
1240     DeclFromParser<ObjCPropertyDecl> parser_property_decl(
1241         origin_property_decl.Import(source));
1242     if (parser_property_decl.IsValid()) {
1243       LLDB_LOG(log, "  CAS::FOPD found\n{1}",
1244                ClangUtil::DumpDecl(parser_property_decl.decl));
1245 
1246       context.AddNamedDecl(parser_property_decl.decl);
1247       found = true;
1248     }
1249   }
1250 
1251   DeclFromUser<ObjCIvarDecl> origin_ivar_decl(
1252       origin_iface_decl->getIvarDecl(&name_identifier));
1253 
1254   if (origin_ivar_decl.IsValid()) {
1255     DeclFromParser<ObjCIvarDecl> parser_ivar_decl(
1256         origin_ivar_decl.Import(source));
1257     if (parser_ivar_decl.IsValid()) {
1258       LLDB_LOG(log, "  CAS::FOPD found\n{1}",
1259                ClangUtil::DumpDecl(parser_ivar_decl.decl));
1260 
1261       context.AddNamedDecl(parser_ivar_decl.decl);
1262       found = true;
1263     }
1264   }
1265 
1266   return found;
1267 }
1268 
1269 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) {
1270   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1271 
1272   DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl(
1273       cast<ObjCInterfaceDecl>(context.m_decl_context));
1274   DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl(
1275       parser_iface_decl.GetOrigin(*this));
1276 
1277   ConstString class_name(parser_iface_decl->getNameAsString().c_str());
1278 
1279   LLDB_LOG(log,
1280            "ClangASTSource::FindObjCPropertyAndIvarDecls on "
1281            "(ASTContext*){1} '{2}' for '{3}.{4}'",
1282            m_ast_context, m_clang_ast_context->getDisplayName(),
1283            parser_iface_decl->getName(), context.m_decl_name.getAsString());
1284 
1285   if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this, origin_iface_decl))
1286     return;
1287 
1288   LLDB_LOG(log,
1289            "CAS::FOPD couldn't find the property on origin "
1290            "(ObjCInterfaceDecl*){1}/(ASTContext*){2}, searching "
1291            "elsewhere...",
1292            origin_iface_decl.decl, &origin_iface_decl->getASTContext());
1293 
1294   SymbolContext null_sc;
1295   TypeList type_list;
1296 
1297   do {
1298     ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1299         const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl));
1300 
1301     if (!complete_interface_decl)
1302       break;
1303 
1304     // We found the complete interface.  The runtime never needs to be queried
1305     // in this scenario.
1306 
1307     DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1308         complete_interface_decl);
1309 
1310     if (complete_iface_decl.decl == origin_iface_decl.decl)
1311       break; // already checked this one
1312 
1313     LLDB_LOG(log,
1314              "CAS::FOPD trying origin "
1315              "(ObjCInterfaceDecl*){1}/(ASTContext*){2}...",
1316              complete_iface_decl.decl, &complete_iface_decl->getASTContext());
1317 
1318     FindObjCPropertyAndIvarDeclsWithOrigin(context, *this, complete_iface_decl);
1319 
1320     return;
1321   } while (false);
1322 
1323   do {
1324     // Check the modules only if the debug information didn't have a complete
1325     // interface.
1326 
1327     ClangModulesDeclVendor *modules_decl_vendor =
1328         m_target->GetClangModulesDeclVendor();
1329 
1330     if (!modules_decl_vendor)
1331       break;
1332 
1333     bool append = false;
1334     uint32_t max_matches = 1;
1335     std::vector<clang::NamedDecl *> decls;
1336 
1337     if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1338       break;
1339 
1340     DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules(
1341         dyn_cast<ObjCInterfaceDecl>(decls[0]));
1342 
1343     if (!interface_decl_from_modules.IsValid())
1344       break;
1345 
1346     LLDB_LOG(log,
1347              "CAS::FOPD[{0}] trying module "
1348              "(ObjCInterfaceDecl*){1}/(ASTContext*){2}...",
1349              interface_decl_from_modules.decl,
1350              &interface_decl_from_modules->getASTContext());
1351 
1352     if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this,
1353                                                interface_decl_from_modules))
1354       return;
1355   } while (false);
1356 
1357   do {
1358     // Check the runtime only if the debug information didn't have a complete
1359     // interface and nothing was in the modules.
1360 
1361     lldb::ProcessSP process(m_target->GetProcessSP());
1362 
1363     if (!process)
1364       return;
1365 
1366     ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1367 
1368     if (!language_runtime)
1369       return;
1370 
1371     DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1372 
1373     if (!decl_vendor)
1374       break;
1375 
1376     bool append = false;
1377     uint32_t max_matches = 1;
1378     std::vector<clang::NamedDecl *> decls;
1379 
1380     auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1381     if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1382       break;
1383 
1384     DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime(
1385         dyn_cast<ObjCInterfaceDecl>(decls[0]));
1386 
1387     if (!interface_decl_from_runtime.IsValid())
1388       break;
1389 
1390     LLDB_LOG(log,
1391              "CAS::FOPD[{0}] trying runtime "
1392              "(ObjCInterfaceDecl*){1}/(ASTContext*){2}...",
1393              interface_decl_from_runtime.decl,
1394              &interface_decl_from_runtime->getASTContext());
1395 
1396     if (FindObjCPropertyAndIvarDeclsWithOrigin(context, *this,
1397                                                interface_decl_from_runtime))
1398       return;
1399   } while (false);
1400 }
1401 
1402 void ClangASTSource::LookupInNamespace(NameSearchContext &context) {
1403   const NamespaceDecl *namespace_context =
1404       dyn_cast<NamespaceDecl>(context.m_decl_context);
1405 
1406   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1407 
1408   ClangASTImporter::NamespaceMapSP namespace_map =
1409       m_ast_importer_sp->GetNamespaceMap(namespace_context);
1410 
1411   LLDB_LOGV(log, "  CAS::FEVD Inspecting namespace map {1} ({2} entries)",
1412             namespace_map.get(), namespace_map->size());
1413 
1414   if (!namespace_map)
1415     return;
1416 
1417   for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
1418                                                 e = namespace_map->end();
1419        i != e; ++i) {
1420     LLDB_LOG(log, "  CAS::FEVD Searching namespace {1} in module {2}",
1421              i->second.GetName(), i->first->GetFileSpec().GetFilename());
1422 
1423     FindExternalVisibleDecls(context, i->first, i->second);
1424   }
1425 }
1426 
1427 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap;
1428 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap;
1429 
1430 template <class D, class O>
1431 static bool ImportOffsetMap(llvm::DenseMap<const D *, O> &destination_map,
1432                             llvm::DenseMap<const D *, O> &source_map,
1433                             ClangASTSource &source) {
1434   // When importing fields into a new record, clang has a hard requirement that
1435   // fields be imported in field offset order.  Since they are stored in a
1436   // DenseMap with a pointer as the key type, this means we cannot simply
1437   // iterate over the map, as the order will be non-deterministic.  Instead we
1438   // have to sort by the offset and then insert in sorted order.
1439   typedef llvm::DenseMap<const D *, O> MapType;
1440   typedef typename MapType::value_type PairType;
1441   std::vector<PairType> sorted_items;
1442   sorted_items.reserve(source_map.size());
1443   sorted_items.assign(source_map.begin(), source_map.end());
1444   llvm::sort(sorted_items.begin(), sorted_items.end(),
1445              [](const PairType &lhs, const PairType &rhs) {
1446                return lhs.second < rhs.second;
1447              });
1448 
1449   for (const auto &item : sorted_items) {
1450     DeclFromUser<D> user_decl(const_cast<D *>(item.first));
1451     DeclFromParser<D> parser_decl(user_decl.Import(source));
1452     if (parser_decl.IsInvalid())
1453       return false;
1454     destination_map.insert(
1455         std::pair<const D *, O>(parser_decl.decl, item.second));
1456   }
1457 
1458   return true;
1459 }
1460 
1461 template <bool IsVirtual>
1462 bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
1463                         DeclFromUser<const CXXRecordDecl> &record,
1464                         BaseOffsetMap &base_offsets) {
1465   for (CXXRecordDecl::base_class_const_iterator
1466            bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
1467            be = (IsVirtual ? record->vbases_end() : record->bases_end());
1468        bi != be; ++bi) {
1469     if (!IsVirtual && bi->isVirtual())
1470       continue;
1471 
1472     const clang::Type *origin_base_type = bi->getType().getTypePtr();
1473     const clang::RecordType *origin_base_record_type =
1474         origin_base_type->getAs<RecordType>();
1475 
1476     if (!origin_base_record_type)
1477       return false;
1478 
1479     DeclFromUser<RecordDecl> origin_base_record(
1480         origin_base_record_type->getDecl());
1481 
1482     if (origin_base_record.IsInvalid())
1483       return false;
1484 
1485     DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
1486         DynCast<CXXRecordDecl>(origin_base_record));
1487 
1488     if (origin_base_cxx_record.IsInvalid())
1489       return false;
1490 
1491     CharUnits base_offset;
1492 
1493     if (IsVirtual)
1494       base_offset =
1495           record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
1496     else
1497       base_offset =
1498           record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
1499 
1500     base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
1501         origin_base_cxx_record.decl, base_offset));
1502   }
1503 
1504   return true;
1505 }
1506 
1507 bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size,
1508                                       uint64_t &alignment,
1509                                       FieldOffsetMap &field_offsets,
1510                                       BaseOffsetMap &base_offsets,
1511                                       BaseOffsetMap &virtual_base_offsets) {
1512 
1513   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1514 
1515   LLDB_LOG(log,
1516            "LayoutRecordType on (ASTContext*){1} '{2}' for (RecordDecl*)"
1517            "{3} [name = '{4}']",
1518            m_ast_context, m_clang_ast_context->getDisplayName(), record,
1519            record->getName());
1520 
1521   DeclFromParser<const RecordDecl> parser_record(record);
1522   DeclFromUser<const RecordDecl> origin_record(
1523       parser_record.GetOrigin(*this));
1524 
1525   if (origin_record.IsInvalid())
1526     return false;
1527 
1528   FieldOffsetMap origin_field_offsets;
1529   BaseOffsetMap origin_base_offsets;
1530   BaseOffsetMap origin_virtual_base_offsets;
1531 
1532   TypeSystemClang::GetCompleteDecl(
1533       &origin_record->getASTContext(),
1534       const_cast<RecordDecl *>(origin_record.decl));
1535 
1536   clang::RecordDecl *definition = origin_record.decl->getDefinition();
1537   if (!definition || !definition->isCompleteDefinition())
1538     return false;
1539 
1540   const ASTRecordLayout &record_layout(
1541       origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
1542 
1543   int field_idx = 0, field_count = record_layout.getFieldCount();
1544 
1545   for (RecordDecl::field_iterator fi = origin_record->field_begin(),
1546                                   fe = origin_record->field_end();
1547        fi != fe; ++fi) {
1548     if (field_idx >= field_count)
1549       return false; // Layout didn't go well.  Bail out.
1550 
1551     uint64_t field_offset = record_layout.getFieldOffset(field_idx);
1552 
1553     origin_field_offsets.insert(
1554         std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
1555 
1556     field_idx++;
1557   }
1558 
1559   lldbassert(&record->getASTContext() == m_ast_context);
1560 
1561   DeclFromUser<const CXXRecordDecl> origin_cxx_record(
1562       DynCast<const CXXRecordDecl>(origin_record));
1563 
1564   if (origin_cxx_record.IsValid()) {
1565     if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
1566                                    origin_base_offsets) ||
1567         !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
1568                                   origin_virtual_base_offsets))
1569       return false;
1570   }
1571 
1572   if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) ||
1573       !ImportOffsetMap(base_offsets, origin_base_offsets, *this) ||
1574       !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets,
1575                        *this))
1576     return false;
1577 
1578   size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth();
1579   alignment = record_layout.getAlignment().getQuantity() *
1580               m_ast_context->getCharWidth();
1581 
1582   if (log) {
1583     LLDB_LOG(log, "LRT returned:");
1584     LLDB_LOG(log, "LRT   Original = (RecordDecl*)%p",
1585              static_cast<const void *>(origin_record.decl));
1586     LLDB_LOG(log, "LRT   Size = %" PRId64, size);
1587     LLDB_LOG(log, "LRT   Alignment = %" PRId64, alignment);
1588     LLDB_LOG(log, "LRT   Fields:");
1589     for (RecordDecl::field_iterator fi = record->field_begin(),
1590                                     fe = record->field_end();
1591          fi != fe; ++fi) {
1592       LLDB_LOG(log,
1593                "LRT[{0}]     (FieldDecl*){1}, Name = '{2}', Offset = {3} bits",
1594                *fi, fi->getName(), field_offsets[*fi]);
1595     }
1596     DeclFromParser<const CXXRecordDecl> parser_cxx_record =
1597         DynCast<const CXXRecordDecl>(parser_record);
1598     if (parser_cxx_record.IsValid()) {
1599       LLDB_LOG(log, "LRT   Bases:");
1600       for (CXXRecordDecl::base_class_const_iterator
1601                bi = parser_cxx_record->bases_begin(),
1602                be = parser_cxx_record->bases_end();
1603            bi != be; ++bi) {
1604         bool is_virtual = bi->isVirtual();
1605 
1606         QualType base_type = bi->getType();
1607         const RecordType *base_record_type = base_type->getAs<RecordType>();
1608         DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
1609         DeclFromParser<CXXRecordDecl> base_cxx_record =
1610             DynCast<CXXRecordDecl>(base_record);
1611 
1612         LLDB_LOG(log,
1613                  "LRT     {1}(CXXRecordDecl*){2}, Name = '{3}', Offset = "
1614                  "{4} chars",
1615                  (is_virtual ? "Virtual " : ""), base_cxx_record.decl,
1616                  base_cxx_record.decl->getName(),
1617                  (is_virtual
1618                       ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1619                       : base_offsets[base_cxx_record.decl].getQuantity()));
1620       }
1621     } else {
1622       LLDB_LOG(log, "LRD   Not a CXXRecord, so no bases");
1623     }
1624   }
1625 
1626   return true;
1627 }
1628 
1629 void ClangASTSource::CompleteNamespaceMap(
1630     ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name,
1631     ClangASTImporter::NamespaceMapSP &parent_map) const {
1632 
1633   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1634 
1635   if (log) {
1636     if (parent_map && parent_map->size())
1637       LLDB_LOG(log,
1638                "CompleteNamespaceMap on (ASTContext*){1} '{2}' Searching "
1639                "for namespace {3} in namespace {4}",
1640                m_ast_context, m_clang_ast_context->getDisplayName(), name,
1641                parent_map->begin()->second.GetName());
1642     else
1643       LLDB_LOG(log,
1644                "CompleteNamespaceMap on (ASTContext*){1} '{2}' Searching "
1645                "for namespace {3}",
1646                m_ast_context, m_clang_ast_context->getDisplayName(), name);
1647   }
1648 
1649   if (parent_map) {
1650     for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1651                                                   e = parent_map->end();
1652          i != e; ++i) {
1653       CompilerDeclContext found_namespace_decl;
1654 
1655       lldb::ModuleSP module_sp = i->first;
1656       CompilerDeclContext module_parent_namespace_decl = i->second;
1657 
1658       SymbolFile *symbol_file = module_sp->GetSymbolFile();
1659 
1660       if (!symbol_file)
1661         continue;
1662 
1663       found_namespace_decl =
1664           symbol_file->FindNamespace(name, module_parent_namespace_decl);
1665 
1666       if (!found_namespace_decl)
1667         continue;
1668 
1669       namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1670           module_sp, found_namespace_decl));
1671 
1672       LLDB_LOG(log, "  CMN Found namespace {1} in module {2}", name,
1673                module_sp->GetFileSpec().GetFilename());
1674     }
1675   } else {
1676     const ModuleList &target_images = m_target->GetImages();
1677     std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
1678 
1679     CompilerDeclContext null_namespace_decl;
1680 
1681     for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
1682       lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
1683 
1684       if (!image)
1685         continue;
1686 
1687       CompilerDeclContext found_namespace_decl;
1688 
1689       SymbolFile *symbol_file = image->GetSymbolFile();
1690 
1691       if (!symbol_file)
1692         continue;
1693 
1694       found_namespace_decl =
1695           symbol_file->FindNamespace(name, null_namespace_decl);
1696 
1697       if (!found_namespace_decl)
1698         continue;
1699 
1700       namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1701           image, found_namespace_decl));
1702 
1703       LLDB_LOG(log, "  CMN[{0}] Found namespace {1} in module {2}", name,
1704                image->GetFileSpec().GetFilename());
1705     }
1706   }
1707 }
1708 
1709 NamespaceDecl *ClangASTSource::AddNamespace(
1710     NameSearchContext &context,
1711     ClangASTImporter::NamespaceMapSP &namespace_decls) {
1712   if (!namespace_decls)
1713     return nullptr;
1714 
1715   const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1716 
1717   clang::ASTContext *src_ast =
1718       TypeSystemClang::DeclContextGetTypeSystemClang(namespace_decl);
1719   if (!src_ast)
1720     return nullptr;
1721   clang::NamespaceDecl *src_namespace_decl =
1722       TypeSystemClang::DeclContextGetAsNamespaceDecl(namespace_decl);
1723 
1724   if (!src_namespace_decl)
1725     return nullptr;
1726 
1727   Decl *copied_decl = CopyDecl(src_namespace_decl);
1728 
1729   if (!copied_decl)
1730     return nullptr;
1731 
1732   NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1733 
1734   if (!copied_namespace_decl)
1735     return nullptr;
1736 
1737   context.m_decls.push_back(copied_namespace_decl);
1738 
1739   m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1740                                           namespace_decls);
1741 
1742   return dyn_cast<NamespaceDecl>(copied_decl);
1743 }
1744 
1745 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) {
1746   return m_ast_importer_sp->CopyDecl(m_ast_context, src_decl);
1747 }
1748 
1749 ClangASTImporter::DeclOrigin ClangASTSource::GetDeclOrigin(const clang::Decl *decl) {
1750   return m_ast_importer_sp->GetDeclOrigin(decl);
1751 }
1752 
1753 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) {
1754   TypeSystemClang *src_ast =
1755       llvm::dyn_cast_or_null<TypeSystemClang>(src_type.GetTypeSystem());
1756   if (src_ast == nullptr)
1757     return CompilerType();
1758 
1759   SetImportInProgress(true);
1760 
1761   QualType copied_qual_type = ClangUtil::GetQualType(
1762       m_ast_importer_sp->CopyType(*m_clang_ast_context, src_type));
1763 
1764   SetImportInProgress(false);
1765 
1766   if (copied_qual_type.getAsOpaquePtr() &&
1767       copied_qual_type->getCanonicalTypeInternal().isNull())
1768     // this shouldn't happen, but we're hardening because the AST importer
1769     // seems to be generating bad types on occasion.
1770     return CompilerType();
1771 
1772   return m_clang_ast_context->GetType(copied_qual_type);
1773 }
1774