LLDB mainline
ClangASTImporter.cpp
Go to the documentation of this file.
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"
13#include "lldb/Utility/Log.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/RecordLayout.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Sema/Sema.h"
21#include "llvm/Support/raw_ostream.h"
22
29
30#include <memory>
31#include <optional>
32#include <type_traits>
33
34using namespace lldb_private;
35using namespace clang;
36
38 const CompilerType &src_type) {
39 clang::ASTContext &dst_clang_ast = dst_ast.getASTContext();
40
41 auto src_ast = src_type.GetTypeSystem<TypeSystemClang>();
42 if (!src_ast)
43 return CompilerType();
44
45 clang::ASTContext &src_clang_ast = src_ast->getASTContext();
46
47 clang::QualType src_qual_type = ClangUtil::GetQualType(src_type);
48
49 ImporterDelegateSP delegate_sp(GetDelegate(&dst_clang_ast, &src_clang_ast));
50 if (!delegate_sp)
51 return CompilerType();
52
53 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, &dst_clang_ast);
54
55 llvm::Expected<QualType> ret_or_error = delegate_sp->Import(src_qual_type);
56 if (!ret_or_error) {
58 LLDB_LOG_ERROR(log, ret_or_error.takeError(),
59 "Couldn't import type: {0}");
60 return CompilerType();
61 }
62
63 lldb::opaque_compiler_type_t dst_clang_type = ret_or_error->getAsOpaquePtr();
64
65 if (dst_clang_type)
66 return CompilerType(dst_ast.weak_from_this(), dst_clang_type);
67 return CompilerType();
68}
69
70clang::Decl *ClangASTImporter::CopyDecl(clang::ASTContext *dst_ast,
71 clang::Decl *decl) {
72 ImporterDelegateSP delegate_sp;
73
74 clang::ASTContext *src_ast = &decl->getASTContext();
75 delegate_sp = GetDelegate(dst_ast, src_ast);
76
77 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp, dst_ast);
78
79 if (!delegate_sp)
80 return nullptr;
81
82 llvm::Expected<clang::Decl *> result = delegate_sp->Import(decl);
83 if (!result) {
85 LLDB_LOG_ERROR(log, result.takeError(), "Couldn't import decl: {0}");
86 if (log) {
88 if (std::optional<ClangASTMetadata> metadata = GetDeclMetadata(decl))
89 user_id = metadata->GetUserID();
90
91 if (NamedDecl *named_decl = dyn_cast<NamedDecl>(decl))
92 LLDB_LOG(log,
93 " [ClangASTImporter] WARNING: Failed to import a {0} "
94 "'{1}', metadata {2}",
95 decl->getDeclKindName(), named_decl->getNameAsString(),
96 user_id);
97 else
98 LLDB_LOG(log,
99 " [ClangASTImporter] WARNING: Failed to import a {0}, "
100 "metadata {1}",
101 decl->getDeclKindName(), user_id);
102 }
103 return nullptr;
104 }
105
106 return *result;
107}
108
110private:
111 struct Backup {
112 clang::DeclContext *decl_context;
113 clang::DeclContext *lexical_decl_context;
114 };
115
116 llvm::DenseMap<clang::Decl *, Backup> m_backups;
117
118 void OverrideOne(clang::Decl *decl) {
119 if (m_backups.contains(decl)) {
120 return;
121 }
122
123 m_backups[decl] = {decl->getDeclContext(), decl->getLexicalDeclContext()};
124
125 decl->setDeclContext(decl->getASTContext().getTranslationUnitDecl());
126 decl->setLexicalDeclContext(decl->getASTContext().getTranslationUnitDecl());
127 // Changing the DeclContext might change the linkage. For example, if the
128 // entity was previously declared inside a function, it will not be
129 // external, but changing the declaration context to the TU will make it
130 // external. Make sure this will recompute the linkage if it was computed
131 // before.
132 decl->invalidateCachedLinkage();
133 }
134
136 clang::Decl *decl, clang::DeclContext *base,
137 clang::DeclContext *(clang::Decl::*contextFromDecl)(),
138 clang::DeclContext *(clang::DeclContext::*contextFromContext)()) {
139 for (DeclContext *decl_ctx = (decl->*contextFromDecl)(); decl_ctx;
140 decl_ctx = (decl_ctx->*contextFromContext)()) {
141 if (decl_ctx == base) {
142 return true;
143 }
144 }
145
146 return false;
147 }
148
149 clang::Decl *GetEscapedChild(clang::Decl *decl,
150 clang::DeclContext *base = nullptr) {
151 if (base) {
152 // decl's DeclContext chains must pass through base.
153
154 if (!ChainPassesThrough(decl, base, &clang::Decl::getDeclContext,
155 &clang::DeclContext::getParent) ||
156 !ChainPassesThrough(decl, base, &clang::Decl::getLexicalDeclContext,
157 &clang::DeclContext::getLexicalParent)) {
158 return decl;
159 }
160 } else {
161 base = clang::dyn_cast<clang::DeclContext>(decl);
162
163 if (!base) {
164 return nullptr;
165 }
166 }
167
168 if (clang::DeclContext *context =
169 clang::dyn_cast<clang::DeclContext>(decl)) {
170 for (clang::Decl *decl : context->decls()) {
171 if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
172 return escaped_child;
173 }
174 }
175 }
176
177 return nullptr;
178 }
179
180 void Override(clang::Decl *decl) {
181 if (clang::Decl *escaped_child = GetEscapedChild(decl)) {
183
184 LLDB_LOG(log,
185 " [ClangASTImporter] DeclContextOverride couldn't "
186 "override ({0}Decl*){1} - its child ({2}Decl*){3} escapes",
187 decl->getDeclKindName(), decl, escaped_child->getDeclKindName(),
188 escaped_child);
189 lldbassert(0 && "Couldn't override!");
190 }
191
192 OverrideOne(decl);
193 }
194
195public:
197
199 for (DeclContext *decl_context = decl->getLexicalDeclContext();
200 decl_context; decl_context = decl_context->getLexicalParent()) {
201 DeclContext *redecl_context = decl_context->getRedeclContext();
202
203 if (llvm::isa<FunctionDecl>(redecl_context) &&
204 llvm::isa<TranslationUnitDecl>(redecl_context->getLexicalParent())) {
205 for (clang::Decl *child_decl : decl_context->decls()) {
206 Override(child_decl);
207 }
208 }
209 }
210 }
211
213 for (const auto &backup : m_backups) {
214 backup.first->setDeclContext(backup.second.decl_context);
215 backup.first->setLexicalDeclContext(backup.second.lexical_decl_context);
216 }
217 }
218};
219
220namespace {
221/// Completes all imported TagDecls at the end of the scope.
222///
223/// While in a CompleteTagDeclsScope, every decl that could be completed will
224/// be completed at the end of the scope (including all Decls that are
225/// imported while completing the original Decls).
226class CompleteTagDeclsScope : public ClangASTImporter::NewDeclListener {
228 /// List of declarations in the target context that need to be completed.
229 /// Every declaration should only be completed once and therefore should only
230 /// be once in this list.
231 llvm::SetVector<NamedDecl *> m_decls_to_complete;
232 /// Set of declarations that already were successfully completed (not just
233 /// added to m_decls_to_complete).
234 llvm::SmallPtrSet<NamedDecl *, 32> m_decls_already_completed;
235 clang::ASTContext *m_dst_ctx;
236 clang::ASTContext *m_src_ctx;
237 ClangASTImporter &importer;
238
239 void CompleteDecl(
240 Decl *decl,
241 lldb_private::ClangASTImporter::ASTContextMetadata const &to_context_md) {
242 // The decl that should be completed has to be imported into the target
243 // context from some other context.
244 assert(to_context_md.hasOrigin(decl));
245 // We should only complete decls coming from the source context.
246 assert(to_context_md.getOrigin(decl).ctx == m_src_ctx);
247
248 Decl *original_decl = to_context_md.getOrigin(decl).decl;
249
250 // Complete the decl now.
251 TypeSystemClang::GetCompleteDecl(m_src_ctx, original_decl);
252 if (auto *tag_decl = dyn_cast<TagDecl>(decl)) {
253 if (auto *original_tag_decl = dyn_cast<TagDecl>(original_decl)) {
254 if (original_tag_decl->isCompleteDefinition()) {
255 m_delegate->ImportDefinitionTo(tag_decl, original_tag_decl);
256 tag_decl->setCompleteDefinition(true);
257 }
258 }
259
260 tag_decl->setHasExternalLexicalStorage(false);
261 tag_decl->setHasExternalVisibleStorage(false);
262 } else if (auto *container_decl = dyn_cast<ObjCContainerDecl>(decl)) {
263 container_decl->setHasExternalLexicalStorage(false);
264 container_decl->setHasExternalVisibleStorage(false);
265 }
266 }
267
268public:
269 /// Constructs a CompleteTagDeclsScope.
270 /// \param importer The ClangASTImporter that we should observe.
271 /// \param dst_ctx The ASTContext to which Decls are imported.
272 /// \param src_ctx The ASTContext from which Decls are imported.
273 explicit CompleteTagDeclsScope(ClangASTImporter &importer,
274 clang::ASTContext *dst_ctx,
275 clang::ASTContext *src_ctx)
276 : m_delegate(importer.GetDelegate(dst_ctx, src_ctx)), m_dst_ctx(dst_ctx),
277 m_src_ctx(src_ctx), importer(importer) {
278 m_delegate->SetImportListener(this);
279 }
280
281 ~CompleteTagDeclsScope() override {
283 importer.GetContextMetadata(m_dst_ctx);
284
285 // Complete all decls we collected until now.
286 while (!m_decls_to_complete.empty()) {
287 NamedDecl *decl = m_decls_to_complete.pop_back_val();
288 m_decls_already_completed.insert(decl);
289
290 CompleteDecl(decl, *to_context_md);
291
292 to_context_md->removeOrigin(decl);
293 }
294
295 // Stop listening to imported decls. We do this after clearing the
296 // Decls we needed to import to catch all Decls they might have pulled in.
297 m_delegate->RemoveImportListener();
298 }
299
300 void NewDeclImported(clang::Decl *from, clang::Decl *to) override {
301 // Filter out decls that we can't complete later.
302 if (!isa<TagDecl>(to) && !isa<ObjCInterfaceDecl>(to))
303 return;
304 auto *from_record_decl = dyn_cast<CXXRecordDecl>(from);
305 // We don't need to complete injected class name decls.
306 if (from_record_decl && from_record_decl->isInjectedClassName())
307 return;
308
309 NamedDecl *to_named_decl = dyn_cast<NamedDecl>(to);
310 // Check if we already completed this type.
311 if (m_decls_already_completed.contains(to_named_decl))
312 return;
313 // Queue this type to be completed.
314 m_decls_to_complete.insert(to_named_decl);
315 }
316};
317} // namespace
318
320 const CompilerType &src_type) {
322
323 auto src_ctxt = src_type.GetTypeSystem<TypeSystemClang>();
324 if (!src_ctxt)
325 return {};
326
327 LLDB_LOG(log,
328 " [ClangASTImporter] DeportType called on ({0}Type*){1:x} "
329 "from (ASTContext*){2:x} to (ASTContext*){3:x}",
330 src_type.GetTypeName(), src_type.GetOpaqueQualType(),
331 &src_ctxt->getASTContext(), &dst.getASTContext());
332
333 DeclContextOverride decl_context_override;
334
335 if (auto *t = ClangUtil::GetQualType(src_type)->getAs<TagType>())
336 decl_context_override.OverrideAllDeclsFromContainingFunction(t->getDecl());
337
338 CompleteTagDeclsScope complete_scope(*this, &dst.getASTContext(),
339 &src_ctxt->getASTContext());
340 return CopyType(dst, src_type);
341}
342
343clang::Decl *ClangASTImporter::DeportDecl(clang::ASTContext *dst_ctx,
344 clang::Decl *decl) {
346
347 clang::ASTContext *src_ctx = &decl->getASTContext();
348 LLDB_LOG(log,
349 " [ClangASTImporter] DeportDecl called on ({0}Decl*){1:x} from "
350 "(ASTContext*){2:x} to (ASTContext*){3:x}",
351 decl->getDeclKindName(), decl, src_ctx, dst_ctx);
352
353 DeclContextOverride decl_context_override;
354
355 decl_context_override.OverrideAllDeclsFromContainingFunction(decl);
356
357 clang::Decl *result;
358 {
359 CompleteTagDeclsScope complete_scope(*this, dst_ctx, src_ctx);
360 result = CopyDecl(dst_ctx, decl);
361 }
362
363 if (!result)
364 return nullptr;
365
366 LLDB_LOG(log,
367 " [ClangASTImporter] DeportDecl deported ({0}Decl*){1:x} to "
368 "({2}Decl*){3:x}",
369 decl->getDeclKindName(), decl, result->getDeclKindName(), result);
370
371 return result;
372}
373
374bool ClangASTImporter::CanImport(const Decl *d) {
375 if (!d)
376 return false;
377 if (isa<TagDecl>(d))
378 return GetDeclOrigin(d).Valid();
379 if (isa<ObjCInterfaceDecl>(d))
380 return GetDeclOrigin(d).Valid();
381 return false;
382}
383
385 if (!ClangUtil::IsClangType(type))
386 return false;
387
388 clang::QualType qual_type(
390
391 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
392 switch (type_class) {
393 case clang::Type::Record:
394 return CanImport(qual_type->getAsCXXRecordDecl());
395 case clang::Type::Enum:
396 return CanImport(llvm::cast<clang::EnumType>(qual_type)->getDecl());
397 case clang::Type::ObjCObject:
398 case clang::Type::ObjCInterface: {
399 const clang::ObjCObjectType *objc_class_type =
400 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
401 if (objc_class_type) {
402 clang::ObjCInterfaceDecl *class_interface_decl =
403 objc_class_type->getInterface();
404 // We currently can't complete objective C types through the newly added
405 // ASTContext because it only supports TagDecl objects right now...
406 return CanImport(class_interface_decl);
407 }
408 } break;
409
410 case clang::Type::Typedef:
412 llvm::cast<clang::TypedefType>(qual_type)
413 ->getDecl()
414 ->getUnderlyingType()
415 .getAsOpaquePtr()));
416
417 case clang::Type::Auto:
419 llvm::cast<clang::AutoType>(qual_type)
420 ->getDeducedType()
421 .getAsOpaquePtr()));
422
423 case clang::Type::Paren:
424 return CanImport(CompilerType(
425 type.GetTypeSystem(),
426 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
427
428 default:
429 break;
430 }
431
432 return false;
433}
434
436 if (!ClangUtil::IsClangType(type))
437 return false;
438
439 clang::QualType qual_type(
441
442 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
443 switch (type_class) {
444 case clang::Type::Record: {
445 const clang::CXXRecordDecl *cxx_record_decl =
446 qual_type->getAsCXXRecordDecl();
447 if (cxx_record_decl) {
448 if (GetDeclOrigin(cxx_record_decl).Valid())
449 return CompleteAndFetchChildren(qual_type);
450 }
451 } break;
452
453 case clang::Type::Enum: {
454 clang::EnumDecl *enum_decl =
455 llvm::cast<clang::EnumType>(qual_type)->getDecl();
456 if (enum_decl) {
457 if (GetDeclOrigin(enum_decl).Valid())
458 return CompleteAndFetchChildren(qual_type);
459 }
460 } break;
461
462 case clang::Type::ObjCObject:
463 case clang::Type::ObjCInterface: {
464 const clang::ObjCObjectType *objc_class_type =
465 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
466 if (objc_class_type) {
467 clang::ObjCInterfaceDecl *class_interface_decl =
468 objc_class_type->getInterface();
469 // We currently can't complete objective C types through the newly added
470 // ASTContext because it only supports TagDecl objects right now...
471 if (class_interface_decl) {
472 if (GetDeclOrigin(class_interface_decl).Valid())
473 return CompleteAndFetchChildren(qual_type);
474 }
475 }
476 } break;
477
478 case clang::Type::Typedef:
479 return Import(CompilerType(type.GetTypeSystem(),
480 llvm::cast<clang::TypedefType>(qual_type)
481 ->getDecl()
482 ->getUnderlyingType()
483 .getAsOpaquePtr()));
484
485 case clang::Type::Auto:
486 return Import(CompilerType(type.GetTypeSystem(),
487 llvm::cast<clang::AutoType>(qual_type)
488 ->getDeducedType()
489 .getAsOpaquePtr()));
490
491 case clang::Type::Paren:
492 return Import(CompilerType(
493 type.GetTypeSystem(),
494 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
495
496 default:
497 break;
498 }
499 return false;
500}
501
503 if (!CanImport(compiler_type))
504 return false;
505
506 if (Import(compiler_type)) {
508 return true;
509 }
510
512 false);
513 return false;
514}
515
516/// Copy layout information from \ref source_map to the \ref destination_map.
517///
518/// In the process of copying over layout info, we may need to import
519/// decls from the \ref source_map. This function will use the supplied
520/// \ref importer to import the necessary decls into \ref dest_ctx.
521///
522/// \param[in,out] dest_ctx Destination ASTContext into which we import
523/// decls from the \ref source_map.
524/// \param[out] destination_map A map from decls in \ref dest_ctx to an
525/// integral offest, which will be copies
526/// of the decl/offest pairs in \ref source_map
527/// if successful.
528/// \param[in] source_map A map from decls to integral offests. These will
529/// be copied into \ref destination_map.
530/// \param[in,out] importer Used to import decls into \ref dest_ctx.
531///
532/// \returns On success, will return 'true' and the offsets in \ref
533/// destination_map
534/// are usable copies of \ref source_map.
535template <class D, class O>
536static bool ImportOffsetMap(clang::ASTContext *dest_ctx,
537 llvm::DenseMap<const D *, O> &destination_map,
538 llvm::DenseMap<const D *, O> &source_map,
539 ClangASTImporter &importer) {
540 // When importing fields into a new record, clang has a hard requirement that
541 // fields be imported in field offset order. Since they are stored in a
542 // DenseMap with a pointer as the key type, this means we cannot simply
543 // iterate over the map, as the order will be non-deterministic. Instead we
544 // have to sort by the offset and then insert in sorted order.
545 typedef std::pair<const D *, O> PairType;
546 std::vector<PairType> sorted_items;
547 sorted_items.reserve(source_map.size());
548 sorted_items.assign(source_map.begin(), source_map.end());
549 llvm::sort(sorted_items, llvm::less_second());
550
551 for (const auto &item : sorted_items) {
552 DeclFromUser<D> user_decl(const_cast<D *>(item.first));
553 DeclFromParser<D> parser_decl(user_decl.Import(dest_ctx, importer));
554 if (parser_decl.IsInvalid())
555 return false;
556 destination_map.insert(
557 std::pair<const D *, O>(parser_decl.decl, item.second));
558 }
559
560 return true;
561}
562
563/// Given a CXXRecordDecl, will calculate and populate \ref base_offsets
564/// with the integral offsets of any of its (possibly virtual) base classes.
565///
566/// \param[in] record_layout ASTRecordLayout of \ref record.
567/// \param[in] record The record that we're calculating the base layouts of.
568/// \param[out] base_offsets Map of base-class decl to integral offset which
569/// this function will fill in.
570///
571/// \returns On success, will return 'true' and the offsets in \ref base_offsets
572/// are usable.
573template <bool IsVirtual>
574bool ExtractBaseOffsets(const ASTRecordLayout &record_layout,
576 llvm::DenseMap<const clang::CXXRecordDecl *,
577 clang::CharUnits> &base_offsets) {
578 for (CXXRecordDecl::base_class_const_iterator
579 bi = (IsVirtual ? record->vbases_begin() : record->bases_begin()),
580 be = (IsVirtual ? record->vbases_end() : record->bases_end());
581 bi != be; ++bi) {
582 if (!IsVirtual && bi->isVirtual())
583 continue;
584
585 const clang::Type *origin_base_type = bi->getType().getTypePtr();
586 const clang::RecordType *origin_base_record_type =
587 origin_base_type->getAs<RecordType>();
588
589 if (!origin_base_record_type)
590 return false;
591
592 DeclFromUser<RecordDecl> origin_base_record(
593 origin_base_record_type->getDecl());
594
595 if (origin_base_record.IsInvalid())
596 return false;
597
598 DeclFromUser<CXXRecordDecl> origin_base_cxx_record(
599 DynCast<CXXRecordDecl>(origin_base_record));
600
601 if (origin_base_cxx_record.IsInvalid())
602 return false;
603
604 CharUnits base_offset;
605
606 if (IsVirtual)
607 base_offset =
608 record_layout.getVBaseClassOffset(origin_base_cxx_record.decl);
609 else
610 base_offset =
611 record_layout.getBaseClassOffset(origin_base_cxx_record.decl);
612
613 base_offsets.insert(std::pair<const CXXRecordDecl *, CharUnits>(
614 origin_base_cxx_record.decl, base_offset));
615 }
616
617 return true;
618}
619
621 const RecordDecl *record, uint64_t &size, uint64_t &alignment,
622 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
623 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
624 &base_offsets,
625 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
626 &vbase_offsets) {
627
629
630 clang::ASTContext &dest_ctx = record->getASTContext();
631 LLDB_LOG(log,
632 "LayoutRecordType on (ASTContext*){0:x} '{1}' for (RecordDecl*)"
633 "{2:x} [name = '{3}']",
634 &dest_ctx,
635 TypeSystemClang::GetASTContext(&dest_ctx)->getDisplayName(), record,
636 record->getName());
637
638 DeclFromParser<const RecordDecl> parser_record(record);
639 DeclFromUser<const RecordDecl> origin_record(parser_record.GetOrigin(*this));
640
641 if (origin_record.IsInvalid())
642 return false;
643
644 std::remove_reference_t<decltype(field_offsets)> origin_field_offsets;
645 std::remove_reference_t<decltype(base_offsets)> origin_base_offsets;
646 std::remove_reference_t<decltype(vbase_offsets)> origin_virtual_base_offsets;
647
649 &origin_record->getASTContext(),
650 const_cast<RecordDecl *>(origin_record.decl));
651
652 clang::RecordDecl *definition = origin_record.decl->getDefinition();
653 if (!definition || !definition->isCompleteDefinition())
654 return false;
655
656 const ASTRecordLayout &record_layout(
657 origin_record->getASTContext().getASTRecordLayout(origin_record.decl));
658
659 int field_idx = 0, field_count = record_layout.getFieldCount();
660
661 for (RecordDecl::field_iterator fi = origin_record->field_begin(),
662 fe = origin_record->field_end();
663 fi != fe; ++fi) {
664 if (field_idx >= field_count)
665 return false; // Layout didn't go well. Bail out.
666
667 uint64_t field_offset = record_layout.getFieldOffset(field_idx);
668
669 origin_field_offsets.insert(
670 std::pair<const FieldDecl *, uint64_t>(*fi, field_offset));
671
672 field_idx++;
673 }
674
675 DeclFromUser<const CXXRecordDecl> origin_cxx_record(
676 DynCast<const CXXRecordDecl>(origin_record));
677
678 if (origin_cxx_record.IsValid()) {
679 if (!ExtractBaseOffsets<false>(record_layout, origin_cxx_record,
680 origin_base_offsets) ||
681 !ExtractBaseOffsets<true>(record_layout, origin_cxx_record,
682 origin_virtual_base_offsets))
683 return false;
684 }
685
686 if (!ImportOffsetMap(&dest_ctx, field_offsets, origin_field_offsets, *this) ||
687 !ImportOffsetMap(&dest_ctx, base_offsets, origin_base_offsets, *this) ||
688 !ImportOffsetMap(&dest_ctx, vbase_offsets, origin_virtual_base_offsets,
689 *this))
690 return false;
691
692 size = record_layout.getSize().getQuantity() * dest_ctx.getCharWidth();
693 alignment =
694 record_layout.getAlignment().getQuantity() * dest_ctx.getCharWidth();
695
696 if (log) {
697 LLDB_LOG(log, "LRT returned:");
698 LLDB_LOG(log, "LRT Original = (RecordDecl*){0:x}",
699 static_cast<const void *>(origin_record.decl));
700 LLDB_LOG(log, "LRT Size = {0}", size);
701 LLDB_LOG(log, "LRT Alignment = {0}", alignment);
702 LLDB_LOG(log, "LRT Fields:");
703 for (RecordDecl::field_iterator fi = record->field_begin(),
704 fe = record->field_end();
705 fi != fe; ++fi) {
706 LLDB_LOG(
707 log,
708 "LRT (FieldDecl*){0:x}, Name = '{1}', Type = '{2}', Offset = "
709 "{3} bits",
710 *fi, fi->getName(), fi->getType().getAsString(), field_offsets[*fi]);
711 }
712 DeclFromParser<const CXXRecordDecl> parser_cxx_record =
713 DynCast<const CXXRecordDecl>(parser_record);
714 if (parser_cxx_record.IsValid()) {
715 LLDB_LOG(log, "LRT Bases:");
716 for (CXXRecordDecl::base_class_const_iterator
717 bi = parser_cxx_record->bases_begin(),
718 be = parser_cxx_record->bases_end();
719 bi != be; ++bi) {
720 bool is_virtual = bi->isVirtual();
721
722 QualType base_type = bi->getType();
723 const RecordType *base_record_type = base_type->getAs<RecordType>();
724 DeclFromParser<RecordDecl> base_record(base_record_type->getDecl());
725 DeclFromParser<CXXRecordDecl> base_cxx_record =
726 DynCast<CXXRecordDecl>(base_record);
727
728 LLDB_LOG(log,
729 "LRT {0}(CXXRecordDecl*){1:x}, Name = '{2}', Offset = "
730 "{3} chars",
731 (is_virtual ? "Virtual " : ""), base_cxx_record.decl,
732 base_cxx_record.decl->getName(),
733 (is_virtual
734 ? vbase_offsets[base_cxx_record.decl].getQuantity()
735 : base_offsets[base_cxx_record.decl].getQuantity()));
736 }
737 } else {
738 LLDB_LOG(log, "LRD Not a CXXRecord, so no bases");
739 }
740 }
741
742 return true;
743}
744
746 const clang::RecordDecl *record_decl, uint64_t &bit_size,
747 uint64_t &alignment,
748 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
749 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
750 &base_offsets,
751 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
752 &vbase_offsets) {
753 RecordDeclToLayoutMap::iterator pos =
754 m_record_decl_to_layout_map.find(record_decl);
755 base_offsets.clear();
756 vbase_offsets.clear();
757 if (pos != m_record_decl_to_layout_map.end()) {
758 bit_size = pos->second.bit_size;
759 alignment = pos->second.alignment;
760 field_offsets.swap(pos->second.field_offsets);
761 base_offsets.swap(pos->second.base_offsets);
762 vbase_offsets.swap(pos->second.vbase_offsets);
764 return true;
765 }
766
767 // It's possible that we calculated the layout in a different
768 // ClangASTImporter instance. Try to import such layout if
769 // our decl has an origin.
770 if (auto origin = GetDeclOrigin(record_decl); origin.Valid())
771 if (importRecordLayoutFromOrigin(record_decl, bit_size, alignment,
772 field_offsets, base_offsets,
773 vbase_offsets))
774 return true;
775
776 bit_size = 0;
777 alignment = 0;
778 field_offsets.clear();
779
780 return false;
781}
782
783void ClangASTImporter::SetRecordLayout(clang::RecordDecl *decl,
784 const LayoutInfo &layout) {
785 m_record_decl_to_layout_map.insert(std::make_pair(decl, layout));
786}
787
788bool ClangASTImporter::CompleteTagDecl(clang::TagDecl *decl) {
789 DeclOrigin decl_origin = GetDeclOrigin(decl);
790
791 if (!decl_origin.Valid())
792 return false;
793
794 if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
795 return false;
796
797 ImporterDelegateSP delegate_sp(
798 GetDelegate(&decl->getASTContext(), decl_origin.ctx));
799
800 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
801 &decl->getASTContext());
802 if (delegate_sp)
803 delegate_sp->ImportDefinitionTo(decl, decl_origin.decl);
804
805 return true;
806}
807
809 clang::TagDecl *origin_decl) {
810 clang::ASTContext *origin_ast_ctx = &origin_decl->getASTContext();
811
812 if (!TypeSystemClang::GetCompleteDecl(origin_ast_ctx, origin_decl))
813 return false;
814
815 ImporterDelegateSP delegate_sp(
816 GetDelegate(&decl->getASTContext(), origin_ast_ctx));
817
818 if (delegate_sp)
819 delegate_sp->ImportDefinitionTo(decl, origin_decl);
820
821 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
822
823 context_md->setOrigin(decl, DeclOrigin(origin_ast_ctx, origin_decl));
824 return true;
825}
826
828 clang::ObjCInterfaceDecl *interface_decl) {
829 DeclOrigin decl_origin = GetDeclOrigin(interface_decl);
830
831 if (!decl_origin.Valid())
832 return false;
833
834 if (!TypeSystemClang::GetCompleteDecl(decl_origin.ctx, decl_origin.decl))
835 return false;
836
837 ImporterDelegateSP delegate_sp(
838 GetDelegate(&interface_decl->getASTContext(), decl_origin.ctx));
839
840 if (delegate_sp)
841 delegate_sp->ImportDefinitionTo(interface_decl, decl_origin.decl);
842
843 if (ObjCInterfaceDecl *super_class = interface_decl->getSuperClass())
844 RequireCompleteType(clang::QualType(super_class->getTypeForDecl(), 0));
845
846 return true;
847}
848
850 if (!RequireCompleteType(type))
851 return false;
852
854
855 if (const TagType *tag_type = type->getAs<TagType>()) {
856 TagDecl *tag_decl = tag_type->getDecl();
857
858 DeclOrigin decl_origin = GetDeclOrigin(tag_decl);
859
860 if (!decl_origin.Valid())
861 return false;
862
863 ImporterDelegateSP delegate_sp(
864 GetDelegate(&tag_decl->getASTContext(), decl_origin.ctx));
865
866 ASTImporterDelegate::CxxModuleScope std_scope(*delegate_sp,
867 &tag_decl->getASTContext());
868
869 TagDecl *origin_tag_decl = llvm::dyn_cast<TagDecl>(decl_origin.decl);
870
871 for (Decl *origin_child_decl : origin_tag_decl->decls()) {
872 llvm::Expected<Decl *> imported_or_err =
873 delegate_sp->Import(origin_child_decl);
874 if (!imported_or_err) {
875 LLDB_LOG_ERROR(log, imported_or_err.takeError(),
876 "Couldn't import decl: {0}");
877 return false;
878 }
879 }
880
881 if (RecordDecl *record_decl = dyn_cast<RecordDecl>(origin_tag_decl))
882 record_decl->setHasLoadedFieldsFromExternalStorage(true);
883
884 return true;
885 }
886
887 if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
888 if (ObjCInterfaceDecl *objc_interface_decl =
889 objc_object_type->getInterface()) {
890 DeclOrigin decl_origin = GetDeclOrigin(objc_interface_decl);
891
892 if (!decl_origin.Valid())
893 return false;
894
895 ImporterDelegateSP delegate_sp(
896 GetDelegate(&objc_interface_decl->getASTContext(), decl_origin.ctx));
897
898 ObjCInterfaceDecl *origin_interface_decl =
899 llvm::dyn_cast<ObjCInterfaceDecl>(decl_origin.decl);
900
901 for (Decl *origin_child_decl : origin_interface_decl->decls()) {
902 llvm::Expected<Decl *> imported_or_err =
903 delegate_sp->Import(origin_child_decl);
904 if (!imported_or_err) {
905 LLDB_LOG_ERROR(log, imported_or_err.takeError(),
906 "Couldn't import decl: {0}");
907 return false;
908 }
909 }
910
911 return true;
912 }
913 return false;
914 }
915
916 return true;
917}
918
919bool ClangASTImporter::RequireCompleteType(clang::QualType type) {
920 if (type.isNull())
921 return false;
922
923 if (const TagType *tag_type = type->getAs<TagType>()) {
924 TagDecl *tag_decl = tag_type->getDecl();
925
926 if (tag_decl->getDefinition())
927 return true;
928
929 return CompleteTagDecl(tag_decl);
930 }
931 if (const ObjCObjectType *objc_object_type = type->getAs<ObjCObjectType>()) {
932 if (ObjCInterfaceDecl *objc_interface_decl =
933 objc_object_type->getInterface())
934 return CompleteObjCInterfaceDecl(objc_interface_decl);
935 return false;
936 }
937 if (const ArrayType *array_type = type->getAsArrayTypeUnsafe())
938 return RequireCompleteType(array_type->getElementType());
939 if (const AtomicType *atomic_type = type->getAs<AtomicType>())
940 return RequireCompleteType(atomic_type->getPointeeType());
941
942 return true;
943}
944
945std::optional<ClangASTMetadata>
946ClangASTImporter::GetDeclMetadata(const clang::Decl *decl) {
947 DeclOrigin decl_origin = GetDeclOrigin(decl);
948
949 if (decl_origin.Valid()) {
951 return ast->GetMetadata(decl_origin.decl);
952 }
953 TypeSystemClang *ast = TypeSystemClang::GetASTContext(&decl->getASTContext());
954 return ast->GetMetadata(decl);
955}
956
958ClangASTImporter::GetDeclOrigin(const clang::Decl *decl) {
959 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
960
961 return context_md->getOrigin(decl);
962}
963
964void ClangASTImporter::SetDeclOrigin(const clang::Decl *decl,
965 clang::Decl *original_decl) {
966 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
967 context_md->setOrigin(
968 decl, DeclOrigin(&original_decl->getASTContext(), original_decl));
969}
970
971void ClangASTImporter::RegisterNamespaceMap(const clang::NamespaceDecl *decl,
972 NamespaceMapSP namespace_map) {
973 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
974
975 context_md->m_namespace_maps[decl] = std::move(namespace_map);
976}
977
979ClangASTImporter::GetNamespaceMap(const clang::NamespaceDecl *decl) {
980 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
981
982 NamespaceMetaMap &namespace_maps = context_md->m_namespace_maps;
983
984 NamespaceMetaMap::iterator iter = namespace_maps.find(decl);
985
986 if (iter != namespace_maps.end())
987 return iter->second;
988 return NamespaceMapSP();
989}
990
991void ClangASTImporter::BuildNamespaceMap(const clang::NamespaceDecl *decl) {
992 assert(decl);
993 ASTContextMetadataSP context_md = GetContextMetadata(&decl->getASTContext());
994
995 const DeclContext *parent_context = decl->getDeclContext();
996 const NamespaceDecl *parent_namespace =
997 dyn_cast<NamespaceDecl>(parent_context);
998 NamespaceMapSP parent_map;
999
1000 if (parent_namespace)
1001 parent_map = GetNamespaceMap(parent_namespace);
1002
1003 NamespaceMapSP new_map;
1004
1005 new_map = std::make_shared<NamespaceMap>();
1006
1007 if (context_md->m_map_completer) {
1008 std::string namespace_string = decl->getDeclName().getAsString();
1009
1010 context_md->m_map_completer->CompleteNamespaceMap(
1011 new_map, ConstString(namespace_string), parent_map);
1012 }
1013
1014 context_md->m_namespace_maps[decl] = new_map;
1015}
1016
1017void ClangASTImporter::ForgetDestination(clang::ASTContext *dst_ast) {
1019
1020 LLDB_LOG(log,
1021 " [ClangASTImporter] Forgetting destination (ASTContext*){0:x}",
1022 dst_ast);
1023
1024 m_metadata_map.erase(dst_ast);
1025}
1026
1027void ClangASTImporter::ForgetSource(clang::ASTContext *dst_ast,
1028 clang::ASTContext *src_ast) {
1030
1032
1033 LLDB_LOG(log,
1034 " [ClangASTImporter] Forgetting source->dest "
1035 "(ASTContext*){0:x}->(ASTContext*){1:x}",
1036 src_ast, dst_ast);
1037
1038 if (!md)
1039 return;
1040
1041 md->m_delegates.erase(src_ast);
1042 md->removeOriginsWithContext(src_ast);
1043}
1044
1046
1047llvm::Expected<Decl *>
1049 // FIXME: The Minimal import mode of clang::ASTImporter does not correctly
1050 // import Lambda definitions. Work around this for now by not importing
1051 // lambdas at all. This is most likely encountered when importing decls from
1052 // the `std` module (not from debug-info), where lambdas can be defined in
1053 // inline function bodies. Those will be imported by LLDB.
1054 if (const auto *CXX = llvm::dyn_cast<clang::CXXRecordDecl>(From))
1055 if (CXX->isLambda())
1056 return llvm::make_error<ASTImportError>(
1057 ASTImportError::UnsupportedConstruct);
1058
1059 if (m_std_handler) {
1060 std::optional<Decl *> D = m_std_handler->Import(From);
1061 if (D) {
1062 // Make sure we don't use this decl later to map it back to it's original
1063 // decl. The decl the CxxModuleHandler created has nothing to do with
1064 // the one from debug info, and linking those two would just cause the
1065 // ASTImporter to try 'updating' the module decl with the minimal one from
1066 // the debug info.
1067 m_decls_to_ignore.insert(*D);
1068 return *D;
1069 }
1070 }
1071
1072 // Check which ASTContext this declaration originally came from.
1073 DeclOrigin origin = m_main.GetDeclOrigin(From);
1074
1075 // Prevent infinite recursion when the origin tracking contains a cycle.
1076 assert(origin.decl != From && "Origin points to itself?");
1077
1078 // If it originally came from the target ASTContext then we can just
1079 // pretend that the original is the one we imported. This can happen for
1080 // example when inspecting a persistent declaration from the scratch
1081 // ASTContext (which will provide the declaration when parsing the
1082 // expression and then we later try to copy the declaration back to the
1083 // scratch ASTContext to store the result).
1084 // Without this check we would ask the ASTImporter to import a declaration
1085 // into the same ASTContext where it came from (which doesn't make a lot of
1086 // sense).
1087 if (origin.Valid() && origin.ctx == &getToContext()) {
1088 RegisterImportedDecl(From, origin.decl);
1089 return origin.decl;
1090 }
1091
1092 // This declaration came originally from another ASTContext. Instead of
1093 // copying our potentially incomplete 'From' Decl we instead go to the
1094 // original ASTContext and copy the original to the target. This is not
1095 // only faster than first completing our current decl and then copying it
1096 // to the target, but it also prevents that indirectly copying the same
1097 // declaration to the same target requires the ASTImporter to merge all
1098 // the different decls that appear to come from different ASTContexts (even
1099 // though all these different source ASTContexts just got a copy from
1100 // one source AST).
1101 if (origin.Valid()) {
1102 auto R = m_main.CopyDecl(&getToContext(), origin.decl);
1103 if (R) {
1104 RegisterImportedDecl(From, R);
1105 return R;
1106 }
1107 }
1108
1109 // If we have a forcefully completed type, try to find an actual definition
1110 // for it in other modules.
1111 std::optional<ClangASTMetadata> md = m_main.GetDeclMetadata(From);
1112 auto *td = dyn_cast<TagDecl>(From);
1113 if (td && md && md->IsForcefullyCompleted()) {
1115 LLDB_LOG(log,
1116 "[ClangASTImporter] Searching for a complete definition of {0} in "
1117 "other modules",
1118 td->getName());
1119 Expected<DeclContext *> dc_or_err = ImportContext(td->getDeclContext());
1120 if (!dc_or_err)
1121 return dc_or_err.takeError();
1122 Expected<DeclarationName> dn_or_err = Import(td->getDeclName());
1123 if (!dn_or_err)
1124 return dn_or_err.takeError();
1125 DeclContext *dc = *dc_or_err;
1126 DeclContext::lookup_result lr = dc->lookup(*dn_or_err);
1127 for (clang::Decl *candidate : lr) {
1128 if (candidate->getKind() == From->getKind()) {
1129 RegisterImportedDecl(From, candidate);
1130 m_decls_to_ignore.insert(candidate);
1131 return candidate;
1132 }
1133 }
1134 LLDB_LOG(log, "[ClangASTImporter] Complete definition not found");
1135 }
1136
1137 return ASTImporter::ImportImpl(From);
1138}
1139
1141 clang::Decl *to, clang::Decl *from) {
1143
1144 auto getDeclName = [](Decl const *decl) {
1145 std::string name_string;
1146 if (auto const *from_named_decl = dyn_cast<clang::NamedDecl>(decl)) {
1147 llvm::raw_string_ostream name_stream(name_string);
1148 from_named_decl->printName(name_stream);
1149 }
1150
1151 return name_string;
1152 };
1153
1154 if (log) {
1155 if (auto *D = GetAlreadyImportedOrNull(from); D && D != to) {
1156 LLDB_LOG(
1157 log,
1158 "[ClangASTImporter] ERROR: overwriting an already imported decl "
1159 "'{0:x}' ('{1}') from '{2:x}' with '{3:x}'. Likely due to a name "
1160 "conflict when importing '{1}'.",
1161 D, getDeclName(from), from, to);
1162 }
1163 }
1164
1165 // We might have a forward declaration from a shared library that we
1166 // gave external lexical storage so that Clang asks us about the full
1167 // definition when it needs it. In this case the ASTImporter isn't aware
1168 // that the forward decl from the shared library is the actual import
1169 // target but would create a second declaration that would then be defined.
1170 // We want that 'to' is actually complete after this function so let's
1171 // tell the ASTImporter that 'to' was imported from 'from'.
1172 MapImported(from, to);
1173
1174 if (llvm::Error err = ImportDefinition(from)) {
1175 LLDB_LOG_ERROR(log, std::move(err),
1176 "[ClangASTImporter] Error during importing definition: {0}");
1177 return;
1178 }
1179
1180 if (clang::TagDecl *to_tag = dyn_cast<clang::TagDecl>(to)) {
1181 if (clang::TagDecl *from_tag = dyn_cast<clang::TagDecl>(from)) {
1182 to_tag->setCompleteDefinition(from_tag->isCompleteDefinition());
1183
1184 if (Log *log_ast = GetLog(LLDBLog::AST)) {
1185 LLDB_LOG(log_ast,
1186 "==== [ClangASTImporter][TUDecl: {0:x}] Imported "
1187 "({1}Decl*){2:x}, named {3} (from "
1188 "(Decl*){4:x})",
1189 static_cast<void *>(to->getTranslationUnitDecl()),
1190 from->getDeclKindName(), static_cast<void *>(to),
1191 getDeclName(from), static_cast<void *>(from));
1192
1193 // Log the AST of the TU.
1194 std::string ast_string;
1195 llvm::raw_string_ostream ast_stream(ast_string);
1196 to->getTranslationUnitDecl()->dump(ast_stream);
1197 LLDB_LOG(log_ast, "{0}", ast_string);
1198 }
1199 }
1200 }
1201
1202 // If we're dealing with an Objective-C class, ensure that the inheritance
1203 // has been set up correctly. The ASTImporter may not do this correctly if
1204 // the class was originally sourced from symbols.
1205
1206 if (ObjCInterfaceDecl *to_objc_interface = dyn_cast<ObjCInterfaceDecl>(to)) {
1207 ObjCInterfaceDecl *to_superclass = to_objc_interface->getSuperClass();
1208
1209 if (to_superclass)
1210 return; // we're not going to override it if it's set
1211
1212 ObjCInterfaceDecl *from_objc_interface = dyn_cast<ObjCInterfaceDecl>(from);
1213
1214 if (!from_objc_interface)
1215 return;
1216
1217 ObjCInterfaceDecl *from_superclass = from_objc_interface->getSuperClass();
1218
1219 if (!from_superclass)
1220 return;
1221
1222 llvm::Expected<Decl *> imported_from_superclass_decl =
1223 Import(from_superclass);
1224
1225 if (!imported_from_superclass_decl) {
1226 LLDB_LOG_ERROR(log, imported_from_superclass_decl.takeError(),
1227 "Couldn't import decl: {0}");
1228 return;
1229 }
1230
1231 ObjCInterfaceDecl *imported_from_superclass =
1232 dyn_cast<ObjCInterfaceDecl>(*imported_from_superclass_decl);
1233
1234 if (!imported_from_superclass)
1235 return;
1236
1237 if (!to_objc_interface->hasDefinition())
1238 to_objc_interface->startDefinition();
1239
1240 to_objc_interface->setSuperClass(m_source_ctx->getTrivialTypeSourceInfo(
1241 m_source_ctx->getObjCInterfaceType(imported_from_superclass)));
1242 }
1243}
1244
1245/// Takes a CXXMethodDecl and completes the return type if necessary. This
1246/// is currently only necessary for virtual functions with covariant return
1247/// types where Clang's CodeGen expects that the underlying records are already
1248/// completed.
1250 CXXMethodDecl *to_method) {
1251 if (!to_method->isVirtual())
1252 return;
1253 QualType return_type = to_method->getReturnType();
1254 if (!return_type->isPointerType() && !return_type->isReferenceType())
1255 return;
1256
1257 clang::RecordDecl *rd = return_type->getPointeeType()->getAsRecordDecl();
1258 if (!rd)
1259 return;
1260 if (rd->getDefinition())
1261 return;
1262
1263 importer.CompleteTagDecl(rd);
1264}
1265
1266/// Recreate a module with its parents in \p to_source and return its id.
1267static OptionalClangModuleID
1271 if (!from_id.HasValue())
1272 return {};
1273 clang::Module *module = from_source.getModule(from_id.GetValue());
1275 from_source.GetIDForModule(module->Parent), from_source, to_source);
1276 TypeSystemClang &to_ts = to_source.GetTypeSystem();
1277 return to_ts.GetOrCreateClangModule(module->Name, parent, module->IsFramework,
1278 module->IsExplicit);
1279}
1280
1282 clang::Decl *to) {
1284
1285 // Some decls shouldn't be tracked here because they were not created by
1286 // copying 'from' to 'to'. Just exit early for those.
1287 if (m_decls_to_ignore.count(to))
1288 return;
1289
1290 // Transfer module ownership information.
1291 auto *from_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1292 getFromContext().getExternalSource());
1293 // Can also be a ClangASTSourceProxy.
1294 auto *to_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1295 getToContext().getExternalSource());
1296 if (from_source && to_source) {
1297 OptionalClangModuleID from_id(from->getOwningModuleID());
1298 OptionalClangModuleID to_id =
1299 RemapModule(from_id, *from_source, *to_source);
1300 TypeSystemClang &to_ts = to_source->GetTypeSystem();
1301 to_ts.SetOwningModule(to, to_id);
1302 }
1303
1305 if (std::optional<ClangASTMetadata> metadata = m_main.GetDeclMetadata(from)) {
1306 user_id = metadata->GetUserID();
1307 lldb::LanguageType lang_type = metadata->GetLanguageType();
1308 if (Language::LanguageIsRust(lang_type)) {
1309 if (TypeSystemClang *to_ts =
1310 TypeSystemClang::GetASTContext(&to->getASTContext())) {
1311 ClangASTMetadata to_metadata;
1312 if (std::optional<ClangASTMetadata> existing = to_ts->GetMetadata(to))
1313 to_metadata = *existing;
1314 to_metadata.SetLanguageType(lang_type);
1315 to_ts->SetMetadata(to, to_metadata);
1316 }
1317 }
1318 }
1319
1320 if (log) {
1321 if (NamedDecl *from_named_decl = dyn_cast<clang::NamedDecl>(from)) {
1322 std::string name_string;
1323 llvm::raw_string_ostream name_stream(name_string);
1324 from_named_decl->printName(name_stream);
1325
1326 LLDB_LOG(
1327 log,
1328 " [ClangASTImporter] Imported ({0}Decl*){1:x}, named {2} (from "
1329 "(Decl*){3:x}), metadata {4}",
1330 from->getDeclKindName(), to, name_string, from, user_id);
1331 } else {
1332 LLDB_LOG(log,
1333 " [ClangASTImporter] Imported ({0}Decl*){1:x} (from "
1334 "(Decl*){2:x}), metadata {3}",
1335 from->getDeclKindName(), to, from, user_id);
1336 }
1337 }
1338
1339 ASTContextMetadataSP to_context_md =
1340 m_main.GetContextMetadata(&to->getASTContext());
1341 ASTContextMetadataSP from_context_md =
1342 m_main.MaybeGetContextMetadata(m_source_ctx);
1343
1344 if (from_context_md) {
1345 DeclOrigin origin = from_context_md->getOrigin(from);
1346
1347 if (origin.Valid()) {
1348 if (origin.ctx != &to->getASTContext()) {
1349 if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)
1350 to_context_md->setOrigin(to, origin);
1351
1352 LLDB_LOG(log,
1353 " [ClangASTImporter] Propagated origin "
1354 "(Decl*){0:x}/(ASTContext*){1:x} from (ASTContext*){2:x} to "
1355 "(ASTContext*){3:x}",
1356 origin.decl, origin.ctx, &from->getASTContext(),
1357 &to->getASTContext());
1358 }
1359 } else {
1361 m_new_decl_listener->NewDeclImported(from, to);
1362
1363 if (!to_context_md->hasOrigin(to) || user_id != LLDB_INVALID_UID)
1364 to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));
1365
1366 LLDB_LOG(log,
1367 " [ClangASTImporter] Decl has no origin information in "
1368 "(ASTContext*){0:x}",
1369 &from->getASTContext());
1370 }
1371
1372 if (auto *to_namespace = dyn_cast<clang::NamespaceDecl>(to)) {
1373 auto *from_namespace = cast<clang::NamespaceDecl>(from);
1374
1375 NamespaceMetaMap &namespace_maps = from_context_md->m_namespace_maps;
1376
1377 NamespaceMetaMap::iterator namespace_map_iter =
1378 namespace_maps.find(from_namespace);
1379
1380 if (namespace_map_iter != namespace_maps.end())
1381 to_context_md->m_namespace_maps[to_namespace] =
1382 namespace_map_iter->second;
1383 }
1384 } else {
1385 to_context_md->setOrigin(to, DeclOrigin(m_source_ctx, from));
1386
1387 LLDB_LOG(log,
1388 " [ClangASTImporter] Sourced origin "
1389 "(Decl*){0:x}/(ASTContext*){1:x} into (ASTContext*){2:x}",
1390 from, m_source_ctx, &to->getASTContext());
1391 }
1392
1393 if (auto *to_namespace_decl = dyn_cast<NamespaceDecl>(to)) {
1394 m_main.BuildNamespaceMap(to_namespace_decl);
1395 to_namespace_decl->setHasExternalVisibleStorage();
1396 }
1397
1398 MarkDeclImported(from, to);
1399}
1400
1402 Decl *to) {
1404
1405 if (auto *to_tag_decl = dyn_cast<TagDecl>(to)) {
1406 to_tag_decl->setHasExternalLexicalStorage();
1407 to_tag_decl->getPrimaryContext()->setMustBuildLookupTable();
1408 auto from_tag_decl = cast<TagDecl>(from);
1409
1410 LLDB_LOG(
1411 log,
1412 " [ClangASTImporter] To is a TagDecl - attributes {0}{1} [{2}->{3}]",
1413 (to_tag_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1414 (to_tag_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1415 (from_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"),
1416 (to_tag_decl->isCompleteDefinition() ? "complete" : "incomplete"));
1417 }
1418
1419 if (auto *to_container_decl = dyn_cast<ObjCContainerDecl>(to)) {
1420 to_container_decl->setHasExternalLexicalStorage();
1421 to_container_decl->setHasExternalVisibleStorage();
1422
1423 if (log) {
1424 if (ObjCInterfaceDecl *to_interface_decl =
1425 llvm::dyn_cast<ObjCInterfaceDecl>(to_container_decl)) {
1426 LLDB_LOG(
1427 log,
1428 " [ClangASTImporter] To is an ObjCInterfaceDecl - attributes "
1429 "{0}{1}{2}",
1430 (to_interface_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1431 (to_interface_decl->hasExternalVisibleStorage() ? " Visible" : ""),
1432 (to_interface_decl->hasDefinition() ? " HasDefinition" : ""));
1433 } else {
1434 LLDB_LOG(
1435 log, " [ClangASTImporter] To is an {0}Decl - attributes {1}{2}",
1436 ((Decl *)to_container_decl)->getDeclKindName(),
1437 (to_container_decl->hasExternalLexicalStorage() ? " Lexical" : ""),
1438 (to_container_decl->hasExternalVisibleStorage() ? " Visible" : ""));
1439 }
1440 }
1441 }
1442
1443 if (clang::CXXMethodDecl *to_method = dyn_cast<CXXMethodDecl>(to))
1444 MaybeCompleteReturnType(m_main, to_method);
1445}
1446
1447clang::Decl *
1449 return m_main.GetDeclOrigin(To).decl;
1450}
static OptionalClangModuleID RemapModule(OptionalClangModuleID from_id, ClangExternalASTSourceCallbacks &from_source, ClangExternalASTSourceCallbacks &to_source)
Recreate a module with its parents in to_source and return its id.
bool ExtractBaseOffsets(const ASTRecordLayout &record_layout, DeclFromUser< const CXXRecordDecl > &record, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &base_offsets)
Given a CXXRecordDecl, will calculate and populate base_offsets with the integral offsets of any of i...
static void MaybeCompleteReturnType(ClangASTImporter &importer, CXXMethodDecl *to_method)
Takes a CXXMethodDecl and completes the return type if necessary.
static bool ImportOffsetMap(clang::ASTContext *dest_ctx, llvm::DenseMap< const D *, O > &destination_map, llvm::DenseMap< const D *, O > &source_map, ClangASTImporter &importer)
Copy layout information from source_map to the destination_map.
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
DeclContextOverride()=default
void Override(clang::Decl *decl)
llvm::DenseMap< clang::Decl *, Backup > m_backups
void OverrideAllDeclsFromContainingFunction(clang::Decl *decl)
void OverrideOne(clang::Decl *decl)
clang::Decl * GetEscapedChild(clang::Decl *decl, clang::DeclContext *base=nullptr)
bool ChainPassesThrough(clang::Decl *decl, clang::DeclContext *base, clang::DeclContext *(clang::Decl::*contextFromDecl)(), clang::DeclContext *(clang::DeclContext::*contextFromContext)())
bool hasOrigin(const clang::Decl *decl) const
Returns true there is a known DeclOrigin for the given Decl.
DeclOrigin getOrigin(const clang::Decl *decl) const
Returns the DeclOrigin for the given Decl or an invalid DeclOrigin instance if there no known DeclOri...
Scope guard that attaches a CxxModuleHandler to an ASTImporterDelegate and deattaches it at the end o...
Manages and observes all Clang AST node importing in LLDB.
bool CompleteTagDecl(clang::TagDecl *decl)
std::optional< ClangASTMetadata > GetDeclMetadata(const clang::Decl *decl)
clang::Decl * DeportDecl(clang::ASTContext *dst_ctx, clang::Decl *decl)
Copies the given decl to the destination type system.
void BuildNamespaceMap(const clang::NamespaceDecl *decl)
void ForgetDestination(clang::ASTContext *dst_ctx)
CompilerType CopyType(TypeSystemClang &dst, const CompilerType &src_type)
Copies the given type and the respective declarations to the destination type system.
clang::Decl * CopyDecl(clang::ASTContext *dst_ctx, clang::Decl *decl)
DeclOrigin GetDeclOrigin(const clang::Decl *decl)
bool LayoutRecordType(const clang::RecordDecl *record_decl, uint64_t &bit_size, uint64_t &alignment, llvm::DenseMap< const clang::FieldDecl *, uint64_t > &field_offsets, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &base_offsets, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &vbase_offsets)
bool CompleteTagDeclWithOrigin(clang::TagDecl *decl, clang::TagDecl *origin)
bool CanImport(const CompilerType &type)
Returns true iff the given type was copied from another TypeSystemClang and the original type in this...
ASTContextMetadataSP GetContextMetadata(clang::ASTContext *dst_ctx)
bool importRecordLayoutFromOrigin(const clang::RecordDecl *record, uint64_t &size, uint64_t &alignment, llvm::DenseMap< const clang::FieldDecl *, uint64_t > &field_offsets, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &base_offsets, llvm::DenseMap< const clang::CXXRecordDecl *, clang::CharUnits > &vbase_offsets)
If record has a valid origin, this function copies that origin's layout into this ClangASTImporter in...
void ForgetSource(clang::ASTContext *dst_ctx, clang::ASTContext *src_ctx)
bool CompleteObjCInterfaceDecl(clang::ObjCInterfaceDecl *interface_decl)
void RegisterNamespaceMap(const clang::NamespaceDecl *decl, NamespaceMapSP namespace_map)
ASTContextMetadataSP MaybeGetContextMetadata(clang::ASTContext *dst_ctx)
std::shared_ptr< NamespaceMap > NamespaceMapSP
NamespaceMapSP GetNamespaceMap(const clang::NamespaceDecl *decl)
std::shared_ptr< ASTImporterDelegate > ImporterDelegateSP
llvm::DenseMap< const clang::NamespaceDecl *, NamespaceMapSP > NamespaceMetaMap
bool CompleteType(const CompilerType &compiler_type)
void SetRecordLayout(clang::RecordDecl *decl, const LayoutInfo &layout)
Sets the layout for the given RecordDecl.
bool RequireCompleteType(clang::QualType type)
CompilerType DeportType(TypeSystemClang &dst, const CompilerType &src_type)
Copies the given type and the respective declarations to the destination type system.
RecordDeclToLayoutMap m_record_decl_to_layout_map
bool Import(const CompilerType &type)
If the given type was copied from another TypeSystemClang then copy over all missing information (e....
ImporterDelegateSP GetDelegate(clang::ASTContext *dst_ctx, clang::ASTContext *src_ctx)
void SetDeclOrigin(const clang::Decl *decl, clang::Decl *original_decl)
Updates the internal origin-tracking information so that the given 'original' decl is from now on use...
std::shared_ptr< ASTContextMetadata > ASTContextMetadataSP
bool CompleteAndFetchChildren(clang::QualType type)
void SetLanguageType(lldb::LanguageType lang_type)
OptionalClangModuleID GetIDForModule(clang::Module *module)
Generic representation of a type in a programming language.
TypeSystemSPWrapper GetTypeSystem() const
Accessors.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
ConstString GetTypeName(bool BaseOnly=false) const
A uniqued constant string class.
Definition ConstString.h:40
DeclFromUser< D > GetOrigin(ClangASTImporter &importer)
DeclFromParser< D > Import(clang::ASTContext *dest_ctx, ClangASTImporter &importer)
static bool LanguageIsRust(lldb::LanguageType language)
Definition Language.cpp:409
A TypeSystem implementation based on Clang.
static void SetOwningModule(clang::Decl *decl, OptionalClangModuleID owning_module)
Set the owning module for decl.
OptionalClangModuleID GetOrCreateClangModule(llvm::StringRef name, OptionalClangModuleID parent, bool is_framework=false, bool is_explicit=false)
Synthesize a clang::Module and return its ID or a default-constructed ID.
static TypeSystemClang * GetASTContext(clang::ASTContext *ast_ctx)
std::optional< ClangASTMetadata > GetMetadata(const clang::Decl *object)
static bool CompleteTagDeclarationDefinition(const CompilerType &type)
static bool SetHasExternalStorage(lldb::opaque_compiler_type_t type, bool has_extern)
bool GetCompleteDecl(clang::Decl *decl)
clang::ASTContext & getASTContext() const
Returns the clang::ASTContext instance managed by this TypeSystemClang.
#define LLDB_INVALID_UID
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
TD< D2 > DynCast(TD< D1 > source)
void * opaque_compiler_type_t
Definition lldb-types.h:91
LanguageType
Programming language type.
uint64_t user_id_t
Definition lldb-types.h:83
clang::DeclContext * decl_context
clang::DeclContext * lexical_decl_context
clang::Decl * GetOriginalDecl(clang::Decl *To) override
llvm::Expected< clang::Decl * > ImportImpl(clang::Decl *From) override
void MarkDeclImported(clang::Decl *from, clang::Decl *to)
llvm::SmallPtrSet< clang::Decl *, 16 > m_decls_to_ignore
Decls we should ignore when mapping decls back to their original ASTContext.
void Imported(clang::Decl *from, clang::Decl *to) override
NewDeclListener * m_new_decl_listener
The currently attached listener.
void ImportDefinitionTo(clang::Decl *to, clang::Decl *from)
Listener interface used by the ASTImporterDelegate to inform other code about decls that have been im...
static clang::QualType GetQualType(const CompilerType &ct)
Definition ClangUtil.cpp:36
static clang::QualType GetCanonicalQualType(const CompilerType &ct)
Definition ClangUtil.cpp:44
static bool IsClangType(const CompilerType &ct)
Definition ClangUtil.cpp:17
static CompilerType RemoveFastQualifiers(const CompilerType &ct)
Definition ClangUtil.cpp:51