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