1 //===-- ClangASTImporter.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 "lldb/Core/Module.h"
10 #include "lldb/Utility/LLDBAssert.h"
11 #include "lldb/Utility/Log.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Sema.h"
17 #include "llvm/Support/raw_ostream.h"
18 
19 #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
20 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
21 #include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"
22 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
23 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
24 
25 #include <memory>
26 
27 using namespace lldb_private;
28 using namespace clang;
29 
30 CompilerType ClangASTImporter::CopyType(TypeSystemClang &dst_ast,
31                                         const CompilerType &src_type) {
32   clang::ASTContext &dst_clang_ast = dst_ast.getASTContext();
33 
34   TypeSystemClang *src_ast =
35       llvm::dyn_cast_or_null<TypeSystemClang>(src_type.GetTypeSystem());
36   if (!src_ast)
37     return CompilerType();
38 
39   clang::ASTContext &src_clang_ast = src_ast->getASTContext();
40 
41   clang::QualType src_qual_type = ClangUtil::GetQualType(src_type);
42 
43   ImporterDelegateSP delegate_sp(GetDelegate(&dst_clang_ast, &src_clang_ast));
44   if (!delegate_sp)
45     return CompilerType();
46 
47   ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, &dst_clang_ast);
48 
49   llvm::Expected<QualType> ret_or_error = delegate_sp->Import(src_qual_type);
50   if (!ret_or_error) {
51     Log *log =
52       lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
53     LLDB_LOG_ERROR(log, ret_or_error.takeError(),
54         "Couldn't import type: {0}");
55     return CompilerType();
56   }
57 
58   lldb::opaque_compiler_type_t dst_clang_type = ret_or_error->getAsOpaquePtr();
59 
60   if (dst_clang_type)
61     return CompilerType(&dst_ast, dst_clang_type);
62   return CompilerType();
63 }
64 
65 clang::Decl *ClangASTImporter::CopyDecl(clang::ASTContext *dst_ast,
66                                         clang::Decl *decl) {
67   ImporterDelegateSP delegate_sp;
68 
69   clang::ASTContext *src_ast = &decl->getASTContext();
70   delegate_sp = GetDelegate(dst_ast, src_ast);
71 
72   ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
73 
74   if (!delegate_sp)
75     return nullptr;
76 
77   llvm::Expected<clang::Decl *> result = delegate_sp->Import(decl);
78   if (!result) {
79     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
80     LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}");
81     if (log) {
82       lldb::user_id_t user_id = LLDB_INVALID_UID;
83       ClangASTMetadata *metadata = GetDeclMetadata(decl);
84       if (metadata)
85         user_id = metadata->GetUserID();
86 
87       if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl))
88         LLDB_LOG(log,
89                  "  [ClangASTImporter] WARNING: Failed to import a {0} "
90                  "'{1}', metadata {2}",
91                  decl->getDeclKindName(), named_decl->getNameAsString(),
92                  user_id);
93       else
94         LLDB_LOG(log,
95                  "  [ClangASTImporter] WARNING: Failed to import a {0}, "
96                  "metadata {1}",
97                  decl->getDeclKindName(), user_id);
98     }
99     return nullptr;
100   }
101 
102   return *result;
103 }
104 
105 class DeclContextOverride {
106 private:
107   struct Backup {
108     clang::DeclContext *decl_context;
109     clang::DeclContext *lexical_decl_context;
110   };
111 
112   llvm::DenseMap<clang::Decl *, Backup> m_backups;
113 
114   void OverrideOne(clang::Decl *decl) {
115     if (m_backups.find(decl) != m_backups.end()) {
116       return;
117     }
118 
119     m_backups[decl] = {decl->getDeclContext(), decl->getLexicalDeclContext()};
120 
121     decl->setDeclContext(decl->getASTContext().getTranslationUnitDecl());
122     decl->setLexicalDeclContext(decl->getASTContext().getTranslationUnitDecl());
123   }
124 
125   bool ChainPassesThrough(
126       clang::Decl *decl, clang::DeclContext *base,
127       clang::DeclContext *(clang::Decl::*contextFromDecl)(),
128       clang::DeclContext *(clang::DeclContext::*contextFromContext)()) {
129     for (DeclContext *decl_ctx = (decl->*contextFromDecl)(); decl_ctx;
130          decl_ctx = (decl_ctx->*contextFromContext)()) {
131       if (decl_ctx == base) {
132         return true;
133       }
134     }
135 
136     return false;
137   }
138 
139   clang::Decl *GetEscapedChild(clang::Decl *decl,
140                                clang::DeclContext *base = nullptr) {
141     if (base) {
142       // decl's DeclContext chains must pass through base.
143 
144       if (!ChainPassesThrough(decl, base, &clang::Decl::getDeclContext,
145                               &clang::DeclContext::getParent) ||
146           !ChainPassesThrough(decl, base, &clang::Decl::getLexicalDeclContext,
147                               &clang::DeclContext::getLexicalParent)) {
148         return decl;
149       }
150     } else {
151       base = clang::dyn_cast<clang::DeclContext>(decl);
152 
153       if (!base) {
154         return nullptr;
155       }
156     }
157 
158     if (clang::DeclContext *context =
159             clang::dyn_cast<clang::DeclContext>(decl)) {
160       for (clang::Decl *decl : context->decls()) {
161         if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
162           return escaped_child;
163         }
164       }
165     }
166 
167     return nullptr;
168   }
169 
170   void Override(clang::Decl *decl) {
171     if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
172       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
173 
174       LLDB_LOG(log,
175                "    [ClangASTImporter] DeclContextOverride couldn't "
176                "override ({0}Decl*){1} - its child ({2}Decl*){3} escapes",
177                decl->getDeclKindName(), decl, escaped_child->getDeclKindName(),
178                escaped_child);
179       lldbassert(0 && "Couldn't override!");
180     }
181 
182     OverrideOne(decl);
183   }
184 
185 public:
186   DeclContextOverride() {}
187 
188   void OverrideAllDeclsFromContainingFunction(clang::Decl *decl) {
189     for (DeclContext *decl_context = decl->getLexicalDeclContext();
190          decl_context; decl_context = decl_context->getLexicalParent()) {
191       DeclContext *redecl_context = decl_context->getRedeclContext();
192 
193       if (llvm::isa<FunctionDecl>(redecl_context) &&
194           llvm::isa<TranslationUnitDecl>(redecl_context->getLexicalParent())) {
195         for (clang::Decl *child_decl : decl_context->decls()) {
196           Override(child_decl);
197         }
198       }
199     }
200   }
201 
202   ~DeclContextOverride() {
203     for (const std::pair<clang::Decl *, Backup> &backup : m_backups) {
204       backup.first->setDeclContext(backup.second.decl_context);
205       backup.first->setLexicalDeclContext(backup.second.lexical_decl_context);
206     }
207   }
208 };
209 
210 namespace {
211 /// Completes all imported TagDecls at the end of the scope.
212 ///
213 /// While in a CompleteTagDeclsScope, every decl that could be completed will
214 /// be completed at the end of the scope (including all Decls that are
215 /// imported while completing the original Decls).
216 class CompleteTagDeclsScope : public ClangASTImporter::NewDeclListener {
217   ClangASTImporter::ImporterDelegateSP m_delegate;
218   llvm::SmallVector<NamedDecl *, 32> m_decls_to_complete;
219   llvm::SmallPtrSet<NamedDecl *, 32> m_decls_already_completed;
220   clang::ASTContext *m_dst_ctx;
221   clang::ASTContext *m_src_ctx;
222   ClangASTImporter &importer;
223 
224 public:
225   /// Constructs a CompleteTagDeclsScope.
226   /// \param importer The ClangASTImporter that we should observe.
227   /// \param dst_ctx The ASTContext to which Decls are imported.
228   /// \param src_ctx The ASTContext from which Decls are imported.
229   explicit CompleteTagDeclsScope(ClangASTImporter &importer,
230                             clang::ASTContext *dst_ctx,
231                             clang::ASTContext *src_ctx)
232       : m_delegate(importer.GetDelegate(dst_ctx, src_ctx)), m_dst_ctx(dst_ctx),
233         m_src_ctx(src_ctx), importer(importer) {
234     m_delegate->SetImportListener(this);
235   }
236 
237   virtual ~CompleteTagDeclsScope() {
238     ClangASTImporter::ASTContextMetadataSP to_context_md =
239         importer.GetContextMetadata(m_dst_ctx);
240 
241     // Complete all decls we collected until now.
242     while (!m_decls_to_complete.empty()) {
243       NamedDecl *decl = m_decls_to_complete.pop_back_val();
244       m_decls_already_completed.insert(decl);
245 
246       // We should only complete decls coming from the source context.
247       assert(to_context_md->m_origins[decl].ctx == m_src_ctx);
248 
249       Decl *original_decl = to_context_md->m_origins[decl].decl;
250 
251       // Complete the decl now.
252       TypeSystemClang::GetCompleteDecl(m_src_ctx, original_decl);
253       if (auto *tag_decl = dyn_cast<TagDecl>(decl)) {
254         if (auto *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {
255           if (original_tag_decl->isCompleteDefinition()) {
256             m_delegate->ImportDefinitionTo(tag_decl, original_tag_decl);
257             tag_decl->setCompleteDefinition(true);
258           }
259         }
260 
261         tag_decl->setHasExternalLexicalStorage(false);
262         tag_decl->setHasExternalVisibleStorage(false);
263       } else if (auto *container_decl = dyn_cast<ObjCContainerDecl>(decl)) {
264         container_decl->setHasExternalLexicalStorage(false);
265         container_decl->setHasExternalVisibleStorage(false);
266       }
267 
268       to_context_md->m_origins.erase(decl);
269     }
270 
271     // Stop listening to imported decls. We do this after clearing the
272     // Decls we needed to import to catch all Decls they might have pulled in.
273     m_delegate->RemoveImportListener();
274   }
275 
276   void NewDeclImported(clang::Decl *from, clang::Decl *to) override {
277     // Filter out decls that we can't complete later.
278     if (!isa<TagDecl>(to) && !isa<ObjCInterfaceDecl>(to))
279       return;
280     RecordDecl *from_record_decl = dyn_cast<RecordDecl>(from);
281     // We don't need to complete injected class name decls.
282     if (from_record_decl && from_record_decl->isInjectedClassName())
283       return;
284 
285     NamedDecl *to_named_decl = dyn_cast<NamedDecl>(to);
286     // Check if we already completed this type.
287     if (m_decls_already_completed.count(to_named_decl) != 0)
288       return;
289     m_decls_to_complete.push_back(to_named_decl);
290   }
291 };
292 } // namespace
293 
294 CompilerType ClangASTImporter::DeportType(TypeSystemClang &dst,
295                                           const CompilerType &src_type) {
296   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
297 
298   TypeSystemClang *src_ctxt =
299       llvm::cast<TypeSystemClang>(src_type.GetTypeSystem());
300 
301   LLDB_LOG(log,
302            "    [ClangASTImporter] DeportType called on ({0}Type*){1} "
303            "from (ASTContext*){2} to (ASTContext*){3}",
304            src_type.GetTypeName(), src_type.GetOpaqueQualType(),
305            &src_ctxt->getASTContext(), &dst.getASTContext());
306 
307   DeclContextOverride decl_context_override;
308 
309   if (auto *t = ClangUtil::GetQualType(src_type)->getAs<TagType>())
310     decl_context_override.OverrideAllDeclsFromContainingFunction(t->getDecl());
311 
312   CompleteTagDeclsScope complete_scope(*this, &dst.getASTContext(),
313                                        &src_ctxt->getASTContext());
314   return CopyType(dst, src_type);
315 }
316 
317 clang::Decl *ClangASTImporter::DeportDecl(clang::ASTContext *dst_ctx,
318                                           clang::Decl *decl) {
319   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
320 
321   clang::ASTContext *src_ctx = &decl->getASTContext();
322   LLDB_LOG(log,
323            "    [ClangASTImporter] DeportDecl called on ({0}Decl*){1} from "
324            "(ASTContext*){2} to (ASTContext*){3}",
325            decl->getDeclKindName(), decl, src_ctx, dst_ctx);
326 
327   DeclContextOverride decl_context_override;
328 
329   decl_context_override.OverrideAllDeclsFromContainingFunction(decl);
330 
331   clang::Decl *result;
332   {
333     CompleteTagDeclsScope complete_scope(*this, dst_ctx, src_ctx);
334     result = CopyDecl(dst_ctx, decl);
335   }
336 
337   if (!result)
338     return nullptr;
339 
340   LLDB_LOG(log,
341            "    [ClangASTImporter] DeportDecl deported ({0}Decl*){1} to "
342            "({2}Decl*){3}",
343            decl->getDeclKindName(), decl, result->getDeclKindName(), result);
344 
345   return result;
346 }
347 
348 bool ClangASTImporter::CanImport(const CompilerType &type) {
349   if (!ClangUtil::IsClangType(type))
350     return false;
351 
352   // TODO: remove external completion BOOL
353   // CompleteAndFetchChildren should get the Decl out and check for the
354 
355   clang::QualType qual_type(
356       ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
357 
358   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
359   switch (type_class) {
360   case clang::Type::Record: {
361     const clang::CXXRecordDecl *cxx_record_decl =
362         qual_type->getAsCXXRecordDecl();
363     if (cxx_record_decl) {
364       if (GetDeclOrigin(cxx_record_decl).Valid())
365         return true;
366     }
367   } break;
368 
369   case clang::Type::Enum: {
370     clang::EnumDecl *enum_decl =
371         llvm::cast<clang::EnumType>(qual_type)->getDecl();
372     if (enum_decl) {
373       if (GetDeclOrigin(enum_decl).Valid())
374         return true;
375     }
376   } break;
377 
378   case clang::Type::ObjCObject:
379   case clang::Type::ObjCInterface: {
380     const clang::ObjCObjectType *objc_class_type =
381         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
382     if (objc_class_type) {
383       clang::ObjCInterfaceDecl *class_interface_decl =
384           objc_class_type->getInterface();
385       // We currently can't complete objective C types through the newly added
386       // ASTContext because it only supports TagDecl objects right now...
387       if (class_interface_decl) {
388         if (GetDeclOrigin(class_interface_decl).Valid())
389           return true;
390       }
391     }
392   } break;
393 
394   case clang::Type::Typedef:
395     return CanImport(CompilerType(type.GetTypeSystem(),
396                                   llvm::cast<clang::TypedefType>(qual_type)
397                                       ->getDecl()
398                                       ->getUnderlyingType()
399                                       .getAsOpaquePtr()));
400 
401   case clang::Type::Auto:
402     return CanImport(CompilerType(type.GetTypeSystem(),
403                                   llvm::cast<clang::AutoType>(qual_type)
404                                       ->getDeducedType()
405                                       .getAsOpaquePtr()));
406 
407   case clang::Type::Elaborated:
408     return CanImport(CompilerType(type.GetTypeSystem(),
409                                   llvm::cast<clang::ElaboratedType>(qual_type)
410                                       ->getNamedType()
411                                       .getAsOpaquePtr()));
412 
413   case clang::Type::Paren:
414     return CanImport(CompilerType(
415         type.GetTypeSystem(),
416         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
417 
418   default:
419     break;
420   }
421 
422   return false;
423 }
424 
425 bool ClangASTImporter::Import(const CompilerType &type) {
426   if (!ClangUtil::IsClangType(type))
427     return false;
428   // TODO: remove external completion BOOL
429   // CompleteAndFetchChildren should get the Decl out and check for the
430 
431   clang::QualType qual_type(
432       ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
433 
434   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
435   switch (type_class) {
436   case clang::Type::Record: {
437     const clang::CXXRecordDecl *cxx_record_decl =
438         qual_type->getAsCXXRecordDecl();
439     if (cxx_record_decl) {
440       if (GetDeclOrigin(cxx_record_decl).Valid())
441         return CompleteAndFetchChildren(qual_type);
442     }
443   } break;
444 
445   case clang::Type::Enum: {
446     clang::EnumDecl *enum_decl =
447         llvm::cast<clang::EnumType>(qual_type)->getDecl();
448     if (enum_decl) {
449       if (GetDeclOrigin(enum_decl).Valid())
450         return CompleteAndFetchChildren(qual_type);
451     }
452   } break;
453 
454   case clang::Type::ObjCObject:
455   case clang::Type::ObjCInterface: {
456     const clang::ObjCObjectType *objc_class_type =
457         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
458     if (objc_class_type) {
459       clang::ObjCInterfaceDecl *class_interface_decl =
460           objc_class_type->getInterface();
461       // We currently can't complete objective C types through the newly added
462       // ASTContext because it only supports TagDecl objects right now...
463       if (class_interface_decl) {
464         if (GetDeclOrigin(class_interface_decl).Valid())
465           return CompleteAndFetchChildren(qual_type);
466       }
467     }
468   } break;
469 
470   case clang::Type::Typedef:
471     return Import(CompilerType(type.GetTypeSystem(),
472                                llvm::cast<clang::TypedefType>(qual_type)
473                                    ->getDecl()
474                                    ->getUnderlyingType()
475                                    .getAsOpaquePtr()));
476 
477   case clang::Type::Auto:
478     return Import(CompilerType(type.GetTypeSystem(),
479                                llvm::cast<clang::AutoType>(qual_type)
480                                    ->getDeducedType()
481                                    .getAsOpaquePtr()));
482 
483   case clang::Type::Elaborated:
484     return Import(CompilerType(type.GetTypeSystem(),
485                                llvm::cast<clang::ElaboratedType>(qual_type)
486                                    ->getNamedType()
487                                    .getAsOpaquePtr()));
488 
489   case clang::Type::Paren:
490     return Import(CompilerType(
491         type.GetTypeSystem(),
492         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
493 
494   default:
495     break;
496   }
497   return false;
498 }
499 
500 bool ClangASTImporter::CompleteType(const CompilerType &compiler_type) {
501   if (!CanImport(compiler_type))
502     return false;
503 
504   if (Import(compiler_type)) {
505     TypeSystemClang::CompleteTagDeclarationDefinition(compiler_type);
506     return true;
507   }
508 
509   TypeSystemClang::SetHasExternalStorage(compiler_type.GetOpaqueQualType(),
510                                          false);
511   return false;
512 }
513 
514 bool ClangASTImporter::LayoutRecordType(
515     const clang::RecordDecl *record_decl, uint64_t &bit_size,
516     uint64_t &alignment,
517     llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
518     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
519         &base_offsets,
520     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
521         &vbase_offsets) {
522   RecordDeclToLayoutMap::iterator pos =
523       m_record_decl_to_layout_map.find(record_decl);
524   bool success = false;
525   base_offsets.clear();
526   vbase_offsets.clear();
527   if (pos != m_record_decl_to_layout_map.end()) {
528     bit_size = pos->second.bit_size;
529     alignment = pos->second.alignment;
530     field_offsets.swap(pos->second.field_offsets);
531     base_offsets.swap(pos->second.base_offsets);
532     vbase_offsets.swap(pos->second.vbase_offsets);
533     m_record_decl_to_layout_map.erase(pos);
534     success = true;
535   } else {
536     bit_size = 0;
537     alignment = 0;
538     field_offsets.clear();
539   }
540   return success;
541 }
542 
543 void ClangASTImporter::SetRecordLayout(clang::RecordDecl *decl,
544                                         const LayoutInfo &layout) {
545   m_record_decl_to_layout_map.insert(std::make_pair(decl, layout));
546 }
547 
548 bool ClangASTImporter::CompleteTagDecl(clang::TagDecl *decl) {
549   DeclOrigin decl_origin = GetDeclOrigin(decl);
550 
551   if (!decl_origin.Valid())
552     return false;
553 
554   if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
555     return false;
556 
557   ImporterDelegateSP delegate_sp(
558       GetDelegate(&decl->getASTContext(), decl_origin.ctx));
559 
560   ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
561                                                 &decl->getASTContext());
562   if (delegate_sp)
563     delegate_sp->ImportDefinitionTo(decl, decl_origin.decl);
564 
565   return true;
566 }
567 
568 bool ClangASTImporter::CompleteTagDeclWithOrigin(clang::TagDecl *decl,
569                                                  clang::TagDecl *origin_decl) {
570   clang::ASTContext *origin_ast_ctx = &origin_decl->getASTContext();
571 
572   if (!TypeSystemClang::GetCompleteDecl(origin_ast_ctx, origin_decl))
573     return false;
574 
575   ImporterDelegateSP delegate_sp(
576       GetDelegate(&decl->getASTContext(), origin_ast_ctx));
577 
578   if (delegate_sp)
579     delegate_sp->ImportDefinitionTo(decl, origin_decl);
580 
581   ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
582 
583   OriginMap &origins = context_md->m_origins;
584 
585   origins[decl] = DeclOrigin(origin_ast_ctx, origin_decl);
586 
587   return true;
588 }
589 
590 bool ClangASTImporter::CompleteObjCInterfaceDecl(
591     clang::ObjCInterfaceDecl *interface_decl) {
592   DeclOrigin decl_origin = GetDeclOrigin(interface_decl);
593 
594   if (!decl_origin.Valid())
595     return false;
596 
597   if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
598     return false;
599 
600   ImporterDelegateSP delegate_sp(
601       GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx));
602 
603   if (delegate_sp)
604     delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl);
605 
606   if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass())
607     RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0));
608 
609   return true;
610 }
611 
612 bool ClangASTImporter::CompleteAndFetchChildren(clang::QualType type) {
613   if (!RequireCompleteType(type))
614     return false;
615 
616   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
617 
618   if (const TagType *tag_type = type->getAs<TagType>()) {
619     TagDecl *tag_decl = tag_type->getDecl();
620 
621     DeclOrigin decl_origin = GetDeclOrigin(tag_decl);
622 
623     if (!decl_origin.Valid())
624       return false;
625 
626     ImporterDelegateSP delegate_sp(
627         GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx));
628 
629     ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
630                                                   &tag_decl->getASTContext());
631 
632     TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl);
633 
634     for (Decl *origin_child_decl : origin_tag_decl->decls()) {
635       llvm::Expected<Decl *> imported_or_err =
636           delegate_sp->Import(origin_child_decl);
637       if (!imported_or_err) {
638         LLDB_LOG_ERROR(log, imported_or_err.takeError(),
639                        "Couldn't import decl: {0}");
640         return false;
641       }
642     }
643 
644     if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl))
645       record_decl->setHasLoadedFieldsFromExternalStorage(true);
646 
647     return true;
648   }
649 
650   if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
651     if (ObjCInterfaceDecl *objc_interface_decl =
652             objc_object_type->getInterface()) {
653       DeclOrigin decl_origin = GetDeclOrigin(objc_interface_decl);
654 
655       if (!decl_origin.Valid())
656         return false;
657 
658       ImporterDelegateSP delegate_sp(
659           GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx));
660 
661       ObjCInterfaceDecl *origin_interface_decl =
662           llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl);
663 
664       for (Decl *origin_child_decl : origin_interface_decl->decls()) {
665         llvm::Expected<Decl *> imported_or_err =
666             delegate_sp->Import(origin_child_decl);
667         if (!imported_or_err) {
668           LLDB_LOG_ERROR(log, imported_or_err.takeError(),
669                          "Couldn't import decl: {0}");
670           return false;
671         }
672       }
673 
674       return true;
675     }
676     return false;
677   }
678 
679   return true;
680 }
681 
682 bool ClangASTImporter::RequireCompleteType(clang::QualType type) {
683   if (type.isNull())
684     return false;
685 
686   if (const TagType *tag_type = type->getAs<TagType>()) {
687     TagDecl *tag_decl = tag_type->getDecl();
688 
689     if (tag_decl->getDefinition() || tag_decl->isBeingDefined())
690       return true;
691 
692     return CompleteTagDecl(tag_decl);
693   }
694   if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
695     if (ObjCInterfaceDecl *objc_interface_decl =
696             objc_object_type->getInterface())
697       return CompleteObjCInterfaceDecl(objc_interface_decl);
698     return false;
699   }
700   if (const ArrayType *array_type = type->getAsArrayTypeUnsafe())
701     return RequireCompleteType(array_type->getElementType());
702   if (const AtomicType *atomic_type = type->getAs<AtomicType>())
703     return RequireCompleteType(atomic_type->getPointeeType());
704 
705   return true;
706 }
707 
708 ClangASTMetadata *ClangASTImporter::GetDeclMetadata(const clang::Decl *decl) {
709   DeclOrigin decl_origin = GetDeclOrigin(decl);
710 
711   if (decl_origin.Valid()) {
712     TypeSystemClang *ast = TypeSystemClang::GetASTContext(decl_origin.ctx);
713     return ast->GetMetadata(decl_origin.decl);
714   }
715   TypeSystemClang *ast = TypeSystemClang::GetASTContext(&decl->getASTContext());
716   return ast->GetMetadata(decl);
717 }
718 
719 ClangASTImporter::DeclOrigin
720 ClangASTImporter::GetDeclOrigin(const clang::Decl *decl) {
721   ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
722 
723   OriginMap &origins = context_md->m_origins;
724 
725   OriginMap::iterator iter = origins.find(decl);
726 
727   if (iter != origins.end())
728     return iter->second;
729   return DeclOrigin();
730 }
731 
732 void ClangASTImporter::SetDeclOrigin(const clang::Decl *decl,
733                                      clang::Decl *original_decl) {
734   ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
735 
736   OriginMap &origins = context_md->m_origins;
737 
738   OriginMap::iterator iter = origins.find(decl);
739 
740   if (iter != origins.end()) {
741     iter->second.decl = original_decl;
742     iter->second.ctx = &original_decl->getASTContext();
743     return;
744   }
745   origins[decl] = DeclOrigin(&original_decl->getASTContext(), original_decl);
746 }
747 
748 void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl *decl,
749                                             NamespaceMapSP &namespace_map) {
750   ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
751 
752   context_md->m_namespace_maps[decl] = namespace_map;
753 }
754 
755 ClangASTImporter::NamespaceMapSP
756 ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl *decl) {
757   ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
758 
759   NamespaceMetaMap &namespace_maps = context_md->m_namespace_maps;
760 
761   NamespaceMetaMap::iterator iter = namespace_maps.find(decl);
762 
763   if (iter != namespace_maps.end())
764     return iter->second;
765   return NamespaceMapSP();
766 }
767 
768 void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl *decl) {
769   assert(decl);
770   ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
771 
772   const DeclContext *parent_context = decl->getDeclContext();
773   const NamespaceDecl *parent_namespace =
774       dyn_cast<NamespaceDecl>(parent_context);
775   NamespaceMapSP parent_map;
776 
777   if (parent_namespace)
778     parent_map = GetNamespaceMap(parent_namespace);
779 
780   NamespaceMapSP new_map;
781 
782   new_map = std::make_shared<NamespaceMap>();
783 
784   if (context_md->m_map_completer) {
785     std::string namespace_string = decl->getDeclName().getAsString();
786 
787     context_md->m_map_completer->CompleteNamespaceMap(
788         new_map, ConstString(namespace_string.c_str()), parent_map);
789   }
790 
791   context_md->m_namespace_maps[decl] = new_map;
792 }
793 
794 void ClangASTImporter::ForgetDestination(clang::ASTContext *dst_ast) {
795   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
796 
797   LLDB_LOG(log,
798            "    [ClangASTImporter] Forgetting destination (ASTContext*){0}",
799            dst_ast);
800 
801   m_metadata_map.erase(dst_ast);
802 }
803 
804 void ClangASTImporter::ForgetSource(clang::ASTContext *dst_ast,
805                                     clang::ASTContext *src_ast) {
806   ASTContextMetadataSP md = MaybeGetContextMetadata(dst_ast);
807 
808   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
809 
810   LLDB_LOG(log,
811            "    [ClangASTImporter] Forgetting source->dest "
812            "(ASTContext*){0}->(ASTContext*){1}",
813            src_ast, dst_ast);
814 
815   if (!md)
816     return;
817 
818   md->m_delegates.erase(src_ast);
819 
820   for (OriginMap::iterator iter = md->m_origins.begin();
821        iter != md->m_origins.end();) {
822     if (iter->second.ctx == src_ast)
823       md->m_origins.erase(iter++);
824     else
825       ++iter;
826   }
827 }
828 
829 ClangASTImporter::MapCompleter::~MapCompleter() { return; }
830 
831 llvm::Expected<Decl *>
832 ClangASTImporter::ASTImporterDelegate::ImportImpl(Decl *From) {
833   if (m_std_handler) {
834     llvm::Optional<Decl *> D = m_std_handler->Import(From);
835     if (D) {
836       // Make sure we don't use this decl later to map it back to it's original
837       // decl. The decl the CxxModuleHandler created has nothing to do with
838       // the one from debug info, and linking those two would just cause the
839       // ASTImporter to try 'updating' the module decl with the minimal one from
840       // the debug info.
841       m_decls_to_ignore.insert(*D);
842       return *D;
843     }
844   }
845 
846   // Check which ASTContext this declaration originally came from.
847   DeclOrigin origin = m_master.GetDeclOrigin(From);
848   // If it originally came from the target ASTContext then we can just
849   // pretend that the original is the one we imported. This can happen for
850   // example when inspecting a persistent declaration from the scratch
851   // ASTContext (which will provide the declaration when parsing the
852   // expression and then we later try to copy the declaration back to the
853   // scratch ASTContext to store the result).
854   // Without this check we would ask the ASTImporter to import a declaration
855   // into the same ASTContext where it came from (which doesn't make a lot of
856   // sense).
857   if (origin.Valid() && origin.ctx == &getToContext()) {
858     RegisterImportedDecl(From, origin.decl);
859     return origin.decl;
860   }
861 
862   // This declaration came originally from another ASTContext. Instead of
863   // copying our potentially incomplete 'From' Decl we instead go to the
864   // original ASTContext and copy the original to the target. This is not
865   // only faster than first completing our current decl and then copying it
866   // to the target, but it also prevents that indirectly copying the same
867   // declaration to the same target requires the ASTImporter to merge all
868   // the different decls that appear to come from different ASTContexts (even
869   // though all these different source ASTContexts just got a copy from
870   // one source AST).
871   if (origin.Valid()) {
872     auto R = m_master.CopyDecl(&getToContext(), origin.decl);
873     if (R) {
874       RegisterImportedDecl(From, R);
875       return R;
876     }
877   }
878 
879   return ASTImporter::ImportImpl(From);
880 }
881 
882 void ClangASTImporter::ASTImporterDelegate::ImportDefinitionTo(
883     clang::Decl *to, clang::Decl *from) {
884   // We might have a forward declaration from a shared library that we
885   // gave external lexical storage so that Clang asks us about the full
886   // definition when it needs it. In this case the ASTImporter isn't aware
887   // that the forward decl from the shared library is the actual import
888   // target but would create a second declaration that would then be defined.
889   // We want that 'to' is actually complete after this function so let's
890   // tell the ASTImporter that 'to' was imported from 'from'.
891   MapImported(from, to);
892   ASTImporter::Imported(from, to);
893 
894   /*
895   if (to_objc_interface)
896       to_objc_interface->startDefinition();
897 
898   CXXRecordDecl *to_cxx_record = dyn_cast<CXXRecordDecl>(to);
899 
900   if (to_cxx_record)
901       to_cxx_record->startDefinition();
902   */
903 
904   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
905 
906   if (llvm::Error err = ImportDefinition(from)) {
907     LLDB_LOG_ERROR(log, std::move(err),
908                    "[ClangASTImporter] Error during importing definition: {0}");
909     return;
910   }
911 
912   if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) {
913     if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) {
914       to_tag->setCompleteDefinition(from_tag->isCompleteDefinition());
915 
916       if (Log *log_ast =
917               lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_AST)) {
918         std::string name_string;
919         if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
920           llvm::raw_string_ostream name_stream(name_string);
921           from_named_decl->printName(name_stream);
922           name_stream.flush();
923         }
924         LLDB_LOG(log_ast, "==== [ClangASTImporter][TUDecl: {0}] Imported "
925                           "({1}Decl*){2}, named {3} (from "
926                           "(Decl*){4})",
927                  static_cast<void *>(to->getTranslationUnitDecl()),
928                  from->getDeclKindName(), static_cast<void *>(to), name_string,
929                  static_cast<void *>(from));
930 
931         // Log the AST of the TU.
932         std::string ast_string;
933         llvm::raw_string_ostream ast_stream(ast_string);
934         to->getTranslationUnitDecl()->dump(ast_stream);
935         LLDB_LOG(log_ast, "{0}", ast_string);
936       }
937     }
938   }
939 
940   // If we're dealing with an Objective-C class, ensure that the inheritance
941   // has been set up correctly.  The ASTImporter may not do this correctly if
942   // the class was originally sourced from symbols.
943 
944   if (ObjCInterfaceDecl *to_objc_interface = dyn_cast<ObjCInterfaceDecl>(to)) {
945     do {
946       ObjCInterfaceDecl *to_superclass = to_objc_interface->getSuperClass();
947 
948       if (to_superclass)
949         break; // we're not going to override it if it's set
950 
951       ObjCInterfaceDecl *from_objc_interface =
952           dyn_cast<ObjCInterfaceDecl>(from);
953 
954       if (!from_objc_interface)
955         break;
956 
957       ObjCInterfaceDecl *from_superclass = from_objc_interface->getSuperClass();
958 
959       if (!from_superclass)
960         break;
961 
962       llvm::Expected<Decl *> imported_from_superclass_decl =
963           Import(from_superclass);
964 
965       if (!imported_from_superclass_decl) {
966         LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(),
967                        "Couldn't import decl: {0}");
968         break;
969       }
970 
971       ObjCInterfaceDecl *imported_from_superclass =
972           dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl);
973 
974       if (!imported_from_superclass)
975         break;
976 
977       if (!to_objc_interface->hasDefinition())
978         to_objc_interface->startDefinition();
979 
980       to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo(
981           m_source_ctx->getObjCInterfaceType(imported_from_superclass)));
982     } while (false);
983   }
984 }
985 
986 /// Takes a CXXMethodDecl and completes the return type if necessary. This
987 /// is currently only necessary for virtual functions with covariant return
988 /// types where Clang's CodeGen expects that the underlying records are already
989 /// completed.
990 static void MaybeCompleteReturnType(ClangASTImporter &importer,
991                                         CXXMethodDecl *to_method) {
992   if (!to_method->isVirtual())
993     return;
994   QualType return_type = to_method->getReturnType();
995   if (!return_type->isPointerType() && !return_type->isReferenceType())
996     return;
997 
998   clang::RecordDecl *rd = return_type->getPointeeType()->getAsRecordDecl();
999   if (!rd)
1000     return;
1001   if (rd->getDefinition())
1002     return;
1003 
1004   importer.CompleteTagDecl(rd);
1005 }
1006 
1007 /// Recreate a module with its parents in \p to_source and return its id.
1008 static OptionalClangModuleID
1009 RemapModule(OptionalClangModuleID from_id,
1010             ClangExternalASTSourceCallbacks &from_source,
1011             ClangExternalASTSourceCallbacks &to_source) {
1012   if (!from_id.HasValue())
1013     return {};
1014   clang::Module *module = from_source.getModule(from_id.GetValue());
1015   OptionalClangModuleID parent = RemapModule(
1016       from_source.GetIDForModule(module->Parent), from_source, to_source);
1017   TypeSystemClang &to_ts = to_source.GetTypeSystem();
1018   return to_ts.GetOrCreateClangModule(module->Name, parent, module->IsFramework,
1019                                       module->IsExplicit);
1020 }
1021 
1022 void ClangASTImporter::ASTImporterDelegate::Imported(clang::Decl *from,
1023                                                      clang::Decl *to) {
1024   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1025 
1026   // Some decls shouldn't be tracked here because they were not created by
1027   // copying 'from' to 'to'. Just exit early for those.
1028   if (m_decls_to_ignore.find(to) != m_decls_to_ignore.end())
1029     return clang::ASTImporter::Imported(from, to);
1030 
1031   // Transfer module ownership information.
1032   auto *from_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1033       getFromContext().getExternalSource());
1034   // Can also be a ClangASTSourceProxy.
1035   auto *to_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1036       getToContext().getExternalSource());
1037   if (from_source && to_source) {
1038     OptionalClangModuleID from_id(from->getOwningModuleID());
1039     OptionalClangModuleID to_id =
1040         RemapModule(from_id, *from_source, *to_source);
1041     TypeSystemClang &to_ts = to_source->GetTypeSystem();
1042     to_ts.SetOwningModule(to, to_id);
1043   }
1044 
1045   lldb::user_id_t user_id = LLDB_INVALID_UID;
1046   ClangASTMetadata *metadata = m_master.GetDeclMetadata(from);
1047   if (metadata)
1048     user_id = metadata->GetUserID();
1049 
1050   if (log) {
1051     if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
1052       std::string name_string;
1053       llvm::raw_string_ostream name_stream(name_string);
1054       from_named_decl->printName(name_stream);
1055       name_stream.flush();
1056 
1057       LLDB_LOG(log,
1058                "    [ClangASTImporter] Imported ({0}Decl*){1}, named {2} (from "
1059                "(Decl*){3}), metadata {4}",
1060                from->getDeclKindName(), to, name_string, from, user_id);
1061     } else {
1062       LLDB_LOG(log,
1063                "    [ClangASTImporter] Imported ({0}Decl*){1} (from "
1064                "(Decl*){2}), metadata {3}",
1065                from->getDeclKindName(), to, from, user_id);
1066     }
1067   }
1068 
1069   ASTContextMetadataSP to_context_md =
1070       m_master.GetContextMetadata(&to->getASTContext());
1071   ASTContextMetadataSP from_context_md =
1072       m_master.MaybeGetContextMetadata(m_source_ctx);
1073 
1074   if (from_context_md) {
1075     OriginMap &origins = from_context_md->m_origins;
1076 
1077     OriginMap::iterator origin_iter = origins.find(from);
1078 
1079     if (origin_iter != origins.end()) {
1080       if (to_context_md->m_origins.find(to) == to_context_md->m_origins.end() ||
1081           user_id != LLDB_INVALID_UID) {
1082         if (origin_iter->second.ctx != &to->getASTContext())
1083           to_context_md->m_origins[to] = origin_iter->second;
1084       }
1085 
1086       ImporterDelegateSP direct_completer =
1087           m_master.GetDelegate(&to->getASTContext(), origin_iter->second.ctx);
1088 
1089       if (direct_completer.get() != this)
1090         direct_completer->ASTImporter::Imported(origin_iter->second.decl, to);
1091 
1092       LLDB_LOG(log,
1093                "    [ClangASTImporter] Propagated origin "
1094                "(Decl*){0}/(ASTContext*){1} from (ASTContext*){2} to "
1095                "(ASTContext*){3}",
1096                origin_iter->second.decl, origin_iter->second.ctx,
1097                &from->getASTContext(), &to->getASTContext());
1098     } else {
1099       if (m_new_decl_listener)
1100         m_new_decl_listener->NewDeclImported(from, to);
1101 
1102       if (to_context_md->m_origins.find(to) == to_context_md->m_origins.end() ||
1103           user_id != LLDB_INVALID_UID) {
1104         to_context_md->m_origins[to] = DeclOrigin(m_source_ctx, from);
1105       }
1106 
1107       LLDB_LOG(log,
1108                "    [ClangASTImporter] Decl has no origin information in "
1109                "(ASTContext*){0}",
1110                &from->getASTContext());
1111     }
1112 
1113     if (auto *to_namespace = dyn_cast<clang::NamespaceDecl>(to)) {
1114       auto *from_namespace = cast<clang::NamespaceDecl>(from);
1115 
1116       NamespaceMetaMap &namespace_maps = from_context_md->m_namespace_maps;
1117 
1118       NamespaceMetaMap::iterator namespace_map_iter =
1119           namespace_maps.find(from_namespace);
1120 
1121       if (namespace_map_iter != namespace_maps.end())
1122         to_context_md->m_namespace_maps[to_namespace] =
1123             namespace_map_iter->second;
1124     }
1125   } else {
1126     to_context_md->m_origins[to] = DeclOrigin(m_source_ctx, from);
1127 
1128     LLDB_LOG(log,
1129              "    [ClangASTImporter] Sourced origin "
1130              "(Decl*){0}/(ASTContext*){1} into (ASTContext*){2}",
1131              from, m_source_ctx, &to->getASTContext());
1132   }
1133 
1134   if (auto *to_tag_decl = dyn_cast<TagDecl>(to)) {
1135     to_tag_decl->setHasExternalLexicalStorage();
1136     to_tag_decl->getPrimaryContext()->setMustBuildLookupTable();
1137     auto from_tag_decl = cast<TagDecl>(from);
1138 
1139     LLDB_LOG(
1140         log,
1141         "    [ClangASTImporter] To is a TagDecl - attributes {0}{1} [{2}->{3}]",
1142         (to_tag_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1143         (to_tag_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1144         (from_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"),
1145         (to_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"));
1146   }
1147 
1148   if (auto *to_namespace_decl = dyn_cast<NamespaceDecl>(to)) {
1149     m_master.BuildNamespaceMap(to_namespace_decl);
1150     to_namespace_decl->setHasExternalVisibleStorage();
1151   }
1152 
1153   if (auto *to_container_decl = dyn_cast<ObjCContainerDecl>(to)) {
1154     to_container_decl->setHasExternalLexicalStorage();
1155     to_container_decl->setHasExternalVisibleStorage();
1156 
1157     if (log) {
1158       if (ObjCInterfaceDecl *to_interface_decl =
1159               llvm::dyn_cast<ObjCInterfaceDecl>(to_container_decl)) {
1160         LLDB_LOG(
1161             log,
1162             "    [ClangASTImporter] To is an ObjCInterfaceDecl - attributes "
1163             "{0}{1}{2}",
1164             (to_interface_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1165             (to_interface_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1166             (to_interface_decl->hasDefinition() ? " HasDefinition" : ""));
1167       } else {
1168         LLDB_LOG(
1169             log, "    [ClangASTImporter] To is an {0}Decl - attributes {1}{2}",
1170             ((Decl *)to_container_decl)->getDeclKindName(),
1171             (to_container_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1172             (to_container_decl->hasExternalVisibleStorage() ? " Visible" : ""));
1173       }
1174     }
1175   }
1176 
1177   if (clang::CXXMethodDecl *to_method = dyn_cast<CXXMethodDecl>(to))
1178     MaybeCompleteReturnType(m_master, to_method);
1179 }
1180 
1181 clang::Decl *
1182 ClangASTImporter::ASTImporterDelegate::GetOriginalDecl(clang::Decl *To) {
1183   return m_master.GetDeclOrigin(To).decl;
1184 }
1185