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