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