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