xref: /llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h (revision 081723b9db84e78d7dd240b46af2aeb3b51b00be)
1 //===-- TypeSystemClang.h ---------------------------------------*- C++ -*-===//
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 #ifndef LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H
10 #define LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H
11 
12 #include <cstdint>
13 
14 #include <functional>
15 #include <initializer_list>
16 #include <memory>
17 #include <optional>
18 #include <set>
19 #include <string>
20 #include <utility>
21 #include <vector>
22 
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/ASTFwd.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/TemplateBase.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/APSInt.h"
30 #include "llvm/ADT/SmallVector.h"
31 
32 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
33 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
34 #include "lldb/Expression/ExpressionVariable.h"
35 #include "lldb/Symbol/CompilerType.h"
36 #include "lldb/Symbol/TypeSystem.h"
37 #include "lldb/Target/Target.h"
38 #include "lldb/Utility/ConstString.h"
39 #include "lldb/Utility/Flags.h"
40 #include "lldb/Utility/Log.h"
41 #include "lldb/lldb-enumerations.h"
42 
43 class DWARFASTParserClang;
44 class PDBASTParser;
45 
46 namespace clang {
47 class FileManager;
48 class HeaderSearch;
49 class ModuleMap;
50 } // namespace clang
51 
52 namespace lldb_private {
53 
54 class ClangASTSource;
55 class Declaration;
56 
57 /// A Clang module ID.
58 class OptionalClangModuleID {
59   unsigned m_id = 0;
60 
61 public:
62   OptionalClangModuleID() = default;
63   explicit OptionalClangModuleID(unsigned id) : m_id(id) {}
64   bool HasValue() const { return m_id != 0; }
65   unsigned GetValue() const { return m_id; }
66 };
67 
68 /// The implementation of lldb::Type's m_payload field for TypeSystemClang.
69 class TypePayloadClang {
70   /// The payload is used for typedefs and ptrauth types.
71   /// For typedefs, the Layout is as follows:
72   /// \verbatim
73   /// bit 0..30 ... Owning Module ID.
74   /// bit 31 ...... IsCompleteObjCClass.
75   /// \endverbatim
76   /// For ptrauth types, we store the PointerAuthQualifier as an opaque value.
77   Type::Payload m_payload = 0;
78 
79 public:
80   TypePayloadClang() = default;
81   explicit TypePayloadClang(OptionalClangModuleID owning_module,
82                             bool is_complete_objc_class = false);
83   explicit TypePayloadClang(uint32_t opaque_payload) : m_payload(opaque_payload) {}
84   operator Type::Payload() { return m_payload; }
85 
86   static constexpr unsigned ObjCClassBit = 1 << 31;
87   bool IsCompleteObjCClass() { return Flags(m_payload).Test(ObjCClassBit); }
88   void SetIsCompleteObjCClass(bool is_complete_objc_class) {
89     m_payload = is_complete_objc_class ? Flags(m_payload).Set(ObjCClassBit)
90                                        : Flags(m_payload).Clear(ObjCClassBit);
91   }
92   OptionalClangModuleID GetOwningModule() {
93     return OptionalClangModuleID(Flags(m_payload).Clear(ObjCClassBit));
94   }
95   void SetOwningModule(OptionalClangModuleID id);
96   /// \}
97 };
98 
99 /// A TypeSystem implementation based on Clang.
100 ///
101 /// This class uses a single clang::ASTContext as the backend for storing
102 /// its types and declarations. Every clang::ASTContext should also just have
103 /// a single associated TypeSystemClang instance that manages it.
104 ///
105 /// The clang::ASTContext instance can either be created by TypeSystemClang
106 /// itself or it can adopt an existing clang::ASTContext (for example, when
107 /// it is necessary to provide a TypeSystem interface for an existing
108 /// clang::ASTContext that was created by clang::CompilerInstance).
109 class TypeSystemClang : public TypeSystem {
110   // LLVM RTTI support
111   static char ID;
112 
113 public:
114   typedef void (*CompleteTagDeclCallback)(void *baton, clang::TagDecl *);
115   typedef void (*CompleteObjCInterfaceDeclCallback)(void *baton,
116                                                     clang::ObjCInterfaceDecl *);
117 
118   // llvm casting support
119   bool isA(const void *ClassID) const override { return ClassID == &ID; }
120   static bool classof(const TypeSystem *ts) { return ts->isA(&ID); }
121 
122   /// Constructs a TypeSystemClang with an ASTContext using the given triple.
123   ///
124   /// \param name The name for the TypeSystemClang (for logging purposes)
125   /// \param triple The llvm::Triple used for the ASTContext. The triple defines
126   ///               certain characteristics of the ASTContext and its types
127   ///               (e.g., whether certain primitive types exist or what their
128   ///               signedness is).
129   explicit TypeSystemClang(llvm::StringRef name, llvm::Triple triple);
130 
131   /// Constructs a TypeSystemClang that uses an existing ASTContext internally.
132   /// Useful when having an existing ASTContext created by Clang.
133   ///
134   /// \param name The name for the TypeSystemClang (for logging purposes)
135   /// \param existing_ctxt An existing ASTContext.
136   explicit TypeSystemClang(llvm::StringRef name,
137                            clang::ASTContext &existing_ctxt);
138 
139   ~TypeSystemClang() override;
140 
141   void Finalize() override;
142 
143   // PluginInterface functions
144   llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); }
145 
146   static llvm::StringRef GetPluginNameStatic() { return "clang"; }
147 
148   static lldb::TypeSystemSP CreateInstance(lldb::LanguageType language,
149                                            Module *module, Target *target);
150 
151   static LanguageSet GetSupportedLanguagesForTypes();
152   static LanguageSet GetSupportedLanguagesForExpressions();
153 
154   static void Initialize();
155 
156   static void Terminate();
157 
158   static TypeSystemClang *GetASTContext(clang::ASTContext *ast_ctx);
159 
160   /// Returns the display name of this TypeSystemClang that indicates what
161   /// purpose it serves in LLDB. Used for example in logs.
162   llvm::StringRef getDisplayName() const { return m_display_name; }
163 
164   /// Returns the clang::ASTContext instance managed by this TypeSystemClang.
165   clang::ASTContext &getASTContext() const;
166 
167   clang::MangleContext *getMangleContext();
168 
169   std::shared_ptr<clang::TargetOptions> &getTargetOptions();
170 
171   clang::TargetInfo *getTargetInfo();
172 
173   void setSema(clang::Sema *s);
174   clang::Sema *getSema() { return m_sema; }
175 
176   const char *GetTargetTriple();
177 
178   void SetExternalSource(
179       llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> &ast_source_up);
180 
181   bool GetCompleteDecl(clang::Decl *decl) {
182     return TypeSystemClang::GetCompleteDecl(&getASTContext(), decl);
183   }
184 
185   static void DumpDeclHiearchy(clang::Decl *decl);
186 
187   static void DumpDeclContextHiearchy(clang::DeclContext *decl_ctx);
188 
189   static bool GetCompleteDecl(clang::ASTContext *ast, clang::Decl *decl);
190 
191   void SetMetadataAsUserID(const clang::Decl *decl, lldb::user_id_t user_id);
192   void SetMetadataAsUserID(const clang::Type *type, lldb::user_id_t user_id);
193 
194   void SetMetadata(const clang::Decl *object, ClangASTMetadata meta_data);
195 
196   void SetMetadata(const clang::Type *object, ClangASTMetadata meta_data);
197   std::optional<ClangASTMetadata> GetMetadata(const clang::Decl *object);
198   std::optional<ClangASTMetadata> GetMetadata(const clang::Type *object);
199 
200   void SetCXXRecordDeclAccess(const clang::CXXRecordDecl *object,
201                               clang::AccessSpecifier access);
202   clang::AccessSpecifier
203   GetCXXRecordDeclAccess(const clang::CXXRecordDecl *object);
204 
205   // Basic Types
206   CompilerType GetBuiltinTypeForEncodingAndBitSize(lldb::Encoding encoding,
207                                                    size_t bit_size) override;
208 
209   CompilerType GetBasicType(lldb::BasicType type);
210 
211   static lldb::BasicType GetBasicTypeEnumeration(llvm::StringRef name);
212 
213   CompilerType
214   GetBuiltinTypeForDWARFEncodingAndBitSize(llvm::StringRef type_name,
215                                            uint32_t dw_ate, uint32_t bit_size);
216 
217   CompilerType GetCStringType(bool is_const);
218 
219   static clang::DeclContext *GetDeclContextForType(clang::QualType type);
220 
221   static clang::DeclContext *GetDeclContextForType(const CompilerType &type);
222 
223   CompilerDeclContext
224   GetCompilerDeclContextForType(const CompilerType &type) override;
225 
226   uint32_t GetPointerByteSize() override;
227 
228   clang::TranslationUnitDecl *GetTranslationUnitDecl() {
229     return getASTContext().getTranslationUnitDecl();
230   }
231 
232   static bool AreTypesSame(CompilerType type1, CompilerType type2,
233                            bool ignore_qualifiers = false);
234 
235   /// Creates a CompilerType from the given QualType with the current
236   /// TypeSystemClang instance as the CompilerType's typesystem.
237   /// \param qt The QualType for a type that belongs to the ASTContext of this
238   ///           TypeSystemClang.
239   /// \return The CompilerType representing the given QualType. If the
240   ///         QualType's type pointer is a nullptr then the function returns an
241   ///         invalid CompilerType.
242   CompilerType GetType(clang::QualType qt) {
243     if (qt.getTypePtrOrNull() == nullptr)
244       return CompilerType();
245     // Check that the type actually belongs to this TypeSystemClang.
246     assert(qt->getAsTagDecl() == nullptr ||
247            &qt->getAsTagDecl()->getASTContext() == &getASTContext());
248     return CompilerType(weak_from_this(), qt.getAsOpaquePtr());
249   }
250 
251   CompilerType GetTypeForDecl(clang::NamedDecl *decl);
252 
253   CompilerType GetTypeForDecl(clang::TagDecl *decl);
254 
255   CompilerType GetTypeForDecl(clang::ObjCInterfaceDecl *objc_decl);
256 
257   CompilerType GetTypeForDecl(clang::ValueDecl *value_decl);
258 
259   template <typename RecordDeclType>
260   CompilerType
261   GetTypeForIdentifier(llvm::StringRef type_name,
262                        clang::DeclContext *decl_context = nullptr) {
263     CompilerType compiler_type;
264     if (type_name.empty())
265       return compiler_type;
266 
267     clang::ASTContext &ast = getASTContext();
268     if (!decl_context)
269       decl_context = ast.getTranslationUnitDecl();
270 
271     clang::IdentifierInfo &myIdent = ast.Idents.get(type_name);
272     clang::DeclarationName myName =
273         ast.DeclarationNames.getIdentifier(&myIdent);
274     clang::DeclContext::lookup_result result = decl_context->lookup(myName);
275     if (result.empty())
276       return compiler_type;
277 
278     clang::NamedDecl *named_decl = *result.begin();
279     if (const RecordDeclType *record_decl =
280             llvm::dyn_cast<RecordDeclType>(named_decl))
281       compiler_type = CompilerType(
282           weak_from_this(),
283           clang::QualType(record_decl->getTypeForDecl(), 0).getAsOpaquePtr());
284 
285     return compiler_type;
286   }
287 
288   CompilerType CreateStructForIdentifier(
289       llvm::StringRef type_name,
290       const std::initializer_list<std::pair<const char *, CompilerType>>
291           &type_fields,
292       bool packed = false);
293 
294   CompilerType GetOrCreateStructForIdentifier(
295       llvm::StringRef type_name,
296       const std::initializer_list<std::pair<const char *, CompilerType>>
297           &type_fields,
298       bool packed = false);
299 
300   static bool IsOperator(llvm::StringRef name,
301                          clang::OverloadedOperatorKind &op_kind);
302 
303   // Structure, Unions, Classes
304 
305   static clang::AccessSpecifier
306   ConvertAccessTypeToAccessSpecifier(lldb::AccessType access);
307 
308   static clang::AccessSpecifier
309   UnifyAccessSpecifiers(clang::AccessSpecifier lhs, clang::AccessSpecifier rhs);
310 
311   uint32_t GetNumBaseClasses(const clang::CXXRecordDecl *cxx_record_decl,
312                              bool omit_empty_base_classes);
313 
314   uint32_t GetIndexForRecordChild(const clang::RecordDecl *record_decl,
315                                   clang::NamedDecl *canonical_decl,
316                                   bool omit_empty_base_classes);
317 
318   uint32_t GetIndexForRecordBase(const clang::RecordDecl *record_decl,
319                                  const clang::CXXBaseSpecifier *base_spec,
320                                  bool omit_empty_base_classes);
321 
322   /// Synthesize a clang::Module and return its ID or a default-constructed ID.
323   OptionalClangModuleID GetOrCreateClangModule(llvm::StringRef name,
324                                                OptionalClangModuleID parent,
325                                                bool is_framework = false,
326                                                bool is_explicit = false);
327 
328   CompilerType
329   CreateRecordType(clang::DeclContext *decl_ctx,
330                    OptionalClangModuleID owning_module,
331                    lldb::AccessType access_type, llvm::StringRef name, int kind,
332                    lldb::LanguageType language,
333                    std::optional<ClangASTMetadata> metadata = std::nullopt,
334                    bool exports_symbols = false);
335 
336   class TemplateParameterInfos {
337   public:
338     TemplateParameterInfos() = default;
339     TemplateParameterInfos(llvm::ArrayRef<const char *> names_in,
340                            llvm::ArrayRef<clang::TemplateArgument> args_in)
341         : names(names_in), args(args_in) {
342       assert(names.size() == args_in.size());
343     }
344 
345     TemplateParameterInfos(TemplateParameterInfos const &) = delete;
346     TemplateParameterInfos(TemplateParameterInfos &&) = delete;
347 
348     TemplateParameterInfos &operator=(TemplateParameterInfos const &) = delete;
349     TemplateParameterInfos &operator=(TemplateParameterInfos &&) = delete;
350 
351     ~TemplateParameterInfos() = default;
352 
353     bool IsValid() const {
354       // Having a pack name but no packed args doesn't make sense, so mark
355       // these template parameters as invalid.
356       if (pack_name && !packed_args)
357         return false;
358       return args.size() == names.size() &&
359              (!packed_args || !packed_args->packed_args);
360     }
361 
362     bool IsEmpty() const { return args.empty(); }
363     size_t Size() const { return args.size(); }
364 
365     llvm::ArrayRef<clang::TemplateArgument> GetArgs() const { return args; }
366     llvm::ArrayRef<const char *> GetNames() const { return names; }
367 
368     clang::TemplateArgument const &Front() const {
369       assert(!args.empty());
370       return args.front();
371     }
372 
373     void InsertArg(char const *name, clang::TemplateArgument arg) {
374       args.emplace_back(std::move(arg));
375       names.push_back(name);
376     }
377 
378     // Parameter pack related
379 
380     bool hasParameterPack() const { return static_cast<bool>(packed_args); }
381 
382     TemplateParameterInfos const &GetParameterPack() const {
383       assert(packed_args != nullptr);
384       return *packed_args;
385     }
386 
387     TemplateParameterInfos &GetParameterPack() {
388       assert(packed_args != nullptr);
389       return *packed_args;
390     }
391 
392     llvm::ArrayRef<clang::TemplateArgument> GetParameterPackArgs() const {
393       assert(packed_args != nullptr);
394       return packed_args->GetArgs();
395     }
396 
397     bool HasPackName() const { return pack_name && pack_name[0]; }
398 
399     llvm::StringRef GetPackName() const {
400       assert(HasPackName());
401       return pack_name;
402     }
403 
404     void SetPackName(char const *name) { pack_name = name; }
405 
406     void SetParameterPack(std::unique_ptr<TemplateParameterInfos> args) {
407       packed_args = std::move(args);
408     }
409 
410   private:
411     /// Element 'names[i]' holds the template argument name
412     /// of 'args[i]'
413     llvm::SmallVector<const char *, 2> names;
414     llvm::SmallVector<clang::TemplateArgument, 2> args;
415 
416     const char * pack_name = nullptr;
417     std::unique_ptr<TemplateParameterInfos> packed_args;
418   };
419 
420   clang::FunctionTemplateDecl *CreateFunctionTemplateDecl(
421       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
422       clang::FunctionDecl *func_decl, const TemplateParameterInfos &infos);
423 
424   void CreateFunctionTemplateSpecializationInfo(
425       clang::FunctionDecl *func_decl, clang::FunctionTemplateDecl *Template,
426       const TemplateParameterInfos &infos);
427 
428   clang::ClassTemplateDecl *CreateClassTemplateDecl(
429       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
430       lldb::AccessType access_type, llvm::StringRef class_name, int kind,
431       const TemplateParameterInfos &infos);
432 
433   clang::TemplateTemplateParmDecl *
434   CreateTemplateTemplateParmDecl(const char *template_name);
435 
436   clang::ClassTemplateSpecializationDecl *CreateClassTemplateSpecializationDecl(
437       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
438       clang::ClassTemplateDecl *class_template_decl, int kind,
439       const TemplateParameterInfos &infos);
440 
441   CompilerType
442   CreateClassTemplateSpecializationType(clang::ClassTemplateSpecializationDecl *
443                                             class_template_specialization_decl);
444 
445   static clang::DeclContext *
446   GetAsDeclContext(clang::FunctionDecl *function_decl);
447 
448   static bool CheckOverloadedOperatorKindParameterCount(
449       bool is_method, clang::OverloadedOperatorKind op_kind,
450       uint32_t num_params);
451 
452   bool FieldIsBitfield(clang::FieldDecl *field, uint32_t &bitfield_bit_size);
453 
454   bool RecordHasFields(const clang::RecordDecl *record_decl);
455 
456   bool BaseSpecifierIsEmpty(const clang::CXXBaseSpecifier *b);
457 
458   CompilerType
459   CreateObjCClass(llvm::StringRef name, clang::DeclContext *decl_ctx,
460                   OptionalClangModuleID owning_module, bool isInternal,
461                   std::optional<ClangASTMetadata> metadata = std::nullopt);
462 
463   // Returns a mask containing bits from the TypeSystemClang::eTypeXXX
464   // enumerations
465 
466   // Namespace Declarations
467 
468   clang::NamespaceDecl *
469   GetUniqueNamespaceDeclaration(const char *name, clang::DeclContext *decl_ctx,
470                                 OptionalClangModuleID owning_module,
471                                 bool is_inline = false);
472 
473   // Function Types
474 
475   clang::FunctionDecl *CreateFunctionDeclaration(
476       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
477       llvm::StringRef name, const CompilerType &function_Type,
478       clang::StorageClass storage, bool is_inline);
479 
480   CompilerType
481   CreateFunctionType(const CompilerType &result_type, const CompilerType *args,
482                      unsigned num_args, bool is_variadic, unsigned type_quals,
483                      clang::CallingConv cc = clang::CC_C,
484                      clang::RefQualifierKind ref_qual = clang::RQ_None);
485 
486   clang::ParmVarDecl *
487   CreateParameterDeclaration(clang::DeclContext *decl_ctx,
488                              OptionalClangModuleID owning_module,
489                              const char *name, const CompilerType &param_type,
490                              int storage, bool add_decl = false);
491 
492   CompilerType CreateBlockPointerType(const CompilerType &function_type);
493 
494   // Array Types
495 
496   CompilerType CreateArrayType(const CompilerType &element_type,
497                                std::optional<size_t> element_count,
498                                bool is_vector);
499 
500   // Enumeration Types
501   CompilerType CreateEnumerationType(llvm::StringRef name,
502                                      clang::DeclContext *decl_ctx,
503                                      OptionalClangModuleID owning_module,
504                                      const Declaration &decl,
505                                      const CompilerType &integer_qual_type,
506                                      bool is_scoped);
507 
508   // Integer type functions
509 
510   CompilerType GetIntTypeFromBitSize(size_t bit_size, bool is_signed);
511 
512   CompilerType GetPointerSizedIntType(bool is_signed);
513 
514   // Floating point functions
515 
516   static CompilerType GetFloatTypeFromBitSize(clang::ASTContext *ast,
517                                               size_t bit_size);
518 
519   // TypeSystem methods
520   plugin::dwarf::DWARFASTParser *GetDWARFParser() override;
521   PDBASTParser *GetPDBParser() override;
522   npdb::PdbAstBuilder *GetNativePDBParser() override;
523 
524   // TypeSystemClang callbacks for external source lookups.
525   void CompleteTagDecl(clang::TagDecl *);
526 
527   void CompleteObjCInterfaceDecl(clang::ObjCInterfaceDecl *);
528 
529   bool LayoutRecordType(
530       const clang::RecordDecl *record_decl, uint64_t &size, uint64_t &alignment,
531       llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
532       llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
533           &base_offsets,
534       llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
535           &vbase_offsets);
536 
537   /// Creates a CompilerDecl from the given Decl with the current
538   /// TypeSystemClang instance as its typesystem.
539   /// The Decl has to come from the ASTContext of this
540   /// TypeSystemClang.
541   CompilerDecl GetCompilerDecl(clang::Decl *decl) {
542     assert(&decl->getASTContext() == &getASTContext() &&
543            "CreateCompilerDecl for Decl from wrong ASTContext?");
544     return CompilerDecl(this, decl);
545   }
546 
547   // CompilerDecl override functions
548   ConstString DeclGetName(void *opaque_decl) override;
549 
550   ConstString DeclGetMangledName(void *opaque_decl) override;
551 
552   CompilerDeclContext DeclGetDeclContext(void *opaque_decl) override;
553 
554   CompilerType DeclGetFunctionReturnType(void *opaque_decl) override;
555 
556   size_t DeclGetFunctionNumArguments(void *opaque_decl) override;
557 
558   CompilerType DeclGetFunctionArgumentType(void *opaque_decl,
559                                            size_t arg_idx) override;
560 
561   std::vector<lldb_private::CompilerContext>
562   DeclGetCompilerContext(void *opaque_decl) override;
563 
564   Scalar DeclGetConstantValue(void *opaque_decl) override;
565 
566   CompilerType GetTypeForDecl(void *opaque_decl) override;
567 
568   // CompilerDeclContext override functions
569 
570   /// Creates a CompilerDeclContext from the given DeclContext
571   /// with the current TypeSystemClang instance as its typesystem.
572   /// The DeclContext has to come from the ASTContext of this
573   /// TypeSystemClang.
574   CompilerDeclContext CreateDeclContext(clang::DeclContext *ctx);
575 
576   /// Set the owning module for \p decl.
577   static void SetOwningModule(clang::Decl *decl,
578                               OptionalClangModuleID owning_module);
579 
580   std::vector<CompilerDecl>
581   DeclContextFindDeclByName(void *opaque_decl_ctx, ConstString name,
582                             const bool ignore_using_decls) override;
583 
584   ConstString DeclContextGetName(void *opaque_decl_ctx) override;
585 
586   ConstString DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) override;
587 
588   bool DeclContextIsClassMethod(void *opaque_decl_ctx) override;
589 
590   bool DeclContextIsContainedInLookup(void *opaque_decl_ctx,
591                                       void *other_opaque_decl_ctx) override;
592 
593   lldb::LanguageType DeclContextGetLanguage(void *opaque_decl_ctx) override;
594 
595   std::vector<lldb_private::CompilerContext>
596   DeclContextGetCompilerContext(void *opaque_decl_ctx) override;
597 
598   // Clang specific clang::DeclContext functions
599 
600   static clang::DeclContext *
601   DeclContextGetAsDeclContext(const CompilerDeclContext &dc);
602 
603   static clang::ObjCMethodDecl *
604   DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc);
605 
606   static clang::CXXMethodDecl *
607   DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc);
608 
609   static clang::FunctionDecl *
610   DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc);
611 
612   static clang::NamespaceDecl *
613   DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc);
614 
615   static std::optional<ClangASTMetadata>
616   DeclContextGetMetaData(const CompilerDeclContext &dc,
617                          const clang::Decl *object);
618 
619   static clang::ASTContext *
620   DeclContextGetTypeSystemClang(const CompilerDeclContext &dc);
621 
622   // Tests
623 
624 #ifndef NDEBUG
625   bool Verify(lldb::opaque_compiler_type_t type) override;
626 #endif
627 
628   bool IsArrayType(lldb::opaque_compiler_type_t type,
629                    CompilerType *element_type, uint64_t *size,
630                    bool *is_incomplete) override;
631 
632   bool IsVectorType(lldb::opaque_compiler_type_t type,
633                     CompilerType *element_type, uint64_t *size) override;
634 
635   bool IsAggregateType(lldb::opaque_compiler_type_t type) override;
636 
637   bool IsAnonymousType(lldb::opaque_compiler_type_t type) override;
638 
639   bool IsBeingDefined(lldb::opaque_compiler_type_t type) override;
640 
641   bool IsCharType(lldb::opaque_compiler_type_t type) override;
642 
643   bool IsCompleteType(lldb::opaque_compiler_type_t type) override;
644 
645   bool IsConst(lldb::opaque_compiler_type_t type) override;
646 
647   bool IsCStringType(lldb::opaque_compiler_type_t type, uint32_t &length);
648 
649   static bool IsCXXClassType(const CompilerType &type);
650 
651   bool IsDefined(lldb::opaque_compiler_type_t type) override;
652 
653   bool IsFloatingPointType(lldb::opaque_compiler_type_t type, uint32_t &count,
654                            bool &is_complex) override;
655 
656   unsigned GetPtrAuthKey(lldb::opaque_compiler_type_t type) override;
657   unsigned GetPtrAuthDiscriminator(lldb::opaque_compiler_type_t type) override;
658   bool GetPtrAuthAddressDiversity(lldb::opaque_compiler_type_t type) override;
659 
660   bool IsFunctionType(lldb::opaque_compiler_type_t type) override;
661 
662   uint32_t IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
663                                   CompilerType *base_type_ptr) override;
664 
665   size_t
666   GetNumberOfFunctionArguments(lldb::opaque_compiler_type_t type) override;
667 
668   CompilerType GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
669                                           const size_t index) override;
670 
671   bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) override;
672 
673   bool IsMemberFunctionPointerType(lldb::opaque_compiler_type_t type) override;
674 
675   bool IsBlockPointerType(lldb::opaque_compiler_type_t type,
676                           CompilerType *function_pointer_type_ptr) override;
677 
678   bool IsIntegerType(lldb::opaque_compiler_type_t type,
679                      bool &is_signed) override;
680 
681   bool IsEnumerationType(lldb::opaque_compiler_type_t type,
682                          bool &is_signed) override;
683 
684   bool IsScopedEnumerationType(lldb::opaque_compiler_type_t type) override;
685 
686   static bool IsObjCClassType(const CompilerType &type);
687 
688   static bool IsObjCClassTypeAndHasIVars(const CompilerType &type,
689                                          bool check_superclass);
690 
691   static bool IsObjCObjectOrInterfaceType(const CompilerType &type);
692 
693   static bool IsObjCObjectPointerType(const CompilerType &type,
694                                       CompilerType *target_type = nullptr);
695 
696   bool IsPolymorphicClass(lldb::opaque_compiler_type_t type) override;
697 
698   static bool IsClassType(lldb::opaque_compiler_type_t type);
699 
700   static bool IsEnumType(lldb::opaque_compiler_type_t type);
701 
702   bool IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
703                              CompilerType *target_type, // Can pass nullptr
704                              bool check_cplusplus, bool check_objc) override;
705 
706   bool IsRuntimeGeneratedType(lldb::opaque_compiler_type_t type) override;
707 
708   bool IsPointerType(lldb::opaque_compiler_type_t type,
709                      CompilerType *pointee_type) override;
710 
711   bool IsPointerOrReferenceType(lldb::opaque_compiler_type_t type,
712                                 CompilerType *pointee_type) override;
713 
714   bool IsReferenceType(lldb::opaque_compiler_type_t type,
715                        CompilerType *pointee_type, bool *is_rvalue) override;
716 
717   bool IsScalarType(lldb::opaque_compiler_type_t type) override;
718 
719   bool IsTypedefType(lldb::opaque_compiler_type_t type) override;
720 
721   bool IsVoidType(lldb::opaque_compiler_type_t type) override;
722 
723   bool CanPassInRegisters(const CompilerType &type) override;
724 
725   bool SupportsLanguage(lldb::LanguageType language) override;
726 
727   static std::optional<std::string> GetCXXClassName(const CompilerType &type);
728 
729   // Type Completion
730 
731   bool GetCompleteType(lldb::opaque_compiler_type_t type) override;
732 
733   bool IsForcefullyCompleted(lldb::opaque_compiler_type_t type) override;
734 
735   // Accessors
736 
737   ConstString GetTypeName(lldb::opaque_compiler_type_t type,
738                           bool base_only) override;
739 
740   ConstString GetDisplayTypeName(lldb::opaque_compiler_type_t type) override;
741 
742   uint32_t GetTypeInfo(lldb::opaque_compiler_type_t type,
743                        CompilerType *pointee_or_element_compiler_type) override;
744 
745   lldb::LanguageType
746   GetMinimumLanguage(lldb::opaque_compiler_type_t type) override;
747 
748   lldb::TypeClass GetTypeClass(lldb::opaque_compiler_type_t type) override;
749 
750   unsigned GetTypeQualifiers(lldb::opaque_compiler_type_t type) override;
751 
752   // Creating related types
753 
754   CompilerType GetArrayElementType(lldb::opaque_compiler_type_t type,
755                                    ExecutionContextScope *exe_scope) override;
756 
757   CompilerType GetArrayType(lldb::opaque_compiler_type_t type,
758                             uint64_t size) override;
759 
760   CompilerType GetCanonicalType(lldb::opaque_compiler_type_t type) override;
761 
762   CompilerType
763   GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) override;
764 
765   CompilerType
766   GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) override;
767 
768   // Returns -1 if this isn't a function of if the function doesn't have a
769   // prototype Returns a value >= 0 if there is a prototype.
770   int GetFunctionArgumentCount(lldb::opaque_compiler_type_t type) override;
771 
772   CompilerType GetFunctionArgumentTypeAtIndex(lldb::opaque_compiler_type_t type,
773                                               size_t idx) override;
774 
775   CompilerType
776   GetFunctionReturnType(lldb::opaque_compiler_type_t type) override;
777 
778   size_t GetNumMemberFunctions(lldb::opaque_compiler_type_t type) override;
779 
780   TypeMemberFunctionImpl
781   GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
782                            size_t idx) override;
783 
784   CompilerType GetNonReferenceType(lldb::opaque_compiler_type_t type) override;
785 
786   CompilerType GetPointeeType(lldb::opaque_compiler_type_t type) override;
787 
788   CompilerType GetPointerType(lldb::opaque_compiler_type_t type) override;
789 
790   CompilerType
791   GetLValueReferenceType(lldb::opaque_compiler_type_t type) override;
792 
793   CompilerType
794   GetRValueReferenceType(lldb::opaque_compiler_type_t type) override;
795 
796   CompilerType GetAtomicType(lldb::opaque_compiler_type_t type) override;
797 
798   CompilerType AddConstModifier(lldb::opaque_compiler_type_t type) override;
799 
800   CompilerType AddPtrAuthModifier(lldb::opaque_compiler_type_t type,
801                                   uint32_t payload) override;
802 
803   CompilerType AddVolatileModifier(lldb::opaque_compiler_type_t type) override;
804 
805   CompilerType AddRestrictModifier(lldb::opaque_compiler_type_t type) override;
806 
807   /// Using the current type, create a new typedef to that type using
808   /// "typedef_name" as the name and "decl_ctx" as the decl context.
809   /// \param opaque_payload is an opaque TypePayloadClang.
810   CompilerType CreateTypedef(lldb::opaque_compiler_type_t type,
811                              const char *name,
812                              const CompilerDeclContext &decl_ctx,
813                              uint32_t opaque_payload) override;
814 
815   // If the current object represents a typedef type, get the underlying type
816   CompilerType GetTypedefedType(lldb::opaque_compiler_type_t type) override;
817 
818   // Create related types using the current type's AST
819   CompilerType GetBasicTypeFromAST(lldb::BasicType basic_type) override;
820 
821   // Create a generic function prototype that can be used in ValuObject types
822   // to correctly display a function pointer with the right value and summary.
823   CompilerType CreateGenericFunctionPrototype() override;
824 
825   // Exploring the type
826 
827   const llvm::fltSemantics &GetFloatTypeSemantics(size_t byte_size) override;
828 
829   std::optional<uint64_t> GetByteSize(lldb::opaque_compiler_type_t type,
830                                       ExecutionContextScope *exe_scope) {
831     if (std::optional<uint64_t> bit_size = GetBitSize(type, exe_scope))
832       return (*bit_size + 7) / 8;
833     return std::nullopt;
834   }
835 
836   std::optional<uint64_t> GetBitSize(lldb::opaque_compiler_type_t type,
837                                      ExecutionContextScope *exe_scope) override;
838 
839   lldb::Encoding GetEncoding(lldb::opaque_compiler_type_t type,
840                              uint64_t &count) override;
841 
842   lldb::Format GetFormat(lldb::opaque_compiler_type_t type) override;
843 
844   std::optional<size_t>
845   GetTypeBitAlign(lldb::opaque_compiler_type_t type,
846                   ExecutionContextScope *exe_scope) override;
847 
848   llvm::Expected<uint32_t>
849   GetNumChildren(lldb::opaque_compiler_type_t type,
850                  bool omit_empty_base_classes,
851                  const ExecutionContext *exe_ctx) override;
852 
853   CompilerType GetBuiltinTypeByName(ConstString name) override;
854 
855   lldb::BasicType
856   GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) override;
857 
858   void ForEachEnumerator(
859       lldb::opaque_compiler_type_t type,
860       std::function<bool(const CompilerType &integer_type,
861                          ConstString name,
862                          const llvm::APSInt &value)> const &callback) override;
863 
864   uint32_t GetNumFields(lldb::opaque_compiler_type_t type) override;
865 
866   CompilerType GetFieldAtIndex(lldb::opaque_compiler_type_t type, size_t idx,
867                                std::string &name, uint64_t *bit_offset_ptr,
868                                uint32_t *bitfield_bit_size_ptr,
869                                bool *is_bitfield_ptr) override;
870 
871   uint32_t GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) override;
872 
873   uint32_t GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) override;
874 
875   CompilerType GetDirectBaseClassAtIndex(lldb::opaque_compiler_type_t type,
876                                          size_t idx,
877                                          uint32_t *bit_offset_ptr) override;
878 
879   CompilerType GetVirtualBaseClassAtIndex(lldb::opaque_compiler_type_t type,
880                                           size_t idx,
881                                           uint32_t *bit_offset_ptr) override;
882 
883   CompilerDecl GetStaticFieldWithName(lldb::opaque_compiler_type_t type,
884                                       llvm::StringRef name) override;
885 
886   static uint32_t GetNumPointeeChildren(clang::QualType type);
887 
888   llvm::Expected<CompilerType> GetChildCompilerTypeAtIndex(
889       lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
890       bool transparent_pointers, bool omit_empty_base_classes,
891       bool ignore_array_bounds, std::string &child_name,
892       uint32_t &child_byte_size, int32_t &child_byte_offset,
893       uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
894       bool &child_is_base_class, bool &child_is_deref_of_parent,
895       ValueObject *valobj, uint64_t &language_flags) override;
896 
897   // Lookup a child given a name. This function will match base class names and
898   // member member names in "clang_type" only, not descendants.
899   uint32_t GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
900                                    llvm::StringRef name,
901                                    bool omit_empty_base_classes) override;
902 
903   // Lookup a child member given a name. This function will match member names
904   // only and will descend into "clang_type" children in search for the first
905   // member in this class, or any base class that matches "name".
906   // TODO: Return all matches for a given name by returning a
907   // vector<vector<uint32_t>>
908   // so we catch all names that match a given child name, not just the first.
909   size_t
910   GetIndexOfChildMemberWithName(lldb::opaque_compiler_type_t type,
911                                 llvm::StringRef name,
912                                 bool omit_empty_base_classes,
913                                 std::vector<uint32_t> &child_indexes) override;
914 
915   CompilerType GetDirectNestedTypeWithName(lldb::opaque_compiler_type_t type,
916                                            llvm::StringRef name) override;
917 
918   bool IsTemplateType(lldb::opaque_compiler_type_t type) override;
919 
920   size_t GetNumTemplateArguments(lldb::opaque_compiler_type_t type,
921                                  bool expand_pack) override;
922 
923   lldb::TemplateArgumentKind
924   GetTemplateArgumentKind(lldb::opaque_compiler_type_t type, size_t idx,
925                           bool expand_pack) override;
926   CompilerType GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
927                                        size_t idx, bool expand_pack) override;
928   std::optional<CompilerType::IntegralTemplateArgument>
929   GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type, size_t idx,
930                               bool expand_pack) override;
931 
932   CompilerType GetTypeForFormatters(void *type) override;
933 
934 #define LLDB_INVALID_DECL_LEVEL UINT32_MAX
935   // LLDB_INVALID_DECL_LEVEL is returned by CountDeclLevels if child_decl_ctx
936   // could not be found in decl_ctx.
937   uint32_t CountDeclLevels(clang::DeclContext *frame_decl_ctx,
938                            clang::DeclContext *child_decl_ctx,
939                            ConstString *child_name = nullptr,
940                            CompilerType *child_type = nullptr);
941 
942   // Modifying RecordType
943   static clang::FieldDecl *AddFieldToRecordType(const CompilerType &type,
944                                                 llvm::StringRef name,
945                                                 const CompilerType &field_type,
946                                                 lldb::AccessType access,
947                                                 uint32_t bitfield_bit_size);
948 
949   static void BuildIndirectFields(const CompilerType &type);
950 
951   static void SetIsPacked(const CompilerType &type);
952 
953   static clang::VarDecl *AddVariableToRecordType(const CompilerType &type,
954                                                  llvm::StringRef name,
955                                                  const CompilerType &var_type,
956                                                  lldb::AccessType access);
957 
958   /// Initializes a variable with an integer value.
959   /// \param var The variable to initialize. Must not already have an
960   ///            initializer and must have an integer or enum type.
961   /// \param init_value The integer value that the variable should be
962   ///                   initialized to. Has to match the bit width of the
963   ///                   variable type.
964   static void SetIntegerInitializerForVariable(clang::VarDecl *var,
965                                                const llvm::APInt &init_value);
966 
967   /// Initializes a variable with a floating point value.
968   /// \param var The variable to initialize. Must not already have an
969   ///            initializer and must have a floating point type.
970   /// \param init_value The float value that the variable should be
971   ///                   initialized to.
972   static void
973   SetFloatingInitializerForVariable(clang::VarDecl *var,
974                                     const llvm::APFloat &init_value);
975 
976   /// For each parameter type of \c prototype, creates a \c clang::ParmVarDecl
977   /// whose \c clang::DeclContext is \c context.
978   ///
979   /// \param[in] context Non-null \c clang::FunctionDecl which will be the \c
980   /// clang::DeclContext of each parameter created/returned by this function.
981   /// \param[in] prototype The \c clang::FunctionProtoType of \c context.
982   /// \param[in] param_names The ith element of this vector contains the name
983   /// of the ith parameter. This parameter may be unnamed, in which case the
984   /// ith entry in \c param_names is an empty string. This vector is either
985   /// empty, or will have an entry for *each* parameter of the prototype
986   /// regardless of whether a parameter is unnamed or not.
987   ///
988   /// \returns A list of newly created of non-null \c clang::ParmVarDecl (one
989   /// for each parameter of \c prototype).
990   llvm::SmallVector<clang::ParmVarDecl *> CreateParameterDeclarations(
991       clang::FunctionDecl *context, const clang::FunctionProtoType &prototype,
992       const llvm::SmallVector<llvm::StringRef> &param_names);
993 
994   clang::CXXMethodDecl *AddMethodToCXXRecordType(
995       lldb::opaque_compiler_type_t type, llvm::StringRef name,
996       const char *mangled_name, const CompilerType &method_type,
997       lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline,
998       bool is_explicit, bool is_attr_used, bool is_artificial);
999 
1000   void AddMethodOverridesForCXXRecordType(lldb::opaque_compiler_type_t type);
1001 
1002   // C++ Base Classes
1003   std::unique_ptr<clang::CXXBaseSpecifier>
1004   CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
1005                            lldb::AccessType access, bool is_virtual,
1006                            bool base_of_class);
1007 
1008   bool TransferBaseClasses(
1009       lldb::opaque_compiler_type_t type,
1010       std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases);
1011 
1012   static bool SetObjCSuperClass(const CompilerType &type,
1013                                 const CompilerType &superclass_compiler_type);
1014 
1015   static bool AddObjCClassProperty(const CompilerType &type,
1016                                    const char *property_name,
1017                                    const CompilerType &property_compiler_type,
1018                                    clang::ObjCIvarDecl *ivar_decl,
1019                                    const char *property_setter_name,
1020                                    const char *property_getter_name,
1021                                    uint32_t property_attributes,
1022                                    ClangASTMetadata metadata);
1023 
1024   static clang::ObjCMethodDecl *AddMethodToObjCObjectType(
1025       const CompilerType &type,
1026       const char *name, // the full symbol name as seen in the symbol table
1027                         // (lldb::opaque_compiler_type_t type, "-[NString
1028                         // stringWithCString:]")
1029       const CompilerType &method_compiler_type, bool is_artificial,
1030       bool is_variadic, bool is_objc_direct_call);
1031 
1032   static bool SetHasExternalStorage(lldb::opaque_compiler_type_t type,
1033                                     bool has_extern);
1034 
1035   // Tag Declarations
1036   static bool StartTagDeclarationDefinition(const CompilerType &type);
1037 
1038   static bool CompleteTagDeclarationDefinition(const CompilerType &type);
1039 
1040   // Modifying Enumeration types
1041   clang::EnumConstantDecl *AddEnumerationValueToEnumerationType(
1042       const CompilerType &enum_type, const Declaration &decl, const char *name,
1043       int64_t enum_value, uint32_t enum_value_bit_size);
1044   clang::EnumConstantDecl *AddEnumerationValueToEnumerationType(
1045       const CompilerType &enum_type, const Declaration &decl, const char *name,
1046       const llvm::APSInt &value);
1047 
1048   /// Returns the underlying integer type for an enum type. If the given type
1049   /// is invalid or not an enum-type, the function returns an invalid
1050   /// CompilerType.
1051   CompilerType GetEnumerationIntegerType(CompilerType type);
1052 
1053   // Pointers & References
1054 
1055   // Call this function using the class type when you want to make a member
1056   // pointer type to pointee_type.
1057   static CompilerType CreateMemberPointerType(const CompilerType &type,
1058                                               const CompilerType &pointee_type);
1059 
1060   // Dumping types
1061 #ifndef NDEBUG
1062   /// Convenience LLVM-style dump method for use in the debugger only.
1063   /// In contrast to the other \p Dump() methods this directly invokes
1064   /// \p clang::QualType::dump().
1065   LLVM_DUMP_METHOD void dump(lldb::opaque_compiler_type_t type) const override;
1066 #endif
1067 
1068   /// \see lldb_private::TypeSystem::Dump
1069   void Dump(llvm::raw_ostream &output) override;
1070 
1071   /// Dump clang AST types from the symbol file.
1072   ///
1073   /// \param[in] s
1074   ///       A stream to send the dumped AST node(s) to
1075   /// \param[in] symbol_name
1076   ///       The name of the symbol to dump, if it is empty dump all the symbols
1077   void DumpFromSymbolFile(Stream &s, llvm::StringRef symbol_name);
1078 
1079   bool DumpTypeValue(lldb::opaque_compiler_type_t type, Stream &s,
1080                      lldb::Format format, const DataExtractor &data,
1081                      lldb::offset_t data_offset, size_t data_byte_size,
1082                      uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
1083                      ExecutionContextScope *exe_scope) override;
1084 
1085   void DumpTypeDescription(
1086       lldb::opaque_compiler_type_t type,
1087       lldb::DescriptionLevel level = lldb::eDescriptionLevelFull) override;
1088 
1089   void DumpTypeDescription(
1090       lldb::opaque_compiler_type_t type, Stream &s,
1091       lldb::DescriptionLevel level = lldb::eDescriptionLevelFull) override;
1092 
1093   static void DumpTypeName(const CompilerType &type);
1094 
1095   static clang::EnumDecl *GetAsEnumDecl(const CompilerType &type);
1096 
1097   static clang::RecordDecl *GetAsRecordDecl(const CompilerType &type);
1098 
1099   static clang::TagDecl *GetAsTagDecl(const CompilerType &type);
1100 
1101   static clang::TypedefNameDecl *GetAsTypedefDecl(const CompilerType &type);
1102 
1103   static clang::CXXRecordDecl *
1104   GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type);
1105 
1106   static clang::ObjCInterfaceDecl *
1107   GetAsObjCInterfaceDecl(const CompilerType &type);
1108 
1109   clang::ClassTemplateDecl *ParseClassTemplateDecl(
1110       clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1111       lldb::AccessType access_type, const char *parent_name, int tag_decl_kind,
1112       const TypeSystemClang::TemplateParameterInfos &template_param_infos);
1113 
1114   clang::BlockDecl *CreateBlockDeclaration(clang::DeclContext *ctx,
1115                                            OptionalClangModuleID owning_module);
1116 
1117   clang::UsingDirectiveDecl *
1118   CreateUsingDirectiveDeclaration(clang::DeclContext *decl_ctx,
1119                                   OptionalClangModuleID owning_module,
1120                                   clang::NamespaceDecl *ns_decl);
1121 
1122   clang::UsingDecl *CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
1123                                            OptionalClangModuleID owning_module,
1124                                            clang::NamedDecl *target);
1125 
1126   clang::VarDecl *CreateVariableDeclaration(clang::DeclContext *decl_context,
1127                                             OptionalClangModuleID owning_module,
1128                                             const char *name,
1129                                             clang::QualType type);
1130 
1131   static lldb::opaque_compiler_type_t
1132   GetOpaqueCompilerType(clang::ASTContext *ast, lldb::BasicType basic_type);
1133 
1134   static clang::QualType GetQualType(lldb::opaque_compiler_type_t type) {
1135     if (type)
1136       return clang::QualType::getFromOpaquePtr(type);
1137     return clang::QualType();
1138   }
1139 
1140   static clang::QualType
1141   GetCanonicalQualType(lldb::opaque_compiler_type_t type) {
1142     if (type)
1143       return clang::QualType::getFromOpaquePtr(type).getCanonicalType();
1144     return clang::QualType();
1145   }
1146 
1147   clang::DeclarationName
1148   GetDeclarationName(llvm::StringRef name,
1149                      const CompilerType &function_clang_type);
1150 
1151   clang::LangOptions *GetLangOpts() const {
1152     return m_language_options_up.get();
1153   }
1154   clang::SourceManager *GetSourceMgr() const {
1155     return m_source_manager_up.get();
1156   }
1157 
1158   /// Complete a type from debug info, or mark it as forcefully completed if
1159   /// there is no definition of the type in the current Module. Call this
1160   /// function in contexts where the usual C++ rules require a type to be
1161   /// complete (base class, member, etc.).
1162   static void RequireCompleteType(CompilerType type);
1163 
1164   bool SetDeclIsForcefullyCompleted(const clang::TagDecl *td);
1165 
1166 private:
1167   /// Returns the PrintingPolicy used when generating the internal type names.
1168   /// These type names are mostly used for the formatter selection.
1169   clang::PrintingPolicy GetTypePrintingPolicy();
1170   /// Returns the internal type name for the given NamedDecl using the
1171   /// type printing policy.
1172   std::string GetTypeNameForDecl(const clang::NamedDecl *named_decl,
1173                                  bool qualified = true);
1174 
1175   const clang::ClassTemplateSpecializationDecl *
1176   GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type);
1177 
1178   bool IsTypeImpl(lldb::opaque_compiler_type_t type,
1179                   llvm::function_ref<bool(clang::QualType)> predicate) const;
1180 
1181   /// Emits information about this TypeSystem into the expression log.
1182   ///
1183   /// Helper method that is used in \ref TypeSystemClang::TypeSystemClang
1184   /// on creation of a new instance.
1185   void LogCreation() const;
1186 
1187   std::optional<uint64_t> GetObjCBitSize(clang::QualType qual_type,
1188                                          ExecutionContextScope *exe_scope);
1189 
1190   // Classes that inherit from TypeSystemClang can see and modify these
1191   std::string m_target_triple;
1192   std::unique_ptr<clang::ASTContext> m_ast_up;
1193   std::unique_ptr<clang::LangOptions> m_language_options_up;
1194   std::unique_ptr<clang::FileManager> m_file_manager_up;
1195   std::unique_ptr<clang::SourceManager> m_source_manager_up;
1196   std::unique_ptr<clang::DiagnosticsEngine> m_diagnostics_engine_up;
1197   std::unique_ptr<clang::DiagnosticConsumer> m_diagnostic_consumer_up;
1198   std::shared_ptr<clang::TargetOptions> m_target_options_rp;
1199   std::unique_ptr<clang::TargetInfo> m_target_info_up;
1200   std::unique_ptr<clang::IdentifierTable> m_identifier_table_up;
1201   std::unique_ptr<clang::SelectorTable> m_selector_table_up;
1202   std::unique_ptr<clang::Builtin::Context> m_builtins_up;
1203   std::unique_ptr<clang::HeaderSearch> m_header_search_up;
1204   std::unique_ptr<clang::ModuleMap> m_module_map_up;
1205   std::unique_ptr<DWARFASTParserClang> m_dwarf_ast_parser_up;
1206   std::unique_ptr<PDBASTParser> m_pdb_ast_parser_up;
1207   std::unique_ptr<npdb::PdbAstBuilder> m_native_pdb_ast_parser_up;
1208   std::unique_ptr<clang::MangleContext> m_mangle_ctx_up;
1209   uint32_t m_pointer_byte_size = 0;
1210   bool m_ast_owned = false;
1211   /// A string describing what this TypeSystemClang represents (e.g.,
1212   /// AST for debug information, an expression, some other utility ClangAST).
1213   /// Useful for logging and debugging.
1214   std::string m_display_name;
1215 
1216   typedef llvm::DenseMap<const clang::Decl *, ClangASTMetadata> DeclMetadataMap;
1217   /// Maps Decls to their associated ClangASTMetadata.
1218   DeclMetadataMap m_decl_metadata;
1219 
1220   typedef llvm::DenseMap<const clang::Type *, ClangASTMetadata> TypeMetadataMap;
1221   /// Maps Types to their associated ClangASTMetadata.
1222   TypeMetadataMap m_type_metadata;
1223 
1224   typedef llvm::DenseMap<const clang::CXXRecordDecl *, clang::AccessSpecifier>
1225       CXXRecordDeclAccessMap;
1226   /// Maps CXXRecordDecl to their most recent added method/field's
1227   /// AccessSpecifier.
1228   CXXRecordDeclAccessMap m_cxx_record_decl_access;
1229 
1230   /// The sema associated that is currently used to build this ASTContext.
1231   /// May be null if we are already done parsing this ASTContext or the
1232   /// ASTContext wasn't created by parsing source code.
1233   clang::Sema *m_sema = nullptr;
1234 
1235   // For TypeSystemClang only
1236   TypeSystemClang(const TypeSystemClang &);
1237   const TypeSystemClang &operator=(const TypeSystemClang &);
1238   /// Creates the internal ASTContext.
1239   void CreateASTContext();
1240   void SetTargetTriple(llvm::StringRef target_triple);
1241 };
1242 
1243 /// The TypeSystemClang instance used for the scratch ASTContext in a
1244 /// lldb::Target.
1245 class ScratchTypeSystemClang : public TypeSystemClang {
1246   /// LLVM RTTI support
1247   static char ID;
1248 
1249 public:
1250   ScratchTypeSystemClang(Target &target, llvm::Triple triple);
1251 
1252   ~ScratchTypeSystemClang() override = default;
1253 
1254   void Finalize() override;
1255 
1256   /// The different kinds of isolated ASTs within the scratch TypeSystem.
1257   ///
1258   /// These ASTs are isolated from the main scratch AST and are each
1259   /// dedicated to a special language option/feature that makes the contained
1260   /// AST nodes incompatible with other AST nodes.
1261   enum IsolatedASTKind {
1262     /// The isolated AST for declarations/types from expressions that imported
1263     /// type information from a C++ module. The templates from a C++ module
1264     /// often conflict with the templates we generate from debug information,
1265     /// so we put these types in their own AST.
1266     CppModules
1267   };
1268 
1269   /// Alias for requesting the default scratch TypeSystemClang in GetForTarget.
1270   // This isn't constexpr as gtest/std::optional comparison logic is trying
1271   // to get the address of this for pretty-printing.
1272   static const std::nullopt_t DefaultAST;
1273 
1274   /// Infers the appropriate sub-AST from Clang's LangOptions.
1275   static std::optional<IsolatedASTKind>
1276   InferIsolatedASTKindFromLangOpts(const clang::LangOptions &l) {
1277     // If modules are activated we want the dedicated C++ module AST.
1278     // See IsolatedASTKind::CppModules for more info.
1279     if (l.Modules)
1280       return IsolatedASTKind::CppModules;
1281     return DefaultAST;
1282   }
1283 
1284   /// Returns the scratch TypeSystemClang for the given target.
1285   /// \param target The Target which scratch TypeSystemClang should be returned.
1286   /// \param ast_kind Allows requesting a specific sub-AST instead of the
1287   ///                 default scratch AST. See also `IsolatedASTKind`.
1288   /// \param create_on_demand If the scratch TypeSystemClang instance can be
1289   /// created by this call if it doesn't exist yet. If it doesn't exist yet and
1290   /// this parameter is false, this function returns a nullptr.
1291   /// \return The scratch type system of the target or a nullptr in case an
1292   ///         error occurred.
1293   static lldb::TypeSystemClangSP
1294   GetForTarget(Target &target,
1295                std::optional<IsolatedASTKind> ast_kind = DefaultAST,
1296                bool create_on_demand = true);
1297 
1298   /// Returns the scratch TypeSystemClang for the given target. The returned
1299   /// TypeSystemClang will be the scratch AST or a sub-AST, depending on which
1300   /// fits best to the passed LangOptions.
1301   /// \param target The Target which scratch TypeSystemClang should be returned.
1302   /// \param lang_opts The LangOptions of a clang ASTContext that the caller
1303   ///                  wants to export type information from. This is used to
1304   ///                  find the best matching sub-AST that will be returned.
1305   static lldb::TypeSystemClangSP
1306   GetForTarget(Target &target, const clang::LangOptions &lang_opts) {
1307     return GetForTarget(target, InferIsolatedASTKindFromLangOpts(lang_opts));
1308   }
1309 
1310   /// \see lldb_private::TypeSystem::Dump
1311   void Dump(llvm::raw_ostream &output) override;
1312 
1313   UserExpression *GetUserExpression(llvm::StringRef expr,
1314                                     llvm::StringRef prefix,
1315                                     SourceLanguage language,
1316                                     Expression::ResultType desired_type,
1317                                     const EvaluateExpressionOptions &options,
1318                                     ValueObject *ctx_obj) override;
1319 
1320   FunctionCaller *GetFunctionCaller(const CompilerType &return_type,
1321                                     const Address &function_address,
1322                                     const ValueList &arg_value_list,
1323                                     const char *name) override;
1324 
1325   std::unique_ptr<UtilityFunction>
1326   CreateUtilityFunction(std::string text, std::string name) override;
1327 
1328   PersistentExpressionState *GetPersistentExpressionState() override;
1329 
1330   /// Unregisters the given ASTContext as a source from the scratch AST (and
1331   /// all sub-ASTs).
1332   /// \see ClangASTImporter::ForgetSource
1333   void ForgetSource(clang::ASTContext *src_ctx, ClangASTImporter &importer);
1334 
1335   // llvm casting support
1336   bool isA(const void *ClassID) const override {
1337     return ClassID == &ID || TypeSystemClang::isA(ClassID);
1338   }
1339   static bool classof(const TypeSystem *ts) { return ts->isA(&ID); }
1340 
1341 private:
1342   std::unique_ptr<ClangASTSource> CreateASTSource();
1343   /// Returns the requested sub-AST.
1344   /// Will lazily create the sub-AST if it hasn't been created before.
1345   TypeSystemClang &GetIsolatedAST(IsolatedASTKind feature);
1346 
1347   /// The target triple.
1348   /// This was potentially adjusted and might not be identical to the triple
1349   /// of `m_target_wp`.
1350   llvm::Triple m_triple;
1351   lldb::TargetWP m_target_wp;
1352   /// The persistent variables associated with this process for the expression
1353   /// parser.
1354   std::unique_ptr<ClangPersistentVariables> m_persistent_variables;
1355   /// The ExternalASTSource that performs lookups and completes minimally
1356   /// imported types.
1357   std::unique_ptr<ClangASTSource> m_scratch_ast_source_up;
1358 
1359   // FIXME: GCC 5.x doesn't support enum as map keys.
1360   typedef int IsolatedASTKey;
1361 
1362   /// Map from IsolatedASTKind to their actual TypeSystemClang instance.
1363   /// This map is lazily filled with sub-ASTs and should be accessed via
1364   /// `GetSubAST` (which lazily fills this map).
1365   llvm::DenseMap<IsolatedASTKey, std::shared_ptr<TypeSystemClang>>
1366       m_isolated_asts;
1367 };
1368 
1369 } // namespace lldb_private
1370 
1371 #endif // LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H
1372