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