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