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