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