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