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