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