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