1 //===-- ClangASTSource.cpp ---------------------------------------*- C++-*-===//
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/ClangASTContext.h"
17 #include "lldb/Symbol/ClangUtil.h"
18 #include "lldb/Symbol/CompilerDeclContext.h"
19 #include "lldb/Symbol/Function.h"
20 #include "lldb/Symbol/SymbolFile.h"
21 #include "lldb/Symbol/TaggedASTType.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Utility/Log.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/RecordLayout.h"
26 
27 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.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(const lldb::TargetSP &target)
53     : m_import_in_progress(false), m_lookups_enabled(false), m_target(target),
54       m_ast_context(nullptr), m_active_lexical_decls(), m_active_lookups() {
55   if (!target->GetUseModernTypeLookup()) {
56     m_ast_importer_sp = m_target->GetClangASTImporter();
57   }
58 }
59 
60 void ClangASTSource::InstallASTContext(ClangASTContext &clang_ast_context,
61                                        clang::FileManager &file_manager,
62                                        bool is_shared_context) {
63   m_ast_context = clang_ast_context.getASTContext();
64   m_clang_ast_context = &clang_ast_context;
65   m_file_manager = &file_manager;
66   if (m_target->GetUseModernTypeLookup()) {
67     // Configure the ExternalASTMerger.  The merger needs to be able to import
68     // types from any source that we would do lookups in, which includes the
69     // persistent AST context as well as the modules and Objective-C runtime
70     // AST contexts.
71 
72     lldbassert(!m_merger_up);
73     clang::ExternalASTMerger::ImporterTarget target = {*m_ast_context,
74                                                        file_manager};
75     std::vector<clang::ExternalASTMerger::ImporterSource> sources;
76     for (lldb::ModuleSP module_sp : m_target->GetImages().Modules()) {
77       auto type_system_or_err =
78           module_sp->GetTypeSystemForLanguage(lldb::eLanguageTypeC);
79       if (auto err = type_system_or_err.takeError()) {
80         LLDB_LOG_ERROR(
81             lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS),
82             std::move(err), "Failed to get ClangASTContext");
83       } else if (auto *module_ast_ctx = llvm::cast_or_null<ClangASTContext>(
84                      &type_system_or_err.get())) {
85         lldbassert(module_ast_ctx->getASTContext());
86         lldbassert(module_ast_ctx->getFileManager());
87         sources.emplace_back(*module_ast_ctx->getASTContext(),
88                              *module_ast_ctx->getFileManager(),
89                              module_ast_ctx->GetOriginMap());
90       }
91     }
92 
93     do {
94       lldb::ProcessSP process(m_target->GetProcessSP());
95 
96       if (!process)
97         break;
98 
99       ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
100 
101       if (!language_runtime)
102         break;
103 
104       if (auto *runtime_decl_vendor = llvm::dyn_cast_or_null<ClangDeclVendor>(
105               language_runtime->GetDeclVendor())) {
106         sources.push_back(runtime_decl_vendor->GetImporterSource());
107       }
108     } while (false);
109 
110     do {
111       auto *modules_decl_vendor = m_target->GetClangModulesDeclVendor();
112 
113       if (!modules_decl_vendor)
114         break;
115 
116       sources.push_back(modules_decl_vendor->GetImporterSource());
117     } while (false);
118 
119     if (!is_shared_context) {
120       // Update the scratch AST context's merger to reflect any new sources we
121       // might have come across since the last time an expression was parsed.
122 
123       if (auto *clang_ast_context = ClangASTContext::GetScratch(*m_target)) {
124 
125         auto scratch_ast_context =
126             static_cast<ClangASTContextForExpressions *>(clang_ast_context);
127 
128         scratch_ast_context->GetMergerUnchecked().AddSources(sources);
129 
130         sources.push_back({*scratch_ast_context->getASTContext(),
131                            *scratch_ast_context->getFileManager(),
132                            scratch_ast_context->GetOriginMap()});
133       }
134     }
135 
136     m_merger_up =
137         std::make_unique<clang::ExternalASTMerger>(target, sources);
138   } else {
139     m_ast_importer_sp->InstallMapCompleter(m_ast_context, *this);
140   }
141 }
142 
143 ClangASTSource::~ClangASTSource() {
144   if (m_ast_importer_sp)
145     m_ast_importer_sp->ForgetDestination(m_ast_context);
146 
147   // We are in the process of destruction, don't create clang ast context on
148   // demand by passing false to
149   // Target::GetScratchClangASTContext(create_on_demand).
150   ClangASTContext *scratch_clang_ast_context =
151       ClangASTContext::GetScratch(*m_target, false);
152 
153   if (!scratch_clang_ast_context)
154     return;
155 
156   clang::ASTContext *scratch_ast_context =
157       scratch_clang_ast_context->getASTContext();
158 
159   if (!scratch_ast_context)
160     return;
161 
162   if (m_ast_context != scratch_ast_context && m_ast_importer_sp)
163     m_ast_importer_sp->ForgetSource(scratch_ast_context, m_ast_context);
164 }
165 
166 void ClangASTSource::StartTranslationUnit(ASTConsumer *Consumer) {
167   if (!m_ast_context)
168     return;
169 
170   m_ast_context->getTranslationUnitDecl()->setHasExternalVisibleStorage();
171   m_ast_context->getTranslationUnitDecl()->setHasExternalLexicalStorage();
172 }
173 
174 // The core lookup interface.
175 bool ClangASTSource::FindExternalVisibleDeclsByName(
176     const DeclContext *decl_ctx, DeclarationName clang_decl_name) {
177   if (!m_ast_context) {
178     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
179     return false;
180   }
181 
182   if (GetImportInProgress()) {
183     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
184     return false;
185   }
186 
187   std::string decl_name(clang_decl_name.getAsString());
188 
189   //    if (m_decl_map.DoingASTImport ())
190   //      return DeclContext::lookup_result();
191   //
192   switch (clang_decl_name.getNameKind()) {
193   // Normal identifiers.
194   case DeclarationName::Identifier: {
195     clang::IdentifierInfo *identifier_info =
196         clang_decl_name.getAsIdentifierInfo();
197 
198     if (!identifier_info || identifier_info->getBuiltinID() != 0) {
199       SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
200       return false;
201     }
202   } break;
203 
204   // Operator names.
205   case DeclarationName::CXXOperatorName:
206   case DeclarationName::CXXLiteralOperatorName:
207     break;
208 
209   // Using directives found in this context.
210   // Tell Sema we didn't find any or we'll end up getting asked a *lot*.
211   case DeclarationName::CXXUsingDirective:
212     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
213     return false;
214 
215   case DeclarationName::ObjCZeroArgSelector:
216   case DeclarationName::ObjCOneArgSelector:
217   case DeclarationName::ObjCMultiArgSelector: {
218     llvm::SmallVector<NamedDecl *, 1> method_decls;
219 
220     NameSearchContext method_search_context(*this, method_decls,
221                                             clang_decl_name, decl_ctx);
222 
223     FindObjCMethodDecls(method_search_context);
224 
225     SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, method_decls);
226     return (method_decls.size() > 0);
227   }
228   // These aren't possible in the global context.
229   case DeclarationName::CXXConstructorName:
230   case DeclarationName::CXXDestructorName:
231   case DeclarationName::CXXConversionFunctionName:
232   case DeclarationName::CXXDeductionGuideName:
233     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
234     return false;
235   }
236 
237   if (!GetLookupsEnabled()) {
238     // Wait until we see a '$' at the start of a name before we start doing any
239     // lookups so we can avoid lookup up all of the builtin types.
240     if (!decl_name.empty() && decl_name[0] == '$') {
241       SetLookupsEnabled(true);
242     } else {
243       SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
244       return false;
245     }
246   }
247 
248   ConstString const_decl_name(decl_name.c_str());
249 
250   const char *uniqued_const_decl_name = const_decl_name.GetCString();
251   if (m_active_lookups.find(uniqued_const_decl_name) !=
252       m_active_lookups.end()) {
253     // We are currently looking up this name...
254     SetNoExternalVisibleDeclsForName(decl_ctx, clang_decl_name);
255     return false;
256   }
257   m_active_lookups.insert(uniqued_const_decl_name);
258   //  static uint32_t g_depth = 0;
259   //  ++g_depth;
260   //  printf("[%5u] FindExternalVisibleDeclsByName() \"%s\"\n", g_depth,
261   //  uniqued_const_decl_name);
262   llvm::SmallVector<NamedDecl *, 4> name_decls;
263   NameSearchContext name_search_context(*this, name_decls, clang_decl_name,
264                                         decl_ctx);
265   FindExternalVisibleDecls(name_search_context);
266   SetExternalVisibleDeclsForName(decl_ctx, clang_decl_name, name_decls);
267   //  --g_depth;
268   m_active_lookups.erase(uniqued_const_decl_name);
269   return (name_decls.size() != 0);
270 }
271 
272 void ClangASTSource::CompleteType(TagDecl *tag_decl) {
273   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
274 
275   static unsigned int invocation_id = 0;
276   unsigned int current_id = invocation_id++;
277 
278   if (log) {
279     LLDB_LOGF(log,
280               "    CompleteTagDecl[%u] on (ASTContext*)%p Completing "
281               "(TagDecl*)%p named %s",
282               current_id, static_cast<void *>(m_ast_context),
283               static_cast<void *>(tag_decl), tag_decl->getName().str().c_str());
284 
285     LLDB_LOG(log, "      CTD[%u] Before:\n{0}", current_id,
286              ClangUtil::DumpDecl(tag_decl));
287   }
288 
289   auto iter = m_active_lexical_decls.find(tag_decl);
290   if (iter != m_active_lexical_decls.end())
291     return;
292   m_active_lexical_decls.insert(tag_decl);
293   ScopedLexicalDeclEraser eraser(m_active_lexical_decls, tag_decl);
294 
295   if (!m_ast_importer_sp) {
296     if (HasMerger()) {
297       GetMergerUnchecked().CompleteType(tag_decl);
298     }
299     return;
300   }
301 
302   if (!m_ast_importer_sp->CompleteTagDecl(tag_decl)) {
303     // We couldn't complete the type.  Maybe there's a definition somewhere
304     // else that can be completed.
305 
306     LLDB_LOGF(log,
307               "      CTD[%u] Type could not be completed in the module in "
308               "which it was first found.",
309               current_id);
310 
311     bool found = false;
312 
313     DeclContext *decl_ctx = tag_decl->getDeclContext();
314 
315     if (const NamespaceDecl *namespace_context =
316             dyn_cast<NamespaceDecl>(decl_ctx)) {
317       ClangASTImporter::NamespaceMapSP namespace_map =
318           m_ast_importer_sp->GetNamespaceMap(namespace_context);
319 
320       if (log && log->GetVerbose())
321         LLDB_LOGF(log, "      CTD[%u] Inspecting namespace map %p (%d entries)",
322                   current_id, static_cast<void *>(namespace_map.get()),
323                   static_cast<int>(namespace_map->size()));
324 
325       if (!namespace_map)
326         return;
327 
328       for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
329                                                     e = namespace_map->end();
330            i != e && !found; ++i) {
331         LLDB_LOGF(log, "      CTD[%u] Searching namespace %s in module %s",
332                   current_id, i->second.GetName().AsCString(),
333                   i->first->GetFileSpec().GetFilename().GetCString());
334 
335         TypeList types;
336 
337         ConstString name(tag_decl->getName().str().c_str());
338 
339         i->first->FindTypesInNamespace(name, &i->second, UINT32_MAX, types);
340 
341         for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
342           lldb::TypeSP type = types.GetTypeAtIndex(ti);
343 
344           if (!type)
345             continue;
346 
347           CompilerType clang_type(type->GetFullCompilerType());
348 
349           if (!ClangUtil::IsClangType(clang_type))
350             continue;
351 
352           const TagType *tag_type =
353               ClangUtil::GetQualType(clang_type)->getAs<TagType>();
354 
355           if (!tag_type)
356             continue;
357 
358           TagDecl *candidate_tag_decl =
359               const_cast<TagDecl *>(tag_type->getDecl());
360 
361           if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
362                                                            candidate_tag_decl))
363             found = true;
364         }
365       }
366     } else {
367       TypeList types;
368 
369       ConstString name(tag_decl->getName().str().c_str());
370 
371       const ModuleList &module_list = m_target->GetImages();
372 
373       bool exact_match = false;
374       llvm::DenseSet<SymbolFile *> searched_symbol_files;
375       module_list.FindTypes(nullptr, name, exact_match, UINT32_MAX,
376                             searched_symbol_files, types);
377 
378       for (uint32_t ti = 0, te = types.GetSize(); ti != te && !found; ++ti) {
379         lldb::TypeSP type = types.GetTypeAtIndex(ti);
380 
381         if (!type)
382           continue;
383 
384         CompilerType clang_type(type->GetFullCompilerType());
385 
386         if (!ClangUtil::IsClangType(clang_type))
387           continue;
388 
389         const TagType *tag_type =
390             ClangUtil::GetQualType(clang_type)->getAs<TagType>();
391 
392         if (!tag_type)
393           continue;
394 
395         TagDecl *candidate_tag_decl =
396             const_cast<TagDecl *>(tag_type->getDecl());
397 
398         // We have found a type by basename and we need to make sure the decl
399         // contexts are the same before we can try to complete this type with
400         // another
401         if (!ClangASTContext::DeclsAreEquivalent(tag_decl, candidate_tag_decl))
402           continue;
403 
404         if (m_ast_importer_sp->CompleteTagDeclWithOrigin(tag_decl,
405                                                          candidate_tag_decl))
406           found = true;
407       }
408     }
409   }
410 
411   LLDB_LOG(log, "      [CTD] After:\n{0}", ClangUtil::DumpDecl(tag_decl));
412 }
413 
414 void ClangASTSource::CompleteType(clang::ObjCInterfaceDecl *interface_decl) {
415   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
416 
417   LLDB_LOGF(log,
418             "    [CompleteObjCInterfaceDecl] on (ASTContext*)%p Completing "
419             "an ObjCInterfaceDecl named %s",
420             static_cast<void *>(m_ast_context),
421             interface_decl->getName().str().c_str());
422   LLDB_LOG(log, "      [COID] Before:\n{0}",
423            ClangUtil::DumpDecl(interface_decl));
424 
425   if (!m_ast_importer_sp) {
426     if (HasMerger()) {
427       ObjCInterfaceDecl *complete_iface_decl =
428         GetCompleteObjCInterface(interface_decl);
429 
430       if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
431         m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()});
432       }
433 
434       GetMergerUnchecked().CompleteType(interface_decl);
435     } else {
436       lldbassert(0 && "No mechanism for completing a type!");
437     }
438     return;
439   }
440 
441   Decl *original_decl = nullptr;
442   ASTContext *original_ctx = nullptr;
443 
444   if (m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl,
445                                            &original_ctx)) {
446     if (ObjCInterfaceDecl *original_iface_decl =
447             dyn_cast<ObjCInterfaceDecl>(original_decl)) {
448       ObjCInterfaceDecl *complete_iface_decl =
449           GetCompleteObjCInterface(original_iface_decl);
450 
451       if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
452         m_ast_importer_sp->SetDeclOrigin(interface_decl, complete_iface_decl);
453       }
454     }
455   }
456 
457   m_ast_importer_sp->CompleteObjCInterfaceDecl(interface_decl);
458 
459   if (interface_decl->getSuperClass() &&
460       interface_decl->getSuperClass() != interface_decl)
461     CompleteType(interface_decl->getSuperClass());
462 
463   if (log) {
464     LLDB_LOGF(log, "      [COID] After:");
465     LLDB_LOG(log, "      [COID] {0}", ClangUtil::DumpDecl(interface_decl));
466   }
467 }
468 
469 clang::ObjCInterfaceDecl *ClangASTSource::GetCompleteObjCInterface(
470     const clang::ObjCInterfaceDecl *interface_decl) {
471   lldb::ProcessSP process(m_target->GetProcessSP());
472 
473   if (!process)
474     return nullptr;
475 
476   ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
477 
478   if (!language_runtime)
479     return nullptr;
480 
481   ConstString class_name(interface_decl->getNameAsString().c_str());
482 
483   lldb::TypeSP complete_type_sp(
484       language_runtime->LookupInCompleteClassCache(class_name));
485 
486   if (!complete_type_sp)
487     return nullptr;
488 
489   TypeFromUser complete_type =
490       TypeFromUser(complete_type_sp->GetFullCompilerType());
491   lldb::opaque_compiler_type_t complete_opaque_type =
492       complete_type.GetOpaqueQualType();
493 
494   if (!complete_opaque_type)
495     return nullptr;
496 
497   const clang::Type *complete_clang_type =
498       QualType::getFromOpaquePtr(complete_opaque_type).getTypePtr();
499   const ObjCInterfaceType *complete_interface_type =
500       dyn_cast<ObjCInterfaceType>(complete_clang_type);
501 
502   if (!complete_interface_type)
503     return nullptr;
504 
505   ObjCInterfaceDecl *complete_iface_decl(complete_interface_type->getDecl());
506 
507   return complete_iface_decl;
508 }
509 
510 void ClangASTSource::FindExternalLexicalDecls(
511     const DeclContext *decl_context,
512     llvm::function_ref<bool(Decl::Kind)> predicate,
513     llvm::SmallVectorImpl<Decl *> &decls) {
514 
515   if (HasMerger()) {
516     if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(decl_context)) {
517       ObjCInterfaceDecl *complete_iface_decl =
518          GetCompleteObjCInterface(interface_decl);
519 
520       if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
521         m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()});
522       }
523     }
524     return GetMergerUnchecked().FindExternalLexicalDecls(decl_context,
525                                                          predicate,
526                                                          decls);
527   } else if (!m_ast_importer_sp)
528     return;
529 
530   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
531 
532   const Decl *context_decl = dyn_cast<Decl>(decl_context);
533 
534   if (!context_decl)
535     return;
536 
537   auto iter = m_active_lexical_decls.find(context_decl);
538   if (iter != m_active_lexical_decls.end())
539     return;
540   m_active_lexical_decls.insert(context_decl);
541   ScopedLexicalDeclEraser eraser(m_active_lexical_decls, context_decl);
542 
543   static unsigned int invocation_id = 0;
544   unsigned int current_id = invocation_id++;
545 
546   if (log) {
547     if (const NamedDecl *context_named_decl = dyn_cast<NamedDecl>(context_decl))
548       LLDB_LOGF(
549           log,
550           "FindExternalLexicalDecls[%u] on (ASTContext*)%p in '%s' (%sDecl*)%p",
551           current_id, static_cast<void *>(m_ast_context),
552           context_named_decl->getNameAsString().c_str(),
553           context_decl->getDeclKindName(),
554           static_cast<const void *>(context_decl));
555     else if (context_decl)
556       LLDB_LOGF(
557           log, "FindExternalLexicalDecls[%u] on (ASTContext*)%p in (%sDecl*)%p",
558           current_id, static_cast<void *>(m_ast_context),
559           context_decl->getDeclKindName(),
560           static_cast<const void *>(context_decl));
561     else
562       LLDB_LOGF(
563           log,
564           "FindExternalLexicalDecls[%u] on (ASTContext*)%p in a NULL context",
565           current_id, static_cast<const void *>(m_ast_context));
566   }
567 
568   Decl *original_decl = nullptr;
569   ASTContext *original_ctx = nullptr;
570 
571   if (!m_ast_importer_sp->ResolveDeclOrigin(context_decl, &original_decl,
572                                             &original_ctx))
573     return;
574 
575   LLDB_LOG(
576       log, "  FELD[{0}] Original decl (ASTContext*){1:x} (Decl*){2:x}:\n{3}",
577       current_id, static_cast<void *>(original_ctx),
578       static_cast<void *>(original_decl), ClangUtil::DumpDecl(original_decl));
579 
580   if (ObjCInterfaceDecl *original_iface_decl =
581           dyn_cast<ObjCInterfaceDecl>(original_decl)) {
582     ObjCInterfaceDecl *complete_iface_decl =
583         GetCompleteObjCInterface(original_iface_decl);
584 
585     if (complete_iface_decl && (complete_iface_decl != original_iface_decl)) {
586       original_decl = complete_iface_decl;
587       original_ctx = &complete_iface_decl->getASTContext();
588 
589       m_ast_importer_sp->SetDeclOrigin(context_decl, complete_iface_decl);
590     }
591   }
592 
593   if (TagDecl *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {
594     ExternalASTSource *external_source = original_ctx->getExternalSource();
595 
596     if (external_source)
597       external_source->CompleteType(original_tag_decl);
598   }
599 
600   const DeclContext *original_decl_context =
601       dyn_cast<DeclContext>(original_decl);
602 
603   if (!original_decl_context)
604     return;
605 
606   // Indicates whether we skipped any Decls of the original DeclContext.
607   bool SkippedDecls = false;
608   for (TagDecl::decl_iterator iter = original_decl_context->decls_begin();
609        iter != original_decl_context->decls_end(); ++iter) {
610     Decl *decl = *iter;
611 
612     // The predicate function returns true if the passed declaration kind is
613     // the one we are looking for.
614     // See clang::ExternalASTSource::FindExternalLexicalDecls()
615     if (predicate(decl->getKind())) {
616       if (log) {
617         std::string ast_dump = ClangUtil::DumpDecl(decl);
618         if (const NamedDecl *context_named_decl =
619                 dyn_cast<NamedDecl>(context_decl))
620           LLDB_LOGF(log, "  FELD[%d] Adding [to %sDecl %s] lexical %sDecl %s",
621                     current_id, context_named_decl->getDeclKindName(),
622                     context_named_decl->getNameAsString().c_str(),
623                     decl->getDeclKindName(), ast_dump.c_str());
624         else
625           LLDB_LOGF(log, "  FELD[%d] Adding lexical %sDecl %s", current_id,
626                     decl->getDeclKindName(), ast_dump.c_str());
627       }
628 
629       Decl *copied_decl = CopyDecl(decl);
630 
631       if (!copied_decl)
632         continue;
633 
634       if (FieldDecl *copied_field = dyn_cast<FieldDecl>(copied_decl)) {
635         QualType copied_field_type = copied_field->getType();
636 
637         m_ast_importer_sp->RequireCompleteType(copied_field_type);
638       }
639       auto decl_context_non_const = const_cast<DeclContext *>(decl_context);
640 
641       // The decl ended up in the wrong DeclContext. Let's fix that so
642       // the decl we copied will actually be found.
643       // FIXME: This is a horrible hack that shouldn't be necessary. However
644       // it seems our current setup sometimes fails to copy decls to the right
645       // place. See rdar://55129537.
646       if (copied_decl->getDeclContext() != decl_context) {
647         assert(copied_decl->getDeclContext()->containsDecl(copied_decl));
648         copied_decl->getDeclContext()->removeDecl(copied_decl);
649         copied_decl->setDeclContext(decl_context_non_const);
650         assert(!decl_context_non_const->containsDecl(copied_decl));
651         decl_context_non_const->addDeclInternal(copied_decl);
652       }
653     } else {
654       SkippedDecls = true;
655     }
656   }
657 
658   // CopyDecl may build a lookup table which may set up ExternalLexicalStorage
659   // to false.  However, since we skipped some of the external Decls we must
660   // set it back!
661   if (SkippedDecls) {
662     decl_context->setHasExternalLexicalStorage(true);
663     // This sets HasLazyExternalLexicalLookups to true.  By setting this bit we
664     // ensure that the lookup table is rebuilt, which means the external source
665     // is consulted again when a clang::DeclContext::lookup is called.
666     const_cast<DeclContext *>(decl_context)->setMustBuildLookupTable();
667   }
668 
669   return;
670 }
671 
672 void ClangASTSource::FindExternalVisibleDecls(NameSearchContext &context) {
673   assert(m_ast_context);
674 
675   const ConstString name(context.m_decl_name.getAsString().c_str());
676 
677   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
678 
679   static unsigned int invocation_id = 0;
680   unsigned int current_id = invocation_id++;
681 
682   if (log) {
683     if (!context.m_decl_context)
684       LLDB_LOGF(log,
685                 "ClangASTSource::FindExternalVisibleDecls[%u] on "
686                 "(ASTContext*)%p for '%s' in a NULL DeclContext",
687                 current_id, static_cast<void *>(m_ast_context),
688                 name.GetCString());
689     else if (const NamedDecl *context_named_decl =
690                  dyn_cast<NamedDecl>(context.m_decl_context))
691       LLDB_LOGF(log,
692                 "ClangASTSource::FindExternalVisibleDecls[%u] on "
693                 "(ASTContext*)%p for '%s' in '%s'",
694                 current_id, static_cast<void *>(m_ast_context),
695                 name.GetCString(),
696                 context_named_decl->getNameAsString().c_str());
697     else
698       LLDB_LOGF(log,
699                 "ClangASTSource::FindExternalVisibleDecls[%u] on "
700                 "(ASTContext*)%p for '%s' in a '%s'",
701                 current_id, static_cast<void *>(m_ast_context),
702                 name.GetCString(), context.m_decl_context->getDeclKindName());
703   }
704 
705   if (HasMerger() && !isa<TranslationUnitDecl>(context.m_decl_context)
706       /* possibly handle NamespaceDecls here? */) {
707     if (auto *interface_decl =
708     dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) {
709       ObjCInterfaceDecl *complete_iface_decl =
710       GetCompleteObjCInterface(interface_decl);
711 
712       if (complete_iface_decl && (complete_iface_decl != interface_decl)) {
713         GetMergerUnchecked().ForceRecordOrigin(
714             interface_decl,
715             {complete_iface_decl, &complete_iface_decl->getASTContext()});
716       }
717     }
718 
719     GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context,
720                                                 context.m_decl_name);
721     return; // otherwise we may need to fall back
722   }
723 
724   context.m_namespace_map = std::make_shared<ClangASTImporter::NamespaceMap>();
725 
726   if (const NamespaceDecl *namespace_context =
727           dyn_cast<NamespaceDecl>(context.m_decl_context)) {
728     ClangASTImporter::NamespaceMapSP namespace_map =  m_ast_importer_sp ?
729         m_ast_importer_sp->GetNamespaceMap(namespace_context) : nullptr;
730 
731     if (log && log->GetVerbose())
732       LLDB_LOGF(log, "  CAS::FEVD[%u] Inspecting namespace map %p (%d entries)",
733                 current_id, static_cast<void *>(namespace_map.get()),
734                 static_cast<int>(namespace_map->size()));
735 
736     if (!namespace_map)
737       return;
738 
739     for (ClangASTImporter::NamespaceMap::iterator i = namespace_map->begin(),
740                                                   e = namespace_map->end();
741          i != e; ++i) {
742       LLDB_LOGF(log, "  CAS::FEVD[%u] Searching namespace %s in module %s",
743                 current_id, i->second.GetName().AsCString(),
744                 i->first->GetFileSpec().GetFilename().GetCString());
745 
746       FindExternalVisibleDecls(context, i->first, i->second, current_id);
747     }
748   } else if (isa<ObjCInterfaceDecl>(context.m_decl_context) && !HasMerger()) {
749     FindObjCPropertyAndIvarDecls(context);
750   } else if (!isa<TranslationUnitDecl>(context.m_decl_context)) {
751     // we shouldn't be getting FindExternalVisibleDecls calls for these
752     return;
753   } else {
754     CompilerDeclContext namespace_decl;
755 
756     LLDB_LOGF(log, "  CAS::FEVD[%u] Searching the root namespace", current_id);
757 
758     FindExternalVisibleDecls(context, lldb::ModuleSP(), namespace_decl,
759                              current_id);
760   }
761 
762   if (!context.m_namespace_map->empty()) {
763     if (log && log->GetVerbose())
764       LLDB_LOGF(log,
765                 "  CAS::FEVD[%u] Registering namespace map %p (%d entries)",
766                 current_id, static_cast<void *>(context.m_namespace_map.get()),
767                 static_cast<int>(context.m_namespace_map->size()));
768 
769     NamespaceDecl *clang_namespace_decl =
770         AddNamespace(context, context.m_namespace_map);
771 
772     if (clang_namespace_decl)
773       clang_namespace_decl->setHasExternalVisibleStorage();
774   }
775 }
776 
777 clang::Sema *ClangASTSource::getSema() {
778   return m_clang_ast_context->getSema();
779 }
780 
781 bool ClangASTSource::IgnoreName(const ConstString name,
782                                 bool ignore_all_dollar_names) {
783   static const ConstString id_name("id");
784   static const ConstString Class_name("Class");
785 
786   if (m_ast_context->getLangOpts().ObjC)
787     if (name == id_name || name == Class_name)
788       return true;
789 
790   StringRef name_string_ref = name.GetStringRef();
791 
792   // The ClangASTSource is not responsible for finding $-names.
793   return name_string_ref.empty() ||
794          (ignore_all_dollar_names && name_string_ref.startswith("$")) ||
795          name_string_ref.startswith("_$");
796 }
797 
798 void ClangASTSource::FindExternalVisibleDecls(
799     NameSearchContext &context, lldb::ModuleSP module_sp,
800     CompilerDeclContext &namespace_decl, unsigned int current_id) {
801   assert(m_ast_context);
802 
803   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
804 
805   SymbolContextList sc_list;
806 
807   const ConstString name(context.m_decl_name.getAsString().c_str());
808   if (IgnoreName(name, true))
809     return;
810 
811   if (module_sp && namespace_decl) {
812     CompilerDeclContext found_namespace_decl;
813 
814     if (SymbolFile *symbol_file = module_sp->GetSymbolFile()) {
815       found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl);
816 
817       if (found_namespace_decl) {
818         context.m_namespace_map->push_back(
819             std::pair<lldb::ModuleSP, CompilerDeclContext>(
820                 module_sp, found_namespace_decl));
821 
822         LLDB_LOGF(log, "  CAS::FEVD[%u] Found namespace %s in module %s",
823                   current_id, name.GetCString(),
824                   module_sp->GetFileSpec().GetFilename().GetCString());
825       }
826     }
827   } else if (!HasMerger()) {
828     const ModuleList &target_images = m_target->GetImages();
829     std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
830 
831     for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
832       lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
833 
834       if (!image)
835         continue;
836 
837       CompilerDeclContext found_namespace_decl;
838 
839       SymbolFile *symbol_file = image->GetSymbolFile();
840 
841       if (!symbol_file)
842         continue;
843 
844       found_namespace_decl = symbol_file->FindNamespace(name, &namespace_decl);
845 
846       if (found_namespace_decl) {
847         context.m_namespace_map->push_back(
848             std::pair<lldb::ModuleSP, CompilerDeclContext>(
849                 image, found_namespace_decl));
850 
851         LLDB_LOGF(log, "  CAS::FEVD[%u] Found namespace %s in module %s",
852                   current_id, name.GetCString(),
853                   image->GetFileSpec().GetFilename().GetCString());
854       }
855     }
856   }
857 
858   do {
859     if (context.m_found.type)
860       break;
861 
862     TypeList types;
863     const bool exact_match = true;
864     llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
865     if (module_sp && namespace_decl)
866       module_sp->FindTypesInNamespace(name, &namespace_decl, 1, types);
867     else {
868       m_target->GetImages().FindTypes(module_sp.get(), name, exact_match, 1,
869                                       searched_symbol_files, types);
870     }
871 
872     if (size_t num_types = types.GetSize()) {
873       for (size_t ti = 0; ti < num_types; ++ti) {
874         lldb::TypeSP type_sp = types.GetTypeAtIndex(ti);
875 
876         if (log) {
877           const char *name_string = type_sp->GetName().GetCString();
878 
879           LLDB_LOGF(log, "  CAS::FEVD[%u] Matching type found for \"%s\": %s",
880                     current_id, name.GetCString(),
881                     (name_string ? name_string : "<anonymous>"));
882         }
883 
884         CompilerType full_type = type_sp->GetFullCompilerType();
885 
886         CompilerType copied_clang_type(GuardedCopyType(full_type));
887 
888         if (!copied_clang_type) {
889           LLDB_LOGF(log, "  CAS::FEVD[%u] - Couldn't export a type",
890                     current_id);
891 
892           continue;
893         }
894 
895         context.AddTypeDecl(copied_clang_type);
896 
897         context.m_found.type = true;
898         break;
899       }
900     }
901 
902     if (!context.m_found.type) {
903       // Try the modules next.
904 
905       do {
906         if (ClangModulesDeclVendor *modules_decl_vendor =
907                 m_target->GetClangModulesDeclVendor()) {
908           bool append = false;
909           uint32_t max_matches = 1;
910           std::vector<clang::NamedDecl *> decls;
911 
912           if (!modules_decl_vendor->FindDecls(name, append, max_matches, decls))
913             break;
914 
915           if (log) {
916             LLDB_LOGF(log,
917                       "  CAS::FEVD[%u] Matching entity found for \"%s\" in "
918                       "the modules",
919                       current_id, name.GetCString());
920           }
921 
922           clang::NamedDecl *const decl_from_modules = decls[0];
923 
924           if (llvm::isa<clang::TypeDecl>(decl_from_modules) ||
925               llvm::isa<clang::ObjCContainerDecl>(decl_from_modules) ||
926               llvm::isa<clang::EnumConstantDecl>(decl_from_modules)) {
927             clang::Decl *copied_decl = CopyDecl(decl_from_modules);
928             clang::NamedDecl *copied_named_decl =
929                 copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
930 
931             if (!copied_named_decl) {
932               LLDB_LOGF(
933                   log,
934                   "  CAS::FEVD[%u] - Couldn't export a type from the modules",
935                   current_id);
936 
937               break;
938             }
939 
940             context.AddNamedDecl(copied_named_decl);
941 
942             context.m_found.type = true;
943           }
944         }
945       } while (false);
946     }
947 
948     if (!context.m_found.type) {
949       do {
950         // Couldn't find any types elsewhere.  Try the Objective-C runtime if
951         // one exists.
952 
953         lldb::ProcessSP process(m_target->GetProcessSP());
954 
955         if (!process)
956           break;
957 
958         ObjCLanguageRuntime *language_runtime(
959             ObjCLanguageRuntime::Get(*process));
960 
961         if (!language_runtime)
962           break;
963 
964         DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
965 
966         if (!decl_vendor)
967           break;
968 
969         bool append = false;
970         uint32_t max_matches = 1;
971         std::vector<clang::NamedDecl *> decls;
972 
973         auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
974         if (!clang_decl_vendor->FindDecls(name, append, max_matches, decls))
975           break;
976 
977         if (log) {
978           LLDB_LOGF(
979               log,
980               "  CAS::FEVD[%u] Matching type found for \"%s\" in the runtime",
981               current_id, name.GetCString());
982         }
983 
984         clang::Decl *copied_decl = CopyDecl(decls[0]);
985         clang::NamedDecl *copied_named_decl =
986             copied_decl ? dyn_cast<clang::NamedDecl>(copied_decl) : nullptr;
987 
988         if (!copied_named_decl) {
989           LLDB_LOGF(log,
990                     "  CAS::FEVD[%u] - Couldn't export a type from the runtime",
991                     current_id);
992 
993           break;
994         }
995 
996         context.AddNamedDecl(copied_named_decl);
997       } while (false);
998     }
999 
1000   } while (false);
1001 }
1002 
1003 template <class D> class TaggedASTDecl {
1004 public:
1005   TaggedASTDecl() : decl(nullptr) {}
1006   TaggedASTDecl(D *_decl) : decl(_decl) {}
1007   bool IsValid() const { return (decl != nullptr); }
1008   bool IsInvalid() const { return !IsValid(); }
1009   D *operator->() const { return decl; }
1010   D *decl;
1011 };
1012 
1013 template <class D2, template <class D> class TD, class D1>
1014 TD<D2> DynCast(TD<D1> source) {
1015   return TD<D2>(dyn_cast<D2>(source.decl));
1016 }
1017 
1018 template <class D = Decl> class DeclFromParser;
1019 template <class D = Decl> class DeclFromUser;
1020 
1021 template <class D> class DeclFromParser : public TaggedASTDecl<D> {
1022 public:
1023   DeclFromParser() : TaggedASTDecl<D>() {}
1024   DeclFromParser(D *_decl) : TaggedASTDecl<D>(_decl) {}
1025 
1026   DeclFromUser<D> GetOrigin(ClangASTSource &source);
1027 };
1028 
1029 template <class D> class DeclFromUser : public TaggedASTDecl<D> {
1030 public:
1031   DeclFromUser() : TaggedASTDecl<D>() {}
1032   DeclFromUser(D *_decl) : TaggedASTDecl<D>(_decl) {}
1033 
1034   DeclFromParser<D> Import(ClangASTSource &source);
1035 };
1036 
1037 template <class D>
1038 DeclFromUser<D> DeclFromParser<D>::GetOrigin(ClangASTSource &source) {
1039   DeclFromUser<> origin_decl;
1040   source.ResolveDeclOrigin(this->decl, &origin_decl.decl, nullptr);
1041   if (origin_decl.IsInvalid())
1042     return DeclFromUser<D>();
1043   return DeclFromUser<D>(dyn_cast<D>(origin_decl.decl));
1044 }
1045 
1046 template <class D>
1047 DeclFromParser<D> DeclFromUser<D>::Import(ClangASTSource &source) {
1048   DeclFromParser<> parser_generic_decl(source.CopyDecl(this->decl));
1049   if (parser_generic_decl.IsInvalid())
1050     return DeclFromParser<D>();
1051   return DeclFromParser<D>(dyn_cast<D>(parser_generic_decl.decl));
1052 }
1053 
1054 bool ClangASTSource::FindObjCMethodDeclsWithOrigin(
1055     unsigned int current_id, NameSearchContext &context,
1056     ObjCInterfaceDecl *original_interface_decl, const char *log_info) {
1057   const DeclarationName &decl_name(context.m_decl_name);
1058   clang::ASTContext *original_ctx = &original_interface_decl->getASTContext();
1059 
1060   Selector original_selector;
1061 
1062   if (decl_name.isObjCZeroArgSelector()) {
1063     IdentifierInfo *ident = &original_ctx->Idents.get(decl_name.getAsString());
1064     original_selector = original_ctx->Selectors.getSelector(0, &ident);
1065   } else if (decl_name.isObjCOneArgSelector()) {
1066     const std::string &decl_name_string = decl_name.getAsString();
1067     std::string decl_name_string_without_colon(decl_name_string.c_str(),
1068                                                decl_name_string.length() - 1);
1069     IdentifierInfo *ident =
1070         &original_ctx->Idents.get(decl_name_string_without_colon);
1071     original_selector = original_ctx->Selectors.getSelector(1, &ident);
1072   } else {
1073     SmallVector<IdentifierInfo *, 4> idents;
1074 
1075     clang::Selector sel = decl_name.getObjCSelector();
1076 
1077     unsigned num_args = sel.getNumArgs();
1078 
1079     for (unsigned i = 0; i != num_args; ++i) {
1080       idents.push_back(&original_ctx->Idents.get(sel.getNameForSlot(i)));
1081     }
1082 
1083     original_selector =
1084         original_ctx->Selectors.getSelector(num_args, idents.data());
1085   }
1086 
1087   DeclarationName original_decl_name(original_selector);
1088 
1089   llvm::SmallVector<NamedDecl *, 1> methods;
1090 
1091   ClangASTContext::GetCompleteDecl(original_ctx, original_interface_decl);
1092 
1093   if (ObjCMethodDecl *instance_method_decl =
1094           original_interface_decl->lookupInstanceMethod(original_selector)) {
1095     methods.push_back(instance_method_decl);
1096   } else if (ObjCMethodDecl *class_method_decl =
1097                  original_interface_decl->lookupClassMethod(
1098                      original_selector)) {
1099     methods.push_back(class_method_decl);
1100   }
1101 
1102   if (methods.empty()) {
1103     return false;
1104   }
1105 
1106   for (NamedDecl *named_decl : methods) {
1107     if (!named_decl)
1108       continue;
1109 
1110     ObjCMethodDecl *result_method = dyn_cast<ObjCMethodDecl>(named_decl);
1111 
1112     if (!result_method)
1113       continue;
1114 
1115     Decl *copied_decl = CopyDecl(result_method);
1116 
1117     if (!copied_decl)
1118       continue;
1119 
1120     ObjCMethodDecl *copied_method_decl = dyn_cast<ObjCMethodDecl>(copied_decl);
1121 
1122     if (!copied_method_decl)
1123       continue;
1124 
1125     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1126 
1127     LLDB_LOG(log, "  CAS::FOMD[{0}] found ({1}) {2}", current_id, log_info,
1128              ClangUtil::DumpDecl(copied_method_decl));
1129 
1130     context.AddNamedDecl(copied_method_decl);
1131   }
1132 
1133   return true;
1134 }
1135 
1136 void ClangASTSource::FindObjCMethodDecls(NameSearchContext &context) {
1137   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1138 
1139   if (HasMerger()) {
1140     if (auto *interface_decl = dyn_cast<ObjCInterfaceDecl>(context.m_decl_context)) {
1141       ObjCInterfaceDecl *complete_iface_decl =
1142           GetCompleteObjCInterface(interface_decl);
1143 
1144       if (complete_iface_decl && (complete_iface_decl != context.m_decl_context)) {
1145         m_merger_up->ForceRecordOrigin(interface_decl, {complete_iface_decl, &complete_iface_decl->getASTContext()});
1146       }
1147     }
1148 
1149     GetMergerUnchecked().FindExternalVisibleDeclsByName(context.m_decl_context,
1150                                                         context.m_decl_name);
1151     return;
1152   }
1153 
1154   static unsigned int invocation_id = 0;
1155   unsigned int current_id = invocation_id++;
1156 
1157   const DeclarationName &decl_name(context.m_decl_name);
1158   const DeclContext *decl_ctx(context.m_decl_context);
1159 
1160   const ObjCInterfaceDecl *interface_decl =
1161       dyn_cast<ObjCInterfaceDecl>(decl_ctx);
1162 
1163   if (!interface_decl)
1164     return;
1165 
1166   do {
1167     Decl *original_decl = nullptr;
1168     ASTContext *original_ctx = nullptr;
1169 
1170     m_ast_importer_sp->ResolveDeclOrigin(interface_decl, &original_decl,
1171                                          &original_ctx);
1172 
1173     if (!original_decl)
1174       break;
1175 
1176     ObjCInterfaceDecl *original_interface_decl =
1177         dyn_cast<ObjCInterfaceDecl>(original_decl);
1178 
1179     if (FindObjCMethodDeclsWithOrigin(current_id, context,
1180                                       original_interface_decl, "at origin"))
1181       return; // found it, no need to look any further
1182   } while (false);
1183 
1184   StreamString ss;
1185 
1186   if (decl_name.isObjCZeroArgSelector()) {
1187     ss.Printf("%s", decl_name.getAsString().c_str());
1188   } else if (decl_name.isObjCOneArgSelector()) {
1189     ss.Printf("%s", decl_name.getAsString().c_str());
1190   } else {
1191     clang::Selector sel = decl_name.getObjCSelector();
1192 
1193     for (unsigned i = 0, e = sel.getNumArgs(); i != e; ++i) {
1194       llvm::StringRef r = sel.getNameForSlot(i);
1195       ss.Printf("%s:", r.str().c_str());
1196     }
1197   }
1198   ss.Flush();
1199 
1200   if (ss.GetString().contains("$__lldb"))
1201     return; // we don't need any results
1202 
1203   ConstString selector_name(ss.GetString());
1204 
1205   LLDB_LOGF(log,
1206             "ClangASTSource::FindObjCMethodDecls[%d] on (ASTContext*)%p "
1207             "for selector [%s %s]",
1208             current_id, static_cast<void *>(m_ast_context),
1209             interface_decl->getNameAsString().c_str(),
1210             selector_name.AsCString());
1211   SymbolContextList sc_list;
1212 
1213   const bool include_symbols = false;
1214   const bool include_inlines = false;
1215 
1216   std::string interface_name = interface_decl->getNameAsString();
1217 
1218   do {
1219     StreamString ms;
1220     ms.Printf("-[%s %s]", interface_name.c_str(), selector_name.AsCString());
1221     ms.Flush();
1222     ConstString instance_method_name(ms.GetString());
1223 
1224     sc_list.Clear();
1225     m_target->GetImages().FindFunctions(
1226         instance_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1227         include_inlines, sc_list);
1228 
1229     if (sc_list.GetSize())
1230       break;
1231 
1232     ms.Clear();
1233     ms.Printf("+[%s %s]", interface_name.c_str(), selector_name.AsCString());
1234     ms.Flush();
1235     ConstString class_method_name(ms.GetString());
1236 
1237     sc_list.Clear();
1238     m_target->GetImages().FindFunctions(
1239         class_method_name, lldb::eFunctionNameTypeFull, include_symbols,
1240         include_inlines, sc_list);
1241 
1242     if (sc_list.GetSize())
1243       break;
1244 
1245     // Fall back and check for methods in categories.  If we find methods this
1246     // way, we need to check that they're actually in categories on the desired
1247     // class.
1248 
1249     SymbolContextList candidate_sc_list;
1250 
1251     m_target->GetImages().FindFunctions(
1252         selector_name, lldb::eFunctionNameTypeSelector, include_symbols,
1253         include_inlines, candidate_sc_list);
1254 
1255     for (uint32_t ci = 0, ce = candidate_sc_list.GetSize(); ci != ce; ++ci) {
1256       SymbolContext candidate_sc;
1257 
1258       if (!candidate_sc_list.GetContextAtIndex(ci, candidate_sc))
1259         continue;
1260 
1261       if (!candidate_sc.function)
1262         continue;
1263 
1264       const char *candidate_name = candidate_sc.function->GetName().AsCString();
1265 
1266       const char *cursor = candidate_name;
1267 
1268       if (*cursor != '+' && *cursor != '-')
1269         continue;
1270 
1271       ++cursor;
1272 
1273       if (*cursor != '[')
1274         continue;
1275 
1276       ++cursor;
1277 
1278       size_t interface_len = interface_name.length();
1279 
1280       if (strncmp(cursor, interface_name.c_str(), interface_len))
1281         continue;
1282 
1283       cursor += interface_len;
1284 
1285       if (*cursor == ' ' || *cursor == '(')
1286         sc_list.Append(candidate_sc);
1287     }
1288   } while (false);
1289 
1290   if (sc_list.GetSize()) {
1291     // We found a good function symbol.  Use that.
1292 
1293     for (uint32_t i = 0, e = sc_list.GetSize(); i != e; ++i) {
1294       SymbolContext sc;
1295 
1296       if (!sc_list.GetContextAtIndex(i, sc))
1297         continue;
1298 
1299       if (!sc.function)
1300         continue;
1301 
1302       CompilerDeclContext function_decl_ctx = sc.function->GetDeclContext();
1303       if (!function_decl_ctx)
1304         continue;
1305 
1306       ObjCMethodDecl *method_decl =
1307           ClangASTContext::DeclContextGetAsObjCMethodDecl(function_decl_ctx);
1308 
1309       if (!method_decl)
1310         continue;
1311 
1312       ObjCInterfaceDecl *found_interface_decl =
1313           method_decl->getClassInterface();
1314 
1315       if (!found_interface_decl)
1316         continue;
1317 
1318       if (found_interface_decl->getName() == interface_decl->getName()) {
1319         Decl *copied_decl = CopyDecl(method_decl);
1320 
1321         if (!copied_decl)
1322           continue;
1323 
1324         ObjCMethodDecl *copied_method_decl =
1325             dyn_cast<ObjCMethodDecl>(copied_decl);
1326 
1327         if (!copied_method_decl)
1328           continue;
1329 
1330         LLDB_LOG(log, "  CAS::FOMD[{0}] found (in symbols)\n{1}", current_id,
1331                  ClangUtil::DumpDecl(copied_method_decl));
1332 
1333         context.AddNamedDecl(copied_method_decl);
1334       }
1335     }
1336 
1337     return;
1338   }
1339 
1340   // Try the debug information.
1341 
1342   do {
1343     ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1344         const_cast<ObjCInterfaceDecl *>(interface_decl));
1345 
1346     if (!complete_interface_decl)
1347       break;
1348 
1349     // We found the complete interface.  The runtime never needs to be queried
1350     // in this scenario.
1351 
1352     DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1353         complete_interface_decl);
1354 
1355     if (complete_interface_decl == interface_decl)
1356       break; // already checked this one
1357 
1358     LLDB_LOGF(log,
1359               "CAS::FOPD[%d] trying origin "
1360               "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1361               current_id, static_cast<void *>(complete_interface_decl),
1362               static_cast<void *>(&complete_iface_decl->getASTContext()));
1363 
1364     FindObjCMethodDeclsWithOrigin(current_id, context, complete_interface_decl,
1365                                   "in debug info");
1366 
1367     return;
1368   } while (false);
1369 
1370   do {
1371     // Check the modules only if the debug information didn't have a complete
1372     // interface.
1373 
1374     if (ClangModulesDeclVendor *modules_decl_vendor =
1375             m_target->GetClangModulesDeclVendor()) {
1376       ConstString interface_name(interface_decl->getNameAsString().c_str());
1377       bool append = false;
1378       uint32_t max_matches = 1;
1379       std::vector<clang::NamedDecl *> decls;
1380 
1381       if (!modules_decl_vendor->FindDecls(interface_name, append, max_matches,
1382                                           decls))
1383         break;
1384 
1385       ObjCInterfaceDecl *interface_decl_from_modules =
1386           dyn_cast<ObjCInterfaceDecl>(decls[0]);
1387 
1388       if (!interface_decl_from_modules)
1389         break;
1390 
1391       if (FindObjCMethodDeclsWithOrigin(
1392               current_id, context, interface_decl_from_modules, "in modules"))
1393         return;
1394     }
1395   } while (false);
1396 
1397   do {
1398     // Check the runtime only if the debug information didn't have a complete
1399     // interface and the modules don't get us anywhere.
1400 
1401     lldb::ProcessSP process(m_target->GetProcessSP());
1402 
1403     if (!process)
1404       break;
1405 
1406     ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1407 
1408     if (!language_runtime)
1409       break;
1410 
1411     DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1412 
1413     if (!decl_vendor)
1414       break;
1415 
1416     ConstString interface_name(interface_decl->getNameAsString().c_str());
1417     bool append = false;
1418     uint32_t max_matches = 1;
1419     std::vector<clang::NamedDecl *> decls;
1420 
1421     auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1422     if (!clang_decl_vendor->FindDecls(interface_name, append, max_matches,
1423                                       decls))
1424       break;
1425 
1426     ObjCInterfaceDecl *runtime_interface_decl =
1427         dyn_cast<ObjCInterfaceDecl>(decls[0]);
1428 
1429     if (!runtime_interface_decl)
1430       break;
1431 
1432     FindObjCMethodDeclsWithOrigin(current_id, context, runtime_interface_decl,
1433                                   "in runtime");
1434   } while (false);
1435 }
1436 
1437 static bool FindObjCPropertyAndIvarDeclsWithOrigin(
1438     unsigned int current_id, NameSearchContext &context, ClangASTSource &source,
1439     DeclFromUser<const ObjCInterfaceDecl> &origin_iface_decl) {
1440   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1441 
1442   if (origin_iface_decl.IsInvalid())
1443     return false;
1444 
1445   std::string name_str = context.m_decl_name.getAsString();
1446   StringRef name(name_str);
1447   IdentifierInfo &name_identifier(
1448       origin_iface_decl->getASTContext().Idents.get(name));
1449 
1450   DeclFromUser<ObjCPropertyDecl> origin_property_decl(
1451       origin_iface_decl->FindPropertyDeclaration(
1452           &name_identifier, ObjCPropertyQueryKind::OBJC_PR_query_instance));
1453 
1454   bool found = false;
1455 
1456   if (origin_property_decl.IsValid()) {
1457     DeclFromParser<ObjCPropertyDecl> parser_property_decl(
1458         origin_property_decl.Import(source));
1459     if (parser_property_decl.IsValid()) {
1460       LLDB_LOG(log, "  CAS::FOPD[{0}] found\n{1}", current_id,
1461                ClangUtil::DumpDecl(parser_property_decl.decl));
1462 
1463       context.AddNamedDecl(parser_property_decl.decl);
1464       found = true;
1465     }
1466   }
1467 
1468   DeclFromUser<ObjCIvarDecl> origin_ivar_decl(
1469       origin_iface_decl->getIvarDecl(&name_identifier));
1470 
1471   if (origin_ivar_decl.IsValid()) {
1472     DeclFromParser<ObjCIvarDecl> parser_ivar_decl(
1473         origin_ivar_decl.Import(source));
1474     if (parser_ivar_decl.IsValid()) {
1475       if (log) {
1476         LLDB_LOG(log, "  CAS::FOPD[{0}] found\n{1}", current_id,
1477                  ClangUtil::DumpDecl(parser_ivar_decl.decl));
1478       }
1479 
1480       context.AddNamedDecl(parser_ivar_decl.decl);
1481       found = true;
1482     }
1483   }
1484 
1485   return found;
1486 }
1487 
1488 void ClangASTSource::FindObjCPropertyAndIvarDecls(NameSearchContext &context) {
1489   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1490 
1491   static unsigned int invocation_id = 0;
1492   unsigned int current_id = invocation_id++;
1493 
1494   DeclFromParser<const ObjCInterfaceDecl> parser_iface_decl(
1495       cast<ObjCInterfaceDecl>(context.m_decl_context));
1496   DeclFromUser<const ObjCInterfaceDecl> origin_iface_decl(
1497       parser_iface_decl.GetOrigin(*this));
1498 
1499   ConstString class_name(parser_iface_decl->getNameAsString().c_str());
1500 
1501   LLDB_LOGF(log,
1502             "ClangASTSource::FindObjCPropertyAndIvarDecls[%d] on "
1503             "(ASTContext*)%p for '%s.%s'",
1504             current_id, static_cast<void *>(m_ast_context),
1505             parser_iface_decl->getNameAsString().c_str(),
1506             context.m_decl_name.getAsString().c_str());
1507 
1508   if (FindObjCPropertyAndIvarDeclsWithOrigin(
1509           current_id, context, *this, origin_iface_decl))
1510     return;
1511 
1512   LLDB_LOGF(log,
1513             "CAS::FOPD[%d] couldn't find the property on origin "
1514             "(ObjCInterfaceDecl*)%p/(ASTContext*)%p, searching "
1515             "elsewhere...",
1516             current_id, static_cast<const void *>(origin_iface_decl.decl),
1517             static_cast<void *>(&origin_iface_decl->getASTContext()));
1518 
1519   SymbolContext null_sc;
1520   TypeList type_list;
1521 
1522   do {
1523     ObjCInterfaceDecl *complete_interface_decl = GetCompleteObjCInterface(
1524         const_cast<ObjCInterfaceDecl *>(parser_iface_decl.decl));
1525 
1526     if (!complete_interface_decl)
1527       break;
1528 
1529     // We found the complete interface.  The runtime never needs to be queried
1530     // in this scenario.
1531 
1532     DeclFromUser<const ObjCInterfaceDecl> complete_iface_decl(
1533         complete_interface_decl);
1534 
1535     if (complete_iface_decl.decl == origin_iface_decl.decl)
1536       break; // already checked this one
1537 
1538     LLDB_LOGF(log,
1539               "CAS::FOPD[%d] trying origin "
1540               "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1541               current_id, static_cast<const void *>(complete_iface_decl.decl),
1542               static_cast<void *>(&complete_iface_decl->getASTContext()));
1543 
1544     FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1545                                            complete_iface_decl);
1546 
1547     return;
1548   } while (false);
1549 
1550   do {
1551     // Check the modules only if the debug information didn't have a complete
1552     // interface.
1553 
1554     ClangModulesDeclVendor *modules_decl_vendor =
1555         m_target->GetClangModulesDeclVendor();
1556 
1557     if (!modules_decl_vendor)
1558       break;
1559 
1560     bool append = false;
1561     uint32_t max_matches = 1;
1562     std::vector<clang::NamedDecl *> decls;
1563 
1564     if (!modules_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1565       break;
1566 
1567     DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_modules(
1568         dyn_cast<ObjCInterfaceDecl>(decls[0]));
1569 
1570     if (!interface_decl_from_modules.IsValid())
1571       break;
1572 
1573     LLDB_LOGF(
1574         log,
1575         "CAS::FOPD[%d] trying module "
1576         "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1577         current_id, static_cast<const void *>(interface_decl_from_modules.decl),
1578         static_cast<void *>(&interface_decl_from_modules->getASTContext()));
1579 
1580     if (FindObjCPropertyAndIvarDeclsWithOrigin(current_id, context, *this,
1581                                                interface_decl_from_modules))
1582       return;
1583   } while (false);
1584 
1585   do {
1586     // Check the runtime only if the debug information didn't have a complete
1587     // interface and nothing was in the modules.
1588 
1589     lldb::ProcessSP process(m_target->GetProcessSP());
1590 
1591     if (!process)
1592       return;
1593 
1594     ObjCLanguageRuntime *language_runtime(ObjCLanguageRuntime::Get(*process));
1595 
1596     if (!language_runtime)
1597       return;
1598 
1599     DeclVendor *decl_vendor = language_runtime->GetDeclVendor();
1600 
1601     if (!decl_vendor)
1602       break;
1603 
1604     bool append = false;
1605     uint32_t max_matches = 1;
1606     std::vector<clang::NamedDecl *> decls;
1607 
1608     auto *clang_decl_vendor = llvm::cast<ClangDeclVendor>(decl_vendor);
1609     if (!clang_decl_vendor->FindDecls(class_name, append, max_matches, decls))
1610       break;
1611 
1612     DeclFromUser<const ObjCInterfaceDecl> interface_decl_from_runtime(
1613         dyn_cast<ObjCInterfaceDecl>(decls[0]));
1614 
1615     if (!interface_decl_from_runtime.IsValid())
1616       break;
1617 
1618     LLDB_LOGF(
1619         log,
1620         "CAS::FOPD[%d] trying runtime "
1621         "(ObjCInterfaceDecl*)%p/(ASTContext*)%p...",
1622         current_id, static_cast<const void *>(interface_decl_from_runtime.decl),
1623         static_cast<void *>(&interface_decl_from_runtime->getASTContext()));
1624 
1625     if (FindObjCPropertyAndIvarDeclsWithOrigin(
1626             current_id, context, *this, interface_decl_from_runtime))
1627       return;
1628   } while (false);
1629 }
1630 
1631 typedef llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsetMap;
1632 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetMap;
1633 
1634 template <class D, class O>
1635 static bool ImportOffsetMap(llvm::DenseMap<const D *, O> &destination_map,
1636                             llvm::DenseMap<const D *, O> &source_map,
1637                             ClangASTSource &source) {
1638   // When importing fields into a new record, clang has a hard requirement that
1639   // fields be imported in field offset order.  Since they are stored in a
1640   // DenseMap with a pointer as the key type, this means we cannot simply
1641   // iterate over the map, as the order will be non-deterministic.  Instead we
1642   // have to sort by the offset and then insert in sorted order.
1643   typedef llvm::DenseMap<const D *, O> MapType;
1644   typedef typename MapType::value_type PairType;
1645   std::vector<PairType> sorted_items;
1646   sorted_items.reserve(source_map.size());
1647   sorted_items.assign(source_map.begin(), source_map.end());
1648   llvm::sort(sorted_items.begin(), sorted_items.end(),
1649              [](const PairType &lhs, const PairType &rhs) {
1650                return lhs.second < rhs.second;
1651              });
1652 
1653   for (const auto &item : sorted_items) {
1654     DeclFromUser<D> user_decl(const_cast<D *>(item.first));
1655     DeclFromParser<D> parser_decl(user_decl.Import(source));
1656     if (parser_decl.IsInvalid())
1657       return false;
1658     destination_map.insert(
1659         std::pair<const D *, O>(parser_decl.decl, item.second));
1660   }
1661 
1662   return true;
1663 }
1664 
1665 template <bool IsVirtual>
1666 bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
1667                         DeclFromUser<const CXXRecordDecl> &record,
1668                         BaseOffsetMap &base_offsets) {
1669   for (CXXRecordDecl::base_class_const_iterator
1670            bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
1671            be = (IsVirtual ? record->vbases_end() : record->bases_end());
1672        bi != be; ++bi) {
1673     if (!IsVirtual && bi->isVirtual())
1674       continue;
1675 
1676     const clang::Type *origin_base_type = bi->getType().getTypePtr();
1677     const clang::RecordType *origin_base_record_type =
1678         origin_base_type->getAs<RecordType>();
1679 
1680     if (!origin_base_record_type)
1681       return false;
1682 
1683     DeclFromUser<RecordDecl> origin_base_record(
1684         origin_base_record_type->getDecl());
1685 
1686     if (origin_base_record.IsInvalid())
1687       return false;
1688 
1689     DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
1690         DynCast<CXXRecordDecl>(origin_base_record));
1691 
1692     if (origin_base_cxx_record.IsInvalid())
1693       return false;
1694 
1695     CharUnits base_offset;
1696 
1697     if (IsVirtual)
1698       base_offset =
1699           record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
1700     else
1701       base_offset =
1702           record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
1703 
1704     base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
1705         origin_base_cxx_record.decl, base_offset));
1706   }
1707 
1708   return true;
1709 }
1710 
1711 bool ClangASTSource::layoutRecordType(const RecordDecl *record, uint64_t &size,
1712                                       uint64_t &alignment,
1713                                       FieldOffsetMap &field_offsets,
1714                                       BaseOffsetMap &base_offsets,
1715                                       BaseOffsetMap &virtual_base_offsets) {
1716   static unsigned int invocation_id = 0;
1717   unsigned int current_id = invocation_id++;
1718 
1719   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1720 
1721   LLDB_LOGF(log,
1722             "LayoutRecordType[%u] on (ASTContext*)%p for (RecordDecl*)%p "
1723             "[name = '%s']",
1724             current_id, static_cast<void *>(m_ast_context),
1725             static_cast<const void *>(record),
1726             record->getNameAsString().c_str());
1727 
1728   DeclFromParser<const RecordDecl> parser_record(record);
1729   DeclFromUser<const RecordDecl> origin_record(
1730       parser_record.GetOrigin(*this));
1731 
1732   if (origin_record.IsInvalid())
1733     return false;
1734 
1735   FieldOffsetMap origin_field_offsets;
1736   BaseOffsetMap origin_base_offsets;
1737   BaseOffsetMap origin_virtual_base_offsets;
1738 
1739   ClangASTContext::GetCompleteDecl(
1740       &origin_record->getASTContext(),
1741       const_cast<RecordDecl *>(origin_record.decl));
1742 
1743   clang::RecordDecl *definition = origin_record.decl->getDefinition();
1744   if (!definition || !definition->isCompleteDefinition())
1745     return false;
1746 
1747   const ASTRecordLayout &record_layout(
1748       origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
1749 
1750   int field_idx = 0, field_count = record_layout.getFieldCount();
1751 
1752   for (RecordDecl::field_iterator fi = origin_record->field_begin(),
1753                                   fe = origin_record->field_end();
1754        fi != fe; ++fi) {
1755     if (field_idx >= field_count)
1756       return false; // Layout didn't go well.  Bail out.
1757 
1758     uint64_t field_offset = record_layout.getFieldOffset(field_idx);
1759 
1760     origin_field_offsets.insert(
1761         std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
1762 
1763     field_idx++;
1764   }
1765 
1766   lldbassert(&record->getASTContext() == m_ast_context);
1767 
1768   DeclFromUser<const CXXRecordDecl> origin_cxx_record(
1769       DynCast<const CXXRecordDecl>(origin_record));
1770 
1771   if (origin_cxx_record.IsValid()) {
1772     if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
1773                                    origin_base_offsets) ||
1774         !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
1775                                   origin_virtual_base_offsets))
1776       return false;
1777   }
1778 
1779   if (!ImportOffsetMap(field_offsets, origin_field_offsets, *this) ||
1780       !ImportOffsetMap(base_offsets, origin_base_offsets, *this) ||
1781       !ImportOffsetMap(virtual_base_offsets, origin_virtual_base_offsets,
1782                        *this))
1783     return false;
1784 
1785   size = record_layout.getSize().getQuantity() * m_ast_context->getCharWidth();
1786   alignment = record_layout.getAlignment().getQuantity() *
1787               m_ast_context->getCharWidth();
1788 
1789   if (log) {
1790     LLDB_LOGF(log, "LRT[%u] returned:", current_id);
1791     LLDB_LOGF(log, "LRT[%u]   Original = (RecordDecl*)%p", current_id,
1792               static_cast<const void *>(origin_record.decl));
1793     LLDB_LOGF(log, "LRT[%u]   Size = %" PRId64, current_id, size);
1794     LLDB_LOGF(log, "LRT[%u]   Alignment = %" PRId64, current_id, alignment);
1795     LLDB_LOGF(log, "LRT[%u]   Fields:", current_id);
1796     for (RecordDecl::field_iterator fi = record->field_begin(),
1797                                     fe = record->field_end();
1798          fi != fe; ++fi) {
1799       LLDB_LOGF(log,
1800                 "LRT[%u]     (FieldDecl*)%p, Name = '%s', Offset = %" PRId64
1801                 " bits",
1802                 current_id, static_cast<void *>(*fi),
1803                 fi->getNameAsString().c_str(), field_offsets[*fi]);
1804     }
1805     DeclFromParser<const CXXRecordDecl> parser_cxx_record =
1806         DynCast<const CXXRecordDecl>(parser_record);
1807     if (parser_cxx_record.IsValid()) {
1808       LLDB_LOGF(log, "LRT[%u]   Bases:", current_id);
1809       for (CXXRecordDecl::base_class_const_iterator
1810                bi = parser_cxx_record->bases_begin(),
1811                be = parser_cxx_record->bases_end();
1812            bi != be; ++bi) {
1813         bool is_virtual = bi->isVirtual();
1814 
1815         QualType base_type = bi->getType();
1816         const RecordType *base_record_type = base_type->getAs<RecordType>();
1817         DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
1818         DeclFromParser<CXXRecordDecl> base_cxx_record =
1819             DynCast<CXXRecordDecl>(base_record);
1820 
1821         LLDB_LOGF(
1822             log,
1823             "LRT[%u]     %s(CXXRecordDecl*)%p, Name = '%s', Offset = %" PRId64
1824             " chars",
1825             current_id, (is_virtual ? "Virtual " : ""),
1826             static_cast<void *>(base_cxx_record.decl),
1827             base_cxx_record.decl->getNameAsString().c_str(),
1828             (is_virtual
1829                  ? virtual_base_offsets[base_cxx_record.decl].getQuantity()
1830                  : base_offsets[base_cxx_record.decl].getQuantity()));
1831       }
1832     } else {
1833       LLDB_LOGF(log, "LRD[%u]   Not a CXXRecord, so no bases", current_id);
1834     }
1835   }
1836 
1837   return true;
1838 }
1839 
1840 void ClangASTSource::CompleteNamespaceMap(
1841     ClangASTImporter::NamespaceMapSP &namespace_map, ConstString name,
1842     ClangASTImporter::NamespaceMapSP &parent_map) const {
1843   static unsigned int invocation_id = 0;
1844   unsigned int current_id = invocation_id++;
1845 
1846   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1847 
1848   if (log) {
1849     if (parent_map && parent_map->size())
1850       LLDB_LOGF(log,
1851                 "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1852                 "namespace %s in namespace %s",
1853                 current_id, static_cast<void *>(m_ast_context),
1854                 name.GetCString(),
1855                 parent_map->begin()->second.GetName().AsCString());
1856     else
1857       LLDB_LOGF(log,
1858                 "CompleteNamespaceMap[%u] on (ASTContext*)%p Searching for "
1859                 "namespace %s",
1860                 current_id, static_cast<void *>(m_ast_context),
1861                 name.GetCString());
1862   }
1863 
1864   if (parent_map) {
1865     for (ClangASTImporter::NamespaceMap::iterator i = parent_map->begin(),
1866                                                   e = parent_map->end();
1867          i != e; ++i) {
1868       CompilerDeclContext found_namespace_decl;
1869 
1870       lldb::ModuleSP module_sp = i->first;
1871       CompilerDeclContext module_parent_namespace_decl = i->second;
1872 
1873       SymbolFile *symbol_file = module_sp->GetSymbolFile();
1874 
1875       if (!symbol_file)
1876         continue;
1877 
1878       found_namespace_decl =
1879           symbol_file->FindNamespace(name, &module_parent_namespace_decl);
1880 
1881       if (!found_namespace_decl)
1882         continue;
1883 
1884       namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1885           module_sp, found_namespace_decl));
1886 
1887       LLDB_LOGF(log, "  CMN[%u] Found namespace %s in module %s", current_id,
1888                 name.GetCString(),
1889                 module_sp->GetFileSpec().GetFilename().GetCString());
1890     }
1891   } else {
1892     const ModuleList &target_images = m_target->GetImages();
1893     std::lock_guard<std::recursive_mutex> guard(target_images.GetMutex());
1894 
1895     CompilerDeclContext null_namespace_decl;
1896 
1897     for (size_t i = 0, e = target_images.GetSize(); i < e; ++i) {
1898       lldb::ModuleSP image = target_images.GetModuleAtIndexUnlocked(i);
1899 
1900       if (!image)
1901         continue;
1902 
1903       CompilerDeclContext found_namespace_decl;
1904 
1905       SymbolFile *symbol_file = image->GetSymbolFile();
1906 
1907       if (!symbol_file)
1908         continue;
1909 
1910       found_namespace_decl =
1911           symbol_file->FindNamespace(name, &null_namespace_decl);
1912 
1913       if (!found_namespace_decl)
1914         continue;
1915 
1916       namespace_map->push_back(std::pair<lldb::ModuleSP, CompilerDeclContext>(
1917           image, found_namespace_decl));
1918 
1919       LLDB_LOGF(log, "  CMN[%u] Found namespace %s in module %s", current_id,
1920                 name.GetCString(),
1921                 image->GetFileSpec().GetFilename().GetCString());
1922     }
1923   }
1924 }
1925 
1926 NamespaceDecl *ClangASTSource::AddNamespace(
1927     NameSearchContext &context,
1928     ClangASTImporter::NamespaceMapSP &namespace_decls) {
1929   if (!namespace_decls)
1930     return nullptr;
1931 
1932   const CompilerDeclContext &namespace_decl = namespace_decls->begin()->second;
1933 
1934   clang::ASTContext *src_ast =
1935       ClangASTContext::DeclContextGetClangASTContext(namespace_decl);
1936   if (!src_ast)
1937     return nullptr;
1938   clang::NamespaceDecl *src_namespace_decl =
1939       ClangASTContext::DeclContextGetAsNamespaceDecl(namespace_decl);
1940 
1941   if (!src_namespace_decl)
1942     return nullptr;
1943 
1944   Decl *copied_decl = CopyDecl(src_namespace_decl);
1945 
1946   if (!copied_decl)
1947     return nullptr;
1948 
1949   NamespaceDecl *copied_namespace_decl = dyn_cast<NamespaceDecl>(copied_decl);
1950 
1951   if (!copied_namespace_decl)
1952     return nullptr;
1953 
1954   context.m_decls.push_back(copied_namespace_decl);
1955 
1956   m_ast_importer_sp->RegisterNamespaceMap(copied_namespace_decl,
1957                                           namespace_decls);
1958 
1959   return dyn_cast<NamespaceDecl>(copied_decl);
1960 }
1961 
1962 clang::QualType ClangASTSource::CopyTypeWithMerger(
1963     clang::ASTContext &from_context,
1964     clang::ExternalASTMerger &merger,
1965     clang::QualType type) {
1966   if (!merger.HasImporterForOrigin(from_context)) {
1967     lldbassert(0 && "Couldn't find the importer for a source context!");
1968     return QualType();
1969   }
1970 
1971   if (llvm::Expected<QualType> type_or_error =
1972           merger.ImporterForOrigin(from_context).Import(type)) {
1973     return *type_or_error;
1974   } else {
1975     Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
1976     LLDB_LOG_ERROR(log, type_or_error.takeError(), "Couldn't import type: {0}");
1977     return QualType();
1978   }
1979 }
1980 
1981 clang::Decl *ClangASTSource::CopyDecl(Decl *src_decl) {
1982   clang::ASTContext &from_context = src_decl->getASTContext();
1983   if (m_ast_importer_sp) {
1984     return m_ast_importer_sp->CopyDecl(m_ast_context, &from_context, src_decl);
1985   } else if (m_merger_up) {
1986     if (!m_merger_up->HasImporterForOrigin(from_context)) {
1987       lldbassert(0 && "Couldn't find the importer for a source context!");
1988       return nullptr;
1989     }
1990 
1991     if (llvm::Expected<Decl *> decl_or_error =
1992             m_merger_up->ImporterForOrigin(from_context).Import(src_decl)) {
1993       return *decl_or_error;
1994     } else {
1995       Log *log =
1996           lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
1997       LLDB_LOG_ERROR(log, decl_or_error.takeError(),
1998                      "Couldn't import decl: {0}");
1999       return nullptr;
2000     }
2001   } else {
2002     lldbassert(0 && "No mechanism for copying a decl!");
2003     return nullptr;
2004   }
2005 }
2006 
2007 bool ClangASTSource::ResolveDeclOrigin(const clang::Decl *decl,
2008                                        clang::Decl **original_decl,
2009                                        clang::ASTContext **original_ctx) {
2010   if (m_ast_importer_sp) {
2011     return m_ast_importer_sp->ResolveDeclOrigin(decl, original_decl,
2012                                                 original_ctx);
2013   } else if (m_merger_up) {
2014     return false; // Implement this correctly in ExternalASTMerger
2015   } else {
2016     // this can happen early enough that no ExternalASTSource is installed.
2017     return false;
2018   }
2019 }
2020 
2021 clang::ExternalASTMerger &ClangASTSource::GetMergerUnchecked() {
2022   lldbassert(m_merger_up != nullptr);
2023   return *m_merger_up;
2024 }
2025 
2026 CompilerType ClangASTSource::GuardedCopyType(const CompilerType &src_type) {
2027   ClangASTContext *src_ast =
2028       llvm::dyn_cast_or_null<ClangASTContext>(src_type.GetTypeSystem());
2029   if (src_ast == nullptr)
2030     return CompilerType();
2031 
2032   SetImportInProgress(true);
2033 
2034   QualType copied_qual_type;
2035 
2036   if (m_ast_importer_sp) {
2037     copied_qual_type =
2038         m_ast_importer_sp->CopyType(m_ast_context, src_ast->getASTContext(),
2039                                     ClangUtil::GetQualType(src_type));
2040   } else if (m_merger_up) {
2041     copied_qual_type =
2042         CopyTypeWithMerger(*src_ast->getASTContext(), *m_merger_up,
2043                  ClangUtil::GetQualType(src_type));
2044   } else {
2045     lldbassert(0 && "No mechanism for copying a type!");
2046     return CompilerType();
2047   }
2048 
2049   SetImportInProgress(false);
2050 
2051   if (copied_qual_type.getAsOpaquePtr() &&
2052       copied_qual_type->getCanonicalTypeInternal().isNull())
2053     // this shouldn't happen, but we're hardening because the AST importer
2054     // seems to be generating bad types on occasion.
2055     return CompilerType();
2056 
2057   return CompilerType(m_clang_ast_context, copied_qual_type.getAsOpaquePtr());
2058 }
2059 
2060 clang::NamedDecl *NameSearchContext::AddVarDecl(const CompilerType &type) {
2061   assert(type && "Type for variable must be valid!");
2062 
2063   if (!type.IsValid())
2064     return nullptr;
2065 
2066   ClangASTContext *lldb_ast =
2067       llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
2068   if (!lldb_ast)
2069     return nullptr;
2070 
2071   IdentifierInfo *ii = m_decl_name.getAsIdentifierInfo();
2072 
2073   clang::ASTContext *ast = lldb_ast->getASTContext();
2074 
2075   clang::NamedDecl *Decl = VarDecl::Create(
2076       *ast, const_cast<DeclContext *>(m_decl_context), SourceLocation(),
2077       SourceLocation(), ii, ClangUtil::GetQualType(type), nullptr, SC_Static);
2078   m_decls.push_back(Decl);
2079 
2080   return Decl;
2081 }
2082 
2083 clang::NamedDecl *NameSearchContext::AddFunDecl(const CompilerType &type,
2084                                                 bool extern_c) {
2085   assert(type && "Type for variable must be valid!");
2086 
2087   if (!type.IsValid())
2088     return nullptr;
2089 
2090   if (m_function_types.count(type))
2091     return nullptr;
2092 
2093   ClangASTContext *lldb_ast =
2094       llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
2095   if (!lldb_ast)
2096     return nullptr;
2097 
2098   m_function_types.insert(type);
2099 
2100   QualType qual_type(ClangUtil::GetQualType(type));
2101 
2102   clang::ASTContext *ast = lldb_ast->getASTContext();
2103 
2104   const bool isInlineSpecified = false;
2105   const bool hasWrittenPrototype = true;
2106   const bool isConstexprSpecified = false;
2107 
2108   clang::DeclContext *context = const_cast<DeclContext *>(m_decl_context);
2109 
2110   if (extern_c) {
2111     context = LinkageSpecDecl::Create(
2112         *ast, context, SourceLocation(), SourceLocation(),
2113         clang::LinkageSpecDecl::LanguageIDs::lang_c, false);
2114   }
2115 
2116   // Pass the identifier info for functions the decl_name is needed for
2117   // operators
2118   clang::DeclarationName decl_name =
2119       m_decl_name.getNameKind() == DeclarationName::Identifier
2120           ? m_decl_name.getAsIdentifierInfo()
2121           : m_decl_name;
2122 
2123   clang::FunctionDecl *func_decl = FunctionDecl::Create(
2124       *ast, context, SourceLocation(), SourceLocation(), decl_name, qual_type,
2125       nullptr, SC_Extern, isInlineSpecified, hasWrittenPrototype,
2126       isConstexprSpecified ? CSK_constexpr : CSK_unspecified);
2127 
2128   // We have to do more than just synthesize the FunctionDecl.  We have to
2129   // synthesize ParmVarDecls for all of the FunctionDecl's arguments.  To do
2130   // this, we raid the function's FunctionProtoType for types.
2131 
2132   const FunctionProtoType *func_proto_type =
2133       qual_type.getTypePtr()->getAs<FunctionProtoType>();
2134 
2135   if (func_proto_type) {
2136     unsigned NumArgs = func_proto_type->getNumParams();
2137     unsigned ArgIndex;
2138 
2139     SmallVector<ParmVarDecl *, 5> parm_var_decls;
2140 
2141     for (ArgIndex = 0; ArgIndex < NumArgs; ++ArgIndex) {
2142       QualType arg_qual_type(func_proto_type->getParamType(ArgIndex));
2143 
2144       parm_var_decls.push_back(
2145           ParmVarDecl::Create(*ast, const_cast<DeclContext *>(context),
2146                               SourceLocation(), SourceLocation(), nullptr,
2147                               arg_qual_type, nullptr, SC_Static, nullptr));
2148     }
2149 
2150     func_decl->setParams(ArrayRef<ParmVarDecl *>(parm_var_decls));
2151   } else {
2152     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2153 
2154     LLDB_LOGF(log, "Function type wasn't a FunctionProtoType");
2155   }
2156 
2157   // If this is an operator (e.g. operator new or operator==), only insert the
2158   // declaration we inferred from the symbol if we can provide the correct
2159   // number of arguments. We shouldn't really inject random decl(s) for
2160   // functions that are analyzed semantically in a special way, otherwise we
2161   // will crash in clang.
2162   clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
2163   if (func_proto_type &&
2164       ClangASTContext::IsOperator(decl_name.getAsString().c_str(), op_kind)) {
2165     if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
2166             false, op_kind, func_proto_type->getNumParams()))
2167       return nullptr;
2168   }
2169   m_decls.push_back(func_decl);
2170 
2171   return func_decl;
2172 }
2173 
2174 clang::NamedDecl *NameSearchContext::AddGenericFunDecl() {
2175   FunctionProtoType::ExtProtoInfo proto_info;
2176 
2177   proto_info.Variadic = true;
2178 
2179   QualType generic_function_type(m_ast_source.m_ast_context->getFunctionType(
2180       m_ast_source.m_ast_context->UnknownAnyTy, // result
2181       ArrayRef<QualType>(),                     // argument types
2182       proto_info));
2183 
2184   return AddFunDecl(CompilerType(m_ast_source.m_clang_ast_context,
2185                                  generic_function_type.getAsOpaquePtr()),
2186                     true);
2187 }
2188 
2189 clang::NamedDecl *
2190 NameSearchContext::AddTypeDecl(const CompilerType &clang_type) {
2191   if (ClangUtil::IsClangType(clang_type)) {
2192     QualType qual_type = ClangUtil::GetQualType(clang_type);
2193 
2194     if (const TypedefType *typedef_type =
2195             llvm::dyn_cast<TypedefType>(qual_type)) {
2196       TypedefNameDecl *typedef_name_decl = typedef_type->getDecl();
2197 
2198       m_decls.push_back(typedef_name_decl);
2199 
2200       return (NamedDecl *)typedef_name_decl;
2201     } else if (const TagType *tag_type = qual_type->getAs<TagType>()) {
2202       TagDecl *tag_decl = tag_type->getDecl();
2203 
2204       m_decls.push_back(tag_decl);
2205 
2206       return tag_decl;
2207     } else if (const ObjCObjectType *objc_object_type =
2208                    qual_type->getAs<ObjCObjectType>()) {
2209       ObjCInterfaceDecl *interface_decl = objc_object_type->getInterface();
2210 
2211       m_decls.push_back((NamedDecl *)interface_decl);
2212 
2213       return (NamedDecl *)interface_decl;
2214     }
2215   }
2216   return nullptr;
2217 }
2218 
2219 void NameSearchContext::AddLookupResult(clang::DeclContextLookupResult result) {
2220   for (clang::NamedDecl *decl : result)
2221     m_decls.push_back(decl);
2222 }
2223 
2224 void NameSearchContext::AddNamedDecl(clang::NamedDecl *decl) {
2225   m_decls.push_back(decl);
2226 }
2227