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