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