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