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