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