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