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