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