1 //===-- TypeSystemClang.cpp -----------------------------------------------==='//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "TypeSystemClang.h"
10 
11 #include "llvm/Support/FormatAdapters.h"
12 #include "llvm/Support/FormatVariadic.h"
13 
14 #include <mutex>
15 #include <memory>
16 #include <string>
17 #include <vector>
18 
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/ASTImporter.h"
21 #include "clang/AST/Attr.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/Type.h"
28 #include "clang/AST/VTableBuilder.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/Diagnostic.h"
31 #include "clang/Basic/FileManager.h"
32 #include "clang/Basic/FileSystemOptions.h"
33 #include "clang/Basic/LangStandard.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Basic/TargetOptions.h"
37 #include "clang/Frontend/FrontendOptions.h"
38 #include "clang/Lex/HeaderSearch.h"
39 #include "clang/Lex/HeaderSearchOptions.h"
40 #include "clang/Lex/ModuleMap.h"
41 #include "clang/Sema/Sema.h"
42 
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/Threading.h"
45 
46 #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
47 #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
48 #include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"
49 #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
50 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
51 #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
52 #include "Plugins/ExpressionParser/Clang/ClangUtil.h"
53 #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
54 #include "lldb/Core/DumpDataExtractor.h"
55 #include "lldb/Core/Module.h"
56 #include "lldb/Core/PluginManager.h"
57 #include "lldb/Core/StreamFile.h"
58 #include "lldb/Core/ThreadSafeDenseMap.h"
59 #include "lldb/Core/UniqueCStringMap.h"
60 #include "lldb/Symbol/ObjectFile.h"
61 #include "lldb/Symbol/SymbolFile.h"
62 #include "lldb/Target/ExecutionContext.h"
63 #include "lldb/Target/Language.h"
64 #include "lldb/Target/Process.h"
65 #include "lldb/Target/Target.h"
66 #include "lldb/Utility/ArchSpec.h"
67 #include "lldb/Utility/DataExtractor.h"
68 #include "lldb/Utility/Flags.h"
69 #include "lldb/Utility/LLDBAssert.h"
70 #include "lldb/Utility/LLDBLog.h"
71 #include "lldb/Utility/RegularExpression.h"
72 #include "lldb/Utility/Scalar.h"
73 
74 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
75 #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
76 #include "Plugins/SymbolFile/PDB/PDBASTParser.h"
77 #include "Plugins/SymbolFile/NativePDB/PdbAstBuilder.h"
78 
79 #include <cstdio>
80 
81 #include <mutex>
82 #include <optional>
83 
84 using namespace lldb;
85 using namespace lldb_private;
86 using namespace lldb_private::dwarf;
87 using namespace clang;
88 using llvm::StringSwitch;
89 
90 LLDB_PLUGIN_DEFINE(TypeSystemClang)
91 
92 namespace {
93 static void VerifyDecl(clang::Decl *decl) {
94   assert(decl && "VerifyDecl called with nullptr?");
95 #ifndef NDEBUG
96   // We don't care about the actual access value here but only want to trigger
97   // that Clang calls its internal Decl::AccessDeclContextCheck validation.
98   decl->getAccess();
99 #endif
100 }
101 
102 static inline bool
103 TypeSystemClangSupportsLanguage(lldb::LanguageType language) {
104   return language == eLanguageTypeUnknown || // Clang is the default type system
105          lldb_private::Language::LanguageIsC(language) ||
106          lldb_private::Language::LanguageIsCPlusPlus(language) ||
107          lldb_private::Language::LanguageIsObjC(language) ||
108          lldb_private::Language::LanguageIsPascal(language) ||
109          // Use Clang for Rust until there is a proper language plugin for it
110          language == eLanguageTypeRust ||
111          language == eLanguageTypeExtRenderScript ||
112          // Use Clang for D until there is a proper language plugin for it
113          language == eLanguageTypeD ||
114          // Open Dylan compiler debug info is designed to be Clang-compatible
115          language == eLanguageTypeDylan;
116 }
117 
118 // Checks whether m1 is an overload of m2 (as opposed to an override). This is
119 // called by addOverridesForMethod to distinguish overrides (which share a
120 // vtable entry) from overloads (which require distinct entries).
121 bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) {
122   // FIXME: This should detect covariant return types, but currently doesn't.
123   lldbassert(&m1->getASTContext() == &m2->getASTContext() &&
124              "Methods should have the same AST context");
125   clang::ASTContext &context = m1->getASTContext();
126 
127   const auto *m1Type = llvm::cast<clang::FunctionProtoType>(
128       context.getCanonicalType(m1->getType()));
129 
130   const auto *m2Type = llvm::cast<clang::FunctionProtoType>(
131       context.getCanonicalType(m2->getType()));
132 
133   auto compareArgTypes = [&context](const clang::QualType &m1p,
134                                     const clang::QualType &m2p) {
135     return context.hasSameType(m1p.getUnqualifiedType(),
136                                m2p.getUnqualifiedType());
137   };
138 
139   // FIXME: In C++14 and later, we can just pass m2Type->param_type_end()
140   //        as a fourth parameter to std::equal().
141   return (m1->getNumParams() != m2->getNumParams()) ||
142          !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(),
143                      m2Type->param_type_begin(), compareArgTypes);
144 }
145 
146 // If decl is a virtual method, walk the base classes looking for methods that
147 // decl overrides. This table of overridden methods is used by IRGen to
148 // determine the vtable layout for decl's parent class.
149 void addOverridesForMethod(clang::CXXMethodDecl *decl) {
150   if (!decl->isVirtual())
151     return;
152 
153   clang::CXXBasePaths paths;
154   llvm::SmallVector<clang::NamedDecl *, 4> decls;
155 
156   auto find_overridden_methods =
157       [&decls, decl](const clang::CXXBaseSpecifier *specifier,
158                      clang::CXXBasePath &path) {
159         if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>(
160                 specifier->getType()->castAs<clang::RecordType>()->getDecl())) {
161 
162           clang::DeclarationName name = decl->getDeclName();
163 
164           // If this is a destructor, check whether the base class destructor is
165           // virtual.
166           if (name.getNameKind() == clang::DeclarationName::CXXDestructorName)
167             if (auto *baseDtorDecl = base_record->getDestructor()) {
168               if (baseDtorDecl->isVirtual()) {
169                 decls.push_back(baseDtorDecl);
170                 return true;
171               } else
172                 return false;
173             }
174 
175           // Otherwise, search for name in the base class.
176           for (path.Decls = base_record->lookup(name).begin();
177                path.Decls != path.Decls.end(); ++path.Decls) {
178             if (auto *method_decl =
179                     llvm::dyn_cast<clang::CXXMethodDecl>(*path.Decls))
180               if (method_decl->isVirtual() && !isOverload(decl, method_decl)) {
181                 decls.push_back(method_decl);
182                 return true;
183               }
184           }
185         }
186 
187         return false;
188       };
189 
190   if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) {
191     for (auto *overridden_decl : decls)
192       decl->addOverriddenMethod(
193           llvm::cast<clang::CXXMethodDecl>(overridden_decl));
194   }
195 }
196 }
197 
198 static lldb::addr_t GetVTableAddress(Process &process,
199                                      VTableContextBase &vtable_ctx,
200                                      ValueObject &valobj,
201                                      const ASTRecordLayout &record_layout) {
202   // Retrieve type info
203   CompilerType pointee_type;
204   CompilerType this_type(valobj.GetCompilerType());
205   uint32_t type_info = this_type.GetTypeInfo(&pointee_type);
206   if (!type_info)
207     return LLDB_INVALID_ADDRESS;
208 
209   // Check if it's a pointer or reference
210   bool ptr_or_ref = false;
211   if (type_info & (eTypeIsPointer | eTypeIsReference)) {
212     ptr_or_ref = true;
213     type_info = pointee_type.GetTypeInfo();
214   }
215 
216   // We process only C++ classes
217   const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus;
218   if ((type_info & cpp_class) != cpp_class)
219     return LLDB_INVALID_ADDRESS;
220 
221   // Calculate offset to VTable pointer
222   lldb::offset_t vbtable_ptr_offset =
223       vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity()
224                                : 0;
225 
226   if (ptr_or_ref) {
227     // We have a pointer / ref to object, so read
228     // VTable pointer from process memory
229 
230     if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad)
231       return LLDB_INVALID_ADDRESS;
232 
233     auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
234     if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS)
235       return LLDB_INVALID_ADDRESS;
236 
237     vbtable_ptr_addr += vbtable_ptr_offset;
238 
239     Status err;
240     return process.ReadPointerFromMemory(vbtable_ptr_addr, err);
241   }
242 
243   // We have an object already read from process memory,
244   // so just extract VTable pointer from it
245 
246   DataExtractor data;
247   Status err;
248   auto size = valobj.GetData(data, err);
249   if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size)
250     return LLDB_INVALID_ADDRESS;
251 
252   return data.GetAddress(&vbtable_ptr_offset);
253 }
254 
255 static int64_t ReadVBaseOffsetFromVTable(Process &process,
256                                          VTableContextBase &vtable_ctx,
257                                          lldb::addr_t vtable_ptr,
258                                          const CXXRecordDecl *cxx_record_decl,
259                                          const CXXRecordDecl *base_class_decl) {
260   if (vtable_ctx.isMicrosoft()) {
261     clang::MicrosoftVTableContext &msoft_vtable_ctx =
262         static_cast<clang::MicrosoftVTableContext &>(vtable_ctx);
263 
264     // Get the index into the virtual base table. The
265     // index is the index in uint32_t from vbtable_ptr
266     const unsigned vbtable_index =
267         msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl);
268     const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4;
269     Status err;
270     return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX,
271                                                err);
272   }
273 
274   clang::ItaniumVTableContext &itanium_vtable_ctx =
275       static_cast<clang::ItaniumVTableContext &>(vtable_ctx);
276 
277   clang::CharUnits base_offset_offset =
278       itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl,
279                                                     base_class_decl);
280   const lldb::addr_t base_offset_addr =
281       vtable_ptr + base_offset_offset.getQuantity();
282   const uint32_t base_offset_size = process.GetAddressByteSize();
283   Status err;
284   return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size,
285                                              INT64_MAX, err);
286 }
287 
288 static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx,
289                               ValueObject &valobj,
290                               const ASTRecordLayout &record_layout,
291                               const CXXRecordDecl *cxx_record_decl,
292                               const CXXRecordDecl *base_class_decl,
293                               int32_t &bit_offset) {
294   ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
295   Process *process = exe_ctx.GetProcessPtr();
296   if (!process)
297     return false;
298 
299   lldb::addr_t vtable_ptr =
300       GetVTableAddress(*process, vtable_ctx, valobj, record_layout);
301   if (vtable_ptr == LLDB_INVALID_ADDRESS)
302     return false;
303 
304   auto base_offset = ReadVBaseOffsetFromVTable(
305       *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl);
306   if (base_offset == INT64_MAX)
307     return false;
308 
309   bit_offset = base_offset * 8;
310 
311   return true;
312 }
313 
314 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, TypeSystemClang *>
315     ClangASTMap;
316 
317 static ClangASTMap &GetASTMap() {
318   static ClangASTMap *g_map_ptr = nullptr;
319   static llvm::once_flag g_once_flag;
320   llvm::call_once(g_once_flag, []() {
321     g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
322   });
323   return *g_map_ptr;
324 }
325 
326 TypePayloadClang::TypePayloadClang(OptionalClangModuleID owning_module,
327                                    bool is_complete_objc_class)
328     : m_payload(owning_module.GetValue()) {
329   SetIsCompleteObjCClass(is_complete_objc_class);
330 }
331 
332 void TypePayloadClang::SetOwningModule(OptionalClangModuleID id) {
333   assert(id.GetValue() < ObjCClassBit);
334   bool is_complete = IsCompleteObjCClass();
335   m_payload = id.GetValue();
336   SetIsCompleteObjCClass(is_complete);
337 }
338 
339 static void SetMemberOwningModule(clang::Decl *member,
340                                   const clang::Decl *parent) {
341   if (!member || !parent)
342     return;
343 
344   OptionalClangModuleID id(parent->getOwningModuleID());
345   if (!id.HasValue())
346     return;
347 
348   member->setFromASTFile();
349   member->setOwningModuleID(id.GetValue());
350   member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
351   if (llvm::isa<clang::NamedDecl>(member))
352     if (auto *dc = llvm::dyn_cast<clang::DeclContext>(parent)) {
353       dc->setHasExternalVisibleStorage(true);
354       // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be
355       // called when searching for members.
356       dc->setHasExternalLexicalStorage(true);
357     }
358 }
359 
360 char TypeSystemClang::ID;
361 
362 bool TypeSystemClang::IsOperator(llvm::StringRef name,
363                                  clang::OverloadedOperatorKind &op_kind) {
364   // All operators have to start with "operator".
365   if (!name.consume_front("operator"))
366     return false;
367 
368   // Remember if there was a space after "operator". This is necessary to
369   // check for collisions with strangely named functions like "operatorint()".
370   bool space_after_operator = name.consume_front(" ");
371 
372   op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
373                 .Case("+", clang::OO_Plus)
374                 .Case("+=", clang::OO_PlusEqual)
375                 .Case("++", clang::OO_PlusPlus)
376                 .Case("-", clang::OO_Minus)
377                 .Case("-=", clang::OO_MinusEqual)
378                 .Case("--", clang::OO_MinusMinus)
379                 .Case("->", clang::OO_Arrow)
380                 .Case("->*", clang::OO_ArrowStar)
381                 .Case("*", clang::OO_Star)
382                 .Case("*=", clang::OO_StarEqual)
383                 .Case("/", clang::OO_Slash)
384                 .Case("/=", clang::OO_SlashEqual)
385                 .Case("%", clang::OO_Percent)
386                 .Case("%=", clang::OO_PercentEqual)
387                 .Case("^", clang::OO_Caret)
388                 .Case("^=", clang::OO_CaretEqual)
389                 .Case("&", clang::OO_Amp)
390                 .Case("&=", clang::OO_AmpEqual)
391                 .Case("&&", clang::OO_AmpAmp)
392                 .Case("|", clang::OO_Pipe)
393                 .Case("|=", clang::OO_PipeEqual)
394                 .Case("||", clang::OO_PipePipe)
395                 .Case("~", clang::OO_Tilde)
396                 .Case("!", clang::OO_Exclaim)
397                 .Case("!=", clang::OO_ExclaimEqual)
398                 .Case("=", clang::OO_Equal)
399                 .Case("==", clang::OO_EqualEqual)
400                 .Case("<", clang::OO_Less)
401                 .Case("<<", clang::OO_LessLess)
402                 .Case("<<=", clang::OO_LessLessEqual)
403                 .Case("<=", clang::OO_LessEqual)
404                 .Case(">", clang::OO_Greater)
405                 .Case(">>", clang::OO_GreaterGreater)
406                 .Case(">>=", clang::OO_GreaterGreaterEqual)
407                 .Case(">=", clang::OO_GreaterEqual)
408                 .Case("()", clang::OO_Call)
409                 .Case("[]", clang::OO_Subscript)
410                 .Case(",", clang::OO_Comma)
411                 .Default(clang::NUM_OVERLOADED_OPERATORS);
412 
413   // We found a fitting operator, so we can exit now.
414   if (op_kind != clang::NUM_OVERLOADED_OPERATORS)
415     return true;
416 
417   // After the "operator " or "operator" part is something unknown. This means
418   // it's either one of the named operators (new/delete), a conversion operator
419   // (e.g. operator bool) or a function which name starts with "operator"
420   // (e.g. void operatorbool).
421 
422   // If it's a function that starts with operator it can't have a space after
423   // "operator" because identifiers can't contain spaces.
424   // E.g. "operator int" (conversion operator)
425   //  vs. "operatorint" (function with colliding name).
426   if (!space_after_operator)
427     return false; // not an operator.
428 
429   // Now the operator is either one of the named operators or a conversion
430   // operator.
431   op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
432                 .Case("new", clang::OO_New)
433                 .Case("new[]", clang::OO_Array_New)
434                 .Case("delete", clang::OO_Delete)
435                 .Case("delete[]", clang::OO_Array_Delete)
436                 // conversion operators hit this case.
437                 .Default(clang::NUM_OVERLOADED_OPERATORS);
438 
439   return true;
440 }
441 
442 clang::AccessSpecifier
443 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(AccessType access) {
444   switch (access) {
445   default:
446     break;
447   case eAccessNone:
448     return AS_none;
449   case eAccessPublic:
450     return AS_public;
451   case eAccessPrivate:
452     return AS_private;
453   case eAccessProtected:
454     return AS_protected;
455   }
456   return AS_none;
457 }
458 
459 static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) {
460   // FIXME: Cleanup per-file based stuff.
461 
462   // Set some properties which depend solely on the input kind; it would be
463   // nice to move these to the language standard, and have the driver resolve
464   // the input kind + language standard.
465   if (IK.getLanguage() == clang::Language::Asm) {
466     Opts.AsmPreprocessor = 1;
467   } else if (IK.isObjectiveC()) {
468     Opts.ObjC = 1;
469   }
470 
471   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
472 
473   if (LangStd == LangStandard::lang_unspecified) {
474     // Based on the base language, pick one.
475     switch (IK.getLanguage()) {
476     case clang::Language::Unknown:
477     case clang::Language::LLVM_IR:
478     case clang::Language::RenderScript:
479       llvm_unreachable("Invalid input kind!");
480     case clang::Language::OpenCL:
481       LangStd = LangStandard::lang_opencl10;
482       break;
483     case clang::Language::OpenCLCXX:
484       LangStd = LangStandard::lang_openclcpp10;
485       break;
486     case clang::Language::CUDA:
487       LangStd = LangStandard::lang_cuda;
488       break;
489     case clang::Language::Asm:
490     case clang::Language::C:
491     case clang::Language::ObjC:
492       LangStd = LangStandard::lang_gnu99;
493       break;
494     case clang::Language::CXX:
495     case clang::Language::ObjCXX:
496       LangStd = LangStandard::lang_gnucxx98;
497       break;
498     case clang::Language::HIP:
499       LangStd = LangStandard::lang_hip;
500       break;
501     case clang::Language::HLSL:
502       LangStd = LangStandard::lang_hlsl;
503       break;
504     }
505   }
506 
507   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
508   Opts.LineComment = Std.hasLineComments();
509   Opts.C99 = Std.isC99();
510   Opts.CPlusPlus = Std.isCPlusPlus();
511   Opts.CPlusPlus11 = Std.isCPlusPlus11();
512   Opts.Digraphs = Std.hasDigraphs();
513   Opts.GNUMode = Std.isGNUMode();
514   Opts.GNUInline = !Std.isC99();
515   Opts.HexFloats = Std.hasHexFloats();
516 
517   Opts.WChar = true;
518 
519   // OpenCL has some additional defaults.
520   if (LangStd == LangStandard::lang_opencl10) {
521     Opts.OpenCL = 1;
522     Opts.AltiVec = 1;
523     Opts.CXXOperatorNames = 1;
524     Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::All);
525   }
526 
527   // OpenCL and C++ both have bool, true, false keywords.
528   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
529 
530   Opts.setValueVisibilityMode(DefaultVisibility);
531 
532   // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
533   // specified, or -std is set to a conforming mode.
534   Opts.Trigraphs = !Opts.GNUMode;
535   Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
536   Opts.OptimizeSize = 0;
537 
538   // FIXME: Eliminate this dependency.
539   //    unsigned Opt =
540   //    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
541   //    Opts.Optimize = Opt != 0;
542   unsigned Opt = 0;
543 
544   // This is the __NO_INLINE__ define, which just depends on things like the
545   // optimization level and -fno-inline, not actually whether the backend has
546   // inlining enabled.
547   //
548   // FIXME: This is affected by other options (-fno-inline).
549   Opts.NoInlineDefine = !Opt;
550 
551   // This is needed to allocate the extra space for the owning module
552   // on each decl.
553   Opts.ModulesLocalVisibility = 1;
554 }
555 
556 TypeSystemClang::TypeSystemClang(llvm::StringRef name,
557                                  llvm::Triple target_triple) {
558   m_display_name = name.str();
559   if (!target_triple.str().empty())
560     SetTargetTriple(target_triple.str());
561   // The caller didn't pass an ASTContext so create a new one for this
562   // TypeSystemClang.
563   CreateASTContext();
564 }
565 
566 TypeSystemClang::TypeSystemClang(llvm::StringRef name,
567                                  ASTContext &existing_ctxt) {
568   m_display_name = name.str();
569   SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str());
570 
571   m_ast_up.reset(&existing_ctxt);
572   GetASTMap().Insert(&existing_ctxt, this);
573 }
574 
575 // Destructor
576 TypeSystemClang::~TypeSystemClang() { Finalize(); }
577 
578 lldb::TypeSystemSP TypeSystemClang::CreateInstance(lldb::LanguageType language,
579                                                    lldb_private::Module *module,
580                                                    Target *target) {
581   if (!TypeSystemClangSupportsLanguage(language))
582     return lldb::TypeSystemSP();
583   ArchSpec arch;
584   if (module)
585     arch = module->GetArchitecture();
586   else if (target)
587     arch = target->GetArchitecture();
588 
589   if (!arch.IsValid())
590     return lldb::TypeSystemSP();
591 
592   llvm::Triple triple = arch.GetTriple();
593   // LLVM wants this to be set to iOS or MacOSX; if we're working on
594   // a bare-boards type image, change the triple for llvm's benefit.
595   if (triple.getVendor() == llvm::Triple::Apple &&
596       triple.getOS() == llvm::Triple::UnknownOS) {
597     if (triple.getArch() == llvm::Triple::arm ||
598         triple.getArch() == llvm::Triple::aarch64 ||
599         triple.getArch() == llvm::Triple::aarch64_32 ||
600         triple.getArch() == llvm::Triple::thumb) {
601       triple.setOS(llvm::Triple::IOS);
602     } else {
603       triple.setOS(llvm::Triple::MacOSX);
604     }
605   }
606 
607   if (module) {
608     std::string ast_name =
609         "ASTContext for '" + module->GetFileSpec().GetPath() + "'";
610     return std::make_shared<TypeSystemClang>(ast_name, triple);
611   } else if (target && target->IsValid())
612     return std::make_shared<ScratchTypeSystemClang>(*target, triple);
613   return lldb::TypeSystemSP();
614 }
615 
616 LanguageSet TypeSystemClang::GetSupportedLanguagesForTypes() {
617   LanguageSet languages;
618   languages.Insert(lldb::eLanguageTypeC89);
619   languages.Insert(lldb::eLanguageTypeC);
620   languages.Insert(lldb::eLanguageTypeC11);
621   languages.Insert(lldb::eLanguageTypeC_plus_plus);
622   languages.Insert(lldb::eLanguageTypeC99);
623   languages.Insert(lldb::eLanguageTypeObjC);
624   languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
625   languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
626   languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
627   languages.Insert(lldb::eLanguageTypeC11);
628   languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
629   return languages;
630 }
631 
632 LanguageSet TypeSystemClang::GetSupportedLanguagesForExpressions() {
633   LanguageSet languages;
634   languages.Insert(lldb::eLanguageTypeC_plus_plus);
635   languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
636   languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
637   languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
638   languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
639   return languages;
640 }
641 
642 void TypeSystemClang::Initialize() {
643   PluginManager::RegisterPlugin(
644       GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance,
645       GetSupportedLanguagesForTypes(), GetSupportedLanguagesForExpressions());
646 }
647 
648 void TypeSystemClang::Terminate() {
649   PluginManager::UnregisterPlugin(CreateInstance);
650 }
651 
652 void TypeSystemClang::Finalize() {
653   assert(m_ast_up);
654   GetASTMap().Erase(m_ast_up.get());
655   if (!m_ast_owned)
656     m_ast_up.release();
657 
658   m_builtins_up.reset();
659   m_selector_table_up.reset();
660   m_identifier_table_up.reset();
661   m_target_info_up.reset();
662   m_target_options_rp.reset();
663   m_diagnostics_engine_up.reset();
664   m_source_manager_up.reset();
665   m_language_options_up.reset();
666 }
667 
668 void TypeSystemClang::setSema(Sema *s) {
669   // Ensure that the new sema actually belongs to our ASTContext.
670   assert(s == nullptr || &s->getASTContext() == m_ast_up.get());
671   m_sema = s;
672 }
673 
674 const char *TypeSystemClang::GetTargetTriple() {
675   return m_target_triple.c_str();
676 }
677 
678 void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) {
679   m_target_triple = target_triple.str();
680 }
681 
682 void TypeSystemClang::SetExternalSource(
683     llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
684   ASTContext &ast = getASTContext();
685   ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
686   ast.setExternalSource(ast_source_up);
687 }
688 
689 ASTContext &TypeSystemClang::getASTContext() {
690   assert(m_ast_up);
691   return *m_ast_up;
692 }
693 
694 class NullDiagnosticConsumer : public DiagnosticConsumer {
695 public:
696   NullDiagnosticConsumer() { m_log = GetLog(LLDBLog::Expressions); }
697 
698   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
699                         const clang::Diagnostic &info) override {
700     if (m_log) {
701       llvm::SmallVector<char, 32> diag_str(10);
702       info.FormatDiagnostic(diag_str);
703       diag_str.push_back('\0');
704       LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data());
705     }
706   }
707 
708   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
709     return new NullDiagnosticConsumer();
710   }
711 
712 private:
713   Log *m_log;
714 };
715 
716 void TypeSystemClang::CreateASTContext() {
717   assert(!m_ast_up);
718   m_ast_owned = true;
719 
720   m_language_options_up = std::make_unique<LangOptions>();
721   ParseLangArgs(*m_language_options_up, clang::Language::ObjCXX,
722                 GetTargetTriple());
723 
724   m_identifier_table_up =
725       std::make_unique<IdentifierTable>(*m_language_options_up, nullptr);
726   m_builtins_up = std::make_unique<Builtin::Context>();
727 
728   m_selector_table_up = std::make_unique<SelectorTable>();
729 
730   clang::FileSystemOptions file_system_options;
731   m_file_manager_up = std::make_unique<clang::FileManager>(
732       file_system_options, FileSystem::Instance().GetVirtualFileSystem());
733 
734   llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
735   m_diagnostics_engine_up =
736       std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions());
737 
738   m_source_manager_up = std::make_unique<clang::SourceManager>(
739       *m_diagnostics_engine_up, *m_file_manager_up);
740   m_ast_up = std::make_unique<ASTContext>(
741       *m_language_options_up, *m_source_manager_up, *m_identifier_table_up,
742       *m_selector_table_up, *m_builtins_up, TU_Complete);
743 
744   m_diagnostic_consumer_up = std::make_unique<NullDiagnosticConsumer>();
745   m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), false);
746 
747   // This can be NULL if we don't know anything about the architecture or if
748   // the target for an architecture isn't enabled in the llvm/clang that we
749   // built
750   TargetInfo *target_info = getTargetInfo();
751   if (target_info)
752     m_ast_up->InitBuiltinTypes(*target_info);
753 
754   GetASTMap().Insert(m_ast_up.get(), this);
755 
756   llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
757       new ClangExternalASTSourceCallbacks(*this));
758   SetExternalSource(ast_source_up);
759 }
760 
761 TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) {
762   TypeSystemClang *clang_ast = GetASTMap().Lookup(ast);
763   return clang_ast;
764 }
765 
766 clang::MangleContext *TypeSystemClang::getMangleContext() {
767   if (m_mangle_ctx_up == nullptr)
768     m_mangle_ctx_up.reset(getASTContext().createMangleContext());
769   return m_mangle_ctx_up.get();
770 }
771 
772 std::shared_ptr<clang::TargetOptions> &TypeSystemClang::getTargetOptions() {
773   if (m_target_options_rp == nullptr && !m_target_triple.empty()) {
774     m_target_options_rp = std::make_shared<clang::TargetOptions>();
775     if (m_target_options_rp != nullptr)
776       m_target_options_rp->Triple = m_target_triple;
777   }
778   return m_target_options_rp;
779 }
780 
781 TargetInfo *TypeSystemClang::getTargetInfo() {
782   // target_triple should be something like "x86_64-apple-macosx"
783   if (m_target_info_up == nullptr && !m_target_triple.empty())
784     m_target_info_up.reset(TargetInfo::CreateTargetInfo(
785         getASTContext().getDiagnostics(), getTargetOptions()));
786   return m_target_info_up.get();
787 }
788 
789 #pragma mark Basic Types
790 
791 static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
792                                           ASTContext &ast, QualType qual_type) {
793   uint64_t qual_type_bit_size = ast.getTypeSize(qual_type);
794   return qual_type_bit_size == bit_size;
795 }
796 
797 CompilerType
798 TypeSystemClang::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
799                                                      size_t bit_size) {
800   ASTContext &ast = getASTContext();
801   switch (encoding) {
802   case eEncodingInvalid:
803     if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
804       return GetType(ast.VoidPtrTy);
805     break;
806 
807   case eEncodingUint:
808     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
809       return GetType(ast.UnsignedCharTy);
810     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
811       return GetType(ast.UnsignedShortTy);
812     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
813       return GetType(ast.UnsignedIntTy);
814     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
815       return GetType(ast.UnsignedLongTy);
816     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
817       return GetType(ast.UnsignedLongLongTy);
818     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
819       return GetType(ast.UnsignedInt128Ty);
820     break;
821 
822   case eEncodingSint:
823     if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
824       return GetType(ast.SignedCharTy);
825     if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
826       return GetType(ast.ShortTy);
827     if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
828       return GetType(ast.IntTy);
829     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
830       return GetType(ast.LongTy);
831     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
832       return GetType(ast.LongLongTy);
833     if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
834       return GetType(ast.Int128Ty);
835     break;
836 
837   case eEncodingIEEE754:
838     if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
839       return GetType(ast.FloatTy);
840     if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
841       return GetType(ast.DoubleTy);
842     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
843       return GetType(ast.LongDoubleTy);
844     if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
845       return GetType(ast.HalfTy);
846     break;
847 
848   case eEncodingVector:
849     // Sanity check that bit_size is a multiple of 8's.
850     if (bit_size && !(bit_size & 0x7u))
851       return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8));
852     break;
853   }
854 
855   return CompilerType();
856 }
857 
858 lldb::BasicType
859 TypeSystemClang::GetBasicTypeEnumeration(ConstString name) {
860   if (name) {
861     typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
862     static TypeNameToBasicTypeMap g_type_map;
863     static llvm::once_flag g_once_flag;
864     llvm::call_once(g_once_flag, []() {
865       // "void"
866       g_type_map.Append(ConstString("void"), eBasicTypeVoid);
867 
868       // "char"
869       g_type_map.Append(ConstString("char"), eBasicTypeChar);
870       g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar);
871       g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar);
872       g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar);
873       g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar);
874       g_type_map.Append(ConstString("unsigned wchar_t"),
875                         eBasicTypeUnsignedWChar);
876       // "short"
877       g_type_map.Append(ConstString("short"), eBasicTypeShort);
878       g_type_map.Append(ConstString("short int"), eBasicTypeShort);
879       g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort);
880       g_type_map.Append(ConstString("unsigned short int"),
881                         eBasicTypeUnsignedShort);
882 
883       // "int"
884       g_type_map.Append(ConstString("int"), eBasicTypeInt);
885       g_type_map.Append(ConstString("signed int"), eBasicTypeInt);
886       g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt);
887       g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt);
888 
889       // "long"
890       g_type_map.Append(ConstString("long"), eBasicTypeLong);
891       g_type_map.Append(ConstString("long int"), eBasicTypeLong);
892       g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong);
893       g_type_map.Append(ConstString("unsigned long int"),
894                         eBasicTypeUnsignedLong);
895 
896       // "long long"
897       g_type_map.Append(ConstString("long long"), eBasicTypeLongLong);
898       g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong);
899       g_type_map.Append(ConstString("unsigned long long"),
900                         eBasicTypeUnsignedLongLong);
901       g_type_map.Append(ConstString("unsigned long long int"),
902                         eBasicTypeUnsignedLongLong);
903 
904       // "int128"
905       g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128);
906       g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128);
907 
908       // Miscellaneous
909       g_type_map.Append(ConstString("bool"), eBasicTypeBool);
910       g_type_map.Append(ConstString("float"), eBasicTypeFloat);
911       g_type_map.Append(ConstString("double"), eBasicTypeDouble);
912       g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble);
913       g_type_map.Append(ConstString("id"), eBasicTypeObjCID);
914       g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel);
915       g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr);
916       g_type_map.Sort();
917     });
918 
919     return g_type_map.Find(name, eBasicTypeInvalid);
920   }
921   return eBasicTypeInvalid;
922 }
923 
924 uint32_t TypeSystemClang::GetPointerByteSize() {
925   if (m_pointer_byte_size == 0)
926     if (auto size = GetBasicType(lldb::eBasicTypeVoid)
927                         .GetPointerType()
928                         .GetByteSize(nullptr))
929       m_pointer_byte_size = *size;
930   return m_pointer_byte_size;
931 }
932 
933 CompilerType TypeSystemClang::GetBasicType(lldb::BasicType basic_type) {
934   clang::ASTContext &ast = getASTContext();
935 
936   lldb::opaque_compiler_type_t clang_type =
937       GetOpaqueCompilerType(&ast, basic_type);
938 
939   if (clang_type)
940     return CompilerType(weak_from_this(), clang_type);
941   return CompilerType();
942 }
943 
944 CompilerType TypeSystemClang::GetBuiltinTypeForDWARFEncodingAndBitSize(
945     llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) {
946   ASTContext &ast = getASTContext();
947 
948   switch (dw_ate) {
949   default:
950     break;
951 
952   case DW_ATE_address:
953     if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
954       return GetType(ast.VoidPtrTy);
955     break;
956 
957   case DW_ATE_boolean:
958     if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy))
959       return GetType(ast.BoolTy);
960     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
961       return GetType(ast.UnsignedCharTy);
962     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
963       return GetType(ast.UnsignedShortTy);
964     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
965       return GetType(ast.UnsignedIntTy);
966     break;
967 
968   case DW_ATE_lo_user:
969     // This has been seen to mean DW_AT_complex_integer
970     if (type_name.contains("complex")) {
971       CompilerType complex_int_clang_type =
972           GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
973                                                    bit_size / 2);
974       return GetType(
975           ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type)));
976     }
977     break;
978 
979   case DW_ATE_complex_float: {
980     CanQualType FloatComplexTy = ast.getComplexType(ast.FloatTy);
981     if (QualTypeMatchesBitSize(bit_size, ast, FloatComplexTy))
982       return GetType(FloatComplexTy);
983 
984     CanQualType DoubleComplexTy = ast.getComplexType(ast.DoubleTy);
985     if (QualTypeMatchesBitSize(bit_size, ast, DoubleComplexTy))
986       return GetType(DoubleComplexTy);
987 
988     CanQualType LongDoubleComplexTy = ast.getComplexType(ast.LongDoubleTy);
989     if (QualTypeMatchesBitSize(bit_size, ast, LongDoubleComplexTy))
990       return GetType(LongDoubleComplexTy);
991 
992     CompilerType complex_float_clang_type =
993         GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
994                                                  bit_size / 2);
995     return GetType(
996         ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type)));
997   }
998 
999   case DW_ATE_float:
1000     if (type_name == "float" &&
1001         QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
1002       return GetType(ast.FloatTy);
1003     if (type_name == "double" &&
1004         QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
1005       return GetType(ast.DoubleTy);
1006     if (type_name == "long double" &&
1007         QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
1008       return GetType(ast.LongDoubleTy);
1009     // Fall back to not requiring a name match
1010     if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
1011       return GetType(ast.FloatTy);
1012     if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
1013       return GetType(ast.DoubleTy);
1014     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
1015       return GetType(ast.LongDoubleTy);
1016     if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
1017       return GetType(ast.HalfTy);
1018     break;
1019 
1020   case DW_ATE_signed:
1021     if (!type_name.empty()) {
1022       if (type_name == "wchar_t" &&
1023           QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) &&
1024           (getTargetInfo() &&
1025            TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1026         return GetType(ast.WCharTy);
1027       if (type_name == "void" &&
1028           QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy))
1029         return GetType(ast.VoidTy);
1030       if (type_name.contains("long long") &&
1031           QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1032         return GetType(ast.LongLongTy);
1033       if (type_name.contains("long") &&
1034           QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1035         return GetType(ast.LongTy);
1036       if (type_name.contains("short") &&
1037           QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1038         return GetType(ast.ShortTy);
1039       if (type_name.contains("char")) {
1040         if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1041           return GetType(ast.CharTy);
1042         if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1043           return GetType(ast.SignedCharTy);
1044       }
1045       if (type_name.contains("int")) {
1046         if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1047           return GetType(ast.IntTy);
1048         if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1049           return GetType(ast.Int128Ty);
1050       }
1051     }
1052     // We weren't able to match up a type name, just search by size
1053     if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1054       return GetType(ast.CharTy);
1055     if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1056       return GetType(ast.ShortTy);
1057     if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1058       return GetType(ast.IntTy);
1059     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1060       return GetType(ast.LongTy);
1061     if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1062       return GetType(ast.LongLongTy);
1063     if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1064       return GetType(ast.Int128Ty);
1065     break;
1066 
1067   case DW_ATE_signed_char:
1068     if (type_name == "char") {
1069       if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1070         return GetType(ast.CharTy);
1071     }
1072     if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1073       return GetType(ast.SignedCharTy);
1074     break;
1075 
1076   case DW_ATE_unsigned:
1077     if (!type_name.empty()) {
1078       if (type_name == "wchar_t") {
1079         if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) {
1080           if (!(getTargetInfo() &&
1081                 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1082             return GetType(ast.WCharTy);
1083         }
1084       }
1085       if (type_name.contains("long long")) {
1086         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1087           return GetType(ast.UnsignedLongLongTy);
1088       } else if (type_name.contains("long")) {
1089         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1090           return GetType(ast.UnsignedLongTy);
1091       } else if (type_name.contains("short")) {
1092         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1093           return GetType(ast.UnsignedShortTy);
1094       } else if (type_name.contains("char")) {
1095         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1096           return GetType(ast.UnsignedCharTy);
1097       } else if (type_name.contains("int")) {
1098         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1099           return GetType(ast.UnsignedIntTy);
1100         if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1101           return GetType(ast.UnsignedInt128Ty);
1102       }
1103     }
1104     // We weren't able to match up a type name, just search by size
1105     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1106       return GetType(ast.UnsignedCharTy);
1107     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1108       return GetType(ast.UnsignedShortTy);
1109     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1110       return GetType(ast.UnsignedIntTy);
1111     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1112       return GetType(ast.UnsignedLongTy);
1113     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1114       return GetType(ast.UnsignedLongLongTy);
1115     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1116       return GetType(ast.UnsignedInt128Ty);
1117     break;
1118 
1119   case DW_ATE_unsigned_char:
1120     if (type_name == "char") {
1121       if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1122         return GetType(ast.CharTy);
1123     }
1124     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1125       return GetType(ast.UnsignedCharTy);
1126     if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1127       return GetType(ast.UnsignedShortTy);
1128     break;
1129 
1130   case DW_ATE_imaginary_float:
1131     break;
1132 
1133   case DW_ATE_UTF:
1134     switch (bit_size) {
1135     case 8:
1136       return GetType(ast.Char8Ty);
1137     case 16:
1138       return GetType(ast.Char16Ty);
1139     case 32:
1140       return GetType(ast.Char32Ty);
1141     default:
1142       if (!type_name.empty()) {
1143         if (type_name == "char16_t")
1144           return GetType(ast.Char16Ty);
1145         if (type_name == "char32_t")
1146           return GetType(ast.Char32Ty);
1147         if (type_name == "char8_t")
1148           return GetType(ast.Char8Ty);
1149       }
1150     }
1151     break;
1152   }
1153 
1154   Log *log = GetLog(LLDBLog::Types);
1155   LLDB_LOG(log,
1156            "error: need to add support for DW_TAG_base_type '{0}' "
1157            "encoded with DW_ATE = {1:x}, bit_size = {2}",
1158            type_name, dw_ate, bit_size);
1159   return CompilerType();
1160 }
1161 
1162 CompilerType TypeSystemClang::GetCStringType(bool is_const) {
1163   ASTContext &ast = getASTContext();
1164   QualType char_type(ast.CharTy);
1165 
1166   if (is_const)
1167     char_type.addConst();
1168 
1169   return GetType(ast.getPointerType(char_type));
1170 }
1171 
1172 bool TypeSystemClang::AreTypesSame(CompilerType type1, CompilerType type2,
1173                                    bool ignore_qualifiers) {
1174   auto ast = type1.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
1175   if (!ast || type1.GetTypeSystem() != type2.GetTypeSystem())
1176     return false;
1177 
1178   if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1179     return true;
1180 
1181   QualType type1_qual = ClangUtil::GetQualType(type1);
1182   QualType type2_qual = ClangUtil::GetQualType(type2);
1183 
1184   if (ignore_qualifiers) {
1185     type1_qual = type1_qual.getUnqualifiedType();
1186     type2_qual = type2_qual.getUnqualifiedType();
1187   }
1188 
1189   return ast->getASTContext().hasSameType(type1_qual, type2_qual);
1190 }
1191 
1192 CompilerType TypeSystemClang::GetTypeForDecl(void *opaque_decl) {
1193   if (!opaque_decl)
1194     return CompilerType();
1195 
1196   clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl);
1197   if (auto *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl))
1198     return GetTypeForDecl(named_decl);
1199   return CompilerType();
1200 }
1201 
1202 CompilerDeclContext TypeSystemClang::CreateDeclContext(DeclContext *ctx) {
1203   // Check that the DeclContext actually belongs to this ASTContext.
1204   assert(&ctx->getParentASTContext() == &getASTContext());
1205   return CompilerDeclContext(this, ctx);
1206 }
1207 
1208 CompilerType TypeSystemClang::GetTypeForDecl(clang::NamedDecl *decl) {
1209   if (clang::ObjCInterfaceDecl *interface_decl =
1210       llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1211     return GetTypeForDecl(interface_decl);
1212   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1213     return GetTypeForDecl(tag_decl);
1214   return CompilerType();
1215 }
1216 
1217 CompilerType TypeSystemClang::GetTypeForDecl(TagDecl *decl) {
1218   return GetType(getASTContext().getTagDeclType(decl));
1219 }
1220 
1221 CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1222   return GetType(getASTContext().getObjCInterfaceType(decl));
1223 }
1224 
1225 #pragma mark Structure, Unions, Classes
1226 
1227 void TypeSystemClang::SetOwningModule(clang::Decl *decl,
1228                                       OptionalClangModuleID owning_module) {
1229   if (!decl || !owning_module.HasValue())
1230     return;
1231 
1232   decl->setFromASTFile();
1233   decl->setOwningModuleID(owning_module.GetValue());
1234   decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
1235 }
1236 
1237 OptionalClangModuleID
1238 TypeSystemClang::GetOrCreateClangModule(llvm::StringRef name,
1239                                         OptionalClangModuleID parent,
1240                                         bool is_framework, bool is_explicit) {
1241   // Get the external AST source which holds the modules.
1242   auto *ast_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1243       getASTContext().getExternalSource());
1244   assert(ast_source && "external ast source was lost");
1245   if (!ast_source)
1246     return {};
1247 
1248   // Lazily initialize the module map.
1249   if (!m_header_search_up) {
1250     auto HSOpts = std::make_shared<clang::HeaderSearchOptions>();
1251     m_header_search_up = std::make_unique<clang::HeaderSearch>(
1252         HSOpts, *m_source_manager_up, *m_diagnostics_engine_up,
1253         *m_language_options_up, m_target_info_up.get());
1254     m_module_map_up = std::make_unique<clang::ModuleMap>(
1255         *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up,
1256         m_target_info_up.get(), *m_header_search_up);
1257   }
1258 
1259   // Get or create the module context.
1260   bool created;
1261   clang::Module *module;
1262   auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue());
1263   std::tie(module, created) = m_module_map_up->findOrCreateModule(
1264       name, parent_desc ? parent_desc->getModuleOrNull() : nullptr,
1265       is_framework, is_explicit);
1266   if (!created)
1267     return ast_source->GetIDForModule(module);
1268 
1269   return ast_source->RegisterModule(module);
1270 }
1271 
1272 CompilerType TypeSystemClang::CreateRecordType(
1273     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1274     AccessType access_type, llvm::StringRef name, int kind,
1275     LanguageType language, ClangASTMetadata *metadata, bool exports_symbols) {
1276   ASTContext &ast = getASTContext();
1277 
1278   if (decl_ctx == nullptr)
1279     decl_ctx = ast.getTranslationUnitDecl();
1280 
1281   if (language == eLanguageTypeObjC ||
1282       language == eLanguageTypeObjC_plus_plus) {
1283     bool isForwardDecl = true;
1284     bool isInternal = false;
1285     return CreateObjCClass(name, decl_ctx, owning_module, isForwardDecl,
1286                            isInternal, metadata);
1287   }
1288 
1289   // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1290   // we will need to update this code. I was told to currently always use the
1291   // CXXRecordDecl class since we often don't know from debug information if
1292   // something is struct or a class, so we default to always use the more
1293   // complete definition just in case.
1294 
1295   bool has_name = !name.empty();
1296   CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, 0);
1297   decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1298   decl->setDeclContext(decl_ctx);
1299   if (has_name)
1300     decl->setDeclName(&ast.Idents.get(name));
1301   SetOwningModule(decl, owning_module);
1302 
1303   if (!has_name) {
1304     // In C++ a lambda is also represented as an unnamed class. This is
1305     // different from an *anonymous class* that the user wrote:
1306     //
1307     // struct A {
1308     //  // anonymous class (GNU/MSVC extension)
1309     //  struct {
1310     //    int x;
1311     //  };
1312     //  // unnamed class within a class
1313     //  struct {
1314     //    int y;
1315     //  } B;
1316     // };
1317     //
1318     // void f() {
1319     //    // unammed class outside of a class
1320     //    struct {
1321     //      int z;
1322     //    } C;
1323     // }
1324     //
1325     // Anonymous classes is a GNU/MSVC extension that clang supports. It
1326     // requires the anonymous class be embedded within a class. So the new
1327     // heuristic verifies this condition.
1328     if (isa<CXXRecordDecl>(decl_ctx) && exports_symbols)
1329       decl->setAnonymousStructOrUnion(true);
1330   }
1331 
1332   if (metadata)
1333     SetMetadata(decl, *metadata);
1334 
1335   if (access_type != eAccessNone)
1336     decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1337 
1338   if (decl_ctx)
1339     decl_ctx->addDecl(decl);
1340 
1341   return GetType(ast.getTagDeclType(decl));
1342 }
1343 
1344 namespace {
1345 /// Returns true iff the given TemplateArgument should be represented as an
1346 /// NonTypeTemplateParmDecl in the AST.
1347 bool IsValueParam(const clang::TemplateArgument &argument) {
1348   return argument.getKind() == TemplateArgument::Integral;
1349 }
1350 
1351 void AddAccessSpecifierDecl(clang::CXXRecordDecl *cxx_record_decl,
1352                             ASTContext &ct,
1353                             clang::AccessSpecifier previous_access,
1354                             clang::AccessSpecifier access_specifier) {
1355   if (!cxx_record_decl->isClass() && !cxx_record_decl->isStruct())
1356     return;
1357   if (previous_access != access_specifier) {
1358     // For struct, don't add AS_public if it's the first AccessSpecDecl.
1359     // For class, don't add AS_private if it's the first AccessSpecDecl.
1360     if ((cxx_record_decl->isStruct() &&
1361          previous_access == clang::AccessSpecifier::AS_none &&
1362          access_specifier == clang::AccessSpecifier::AS_public) ||
1363         (cxx_record_decl->isClass() &&
1364          previous_access == clang::AccessSpecifier::AS_none &&
1365          access_specifier == clang::AccessSpecifier::AS_private)) {
1366       return;
1367     }
1368     cxx_record_decl->addDecl(
1369         AccessSpecDecl::Create(ct, access_specifier, cxx_record_decl,
1370                                SourceLocation(), SourceLocation()));
1371   }
1372 }
1373 } // namespace
1374 
1375 static TemplateParameterList *CreateTemplateParameterList(
1376     ASTContext &ast,
1377     const TypeSystemClang::TemplateParameterInfos &template_param_infos,
1378     llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1379   const bool parameter_pack = false;
1380   const bool is_typename = false;
1381   const unsigned depth = 0;
1382   const size_t num_template_params = template_param_infos.args.size();
1383   DeclContext *const decl_context =
1384       ast.getTranslationUnitDecl(); // Is this the right decl context?,
1385   for (size_t i = 0; i < num_template_params; ++i) {
1386     const char *name = template_param_infos.names[i];
1387 
1388     IdentifierInfo *identifier_info = nullptr;
1389     if (name && name[0])
1390       identifier_info = &ast.Idents.get(name);
1391     if (IsValueParam(template_param_infos.args[i])) {
1392       QualType template_param_type =
1393           template_param_infos.args[i].getIntegralType();
1394       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1395           ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1396           identifier_info, template_param_type, parameter_pack,
1397           ast.getTrivialTypeSourceInfo(template_param_type)));
1398     } else {
1399       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1400           ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1401           identifier_info, is_typename, parameter_pack));
1402     }
1403   }
1404 
1405   if (template_param_infos.packed_args) {
1406     IdentifierInfo *identifier_info = nullptr;
1407     if (template_param_infos.pack_name && template_param_infos.pack_name[0])
1408       identifier_info = &ast.Idents.get(template_param_infos.pack_name);
1409     const bool parameter_pack_true = true;
1410 
1411     if (!template_param_infos.packed_args->args.empty() &&
1412         IsValueParam(template_param_infos.packed_args->args[0])) {
1413       QualType template_param_type =
1414           template_param_infos.packed_args->args[0].getIntegralType();
1415       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1416           ast, decl_context, SourceLocation(), SourceLocation(), depth,
1417           num_template_params, identifier_info, template_param_type,
1418           parameter_pack_true,
1419           ast.getTrivialTypeSourceInfo(template_param_type)));
1420     } else {
1421       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1422           ast, decl_context, SourceLocation(), SourceLocation(), depth,
1423           num_template_params, identifier_info, is_typename,
1424           parameter_pack_true));
1425     }
1426   }
1427   clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1428   TemplateParameterList *template_param_list = TemplateParameterList::Create(
1429       ast, SourceLocation(), SourceLocation(), template_param_decls,
1430       SourceLocation(), requires_clause);
1431   return template_param_list;
1432 }
1433 
1434 std::string TypeSystemClang::PrintTemplateParams(
1435     const TemplateParameterInfos &template_param_infos) {
1436   llvm::SmallVector<NamedDecl *, 8> ignore;
1437   clang::TemplateParameterList *template_param_list =
1438       CreateTemplateParameterList(getASTContext(), template_param_infos,
1439                                   ignore);
1440   llvm::SmallVector<clang::TemplateArgument, 2> args =
1441       template_param_infos.args;
1442   if (template_param_infos.hasParameterPack()) {
1443     args.append(template_param_infos.packed_args->args);
1444   }
1445   std::string str;
1446   llvm::raw_string_ostream os(str);
1447   clang::printTemplateArgumentList(os, args, GetTypePrintingPolicy(),
1448                                    template_param_list);
1449   return str;
1450 }
1451 
1452 clang::FunctionTemplateDecl *TypeSystemClang::CreateFunctionTemplateDecl(
1453     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1454     clang::FunctionDecl *func_decl,
1455     const TemplateParameterInfos &template_param_infos) {
1456   //    /// Create a function template node.
1457   ASTContext &ast = getASTContext();
1458 
1459   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1460   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1461       ast, template_param_infos, template_param_decls);
1462   FunctionTemplateDecl *func_tmpl_decl =
1463       FunctionTemplateDecl::CreateDeserialized(ast, 0);
1464   func_tmpl_decl->setDeclContext(decl_ctx);
1465   func_tmpl_decl->setLocation(func_decl->getLocation());
1466   func_tmpl_decl->setDeclName(func_decl->getDeclName());
1467   func_tmpl_decl->setTemplateParameters(template_param_list);
1468   func_tmpl_decl->init(func_decl);
1469   SetOwningModule(func_tmpl_decl, owning_module);
1470 
1471   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1472        i < template_param_decl_count; ++i) {
1473     // TODO: verify which decl context we should put template_param_decls into..
1474     template_param_decls[i]->setDeclContext(func_decl);
1475   }
1476   // Function templates inside a record need to have an access specifier.
1477   // It doesn't matter what access specifier we give the template as LLDB
1478   // anyway allows accessing everything inside a record.
1479   if (decl_ctx->isRecord())
1480     func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public);
1481 
1482   return func_tmpl_decl;
1483 }
1484 
1485 void TypeSystemClang::CreateFunctionTemplateSpecializationInfo(
1486     FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1487     const TemplateParameterInfos &infos) {
1488   TemplateArgumentList *template_args_ptr =
1489       TemplateArgumentList::CreateCopy(func_decl->getASTContext(), infos.args);
1490 
1491   func_decl->setFunctionTemplateSpecialization(func_tmpl_decl,
1492                                                template_args_ptr, nullptr);
1493 }
1494 
1495 /// Returns true if the given template parameter can represent the given value.
1496 /// For example, `typename T` can represent `int` but not integral values such
1497 /// as `int I = 3`.
1498 static bool TemplateParameterAllowsValue(NamedDecl *param,
1499                                          const TemplateArgument &value) {
1500   if (llvm::isa<TemplateTypeParmDecl>(param)) {
1501     // Compare the argument kind, i.e. ensure that <typename> != <int>.
1502     if (value.getKind() != TemplateArgument::Type)
1503       return false;
1504   } else if (auto *type_param =
1505                  llvm::dyn_cast<NonTypeTemplateParmDecl>(param)) {
1506     // Compare the argument kind, i.e. ensure that <typename> != <int>.
1507     if (!IsValueParam(value))
1508       return false;
1509     // Compare the integral type, i.e. ensure that <int> != <char>.
1510     if (type_param->getType() != value.getIntegralType())
1511       return false;
1512   } else {
1513     // There is no way to create other parameter decls at the moment, so we
1514     // can't reach this case during normal LLDB usage. Log that this happened
1515     // and assert.
1516     Log *log = GetLog(LLDBLog::Expressions);
1517     LLDB_LOG(log,
1518              "Don't know how to compare template parameter to passed"
1519              " value. Decl kind of parameter is: {0}",
1520              param->getDeclKindName());
1521     lldbassert(false && "Can't compare this TemplateParmDecl subclass");
1522     // In release builds just fall back to marking the parameter as not
1523     // accepting the value so that we don't try to fit an instantiation to a
1524     // template that doesn't fit. E.g., avoid that `S<1>` is being connected to
1525     // `template<typename T> struct S;`.
1526     return false;
1527   }
1528   return true;
1529 }
1530 
1531 /// Returns true if the given class template declaration could produce an
1532 /// instantiation with the specified values.
1533 /// For example, `<typename T>` allows the arguments `float`, but not for
1534 /// example `bool, float` or `3` (as an integer parameter value).
1535 static bool ClassTemplateAllowsToInstantiationArgs(
1536     ClassTemplateDecl *class_template_decl,
1537     const TypeSystemClang::TemplateParameterInfos &instantiation_values) {
1538 
1539   TemplateParameterList &params = *class_template_decl->getTemplateParameters();
1540 
1541   // Save some work by iterating only once over the found parameters and
1542   // calculate the information related to parameter packs.
1543 
1544   // Contains the first pack parameter (or non if there are none).
1545   std::optional<NamedDecl *> pack_parameter;
1546   // Contains the number of non-pack parameters.
1547   size_t non_pack_params = params.size();
1548   for (size_t i = 0; i < params.size(); ++i) {
1549     NamedDecl *param = params.getParam(i);
1550     if (param->isParameterPack()) {
1551       pack_parameter = param;
1552       non_pack_params = i;
1553       break;
1554     }
1555   }
1556 
1557   // The found template needs to have compatible non-pack template arguments.
1558   // E.g., ensure that <typename, typename> != <typename>.
1559   // The pack parameters are compared later.
1560   if (non_pack_params != instantiation_values.args.size())
1561     return false;
1562 
1563   // Ensure that <typename...> != <typename>.
1564   if (pack_parameter.has_value() != instantiation_values.hasParameterPack())
1565     return false;
1566 
1567   // Compare the first pack parameter that was found with the first pack
1568   // parameter value. The special case of having an empty parameter pack value
1569   // always fits to a pack parameter.
1570   // E.g., ensure that <int...> != <typename...>.
1571   if (pack_parameter && !instantiation_values.packed_args->args.empty() &&
1572       !TemplateParameterAllowsValue(
1573           *pack_parameter, instantiation_values.packed_args->args.front()))
1574     return false;
1575 
1576   // Compare all the non-pack parameters now.
1577   // E.g., ensure that <int> != <long>.
1578   for (const auto pair : llvm::zip_first(instantiation_values.args, params)) {
1579     const TemplateArgument &passed_arg = std::get<0>(pair);
1580     NamedDecl *found_param = std::get<1>(pair);
1581     if (!TemplateParameterAllowsValue(found_param, passed_arg))
1582       return false;
1583   }
1584 
1585   return class_template_decl;
1586 }
1587 
1588 ClassTemplateDecl *TypeSystemClang::CreateClassTemplateDecl(
1589     DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1590     lldb::AccessType access_type, llvm::StringRef class_name, int kind,
1591     const TemplateParameterInfos &template_param_infos) {
1592   ASTContext &ast = getASTContext();
1593 
1594   ClassTemplateDecl *class_template_decl = nullptr;
1595   if (decl_ctx == nullptr)
1596     decl_ctx = ast.getTranslationUnitDecl();
1597 
1598   IdentifierInfo &identifier_info = ast.Idents.get(class_name);
1599   DeclarationName decl_name(&identifier_info);
1600 
1601   // Search the AST for an existing ClassTemplateDecl that could be reused.
1602   clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1603   for (NamedDecl *decl : result) {
1604     class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1605     if (!class_template_decl)
1606       continue;
1607     // The class template has to be able to represents the instantiation
1608     // values we received. Without this we might end up putting an instantiation
1609     // with arguments such as <int, int> to a template such as:
1610     //     template<typename T> struct S;
1611     // Connecting the instantiation to an incompatible template could cause
1612     // problems later on.
1613     if (!ClassTemplateAllowsToInstantiationArgs(class_template_decl,
1614                                                 template_param_infos))
1615       continue;
1616     return class_template_decl;
1617   }
1618 
1619   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1620 
1621   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1622       ast, template_param_infos, template_param_decls);
1623 
1624   CXXRecordDecl *template_cxx_decl = CXXRecordDecl::CreateDeserialized(ast, 0);
1625   template_cxx_decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1626   // What decl context do we use here? TU? The actual decl context?
1627   template_cxx_decl->setDeclContext(decl_ctx);
1628   template_cxx_decl->setDeclName(decl_name);
1629   SetOwningModule(template_cxx_decl, owning_module);
1630 
1631   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1632        i < template_param_decl_count; ++i) {
1633     template_param_decls[i]->setDeclContext(template_cxx_decl);
1634   }
1635 
1636   // With templated classes, we say that a class is templated with
1637   // specializations, but that the bare class has no functions.
1638   // template_cxx_decl->startDefinition();
1639   // template_cxx_decl->completeDefinition();
1640 
1641   class_template_decl = ClassTemplateDecl::CreateDeserialized(ast, 0);
1642   // What decl context do we use here? TU? The actual decl context?
1643   class_template_decl->setDeclContext(decl_ctx);
1644   class_template_decl->setDeclName(decl_name);
1645   class_template_decl->setTemplateParameters(template_param_list);
1646   class_template_decl->init(template_cxx_decl);
1647   template_cxx_decl->setDescribedClassTemplate(class_template_decl);
1648   SetOwningModule(class_template_decl, owning_module);
1649 
1650   if (access_type != eAccessNone)
1651     class_template_decl->setAccess(
1652         ConvertAccessTypeToAccessSpecifier(access_type));
1653 
1654   decl_ctx->addDecl(class_template_decl);
1655 
1656   VerifyDecl(class_template_decl);
1657 
1658   return class_template_decl;
1659 }
1660 
1661 TemplateTemplateParmDecl *
1662 TypeSystemClang::CreateTemplateTemplateParmDecl(const char *template_name) {
1663   ASTContext &ast = getASTContext();
1664 
1665   auto *decl_ctx = ast.getTranslationUnitDecl();
1666 
1667   IdentifierInfo &identifier_info = ast.Idents.get(template_name);
1668   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1669 
1670   TypeSystemClang::TemplateParameterInfos template_param_infos;
1671   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1672       ast, template_param_infos, template_param_decls);
1673 
1674   // LLDB needs to create those decls only to be able to display a
1675   // type that includes a template template argument. Only the name matters for
1676   // this purpose, so we use dummy values for the other characteristics of the
1677   // type.
1678   return TemplateTemplateParmDecl::Create(
1679       ast, decl_ctx, SourceLocation(),
1680       /*Depth*/ 0, /*Position*/ 0,
1681       /*IsParameterPack*/ false, &identifier_info, template_param_list);
1682 }
1683 
1684 ClassTemplateSpecializationDecl *
1685 TypeSystemClang::CreateClassTemplateSpecializationDecl(
1686     DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1687     ClassTemplateDecl *class_template_decl, int kind,
1688     const TemplateParameterInfos &template_param_infos) {
1689   ASTContext &ast = getASTContext();
1690   llvm::SmallVector<clang::TemplateArgument, 2> args(
1691       template_param_infos.args.size() +
1692       (template_param_infos.packed_args ? 1 : 0));
1693   std::copy(template_param_infos.args.begin(), template_param_infos.args.end(),
1694             args.begin());
1695   if (template_param_infos.packed_args) {
1696     args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1697         ast, template_param_infos.packed_args->args);
1698   }
1699   ClassTemplateSpecializationDecl *class_template_specialization_decl =
1700       ClassTemplateSpecializationDecl::CreateDeserialized(ast, 0);
1701   class_template_specialization_decl->setTagKind(
1702       static_cast<TagDecl::TagKind>(kind));
1703   class_template_specialization_decl->setDeclContext(decl_ctx);
1704   class_template_specialization_decl->setInstantiationOf(class_template_decl);
1705   class_template_specialization_decl->setTemplateArgs(
1706       TemplateArgumentList::CreateCopy(ast, args));
1707   ast.getTypeDeclType(class_template_specialization_decl, nullptr);
1708   class_template_specialization_decl->setDeclName(
1709       class_template_decl->getDeclName());
1710   SetOwningModule(class_template_specialization_decl, owning_module);
1711   decl_ctx->addDecl(class_template_specialization_decl);
1712 
1713   class_template_specialization_decl->setSpecializationKind(
1714       TSK_ExplicitSpecialization);
1715 
1716   return class_template_specialization_decl;
1717 }
1718 
1719 CompilerType TypeSystemClang::CreateClassTemplateSpecializationType(
1720     ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1721   if (class_template_specialization_decl) {
1722     ASTContext &ast = getASTContext();
1723     return GetType(ast.getTagDeclType(class_template_specialization_decl));
1724   }
1725   return CompilerType();
1726 }
1727 
1728 static inline bool check_op_param(bool is_method,
1729                                   clang::OverloadedOperatorKind op_kind,
1730                                   bool unary, bool binary,
1731                                   uint32_t num_params) {
1732   // Special-case call since it can take any number of operands
1733   if (op_kind == OO_Call)
1734     return true;
1735 
1736   // The parameter count doesn't include "this"
1737   if (is_method)
1738     ++num_params;
1739   if (num_params == 1)
1740     return unary;
1741   if (num_params == 2)
1742     return binary;
1743   else
1744     return false;
1745 }
1746 
1747 bool TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
1748     bool is_method, clang::OverloadedOperatorKind op_kind,
1749     uint32_t num_params) {
1750   switch (op_kind) {
1751   default:
1752     break;
1753   // C++ standard allows any number of arguments to new/delete
1754   case OO_New:
1755   case OO_Array_New:
1756   case OO_Delete:
1757   case OO_Array_Delete:
1758     return true;
1759   }
1760 
1761 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
1762   case OO_##Name:                                                              \
1763     return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1764   switch (op_kind) {
1765 #include "clang/Basic/OperatorKinds.def"
1766   default:
1767     break;
1768   }
1769   return false;
1770 }
1771 
1772 clang::AccessSpecifier
1773 TypeSystemClang::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
1774                                        clang::AccessSpecifier rhs) {
1775   // Make the access equal to the stricter of the field and the nested field's
1776   // access
1777   if (lhs == AS_none || rhs == AS_none)
1778     return AS_none;
1779   if (lhs == AS_private || rhs == AS_private)
1780     return AS_private;
1781   if (lhs == AS_protected || rhs == AS_protected)
1782     return AS_protected;
1783   return AS_public;
1784 }
1785 
1786 bool TypeSystemClang::FieldIsBitfield(FieldDecl *field,
1787                                       uint32_t &bitfield_bit_size) {
1788   ASTContext &ast = getASTContext();
1789   if (field == nullptr)
1790     return false;
1791 
1792   if (field->isBitField()) {
1793     Expr *bit_width_expr = field->getBitWidth();
1794     if (bit_width_expr) {
1795       if (std::optional<llvm::APSInt> bit_width_apsint =
1796               bit_width_expr->getIntegerConstantExpr(ast)) {
1797         bitfield_bit_size = bit_width_apsint->getLimitedValue(UINT32_MAX);
1798         return true;
1799       }
1800     }
1801   }
1802   return false;
1803 }
1804 
1805 bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) {
1806   if (record_decl == nullptr)
1807     return false;
1808 
1809   if (!record_decl->field_empty())
1810     return true;
1811 
1812   // No fields, lets check this is a CXX record and check the base classes
1813   const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1814   if (cxx_record_decl) {
1815     CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1816     for (base_class = cxx_record_decl->bases_begin(),
1817         base_class_end = cxx_record_decl->bases_end();
1818          base_class != base_class_end; ++base_class) {
1819       const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1820           base_class->getType()->getAs<RecordType>()->getDecl());
1821       if (RecordHasFields(base_class_decl))
1822         return true;
1823     }
1824   }
1825 
1826   // We always want forcefully completed types to show up so we can print a
1827   // message in the summary that indicates that the type is incomplete.
1828   // This will help users know when they are running into issues with
1829   // -flimit-debug-info instead of just seeing nothing if this is a base class
1830   // (since we were hiding empty base classes), or nothing when you turn open
1831   // an valiable whose type was incomplete.
1832   ClangASTMetadata *meta_data = GetMetadata(record_decl);
1833   if (meta_data && meta_data->IsForcefullyCompleted())
1834     return true;
1835 
1836   return false;
1837 }
1838 
1839 #pragma mark Objective-C Classes
1840 
1841 CompilerType TypeSystemClang::CreateObjCClass(
1842     llvm::StringRef name, clang::DeclContext *decl_ctx,
1843     OptionalClangModuleID owning_module, bool isForwardDecl, bool isInternal,
1844     ClangASTMetadata *metadata) {
1845   ASTContext &ast = getASTContext();
1846   assert(!name.empty());
1847   if (!decl_ctx)
1848     decl_ctx = ast.getTranslationUnitDecl();
1849 
1850   ObjCInterfaceDecl *decl = ObjCInterfaceDecl::CreateDeserialized(ast, 0);
1851   decl->setDeclContext(decl_ctx);
1852   decl->setDeclName(&ast.Idents.get(name));
1853   /*isForwardDecl,*/
1854   decl->setImplicit(isInternal);
1855   SetOwningModule(decl, owning_module);
1856 
1857   if (metadata)
1858     SetMetadata(decl, *metadata);
1859 
1860   return GetType(ast.getObjCInterfaceType(decl));
1861 }
1862 
1863 bool TypeSystemClang::BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1864   return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl());
1865 }
1866 
1867 uint32_t
1868 TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1869                                    bool omit_empty_base_classes) {
1870   uint32_t num_bases = 0;
1871   if (cxx_record_decl) {
1872     if (omit_empty_base_classes) {
1873       CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1874       for (base_class = cxx_record_decl->bases_begin(),
1875           base_class_end = cxx_record_decl->bases_end();
1876            base_class != base_class_end; ++base_class) {
1877         // Skip empty base classes
1878         if (BaseSpecifierIsEmpty(base_class))
1879           continue;
1880         ++num_bases;
1881       }
1882     } else
1883       num_bases = cxx_record_decl->getNumBases();
1884   }
1885   return num_bases;
1886 }
1887 
1888 #pragma mark Namespace Declarations
1889 
1890 NamespaceDecl *TypeSystemClang::GetUniqueNamespaceDeclaration(
1891     const char *name, clang::DeclContext *decl_ctx,
1892     OptionalClangModuleID owning_module, bool is_inline) {
1893   NamespaceDecl *namespace_decl = nullptr;
1894   ASTContext &ast = getASTContext();
1895   TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl();
1896   if (!decl_ctx)
1897     decl_ctx = translation_unit_decl;
1898 
1899   if (name) {
1900     IdentifierInfo &identifier_info = ast.Idents.get(name);
1901     DeclarationName decl_name(&identifier_info);
1902     clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1903     for (NamedDecl *decl : result) {
1904       namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1905       if (namespace_decl)
1906         return namespace_decl;
1907     }
1908 
1909     namespace_decl = NamespaceDecl::Create(ast, decl_ctx, is_inline,
1910                                            SourceLocation(), SourceLocation(),
1911                                            &identifier_info, nullptr, false);
1912 
1913     decl_ctx->addDecl(namespace_decl);
1914   } else {
1915     if (decl_ctx == translation_unit_decl) {
1916       namespace_decl = translation_unit_decl->getAnonymousNamespace();
1917       if (namespace_decl)
1918         return namespace_decl;
1919 
1920       namespace_decl =
1921           NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1922                                 SourceLocation(), nullptr, nullptr, false);
1923       translation_unit_decl->setAnonymousNamespace(namespace_decl);
1924       translation_unit_decl->addDecl(namespace_decl);
1925       assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
1926     } else {
1927       NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1928       if (parent_namespace_decl) {
1929         namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1930         if (namespace_decl)
1931           return namespace_decl;
1932         namespace_decl =
1933             NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1934                                   SourceLocation(), nullptr, nullptr, false);
1935         parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1936         parent_namespace_decl->addDecl(namespace_decl);
1937         assert(namespace_decl ==
1938                parent_namespace_decl->getAnonymousNamespace());
1939       } else {
1940         assert(false && "GetUniqueNamespaceDeclaration called with no name and "
1941                         "no namespace as decl_ctx");
1942       }
1943     }
1944   }
1945   // Note: namespaces can span multiple modules, so perhaps this isn't a good
1946   // idea.
1947   SetOwningModule(namespace_decl, owning_module);
1948 
1949   VerifyDecl(namespace_decl);
1950   return namespace_decl;
1951 }
1952 
1953 clang::BlockDecl *
1954 TypeSystemClang::CreateBlockDeclaration(clang::DeclContext *ctx,
1955                                         OptionalClangModuleID owning_module) {
1956   if (ctx) {
1957     clang::BlockDecl *decl =
1958         clang::BlockDecl::CreateDeserialized(getASTContext(), 0);
1959     decl->setDeclContext(ctx);
1960     ctx->addDecl(decl);
1961     SetOwningModule(decl, owning_module);
1962     return decl;
1963   }
1964   return nullptr;
1965 }
1966 
1967 clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1968                                         clang::DeclContext *right,
1969                                         clang::DeclContext *root) {
1970   if (root == nullptr)
1971     return nullptr;
1972 
1973   std::set<clang::DeclContext *> path_left;
1974   for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
1975     path_left.insert(d);
1976 
1977   for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
1978     if (path_left.find(d) != path_left.end())
1979       return d;
1980 
1981   return nullptr;
1982 }
1983 
1984 clang::UsingDirectiveDecl *TypeSystemClang::CreateUsingDirectiveDeclaration(
1985     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1986     clang::NamespaceDecl *ns_decl) {
1987   if (decl_ctx && ns_decl) {
1988     auto *translation_unit = getASTContext().getTranslationUnitDecl();
1989     clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
1990           getASTContext(), decl_ctx, clang::SourceLocation(),
1991           clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
1992           clang::SourceLocation(), ns_decl,
1993           FindLCABetweenDecls(decl_ctx, ns_decl,
1994                               translation_unit));
1995       decl_ctx->addDecl(using_decl);
1996       SetOwningModule(using_decl, owning_module);
1997       return using_decl;
1998   }
1999   return nullptr;
2000 }
2001 
2002 clang::UsingDecl *
2003 TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
2004                                         OptionalClangModuleID owning_module,
2005                                         clang::NamedDecl *target) {
2006   if (current_decl_ctx && target) {
2007     clang::UsingDecl *using_decl = clang::UsingDecl::Create(
2008         getASTContext(), current_decl_ctx, clang::SourceLocation(),
2009         clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
2010     SetOwningModule(using_decl, owning_module);
2011     clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
2012         getASTContext(), current_decl_ctx, clang::SourceLocation(),
2013         target->getDeclName(), using_decl, target);
2014     SetOwningModule(shadow_decl, owning_module);
2015     using_decl->addShadowDecl(shadow_decl);
2016     current_decl_ctx->addDecl(using_decl);
2017     return using_decl;
2018   }
2019   return nullptr;
2020 }
2021 
2022 clang::VarDecl *TypeSystemClang::CreateVariableDeclaration(
2023     clang::DeclContext *decl_context, OptionalClangModuleID owning_module,
2024     const char *name, clang::QualType type) {
2025   if (decl_context) {
2026     clang::VarDecl *var_decl =
2027         clang::VarDecl::CreateDeserialized(getASTContext(), 0);
2028     var_decl->setDeclContext(decl_context);
2029     if (name && name[0])
2030       var_decl->setDeclName(&getASTContext().Idents.getOwn(name));
2031     var_decl->setType(type);
2032     SetOwningModule(var_decl, owning_module);
2033     var_decl->setAccess(clang::AS_public);
2034     decl_context->addDecl(var_decl);
2035     return var_decl;
2036   }
2037   return nullptr;
2038 }
2039 
2040 lldb::opaque_compiler_type_t
2041 TypeSystemClang::GetOpaqueCompilerType(clang::ASTContext *ast,
2042                                        lldb::BasicType basic_type) {
2043   switch (basic_type) {
2044   case eBasicTypeVoid:
2045     return ast->VoidTy.getAsOpaquePtr();
2046   case eBasicTypeChar:
2047     return ast->CharTy.getAsOpaquePtr();
2048   case eBasicTypeSignedChar:
2049     return ast->SignedCharTy.getAsOpaquePtr();
2050   case eBasicTypeUnsignedChar:
2051     return ast->UnsignedCharTy.getAsOpaquePtr();
2052   case eBasicTypeWChar:
2053     return ast->getWCharType().getAsOpaquePtr();
2054   case eBasicTypeSignedWChar:
2055     return ast->getSignedWCharType().getAsOpaquePtr();
2056   case eBasicTypeUnsignedWChar:
2057     return ast->getUnsignedWCharType().getAsOpaquePtr();
2058   case eBasicTypeChar8:
2059     return ast->Char8Ty.getAsOpaquePtr();
2060   case eBasicTypeChar16:
2061     return ast->Char16Ty.getAsOpaquePtr();
2062   case eBasicTypeChar32:
2063     return ast->Char32Ty.getAsOpaquePtr();
2064   case eBasicTypeShort:
2065     return ast->ShortTy.getAsOpaquePtr();
2066   case eBasicTypeUnsignedShort:
2067     return ast->UnsignedShortTy.getAsOpaquePtr();
2068   case eBasicTypeInt:
2069     return ast->IntTy.getAsOpaquePtr();
2070   case eBasicTypeUnsignedInt:
2071     return ast->UnsignedIntTy.getAsOpaquePtr();
2072   case eBasicTypeLong:
2073     return ast->LongTy.getAsOpaquePtr();
2074   case eBasicTypeUnsignedLong:
2075     return ast->UnsignedLongTy.getAsOpaquePtr();
2076   case eBasicTypeLongLong:
2077     return ast->LongLongTy.getAsOpaquePtr();
2078   case eBasicTypeUnsignedLongLong:
2079     return ast->UnsignedLongLongTy.getAsOpaquePtr();
2080   case eBasicTypeInt128:
2081     return ast->Int128Ty.getAsOpaquePtr();
2082   case eBasicTypeUnsignedInt128:
2083     return ast->UnsignedInt128Ty.getAsOpaquePtr();
2084   case eBasicTypeBool:
2085     return ast->BoolTy.getAsOpaquePtr();
2086   case eBasicTypeHalf:
2087     return ast->HalfTy.getAsOpaquePtr();
2088   case eBasicTypeFloat:
2089     return ast->FloatTy.getAsOpaquePtr();
2090   case eBasicTypeDouble:
2091     return ast->DoubleTy.getAsOpaquePtr();
2092   case eBasicTypeLongDouble:
2093     return ast->LongDoubleTy.getAsOpaquePtr();
2094   case eBasicTypeFloatComplex:
2095     return ast->getComplexType(ast->FloatTy).getAsOpaquePtr();
2096   case eBasicTypeDoubleComplex:
2097     return ast->getComplexType(ast->DoubleTy).getAsOpaquePtr();
2098   case eBasicTypeLongDoubleComplex:
2099     return ast->getComplexType(ast->LongDoubleTy).getAsOpaquePtr();
2100   case eBasicTypeObjCID:
2101     return ast->getObjCIdType().getAsOpaquePtr();
2102   case eBasicTypeObjCClass:
2103     return ast->getObjCClassType().getAsOpaquePtr();
2104   case eBasicTypeObjCSel:
2105     return ast->getObjCSelType().getAsOpaquePtr();
2106   case eBasicTypeNullPtr:
2107     return ast->NullPtrTy.getAsOpaquePtr();
2108   default:
2109     return nullptr;
2110   }
2111 }
2112 
2113 #pragma mark Function Types
2114 
2115 clang::DeclarationName
2116 TypeSystemClang::GetDeclarationName(llvm::StringRef name,
2117                                     const CompilerType &function_clang_type) {
2118   clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
2119   if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
2120     return DeclarationName(&getASTContext().Idents.get(
2121         name)); // Not operator, but a regular function.
2122 
2123   // Check the number of operator parameters. Sometimes we have seen bad DWARF
2124   // that doesn't correctly describe operators and if we try to create a method
2125   // and add it to the class, clang will assert and crash, so we need to make
2126   // sure things are acceptable.
2127   clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
2128   const clang::FunctionProtoType *function_type =
2129       llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
2130   if (function_type == nullptr)
2131     return clang::DeclarationName();
2132 
2133   const bool is_method = false;
2134   const unsigned int num_params = function_type->getNumParams();
2135   if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
2136           is_method, op_kind, num_params))
2137     return clang::DeclarationName();
2138 
2139   return getASTContext().DeclarationNames.getCXXOperatorName(op_kind);
2140 }
2141 
2142 PrintingPolicy TypeSystemClang::GetTypePrintingPolicy() {
2143   clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
2144   printing_policy.SuppressTagKeyword = true;
2145   // Inline namespaces are important for some type formatters (e.g., libc++
2146   // and libstdc++ are differentiated by their inline namespaces).
2147   printing_policy.SuppressInlineNamespace = false;
2148   printing_policy.SuppressUnwrittenScope = false;
2149   // Default arguments are also always important for type formatters. Otherwise
2150   // we would need to always specify two type names for the setups where we do
2151   // know the default arguments and where we don't know default arguments.
2152   //
2153   // For example, without this we would need to have formatters for both:
2154   //   std::basic_string<char>
2155   // and
2156   //   std::basic_string<char, std::char_traits<char>, std::allocator<char> >
2157   // to support setups where LLDB was able to reconstruct default arguments
2158   // (and we then would have suppressed them from the type name) and also setups
2159   // where LLDB wasn't able to reconstruct the default arguments.
2160   printing_policy.SuppressDefaultTemplateArgs = false;
2161   return printing_policy;
2162 }
2163 
2164 std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl,
2165                                                 bool qualified) {
2166   clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
2167   std::string result;
2168   llvm::raw_string_ostream os(result);
2169   named_decl->getNameForDiagnostic(os, printing_policy, qualified);
2170   return result;
2171 }
2172 
2173 FunctionDecl *TypeSystemClang::CreateFunctionDeclaration(
2174     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2175     llvm::StringRef name, const CompilerType &function_clang_type,
2176     clang::StorageClass storage, bool is_inline) {
2177   FunctionDecl *func_decl = nullptr;
2178   ASTContext &ast = getASTContext();
2179   if (!decl_ctx)
2180     decl_ctx = ast.getTranslationUnitDecl();
2181 
2182   const bool hasWrittenPrototype = true;
2183   const bool isConstexprSpecified = false;
2184 
2185   clang::DeclarationName declarationName =
2186       GetDeclarationName(name, function_clang_type);
2187   func_decl = FunctionDecl::CreateDeserialized(ast, 0);
2188   func_decl->setDeclContext(decl_ctx);
2189   func_decl->setDeclName(declarationName);
2190   func_decl->setType(ClangUtil::GetQualType(function_clang_type));
2191   func_decl->setStorageClass(storage);
2192   func_decl->setInlineSpecified(is_inline);
2193   func_decl->setHasWrittenPrototype(hasWrittenPrototype);
2194   func_decl->setConstexprKind(isConstexprSpecified
2195                                   ? ConstexprSpecKind::Constexpr
2196                                   : ConstexprSpecKind::Unspecified);
2197   SetOwningModule(func_decl, owning_module);
2198   decl_ctx->addDecl(func_decl);
2199 
2200   VerifyDecl(func_decl);
2201 
2202   return func_decl;
2203 }
2204 
2205 CompilerType TypeSystemClang::CreateFunctionType(
2206     const CompilerType &result_type, const CompilerType *args,
2207     unsigned num_args, bool is_variadic, unsigned type_quals,
2208     clang::CallingConv cc, clang::RefQualifierKind ref_qual) {
2209   if (!result_type || !ClangUtil::IsClangType(result_type))
2210     return CompilerType(); // invalid return type
2211 
2212   std::vector<QualType> qual_type_args;
2213   if (num_args > 0 && args == nullptr)
2214     return CompilerType(); // invalid argument array passed in
2215 
2216   // Verify that all arguments are valid and the right type
2217   for (unsigned i = 0; i < num_args; ++i) {
2218     if (args[i]) {
2219       // Make sure we have a clang type in args[i] and not a type from another
2220       // language whose name might match
2221       const bool is_clang_type = ClangUtil::IsClangType(args[i]);
2222       lldbassert(is_clang_type);
2223       if (is_clang_type)
2224         qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
2225       else
2226         return CompilerType(); //  invalid argument type (must be a clang type)
2227     } else
2228       return CompilerType(); // invalid argument type (empty)
2229   }
2230 
2231   // TODO: Detect calling convention in DWARF?
2232   FunctionProtoType::ExtProtoInfo proto_info;
2233   proto_info.ExtInfo = cc;
2234   proto_info.Variadic = is_variadic;
2235   proto_info.ExceptionSpec = EST_None;
2236   proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals);
2237   proto_info.RefQualifier = ref_qual;
2238 
2239   return GetType(getASTContext().getFunctionType(
2240       ClangUtil::GetQualType(result_type), qual_type_args, proto_info));
2241 }
2242 
2243 ParmVarDecl *TypeSystemClang::CreateParameterDeclaration(
2244     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2245     const char *name, const CompilerType &param_type, int storage,
2246     bool add_decl) {
2247   ASTContext &ast = getASTContext();
2248   auto *decl = ParmVarDecl::CreateDeserialized(ast, 0);
2249   decl->setDeclContext(decl_ctx);
2250   if (name && name[0])
2251     decl->setDeclName(&ast.Idents.get(name));
2252   decl->setType(ClangUtil::GetQualType(param_type));
2253   decl->setStorageClass(static_cast<clang::StorageClass>(storage));
2254   SetOwningModule(decl, owning_module);
2255   if (add_decl)
2256     decl_ctx->addDecl(decl);
2257 
2258   return decl;
2259 }
2260 
2261 void TypeSystemClang::SetFunctionParameters(
2262     FunctionDecl *function_decl, llvm::ArrayRef<ParmVarDecl *> params) {
2263   if (function_decl)
2264     function_decl->setParams(params);
2265 }
2266 
2267 CompilerType
2268 TypeSystemClang::CreateBlockPointerType(const CompilerType &function_type) {
2269   QualType block_type = m_ast_up->getBlockPointerType(
2270       clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2271 
2272   return GetType(block_type);
2273 }
2274 
2275 #pragma mark Array Types
2276 
2277 CompilerType TypeSystemClang::CreateArrayType(const CompilerType &element_type,
2278                                               size_t element_count,
2279                                               bool is_vector) {
2280   if (element_type.IsValid()) {
2281     ASTContext &ast = getASTContext();
2282 
2283     if (is_vector) {
2284       return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type),
2285                                           element_count));
2286     } else {
2287 
2288       llvm::APInt ap_element_count(64, element_count);
2289       if (element_count == 0) {
2290         return GetType(ast.getIncompleteArrayType(
2291             ClangUtil::GetQualType(element_type), clang::ArrayType::Normal, 0));
2292       } else {
2293         return GetType(ast.getConstantArrayType(
2294             ClangUtil::GetQualType(element_type), ap_element_count, nullptr,
2295             clang::ArrayType::Normal, 0));
2296       }
2297     }
2298   }
2299   return CompilerType();
2300 }
2301 
2302 CompilerType TypeSystemClang::CreateStructForIdentifier(
2303     ConstString type_name,
2304     const std::initializer_list<std::pair<const char *, CompilerType>>
2305         &type_fields,
2306     bool packed) {
2307   CompilerType type;
2308   if (!type_name.IsEmpty() &&
2309       (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2310           .IsValid()) {
2311     lldbassert(0 && "Trying to create a type for an existing name");
2312     return type;
2313   }
2314 
2315   type = CreateRecordType(nullptr, OptionalClangModuleID(), lldb::eAccessPublic,
2316                           type_name.GetCString(), clang::TTK_Struct,
2317                           lldb::eLanguageTypeC);
2318   StartTagDeclarationDefinition(type);
2319   for (const auto &field : type_fields)
2320     AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2321                          0);
2322   if (packed)
2323     SetIsPacked(type);
2324   CompleteTagDeclarationDefinition(type);
2325   return type;
2326 }
2327 
2328 CompilerType TypeSystemClang::GetOrCreateStructForIdentifier(
2329     ConstString type_name,
2330     const std::initializer_list<std::pair<const char *, CompilerType>>
2331         &type_fields,
2332     bool packed) {
2333   CompilerType type;
2334   if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2335     return type;
2336 
2337   return CreateStructForIdentifier(type_name, type_fields, packed);
2338 }
2339 
2340 #pragma mark Enumeration Types
2341 
2342 CompilerType TypeSystemClang::CreateEnumerationType(
2343     llvm::StringRef name, clang::DeclContext *decl_ctx,
2344     OptionalClangModuleID owning_module, const Declaration &decl,
2345     const CompilerType &integer_clang_type, bool is_scoped) {
2346   // TODO: Do something intelligent with the Declaration object passed in
2347   // like maybe filling in the SourceLocation with it...
2348   ASTContext &ast = getASTContext();
2349 
2350   // TODO: ask about these...
2351   //    const bool IsFixed = false;
2352   EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, 0);
2353   enum_decl->setDeclContext(decl_ctx);
2354   if (!name.empty())
2355     enum_decl->setDeclName(&ast.Idents.get(name));
2356   enum_decl->setScoped(is_scoped);
2357   enum_decl->setScopedUsingClassTag(is_scoped);
2358   enum_decl->setFixed(false);
2359   SetOwningModule(enum_decl, owning_module);
2360   if (decl_ctx)
2361     decl_ctx->addDecl(enum_decl);
2362 
2363   // TODO: check if we should be setting the promotion type too?
2364   enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2365 
2366   enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2367 
2368   return GetType(ast.getTagDeclType(enum_decl));
2369 }
2370 
2371 CompilerType TypeSystemClang::GetIntTypeFromBitSize(size_t bit_size,
2372                                                     bool is_signed) {
2373   clang::ASTContext &ast = getASTContext();
2374 
2375   if (is_signed) {
2376     if (bit_size == ast.getTypeSize(ast.SignedCharTy))
2377       return GetType(ast.SignedCharTy);
2378 
2379     if (bit_size == ast.getTypeSize(ast.ShortTy))
2380       return GetType(ast.ShortTy);
2381 
2382     if (bit_size == ast.getTypeSize(ast.IntTy))
2383       return GetType(ast.IntTy);
2384 
2385     if (bit_size == ast.getTypeSize(ast.LongTy))
2386       return GetType(ast.LongTy);
2387 
2388     if (bit_size == ast.getTypeSize(ast.LongLongTy))
2389       return GetType(ast.LongLongTy);
2390 
2391     if (bit_size == ast.getTypeSize(ast.Int128Ty))
2392       return GetType(ast.Int128Ty);
2393   } else {
2394     if (bit_size == ast.getTypeSize(ast.UnsignedCharTy))
2395       return GetType(ast.UnsignedCharTy);
2396 
2397     if (bit_size == ast.getTypeSize(ast.UnsignedShortTy))
2398       return GetType(ast.UnsignedShortTy);
2399 
2400     if (bit_size == ast.getTypeSize(ast.UnsignedIntTy))
2401       return GetType(ast.UnsignedIntTy);
2402 
2403     if (bit_size == ast.getTypeSize(ast.UnsignedLongTy))
2404       return GetType(ast.UnsignedLongTy);
2405 
2406     if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy))
2407       return GetType(ast.UnsignedLongLongTy);
2408 
2409     if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty))
2410       return GetType(ast.UnsignedInt128Ty);
2411   }
2412   return CompilerType();
2413 }
2414 
2415 CompilerType TypeSystemClang::GetPointerSizedIntType(bool is_signed) {
2416   return GetIntTypeFromBitSize(
2417       getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed);
2418 }
2419 
2420 void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2421   if (decl_ctx) {
2422     DumpDeclContextHiearchy(decl_ctx->getParent());
2423 
2424     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2425     if (named_decl) {
2426       printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2427              named_decl->getDeclName().getAsString().c_str());
2428     } else {
2429       printf("%20s\n", decl_ctx->getDeclKindName());
2430     }
2431   }
2432 }
2433 
2434 void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) {
2435   if (decl == nullptr)
2436     return;
2437   DumpDeclContextHiearchy(decl->getDeclContext());
2438 
2439   clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2440   if (record_decl) {
2441     printf("%20s: %s%s\n", decl->getDeclKindName(),
2442            record_decl->getDeclName().getAsString().c_str(),
2443            record_decl->isInjectedClassName() ? " (injected class name)" : "");
2444 
2445   } else {
2446     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2447     if (named_decl) {
2448       printf("%20s: %s\n", decl->getDeclKindName(),
2449              named_decl->getDeclName().getAsString().c_str());
2450     } else {
2451       printf("%20s\n", decl->getDeclKindName());
2452     }
2453   }
2454 }
2455 
2456 bool TypeSystemClang::DeclsAreEquivalent(clang::Decl *lhs_decl,
2457                                          clang::Decl *rhs_decl) {
2458   if (lhs_decl && rhs_decl) {
2459     // Make sure the decl kinds match first
2460     const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind();
2461     const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind();
2462 
2463     if (lhs_decl_kind == rhs_decl_kind) {
2464       // Now check that the decl contexts kinds are all equivalent before we
2465       // have to check any names of the decl contexts...
2466       clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext();
2467       clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext();
2468       if (lhs_decl_ctx && rhs_decl_ctx) {
2469         while (true) {
2470           if (lhs_decl_ctx && rhs_decl_ctx) {
2471             const clang::Decl::Kind lhs_decl_ctx_kind =
2472                 lhs_decl_ctx->getDeclKind();
2473             const clang::Decl::Kind rhs_decl_ctx_kind =
2474                 rhs_decl_ctx->getDeclKind();
2475             if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) {
2476               lhs_decl_ctx = lhs_decl_ctx->getParent();
2477               rhs_decl_ctx = rhs_decl_ctx->getParent();
2478 
2479               if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr)
2480                 break;
2481             } else
2482               return false;
2483           } else
2484             return false;
2485         }
2486 
2487         // Now make sure the name of the decls match
2488         clang::NamedDecl *lhs_named_decl =
2489             llvm::dyn_cast<clang::NamedDecl>(lhs_decl);
2490         clang::NamedDecl *rhs_named_decl =
2491             llvm::dyn_cast<clang::NamedDecl>(rhs_decl);
2492         if (lhs_named_decl && rhs_named_decl) {
2493           clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName();
2494           clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName();
2495           if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2496             if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2497               return false;
2498           } else
2499             return false;
2500         } else
2501           return false;
2502 
2503         // We know that the decl context kinds all match, so now we need to
2504         // make sure the names match as well
2505         lhs_decl_ctx = lhs_decl->getDeclContext();
2506         rhs_decl_ctx = rhs_decl->getDeclContext();
2507         while (true) {
2508           switch (lhs_decl_ctx->getDeclKind()) {
2509           case clang::Decl::TranslationUnit:
2510             // We don't care about the translation unit names
2511             return true;
2512           default: {
2513             clang::NamedDecl *lhs_named_decl =
2514                 llvm::dyn_cast<clang::NamedDecl>(lhs_decl_ctx);
2515             clang::NamedDecl *rhs_named_decl =
2516                 llvm::dyn_cast<clang::NamedDecl>(rhs_decl_ctx);
2517             if (lhs_named_decl && rhs_named_decl) {
2518               clang::DeclarationName lhs_decl_name =
2519                   lhs_named_decl->getDeclName();
2520               clang::DeclarationName rhs_decl_name =
2521                   rhs_named_decl->getDeclName();
2522               if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2523                 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2524                   return false;
2525               } else
2526                 return false;
2527             } else
2528               return false;
2529           } break;
2530           }
2531           lhs_decl_ctx = lhs_decl_ctx->getParent();
2532           rhs_decl_ctx = rhs_decl_ctx->getParent();
2533         }
2534       }
2535     }
2536   }
2537   return false;
2538 }
2539 bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast,
2540                                       clang::Decl *decl) {
2541   if (!decl)
2542     return false;
2543 
2544   ExternalASTSource *ast_source = ast->getExternalSource();
2545 
2546   if (!ast_source)
2547     return false;
2548 
2549   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2550     if (tag_decl->isCompleteDefinition())
2551       return true;
2552 
2553     if (!tag_decl->hasExternalLexicalStorage())
2554       return false;
2555 
2556     ast_source->CompleteType(tag_decl);
2557 
2558     return !tag_decl->getTypeForDecl()->isIncompleteType();
2559   } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2560                  llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2561     if (objc_interface_decl->getDefinition())
2562       return true;
2563 
2564     if (!objc_interface_decl->hasExternalLexicalStorage())
2565       return false;
2566 
2567     ast_source->CompleteType(objc_interface_decl);
2568 
2569     return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2570   } else {
2571     return false;
2572   }
2573 }
2574 
2575 void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl,
2576                                           user_id_t user_id) {
2577   ClangASTMetadata meta_data;
2578   meta_data.SetUserID(user_id);
2579   SetMetadata(decl, meta_data);
2580 }
2581 
2582 void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type,
2583                                           user_id_t user_id) {
2584   ClangASTMetadata meta_data;
2585   meta_data.SetUserID(user_id);
2586   SetMetadata(type, meta_data);
2587 }
2588 
2589 void TypeSystemClang::SetMetadata(const clang::Decl *object,
2590                                   ClangASTMetadata &metadata) {
2591   m_decl_metadata[object] = metadata;
2592 }
2593 
2594 void TypeSystemClang::SetMetadata(const clang::Type *object,
2595                                   ClangASTMetadata &metadata) {
2596   m_type_metadata[object] = metadata;
2597 }
2598 
2599 ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Decl *object) {
2600   auto It = m_decl_metadata.find(object);
2601   if (It != m_decl_metadata.end())
2602     return &It->second;
2603   return nullptr;
2604 }
2605 
2606 ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Type *object) {
2607   auto It = m_type_metadata.find(object);
2608   if (It != m_type_metadata.end())
2609     return &It->second;
2610   return nullptr;
2611 }
2612 
2613 void TypeSystemClang::SetCXXRecordDeclAccess(const clang::CXXRecordDecl *object,
2614                                              clang::AccessSpecifier access) {
2615   if (access == clang::AccessSpecifier::AS_none)
2616     m_cxx_record_decl_access.erase(object);
2617   else
2618     m_cxx_record_decl_access[object] = access;
2619 }
2620 
2621 clang::AccessSpecifier
2622 TypeSystemClang::GetCXXRecordDeclAccess(const clang::CXXRecordDecl *object) {
2623   auto It = m_cxx_record_decl_access.find(object);
2624   if (It != m_cxx_record_decl_access.end())
2625     return It->second;
2626   return clang::AccessSpecifier::AS_none;
2627 }
2628 
2629 clang::DeclContext *
2630 TypeSystemClang::GetDeclContextForType(const CompilerType &type) {
2631   return GetDeclContextForType(ClangUtil::GetQualType(type));
2632 }
2633 
2634 /// Aggressively desugar the provided type, skipping past various kinds of
2635 /// syntactic sugar and other constructs one typically wants to ignore.
2636 /// The \p mask argument allows one to skip certain kinds of simplifications,
2637 /// when one wishes to handle a certain kind of type directly.
2638 static QualType
2639 RemoveWrappingTypes(QualType type, ArrayRef<clang::Type::TypeClass> mask = {}) {
2640   while (true) {
2641     if (find(mask, type->getTypeClass()) != mask.end())
2642       return type;
2643     switch (type->getTypeClass()) {
2644     // This is not fully correct as _Atomic is more than sugar, but it is
2645     // sufficient for the purposes we care about.
2646     case clang::Type::Atomic:
2647       type = cast<clang::AtomicType>(type)->getValueType();
2648       break;
2649     case clang::Type::Auto:
2650     case clang::Type::Decltype:
2651     case clang::Type::Elaborated:
2652     case clang::Type::Paren:
2653     case clang::Type::SubstTemplateTypeParm:
2654     case clang::Type::TemplateSpecialization:
2655     case clang::Type::Typedef:
2656     case clang::Type::TypeOf:
2657     case clang::Type::TypeOfExpr:
2658     case clang::Type::Using:
2659       type = type->getLocallyUnqualifiedSingleStepDesugaredType();
2660       break;
2661     default:
2662       return type;
2663     }
2664   }
2665 }
2666 
2667 clang::DeclContext *
2668 TypeSystemClang::GetDeclContextForType(clang::QualType type) {
2669   if (type.isNull())
2670     return nullptr;
2671 
2672   clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
2673   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2674   switch (type_class) {
2675   case clang::Type::ObjCInterface:
2676     return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2677         ->getInterface();
2678   case clang::Type::ObjCObjectPointer:
2679     return GetDeclContextForType(
2680         llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2681             ->getPointeeType());
2682   case clang::Type::Record:
2683     return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2684   case clang::Type::Enum:
2685     return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2686   default:
2687     break;
2688   }
2689   // No DeclContext in this type...
2690   return nullptr;
2691 }
2692 
2693 static bool GetCompleteQualType(clang::ASTContext *ast,
2694                                 clang::QualType qual_type,
2695                                 bool allow_completion = true) {
2696   qual_type = RemoveWrappingTypes(qual_type);
2697   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2698   switch (type_class) {
2699   case clang::Type::ConstantArray:
2700   case clang::Type::IncompleteArray:
2701   case clang::Type::VariableArray: {
2702     const clang::ArrayType *array_type =
2703         llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2704 
2705     if (array_type)
2706       return GetCompleteQualType(ast, array_type->getElementType(),
2707                                  allow_completion);
2708   } break;
2709   case clang::Type::Record: {
2710     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2711     if (cxx_record_decl) {
2712       if (cxx_record_decl->hasExternalLexicalStorage()) {
2713         const bool is_complete = cxx_record_decl->isCompleteDefinition();
2714         const bool fields_loaded =
2715             cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2716         if (is_complete && fields_loaded)
2717           return true;
2718 
2719         if (!allow_completion)
2720           return false;
2721 
2722         // Call the field_begin() accessor to for it to use the external source
2723         // to load the fields...
2724         clang::ExternalASTSource *external_ast_source =
2725             ast->getExternalSource();
2726         if (external_ast_source) {
2727           external_ast_source->CompleteType(cxx_record_decl);
2728           if (cxx_record_decl->isCompleteDefinition()) {
2729             cxx_record_decl->field_begin();
2730             cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2731           }
2732         }
2733       }
2734     }
2735     const clang::TagType *tag_type =
2736         llvm::cast<clang::TagType>(qual_type.getTypePtr());
2737     return !tag_type->isIncompleteType();
2738   } break;
2739 
2740   case clang::Type::Enum: {
2741     const clang::TagType *tag_type =
2742         llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
2743     if (tag_type) {
2744       clang::TagDecl *tag_decl = tag_type->getDecl();
2745       if (tag_decl) {
2746         if (tag_decl->getDefinition())
2747           return true;
2748 
2749         if (!allow_completion)
2750           return false;
2751 
2752         if (tag_decl->hasExternalLexicalStorage()) {
2753           if (ast) {
2754             clang::ExternalASTSource *external_ast_source =
2755                 ast->getExternalSource();
2756             if (external_ast_source) {
2757               external_ast_source->CompleteType(tag_decl);
2758               return !tag_type->isIncompleteType();
2759             }
2760           }
2761         }
2762         return false;
2763       }
2764     }
2765 
2766   } break;
2767   case clang::Type::ObjCObject:
2768   case clang::Type::ObjCInterface: {
2769     const clang::ObjCObjectType *objc_class_type =
2770         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
2771     if (objc_class_type) {
2772       clang::ObjCInterfaceDecl *class_interface_decl =
2773           objc_class_type->getInterface();
2774       // We currently can't complete objective C types through the newly added
2775       // ASTContext because it only supports TagDecl objects right now...
2776       if (class_interface_decl) {
2777         if (class_interface_decl->getDefinition())
2778           return true;
2779 
2780         if (!allow_completion)
2781           return false;
2782 
2783         if (class_interface_decl->hasExternalLexicalStorage()) {
2784           if (ast) {
2785             clang::ExternalASTSource *external_ast_source =
2786                 ast->getExternalSource();
2787             if (external_ast_source) {
2788               external_ast_source->CompleteType(class_interface_decl);
2789               return !objc_class_type->isIncompleteType();
2790             }
2791           }
2792         }
2793         return false;
2794       }
2795     }
2796   } break;
2797 
2798   case clang::Type::Attributed:
2799     return GetCompleteQualType(
2800         ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2801         allow_completion);
2802 
2803   default:
2804     break;
2805   }
2806 
2807   return true;
2808 }
2809 
2810 static clang::ObjCIvarDecl::AccessControl
2811 ConvertAccessTypeToObjCIvarAccessControl(AccessType access) {
2812   switch (access) {
2813   case eAccessNone:
2814     return clang::ObjCIvarDecl::None;
2815   case eAccessPublic:
2816     return clang::ObjCIvarDecl::Public;
2817   case eAccessPrivate:
2818     return clang::ObjCIvarDecl::Private;
2819   case eAccessProtected:
2820     return clang::ObjCIvarDecl::Protected;
2821   case eAccessPackage:
2822     return clang::ObjCIvarDecl::Package;
2823   }
2824   return clang::ObjCIvarDecl::None;
2825 }
2826 
2827 // Tests
2828 
2829 #ifndef NDEBUG
2830 bool TypeSystemClang::Verify(lldb::opaque_compiler_type_t type) {
2831   return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr());
2832 }
2833 #endif
2834 
2835 bool TypeSystemClang::IsAggregateType(lldb::opaque_compiler_type_t type) {
2836   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2837 
2838   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2839   switch (type_class) {
2840   case clang::Type::IncompleteArray:
2841   case clang::Type::VariableArray:
2842   case clang::Type::ConstantArray:
2843   case clang::Type::ExtVector:
2844   case clang::Type::Vector:
2845   case clang::Type::Record:
2846   case clang::Type::ObjCObject:
2847   case clang::Type::ObjCInterface:
2848     return true;
2849   default:
2850     break;
2851   }
2852   // The clang type does have a value
2853   return false;
2854 }
2855 
2856 bool TypeSystemClang::IsAnonymousType(lldb::opaque_compiler_type_t type) {
2857   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2858 
2859   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2860   switch (type_class) {
2861   case clang::Type::Record: {
2862     if (const clang::RecordType *record_type =
2863             llvm::dyn_cast_or_null<clang::RecordType>(
2864                 qual_type.getTypePtrOrNull())) {
2865       if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2866         return record_decl->isAnonymousStructOrUnion();
2867       }
2868     }
2869     break;
2870   }
2871   default:
2872     break;
2873   }
2874   // The clang type does have a value
2875   return false;
2876 }
2877 
2878 bool TypeSystemClang::IsArrayType(lldb::opaque_compiler_type_t type,
2879                                   CompilerType *element_type_ptr,
2880                                   uint64_t *size, bool *is_incomplete) {
2881   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2882 
2883   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2884   switch (type_class) {
2885   default:
2886     break;
2887 
2888   case clang::Type::ConstantArray:
2889     if (element_type_ptr)
2890       element_type_ptr->SetCompilerType(
2891           weak_from_this(), llvm::cast<clang::ConstantArrayType>(qual_type)
2892                                 ->getElementType()
2893                                 .getAsOpaquePtr());
2894     if (size)
2895       *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2896                   ->getSize()
2897                   .getLimitedValue(ULLONG_MAX);
2898     if (is_incomplete)
2899       *is_incomplete = false;
2900     return true;
2901 
2902   case clang::Type::IncompleteArray:
2903     if (element_type_ptr)
2904       element_type_ptr->SetCompilerType(
2905           weak_from_this(), llvm::cast<clang::IncompleteArrayType>(qual_type)
2906                                 ->getElementType()
2907                                 .getAsOpaquePtr());
2908     if (size)
2909       *size = 0;
2910     if (is_incomplete)
2911       *is_incomplete = true;
2912     return true;
2913 
2914   case clang::Type::VariableArray:
2915     if (element_type_ptr)
2916       element_type_ptr->SetCompilerType(
2917           weak_from_this(), llvm::cast<clang::VariableArrayType>(qual_type)
2918                                 ->getElementType()
2919                                 .getAsOpaquePtr());
2920     if (size)
2921       *size = 0;
2922     if (is_incomplete)
2923       *is_incomplete = false;
2924     return true;
2925 
2926   case clang::Type::DependentSizedArray:
2927     if (element_type_ptr)
2928       element_type_ptr->SetCompilerType(
2929           weak_from_this(),
2930           llvm::cast<clang::DependentSizedArrayType>(qual_type)
2931               ->getElementType()
2932               .getAsOpaquePtr());
2933     if (size)
2934       *size = 0;
2935     if (is_incomplete)
2936       *is_incomplete = false;
2937     return true;
2938   }
2939   if (element_type_ptr)
2940     element_type_ptr->Clear();
2941   if (size)
2942     *size = 0;
2943   if (is_incomplete)
2944     *is_incomplete = false;
2945   return false;
2946 }
2947 
2948 bool TypeSystemClang::IsVectorType(lldb::opaque_compiler_type_t type,
2949                                    CompilerType *element_type, uint64_t *size) {
2950   clang::QualType qual_type(GetCanonicalQualType(type));
2951 
2952   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2953   switch (type_class) {
2954   case clang::Type::Vector: {
2955     const clang::VectorType *vector_type =
2956         qual_type->getAs<clang::VectorType>();
2957     if (vector_type) {
2958       if (size)
2959         *size = vector_type->getNumElements();
2960       if (element_type)
2961         *element_type = GetType(vector_type->getElementType());
2962     }
2963     return true;
2964   } break;
2965   case clang::Type::ExtVector: {
2966     const clang::ExtVectorType *ext_vector_type =
2967         qual_type->getAs<clang::ExtVectorType>();
2968     if (ext_vector_type) {
2969       if (size)
2970         *size = ext_vector_type->getNumElements();
2971       if (element_type)
2972         *element_type =
2973             CompilerType(weak_from_this(),
2974                          ext_vector_type->getElementType().getAsOpaquePtr());
2975     }
2976     return true;
2977   }
2978   default:
2979     break;
2980   }
2981   return false;
2982 }
2983 
2984 bool TypeSystemClang::IsRuntimeGeneratedType(
2985     lldb::opaque_compiler_type_t type) {
2986   clang::DeclContext *decl_ctx = GetDeclContextForType(GetQualType(type));
2987   if (!decl_ctx)
2988     return false;
2989 
2990   if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
2991     return false;
2992 
2993   clang::ObjCInterfaceDecl *result_iface_decl =
2994       llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
2995 
2996   ClangASTMetadata *ast_metadata = GetMetadata(result_iface_decl);
2997   if (!ast_metadata)
2998     return false;
2999   return (ast_metadata->GetISAPtr() != 0);
3000 }
3001 
3002 bool TypeSystemClang::IsCharType(lldb::opaque_compiler_type_t type) {
3003   return GetQualType(type).getUnqualifiedType()->isCharType();
3004 }
3005 
3006 bool TypeSystemClang::IsCompleteType(lldb::opaque_compiler_type_t type) {
3007   // If the type hasn't been lazily completed yet, complete it now so that we
3008   // can give the caller an accurate answer whether the type actually has a
3009   // definition. Without completing the type now we would just tell the user
3010   // the current (internal) completeness state of the type and most users don't
3011   // care (or even know) about this behavior.
3012   const bool allow_completion = true;
3013   return GetCompleteQualType(&getASTContext(), GetQualType(type),
3014                              allow_completion);
3015 }
3016 
3017 bool TypeSystemClang::IsConst(lldb::opaque_compiler_type_t type) {
3018   return GetQualType(type).isConstQualified();
3019 }
3020 
3021 bool TypeSystemClang::IsCStringType(lldb::opaque_compiler_type_t type,
3022                                     uint32_t &length) {
3023   CompilerType pointee_or_element_clang_type;
3024   length = 0;
3025   Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
3026 
3027   if (!pointee_or_element_clang_type.IsValid())
3028     return false;
3029 
3030   if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
3031     if (pointee_or_element_clang_type.IsCharType()) {
3032       if (type_flags.Test(eTypeIsArray)) {
3033         // We know the size of the array and it could be a C string since it is
3034         // an array of characters
3035         length = llvm::cast<clang::ConstantArrayType>(
3036                      GetCanonicalQualType(type).getTypePtr())
3037                      ->getSize()
3038                      .getLimitedValue();
3039       }
3040       return true;
3041     }
3042   }
3043   return false;
3044 }
3045 
3046 bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) {
3047   if (type) {
3048     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3049 
3050     if (qual_type->isFunctionType()) {
3051       return true;
3052     }
3053 
3054     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3055     switch (type_class) {
3056     default:
3057       break;
3058     case clang::Type::LValueReference:
3059     case clang::Type::RValueReference: {
3060       const clang::ReferenceType *reference_type =
3061           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3062       if (reference_type)
3063         return IsFunctionType(
3064             reference_type->getPointeeType().getAsOpaquePtr());
3065     } break;
3066     }
3067   }
3068   return false;
3069 }
3070 
3071 // Used to detect "Homogeneous Floating-point Aggregates"
3072 uint32_t
3073 TypeSystemClang::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
3074                                         CompilerType *base_type_ptr) {
3075   if (!type)
3076     return 0;
3077 
3078   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
3079   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3080   switch (type_class) {
3081   case clang::Type::Record:
3082     if (GetCompleteType(type)) {
3083       const clang::CXXRecordDecl *cxx_record_decl =
3084           qual_type->getAsCXXRecordDecl();
3085       if (cxx_record_decl) {
3086         if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
3087           return 0;
3088       }
3089       const clang::RecordType *record_type =
3090           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3091       if (record_type) {
3092         const clang::RecordDecl *record_decl = record_type->getDecl();
3093         if (record_decl) {
3094           // We are looking for a structure that contains only floating point
3095           // types
3096           clang::RecordDecl::field_iterator field_pos,
3097               field_end = record_decl->field_end();
3098           uint32_t num_fields = 0;
3099           bool is_hva = false;
3100           bool is_hfa = false;
3101           clang::QualType base_qual_type;
3102           uint64_t base_bitwidth = 0;
3103           for (field_pos = record_decl->field_begin(); field_pos != field_end;
3104                ++field_pos) {
3105             clang::QualType field_qual_type = field_pos->getType();
3106             uint64_t field_bitwidth = getASTContext().getTypeSize(qual_type);
3107             if (field_qual_type->isFloatingType()) {
3108               if (field_qual_type->isComplexType())
3109                 return 0;
3110               else {
3111                 if (num_fields == 0)
3112                   base_qual_type = field_qual_type;
3113                 else {
3114                   if (is_hva)
3115                     return 0;
3116                   is_hfa = true;
3117                   if (field_qual_type.getTypePtr() !=
3118                       base_qual_type.getTypePtr())
3119                     return 0;
3120                 }
3121               }
3122             } else if (field_qual_type->isVectorType() ||
3123                        field_qual_type->isExtVectorType()) {
3124               if (num_fields == 0) {
3125                 base_qual_type = field_qual_type;
3126                 base_bitwidth = field_bitwidth;
3127               } else {
3128                 if (is_hfa)
3129                   return 0;
3130                 is_hva = true;
3131                 if (base_bitwidth != field_bitwidth)
3132                   return 0;
3133                 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3134                   return 0;
3135               }
3136             } else
3137               return 0;
3138             ++num_fields;
3139           }
3140           if (base_type_ptr)
3141             *base_type_ptr =
3142                 CompilerType(weak_from_this(), base_qual_type.getAsOpaquePtr());
3143           return num_fields;
3144         }
3145       }
3146     }
3147     break;
3148 
3149   default:
3150     break;
3151   }
3152   return 0;
3153 }
3154 
3155 size_t TypeSystemClang::GetNumberOfFunctionArguments(
3156     lldb::opaque_compiler_type_t type) {
3157   if (type) {
3158     clang::QualType qual_type(GetCanonicalQualType(type));
3159     const clang::FunctionProtoType *func =
3160         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3161     if (func)
3162       return func->getNumParams();
3163   }
3164   return 0;
3165 }
3166 
3167 CompilerType
3168 TypeSystemClang::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
3169                                             const size_t index) {
3170   if (type) {
3171     clang::QualType qual_type(GetQualType(type));
3172     const clang::FunctionProtoType *func =
3173         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3174     if (func) {
3175       if (index < func->getNumParams())
3176         return CompilerType(weak_from_this(), func->getParamType(index).getAsOpaquePtr());
3177     }
3178   }
3179   return CompilerType();
3180 }
3181 
3182 bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
3183   if (type) {
3184     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3185 
3186     if (qual_type->isFunctionPointerType())
3187       return true;
3188 
3189     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3190     switch (type_class) {
3191     default:
3192       break;
3193 
3194     case clang::Type::LValueReference:
3195     case clang::Type::RValueReference: {
3196       const clang::ReferenceType *reference_type =
3197           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3198       if (reference_type)
3199         return IsFunctionPointerType(
3200             reference_type->getPointeeType().getAsOpaquePtr());
3201     } break;
3202     }
3203   }
3204   return false;
3205 }
3206 
3207 bool TypeSystemClang::IsBlockPointerType(
3208     lldb::opaque_compiler_type_t type,
3209     CompilerType *function_pointer_type_ptr) {
3210   if (type) {
3211     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3212 
3213     if (qual_type->isBlockPointerType()) {
3214       if (function_pointer_type_ptr) {
3215         const clang::BlockPointerType *block_pointer_type =
3216             qual_type->castAs<clang::BlockPointerType>();
3217         QualType pointee_type = block_pointer_type->getPointeeType();
3218         QualType function_pointer_type = m_ast_up->getPointerType(pointee_type);
3219         *function_pointer_type_ptr = CompilerType(
3220             weak_from_this(), function_pointer_type.getAsOpaquePtr());
3221       }
3222       return true;
3223     }
3224 
3225     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3226     switch (type_class) {
3227     default:
3228       break;
3229 
3230     case clang::Type::LValueReference:
3231     case clang::Type::RValueReference: {
3232       const clang::ReferenceType *reference_type =
3233           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3234       if (reference_type)
3235         return IsBlockPointerType(
3236             reference_type->getPointeeType().getAsOpaquePtr(),
3237             function_pointer_type_ptr);
3238     } break;
3239     }
3240   }
3241   return false;
3242 }
3243 
3244 bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type,
3245                                     bool &is_signed) {
3246   if (!type)
3247     return false;
3248 
3249   clang::QualType qual_type(GetCanonicalQualType(type));
3250   const clang::BuiltinType *builtin_type =
3251       llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3252 
3253   if (builtin_type) {
3254     if (builtin_type->isInteger()) {
3255       is_signed = builtin_type->isSignedInteger();
3256       return true;
3257     }
3258   }
3259 
3260   return false;
3261 }
3262 
3263 bool TypeSystemClang::IsEnumerationType(lldb::opaque_compiler_type_t type,
3264                                         bool &is_signed) {
3265   if (type) {
3266     const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3267         GetCanonicalQualType(type)->getCanonicalTypeInternal());
3268 
3269     if (enum_type) {
3270       IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3271                     is_signed);
3272       return true;
3273     }
3274   }
3275 
3276   return false;
3277 }
3278 
3279 bool TypeSystemClang::IsScopedEnumerationType(
3280     lldb::opaque_compiler_type_t type) {
3281   if (type) {
3282     const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3283         GetCanonicalQualType(type)->getCanonicalTypeInternal());
3284 
3285     if (enum_type) {
3286       return enum_type->isScopedEnumeralType();
3287     }
3288   }
3289 
3290   return false;
3291 }
3292 
3293 bool TypeSystemClang::IsPointerType(lldb::opaque_compiler_type_t type,
3294                                     CompilerType *pointee_type) {
3295   if (type) {
3296     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3297     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3298     switch (type_class) {
3299     case clang::Type::Builtin:
3300       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3301       default:
3302         break;
3303       case clang::BuiltinType::ObjCId:
3304       case clang::BuiltinType::ObjCClass:
3305         return true;
3306       }
3307       return false;
3308     case clang::Type::ObjCObjectPointer:
3309       if (pointee_type)
3310         pointee_type->SetCompilerType(
3311             weak_from_this(),
3312             llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3313                 ->getPointeeType()
3314                 .getAsOpaquePtr());
3315       return true;
3316     case clang::Type::BlockPointer:
3317       if (pointee_type)
3318         pointee_type->SetCompilerType(
3319             weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type)
3320                                   ->getPointeeType()
3321                                   .getAsOpaquePtr());
3322       return true;
3323     case clang::Type::Pointer:
3324       if (pointee_type)
3325         pointee_type->SetCompilerType(weak_from_this(),
3326                                       llvm::cast<clang::PointerType>(qual_type)
3327                                           ->getPointeeType()
3328                                           .getAsOpaquePtr());
3329       return true;
3330     case clang::Type::MemberPointer:
3331       if (pointee_type)
3332         pointee_type->SetCompilerType(
3333             weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type)
3334                                   ->getPointeeType()
3335                                   .getAsOpaquePtr());
3336       return true;
3337     default:
3338       break;
3339     }
3340   }
3341   if (pointee_type)
3342     pointee_type->Clear();
3343   return false;
3344 }
3345 
3346 bool TypeSystemClang::IsPointerOrReferenceType(
3347     lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3348   if (type) {
3349     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3350     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3351     switch (type_class) {
3352     case clang::Type::Builtin:
3353       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3354       default:
3355         break;
3356       case clang::BuiltinType::ObjCId:
3357       case clang::BuiltinType::ObjCClass:
3358         return true;
3359       }
3360       return false;
3361     case clang::Type::ObjCObjectPointer:
3362       if (pointee_type)
3363         pointee_type->SetCompilerType(
3364             weak_from_this(),
3365             llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3366                 ->getPointeeType()
3367                 .getAsOpaquePtr());
3368       return true;
3369     case clang::Type::BlockPointer:
3370       if (pointee_type)
3371         pointee_type->SetCompilerType(
3372             weak_from_this(), llvm::cast<clang::BlockPointerType>(qual_type)
3373                                   ->getPointeeType()
3374                                   .getAsOpaquePtr());
3375       return true;
3376     case clang::Type::Pointer:
3377       if (pointee_type)
3378         pointee_type->SetCompilerType(weak_from_this(),
3379                                       llvm::cast<clang::PointerType>(qual_type)
3380                                           ->getPointeeType()
3381                                           .getAsOpaquePtr());
3382       return true;
3383     case clang::Type::MemberPointer:
3384       if (pointee_type)
3385         pointee_type->SetCompilerType(
3386             weak_from_this(), llvm::cast<clang::MemberPointerType>(qual_type)
3387                                   ->getPointeeType()
3388                                   .getAsOpaquePtr());
3389       return true;
3390     case clang::Type::LValueReference:
3391       if (pointee_type)
3392         pointee_type->SetCompilerType(
3393             weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type)
3394                                   ->desugar()
3395                                   .getAsOpaquePtr());
3396       return true;
3397     case clang::Type::RValueReference:
3398       if (pointee_type)
3399         pointee_type->SetCompilerType(
3400             weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type)
3401                                   ->desugar()
3402                                   .getAsOpaquePtr());
3403       return true;
3404     default:
3405       break;
3406     }
3407   }
3408   if (pointee_type)
3409     pointee_type->Clear();
3410   return false;
3411 }
3412 
3413 bool TypeSystemClang::IsReferenceType(lldb::opaque_compiler_type_t type,
3414                                       CompilerType *pointee_type,
3415                                       bool *is_rvalue) {
3416   if (type) {
3417     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3418     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3419 
3420     switch (type_class) {
3421     case clang::Type::LValueReference:
3422       if (pointee_type)
3423         pointee_type->SetCompilerType(
3424             weak_from_this(), llvm::cast<clang::LValueReferenceType>(qual_type)
3425                                   ->desugar()
3426                                   .getAsOpaquePtr());
3427       if (is_rvalue)
3428         *is_rvalue = false;
3429       return true;
3430     case clang::Type::RValueReference:
3431       if (pointee_type)
3432         pointee_type->SetCompilerType(
3433             weak_from_this(), llvm::cast<clang::RValueReferenceType>(qual_type)
3434                                   ->desugar()
3435                                   .getAsOpaquePtr());
3436       if (is_rvalue)
3437         *is_rvalue = true;
3438       return true;
3439 
3440     default:
3441       break;
3442     }
3443   }
3444   if (pointee_type)
3445     pointee_type->Clear();
3446   return false;
3447 }
3448 
3449 bool TypeSystemClang::IsFloatingPointType(lldb::opaque_compiler_type_t type,
3450                                           uint32_t &count, bool &is_complex) {
3451   if (type) {
3452     clang::QualType qual_type(GetCanonicalQualType(type));
3453 
3454     if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3455             qual_type->getCanonicalTypeInternal())) {
3456       clang::BuiltinType::Kind kind = BT->getKind();
3457       if (kind >= clang::BuiltinType::Float &&
3458           kind <= clang::BuiltinType::LongDouble) {
3459         count = 1;
3460         is_complex = false;
3461         return true;
3462       }
3463     } else if (const clang::ComplexType *CT =
3464                    llvm::dyn_cast<clang::ComplexType>(
3465                        qual_type->getCanonicalTypeInternal())) {
3466       if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3467                               is_complex)) {
3468         count = 2;
3469         is_complex = true;
3470         return true;
3471       }
3472     } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3473                    qual_type->getCanonicalTypeInternal())) {
3474       if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3475                               is_complex)) {
3476         count = VT->getNumElements();
3477         is_complex = false;
3478         return true;
3479       }
3480     }
3481   }
3482   count = 0;
3483   is_complex = false;
3484   return false;
3485 }
3486 
3487 bool TypeSystemClang::IsDefined(lldb::opaque_compiler_type_t type) {
3488   if (!type)
3489     return false;
3490 
3491   clang::QualType qual_type(GetQualType(type));
3492   const clang::TagType *tag_type =
3493       llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3494   if (tag_type) {
3495     clang::TagDecl *tag_decl = tag_type->getDecl();
3496     if (tag_decl)
3497       return tag_decl->isCompleteDefinition();
3498     return false;
3499   } else {
3500     const clang::ObjCObjectType *objc_class_type =
3501         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3502     if (objc_class_type) {
3503       clang::ObjCInterfaceDecl *class_interface_decl =
3504           objc_class_type->getInterface();
3505       if (class_interface_decl)
3506         return class_interface_decl->getDefinition() != nullptr;
3507       return false;
3508     }
3509   }
3510   return true;
3511 }
3512 
3513 bool TypeSystemClang::IsObjCClassType(const CompilerType &type) {
3514   if (ClangUtil::IsClangType(type)) {
3515     clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3516 
3517     const clang::ObjCObjectPointerType *obj_pointer_type =
3518         llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3519 
3520     if (obj_pointer_type)
3521       return obj_pointer_type->isObjCClassType();
3522   }
3523   return false;
3524 }
3525 
3526 bool TypeSystemClang::IsObjCObjectOrInterfaceType(const CompilerType &type) {
3527   if (ClangUtil::IsClangType(type))
3528     return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3529   return false;
3530 }
3531 
3532 bool TypeSystemClang::IsClassType(lldb::opaque_compiler_type_t type) {
3533   if (!type)
3534     return false;
3535   clang::QualType qual_type(GetCanonicalQualType(type));
3536   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3537   return (type_class == clang::Type::Record);
3538 }
3539 
3540 bool TypeSystemClang::IsEnumType(lldb::opaque_compiler_type_t type) {
3541   if (!type)
3542     return false;
3543   clang::QualType qual_type(GetCanonicalQualType(type));
3544   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3545   return (type_class == clang::Type::Enum);
3546 }
3547 
3548 bool TypeSystemClang::IsPolymorphicClass(lldb::opaque_compiler_type_t type) {
3549   if (type) {
3550     clang::QualType qual_type(GetCanonicalQualType(type));
3551     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3552     switch (type_class) {
3553     case clang::Type::Record:
3554       if (GetCompleteType(type)) {
3555         const clang::RecordType *record_type =
3556             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3557         const clang::RecordDecl *record_decl = record_type->getDecl();
3558         if (record_decl) {
3559           const clang::CXXRecordDecl *cxx_record_decl =
3560               llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3561           if (cxx_record_decl)
3562             return cxx_record_decl->isPolymorphic();
3563         }
3564       }
3565       break;
3566 
3567     default:
3568       break;
3569     }
3570   }
3571   return false;
3572 }
3573 
3574 bool TypeSystemClang::IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
3575                                             CompilerType *dynamic_pointee_type,
3576                                             bool check_cplusplus,
3577                                             bool check_objc) {
3578   clang::QualType pointee_qual_type;
3579   if (type) {
3580     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3581     bool success = false;
3582     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3583     switch (type_class) {
3584     case clang::Type::Builtin:
3585       if (check_objc &&
3586           llvm::cast<clang::BuiltinType>(qual_type)->getKind() ==
3587               clang::BuiltinType::ObjCId) {
3588         if (dynamic_pointee_type)
3589           dynamic_pointee_type->SetCompilerType(weak_from_this(), type);
3590         return true;
3591       }
3592       break;
3593 
3594     case clang::Type::ObjCObjectPointer:
3595       if (check_objc) {
3596         if (const auto *objc_pointee_type =
3597                 qual_type->getPointeeType().getTypePtrOrNull()) {
3598           if (const auto *objc_object_type =
3599                   llvm::dyn_cast_or_null<clang::ObjCObjectType>(
3600                       objc_pointee_type)) {
3601             if (objc_object_type->isObjCClass())
3602               return false;
3603           }
3604         }
3605         if (dynamic_pointee_type)
3606           dynamic_pointee_type->SetCompilerType(
3607               weak_from_this(),
3608               llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3609                   ->getPointeeType()
3610                   .getAsOpaquePtr());
3611         return true;
3612       }
3613       break;
3614 
3615     case clang::Type::Pointer:
3616       pointee_qual_type =
3617           llvm::cast<clang::PointerType>(qual_type)->getPointeeType();
3618       success = true;
3619       break;
3620 
3621     case clang::Type::LValueReference:
3622     case clang::Type::RValueReference:
3623       pointee_qual_type =
3624           llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType();
3625       success = true;
3626       break;
3627 
3628     default:
3629       break;
3630     }
3631 
3632     if (success) {
3633       // Check to make sure what we are pointing too is a possible dynamic C++
3634       // type We currently accept any "void *" (in case we have a class that
3635       // has been watered down to an opaque pointer) and virtual C++ classes.
3636       const clang::Type::TypeClass pointee_type_class =
3637           pointee_qual_type.getCanonicalType()->getTypeClass();
3638       switch (pointee_type_class) {
3639       case clang::Type::Builtin:
3640         switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) {
3641         case clang::BuiltinType::UnknownAny:
3642         case clang::BuiltinType::Void:
3643           if (dynamic_pointee_type)
3644             dynamic_pointee_type->SetCompilerType(
3645                 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3646           return true;
3647         default:
3648           break;
3649         }
3650         break;
3651 
3652       case clang::Type::Record:
3653         if (check_cplusplus) {
3654           clang::CXXRecordDecl *cxx_record_decl =
3655               pointee_qual_type->getAsCXXRecordDecl();
3656           if (cxx_record_decl) {
3657             bool is_complete = cxx_record_decl->isCompleteDefinition();
3658 
3659             if (is_complete)
3660               success = cxx_record_decl->isDynamicClass();
3661             else {
3662               ClangASTMetadata *metadata = GetMetadata(cxx_record_decl);
3663               if (metadata)
3664                 success = metadata->GetIsDynamicCXXType();
3665               else {
3666                 is_complete = GetType(pointee_qual_type).GetCompleteType();
3667                 if (is_complete)
3668                   success = cxx_record_decl->isDynamicClass();
3669                 else
3670                   success = false;
3671               }
3672             }
3673 
3674             if (success) {
3675               if (dynamic_pointee_type)
3676                 dynamic_pointee_type->SetCompilerType(
3677                     weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3678               return true;
3679             }
3680           }
3681         }
3682         break;
3683 
3684       case clang::Type::ObjCObject:
3685       case clang::Type::ObjCInterface:
3686         if (check_objc) {
3687           if (dynamic_pointee_type)
3688             dynamic_pointee_type->SetCompilerType(
3689                 weak_from_this(), pointee_qual_type.getAsOpaquePtr());
3690           return true;
3691         }
3692         break;
3693 
3694       default:
3695         break;
3696       }
3697     }
3698   }
3699   if (dynamic_pointee_type)
3700     dynamic_pointee_type->Clear();
3701   return false;
3702 }
3703 
3704 bool TypeSystemClang::IsScalarType(lldb::opaque_compiler_type_t type) {
3705   if (!type)
3706     return false;
3707 
3708   return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3709 }
3710 
3711 bool TypeSystemClang::IsTypedefType(lldb::opaque_compiler_type_t type) {
3712   if (!type)
3713     return false;
3714   return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})
3715              ->getTypeClass() == clang::Type::Typedef;
3716 }
3717 
3718 bool TypeSystemClang::IsVoidType(lldb::opaque_compiler_type_t type) {
3719   if (!type)
3720     return false;
3721   return GetCanonicalQualType(type)->isVoidType();
3722 }
3723 
3724 bool TypeSystemClang::CanPassInRegisters(const CompilerType &type) {
3725   if (auto *record_decl =
3726       TypeSystemClang::GetAsRecordDecl(type)) {
3727     return record_decl->canPassInRegisters();
3728   }
3729   return false;
3730 }
3731 
3732 bool TypeSystemClang::SupportsLanguage(lldb::LanguageType language) {
3733   return TypeSystemClangSupportsLanguage(language);
3734 }
3735 
3736 std::optional<std::string>
3737 TypeSystemClang::GetCXXClassName(const CompilerType &type) {
3738   if (!type)
3739     return std::nullopt;
3740 
3741   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3742   if (qual_type.isNull())
3743     return std::nullopt;
3744 
3745   clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3746   if (!cxx_record_decl)
3747     return std::nullopt;
3748 
3749   return std::string(cxx_record_decl->getIdentifier()->getNameStart());
3750 }
3751 
3752 bool TypeSystemClang::IsCXXClassType(const CompilerType &type) {
3753   if (!type)
3754     return false;
3755 
3756   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3757   return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr;
3758 }
3759 
3760 bool TypeSystemClang::IsBeingDefined(lldb::opaque_compiler_type_t type) {
3761   if (!type)
3762     return false;
3763   clang::QualType qual_type(GetCanonicalQualType(type));
3764   const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type);
3765   if (tag_type)
3766     return tag_type->isBeingDefined();
3767   return false;
3768 }
3769 
3770 bool TypeSystemClang::IsObjCObjectPointerType(const CompilerType &type,
3771                                               CompilerType *class_type_ptr) {
3772   if (!ClangUtil::IsClangType(type))
3773     return false;
3774 
3775   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3776 
3777   if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) {
3778     if (class_type_ptr) {
3779       if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) {
3780         const clang::ObjCObjectPointerType *obj_pointer_type =
3781             llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3782         if (obj_pointer_type == nullptr)
3783           class_type_ptr->Clear();
3784         else
3785           class_type_ptr->SetCompilerType(
3786               type.GetTypeSystem(),
3787               clang::QualType(obj_pointer_type->getInterfaceType(), 0)
3788                   .getAsOpaquePtr());
3789       }
3790     }
3791     return true;
3792   }
3793   if (class_type_ptr)
3794     class_type_ptr->Clear();
3795   return false;
3796 }
3797 
3798 // Type Completion
3799 
3800 bool TypeSystemClang::GetCompleteType(lldb::opaque_compiler_type_t type) {
3801   if (!type)
3802     return false;
3803   const bool allow_completion = true;
3804   return GetCompleteQualType(&getASTContext(), GetQualType(type),
3805                              allow_completion);
3806 }
3807 
3808 ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type,
3809                                          bool base_only) {
3810   if (!type)
3811     return ConstString();
3812 
3813   clang::QualType qual_type(GetQualType(type));
3814 
3815   // Remove certain type sugar from the name. Sugar such as elaborated types
3816   // or template types which only serve to improve diagnostics shouldn't
3817   // act as their own types from the user's perspective (e.g., formatter
3818   // shouldn't format a variable differently depending on how the ser has
3819   // specified the type. '::Type' and 'Type' should behave the same).
3820   // Typedefs and atomic derived types are not removed as they are actually
3821   // useful for identifiying specific types.
3822   qual_type = RemoveWrappingTypes(qual_type,
3823                                   {clang::Type::Typedef, clang::Type::Atomic});
3824 
3825   // For a typedef just return the qualified name.
3826   if (const auto *typedef_type = qual_type->getAs<clang::TypedefType>()) {
3827     const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
3828     return ConstString(GetTypeNameForDecl(typedef_decl));
3829   }
3830 
3831   // For consistency, this follows the same code path that clang uses to emit
3832   // debug info. This also handles when we don't want any scopes preceding the
3833   // name.
3834   if (auto *named_decl = qual_type->getAsTagDecl())
3835     return ConstString(GetTypeNameForDecl(named_decl, !base_only));
3836 
3837   return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
3838 }
3839 
3840 ConstString
3841 TypeSystemClang::GetDisplayTypeName(lldb::opaque_compiler_type_t type) {
3842   if (!type)
3843     return ConstString();
3844 
3845   clang::QualType qual_type(GetQualType(type));
3846   clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
3847   printing_policy.SuppressTagKeyword = true;
3848   printing_policy.SuppressScope = false;
3849   printing_policy.SuppressUnwrittenScope = true;
3850   printing_policy.SuppressInlineNamespace = true;
3851   return ConstString(qual_type.getAsString(printing_policy));
3852 }
3853 
3854 uint32_t
3855 TypeSystemClang::GetTypeInfo(lldb::opaque_compiler_type_t type,
3856                              CompilerType *pointee_or_element_clang_type) {
3857   if (!type)
3858     return 0;
3859 
3860   if (pointee_or_element_clang_type)
3861     pointee_or_element_clang_type->Clear();
3862 
3863   clang::QualType qual_type =
3864       RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
3865 
3866   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3867   switch (type_class) {
3868   case clang::Type::Attributed:
3869     return GetTypeInfo(qual_type->castAs<clang::AttributedType>()
3870                            ->getModifiedType()
3871                            .getAsOpaquePtr(),
3872                        pointee_or_element_clang_type);
3873   case clang::Type::Builtin: {
3874     const clang::BuiltinType *builtin_type =
3875         llvm::cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3876 
3877     uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
3878     switch (builtin_type->getKind()) {
3879     case clang::BuiltinType::ObjCId:
3880     case clang::BuiltinType::ObjCClass:
3881       if (pointee_or_element_clang_type)
3882         pointee_or_element_clang_type->SetCompilerType(
3883             weak_from_this(),
3884             getASTContext().ObjCBuiltinClassTy.getAsOpaquePtr());
3885       builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3886       break;
3887 
3888     case clang::BuiltinType::ObjCSel:
3889       if (pointee_or_element_clang_type)
3890         pointee_or_element_clang_type->SetCompilerType(
3891             weak_from_this(), getASTContext().CharTy.getAsOpaquePtr());
3892       builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3893       break;
3894 
3895     case clang::BuiltinType::Bool:
3896     case clang::BuiltinType::Char_U:
3897     case clang::BuiltinType::UChar:
3898     case clang::BuiltinType::WChar_U:
3899     case clang::BuiltinType::Char16:
3900     case clang::BuiltinType::Char32:
3901     case clang::BuiltinType::UShort:
3902     case clang::BuiltinType::UInt:
3903     case clang::BuiltinType::ULong:
3904     case clang::BuiltinType::ULongLong:
3905     case clang::BuiltinType::UInt128:
3906     case clang::BuiltinType::Char_S:
3907     case clang::BuiltinType::SChar:
3908     case clang::BuiltinType::WChar_S:
3909     case clang::BuiltinType::Short:
3910     case clang::BuiltinType::Int:
3911     case clang::BuiltinType::Long:
3912     case clang::BuiltinType::LongLong:
3913     case clang::BuiltinType::Int128:
3914     case clang::BuiltinType::Float:
3915     case clang::BuiltinType::Double:
3916     case clang::BuiltinType::LongDouble:
3917       builtin_type_flags |= eTypeIsScalar;
3918       if (builtin_type->isInteger()) {
3919         builtin_type_flags |= eTypeIsInteger;
3920         if (builtin_type->isSignedInteger())
3921           builtin_type_flags |= eTypeIsSigned;
3922       } else if (builtin_type->isFloatingPoint())
3923         builtin_type_flags |= eTypeIsFloat;
3924       break;
3925     default:
3926       break;
3927     }
3928     return builtin_type_flags;
3929   }
3930 
3931   case clang::Type::BlockPointer:
3932     if (pointee_or_element_clang_type)
3933       pointee_or_element_clang_type->SetCompilerType(
3934           weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
3935     return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
3936 
3937   case clang::Type::Complex: {
3938     uint32_t complex_type_flags =
3939         eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
3940     const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>(
3941         qual_type->getCanonicalTypeInternal());
3942     if (complex_type) {
3943       clang::QualType complex_element_type(complex_type->getElementType());
3944       if (complex_element_type->isIntegerType())
3945         complex_type_flags |= eTypeIsFloat;
3946       else if (complex_element_type->isFloatingType())
3947         complex_type_flags |= eTypeIsInteger;
3948     }
3949     return complex_type_flags;
3950   } break;
3951 
3952   case clang::Type::ConstantArray:
3953   case clang::Type::DependentSizedArray:
3954   case clang::Type::IncompleteArray:
3955   case clang::Type::VariableArray:
3956     if (pointee_or_element_clang_type)
3957       pointee_or_element_clang_type->SetCompilerType(
3958           weak_from_this(), llvm::cast<clang::ArrayType>(qual_type.getTypePtr())
3959                                 ->getElementType()
3960                                 .getAsOpaquePtr());
3961     return eTypeHasChildren | eTypeIsArray;
3962 
3963   case clang::Type::DependentName:
3964     return 0;
3965   case clang::Type::DependentSizedExtVector:
3966     return eTypeHasChildren | eTypeIsVector;
3967   case clang::Type::DependentTemplateSpecialization:
3968     return eTypeIsTemplate;
3969 
3970   case clang::Type::Enum:
3971     if (pointee_or_element_clang_type)
3972       pointee_or_element_clang_type->SetCompilerType(
3973           weak_from_this(), llvm::cast<clang::EnumType>(qual_type)
3974                                 ->getDecl()
3975                                 ->getIntegerType()
3976                                 .getAsOpaquePtr());
3977     return eTypeIsEnumeration | eTypeHasValue;
3978 
3979   case clang::Type::FunctionProto:
3980     return eTypeIsFuncPrototype | eTypeHasValue;
3981   case clang::Type::FunctionNoProto:
3982     return eTypeIsFuncPrototype | eTypeHasValue;
3983   case clang::Type::InjectedClassName:
3984     return 0;
3985 
3986   case clang::Type::LValueReference:
3987   case clang::Type::RValueReference:
3988     if (pointee_or_element_clang_type)
3989       pointee_or_element_clang_type->SetCompilerType(
3990           weak_from_this(),
3991           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr())
3992               ->getPointeeType()
3993               .getAsOpaquePtr());
3994     return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
3995 
3996   case clang::Type::MemberPointer:
3997     return eTypeIsPointer | eTypeIsMember | eTypeHasValue;
3998 
3999   case clang::Type::ObjCObjectPointer:
4000     if (pointee_or_element_clang_type)
4001       pointee_or_element_clang_type->SetCompilerType(
4002           weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
4003     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer |
4004            eTypeHasValue;
4005 
4006   case clang::Type::ObjCObject:
4007     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
4008   case clang::Type::ObjCInterface:
4009     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
4010 
4011   case clang::Type::Pointer:
4012     if (pointee_or_element_clang_type)
4013       pointee_or_element_clang_type->SetCompilerType(
4014           weak_from_this(), qual_type->getPointeeType().getAsOpaquePtr());
4015     return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
4016 
4017   case clang::Type::Record:
4018     if (qual_type->getAsCXXRecordDecl())
4019       return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
4020     else
4021       return eTypeHasChildren | eTypeIsStructUnion;
4022     break;
4023   case clang::Type::SubstTemplateTypeParm:
4024     return eTypeIsTemplate;
4025   case clang::Type::TemplateTypeParm:
4026     return eTypeIsTemplate;
4027   case clang::Type::TemplateSpecialization:
4028     return eTypeIsTemplate;
4029 
4030   case clang::Type::Typedef:
4031     return eTypeIsTypedef | GetType(llvm::cast<clang::TypedefType>(qual_type)
4032                                         ->getDecl()
4033                                         ->getUnderlyingType())
4034                                 .GetTypeInfo(pointee_or_element_clang_type);
4035   case clang::Type::UnresolvedUsing:
4036     return 0;
4037 
4038   case clang::Type::ExtVector:
4039   case clang::Type::Vector: {
4040     uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
4041     const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>(
4042         qual_type->getCanonicalTypeInternal());
4043     if (vector_type) {
4044       if (vector_type->isIntegerType())
4045         vector_type_flags |= eTypeIsFloat;
4046       else if (vector_type->isFloatingType())
4047         vector_type_flags |= eTypeIsInteger;
4048     }
4049     return vector_type_flags;
4050   }
4051   default:
4052     return 0;
4053   }
4054   return 0;
4055 }
4056 
4057 lldb::LanguageType
4058 TypeSystemClang::GetMinimumLanguage(lldb::opaque_compiler_type_t type) {
4059   if (!type)
4060     return lldb::eLanguageTypeC;
4061 
4062   // If the type is a reference, then resolve it to what it refers to first:
4063   clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType());
4064   if (qual_type->isAnyPointerType()) {
4065     if (qual_type->isObjCObjectPointerType())
4066       return lldb::eLanguageTypeObjC;
4067     if (qual_type->getPointeeCXXRecordDecl())
4068       return lldb::eLanguageTypeC_plus_plus;
4069 
4070     clang::QualType pointee_type(qual_type->getPointeeType());
4071     if (pointee_type->getPointeeCXXRecordDecl())
4072       return lldb::eLanguageTypeC_plus_plus;
4073     if (pointee_type->isObjCObjectOrInterfaceType())
4074       return lldb::eLanguageTypeObjC;
4075     if (pointee_type->isObjCClassType())
4076       return lldb::eLanguageTypeObjC;
4077     if (pointee_type.getTypePtr() ==
4078         getASTContext().ObjCBuiltinIdTy.getTypePtr())
4079       return lldb::eLanguageTypeObjC;
4080   } else {
4081     if (qual_type->isObjCObjectOrInterfaceType())
4082       return lldb::eLanguageTypeObjC;
4083     if (qual_type->getAsCXXRecordDecl())
4084       return lldb::eLanguageTypeC_plus_plus;
4085     switch (qual_type->getTypeClass()) {
4086     default:
4087       break;
4088     case clang::Type::Builtin:
4089       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4090       default:
4091       case clang::BuiltinType::Void:
4092       case clang::BuiltinType::Bool:
4093       case clang::BuiltinType::Char_U:
4094       case clang::BuiltinType::UChar:
4095       case clang::BuiltinType::WChar_U:
4096       case clang::BuiltinType::Char16:
4097       case clang::BuiltinType::Char32:
4098       case clang::BuiltinType::UShort:
4099       case clang::BuiltinType::UInt:
4100       case clang::BuiltinType::ULong:
4101       case clang::BuiltinType::ULongLong:
4102       case clang::BuiltinType::UInt128:
4103       case clang::BuiltinType::Char_S:
4104       case clang::BuiltinType::SChar:
4105       case clang::BuiltinType::WChar_S:
4106       case clang::BuiltinType::Short:
4107       case clang::BuiltinType::Int:
4108       case clang::BuiltinType::Long:
4109       case clang::BuiltinType::LongLong:
4110       case clang::BuiltinType::Int128:
4111       case clang::BuiltinType::Float:
4112       case clang::BuiltinType::Double:
4113       case clang::BuiltinType::LongDouble:
4114         break;
4115 
4116       case clang::BuiltinType::NullPtr:
4117         return eLanguageTypeC_plus_plus;
4118 
4119       case clang::BuiltinType::ObjCId:
4120       case clang::BuiltinType::ObjCClass:
4121       case clang::BuiltinType::ObjCSel:
4122         return eLanguageTypeObjC;
4123 
4124       case clang::BuiltinType::Dependent:
4125       case clang::BuiltinType::Overload:
4126       case clang::BuiltinType::BoundMember:
4127       case clang::BuiltinType::UnknownAny:
4128         break;
4129       }
4130       break;
4131     case clang::Type::Typedef:
4132       return GetType(llvm::cast<clang::TypedefType>(qual_type)
4133                          ->getDecl()
4134                          ->getUnderlyingType())
4135           .GetMinimumLanguage();
4136     }
4137   }
4138   return lldb::eLanguageTypeC;
4139 }
4140 
4141 lldb::TypeClass
4142 TypeSystemClang::GetTypeClass(lldb::opaque_compiler_type_t type) {
4143   if (!type)
4144     return lldb::eTypeClassInvalid;
4145 
4146   clang::QualType qual_type =
4147       RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
4148 
4149   switch (qual_type->getTypeClass()) {
4150   case clang::Type::Atomic:
4151   case clang::Type::Auto:
4152   case clang::Type::Decltype:
4153   case clang::Type::Elaborated:
4154   case clang::Type::Paren:
4155   case clang::Type::TypeOf:
4156   case clang::Type::TypeOfExpr:
4157   case clang::Type::Using:
4158     llvm_unreachable("Handled in RemoveWrappingTypes!");
4159   case clang::Type::UnaryTransform:
4160     break;
4161   case clang::Type::FunctionNoProto:
4162     return lldb::eTypeClassFunction;
4163   case clang::Type::FunctionProto:
4164     return lldb::eTypeClassFunction;
4165   case clang::Type::IncompleteArray:
4166     return lldb::eTypeClassArray;
4167   case clang::Type::VariableArray:
4168     return lldb::eTypeClassArray;
4169   case clang::Type::ConstantArray:
4170     return lldb::eTypeClassArray;
4171   case clang::Type::DependentSizedArray:
4172     return lldb::eTypeClassArray;
4173   case clang::Type::DependentSizedExtVector:
4174     return lldb::eTypeClassVector;
4175   case clang::Type::DependentVector:
4176     return lldb::eTypeClassVector;
4177   case clang::Type::ExtVector:
4178     return lldb::eTypeClassVector;
4179   case clang::Type::Vector:
4180     return lldb::eTypeClassVector;
4181   case clang::Type::Builtin:
4182   // Ext-Int is just an integer type.
4183   case clang::Type::BitInt:
4184   case clang::Type::DependentBitInt:
4185     return lldb::eTypeClassBuiltin;
4186   case clang::Type::ObjCObjectPointer:
4187     return lldb::eTypeClassObjCObjectPointer;
4188   case clang::Type::BlockPointer:
4189     return lldb::eTypeClassBlockPointer;
4190   case clang::Type::Pointer:
4191     return lldb::eTypeClassPointer;
4192   case clang::Type::LValueReference:
4193     return lldb::eTypeClassReference;
4194   case clang::Type::RValueReference:
4195     return lldb::eTypeClassReference;
4196   case clang::Type::MemberPointer:
4197     return lldb::eTypeClassMemberPointer;
4198   case clang::Type::Complex:
4199     if (qual_type->isComplexType())
4200       return lldb::eTypeClassComplexFloat;
4201     else
4202       return lldb::eTypeClassComplexInteger;
4203   case clang::Type::ObjCObject:
4204     return lldb::eTypeClassObjCObject;
4205   case clang::Type::ObjCInterface:
4206     return lldb::eTypeClassObjCInterface;
4207   case clang::Type::Record: {
4208     const clang::RecordType *record_type =
4209         llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4210     const clang::RecordDecl *record_decl = record_type->getDecl();
4211     if (record_decl->isUnion())
4212       return lldb::eTypeClassUnion;
4213     else if (record_decl->isStruct())
4214       return lldb::eTypeClassStruct;
4215     else
4216       return lldb::eTypeClassClass;
4217   } break;
4218   case clang::Type::Enum:
4219     return lldb::eTypeClassEnumeration;
4220   case clang::Type::Typedef:
4221     return lldb::eTypeClassTypedef;
4222   case clang::Type::UnresolvedUsing:
4223     break;
4224 
4225   case clang::Type::Attributed:
4226   case clang::Type::BTFTagAttributed:
4227     break;
4228   case clang::Type::TemplateTypeParm:
4229     break;
4230   case clang::Type::SubstTemplateTypeParm:
4231     break;
4232   case clang::Type::SubstTemplateTypeParmPack:
4233     break;
4234   case clang::Type::InjectedClassName:
4235     break;
4236   case clang::Type::DependentName:
4237     break;
4238   case clang::Type::DependentTemplateSpecialization:
4239     break;
4240   case clang::Type::PackExpansion:
4241     break;
4242 
4243   case clang::Type::TemplateSpecialization:
4244     break;
4245   case clang::Type::DeducedTemplateSpecialization:
4246     break;
4247   case clang::Type::Pipe:
4248     break;
4249 
4250   // pointer type decayed from an array or function type.
4251   case clang::Type::Decayed:
4252     break;
4253   case clang::Type::Adjusted:
4254     break;
4255   case clang::Type::ObjCTypeParam:
4256     break;
4257 
4258   case clang::Type::DependentAddressSpace:
4259     break;
4260   case clang::Type::MacroQualified:
4261     break;
4262 
4263   // Matrix types that we're not sure how to display at the moment.
4264   case clang::Type::ConstantMatrix:
4265   case clang::Type::DependentSizedMatrix:
4266     break;
4267   }
4268   // We don't know hot to display this type...
4269   return lldb::eTypeClassOther;
4270 }
4271 
4272 unsigned TypeSystemClang::GetTypeQualifiers(lldb::opaque_compiler_type_t type) {
4273   if (type)
4274     return GetQualType(type).getQualifiers().getCVRQualifiers();
4275   return 0;
4276 }
4277 
4278 // Creating related types
4279 
4280 CompilerType
4281 TypeSystemClang::GetArrayElementType(lldb::opaque_compiler_type_t type,
4282                                      ExecutionContextScope *exe_scope) {
4283   if (type) {
4284     clang::QualType qual_type(GetQualType(type));
4285 
4286     const clang::Type *array_eletype =
4287         qual_type.getTypePtr()->getArrayElementTypeNoTypeQual();
4288 
4289     if (!array_eletype)
4290       return CompilerType();
4291 
4292     return GetType(clang::QualType(array_eletype, 0));
4293   }
4294   return CompilerType();
4295 }
4296 
4297 CompilerType TypeSystemClang::GetArrayType(lldb::opaque_compiler_type_t type,
4298                                            uint64_t size) {
4299   if (type) {
4300     clang::QualType qual_type(GetCanonicalQualType(type));
4301     clang::ASTContext &ast_ctx = getASTContext();
4302     if (size != 0)
4303       return GetType(ast_ctx.getConstantArrayType(
4304           qual_type, llvm::APInt(64, size), nullptr,
4305           clang::ArrayType::ArraySizeModifier::Normal, 0));
4306     else
4307       return GetType(ast_ctx.getIncompleteArrayType(
4308           qual_type, clang::ArrayType::ArraySizeModifier::Normal, 0));
4309   }
4310 
4311   return CompilerType();
4312 }
4313 
4314 CompilerType
4315 TypeSystemClang::GetCanonicalType(lldb::opaque_compiler_type_t type) {
4316   if (type)
4317     return GetType(GetCanonicalQualType(type));
4318   return CompilerType();
4319 }
4320 
4321 static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast,
4322                                                     clang::QualType qual_type) {
4323   if (qual_type->isPointerType())
4324     qual_type = ast->getPointerType(
4325         GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType()));
4326   else if (const ConstantArrayType *arr =
4327                ast->getAsConstantArrayType(qual_type)) {
4328     qual_type = ast->getConstantArrayType(
4329         GetFullyUnqualifiedType_Impl(ast, arr->getElementType()),
4330         arr->getSize(), arr->getSizeExpr(), arr->getSizeModifier(),
4331         arr->getIndexTypeQualifiers().getAsOpaqueValue());
4332   } else
4333     qual_type = qual_type.getUnqualifiedType();
4334   qual_type.removeLocalConst();
4335   qual_type.removeLocalRestrict();
4336   qual_type.removeLocalVolatile();
4337   return qual_type;
4338 }
4339 
4340 CompilerType
4341 TypeSystemClang::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) {
4342   if (type)
4343     return GetType(
4344         GetFullyUnqualifiedType_Impl(&getASTContext(), GetQualType(type)));
4345   return CompilerType();
4346 }
4347 
4348 CompilerType
4349 TypeSystemClang::GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) {
4350   if (type)
4351     return GetEnumerationIntegerType(GetType(GetCanonicalQualType(type)));
4352   return CompilerType();
4353 }
4354 
4355 int TypeSystemClang::GetFunctionArgumentCount(
4356     lldb::opaque_compiler_type_t type) {
4357   if (type) {
4358     const clang::FunctionProtoType *func =
4359         llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type));
4360     if (func)
4361       return func->getNumParams();
4362   }
4363   return -1;
4364 }
4365 
4366 CompilerType TypeSystemClang::GetFunctionArgumentTypeAtIndex(
4367     lldb::opaque_compiler_type_t type, size_t idx) {
4368   if (type) {
4369     const clang::FunctionProtoType *func =
4370         llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type));
4371     if (func) {
4372       const uint32_t num_args = func->getNumParams();
4373       if (idx < num_args)
4374         return GetType(func->getParamType(idx));
4375     }
4376   }
4377   return CompilerType();
4378 }
4379 
4380 CompilerType
4381 TypeSystemClang::GetFunctionReturnType(lldb::opaque_compiler_type_t type) {
4382   if (type) {
4383     clang::QualType qual_type(GetQualType(type));
4384     const clang::FunctionProtoType *func =
4385         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
4386     if (func)
4387       return GetType(func->getReturnType());
4388   }
4389   return CompilerType();
4390 }
4391 
4392 size_t
4393 TypeSystemClang::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) {
4394   size_t num_functions = 0;
4395   if (type) {
4396     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4397     switch (qual_type->getTypeClass()) {
4398     case clang::Type::Record:
4399       if (GetCompleteQualType(&getASTContext(), qual_type)) {
4400         const clang::RecordType *record_type =
4401             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4402         const clang::RecordDecl *record_decl = record_type->getDecl();
4403         assert(record_decl);
4404         const clang::CXXRecordDecl *cxx_record_decl =
4405             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4406         if (cxx_record_decl)
4407           num_functions = std::distance(cxx_record_decl->method_begin(),
4408                                         cxx_record_decl->method_end());
4409       }
4410       break;
4411 
4412     case clang::Type::ObjCObjectPointer: {
4413       const clang::ObjCObjectPointerType *objc_class_type =
4414           qual_type->castAs<clang::ObjCObjectPointerType>();
4415       const clang::ObjCInterfaceType *objc_interface_type =
4416           objc_class_type->getInterfaceType();
4417       if (objc_interface_type &&
4418           GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4419               const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4420         clang::ObjCInterfaceDecl *class_interface_decl =
4421             objc_interface_type->getDecl();
4422         if (class_interface_decl) {
4423           num_functions = std::distance(class_interface_decl->meth_begin(),
4424                                         class_interface_decl->meth_end());
4425         }
4426       }
4427       break;
4428     }
4429 
4430     case clang::Type::ObjCObject:
4431     case clang::Type::ObjCInterface:
4432       if (GetCompleteType(type)) {
4433         const clang::ObjCObjectType *objc_class_type =
4434             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4435         if (objc_class_type) {
4436           clang::ObjCInterfaceDecl *class_interface_decl =
4437               objc_class_type->getInterface();
4438           if (class_interface_decl)
4439             num_functions = std::distance(class_interface_decl->meth_begin(),
4440                                           class_interface_decl->meth_end());
4441         }
4442       }
4443       break;
4444 
4445     default:
4446       break;
4447     }
4448   }
4449   return num_functions;
4450 }
4451 
4452 TypeMemberFunctionImpl
4453 TypeSystemClang::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
4454                                           size_t idx) {
4455   std::string name;
4456   MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
4457   CompilerType clang_type;
4458   CompilerDecl clang_decl;
4459   if (type) {
4460     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4461     switch (qual_type->getTypeClass()) {
4462     case clang::Type::Record:
4463       if (GetCompleteQualType(&getASTContext(), qual_type)) {
4464         const clang::RecordType *record_type =
4465             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4466         const clang::RecordDecl *record_decl = record_type->getDecl();
4467         assert(record_decl);
4468         const clang::CXXRecordDecl *cxx_record_decl =
4469             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4470         if (cxx_record_decl) {
4471           auto method_iter = cxx_record_decl->method_begin();
4472           auto method_end = cxx_record_decl->method_end();
4473           if (idx <
4474               static_cast<size_t>(std::distance(method_iter, method_end))) {
4475             std::advance(method_iter, idx);
4476             clang::CXXMethodDecl *cxx_method_decl =
4477                 method_iter->getCanonicalDecl();
4478             if (cxx_method_decl) {
4479               name = cxx_method_decl->getDeclName().getAsString();
4480               if (cxx_method_decl->isStatic())
4481                 kind = lldb::eMemberFunctionKindStaticMethod;
4482               else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4483                 kind = lldb::eMemberFunctionKindConstructor;
4484               else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4485                 kind = lldb::eMemberFunctionKindDestructor;
4486               else
4487                 kind = lldb::eMemberFunctionKindInstanceMethod;
4488               clang_type = GetType(cxx_method_decl->getType());
4489               clang_decl = GetCompilerDecl(cxx_method_decl);
4490             }
4491           }
4492         }
4493       }
4494       break;
4495 
4496     case clang::Type::ObjCObjectPointer: {
4497       const clang::ObjCObjectPointerType *objc_class_type =
4498           qual_type->castAs<clang::ObjCObjectPointerType>();
4499       const clang::ObjCInterfaceType *objc_interface_type =
4500           objc_class_type->getInterfaceType();
4501       if (objc_interface_type &&
4502           GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4503               const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4504         clang::ObjCInterfaceDecl *class_interface_decl =
4505             objc_interface_type->getDecl();
4506         if (class_interface_decl) {
4507           auto method_iter = class_interface_decl->meth_begin();
4508           auto method_end = class_interface_decl->meth_end();
4509           if (idx <
4510               static_cast<size_t>(std::distance(method_iter, method_end))) {
4511             std::advance(method_iter, idx);
4512             clang::ObjCMethodDecl *objc_method_decl =
4513                 method_iter->getCanonicalDecl();
4514             if (objc_method_decl) {
4515               clang_decl = GetCompilerDecl(objc_method_decl);
4516               name = objc_method_decl->getSelector().getAsString();
4517               if (objc_method_decl->isClassMethod())
4518                 kind = lldb::eMemberFunctionKindStaticMethod;
4519               else
4520                 kind = lldb::eMemberFunctionKindInstanceMethod;
4521             }
4522           }
4523         }
4524       }
4525       break;
4526     }
4527 
4528     case clang::Type::ObjCObject:
4529     case clang::Type::ObjCInterface:
4530       if (GetCompleteType(type)) {
4531         const clang::ObjCObjectType *objc_class_type =
4532             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4533         if (objc_class_type) {
4534           clang::ObjCInterfaceDecl *class_interface_decl =
4535               objc_class_type->getInterface();
4536           if (class_interface_decl) {
4537             auto method_iter = class_interface_decl->meth_begin();
4538             auto method_end = class_interface_decl->meth_end();
4539             if (idx <
4540                 static_cast<size_t>(std::distance(method_iter, method_end))) {
4541               std::advance(method_iter, idx);
4542               clang::ObjCMethodDecl *objc_method_decl =
4543                   method_iter->getCanonicalDecl();
4544               if (objc_method_decl) {
4545                 clang_decl = GetCompilerDecl(objc_method_decl);
4546                 name = objc_method_decl->getSelector().getAsString();
4547                 if (objc_method_decl->isClassMethod())
4548                   kind = lldb::eMemberFunctionKindStaticMethod;
4549                 else
4550                   kind = lldb::eMemberFunctionKindInstanceMethod;
4551               }
4552             }
4553           }
4554         }
4555       }
4556       break;
4557 
4558     default:
4559       break;
4560     }
4561   }
4562 
4563   if (kind == eMemberFunctionKindUnknown)
4564     return TypeMemberFunctionImpl();
4565   else
4566     return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind);
4567 }
4568 
4569 CompilerType
4570 TypeSystemClang::GetNonReferenceType(lldb::opaque_compiler_type_t type) {
4571   if (type)
4572     return GetType(GetQualType(type).getNonReferenceType());
4573   return CompilerType();
4574 }
4575 
4576 CompilerType
4577 TypeSystemClang::GetPointeeType(lldb::opaque_compiler_type_t type) {
4578   if (type) {
4579     clang::QualType qual_type(GetQualType(type));
4580     return GetType(qual_type.getTypePtr()->getPointeeType());
4581   }
4582   return CompilerType();
4583 }
4584 
4585 CompilerType
4586 TypeSystemClang::GetPointerType(lldb::opaque_compiler_type_t type) {
4587   if (type) {
4588     clang::QualType qual_type(GetQualType(type));
4589 
4590     switch (qual_type.getDesugaredType(getASTContext())->getTypeClass()) {
4591     case clang::Type::ObjCObject:
4592     case clang::Type::ObjCInterface:
4593       return GetType(getASTContext().getObjCObjectPointerType(qual_type));
4594 
4595     default:
4596       return GetType(getASTContext().getPointerType(qual_type));
4597     }
4598   }
4599   return CompilerType();
4600 }
4601 
4602 CompilerType
4603 TypeSystemClang::GetLValueReferenceType(lldb::opaque_compiler_type_t type) {
4604   if (type)
4605     return GetType(getASTContext().getLValueReferenceType(GetQualType(type)));
4606   else
4607     return CompilerType();
4608 }
4609 
4610 CompilerType
4611 TypeSystemClang::GetRValueReferenceType(lldb::opaque_compiler_type_t type) {
4612   if (type)
4613     return GetType(getASTContext().getRValueReferenceType(GetQualType(type)));
4614   else
4615     return CompilerType();
4616 }
4617 
4618 CompilerType TypeSystemClang::GetAtomicType(lldb::opaque_compiler_type_t type) {
4619   if (!type)
4620     return CompilerType();
4621   return GetType(getASTContext().getAtomicType(GetQualType(type)));
4622 }
4623 
4624 CompilerType
4625 TypeSystemClang::AddConstModifier(lldb::opaque_compiler_type_t type) {
4626   if (type) {
4627     clang::QualType result(GetQualType(type));
4628     result.addConst();
4629     return GetType(result);
4630   }
4631   return CompilerType();
4632 }
4633 
4634 CompilerType
4635 TypeSystemClang::AddVolatileModifier(lldb::opaque_compiler_type_t type) {
4636   if (type) {
4637     clang::QualType result(GetQualType(type));
4638     result.addVolatile();
4639     return GetType(result);
4640   }
4641   return CompilerType();
4642 }
4643 
4644 CompilerType
4645 TypeSystemClang::AddRestrictModifier(lldb::opaque_compiler_type_t type) {
4646   if (type) {
4647     clang::QualType result(GetQualType(type));
4648     result.addRestrict();
4649     return GetType(result);
4650   }
4651   return CompilerType();
4652 }
4653 
4654 CompilerType TypeSystemClang::CreateTypedef(
4655     lldb::opaque_compiler_type_t type, const char *typedef_name,
4656     const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) {
4657   if (type && typedef_name && typedef_name[0]) {
4658     clang::ASTContext &clang_ast = getASTContext();
4659     clang::QualType qual_type(GetQualType(type));
4660 
4661     clang::DeclContext *decl_ctx =
4662         TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx);
4663     if (!decl_ctx)
4664       decl_ctx = getASTContext().getTranslationUnitDecl();
4665 
4666     clang::TypedefDecl *decl =
4667         clang::TypedefDecl::CreateDeserialized(clang_ast, 0);
4668     decl->setDeclContext(decl_ctx);
4669     decl->setDeclName(&clang_ast.Idents.get(typedef_name));
4670     decl->setTypeSourceInfo(clang_ast.getTrivialTypeSourceInfo(qual_type));
4671     decl_ctx->addDecl(decl);
4672     SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule());
4673 
4674     clang::TagDecl *tdecl = nullptr;
4675     if (!qual_type.isNull()) {
4676       if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>())
4677         tdecl = rt->getDecl();
4678       if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>())
4679         tdecl = et->getDecl();
4680     }
4681 
4682     // Check whether this declaration is an anonymous struct, union, or enum,
4683     // hidden behind a typedef. If so, we try to check whether we have a
4684     // typedef tag to attach to the original record declaration
4685     if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl())
4686       tdecl->setTypedefNameForAnonDecl(decl);
4687 
4688     decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4689 
4690     // Get a uniqued clang::QualType for the typedef decl type
4691     return GetType(clang_ast.getTypedefType(decl));
4692   }
4693   return CompilerType();
4694 }
4695 
4696 CompilerType
4697 TypeSystemClang::GetTypedefedType(lldb::opaque_compiler_type_t type) {
4698   if (type) {
4699     const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(
4700         RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}));
4701     if (typedef_type)
4702       return GetType(typedef_type->getDecl()->getUnderlyingType());
4703   }
4704   return CompilerType();
4705 }
4706 
4707 // Create related types using the current type's AST
4708 
4709 CompilerType TypeSystemClang::GetBasicTypeFromAST(lldb::BasicType basic_type) {
4710   return TypeSystemClang::GetBasicType(basic_type);
4711 }
4712 // Exploring the type
4713 
4714 const llvm::fltSemantics &
4715 TypeSystemClang::GetFloatTypeSemantics(size_t byte_size) {
4716   clang::ASTContext &ast = getASTContext();
4717   const size_t bit_size = byte_size * 8;
4718   if (bit_size == ast.getTypeSize(ast.FloatTy))
4719     return ast.getFloatTypeSemantics(ast.FloatTy);
4720   else if (bit_size == ast.getTypeSize(ast.DoubleTy))
4721     return ast.getFloatTypeSemantics(ast.DoubleTy);
4722   else if (bit_size == ast.getTypeSize(ast.LongDoubleTy) ||
4723            bit_size == llvm::APFloat::semanticsSizeInBits(
4724                            ast.getFloatTypeSemantics(ast.LongDoubleTy)))
4725     return ast.getFloatTypeSemantics(ast.LongDoubleTy);
4726   else if (bit_size == ast.getTypeSize(ast.HalfTy))
4727     return ast.getFloatTypeSemantics(ast.HalfTy);
4728   return llvm::APFloatBase::Bogus();
4729 }
4730 
4731 std::optional<uint64_t>
4732 TypeSystemClang::GetBitSize(lldb::opaque_compiler_type_t type,
4733                             ExecutionContextScope *exe_scope) {
4734   if (GetCompleteType(type)) {
4735     clang::QualType qual_type(GetCanonicalQualType(type));
4736     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4737     switch (type_class) {
4738     case clang::Type::Record:
4739       if (GetCompleteType(type))
4740         return getASTContext().getTypeSize(qual_type);
4741       else
4742         return std::nullopt;
4743       break;
4744 
4745     case clang::Type::ObjCInterface:
4746     case clang::Type::ObjCObject: {
4747       ExecutionContext exe_ctx(exe_scope);
4748       Process *process = exe_ctx.GetProcessPtr();
4749       if (process) {
4750         ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
4751         if (objc_runtime) {
4752           uint64_t bit_size = 0;
4753           if (objc_runtime->GetTypeBitSize(GetType(qual_type), bit_size))
4754             return bit_size;
4755         }
4756       } else {
4757         static bool g_printed = false;
4758         if (!g_printed) {
4759           StreamString s;
4760           DumpTypeDescription(type, &s);
4761 
4762           llvm::outs() << "warning: trying to determine the size of type ";
4763           llvm::outs() << s.GetString() << "\n";
4764           llvm::outs() << "without a valid ExecutionContext. this is not "
4765                           "reliable. please file a bug against LLDB.\n";
4766           llvm::outs() << "backtrace:\n";
4767           llvm::sys::PrintStackTrace(llvm::outs());
4768           llvm::outs() << "\n";
4769           g_printed = true;
4770         }
4771       }
4772     }
4773       [[fallthrough]];
4774     default:
4775       const uint32_t bit_size = getASTContext().getTypeSize(qual_type);
4776       if (bit_size == 0) {
4777         if (qual_type->isIncompleteArrayType())
4778           return getASTContext().getTypeSize(
4779               qual_type->getArrayElementTypeNoTypeQual()
4780                   ->getCanonicalTypeUnqualified());
4781       }
4782       if (qual_type->isObjCObjectOrInterfaceType())
4783         return bit_size +
4784                getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy);
4785       // Function types actually have a size of 0, that's not an error.
4786       if (qual_type->isFunctionProtoType())
4787         return bit_size;
4788       if (bit_size)
4789         return bit_size;
4790     }
4791   }
4792   return std::nullopt;
4793 }
4794 
4795 std::optional<size_t>
4796 TypeSystemClang::GetTypeBitAlign(lldb::opaque_compiler_type_t type,
4797                                  ExecutionContextScope *exe_scope) {
4798   if (GetCompleteType(type))
4799     return getASTContext().getTypeAlign(GetQualType(type));
4800   return {};
4801 }
4802 
4803 lldb::Encoding TypeSystemClang::GetEncoding(lldb::opaque_compiler_type_t type,
4804                                             uint64_t &count) {
4805   if (!type)
4806     return lldb::eEncodingInvalid;
4807 
4808   count = 1;
4809   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4810 
4811   switch (qual_type->getTypeClass()) {
4812   case clang::Type::Atomic:
4813   case clang::Type::Auto:
4814   case clang::Type::Decltype:
4815   case clang::Type::Elaborated:
4816   case clang::Type::Paren:
4817   case clang::Type::Typedef:
4818   case clang::Type::TypeOf:
4819   case clang::Type::TypeOfExpr:
4820   case clang::Type::Using:
4821     llvm_unreachable("Handled in RemoveWrappingTypes!");
4822 
4823   case clang::Type::UnaryTransform:
4824     break;
4825 
4826   case clang::Type::FunctionNoProto:
4827   case clang::Type::FunctionProto:
4828     break;
4829 
4830   case clang::Type::IncompleteArray:
4831   case clang::Type::VariableArray:
4832     break;
4833 
4834   case clang::Type::ConstantArray:
4835     break;
4836 
4837   case clang::Type::DependentVector:
4838   case clang::Type::ExtVector:
4839   case clang::Type::Vector:
4840     // TODO: Set this to more than one???
4841     break;
4842 
4843   case clang::Type::BitInt:
4844   case clang::Type::DependentBitInt:
4845     return qual_type->isUnsignedIntegerType() ? lldb::eEncodingUint
4846                                               : lldb::eEncodingSint;
4847 
4848   case clang::Type::Builtin:
4849     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4850     case clang::BuiltinType::Void:
4851       break;
4852 
4853     case clang::BuiltinType::Char_S:
4854     case clang::BuiltinType::SChar:
4855     case clang::BuiltinType::WChar_S:
4856     case clang::BuiltinType::Short:
4857     case clang::BuiltinType::Int:
4858     case clang::BuiltinType::Long:
4859     case clang::BuiltinType::LongLong:
4860     case clang::BuiltinType::Int128:
4861       return lldb::eEncodingSint;
4862 
4863     case clang::BuiltinType::Bool:
4864     case clang::BuiltinType::Char_U:
4865     case clang::BuiltinType::UChar:
4866     case clang::BuiltinType::WChar_U:
4867     case clang::BuiltinType::Char8:
4868     case clang::BuiltinType::Char16:
4869     case clang::BuiltinType::Char32:
4870     case clang::BuiltinType::UShort:
4871     case clang::BuiltinType::UInt:
4872     case clang::BuiltinType::ULong:
4873     case clang::BuiltinType::ULongLong:
4874     case clang::BuiltinType::UInt128:
4875       return lldb::eEncodingUint;
4876 
4877     // Fixed point types. Note that they are currently ignored.
4878     case clang::BuiltinType::ShortAccum:
4879     case clang::BuiltinType::Accum:
4880     case clang::BuiltinType::LongAccum:
4881     case clang::BuiltinType::UShortAccum:
4882     case clang::BuiltinType::UAccum:
4883     case clang::BuiltinType::ULongAccum:
4884     case clang::BuiltinType::ShortFract:
4885     case clang::BuiltinType::Fract:
4886     case clang::BuiltinType::LongFract:
4887     case clang::BuiltinType::UShortFract:
4888     case clang::BuiltinType::UFract:
4889     case clang::BuiltinType::ULongFract:
4890     case clang::BuiltinType::SatShortAccum:
4891     case clang::BuiltinType::SatAccum:
4892     case clang::BuiltinType::SatLongAccum:
4893     case clang::BuiltinType::SatUShortAccum:
4894     case clang::BuiltinType::SatUAccum:
4895     case clang::BuiltinType::SatULongAccum:
4896     case clang::BuiltinType::SatShortFract:
4897     case clang::BuiltinType::SatFract:
4898     case clang::BuiltinType::SatLongFract:
4899     case clang::BuiltinType::SatUShortFract:
4900     case clang::BuiltinType::SatUFract:
4901     case clang::BuiltinType::SatULongFract:
4902       break;
4903 
4904     case clang::BuiltinType::Half:
4905     case clang::BuiltinType::Float:
4906     case clang::BuiltinType::Float16:
4907     case clang::BuiltinType::Float128:
4908     case clang::BuiltinType::Double:
4909     case clang::BuiltinType::LongDouble:
4910     case clang::BuiltinType::BFloat16:
4911     case clang::BuiltinType::Ibm128:
4912       return lldb::eEncodingIEEE754;
4913 
4914     case clang::BuiltinType::ObjCClass:
4915     case clang::BuiltinType::ObjCId:
4916     case clang::BuiltinType::ObjCSel:
4917       return lldb::eEncodingUint;
4918 
4919     case clang::BuiltinType::NullPtr:
4920       return lldb::eEncodingUint;
4921 
4922     case clang::BuiltinType::Kind::ARCUnbridgedCast:
4923     case clang::BuiltinType::Kind::BoundMember:
4924     case clang::BuiltinType::Kind::BuiltinFn:
4925     case clang::BuiltinType::Kind::Dependent:
4926     case clang::BuiltinType::Kind::OCLClkEvent:
4927     case clang::BuiltinType::Kind::OCLEvent:
4928     case clang::BuiltinType::Kind::OCLImage1dRO:
4929     case clang::BuiltinType::Kind::OCLImage1dWO:
4930     case clang::BuiltinType::Kind::OCLImage1dRW:
4931     case clang::BuiltinType::Kind::OCLImage1dArrayRO:
4932     case clang::BuiltinType::Kind::OCLImage1dArrayWO:
4933     case clang::BuiltinType::Kind::OCLImage1dArrayRW:
4934     case clang::BuiltinType::Kind::OCLImage1dBufferRO:
4935     case clang::BuiltinType::Kind::OCLImage1dBufferWO:
4936     case clang::BuiltinType::Kind::OCLImage1dBufferRW:
4937     case clang::BuiltinType::Kind::OCLImage2dRO:
4938     case clang::BuiltinType::Kind::OCLImage2dWO:
4939     case clang::BuiltinType::Kind::OCLImage2dRW:
4940     case clang::BuiltinType::Kind::OCLImage2dArrayRO:
4941     case clang::BuiltinType::Kind::OCLImage2dArrayWO:
4942     case clang::BuiltinType::Kind::OCLImage2dArrayRW:
4943     case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO:
4944     case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO:
4945     case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW:
4946     case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO:
4947     case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO:
4948     case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW:
4949     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO:
4950     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO:
4951     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW:
4952     case clang::BuiltinType::Kind::OCLImage2dDepthRO:
4953     case clang::BuiltinType::Kind::OCLImage2dDepthWO:
4954     case clang::BuiltinType::Kind::OCLImage2dDepthRW:
4955     case clang::BuiltinType::Kind::OCLImage2dMSAARO:
4956     case clang::BuiltinType::Kind::OCLImage2dMSAAWO:
4957     case clang::BuiltinType::Kind::OCLImage2dMSAARW:
4958     case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO:
4959     case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO:
4960     case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW:
4961     case clang::BuiltinType::Kind::OCLImage3dRO:
4962     case clang::BuiltinType::Kind::OCLImage3dWO:
4963     case clang::BuiltinType::Kind::OCLImage3dRW:
4964     case clang::BuiltinType::Kind::OCLQueue:
4965     case clang::BuiltinType::Kind::OCLReserveID:
4966     case clang::BuiltinType::Kind::OCLSampler:
4967     case clang::BuiltinType::Kind::OMPArraySection:
4968     case clang::BuiltinType::Kind::OMPArrayShaping:
4969     case clang::BuiltinType::Kind::OMPIterator:
4970     case clang::BuiltinType::Kind::Overload:
4971     case clang::BuiltinType::Kind::PseudoObject:
4972     case clang::BuiltinType::Kind::UnknownAny:
4973       break;
4974 
4975     case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
4976     case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
4977     case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
4978     case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
4979     case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
4980     case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
4981     case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
4982     case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
4983     case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout:
4984     case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout:
4985     case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin:
4986     case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin:
4987       break;
4988 
4989     // PowerPC -- Matrix Multiply Assist
4990     case clang::BuiltinType::VectorPair:
4991     case clang::BuiltinType::VectorQuad:
4992       break;
4993 
4994     // ARM -- Scalable Vector Extension
4995     case clang::BuiltinType::SveBool:
4996     case clang::BuiltinType::SveInt8:
4997     case clang::BuiltinType::SveInt8x2:
4998     case clang::BuiltinType::SveInt8x3:
4999     case clang::BuiltinType::SveInt8x4:
5000     case clang::BuiltinType::SveInt16:
5001     case clang::BuiltinType::SveInt16x2:
5002     case clang::BuiltinType::SveInt16x3:
5003     case clang::BuiltinType::SveInt16x4:
5004     case clang::BuiltinType::SveInt32:
5005     case clang::BuiltinType::SveInt32x2:
5006     case clang::BuiltinType::SveInt32x3:
5007     case clang::BuiltinType::SveInt32x4:
5008     case clang::BuiltinType::SveInt64:
5009     case clang::BuiltinType::SveInt64x2:
5010     case clang::BuiltinType::SveInt64x3:
5011     case clang::BuiltinType::SveInt64x4:
5012     case clang::BuiltinType::SveUint8:
5013     case clang::BuiltinType::SveUint8x2:
5014     case clang::BuiltinType::SveUint8x3:
5015     case clang::BuiltinType::SveUint8x4:
5016     case clang::BuiltinType::SveUint16:
5017     case clang::BuiltinType::SveUint16x2:
5018     case clang::BuiltinType::SveUint16x3:
5019     case clang::BuiltinType::SveUint16x4:
5020     case clang::BuiltinType::SveUint32:
5021     case clang::BuiltinType::SveUint32x2:
5022     case clang::BuiltinType::SveUint32x3:
5023     case clang::BuiltinType::SveUint32x4:
5024     case clang::BuiltinType::SveUint64:
5025     case clang::BuiltinType::SveUint64x2:
5026     case clang::BuiltinType::SveUint64x3:
5027     case clang::BuiltinType::SveUint64x4:
5028     case clang::BuiltinType::SveFloat16:
5029     case clang::BuiltinType::SveBFloat16:
5030     case clang::BuiltinType::SveBFloat16x2:
5031     case clang::BuiltinType::SveBFloat16x3:
5032     case clang::BuiltinType::SveBFloat16x4:
5033     case clang::BuiltinType::SveFloat16x2:
5034     case clang::BuiltinType::SveFloat16x3:
5035     case clang::BuiltinType::SveFloat16x4:
5036     case clang::BuiltinType::SveFloat32:
5037     case clang::BuiltinType::SveFloat32x2:
5038     case clang::BuiltinType::SveFloat32x3:
5039     case clang::BuiltinType::SveFloat32x4:
5040     case clang::BuiltinType::SveFloat64:
5041     case clang::BuiltinType::SveFloat64x2:
5042     case clang::BuiltinType::SveFloat64x3:
5043     case clang::BuiltinType::SveFloat64x4:
5044       break;
5045 
5046     // RISC-V V builtin types.
5047     case clang::BuiltinType::RvvInt8mf8:
5048     case clang::BuiltinType::RvvInt8mf4:
5049     case clang::BuiltinType::RvvInt8mf2:
5050     case clang::BuiltinType::RvvInt8m1:
5051     case clang::BuiltinType::RvvInt8m2:
5052     case clang::BuiltinType::RvvInt8m4:
5053     case clang::BuiltinType::RvvInt8m8:
5054     case clang::BuiltinType::RvvUint8mf8:
5055     case clang::BuiltinType::RvvUint8mf4:
5056     case clang::BuiltinType::RvvUint8mf2:
5057     case clang::BuiltinType::RvvUint8m1:
5058     case clang::BuiltinType::RvvUint8m2:
5059     case clang::BuiltinType::RvvUint8m4:
5060     case clang::BuiltinType::RvvUint8m8:
5061     case clang::BuiltinType::RvvInt16mf4:
5062     case clang::BuiltinType::RvvInt16mf2:
5063     case clang::BuiltinType::RvvInt16m1:
5064     case clang::BuiltinType::RvvInt16m2:
5065     case clang::BuiltinType::RvvInt16m4:
5066     case clang::BuiltinType::RvvInt16m8:
5067     case clang::BuiltinType::RvvUint16mf4:
5068     case clang::BuiltinType::RvvUint16mf2:
5069     case clang::BuiltinType::RvvUint16m1:
5070     case clang::BuiltinType::RvvUint16m2:
5071     case clang::BuiltinType::RvvUint16m4:
5072     case clang::BuiltinType::RvvUint16m8:
5073     case clang::BuiltinType::RvvInt32mf2:
5074     case clang::BuiltinType::RvvInt32m1:
5075     case clang::BuiltinType::RvvInt32m2:
5076     case clang::BuiltinType::RvvInt32m4:
5077     case clang::BuiltinType::RvvInt32m8:
5078     case clang::BuiltinType::RvvUint32mf2:
5079     case clang::BuiltinType::RvvUint32m1:
5080     case clang::BuiltinType::RvvUint32m2:
5081     case clang::BuiltinType::RvvUint32m4:
5082     case clang::BuiltinType::RvvUint32m8:
5083     case clang::BuiltinType::RvvInt64m1:
5084     case clang::BuiltinType::RvvInt64m2:
5085     case clang::BuiltinType::RvvInt64m4:
5086     case clang::BuiltinType::RvvInt64m8:
5087     case clang::BuiltinType::RvvUint64m1:
5088     case clang::BuiltinType::RvvUint64m2:
5089     case clang::BuiltinType::RvvUint64m4:
5090     case clang::BuiltinType::RvvUint64m8:
5091     case clang::BuiltinType::RvvFloat16mf4:
5092     case clang::BuiltinType::RvvFloat16mf2:
5093     case clang::BuiltinType::RvvFloat16m1:
5094     case clang::BuiltinType::RvvFloat16m2:
5095     case clang::BuiltinType::RvvFloat16m4:
5096     case clang::BuiltinType::RvvFloat16m8:
5097     case clang::BuiltinType::RvvFloat32mf2:
5098     case clang::BuiltinType::RvvFloat32m1:
5099     case clang::BuiltinType::RvvFloat32m2:
5100     case clang::BuiltinType::RvvFloat32m4:
5101     case clang::BuiltinType::RvvFloat32m8:
5102     case clang::BuiltinType::RvvFloat64m1:
5103     case clang::BuiltinType::RvvFloat64m2:
5104     case clang::BuiltinType::RvvFloat64m4:
5105     case clang::BuiltinType::RvvFloat64m8:
5106     case clang::BuiltinType::RvvBool1:
5107     case clang::BuiltinType::RvvBool2:
5108     case clang::BuiltinType::RvvBool4:
5109     case clang::BuiltinType::RvvBool8:
5110     case clang::BuiltinType::RvvBool16:
5111     case clang::BuiltinType::RvvBool32:
5112     case clang::BuiltinType::RvvBool64:
5113       break;
5114 
5115     case clang::BuiltinType::IncompleteMatrixIdx:
5116       break;
5117     }
5118     break;
5119   // All pointer types are represented as unsigned integer encodings. We may
5120   // nee to add a eEncodingPointer if we ever need to know the difference
5121   case clang::Type::ObjCObjectPointer:
5122   case clang::Type::BlockPointer:
5123   case clang::Type::Pointer:
5124   case clang::Type::LValueReference:
5125   case clang::Type::RValueReference:
5126   case clang::Type::MemberPointer:
5127     return lldb::eEncodingUint;
5128   case clang::Type::Complex: {
5129     lldb::Encoding encoding = lldb::eEncodingIEEE754;
5130     if (qual_type->isComplexType())
5131       encoding = lldb::eEncodingIEEE754;
5132     else {
5133       const clang::ComplexType *complex_type =
5134           qual_type->getAsComplexIntegerType();
5135       if (complex_type)
5136         encoding = GetType(complex_type->getElementType()).GetEncoding(count);
5137       else
5138         encoding = lldb::eEncodingSint;
5139     }
5140     count = 2;
5141     return encoding;
5142   }
5143 
5144   case clang::Type::ObjCInterface:
5145     break;
5146   case clang::Type::Record:
5147     break;
5148   case clang::Type::Enum:
5149     return qual_type->isUnsignedIntegerOrEnumerationType()
5150                ? lldb::eEncodingUint
5151                : lldb::eEncodingSint;
5152   case clang::Type::DependentSizedArray:
5153   case clang::Type::DependentSizedExtVector:
5154   case clang::Type::UnresolvedUsing:
5155   case clang::Type::Attributed:
5156   case clang::Type::BTFTagAttributed:
5157   case clang::Type::TemplateTypeParm:
5158   case clang::Type::SubstTemplateTypeParm:
5159   case clang::Type::SubstTemplateTypeParmPack:
5160   case clang::Type::InjectedClassName:
5161   case clang::Type::DependentName:
5162   case clang::Type::DependentTemplateSpecialization:
5163   case clang::Type::PackExpansion:
5164   case clang::Type::ObjCObject:
5165 
5166   case clang::Type::TemplateSpecialization:
5167   case clang::Type::DeducedTemplateSpecialization:
5168   case clang::Type::Adjusted:
5169   case clang::Type::Pipe:
5170     break;
5171 
5172   // pointer type decayed from an array or function type.
5173   case clang::Type::Decayed:
5174     break;
5175   case clang::Type::ObjCTypeParam:
5176     break;
5177 
5178   case clang::Type::DependentAddressSpace:
5179     break;
5180   case clang::Type::MacroQualified:
5181     break;
5182 
5183   case clang::Type::ConstantMatrix:
5184   case clang::Type::DependentSizedMatrix:
5185     break;
5186   }
5187   count = 0;
5188   return lldb::eEncodingInvalid;
5189 }
5190 
5191 lldb::Format TypeSystemClang::GetFormat(lldb::opaque_compiler_type_t type) {
5192   if (!type)
5193     return lldb::eFormatDefault;
5194 
5195   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5196 
5197   switch (qual_type->getTypeClass()) {
5198   case clang::Type::Atomic:
5199   case clang::Type::Auto:
5200   case clang::Type::Decltype:
5201   case clang::Type::Elaborated:
5202   case clang::Type::Paren:
5203   case clang::Type::Typedef:
5204   case clang::Type::TypeOf:
5205   case clang::Type::TypeOfExpr:
5206   case clang::Type::Using:
5207     llvm_unreachable("Handled in RemoveWrappingTypes!");
5208   case clang::Type::UnaryTransform:
5209     break;
5210 
5211   case clang::Type::FunctionNoProto:
5212   case clang::Type::FunctionProto:
5213     break;
5214 
5215   case clang::Type::IncompleteArray:
5216   case clang::Type::VariableArray:
5217     break;
5218 
5219   case clang::Type::ConstantArray:
5220     return lldb::eFormatVoid; // no value
5221 
5222   case clang::Type::DependentVector:
5223   case clang::Type::ExtVector:
5224   case clang::Type::Vector:
5225     break;
5226 
5227   case clang::Type::BitInt:
5228   case clang::Type::DependentBitInt:
5229     return qual_type->isUnsignedIntegerType() ? lldb::eFormatUnsigned
5230                                               : lldb::eFormatDecimal;
5231 
5232   case clang::Type::Builtin:
5233     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5234     case clang::BuiltinType::UnknownAny:
5235     case clang::BuiltinType::Void:
5236     case clang::BuiltinType::BoundMember:
5237       break;
5238 
5239     case clang::BuiltinType::Bool:
5240       return lldb::eFormatBoolean;
5241     case clang::BuiltinType::Char_S:
5242     case clang::BuiltinType::SChar:
5243     case clang::BuiltinType::WChar_S:
5244     case clang::BuiltinType::Char_U:
5245     case clang::BuiltinType::UChar:
5246     case clang::BuiltinType::WChar_U:
5247       return lldb::eFormatChar;
5248     case clang::BuiltinType::Char8:
5249       return lldb::eFormatUnicode8;
5250     case clang::BuiltinType::Char16:
5251       return lldb::eFormatUnicode16;
5252     case clang::BuiltinType::Char32:
5253       return lldb::eFormatUnicode32;
5254     case clang::BuiltinType::UShort:
5255       return lldb::eFormatUnsigned;
5256     case clang::BuiltinType::Short:
5257       return lldb::eFormatDecimal;
5258     case clang::BuiltinType::UInt:
5259       return lldb::eFormatUnsigned;
5260     case clang::BuiltinType::Int:
5261       return lldb::eFormatDecimal;
5262     case clang::BuiltinType::ULong:
5263       return lldb::eFormatUnsigned;
5264     case clang::BuiltinType::Long:
5265       return lldb::eFormatDecimal;
5266     case clang::BuiltinType::ULongLong:
5267       return lldb::eFormatUnsigned;
5268     case clang::BuiltinType::LongLong:
5269       return lldb::eFormatDecimal;
5270     case clang::BuiltinType::UInt128:
5271       return lldb::eFormatUnsigned;
5272     case clang::BuiltinType::Int128:
5273       return lldb::eFormatDecimal;
5274     case clang::BuiltinType::Half:
5275     case clang::BuiltinType::Float:
5276     case clang::BuiltinType::Double:
5277     case clang::BuiltinType::LongDouble:
5278       return lldb::eFormatFloat;
5279     default:
5280       return lldb::eFormatHex;
5281     }
5282     break;
5283   case clang::Type::ObjCObjectPointer:
5284     return lldb::eFormatHex;
5285   case clang::Type::BlockPointer:
5286     return lldb::eFormatHex;
5287   case clang::Type::Pointer:
5288     return lldb::eFormatHex;
5289   case clang::Type::LValueReference:
5290   case clang::Type::RValueReference:
5291     return lldb::eFormatHex;
5292   case clang::Type::MemberPointer:
5293     break;
5294   case clang::Type::Complex: {
5295     if (qual_type->isComplexType())
5296       return lldb::eFormatComplex;
5297     else
5298       return lldb::eFormatComplexInteger;
5299   }
5300   case clang::Type::ObjCInterface:
5301     break;
5302   case clang::Type::Record:
5303     break;
5304   case clang::Type::Enum:
5305     return lldb::eFormatEnum;
5306   case clang::Type::DependentSizedArray:
5307   case clang::Type::DependentSizedExtVector:
5308   case clang::Type::UnresolvedUsing:
5309   case clang::Type::Attributed:
5310   case clang::Type::BTFTagAttributed:
5311   case clang::Type::TemplateTypeParm:
5312   case clang::Type::SubstTemplateTypeParm:
5313   case clang::Type::SubstTemplateTypeParmPack:
5314   case clang::Type::InjectedClassName:
5315   case clang::Type::DependentName:
5316   case clang::Type::DependentTemplateSpecialization:
5317   case clang::Type::PackExpansion:
5318   case clang::Type::ObjCObject:
5319 
5320   case clang::Type::TemplateSpecialization:
5321   case clang::Type::DeducedTemplateSpecialization:
5322   case clang::Type::Adjusted:
5323   case clang::Type::Pipe:
5324     break;
5325 
5326   // pointer type decayed from an array or function type.
5327   case clang::Type::Decayed:
5328     break;
5329   case clang::Type::ObjCTypeParam:
5330     break;
5331 
5332   case clang::Type::DependentAddressSpace:
5333     break;
5334   case clang::Type::MacroQualified:
5335     break;
5336 
5337   // Matrix types we're not sure how to display yet.
5338   case clang::Type::ConstantMatrix:
5339   case clang::Type::DependentSizedMatrix:
5340     break;
5341   }
5342   // We don't know hot to display this type...
5343   return lldb::eFormatBytes;
5344 }
5345 
5346 static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl,
5347                              bool check_superclass) {
5348   while (class_interface_decl) {
5349     if (class_interface_decl->ivar_size() > 0)
5350       return true;
5351 
5352     if (check_superclass)
5353       class_interface_decl = class_interface_decl->getSuperClass();
5354     else
5355       break;
5356   }
5357   return false;
5358 }
5359 
5360 static std::optional<SymbolFile::ArrayInfo>
5361 GetDynamicArrayInfo(TypeSystemClang &ast, SymbolFile *sym_file,
5362                     clang::QualType qual_type,
5363                     const ExecutionContext *exe_ctx) {
5364   if (qual_type->isIncompleteArrayType())
5365     if (auto *metadata = ast.GetMetadata(qual_type.getTypePtr()))
5366       return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(),
5367                                                  exe_ctx);
5368   return std::nullopt;
5369 }
5370 
5371 uint32_t TypeSystemClang::GetNumChildren(lldb::opaque_compiler_type_t type,
5372                                          bool omit_empty_base_classes,
5373                                          const ExecutionContext *exe_ctx) {
5374   if (!type)
5375     return 0;
5376 
5377   uint32_t num_children = 0;
5378   clang::QualType qual_type(RemoveWrappingTypes(GetQualType(type)));
5379   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5380   switch (type_class) {
5381   case clang::Type::Builtin:
5382     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5383     case clang::BuiltinType::ObjCId:    // child is Class
5384     case clang::BuiltinType::ObjCClass: // child is Class
5385       num_children = 1;
5386       break;
5387 
5388     default:
5389       break;
5390     }
5391     break;
5392 
5393   case clang::Type::Complex:
5394     return 0;
5395   case clang::Type::Record:
5396     if (GetCompleteQualType(&getASTContext(), qual_type)) {
5397       const clang::RecordType *record_type =
5398           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5399       const clang::RecordDecl *record_decl = record_type->getDecl();
5400       assert(record_decl);
5401       const clang::CXXRecordDecl *cxx_record_decl =
5402           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
5403       if (cxx_record_decl) {
5404         if (omit_empty_base_classes) {
5405           // Check each base classes to see if it or any of its base classes
5406           // contain any fields. This can help limit the noise in variable
5407           // views by not having to show base classes that contain no members.
5408           clang::CXXRecordDecl::base_class_const_iterator base_class,
5409               base_class_end;
5410           for (base_class = cxx_record_decl->bases_begin(),
5411               base_class_end = cxx_record_decl->bases_end();
5412                base_class != base_class_end; ++base_class) {
5413             const clang::CXXRecordDecl *base_class_decl =
5414                 llvm::cast<clang::CXXRecordDecl>(
5415                     base_class->getType()
5416                         ->getAs<clang::RecordType>()
5417                         ->getDecl());
5418 
5419             // Skip empty base classes
5420             if (!TypeSystemClang::RecordHasFields(base_class_decl))
5421               continue;
5422 
5423             num_children++;
5424           }
5425         } else {
5426           // Include all base classes
5427           num_children += cxx_record_decl->getNumBases();
5428         }
5429       }
5430       clang::RecordDecl::field_iterator field, field_end;
5431       for (field = record_decl->field_begin(),
5432           field_end = record_decl->field_end();
5433            field != field_end; ++field)
5434         ++num_children;
5435     }
5436     break;
5437 
5438   case clang::Type::ObjCObject:
5439   case clang::Type::ObjCInterface:
5440     if (GetCompleteQualType(&getASTContext(), qual_type)) {
5441       const clang::ObjCObjectType *objc_class_type =
5442           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5443       assert(objc_class_type);
5444       if (objc_class_type) {
5445         clang::ObjCInterfaceDecl *class_interface_decl =
5446             objc_class_type->getInterface();
5447 
5448         if (class_interface_decl) {
5449 
5450           clang::ObjCInterfaceDecl *superclass_interface_decl =
5451               class_interface_decl->getSuperClass();
5452           if (superclass_interface_decl) {
5453             if (omit_empty_base_classes) {
5454               if (ObjCDeclHasIVars(superclass_interface_decl, true))
5455                 ++num_children;
5456             } else
5457               ++num_children;
5458           }
5459 
5460           num_children += class_interface_decl->ivar_size();
5461         }
5462       }
5463     }
5464     break;
5465 
5466   case clang::Type::LValueReference:
5467   case clang::Type::RValueReference:
5468   case clang::Type::ObjCObjectPointer: {
5469     CompilerType pointee_clang_type(GetPointeeType(type));
5470 
5471     uint32_t num_pointee_children = 0;
5472     if (pointee_clang_type.IsAggregateType())
5473       num_pointee_children =
5474           pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5475     // If this type points to a simple type, then it has 1 child
5476     if (num_pointee_children == 0)
5477       num_children = 1;
5478     else
5479       num_children = num_pointee_children;
5480   } break;
5481 
5482   case clang::Type::Vector:
5483   case clang::Type::ExtVector:
5484     num_children =
5485         llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements();
5486     break;
5487 
5488   case clang::Type::ConstantArray:
5489     num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr())
5490                        ->getSize()
5491                        .getLimitedValue();
5492     break;
5493   case clang::Type::IncompleteArray:
5494     if (auto array_info =
5495             GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx))
5496       // Only 1-dimensional arrays are supported.
5497       num_children = array_info->element_orders.size()
5498                          ? array_info->element_orders.back()
5499                          : 0;
5500     break;
5501 
5502   case clang::Type::Pointer: {
5503     const clang::PointerType *pointer_type =
5504         llvm::cast<clang::PointerType>(qual_type.getTypePtr());
5505     clang::QualType pointee_type(pointer_type->getPointeeType());
5506     CompilerType pointee_clang_type(GetType(pointee_type));
5507     uint32_t num_pointee_children = 0;
5508     if (pointee_clang_type.IsAggregateType())
5509       num_pointee_children =
5510           pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5511     if (num_pointee_children == 0) {
5512       // We have a pointer to a pointee type that claims it has no children. We
5513       // will want to look at
5514       num_children = GetNumPointeeChildren(pointee_type);
5515     } else
5516       num_children = num_pointee_children;
5517   } break;
5518 
5519   default:
5520     break;
5521   }
5522   return num_children;
5523 }
5524 
5525 CompilerType TypeSystemClang::GetBuiltinTypeByName(ConstString name) {
5526   return GetBasicType(GetBasicTypeEnumeration(name));
5527 }
5528 
5529 lldb::BasicType
5530 TypeSystemClang::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) {
5531   if (type) {
5532     clang::QualType qual_type(GetQualType(type));
5533     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5534     if (type_class == clang::Type::Builtin) {
5535       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5536       case clang::BuiltinType::Void:
5537         return eBasicTypeVoid;
5538       case clang::BuiltinType::Bool:
5539         return eBasicTypeBool;
5540       case clang::BuiltinType::Char_S:
5541         return eBasicTypeSignedChar;
5542       case clang::BuiltinType::Char_U:
5543         return eBasicTypeUnsignedChar;
5544       case clang::BuiltinType::Char8:
5545         return eBasicTypeChar8;
5546       case clang::BuiltinType::Char16:
5547         return eBasicTypeChar16;
5548       case clang::BuiltinType::Char32:
5549         return eBasicTypeChar32;
5550       case clang::BuiltinType::UChar:
5551         return eBasicTypeUnsignedChar;
5552       case clang::BuiltinType::SChar:
5553         return eBasicTypeSignedChar;
5554       case clang::BuiltinType::WChar_S:
5555         return eBasicTypeSignedWChar;
5556       case clang::BuiltinType::WChar_U:
5557         return eBasicTypeUnsignedWChar;
5558       case clang::BuiltinType::Short:
5559         return eBasicTypeShort;
5560       case clang::BuiltinType::UShort:
5561         return eBasicTypeUnsignedShort;
5562       case clang::BuiltinType::Int:
5563         return eBasicTypeInt;
5564       case clang::BuiltinType::UInt:
5565         return eBasicTypeUnsignedInt;
5566       case clang::BuiltinType::Long:
5567         return eBasicTypeLong;
5568       case clang::BuiltinType::ULong:
5569         return eBasicTypeUnsignedLong;
5570       case clang::BuiltinType::LongLong:
5571         return eBasicTypeLongLong;
5572       case clang::BuiltinType::ULongLong:
5573         return eBasicTypeUnsignedLongLong;
5574       case clang::BuiltinType::Int128:
5575         return eBasicTypeInt128;
5576       case clang::BuiltinType::UInt128:
5577         return eBasicTypeUnsignedInt128;
5578 
5579       case clang::BuiltinType::Half:
5580         return eBasicTypeHalf;
5581       case clang::BuiltinType::Float:
5582         return eBasicTypeFloat;
5583       case clang::BuiltinType::Double:
5584         return eBasicTypeDouble;
5585       case clang::BuiltinType::LongDouble:
5586         return eBasicTypeLongDouble;
5587 
5588       case clang::BuiltinType::NullPtr:
5589         return eBasicTypeNullPtr;
5590       case clang::BuiltinType::ObjCId:
5591         return eBasicTypeObjCID;
5592       case clang::BuiltinType::ObjCClass:
5593         return eBasicTypeObjCClass;
5594       case clang::BuiltinType::ObjCSel:
5595         return eBasicTypeObjCSel;
5596       default:
5597         return eBasicTypeOther;
5598       }
5599     }
5600   }
5601   return eBasicTypeInvalid;
5602 }
5603 
5604 void TypeSystemClang::ForEachEnumerator(
5605     lldb::opaque_compiler_type_t type,
5606     std::function<bool(const CompilerType &integer_type,
5607                        ConstString name,
5608                        const llvm::APSInt &value)> const &callback) {
5609   const clang::EnumType *enum_type =
5610       llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type));
5611   if (enum_type) {
5612     const clang::EnumDecl *enum_decl = enum_type->getDecl();
5613     if (enum_decl) {
5614       CompilerType integer_type = GetType(enum_decl->getIntegerType());
5615 
5616       clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
5617       for (enum_pos = enum_decl->enumerator_begin(),
5618           enum_end_pos = enum_decl->enumerator_end();
5619            enum_pos != enum_end_pos; ++enum_pos) {
5620         ConstString name(enum_pos->getNameAsString().c_str());
5621         if (!callback(integer_type, name, enum_pos->getInitVal()))
5622           break;
5623       }
5624     }
5625   }
5626 }
5627 
5628 #pragma mark Aggregate Types
5629 
5630 uint32_t TypeSystemClang::GetNumFields(lldb::opaque_compiler_type_t type) {
5631   if (!type)
5632     return 0;
5633 
5634   uint32_t count = 0;
5635   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5636   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5637   switch (type_class) {
5638   case clang::Type::Record:
5639     if (GetCompleteType(type)) {
5640       const clang::RecordType *record_type =
5641           llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
5642       if (record_type) {
5643         clang::RecordDecl *record_decl = record_type->getDecl();
5644         if (record_decl) {
5645           uint32_t field_idx = 0;
5646           clang::RecordDecl::field_iterator field, field_end;
5647           for (field = record_decl->field_begin(),
5648               field_end = record_decl->field_end();
5649                field != field_end; ++field)
5650             ++field_idx;
5651           count = field_idx;
5652         }
5653       }
5654     }
5655     break;
5656 
5657   case clang::Type::ObjCObjectPointer: {
5658     const clang::ObjCObjectPointerType *objc_class_type =
5659         qual_type->castAs<clang::ObjCObjectPointerType>();
5660     const clang::ObjCInterfaceType *objc_interface_type =
5661         objc_class_type->getInterfaceType();
5662     if (objc_interface_type &&
5663         GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5664             const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5665       clang::ObjCInterfaceDecl *class_interface_decl =
5666           objc_interface_type->getDecl();
5667       if (class_interface_decl) {
5668         count = class_interface_decl->ivar_size();
5669       }
5670     }
5671     break;
5672   }
5673 
5674   case clang::Type::ObjCObject:
5675   case clang::Type::ObjCInterface:
5676     if (GetCompleteType(type)) {
5677       const clang::ObjCObjectType *objc_class_type =
5678           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5679       if (objc_class_type) {
5680         clang::ObjCInterfaceDecl *class_interface_decl =
5681             objc_class_type->getInterface();
5682 
5683         if (class_interface_decl)
5684           count = class_interface_decl->ivar_size();
5685       }
5686     }
5687     break;
5688 
5689   default:
5690     break;
5691   }
5692   return count;
5693 }
5694 
5695 static lldb::opaque_compiler_type_t
5696 GetObjCFieldAtIndex(clang::ASTContext *ast,
5697                     clang::ObjCInterfaceDecl *class_interface_decl, size_t idx,
5698                     std::string &name, uint64_t *bit_offset_ptr,
5699                     uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) {
5700   if (class_interface_decl) {
5701     if (idx < (class_interface_decl->ivar_size())) {
5702       clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
5703           ivar_end = class_interface_decl->ivar_end();
5704       uint32_t ivar_idx = 0;
5705 
5706       for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end;
5707            ++ivar_pos, ++ivar_idx) {
5708         if (ivar_idx == idx) {
5709           const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
5710 
5711           clang::QualType ivar_qual_type(ivar_decl->getType());
5712 
5713           name.assign(ivar_decl->getNameAsString());
5714 
5715           if (bit_offset_ptr) {
5716             const clang::ASTRecordLayout &interface_layout =
5717                 ast->getASTObjCInterfaceLayout(class_interface_decl);
5718             *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx);
5719           }
5720 
5721           const bool is_bitfield = ivar_pos->isBitField();
5722 
5723           if (bitfield_bit_size_ptr) {
5724             *bitfield_bit_size_ptr = 0;
5725 
5726             if (is_bitfield && ast) {
5727               clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
5728               clang::Expr::EvalResult result;
5729               if (bitfield_bit_size_expr &&
5730                   bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) {
5731                 llvm::APSInt bitfield_apsint = result.Val.getInt();
5732                 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5733               }
5734             }
5735           }
5736           if (is_bitfield_ptr)
5737             *is_bitfield_ptr = is_bitfield;
5738 
5739           return ivar_qual_type.getAsOpaquePtr();
5740         }
5741       }
5742     }
5743   }
5744   return nullptr;
5745 }
5746 
5747 CompilerType TypeSystemClang::GetFieldAtIndex(lldb::opaque_compiler_type_t type,
5748                                               size_t idx, std::string &name,
5749                                               uint64_t *bit_offset_ptr,
5750                                               uint32_t *bitfield_bit_size_ptr,
5751                                               bool *is_bitfield_ptr) {
5752   if (!type)
5753     return CompilerType();
5754 
5755   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5756   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5757   switch (type_class) {
5758   case clang::Type::Record:
5759     if (GetCompleteType(type)) {
5760       const clang::RecordType *record_type =
5761           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5762       const clang::RecordDecl *record_decl = record_type->getDecl();
5763       uint32_t field_idx = 0;
5764       clang::RecordDecl::field_iterator field, field_end;
5765       for (field = record_decl->field_begin(),
5766           field_end = record_decl->field_end();
5767            field != field_end; ++field, ++field_idx) {
5768         if (idx == field_idx) {
5769           // Print the member type if requested
5770           // Print the member name and equal sign
5771           name.assign(field->getNameAsString());
5772 
5773           // Figure out the type byte size (field_type_info.first) and
5774           // alignment (field_type_info.second) from the AST context.
5775           if (bit_offset_ptr) {
5776             const clang::ASTRecordLayout &record_layout =
5777                 getASTContext().getASTRecordLayout(record_decl);
5778             *bit_offset_ptr = record_layout.getFieldOffset(field_idx);
5779           }
5780 
5781           const bool is_bitfield = field->isBitField();
5782 
5783           if (bitfield_bit_size_ptr) {
5784             *bitfield_bit_size_ptr = 0;
5785 
5786             if (is_bitfield) {
5787               clang::Expr *bitfield_bit_size_expr = field->getBitWidth();
5788               clang::Expr::EvalResult result;
5789               if (bitfield_bit_size_expr &&
5790                   bitfield_bit_size_expr->EvaluateAsInt(result,
5791                                                         getASTContext())) {
5792                 llvm::APSInt bitfield_apsint = result.Val.getInt();
5793                 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5794               }
5795             }
5796           }
5797           if (is_bitfield_ptr)
5798             *is_bitfield_ptr = is_bitfield;
5799 
5800           return GetType(field->getType());
5801         }
5802       }
5803     }
5804     break;
5805 
5806   case clang::Type::ObjCObjectPointer: {
5807     const clang::ObjCObjectPointerType *objc_class_type =
5808         qual_type->castAs<clang::ObjCObjectPointerType>();
5809     const clang::ObjCInterfaceType *objc_interface_type =
5810         objc_class_type->getInterfaceType();
5811     if (objc_interface_type &&
5812         GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5813             const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5814       clang::ObjCInterfaceDecl *class_interface_decl =
5815           objc_interface_type->getDecl();
5816       if (class_interface_decl) {
5817         return CompilerType(
5818             weak_from_this(),
5819             GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx,
5820                                 name, bit_offset_ptr, bitfield_bit_size_ptr,
5821                                 is_bitfield_ptr));
5822       }
5823     }
5824     break;
5825   }
5826 
5827   case clang::Type::ObjCObject:
5828   case clang::Type::ObjCInterface:
5829     if (GetCompleteType(type)) {
5830       const clang::ObjCObjectType *objc_class_type =
5831           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5832       assert(objc_class_type);
5833       if (objc_class_type) {
5834         clang::ObjCInterfaceDecl *class_interface_decl =
5835             objc_class_type->getInterface();
5836         return CompilerType(
5837             weak_from_this(),
5838             GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx,
5839                                 name, bit_offset_ptr, bitfield_bit_size_ptr,
5840                                 is_bitfield_ptr));
5841       }
5842     }
5843     break;
5844 
5845   default:
5846     break;
5847   }
5848   return CompilerType();
5849 }
5850 
5851 uint32_t
5852 TypeSystemClang::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) {
5853   uint32_t count = 0;
5854   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5855   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5856   switch (type_class) {
5857   case clang::Type::Record:
5858     if (GetCompleteType(type)) {
5859       const clang::CXXRecordDecl *cxx_record_decl =
5860           qual_type->getAsCXXRecordDecl();
5861       if (cxx_record_decl)
5862         count = cxx_record_decl->getNumBases();
5863     }
5864     break;
5865 
5866   case clang::Type::ObjCObjectPointer:
5867     count = GetPointeeType(type).GetNumDirectBaseClasses();
5868     break;
5869 
5870   case clang::Type::ObjCObject:
5871     if (GetCompleteType(type)) {
5872       const clang::ObjCObjectType *objc_class_type =
5873           qual_type->getAsObjCQualifiedInterfaceType();
5874       if (objc_class_type) {
5875         clang::ObjCInterfaceDecl *class_interface_decl =
5876             objc_class_type->getInterface();
5877 
5878         if (class_interface_decl && class_interface_decl->getSuperClass())
5879           count = 1;
5880       }
5881     }
5882     break;
5883   case clang::Type::ObjCInterface:
5884     if (GetCompleteType(type)) {
5885       const clang::ObjCInterfaceType *objc_interface_type =
5886           qual_type->getAs<clang::ObjCInterfaceType>();
5887       if (objc_interface_type) {
5888         clang::ObjCInterfaceDecl *class_interface_decl =
5889             objc_interface_type->getInterface();
5890 
5891         if (class_interface_decl && class_interface_decl->getSuperClass())
5892           count = 1;
5893       }
5894     }
5895     break;
5896 
5897   default:
5898     break;
5899   }
5900   return count;
5901 }
5902 
5903 uint32_t
5904 TypeSystemClang::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) {
5905   uint32_t count = 0;
5906   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5907   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5908   switch (type_class) {
5909   case clang::Type::Record:
5910     if (GetCompleteType(type)) {
5911       const clang::CXXRecordDecl *cxx_record_decl =
5912           qual_type->getAsCXXRecordDecl();
5913       if (cxx_record_decl)
5914         count = cxx_record_decl->getNumVBases();
5915     }
5916     break;
5917 
5918   default:
5919     break;
5920   }
5921   return count;
5922 }
5923 
5924 CompilerType TypeSystemClang::GetDirectBaseClassAtIndex(
5925     lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5926   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5927   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5928   switch (type_class) {
5929   case clang::Type::Record:
5930     if (GetCompleteType(type)) {
5931       const clang::CXXRecordDecl *cxx_record_decl =
5932           qual_type->getAsCXXRecordDecl();
5933       if (cxx_record_decl) {
5934         uint32_t curr_idx = 0;
5935         clang::CXXRecordDecl::base_class_const_iterator base_class,
5936             base_class_end;
5937         for (base_class = cxx_record_decl->bases_begin(),
5938             base_class_end = cxx_record_decl->bases_end();
5939              base_class != base_class_end; ++base_class, ++curr_idx) {
5940           if (curr_idx == idx) {
5941             if (bit_offset_ptr) {
5942               const clang::ASTRecordLayout &record_layout =
5943                   getASTContext().getASTRecordLayout(cxx_record_decl);
5944               const clang::CXXRecordDecl *base_class_decl =
5945                   llvm::cast<clang::CXXRecordDecl>(
5946                       base_class->getType()
5947                           ->castAs<clang::RecordType>()
5948                           ->getDecl());
5949               if (base_class->isVirtual())
5950                 *bit_offset_ptr =
5951                     record_layout.getVBaseClassOffset(base_class_decl)
5952                         .getQuantity() *
5953                     8;
5954               else
5955                 *bit_offset_ptr =
5956                     record_layout.getBaseClassOffset(base_class_decl)
5957                         .getQuantity() *
5958                     8;
5959             }
5960             return GetType(base_class->getType());
5961           }
5962         }
5963       }
5964     }
5965     break;
5966 
5967   case clang::Type::ObjCObjectPointer:
5968     return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr);
5969 
5970   case clang::Type::ObjCObject:
5971     if (idx == 0 && GetCompleteType(type)) {
5972       const clang::ObjCObjectType *objc_class_type =
5973           qual_type->getAsObjCQualifiedInterfaceType();
5974       if (objc_class_type) {
5975         clang::ObjCInterfaceDecl *class_interface_decl =
5976             objc_class_type->getInterface();
5977 
5978         if (class_interface_decl) {
5979           clang::ObjCInterfaceDecl *superclass_interface_decl =
5980               class_interface_decl->getSuperClass();
5981           if (superclass_interface_decl) {
5982             if (bit_offset_ptr)
5983               *bit_offset_ptr = 0;
5984             return GetType(getASTContext().getObjCInterfaceType(
5985                 superclass_interface_decl));
5986           }
5987         }
5988       }
5989     }
5990     break;
5991   case clang::Type::ObjCInterface:
5992     if (idx == 0 && GetCompleteType(type)) {
5993       const clang::ObjCObjectType *objc_interface_type =
5994           qual_type->getAs<clang::ObjCInterfaceType>();
5995       if (objc_interface_type) {
5996         clang::ObjCInterfaceDecl *class_interface_decl =
5997             objc_interface_type->getInterface();
5998 
5999         if (class_interface_decl) {
6000           clang::ObjCInterfaceDecl *superclass_interface_decl =
6001               class_interface_decl->getSuperClass();
6002           if (superclass_interface_decl) {
6003             if (bit_offset_ptr)
6004               *bit_offset_ptr = 0;
6005             return GetType(getASTContext().getObjCInterfaceType(
6006                 superclass_interface_decl));
6007           }
6008         }
6009       }
6010     }
6011     break;
6012 
6013   default:
6014     break;
6015   }
6016   return CompilerType();
6017 }
6018 
6019 CompilerType TypeSystemClang::GetVirtualBaseClassAtIndex(
6020     lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
6021   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6022   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6023   switch (type_class) {
6024   case clang::Type::Record:
6025     if (GetCompleteType(type)) {
6026       const clang::CXXRecordDecl *cxx_record_decl =
6027           qual_type->getAsCXXRecordDecl();
6028       if (cxx_record_decl) {
6029         uint32_t curr_idx = 0;
6030         clang::CXXRecordDecl::base_class_const_iterator base_class,
6031             base_class_end;
6032         for (base_class = cxx_record_decl->vbases_begin(),
6033             base_class_end = cxx_record_decl->vbases_end();
6034              base_class != base_class_end; ++base_class, ++curr_idx) {
6035           if (curr_idx == idx) {
6036             if (bit_offset_ptr) {
6037               const clang::ASTRecordLayout &record_layout =
6038                   getASTContext().getASTRecordLayout(cxx_record_decl);
6039               const clang::CXXRecordDecl *base_class_decl =
6040                   llvm::cast<clang::CXXRecordDecl>(
6041                       base_class->getType()
6042                           ->castAs<clang::RecordType>()
6043                           ->getDecl());
6044               *bit_offset_ptr =
6045                   record_layout.getVBaseClassOffset(base_class_decl)
6046                       .getQuantity() *
6047                   8;
6048             }
6049             return GetType(base_class->getType());
6050           }
6051         }
6052       }
6053     }
6054     break;
6055 
6056   default:
6057     break;
6058   }
6059   return CompilerType();
6060 }
6061 
6062 // If a pointer to a pointee type (the clang_type arg) says that it has no
6063 // children, then we either need to trust it, or override it and return a
6064 // different result. For example, an "int *" has one child that is an integer,
6065 // but a function pointer doesn't have any children. Likewise if a Record type
6066 // claims it has no children, then there really is nothing to show.
6067 uint32_t TypeSystemClang::GetNumPointeeChildren(clang::QualType type) {
6068   if (type.isNull())
6069     return 0;
6070 
6071   clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
6072   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6073   switch (type_class) {
6074   case clang::Type::Builtin:
6075     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
6076     case clang::BuiltinType::UnknownAny:
6077     case clang::BuiltinType::Void:
6078     case clang::BuiltinType::NullPtr:
6079     case clang::BuiltinType::OCLEvent:
6080     case clang::BuiltinType::OCLImage1dRO:
6081     case clang::BuiltinType::OCLImage1dWO:
6082     case clang::BuiltinType::OCLImage1dRW:
6083     case clang::BuiltinType::OCLImage1dArrayRO:
6084     case clang::BuiltinType::OCLImage1dArrayWO:
6085     case clang::BuiltinType::OCLImage1dArrayRW:
6086     case clang::BuiltinType::OCLImage1dBufferRO:
6087     case clang::BuiltinType::OCLImage1dBufferWO:
6088     case clang::BuiltinType::OCLImage1dBufferRW:
6089     case clang::BuiltinType::OCLImage2dRO:
6090     case clang::BuiltinType::OCLImage2dWO:
6091     case clang::BuiltinType::OCLImage2dRW:
6092     case clang::BuiltinType::OCLImage2dArrayRO:
6093     case clang::BuiltinType::OCLImage2dArrayWO:
6094     case clang::BuiltinType::OCLImage2dArrayRW:
6095     case clang::BuiltinType::OCLImage3dRO:
6096     case clang::BuiltinType::OCLImage3dWO:
6097     case clang::BuiltinType::OCLImage3dRW:
6098     case clang::BuiltinType::OCLSampler:
6099       return 0;
6100     case clang::BuiltinType::Bool:
6101     case clang::BuiltinType::Char_U:
6102     case clang::BuiltinType::UChar:
6103     case clang::BuiltinType::WChar_U:
6104     case clang::BuiltinType::Char16:
6105     case clang::BuiltinType::Char32:
6106     case clang::BuiltinType::UShort:
6107     case clang::BuiltinType::UInt:
6108     case clang::BuiltinType::ULong:
6109     case clang::BuiltinType::ULongLong:
6110     case clang::BuiltinType::UInt128:
6111     case clang::BuiltinType::Char_S:
6112     case clang::BuiltinType::SChar:
6113     case clang::BuiltinType::WChar_S:
6114     case clang::BuiltinType::Short:
6115     case clang::BuiltinType::Int:
6116     case clang::BuiltinType::Long:
6117     case clang::BuiltinType::LongLong:
6118     case clang::BuiltinType::Int128:
6119     case clang::BuiltinType::Float:
6120     case clang::BuiltinType::Double:
6121     case clang::BuiltinType::LongDouble:
6122     case clang::BuiltinType::Dependent:
6123     case clang::BuiltinType::Overload:
6124     case clang::BuiltinType::ObjCId:
6125     case clang::BuiltinType::ObjCClass:
6126     case clang::BuiltinType::ObjCSel:
6127     case clang::BuiltinType::BoundMember:
6128     case clang::BuiltinType::Half:
6129     case clang::BuiltinType::ARCUnbridgedCast:
6130     case clang::BuiltinType::PseudoObject:
6131     case clang::BuiltinType::BuiltinFn:
6132     case clang::BuiltinType::OMPArraySection:
6133       return 1;
6134     default:
6135       return 0;
6136     }
6137     break;
6138 
6139   case clang::Type::Complex:
6140     return 1;
6141   case clang::Type::Pointer:
6142     return 1;
6143   case clang::Type::BlockPointer:
6144     return 0; // If block pointers don't have debug info, then no children for
6145               // them
6146   case clang::Type::LValueReference:
6147     return 1;
6148   case clang::Type::RValueReference:
6149     return 1;
6150   case clang::Type::MemberPointer:
6151     return 0;
6152   case clang::Type::ConstantArray:
6153     return 0;
6154   case clang::Type::IncompleteArray:
6155     return 0;
6156   case clang::Type::VariableArray:
6157     return 0;
6158   case clang::Type::DependentSizedArray:
6159     return 0;
6160   case clang::Type::DependentSizedExtVector:
6161     return 0;
6162   case clang::Type::Vector:
6163     return 0;
6164   case clang::Type::ExtVector:
6165     return 0;
6166   case clang::Type::FunctionProto:
6167     return 0; // When we function pointers, they have no children...
6168   case clang::Type::FunctionNoProto:
6169     return 0; // When we function pointers, they have no children...
6170   case clang::Type::UnresolvedUsing:
6171     return 0;
6172   case clang::Type::Record:
6173     return 0;
6174   case clang::Type::Enum:
6175     return 1;
6176   case clang::Type::TemplateTypeParm:
6177     return 1;
6178   case clang::Type::SubstTemplateTypeParm:
6179     return 1;
6180   case clang::Type::TemplateSpecialization:
6181     return 1;
6182   case clang::Type::InjectedClassName:
6183     return 0;
6184   case clang::Type::DependentName:
6185     return 1;
6186   case clang::Type::DependentTemplateSpecialization:
6187     return 1;
6188   case clang::Type::ObjCObject:
6189     return 0;
6190   case clang::Type::ObjCInterface:
6191     return 0;
6192   case clang::Type::ObjCObjectPointer:
6193     return 1;
6194   default:
6195     break;
6196   }
6197   return 0;
6198 }
6199 
6200 CompilerType TypeSystemClang::GetChildCompilerTypeAtIndex(
6201     lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
6202     bool transparent_pointers, bool omit_empty_base_classes,
6203     bool ignore_array_bounds, std::string &child_name,
6204     uint32_t &child_byte_size, int32_t &child_byte_offset,
6205     uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
6206     bool &child_is_base_class, bool &child_is_deref_of_parent,
6207     ValueObject *valobj, uint64_t &language_flags) {
6208   if (!type)
6209     return CompilerType();
6210 
6211   auto get_exe_scope = [&exe_ctx]() {
6212     return exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
6213   };
6214 
6215   clang::QualType parent_qual_type(
6216       RemoveWrappingTypes(GetCanonicalQualType(type)));
6217   const clang::Type::TypeClass parent_type_class =
6218       parent_qual_type->getTypeClass();
6219   child_bitfield_bit_size = 0;
6220   child_bitfield_bit_offset = 0;
6221   child_is_base_class = false;
6222   language_flags = 0;
6223 
6224   const bool idx_is_valid =
6225       idx < GetNumChildren(type, omit_empty_base_classes, exe_ctx);
6226   int32_t bit_offset;
6227   switch (parent_type_class) {
6228   case clang::Type::Builtin:
6229     if (idx_is_valid) {
6230       switch (llvm::cast<clang::BuiltinType>(parent_qual_type)->getKind()) {
6231       case clang::BuiltinType::ObjCId:
6232       case clang::BuiltinType::ObjCClass:
6233         child_name = "isa";
6234         child_byte_size =
6235             getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy) /
6236             CHAR_BIT;
6237         return GetType(getASTContext().ObjCBuiltinClassTy);
6238 
6239       default:
6240         break;
6241       }
6242     }
6243     break;
6244 
6245   case clang::Type::Record:
6246     if (idx_is_valid && GetCompleteType(type)) {
6247       const clang::RecordType *record_type =
6248           llvm::cast<clang::RecordType>(parent_qual_type.getTypePtr());
6249       const clang::RecordDecl *record_decl = record_type->getDecl();
6250       assert(record_decl);
6251       const clang::ASTRecordLayout &record_layout =
6252           getASTContext().getASTRecordLayout(record_decl);
6253       uint32_t child_idx = 0;
6254 
6255       const clang::CXXRecordDecl *cxx_record_decl =
6256           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6257       if (cxx_record_decl) {
6258         // We might have base classes to print out first
6259         clang::CXXRecordDecl::base_class_const_iterator base_class,
6260             base_class_end;
6261         for (base_class = cxx_record_decl->bases_begin(),
6262             base_class_end = cxx_record_decl->bases_end();
6263              base_class != base_class_end; ++base_class) {
6264           const clang::CXXRecordDecl *base_class_decl = nullptr;
6265 
6266           // Skip empty base classes
6267           if (omit_empty_base_classes) {
6268             base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6269                 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6270             if (!TypeSystemClang::RecordHasFields(base_class_decl))
6271               continue;
6272           }
6273 
6274           if (idx == child_idx) {
6275             if (base_class_decl == nullptr)
6276               base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6277                   base_class->getType()->getAs<clang::RecordType>()->getDecl());
6278 
6279             if (base_class->isVirtual()) {
6280               bool handled = false;
6281               if (valobj) {
6282                 clang::VTableContextBase *vtable_ctx =
6283                     getASTContext().getVTableContext();
6284                 if (vtable_ctx)
6285                   handled = GetVBaseBitOffset(*vtable_ctx, *valobj,
6286                                               record_layout, cxx_record_decl,
6287                                               base_class_decl, bit_offset);
6288               }
6289               if (!handled)
6290                 bit_offset = record_layout.getVBaseClassOffset(base_class_decl)
6291                                  .getQuantity() *
6292                              8;
6293             } else
6294               bit_offset = record_layout.getBaseClassOffset(base_class_decl)
6295                                .getQuantity() *
6296                            8;
6297 
6298             // Base classes should be a multiple of 8 bits in size
6299             child_byte_offset = bit_offset / 8;
6300             CompilerType base_class_clang_type = GetType(base_class->getType());
6301             child_name = base_class_clang_type.GetTypeName().AsCString("");
6302             std::optional<uint64_t> size =
6303                 base_class_clang_type.GetBitSize(get_exe_scope());
6304             if (!size)
6305               return {};
6306             uint64_t base_class_clang_type_bit_size = *size;
6307 
6308             // Base classes bit sizes should be a multiple of 8 bits in size
6309             assert(base_class_clang_type_bit_size % 8 == 0);
6310             child_byte_size = base_class_clang_type_bit_size / 8;
6311             child_is_base_class = true;
6312             return base_class_clang_type;
6313           }
6314           // We don't increment the child index in the for loop since we might
6315           // be skipping empty base classes
6316           ++child_idx;
6317         }
6318       }
6319       // Make sure index is in range...
6320       uint32_t field_idx = 0;
6321       clang::RecordDecl::field_iterator field, field_end;
6322       for (field = record_decl->field_begin(),
6323           field_end = record_decl->field_end();
6324            field != field_end; ++field, ++field_idx, ++child_idx) {
6325         if (idx == child_idx) {
6326           // Print the member type if requested
6327           // Print the member name and equal sign
6328           child_name.assign(field->getNameAsString());
6329 
6330           // Figure out the type byte size (field_type_info.first) and
6331           // alignment (field_type_info.second) from the AST context.
6332           CompilerType field_clang_type = GetType(field->getType());
6333           assert(field_idx < record_layout.getFieldCount());
6334           std::optional<uint64_t> size =
6335               field_clang_type.GetByteSize(get_exe_scope());
6336           if (!size)
6337             return {};
6338           child_byte_size = *size;
6339           const uint32_t child_bit_size = child_byte_size * 8;
6340 
6341           // Figure out the field offset within the current struct/union/class
6342           // type
6343           bit_offset = record_layout.getFieldOffset(field_idx);
6344           if (FieldIsBitfield(*field, child_bitfield_bit_size)) {
6345             child_bitfield_bit_offset = bit_offset % child_bit_size;
6346             const uint32_t child_bit_offset =
6347                 bit_offset - child_bitfield_bit_offset;
6348             child_byte_offset = child_bit_offset / 8;
6349           } else {
6350             child_byte_offset = bit_offset / 8;
6351           }
6352 
6353           return field_clang_type;
6354         }
6355       }
6356     }
6357     break;
6358 
6359   case clang::Type::ObjCObject:
6360   case clang::Type::ObjCInterface:
6361     if (idx_is_valid && GetCompleteType(type)) {
6362       const clang::ObjCObjectType *objc_class_type =
6363           llvm::dyn_cast<clang::ObjCObjectType>(parent_qual_type.getTypePtr());
6364       assert(objc_class_type);
6365       if (objc_class_type) {
6366         uint32_t child_idx = 0;
6367         clang::ObjCInterfaceDecl *class_interface_decl =
6368             objc_class_type->getInterface();
6369 
6370         if (class_interface_decl) {
6371 
6372           const clang::ASTRecordLayout &interface_layout =
6373               getASTContext().getASTObjCInterfaceLayout(class_interface_decl);
6374           clang::ObjCInterfaceDecl *superclass_interface_decl =
6375               class_interface_decl->getSuperClass();
6376           if (superclass_interface_decl) {
6377             if (omit_empty_base_classes) {
6378               CompilerType base_class_clang_type =
6379                   GetType(getASTContext().getObjCInterfaceType(
6380                       superclass_interface_decl));
6381               if (base_class_clang_type.GetNumChildren(omit_empty_base_classes,
6382                                                        exe_ctx) > 0) {
6383                 if (idx == 0) {
6384                   clang::QualType ivar_qual_type(
6385                       getASTContext().getObjCInterfaceType(
6386                           superclass_interface_decl));
6387 
6388                   child_name.assign(
6389                       superclass_interface_decl->getNameAsString());
6390 
6391                   clang::TypeInfo ivar_type_info =
6392                       getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6393 
6394                   child_byte_size = ivar_type_info.Width / 8;
6395                   child_byte_offset = 0;
6396                   child_is_base_class = true;
6397 
6398                   return GetType(ivar_qual_type);
6399                 }
6400 
6401                 ++child_idx;
6402               }
6403             } else
6404               ++child_idx;
6405           }
6406 
6407           const uint32_t superclass_idx = child_idx;
6408 
6409           if (idx < (child_idx + class_interface_decl->ivar_size())) {
6410             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6411                 ivar_end = class_interface_decl->ivar_end();
6412 
6413             for (ivar_pos = class_interface_decl->ivar_begin();
6414                  ivar_pos != ivar_end; ++ivar_pos) {
6415               if (child_idx == idx) {
6416                 clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6417 
6418                 clang::QualType ivar_qual_type(ivar_decl->getType());
6419 
6420                 child_name.assign(ivar_decl->getNameAsString());
6421 
6422                 clang::TypeInfo ivar_type_info =
6423                     getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6424 
6425                 child_byte_size = ivar_type_info.Width / 8;
6426 
6427                 // Figure out the field offset within the current
6428                 // struct/union/class type For ObjC objects, we can't trust the
6429                 // bit offset we get from the Clang AST, since that doesn't
6430                 // account for the space taken up by unbacked properties, or
6431                 // from the changing size of base classes that are newer than
6432                 // this class. So if we have a process around that we can ask
6433                 // about this object, do so.
6434                 child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
6435                 Process *process = nullptr;
6436                 if (exe_ctx)
6437                   process = exe_ctx->GetProcessPtr();
6438                 if (process) {
6439                   ObjCLanguageRuntime *objc_runtime =
6440                       ObjCLanguageRuntime::Get(*process);
6441                   if (objc_runtime != nullptr) {
6442                     CompilerType parent_ast_type = GetType(parent_qual_type);
6443                     child_byte_offset = objc_runtime->GetByteOffsetForIvar(
6444                         parent_ast_type, ivar_decl->getNameAsString().c_str());
6445                   }
6446                 }
6447 
6448                 // Setting this to INT32_MAX to make sure we don't compute it
6449                 // twice...
6450                 bit_offset = INT32_MAX;
6451 
6452                 if (child_byte_offset ==
6453                     static_cast<int32_t>(LLDB_INVALID_IVAR_OFFSET)) {
6454                   bit_offset = interface_layout.getFieldOffset(child_idx -
6455                                                                superclass_idx);
6456                   child_byte_offset = bit_offset / 8;
6457                 }
6458 
6459                 // Note, the ObjC Ivar Byte offset is just that, it doesn't
6460                 // account for the bit offset of a bitfield within its
6461                 // containing object.  So regardless of where we get the byte
6462                 // offset from, we still need to get the bit offset for
6463                 // bitfields from the layout.
6464 
6465                 if (FieldIsBitfield(ivar_decl, child_bitfield_bit_size)) {
6466                   if (bit_offset == INT32_MAX)
6467                     bit_offset = interface_layout.getFieldOffset(
6468                         child_idx - superclass_idx);
6469 
6470                   child_bitfield_bit_offset = bit_offset % 8;
6471                 }
6472                 return GetType(ivar_qual_type);
6473               }
6474               ++child_idx;
6475             }
6476           }
6477         }
6478       }
6479     }
6480     break;
6481 
6482   case clang::Type::ObjCObjectPointer:
6483     if (idx_is_valid) {
6484       CompilerType pointee_clang_type(GetPointeeType(type));
6485 
6486       if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6487         child_is_deref_of_parent = false;
6488         bool tmp_child_is_deref_of_parent = false;
6489         return pointee_clang_type.GetChildCompilerTypeAtIndex(
6490             exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6491             ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6492             child_bitfield_bit_size, child_bitfield_bit_offset,
6493             child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6494             language_flags);
6495       } else {
6496         child_is_deref_of_parent = true;
6497         const char *parent_name =
6498             valobj ? valobj->GetName().GetCString() : nullptr;
6499         if (parent_name) {
6500           child_name.assign(1, '*');
6501           child_name += parent_name;
6502         }
6503 
6504         // We have a pointer to an simple type
6505         if (idx == 0 && pointee_clang_type.GetCompleteType()) {
6506           if (std::optional<uint64_t> size =
6507                   pointee_clang_type.GetByteSize(get_exe_scope())) {
6508             child_byte_size = *size;
6509             child_byte_offset = 0;
6510             return pointee_clang_type;
6511           }
6512         }
6513       }
6514     }
6515     break;
6516 
6517   case clang::Type::Vector:
6518   case clang::Type::ExtVector:
6519     if (idx_is_valid) {
6520       const clang::VectorType *array =
6521           llvm::cast<clang::VectorType>(parent_qual_type.getTypePtr());
6522       if (array) {
6523         CompilerType element_type = GetType(array->getElementType());
6524         if (element_type.GetCompleteType()) {
6525           char element_name[64];
6526           ::snprintf(element_name, sizeof(element_name), "[%" PRIu64 "]",
6527                      static_cast<uint64_t>(idx));
6528           child_name.assign(element_name);
6529           if (std::optional<uint64_t> size =
6530                   element_type.GetByteSize(get_exe_scope())) {
6531             child_byte_size = *size;
6532             child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6533             return element_type;
6534           }
6535         }
6536       }
6537     }
6538     break;
6539 
6540   case clang::Type::ConstantArray:
6541   case clang::Type::IncompleteArray:
6542     if (ignore_array_bounds || idx_is_valid) {
6543       const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe();
6544       if (array) {
6545         CompilerType element_type = GetType(array->getElementType());
6546         if (element_type.GetCompleteType()) {
6547           child_name = std::string(llvm::formatv("[{0}]", idx));
6548           if (std::optional<uint64_t> size =
6549                   element_type.GetByteSize(get_exe_scope())) {
6550             child_byte_size = *size;
6551             child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6552             return element_type;
6553           }
6554         }
6555       }
6556     }
6557     break;
6558 
6559   case clang::Type::Pointer: {
6560     CompilerType pointee_clang_type(GetPointeeType(type));
6561 
6562     // Don't dereference "void *" pointers
6563     if (pointee_clang_type.IsVoidType())
6564       return CompilerType();
6565 
6566     if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6567       child_is_deref_of_parent = false;
6568       bool tmp_child_is_deref_of_parent = false;
6569       return pointee_clang_type.GetChildCompilerTypeAtIndex(
6570           exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6571           ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6572           child_bitfield_bit_size, child_bitfield_bit_offset,
6573           child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6574           language_flags);
6575     } else {
6576       child_is_deref_of_parent = true;
6577 
6578       const char *parent_name =
6579           valobj ? valobj->GetName().GetCString() : nullptr;
6580       if (parent_name) {
6581         child_name.assign(1, '*');
6582         child_name += parent_name;
6583       }
6584 
6585       // We have a pointer to an simple type
6586       if (idx == 0) {
6587         if (std::optional<uint64_t> size =
6588                 pointee_clang_type.GetByteSize(get_exe_scope())) {
6589           child_byte_size = *size;
6590           child_byte_offset = 0;
6591           return pointee_clang_type;
6592         }
6593       }
6594     }
6595     break;
6596   }
6597 
6598   case clang::Type::LValueReference:
6599   case clang::Type::RValueReference:
6600     if (idx_is_valid) {
6601       const clang::ReferenceType *reference_type =
6602           llvm::cast<clang::ReferenceType>(
6603               RemoveWrappingTypes(GetQualType(type)).getTypePtr());
6604       CompilerType pointee_clang_type =
6605           GetType(reference_type->getPointeeType());
6606       if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6607         child_is_deref_of_parent = false;
6608         bool tmp_child_is_deref_of_parent = false;
6609         return pointee_clang_type.GetChildCompilerTypeAtIndex(
6610             exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6611             ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6612             child_bitfield_bit_size, child_bitfield_bit_offset,
6613             child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6614             language_flags);
6615       } else {
6616         const char *parent_name =
6617             valobj ? valobj->GetName().GetCString() : nullptr;
6618         if (parent_name) {
6619           child_name.assign(1, '&');
6620           child_name += parent_name;
6621         }
6622 
6623         // We have a pointer to an simple type
6624         if (idx == 0) {
6625           if (std::optional<uint64_t> size =
6626                   pointee_clang_type.GetByteSize(get_exe_scope())) {
6627             child_byte_size = *size;
6628             child_byte_offset = 0;
6629             return pointee_clang_type;
6630           }
6631         }
6632       }
6633     }
6634     break;
6635 
6636   default:
6637     break;
6638   }
6639   return CompilerType();
6640 }
6641 
6642 uint32_t TypeSystemClang::GetIndexForRecordBase(
6643     const clang::RecordDecl *record_decl,
6644     const clang::CXXBaseSpecifier *base_spec,
6645     bool omit_empty_base_classes) {
6646   uint32_t child_idx = 0;
6647 
6648   const clang::CXXRecordDecl *cxx_record_decl =
6649       llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6650 
6651   if (cxx_record_decl) {
6652     clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
6653     for (base_class = cxx_record_decl->bases_begin(),
6654         base_class_end = cxx_record_decl->bases_end();
6655          base_class != base_class_end; ++base_class) {
6656       if (omit_empty_base_classes) {
6657         if (BaseSpecifierIsEmpty(base_class))
6658           continue;
6659       }
6660 
6661       if (base_class == base_spec)
6662         return child_idx;
6663       ++child_idx;
6664     }
6665   }
6666 
6667   return UINT32_MAX;
6668 }
6669 
6670 uint32_t TypeSystemClang::GetIndexForRecordChild(
6671     const clang::RecordDecl *record_decl, clang::NamedDecl *canonical_decl,
6672     bool omit_empty_base_classes) {
6673   uint32_t child_idx = TypeSystemClang::GetNumBaseClasses(
6674       llvm::dyn_cast<clang::CXXRecordDecl>(record_decl),
6675       omit_empty_base_classes);
6676 
6677   clang::RecordDecl::field_iterator field, field_end;
6678   for (field = record_decl->field_begin(), field_end = record_decl->field_end();
6679        field != field_end; ++field, ++child_idx) {
6680     if (field->getCanonicalDecl() == canonical_decl)
6681       return child_idx;
6682   }
6683 
6684   return UINT32_MAX;
6685 }
6686 
6687 // Look for a child member (doesn't include base classes, but it does include
6688 // their members) in the type hierarchy. Returns an index path into
6689 // "clang_type" on how to reach the appropriate member.
6690 //
6691 //    class A
6692 //    {
6693 //    public:
6694 //        int m_a;
6695 //        int m_b;
6696 //    };
6697 //
6698 //    class B
6699 //    {
6700 //    };
6701 //
6702 //    class C :
6703 //        public B,
6704 //        public A
6705 //    {
6706 //    };
6707 //
6708 // If we have a clang type that describes "class C", and we wanted to looked
6709 // "m_b" in it:
6710 //
6711 // With omit_empty_base_classes == false we would get an integer array back
6712 // with: { 1,  1 } The first index 1 is the child index for "class A" within
6713 // class C The second index 1 is the child index for "m_b" within class A
6714 //
6715 // With omit_empty_base_classes == true we would get an integer array back
6716 // with: { 0,  1 } The first index 0 is the child index for "class A" within
6717 // class C (since class B doesn't have any members it doesn't count) The second
6718 // index 1 is the child index for "m_b" within class A
6719 
6720 size_t TypeSystemClang::GetIndexOfChildMemberWithName(
6721     lldb::opaque_compiler_type_t type, const char *name,
6722     bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) {
6723   if (type && name && name[0]) {
6724     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6725     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6726     switch (type_class) {
6727     case clang::Type::Record:
6728       if (GetCompleteType(type)) {
6729         const clang::RecordType *record_type =
6730             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6731         const clang::RecordDecl *record_decl = record_type->getDecl();
6732 
6733         assert(record_decl);
6734         uint32_t child_idx = 0;
6735 
6736         const clang::CXXRecordDecl *cxx_record_decl =
6737             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6738 
6739         // Try and find a field that matches NAME
6740         clang::RecordDecl::field_iterator field, field_end;
6741         llvm::StringRef name_sref(name);
6742         for (field = record_decl->field_begin(),
6743             field_end = record_decl->field_end();
6744              field != field_end; ++field, ++child_idx) {
6745           llvm::StringRef field_name = field->getName();
6746           if (field_name.empty()) {
6747             CompilerType field_type = GetType(field->getType());
6748             child_indexes.push_back(child_idx);
6749             if (field_type.GetIndexOfChildMemberWithName(
6750                     name, omit_empty_base_classes, child_indexes))
6751               return child_indexes.size();
6752             child_indexes.pop_back();
6753 
6754           } else if (field_name.equals(name_sref)) {
6755             // We have to add on the number of base classes to this index!
6756             child_indexes.push_back(
6757                 child_idx + TypeSystemClang::GetNumBaseClasses(
6758                                 cxx_record_decl, omit_empty_base_classes));
6759             return child_indexes.size();
6760           }
6761         }
6762 
6763         if (cxx_record_decl) {
6764           const clang::RecordDecl *parent_record_decl = cxx_record_decl;
6765 
6766           // Didn't find things easily, lets let clang do its thang...
6767           clang::IdentifierInfo &ident_ref =
6768               getASTContext().Idents.get(name_sref);
6769           clang::DeclarationName decl_name(&ident_ref);
6770 
6771           clang::CXXBasePaths paths;
6772           if (cxx_record_decl->lookupInBases(
6773                   [decl_name](const clang::CXXBaseSpecifier *specifier,
6774                               clang::CXXBasePath &path) {
6775                     CXXRecordDecl *record =
6776                       specifier->getType()->getAsCXXRecordDecl();
6777                     auto r = record->lookup(decl_name);
6778                     path.Decls = r.begin();
6779                     return !r.empty();
6780                   },
6781                   paths)) {
6782             clang::CXXBasePaths::const_paths_iterator path,
6783                 path_end = paths.end();
6784             for (path = paths.begin(); path != path_end; ++path) {
6785               const size_t num_path_elements = path->size();
6786               for (size_t e = 0; e < num_path_elements; ++e) {
6787                 clang::CXXBasePathElement elem = (*path)[e];
6788 
6789                 child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base,
6790                                                   omit_empty_base_classes);
6791                 if (child_idx == UINT32_MAX) {
6792                   child_indexes.clear();
6793                   return 0;
6794                 } else {
6795                   child_indexes.push_back(child_idx);
6796                   parent_record_decl = llvm::cast<clang::RecordDecl>(
6797                       elem.Base->getType()
6798                           ->castAs<clang::RecordType>()
6799                           ->getDecl());
6800                 }
6801               }
6802               for (clang::DeclContext::lookup_iterator I = path->Decls, E;
6803                    I != E; ++I) {
6804                 child_idx = GetIndexForRecordChild(
6805                     parent_record_decl, *I, omit_empty_base_classes);
6806                 if (child_idx == UINT32_MAX) {
6807                   child_indexes.clear();
6808                   return 0;
6809                 } else {
6810                   child_indexes.push_back(child_idx);
6811                 }
6812               }
6813             }
6814             return child_indexes.size();
6815           }
6816         }
6817       }
6818       break;
6819 
6820     case clang::Type::ObjCObject:
6821     case clang::Type::ObjCInterface:
6822       if (GetCompleteType(type)) {
6823         llvm::StringRef name_sref(name);
6824         const clang::ObjCObjectType *objc_class_type =
6825             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
6826         assert(objc_class_type);
6827         if (objc_class_type) {
6828           uint32_t child_idx = 0;
6829           clang::ObjCInterfaceDecl *class_interface_decl =
6830               objc_class_type->getInterface();
6831 
6832           if (class_interface_decl) {
6833             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6834                 ivar_end = class_interface_decl->ivar_end();
6835             clang::ObjCInterfaceDecl *superclass_interface_decl =
6836                 class_interface_decl->getSuperClass();
6837 
6838             for (ivar_pos = class_interface_decl->ivar_begin();
6839                  ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
6840               const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6841 
6842               if (ivar_decl->getName().equals(name_sref)) {
6843                 if ((!omit_empty_base_classes && superclass_interface_decl) ||
6844                     (omit_empty_base_classes &&
6845                      ObjCDeclHasIVars(superclass_interface_decl, true)))
6846                   ++child_idx;
6847 
6848                 child_indexes.push_back(child_idx);
6849                 return child_indexes.size();
6850               }
6851             }
6852 
6853             if (superclass_interface_decl) {
6854               // The super class index is always zero for ObjC classes, so we
6855               // push it onto the child indexes in case we find an ivar in our
6856               // superclass...
6857               child_indexes.push_back(0);
6858 
6859               CompilerType superclass_clang_type =
6860                   GetType(getASTContext().getObjCInterfaceType(
6861                       superclass_interface_decl));
6862               if (superclass_clang_type.GetIndexOfChildMemberWithName(
6863                       name, omit_empty_base_classes, child_indexes)) {
6864                 // We did find an ivar in a superclass so just return the
6865                 // results!
6866                 return child_indexes.size();
6867               }
6868 
6869               // We didn't find an ivar matching "name" in our superclass, pop
6870               // the superclass zero index that we pushed on above.
6871               child_indexes.pop_back();
6872             }
6873           }
6874         }
6875       }
6876       break;
6877 
6878     case clang::Type::ObjCObjectPointer: {
6879       CompilerType objc_object_clang_type = GetType(
6880           llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
6881               ->getPointeeType());
6882       return objc_object_clang_type.GetIndexOfChildMemberWithName(
6883           name, omit_empty_base_classes, child_indexes);
6884     } break;
6885 
6886     case clang::Type::ConstantArray: {
6887       //                const clang::ConstantArrayType *array =
6888       //                llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
6889       //                const uint64_t element_count =
6890       //                array->getSize().getLimitedValue();
6891       //
6892       //                if (idx < element_count)
6893       //                {
6894       //                    std::pair<uint64_t, unsigned> field_type_info =
6895       //                    ast->getTypeInfo(array->getElementType());
6896       //
6897       //                    char element_name[32];
6898       //                    ::snprintf (element_name, sizeof (element_name),
6899       //                    "%s[%u]", parent_name ? parent_name : "", idx);
6900       //
6901       //                    child_name.assign(element_name);
6902       //                    assert(field_type_info.first % 8 == 0);
6903       //                    child_byte_size = field_type_info.first / 8;
6904       //                    child_byte_offset = idx * child_byte_size;
6905       //                    return array->getElementType().getAsOpaquePtr();
6906       //                }
6907     } break;
6908 
6909     //        case clang::Type::MemberPointerType:
6910     //            {
6911     //                MemberPointerType *mem_ptr_type =
6912     //                llvm::cast<MemberPointerType>(qual_type.getTypePtr());
6913     //                clang::QualType pointee_type =
6914     //                mem_ptr_type->getPointeeType();
6915     //
6916     //                if (TypeSystemClang::IsAggregateType
6917     //                (pointee_type.getAsOpaquePtr()))
6918     //                {
6919     //                    return GetIndexOfChildWithName (ast,
6920     //                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
6921     //                                                    name);
6922     //                }
6923     //            }
6924     //            break;
6925     //
6926     case clang::Type::LValueReference:
6927     case clang::Type::RValueReference: {
6928       const clang::ReferenceType *reference_type =
6929           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
6930       clang::QualType pointee_type(reference_type->getPointeeType());
6931       CompilerType pointee_clang_type = GetType(pointee_type);
6932 
6933       if (pointee_clang_type.IsAggregateType()) {
6934         return pointee_clang_type.GetIndexOfChildMemberWithName(
6935             name, omit_empty_base_classes, child_indexes);
6936       }
6937     } break;
6938 
6939     case clang::Type::Pointer: {
6940       CompilerType pointee_clang_type(GetPointeeType(type));
6941 
6942       if (pointee_clang_type.IsAggregateType()) {
6943         return pointee_clang_type.GetIndexOfChildMemberWithName(
6944             name, omit_empty_base_classes, child_indexes);
6945       }
6946     } break;
6947 
6948     default:
6949       break;
6950     }
6951   }
6952   return 0;
6953 }
6954 
6955 // Get the index of the child of "clang_type" whose name matches. This function
6956 // doesn't descend into the children, but only looks one level deep and name
6957 // matches can include base class names.
6958 
6959 uint32_t
6960 TypeSystemClang::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
6961                                          const char *name,
6962                                          bool omit_empty_base_classes) {
6963   if (type && name && name[0]) {
6964     clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6965 
6966     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6967 
6968     switch (type_class) {
6969     case clang::Type::Record:
6970       if (GetCompleteType(type)) {
6971         const clang::RecordType *record_type =
6972             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6973         const clang::RecordDecl *record_decl = record_type->getDecl();
6974 
6975         assert(record_decl);
6976         uint32_t child_idx = 0;
6977 
6978         const clang::CXXRecordDecl *cxx_record_decl =
6979             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6980 
6981         if (cxx_record_decl) {
6982           clang::CXXRecordDecl::base_class_const_iterator base_class,
6983               base_class_end;
6984           for (base_class = cxx_record_decl->bases_begin(),
6985               base_class_end = cxx_record_decl->bases_end();
6986                base_class != base_class_end; ++base_class) {
6987             // Skip empty base classes
6988             clang::CXXRecordDecl *base_class_decl =
6989                 llvm::cast<clang::CXXRecordDecl>(
6990                     base_class->getType()
6991                         ->castAs<clang::RecordType>()
6992                         ->getDecl());
6993             if (omit_empty_base_classes &&
6994                 !TypeSystemClang::RecordHasFields(base_class_decl))
6995               continue;
6996 
6997             CompilerType base_class_clang_type = GetType(base_class->getType());
6998             std::string base_class_type_name(
6999                 base_class_clang_type.GetTypeName().AsCString(""));
7000             if (base_class_type_name == name)
7001               return child_idx;
7002             ++child_idx;
7003           }
7004         }
7005 
7006         // Try and find a field that matches NAME
7007         clang::RecordDecl::field_iterator field, field_end;
7008         llvm::StringRef name_sref(name);
7009         for (field = record_decl->field_begin(),
7010             field_end = record_decl->field_end();
7011              field != field_end; ++field, ++child_idx) {
7012           if (field->getName().equals(name_sref))
7013             return child_idx;
7014         }
7015       }
7016       break;
7017 
7018     case clang::Type::ObjCObject:
7019     case clang::Type::ObjCInterface:
7020       if (GetCompleteType(type)) {
7021         llvm::StringRef name_sref(name);
7022         const clang::ObjCObjectType *objc_class_type =
7023             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
7024         assert(objc_class_type);
7025         if (objc_class_type) {
7026           uint32_t child_idx = 0;
7027           clang::ObjCInterfaceDecl *class_interface_decl =
7028               objc_class_type->getInterface();
7029 
7030           if (class_interface_decl) {
7031             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
7032                 ivar_end = class_interface_decl->ivar_end();
7033             clang::ObjCInterfaceDecl *superclass_interface_decl =
7034                 class_interface_decl->getSuperClass();
7035 
7036             for (ivar_pos = class_interface_decl->ivar_begin();
7037                  ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
7038               const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
7039 
7040               if (ivar_decl->getName().equals(name_sref)) {
7041                 if ((!omit_empty_base_classes && superclass_interface_decl) ||
7042                     (omit_empty_base_classes &&
7043                      ObjCDeclHasIVars(superclass_interface_decl, true)))
7044                   ++child_idx;
7045 
7046                 return child_idx;
7047               }
7048             }
7049 
7050             if (superclass_interface_decl) {
7051               if (superclass_interface_decl->getName().equals(name_sref))
7052                 return 0;
7053             }
7054           }
7055         }
7056       }
7057       break;
7058 
7059     case clang::Type::ObjCObjectPointer: {
7060       CompilerType pointee_clang_type = GetType(
7061           llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
7062               ->getPointeeType());
7063       return pointee_clang_type.GetIndexOfChildWithName(
7064           name, omit_empty_base_classes);
7065     } break;
7066 
7067     case clang::Type::ConstantArray: {
7068       //                const clang::ConstantArrayType *array =
7069       //                llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
7070       //                const uint64_t element_count =
7071       //                array->getSize().getLimitedValue();
7072       //
7073       //                if (idx < element_count)
7074       //                {
7075       //                    std::pair<uint64_t, unsigned> field_type_info =
7076       //                    ast->getTypeInfo(array->getElementType());
7077       //
7078       //                    char element_name[32];
7079       //                    ::snprintf (element_name, sizeof (element_name),
7080       //                    "%s[%u]", parent_name ? parent_name : "", idx);
7081       //
7082       //                    child_name.assign(element_name);
7083       //                    assert(field_type_info.first % 8 == 0);
7084       //                    child_byte_size = field_type_info.first / 8;
7085       //                    child_byte_offset = idx * child_byte_size;
7086       //                    return array->getElementType().getAsOpaquePtr();
7087       //                }
7088     } break;
7089 
7090     //        case clang::Type::MemberPointerType:
7091     //            {
7092     //                MemberPointerType *mem_ptr_type =
7093     //                llvm::cast<MemberPointerType>(qual_type.getTypePtr());
7094     //                clang::QualType pointee_type =
7095     //                mem_ptr_type->getPointeeType();
7096     //
7097     //                if (TypeSystemClang::IsAggregateType
7098     //                (pointee_type.getAsOpaquePtr()))
7099     //                {
7100     //                    return GetIndexOfChildWithName (ast,
7101     //                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
7102     //                                                    name);
7103     //                }
7104     //            }
7105     //            break;
7106     //
7107     case clang::Type::LValueReference:
7108     case clang::Type::RValueReference: {
7109       const clang::ReferenceType *reference_type =
7110           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
7111       CompilerType pointee_type = GetType(reference_type->getPointeeType());
7112 
7113       if (pointee_type.IsAggregateType()) {
7114         return pointee_type.GetIndexOfChildWithName(name,
7115                                                     omit_empty_base_classes);
7116       }
7117     } break;
7118 
7119     case clang::Type::Pointer: {
7120       const clang::PointerType *pointer_type =
7121           llvm::cast<clang::PointerType>(qual_type.getTypePtr());
7122       CompilerType pointee_type = GetType(pointer_type->getPointeeType());
7123 
7124       if (pointee_type.IsAggregateType()) {
7125         return pointee_type.GetIndexOfChildWithName(name,
7126                                                     omit_empty_base_classes);
7127       } else {
7128         //                    if (parent_name)
7129         //                    {
7130         //                        child_name.assign(1, '*');
7131         //                        child_name += parent_name;
7132         //                    }
7133         //
7134         //                    // We have a pointer to an simple type
7135         //                    if (idx == 0)
7136         //                    {
7137         //                        std::pair<uint64_t, unsigned> clang_type_info
7138         //                        = ast->getTypeInfo(pointee_type);
7139         //                        assert(clang_type_info.first % 8 == 0);
7140         //                        child_byte_size = clang_type_info.first / 8;
7141         //                        child_byte_offset = 0;
7142         //                        return pointee_type.getAsOpaquePtr();
7143         //                    }
7144       }
7145     } break;
7146 
7147     default:
7148       break;
7149     }
7150   }
7151   return UINT32_MAX;
7152 }
7153 
7154 bool TypeSystemClang::IsTemplateType(lldb::opaque_compiler_type_t type) {
7155   if (!type)
7156     return false;
7157   CompilerType ct(weak_from_this(), type);
7158   const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr();
7159   if (auto *cxx_record_decl = dyn_cast<clang::TagType>(clang_type))
7160     return isa<clang::ClassTemplateSpecializationDecl>(
7161         cxx_record_decl->getDecl());
7162   return false;
7163 }
7164 
7165 size_t
7166 TypeSystemClang::GetNumTemplateArguments(lldb::opaque_compiler_type_t type,
7167                                          bool expand_pack) {
7168   if (!type)
7169     return 0;
7170 
7171   clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
7172   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7173   switch (type_class) {
7174   case clang::Type::Record:
7175     if (GetCompleteType(type)) {
7176       const clang::CXXRecordDecl *cxx_record_decl =
7177           qual_type->getAsCXXRecordDecl();
7178       if (cxx_record_decl) {
7179         const clang::ClassTemplateSpecializationDecl *template_decl =
7180             llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7181                 cxx_record_decl);
7182         if (template_decl) {
7183           const auto &template_arg_list = template_decl->getTemplateArgs();
7184           size_t num_args = template_arg_list.size();
7185           assert(num_args && "template specialization without any args");
7186           if (expand_pack && num_args) {
7187             const auto &pack = template_arg_list[num_args - 1];
7188             if (pack.getKind() == clang::TemplateArgument::Pack)
7189               num_args += pack.pack_size() - 1;
7190           }
7191           return num_args;
7192         }
7193       }
7194     }
7195     break;
7196 
7197   default:
7198     break;
7199   }
7200 
7201   return 0;
7202 }
7203 
7204 const clang::ClassTemplateSpecializationDecl *
7205 TypeSystemClang::GetAsTemplateSpecialization(
7206     lldb::opaque_compiler_type_t type) {
7207   if (!type)
7208     return nullptr;
7209 
7210   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
7211   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7212   switch (type_class) {
7213   case clang::Type::Record: {
7214     if (! GetCompleteType(type))
7215       return nullptr;
7216     const clang::CXXRecordDecl *cxx_record_decl =
7217         qual_type->getAsCXXRecordDecl();
7218     if (!cxx_record_decl)
7219       return nullptr;
7220     return llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7221         cxx_record_decl);
7222   }
7223 
7224   default:
7225     return nullptr;
7226   }
7227 }
7228 
7229 const TemplateArgument *
7230 GetNthTemplateArgument(const clang::ClassTemplateSpecializationDecl *decl,
7231                        size_t idx, bool expand_pack) {
7232   const auto &args = decl->getTemplateArgs();
7233   const size_t args_size = args.size();
7234 
7235   assert(args_size && "template specialization without any args");
7236   if (!args_size)
7237     return nullptr;
7238 
7239   const size_t last_idx = args_size - 1;
7240 
7241   // We're asked for a template argument that can't be a parameter pack, so
7242   // return it without worrying about 'expand_pack'.
7243   if (idx < last_idx)
7244     return &args[idx];
7245 
7246   // We're asked for the last template argument but we don't want/need to
7247   // expand it.
7248   if (!expand_pack || args[last_idx].getKind() != clang::TemplateArgument::Pack)
7249     return idx >= args.size() ? nullptr : &args[idx];
7250 
7251   // Index into the expanded pack.
7252   // Note that 'idx' counts from the beginning of all template arguments
7253   // (including the ones preceding the parameter pack).
7254   const auto &pack = args[last_idx];
7255   const size_t pack_idx = idx - last_idx;
7256   assert(pack_idx < pack.pack_size() && "parameter pack index out-of-bounds");
7257   return &pack.pack_elements()[pack_idx];
7258 }
7259 
7260 lldb::TemplateArgumentKind
7261 TypeSystemClang::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
7262                                          size_t arg_idx, bool expand_pack) {
7263   const clang::ClassTemplateSpecializationDecl *template_decl =
7264       GetAsTemplateSpecialization(type);
7265   if (!template_decl)
7266     return eTemplateArgumentKindNull;
7267 
7268   const auto *arg = GetNthTemplateArgument(template_decl, arg_idx, expand_pack);
7269   if (!arg)
7270     return eTemplateArgumentKindNull;
7271 
7272   switch (arg->getKind()) {
7273   case clang::TemplateArgument::Null:
7274     return eTemplateArgumentKindNull;
7275 
7276   case clang::TemplateArgument::NullPtr:
7277     return eTemplateArgumentKindNullPtr;
7278 
7279   case clang::TemplateArgument::Type:
7280     return eTemplateArgumentKindType;
7281 
7282   case clang::TemplateArgument::Declaration:
7283     return eTemplateArgumentKindDeclaration;
7284 
7285   case clang::TemplateArgument::Integral:
7286     return eTemplateArgumentKindIntegral;
7287 
7288   case clang::TemplateArgument::Template:
7289     return eTemplateArgumentKindTemplate;
7290 
7291   case clang::TemplateArgument::TemplateExpansion:
7292     return eTemplateArgumentKindTemplateExpansion;
7293 
7294   case clang::TemplateArgument::Expression:
7295     return eTemplateArgumentKindExpression;
7296 
7297   case clang::TemplateArgument::Pack:
7298     return eTemplateArgumentKindPack;
7299   }
7300   llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind");
7301 }
7302 
7303 CompilerType
7304 TypeSystemClang::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
7305                                          size_t idx, bool expand_pack) {
7306   const clang::ClassTemplateSpecializationDecl *template_decl =
7307       GetAsTemplateSpecialization(type);
7308   if (!template_decl)
7309     return CompilerType();
7310 
7311   const auto *arg = GetNthTemplateArgument(template_decl, idx, expand_pack);
7312   if (!arg || arg->getKind() != clang::TemplateArgument::Type)
7313     return CompilerType();
7314 
7315   return GetType(arg->getAsType());
7316 }
7317 
7318 std::optional<CompilerType::IntegralTemplateArgument>
7319 TypeSystemClang::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
7320                                              size_t idx, bool expand_pack) {
7321   const clang::ClassTemplateSpecializationDecl *template_decl =
7322       GetAsTemplateSpecialization(type);
7323   if (!template_decl)
7324     return std::nullopt;
7325 
7326   const auto *arg = GetNthTemplateArgument(template_decl, idx, expand_pack);
7327   if (!arg || arg->getKind() != clang::TemplateArgument::Integral)
7328     return std::nullopt;
7329 
7330   return {{arg->getAsIntegral(), GetType(arg->getIntegralType())}};
7331 }
7332 
7333 CompilerType TypeSystemClang::GetTypeForFormatters(void *type) {
7334   if (type)
7335     return ClangUtil::RemoveFastQualifiers(CompilerType(weak_from_this(), type));
7336   return CompilerType();
7337 }
7338 
7339 clang::EnumDecl *TypeSystemClang::GetAsEnumDecl(const CompilerType &type) {
7340   const clang::EnumType *enutype =
7341       llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type));
7342   if (enutype)
7343     return enutype->getDecl();
7344   return nullptr;
7345 }
7346 
7347 clang::RecordDecl *TypeSystemClang::GetAsRecordDecl(const CompilerType &type) {
7348   const clang::RecordType *record_type =
7349       llvm::dyn_cast<clang::RecordType>(ClangUtil::GetCanonicalQualType(type));
7350   if (record_type)
7351     return record_type->getDecl();
7352   return nullptr;
7353 }
7354 
7355 clang::TagDecl *TypeSystemClang::GetAsTagDecl(const CompilerType &type) {
7356   return ClangUtil::GetAsTagDecl(type);
7357 }
7358 
7359 clang::TypedefNameDecl *
7360 TypeSystemClang::GetAsTypedefDecl(const CompilerType &type) {
7361   const clang::TypedefType *typedef_type =
7362       llvm::dyn_cast<clang::TypedefType>(ClangUtil::GetQualType(type));
7363   if (typedef_type)
7364     return typedef_type->getDecl();
7365   return nullptr;
7366 }
7367 
7368 clang::CXXRecordDecl *
7369 TypeSystemClang::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) {
7370   return GetCanonicalQualType(type)->getAsCXXRecordDecl();
7371 }
7372 
7373 clang::ObjCInterfaceDecl *
7374 TypeSystemClang::GetAsObjCInterfaceDecl(const CompilerType &type) {
7375   const clang::ObjCObjectType *objc_class_type =
7376       llvm::dyn_cast<clang::ObjCObjectType>(
7377           ClangUtil::GetCanonicalQualType(type));
7378   if (objc_class_type)
7379     return objc_class_type->getInterface();
7380   return nullptr;
7381 }
7382 
7383 clang::FieldDecl *TypeSystemClang::AddFieldToRecordType(
7384     const CompilerType &type, llvm::StringRef name,
7385     const CompilerType &field_clang_type, AccessType access,
7386     uint32_t bitfield_bit_size) {
7387   if (!type.IsValid() || !field_clang_type.IsValid())
7388     return nullptr;
7389   auto ts = type.GetTypeSystem();
7390   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7391   if (!ast)
7392     return nullptr;
7393   clang::ASTContext &clang_ast = ast->getASTContext();
7394   clang::IdentifierInfo *ident = nullptr;
7395   if (!name.empty())
7396     ident = &clang_ast.Idents.get(name);
7397 
7398   clang::FieldDecl *field = nullptr;
7399 
7400   clang::Expr *bit_width = nullptr;
7401   if (bitfield_bit_size != 0) {
7402     llvm::APInt bitfield_bit_size_apint(clang_ast.getTypeSize(clang_ast.IntTy),
7403                                         bitfield_bit_size);
7404     bit_width = new (clang_ast)
7405         clang::IntegerLiteral(clang_ast, bitfield_bit_size_apint,
7406                               clang_ast.IntTy, clang::SourceLocation());
7407   }
7408 
7409   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7410   if (record_decl) {
7411     field = clang::FieldDecl::CreateDeserialized(clang_ast, 0);
7412     field->setDeclContext(record_decl);
7413     field->setDeclName(ident);
7414     field->setType(ClangUtil::GetQualType(field_clang_type));
7415     if (bit_width)
7416       field->setBitWidth(bit_width);
7417     SetMemberOwningModule(field, record_decl);
7418 
7419     if (name.empty()) {
7420       // Determine whether this field corresponds to an anonymous struct or
7421       // union.
7422       if (const clang::TagType *TagT =
7423               field->getType()->getAs<clang::TagType>()) {
7424         if (clang::RecordDecl *Rec =
7425                 llvm::dyn_cast<clang::RecordDecl>(TagT->getDecl()))
7426           if (!Rec->getDeclName()) {
7427             Rec->setAnonymousStructOrUnion(true);
7428             field->setImplicit();
7429           }
7430       }
7431     }
7432 
7433     if (field) {
7434       clang::AccessSpecifier access_specifier =
7435           TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access);
7436       field->setAccess(access_specifier);
7437 
7438       if (clang::CXXRecordDecl *cxx_record_decl =
7439               llvm::dyn_cast<CXXRecordDecl>(record_decl)) {
7440         AddAccessSpecifierDecl(cxx_record_decl, ast->getASTContext(),
7441                                ast->GetCXXRecordDeclAccess(cxx_record_decl),
7442                                access_specifier);
7443         ast->SetCXXRecordDeclAccess(cxx_record_decl, access_specifier);
7444       }
7445       record_decl->addDecl(field);
7446 
7447       VerifyDecl(field);
7448     }
7449   } else {
7450     clang::ObjCInterfaceDecl *class_interface_decl =
7451         ast->GetAsObjCInterfaceDecl(type);
7452 
7453     if (class_interface_decl) {
7454       const bool is_synthesized = false;
7455 
7456       field_clang_type.GetCompleteType();
7457 
7458       auto *ivar = clang::ObjCIvarDecl::CreateDeserialized(clang_ast, 0);
7459       ivar->setDeclContext(class_interface_decl);
7460       ivar->setDeclName(ident);
7461       ivar->setType(ClangUtil::GetQualType(field_clang_type));
7462       ivar->setAccessControl(ConvertAccessTypeToObjCIvarAccessControl(access));
7463       if (bit_width)
7464         ivar->setBitWidth(bit_width);
7465       ivar->setSynthesize(is_synthesized);
7466       field = ivar;
7467       SetMemberOwningModule(field, class_interface_decl);
7468 
7469       if (field) {
7470         class_interface_decl->addDecl(field);
7471 
7472         VerifyDecl(field);
7473       }
7474     }
7475   }
7476   return field;
7477 }
7478 
7479 void TypeSystemClang::BuildIndirectFields(const CompilerType &type) {
7480   if (!type)
7481     return;
7482 
7483   auto ts = type.GetTypeSystem();
7484   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7485   if (!ast)
7486     return;
7487 
7488   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7489 
7490   if (!record_decl)
7491     return;
7492 
7493   typedef llvm::SmallVector<clang::IndirectFieldDecl *, 1> IndirectFieldVector;
7494 
7495   IndirectFieldVector indirect_fields;
7496   clang::RecordDecl::field_iterator field_pos;
7497   clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end();
7498   clang::RecordDecl::field_iterator last_field_pos = field_end_pos;
7499   for (field_pos = record_decl->field_begin(); field_pos != field_end_pos;
7500        last_field_pos = field_pos++) {
7501     if (field_pos->isAnonymousStructOrUnion()) {
7502       clang::QualType field_qual_type = field_pos->getType();
7503 
7504       const clang::RecordType *field_record_type =
7505           field_qual_type->getAs<clang::RecordType>();
7506 
7507       if (!field_record_type)
7508         continue;
7509 
7510       clang::RecordDecl *field_record_decl = field_record_type->getDecl();
7511 
7512       if (!field_record_decl)
7513         continue;
7514 
7515       for (clang::RecordDecl::decl_iterator
7516                di = field_record_decl->decls_begin(),
7517                de = field_record_decl->decls_end();
7518            di != de; ++di) {
7519         if (clang::FieldDecl *nested_field_decl =
7520                 llvm::dyn_cast<clang::FieldDecl>(*di)) {
7521           clang::NamedDecl **chain =
7522               new (ast->getASTContext()) clang::NamedDecl *[2];
7523           chain[0] = *field_pos;
7524           chain[1] = nested_field_decl;
7525           clang::IndirectFieldDecl *indirect_field =
7526               clang::IndirectFieldDecl::Create(
7527                   ast->getASTContext(), record_decl, clang::SourceLocation(),
7528                   nested_field_decl->getIdentifier(),
7529                   nested_field_decl->getType(), {chain, 2});
7530           SetMemberOwningModule(indirect_field, record_decl);
7531 
7532           indirect_field->setImplicit();
7533 
7534           indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7535               field_pos->getAccess(), nested_field_decl->getAccess()));
7536 
7537           indirect_fields.push_back(indirect_field);
7538         } else if (clang::IndirectFieldDecl *nested_indirect_field_decl =
7539                        llvm::dyn_cast<clang::IndirectFieldDecl>(*di)) {
7540           size_t nested_chain_size =
7541               nested_indirect_field_decl->getChainingSize();
7542           clang::NamedDecl **chain = new (ast->getASTContext())
7543               clang::NamedDecl *[nested_chain_size + 1];
7544           chain[0] = *field_pos;
7545 
7546           int chain_index = 1;
7547           for (clang::IndirectFieldDecl::chain_iterator
7548                    nci = nested_indirect_field_decl->chain_begin(),
7549                    nce = nested_indirect_field_decl->chain_end();
7550                nci < nce; ++nci) {
7551             chain[chain_index] = *nci;
7552             chain_index++;
7553           }
7554 
7555           clang::IndirectFieldDecl *indirect_field =
7556               clang::IndirectFieldDecl::Create(
7557                   ast->getASTContext(), record_decl, clang::SourceLocation(),
7558                   nested_indirect_field_decl->getIdentifier(),
7559                   nested_indirect_field_decl->getType(),
7560                   {chain, nested_chain_size + 1});
7561           SetMemberOwningModule(indirect_field, record_decl);
7562 
7563           indirect_field->setImplicit();
7564 
7565           indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7566               field_pos->getAccess(), nested_indirect_field_decl->getAccess()));
7567 
7568           indirect_fields.push_back(indirect_field);
7569         }
7570       }
7571     }
7572   }
7573 
7574   // Check the last field to see if it has an incomplete array type as its last
7575   // member and if it does, the tell the record decl about it
7576   if (last_field_pos != field_end_pos) {
7577     if (last_field_pos->getType()->isIncompleteArrayType())
7578       record_decl->hasFlexibleArrayMember();
7579   }
7580 
7581   for (IndirectFieldVector::iterator ifi = indirect_fields.begin(),
7582                                      ife = indirect_fields.end();
7583        ifi < ife; ++ifi) {
7584     record_decl->addDecl(*ifi);
7585   }
7586 }
7587 
7588 void TypeSystemClang::SetIsPacked(const CompilerType &type) {
7589   if (type) {
7590     auto ts = type.GetTypeSystem();
7591     auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7592     if (ast) {
7593       clang::RecordDecl *record_decl = GetAsRecordDecl(type);
7594 
7595       if (!record_decl)
7596         return;
7597 
7598       record_decl->addAttr(
7599           clang::PackedAttr::CreateImplicit(ast->getASTContext()));
7600     }
7601   }
7602 }
7603 
7604 clang::VarDecl *TypeSystemClang::AddVariableToRecordType(
7605     const CompilerType &type, llvm::StringRef name,
7606     const CompilerType &var_type, AccessType access) {
7607   if (!type.IsValid() || !var_type.IsValid())
7608     return nullptr;
7609 
7610   auto ts = type.GetTypeSystem();
7611   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7612   if (!ast)
7613     return nullptr;
7614 
7615   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7616   if (!record_decl)
7617     return nullptr;
7618 
7619   clang::VarDecl *var_decl = nullptr;
7620   clang::IdentifierInfo *ident = nullptr;
7621   if (!name.empty())
7622     ident = &ast->getASTContext().Idents.get(name);
7623 
7624   var_decl = clang::VarDecl::CreateDeserialized(ast->getASTContext(), 0);
7625   var_decl->setDeclContext(record_decl);
7626   var_decl->setDeclName(ident);
7627   var_decl->setType(ClangUtil::GetQualType(var_type));
7628   var_decl->setStorageClass(clang::SC_Static);
7629   SetMemberOwningModule(var_decl, record_decl);
7630   if (!var_decl)
7631     return nullptr;
7632 
7633   var_decl->setAccess(
7634       TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access));
7635   record_decl->addDecl(var_decl);
7636 
7637   VerifyDecl(var_decl);
7638 
7639   return var_decl;
7640 }
7641 
7642 void TypeSystemClang::SetIntegerInitializerForVariable(
7643     VarDecl *var, const llvm::APInt &init_value) {
7644   assert(!var->hasInit() && "variable already initialized");
7645 
7646   clang::ASTContext &ast = var->getASTContext();
7647   QualType qt = var->getType();
7648   assert(qt->isIntegralOrEnumerationType() &&
7649          "only integer or enum types supported");
7650   // If the variable is an enum type, take the underlying integer type as
7651   // the type of the integer literal.
7652   if (const EnumType *enum_type = qt->getAs<EnumType>()) {
7653     const EnumDecl *enum_decl = enum_type->getDecl();
7654     qt = enum_decl->getIntegerType();
7655   }
7656   // Bools are handled separately because the clang AST printer handles bools
7657   // separately from other integral types.
7658   if (qt->isSpecificBuiltinType(BuiltinType::Bool)) {
7659     var->setInit(CXXBoolLiteralExpr::Create(
7660         ast, !init_value.isZero(), qt.getUnqualifiedType(), SourceLocation()));
7661   } else {
7662     var->setInit(IntegerLiteral::Create(
7663         ast, init_value, qt.getUnqualifiedType(), SourceLocation()));
7664   }
7665 }
7666 
7667 void TypeSystemClang::SetFloatingInitializerForVariable(
7668     clang::VarDecl *var, const llvm::APFloat &init_value) {
7669   assert(!var->hasInit() && "variable already initialized");
7670 
7671   clang::ASTContext &ast = var->getASTContext();
7672   QualType qt = var->getType();
7673   assert(qt->isFloatingType() && "only floating point types supported");
7674   var->setInit(FloatingLiteral::Create(
7675       ast, init_value, true, qt.getUnqualifiedType(), SourceLocation()));
7676 }
7677 
7678 clang::CXXMethodDecl *TypeSystemClang::AddMethodToCXXRecordType(
7679     lldb::opaque_compiler_type_t type, llvm::StringRef name,
7680     const char *mangled_name, const CompilerType &method_clang_type,
7681     lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline,
7682     bool is_explicit, bool is_attr_used, bool is_artificial) {
7683   if (!type || !method_clang_type.IsValid() || name.empty())
7684     return nullptr;
7685 
7686   clang::QualType record_qual_type(GetCanonicalQualType(type));
7687 
7688   clang::CXXRecordDecl *cxx_record_decl =
7689       record_qual_type->getAsCXXRecordDecl();
7690 
7691   if (cxx_record_decl == nullptr)
7692     return nullptr;
7693 
7694   clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
7695 
7696   clang::CXXMethodDecl *cxx_method_decl = nullptr;
7697 
7698   clang::DeclarationName decl_name(&getASTContext().Idents.get(name));
7699 
7700   const clang::FunctionType *function_type =
7701       llvm::dyn_cast<clang::FunctionType>(method_qual_type.getTypePtr());
7702 
7703   if (function_type == nullptr)
7704     return nullptr;
7705 
7706   const clang::FunctionProtoType *method_function_prototype(
7707       llvm::dyn_cast<clang::FunctionProtoType>(function_type));
7708 
7709   if (!method_function_prototype)
7710     return nullptr;
7711 
7712   unsigned int num_params = method_function_prototype->getNumParams();
7713 
7714   clang::CXXDestructorDecl *cxx_dtor_decl(nullptr);
7715   clang::CXXConstructorDecl *cxx_ctor_decl(nullptr);
7716 
7717   if (is_artificial)
7718     return nullptr; // skip everything artificial
7719 
7720   const clang::ExplicitSpecifier explicit_spec(
7721       nullptr /*expr*/, is_explicit ? clang::ExplicitSpecKind::ResolvedTrue
7722                                     : clang::ExplicitSpecKind::ResolvedFalse);
7723 
7724   if (name.startswith("~")) {
7725     cxx_dtor_decl =
7726         clang::CXXDestructorDecl::CreateDeserialized(getASTContext(), 0);
7727     cxx_dtor_decl->setDeclContext(cxx_record_decl);
7728     cxx_dtor_decl->setDeclName(
7729         getASTContext().DeclarationNames.getCXXDestructorName(
7730             getASTContext().getCanonicalType(record_qual_type)));
7731     cxx_dtor_decl->setType(method_qual_type);
7732     cxx_dtor_decl->setImplicit(is_artificial);
7733     cxx_dtor_decl->setInlineSpecified(is_inline);
7734     cxx_dtor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7735     cxx_method_decl = cxx_dtor_decl;
7736   } else if (decl_name == cxx_record_decl->getDeclName()) {
7737     cxx_ctor_decl = clang::CXXConstructorDecl::CreateDeserialized(
7738         getASTContext(), 0, 0);
7739     cxx_ctor_decl->setDeclContext(cxx_record_decl);
7740     cxx_ctor_decl->setDeclName(
7741         getASTContext().DeclarationNames.getCXXConstructorName(
7742             getASTContext().getCanonicalType(record_qual_type)));
7743     cxx_ctor_decl->setType(method_qual_type);
7744     cxx_ctor_decl->setImplicit(is_artificial);
7745     cxx_ctor_decl->setInlineSpecified(is_inline);
7746     cxx_ctor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7747     cxx_ctor_decl->setNumCtorInitializers(0);
7748     cxx_ctor_decl->setExplicitSpecifier(explicit_spec);
7749     cxx_method_decl = cxx_ctor_decl;
7750   } else {
7751     clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None;
7752     clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
7753 
7754     if (IsOperator(name, op_kind)) {
7755       if (op_kind != clang::NUM_OVERLOADED_OPERATORS) {
7756         // Check the number of operator parameters. Sometimes we have seen bad
7757         // DWARF that doesn't correctly describe operators and if we try to
7758         // create a method and add it to the class, clang will assert and
7759         // crash, so we need to make sure things are acceptable.
7760         const bool is_method = true;
7761         if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
7762                 is_method, op_kind, num_params))
7763           return nullptr;
7764         cxx_method_decl =
7765             clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0);
7766         cxx_method_decl->setDeclContext(cxx_record_decl);
7767         cxx_method_decl->setDeclName(
7768             getASTContext().DeclarationNames.getCXXOperatorName(op_kind));
7769         cxx_method_decl->setType(method_qual_type);
7770         cxx_method_decl->setStorageClass(SC);
7771         cxx_method_decl->setInlineSpecified(is_inline);
7772         cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7773       } else if (num_params == 0) {
7774         // Conversion operators don't take params...
7775         auto *cxx_conversion_decl =
7776             clang::CXXConversionDecl::CreateDeserialized(getASTContext(), 0);
7777         cxx_conversion_decl->setDeclContext(cxx_record_decl);
7778         cxx_conversion_decl->setDeclName(
7779             getASTContext().DeclarationNames.getCXXConversionFunctionName(
7780                 getASTContext().getCanonicalType(
7781                     function_type->getReturnType())));
7782         cxx_conversion_decl->setType(method_qual_type);
7783         cxx_conversion_decl->setInlineSpecified(is_inline);
7784         cxx_conversion_decl->setExplicitSpecifier(explicit_spec);
7785         cxx_conversion_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7786         cxx_method_decl = cxx_conversion_decl;
7787       }
7788     }
7789 
7790     if (cxx_method_decl == nullptr) {
7791       cxx_method_decl =
7792           clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0);
7793       cxx_method_decl->setDeclContext(cxx_record_decl);
7794       cxx_method_decl->setDeclName(decl_name);
7795       cxx_method_decl->setType(method_qual_type);
7796       cxx_method_decl->setInlineSpecified(is_inline);
7797       cxx_method_decl->setStorageClass(SC);
7798       cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7799     }
7800   }
7801   SetMemberOwningModule(cxx_method_decl, cxx_record_decl);
7802 
7803   clang::AccessSpecifier access_specifier =
7804       TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access);
7805 
7806   cxx_method_decl->setAccess(access_specifier);
7807   cxx_method_decl->setVirtualAsWritten(is_virtual);
7808 
7809   if (is_attr_used)
7810     cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(getASTContext()));
7811 
7812   if (mangled_name != nullptr) {
7813     cxx_method_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
7814         getASTContext(), mangled_name, /*literal=*/false));
7815   }
7816 
7817   // Populate the method decl with parameter decls
7818 
7819   llvm::SmallVector<clang::ParmVarDecl *, 12> params;
7820 
7821   for (unsigned param_index = 0; param_index < num_params; ++param_index) {
7822     params.push_back(clang::ParmVarDecl::Create(
7823         getASTContext(), cxx_method_decl, clang::SourceLocation(),
7824         clang::SourceLocation(),
7825         nullptr, // anonymous
7826         method_function_prototype->getParamType(param_index), nullptr,
7827         clang::SC_None, nullptr));
7828   }
7829 
7830   cxx_method_decl->setParams(llvm::ArrayRef<clang::ParmVarDecl *>(params));
7831 
7832   AddAccessSpecifierDecl(cxx_record_decl, getASTContext(),
7833                          GetCXXRecordDeclAccess(cxx_record_decl),
7834                          access_specifier);
7835   SetCXXRecordDeclAccess(cxx_record_decl, access_specifier);
7836 
7837   cxx_record_decl->addDecl(cxx_method_decl);
7838 
7839   // Sometimes the debug info will mention a constructor (default/copy/move),
7840   // destructor, or assignment operator (copy/move) but there won't be any
7841   // version of this in the code. So we check if the function was artificially
7842   // generated and if it is trivial and this lets the compiler/backend know
7843   // that it can inline the IR for these when it needs to and we can avoid a
7844   // "missing function" error when running expressions.
7845 
7846   if (is_artificial) {
7847     if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() &&
7848                            cxx_record_decl->hasTrivialDefaultConstructor()) ||
7849                           (cxx_ctor_decl->isCopyConstructor() &&
7850                            cxx_record_decl->hasTrivialCopyConstructor()) ||
7851                           (cxx_ctor_decl->isMoveConstructor() &&
7852                            cxx_record_decl->hasTrivialMoveConstructor()))) {
7853       cxx_ctor_decl->setDefaulted();
7854       cxx_ctor_decl->setTrivial(true);
7855     } else if (cxx_dtor_decl) {
7856       if (cxx_record_decl->hasTrivialDestructor()) {
7857         cxx_dtor_decl->setDefaulted();
7858         cxx_dtor_decl->setTrivial(true);
7859       }
7860     } else if ((cxx_method_decl->isCopyAssignmentOperator() &&
7861                 cxx_record_decl->hasTrivialCopyAssignment()) ||
7862                (cxx_method_decl->isMoveAssignmentOperator() &&
7863                 cxx_record_decl->hasTrivialMoveAssignment())) {
7864       cxx_method_decl->setDefaulted();
7865       cxx_method_decl->setTrivial(true);
7866     }
7867   }
7868 
7869   VerifyDecl(cxx_method_decl);
7870 
7871   return cxx_method_decl;
7872 }
7873 
7874 void TypeSystemClang::AddMethodOverridesForCXXRecordType(
7875     lldb::opaque_compiler_type_t type) {
7876   if (auto *record = GetAsCXXRecordDecl(type))
7877     for (auto *method : record->methods())
7878       addOverridesForMethod(method);
7879 }
7880 
7881 #pragma mark C++ Base Classes
7882 
7883 std::unique_ptr<clang::CXXBaseSpecifier>
7884 TypeSystemClang::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
7885                                           AccessType access, bool is_virtual,
7886                                           bool base_of_class) {
7887   if (!type)
7888     return nullptr;
7889 
7890   return std::make_unique<clang::CXXBaseSpecifier>(
7891       clang::SourceRange(), is_virtual, base_of_class,
7892       TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access),
7893       getASTContext().getTrivialTypeSourceInfo(GetQualType(type)),
7894       clang::SourceLocation());
7895 }
7896 
7897 bool TypeSystemClang::TransferBaseClasses(
7898     lldb::opaque_compiler_type_t type,
7899     std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases) {
7900   if (!type)
7901     return false;
7902   clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type);
7903   if (!cxx_record_decl)
7904     return false;
7905   std::vector<clang::CXXBaseSpecifier *> raw_bases;
7906   raw_bases.reserve(bases.size());
7907 
7908   // Clang will make a copy of them, so it's ok that we pass pointers that we're
7909   // about to destroy.
7910   for (auto &b : bases)
7911     raw_bases.push_back(b.get());
7912   cxx_record_decl->setBases(raw_bases.data(), raw_bases.size());
7913   return true;
7914 }
7915 
7916 bool TypeSystemClang::SetObjCSuperClass(
7917     const CompilerType &type, const CompilerType &superclass_clang_type) {
7918   auto ts = type.GetTypeSystem();
7919   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7920   if (!ast)
7921     return false;
7922   clang::ASTContext &clang_ast = ast->getASTContext();
7923 
7924   if (type && superclass_clang_type.IsValid() &&
7925       superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) {
7926     clang::ObjCInterfaceDecl *class_interface_decl =
7927         GetAsObjCInterfaceDecl(type);
7928     clang::ObjCInterfaceDecl *super_interface_decl =
7929         GetAsObjCInterfaceDecl(superclass_clang_type);
7930     if (class_interface_decl && super_interface_decl) {
7931       class_interface_decl->setSuperClass(clang_ast.getTrivialTypeSourceInfo(
7932           clang_ast.getObjCInterfaceType(super_interface_decl)));
7933       return true;
7934     }
7935   }
7936   return false;
7937 }
7938 
7939 bool TypeSystemClang::AddObjCClassProperty(
7940     const CompilerType &type, const char *property_name,
7941     const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl,
7942     const char *property_setter_name, const char *property_getter_name,
7943     uint32_t property_attributes, ClangASTMetadata *metadata) {
7944   if (!type || !property_clang_type.IsValid() || property_name == nullptr ||
7945       property_name[0] == '\0')
7946     return false;
7947   auto ts = type.GetTypeSystem();
7948   auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
7949   if (!ast)
7950     return false;
7951   clang::ASTContext &clang_ast = ast->getASTContext();
7952 
7953   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7954   if (!class_interface_decl)
7955     return false;
7956 
7957   CompilerType property_clang_type_to_access;
7958 
7959   if (property_clang_type.IsValid())
7960     property_clang_type_to_access = property_clang_type;
7961   else if (ivar_decl)
7962     property_clang_type_to_access = ast->GetType(ivar_decl->getType());
7963 
7964   if (!class_interface_decl || !property_clang_type_to_access.IsValid())
7965     return false;
7966 
7967   clang::TypeSourceInfo *prop_type_source;
7968   if (ivar_decl)
7969     prop_type_source = clang_ast.getTrivialTypeSourceInfo(ivar_decl->getType());
7970   else
7971     prop_type_source = clang_ast.getTrivialTypeSourceInfo(
7972         ClangUtil::GetQualType(property_clang_type));
7973 
7974   clang::ObjCPropertyDecl *property_decl =
7975       clang::ObjCPropertyDecl::CreateDeserialized(clang_ast, 0);
7976   property_decl->setDeclContext(class_interface_decl);
7977   property_decl->setDeclName(&clang_ast.Idents.get(property_name));
7978   property_decl->setType(ivar_decl
7979                              ? ivar_decl->getType()
7980                              : ClangUtil::GetQualType(property_clang_type),
7981                          prop_type_source);
7982   SetMemberOwningModule(property_decl, class_interface_decl);
7983 
7984   if (!property_decl)
7985     return false;
7986 
7987   if (metadata)
7988     ast->SetMetadata(property_decl, *metadata);
7989 
7990   class_interface_decl->addDecl(property_decl);
7991 
7992   clang::Selector setter_sel, getter_sel;
7993 
7994   if (property_setter_name) {
7995     std::string property_setter_no_colon(property_setter_name,
7996                                          strlen(property_setter_name) - 1);
7997     clang::IdentifierInfo *setter_ident =
7998         &clang_ast.Idents.get(property_setter_no_colon);
7999     setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
8000   } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) {
8001     std::string setter_sel_string("set");
8002     setter_sel_string.push_back(::toupper(property_name[0]));
8003     setter_sel_string.append(&property_name[1]);
8004     clang::IdentifierInfo *setter_ident =
8005         &clang_ast.Idents.get(setter_sel_string);
8006     setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
8007   }
8008   property_decl->setSetterName(setter_sel);
8009   property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_setter);
8010 
8011   if (property_getter_name != nullptr) {
8012     clang::IdentifierInfo *getter_ident =
8013         &clang_ast.Idents.get(property_getter_name);
8014     getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
8015   } else {
8016     clang::IdentifierInfo *getter_ident = &clang_ast.Idents.get(property_name);
8017     getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
8018   }
8019   property_decl->setGetterName(getter_sel);
8020   property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_getter);
8021 
8022   if (ivar_decl)
8023     property_decl->setPropertyIvarDecl(ivar_decl);
8024 
8025   if (property_attributes & DW_APPLE_PROPERTY_readonly)
8026     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readonly);
8027   if (property_attributes & DW_APPLE_PROPERTY_readwrite)
8028     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite);
8029   if (property_attributes & DW_APPLE_PROPERTY_assign)
8030     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
8031   if (property_attributes & DW_APPLE_PROPERTY_retain)
8032     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_retain);
8033   if (property_attributes & DW_APPLE_PROPERTY_copy)
8034     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_copy);
8035   if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
8036     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic);
8037   if (property_attributes & ObjCPropertyAttribute::kind_nullability)
8038     property_decl->setPropertyAttributes(
8039         ObjCPropertyAttribute::kind_nullability);
8040   if (property_attributes & ObjCPropertyAttribute::kind_null_resettable)
8041     property_decl->setPropertyAttributes(
8042         ObjCPropertyAttribute::kind_null_resettable);
8043   if (property_attributes & ObjCPropertyAttribute::kind_class)
8044     property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_class);
8045 
8046   const bool isInstance =
8047       (property_attributes & ObjCPropertyAttribute::kind_class) == 0;
8048 
8049   clang::ObjCMethodDecl *getter = nullptr;
8050   if (!getter_sel.isNull())
8051     getter = isInstance ? class_interface_decl->lookupInstanceMethod(getter_sel)
8052                         : class_interface_decl->lookupClassMethod(getter_sel);
8053   if (!getter_sel.isNull() && !getter) {
8054     const bool isVariadic = false;
8055     const bool isPropertyAccessor = true;
8056     const bool isSynthesizedAccessorStub = false;
8057     const bool isImplicitlyDeclared = true;
8058     const bool isDefined = false;
8059     const clang::ObjCMethodDecl::ImplementationControl impControl =
8060         clang::ObjCMethodDecl::None;
8061     const bool HasRelatedResultType = false;
8062 
8063     getter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0);
8064     getter->setDeclName(getter_sel);
8065     getter->setReturnType(ClangUtil::GetQualType(property_clang_type_to_access));
8066     getter->setDeclContext(class_interface_decl);
8067     getter->setInstanceMethod(isInstance);
8068     getter->setVariadic(isVariadic);
8069     getter->setPropertyAccessor(isPropertyAccessor);
8070     getter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8071     getter->setImplicit(isImplicitlyDeclared);
8072     getter->setDefined(isDefined);
8073     getter->setDeclImplementation(impControl);
8074     getter->setRelatedResultType(HasRelatedResultType);
8075     SetMemberOwningModule(getter, class_interface_decl);
8076 
8077     if (getter) {
8078       if (metadata)
8079         ast->SetMetadata(getter, *metadata);
8080 
8081       getter->setMethodParams(clang_ast, llvm::ArrayRef<clang::ParmVarDecl *>(),
8082                               llvm::ArrayRef<clang::SourceLocation>());
8083       class_interface_decl->addDecl(getter);
8084     }
8085   }
8086   if (getter) {
8087     getter->setPropertyAccessor(true);
8088     property_decl->setGetterMethodDecl(getter);
8089   }
8090 
8091   clang::ObjCMethodDecl *setter = nullptr;
8092     setter = isInstance ? class_interface_decl->lookupInstanceMethod(setter_sel)
8093                         : class_interface_decl->lookupClassMethod(setter_sel);
8094   if (!setter_sel.isNull() && !setter) {
8095     clang::QualType result_type = clang_ast.VoidTy;
8096     const bool isVariadic = false;
8097     const bool isPropertyAccessor = true;
8098     const bool isSynthesizedAccessorStub = false;
8099     const bool isImplicitlyDeclared = true;
8100     const bool isDefined = false;
8101     const clang::ObjCMethodDecl::ImplementationControl impControl =
8102         clang::ObjCMethodDecl::None;
8103     const bool HasRelatedResultType = false;
8104 
8105     setter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0);
8106     setter->setDeclName(setter_sel);
8107     setter->setReturnType(result_type);
8108     setter->setDeclContext(class_interface_decl);
8109     setter->setInstanceMethod(isInstance);
8110     setter->setVariadic(isVariadic);
8111     setter->setPropertyAccessor(isPropertyAccessor);
8112     setter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8113     setter->setImplicit(isImplicitlyDeclared);
8114     setter->setDefined(isDefined);
8115     setter->setDeclImplementation(impControl);
8116     setter->setRelatedResultType(HasRelatedResultType);
8117     SetMemberOwningModule(setter, class_interface_decl);
8118 
8119     if (setter) {
8120       if (metadata)
8121         ast->SetMetadata(setter, *metadata);
8122 
8123       llvm::SmallVector<clang::ParmVarDecl *, 1> params;
8124       params.push_back(clang::ParmVarDecl::Create(
8125           clang_ast, setter, clang::SourceLocation(), clang::SourceLocation(),
8126           nullptr, // anonymous
8127           ClangUtil::GetQualType(property_clang_type_to_access), nullptr,
8128           clang::SC_Auto, nullptr));
8129 
8130       setter->setMethodParams(clang_ast,
8131                               llvm::ArrayRef<clang::ParmVarDecl *>(params),
8132                               llvm::ArrayRef<clang::SourceLocation>());
8133 
8134       class_interface_decl->addDecl(setter);
8135     }
8136   }
8137   if (setter) {
8138     setter->setPropertyAccessor(true);
8139     property_decl->setSetterMethodDecl(setter);
8140   }
8141 
8142   return true;
8143 }
8144 
8145 bool TypeSystemClang::IsObjCClassTypeAndHasIVars(const CompilerType &type,
8146                                                  bool check_superclass) {
8147   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8148   if (class_interface_decl)
8149     return ObjCDeclHasIVars(class_interface_decl, check_superclass);
8150   return false;
8151 }
8152 
8153 clang::ObjCMethodDecl *TypeSystemClang::AddMethodToObjCObjectType(
8154     const CompilerType &type,
8155     const char *name, // the full symbol name as seen in the symbol table
8156                       // (lldb::opaque_compiler_type_t type, "-[NString
8157                       // stringWithCString:]")
8158     const CompilerType &method_clang_type, lldb::AccessType access,
8159     bool is_artificial, bool is_variadic, bool is_objc_direct_call) {
8160   if (!type || !method_clang_type.IsValid())
8161     return nullptr;
8162 
8163   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8164 
8165   if (class_interface_decl == nullptr)
8166     return nullptr;
8167   auto ts = type.GetTypeSystem();
8168   auto lldb_ast = ts.dyn_cast_or_null<TypeSystemClang>();
8169   if (lldb_ast == nullptr)
8170     return nullptr;
8171   clang::ASTContext &ast = lldb_ast->getASTContext();
8172 
8173   const char *selector_start = ::strchr(name, ' ');
8174   if (selector_start == nullptr)
8175     return nullptr;
8176 
8177   selector_start++;
8178   llvm::SmallVector<clang::IdentifierInfo *, 12> selector_idents;
8179 
8180   size_t len = 0;
8181   const char *start;
8182 
8183   unsigned num_selectors_with_args = 0;
8184   for (start = selector_start; start && *start != '\0' && *start != ']';
8185        start += len) {
8186     len = ::strcspn(start, ":]");
8187     bool has_arg = (start[len] == ':');
8188     if (has_arg)
8189       ++num_selectors_with_args;
8190     selector_idents.push_back(&ast.Idents.get(llvm::StringRef(start, len)));
8191     if (has_arg)
8192       len += 1;
8193   }
8194 
8195   if (selector_idents.size() == 0)
8196     return nullptr;
8197 
8198   clang::Selector method_selector = ast.Selectors.getSelector(
8199       num_selectors_with_args ? selector_idents.size() : 0,
8200       selector_idents.data());
8201 
8202   clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
8203 
8204   // Populate the method decl with parameter decls
8205   const clang::Type *method_type(method_qual_type.getTypePtr());
8206 
8207   if (method_type == nullptr)
8208     return nullptr;
8209 
8210   const clang::FunctionProtoType *method_function_prototype(
8211       llvm::dyn_cast<clang::FunctionProtoType>(method_type));
8212 
8213   if (!method_function_prototype)
8214     return nullptr;
8215 
8216   const bool isInstance = (name[0] == '-');
8217   const bool isVariadic = is_variadic;
8218   const bool isPropertyAccessor = false;
8219   const bool isSynthesizedAccessorStub = false;
8220   /// Force this to true because we don't have source locations.
8221   const bool isImplicitlyDeclared = true;
8222   const bool isDefined = false;
8223   const clang::ObjCMethodDecl::ImplementationControl impControl =
8224       clang::ObjCMethodDecl::None;
8225   const bool HasRelatedResultType = false;
8226 
8227   const unsigned num_args = method_function_prototype->getNumParams();
8228 
8229   if (num_args != num_selectors_with_args)
8230     return nullptr; // some debug information is corrupt.  We are not going to
8231                     // deal with it.
8232 
8233   auto *objc_method_decl = clang::ObjCMethodDecl::CreateDeserialized(ast, 0);
8234   objc_method_decl->setDeclName(method_selector);
8235   objc_method_decl->setReturnType(method_function_prototype->getReturnType());
8236   objc_method_decl->setDeclContext(
8237       lldb_ast->GetDeclContextForType(ClangUtil::GetQualType(type)));
8238   objc_method_decl->setInstanceMethod(isInstance);
8239   objc_method_decl->setVariadic(isVariadic);
8240   objc_method_decl->setPropertyAccessor(isPropertyAccessor);
8241   objc_method_decl->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
8242   objc_method_decl->setImplicit(isImplicitlyDeclared);
8243   objc_method_decl->setDefined(isDefined);
8244   objc_method_decl->setDeclImplementation(impControl);
8245   objc_method_decl->setRelatedResultType(HasRelatedResultType);
8246   SetMemberOwningModule(objc_method_decl, class_interface_decl);
8247 
8248   if (objc_method_decl == nullptr)
8249     return nullptr;
8250 
8251   if (num_args > 0) {
8252     llvm::SmallVector<clang::ParmVarDecl *, 12> params;
8253 
8254     for (unsigned param_index = 0; param_index < num_args; ++param_index) {
8255       params.push_back(clang::ParmVarDecl::Create(
8256           ast, objc_method_decl, clang::SourceLocation(),
8257           clang::SourceLocation(),
8258           nullptr, // anonymous
8259           method_function_prototype->getParamType(param_index), nullptr,
8260           clang::SC_Auto, nullptr));
8261     }
8262 
8263     objc_method_decl->setMethodParams(
8264         ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
8265         llvm::ArrayRef<clang::SourceLocation>());
8266   }
8267 
8268   if (is_objc_direct_call) {
8269     // Add a the objc_direct attribute to the declaration we generate that
8270     // we generate a direct method call for this ObjCMethodDecl.
8271     objc_method_decl->addAttr(
8272         clang::ObjCDirectAttr::CreateImplicit(ast, SourceLocation()));
8273     // Usually Sema is creating implicit parameters (e.g., self) when it
8274     // parses the method. We don't have a parsing Sema when we build our own
8275     // AST here so we manually need to create these implicit parameters to
8276     // make the direct call code generation happy.
8277     objc_method_decl->createImplicitParams(ast, class_interface_decl);
8278   }
8279 
8280   class_interface_decl->addDecl(objc_method_decl);
8281 
8282   VerifyDecl(objc_method_decl);
8283 
8284   return objc_method_decl;
8285 }
8286 
8287 bool TypeSystemClang::SetHasExternalStorage(lldb::opaque_compiler_type_t type,
8288                                             bool has_extern) {
8289   if (!type)
8290     return false;
8291 
8292   clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
8293 
8294   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8295   switch (type_class) {
8296   case clang::Type::Record: {
8297     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
8298     if (cxx_record_decl) {
8299       cxx_record_decl->setHasExternalLexicalStorage(has_extern);
8300       cxx_record_decl->setHasExternalVisibleStorage(has_extern);
8301       return true;
8302     }
8303   } break;
8304 
8305   case clang::Type::Enum: {
8306     clang::EnumDecl *enum_decl =
8307         llvm::cast<clang::EnumType>(qual_type)->getDecl();
8308     if (enum_decl) {
8309       enum_decl->setHasExternalLexicalStorage(has_extern);
8310       enum_decl->setHasExternalVisibleStorage(has_extern);
8311       return true;
8312     }
8313   } break;
8314 
8315   case clang::Type::ObjCObject:
8316   case clang::Type::ObjCInterface: {
8317     const clang::ObjCObjectType *objc_class_type =
8318         llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8319     assert(objc_class_type);
8320     if (objc_class_type) {
8321       clang::ObjCInterfaceDecl *class_interface_decl =
8322           objc_class_type->getInterface();
8323 
8324       if (class_interface_decl) {
8325         class_interface_decl->setHasExternalLexicalStorage(has_extern);
8326         class_interface_decl->setHasExternalVisibleStorage(has_extern);
8327         return true;
8328       }
8329     }
8330   } break;
8331 
8332   default:
8333     break;
8334   }
8335   return false;
8336 }
8337 
8338 #pragma mark TagDecl
8339 
8340 bool TypeSystemClang::StartTagDeclarationDefinition(const CompilerType &type) {
8341   clang::QualType qual_type(ClangUtil::GetQualType(type));
8342   if (!qual_type.isNull()) {
8343     const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8344     if (tag_type) {
8345       clang::TagDecl *tag_decl = tag_type->getDecl();
8346       if (tag_decl) {
8347         tag_decl->startDefinition();
8348         return true;
8349       }
8350     }
8351 
8352     const clang::ObjCObjectType *object_type =
8353         qual_type->getAs<clang::ObjCObjectType>();
8354     if (object_type) {
8355       clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface();
8356       if (interface_decl) {
8357         interface_decl->startDefinition();
8358         return true;
8359       }
8360     }
8361   }
8362   return false;
8363 }
8364 
8365 bool TypeSystemClang::CompleteTagDeclarationDefinition(
8366     const CompilerType &type) {
8367   clang::QualType qual_type(ClangUtil::GetQualType(type));
8368   if (qual_type.isNull())
8369     return false;
8370 
8371   auto ts = type.GetTypeSystem();
8372   auto lldb_ast = ts.dyn_cast_or_null<TypeSystemClang>();
8373   if (lldb_ast == nullptr)
8374     return false;
8375 
8376   // Make sure we use the same methodology as
8377   // TypeSystemClang::StartTagDeclarationDefinition() as to how we start/end
8378   // the definition.
8379   const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8380   if (tag_type) {
8381     clang::TagDecl *tag_decl = tag_type->getDecl();
8382 
8383     if (auto *cxx_record_decl = llvm::dyn_cast<CXXRecordDecl>(tag_decl)) {
8384       // If we have a move constructor declared but no copy constructor we
8385       // need to explicitly mark it as deleted. Usually Sema would do this for
8386       // us in Sema::DeclareImplicitCopyConstructor but we don't have a Sema
8387       // when building an AST from debug information.
8388       // See also:
8389       // C++11 [class.copy]p7, p18:
8390       //  If the class definition declares a move constructor or move assignment
8391       //  operator, an implicitly declared copy constructor or copy assignment
8392       //  operator is defined as deleted.
8393       if (cxx_record_decl->hasUserDeclaredMoveConstructor() ||
8394           cxx_record_decl->hasUserDeclaredMoveAssignment()) {
8395         if (cxx_record_decl->needsImplicitCopyConstructor())
8396           cxx_record_decl->setImplicitCopyConstructorIsDeleted();
8397         if (cxx_record_decl->needsImplicitCopyAssignment())
8398           cxx_record_decl->setImplicitCopyAssignmentIsDeleted();
8399       }
8400 
8401       if (!cxx_record_decl->isCompleteDefinition())
8402         cxx_record_decl->completeDefinition();
8403       cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
8404       cxx_record_decl->setHasExternalLexicalStorage(false);
8405       cxx_record_decl->setHasExternalVisibleStorage(false);
8406       lldb_ast->SetCXXRecordDeclAccess(cxx_record_decl,
8407                                        clang::AccessSpecifier::AS_none);
8408       return true;
8409     }
8410   }
8411 
8412   const clang::EnumType *enutype = qual_type->getAs<clang::EnumType>();
8413 
8414   if (!enutype)
8415     return false;
8416   clang::EnumDecl *enum_decl = enutype->getDecl();
8417 
8418   if (enum_decl->isCompleteDefinition())
8419     return true;
8420 
8421   clang::ASTContext &ast = lldb_ast->getASTContext();
8422 
8423   /// TODO This really needs to be fixed.
8424 
8425   QualType integer_type(enum_decl->getIntegerType());
8426   if (!integer_type.isNull()) {
8427     unsigned NumPositiveBits = 1;
8428     unsigned NumNegativeBits = 0;
8429 
8430     clang::QualType promotion_qual_type;
8431     // If the enum integer type is less than an integer in bit width,
8432     // then we must promote it to an integer size.
8433     if (ast.getTypeSize(enum_decl->getIntegerType()) <
8434         ast.getTypeSize(ast.IntTy)) {
8435       if (enum_decl->getIntegerType()->isSignedIntegerType())
8436         promotion_qual_type = ast.IntTy;
8437       else
8438         promotion_qual_type = ast.UnsignedIntTy;
8439     } else
8440       promotion_qual_type = enum_decl->getIntegerType();
8441 
8442     enum_decl->completeDefinition(enum_decl->getIntegerType(),
8443                                   promotion_qual_type, NumPositiveBits,
8444                                   NumNegativeBits);
8445   }
8446   return true;
8447 }
8448 
8449 clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8450     const CompilerType &enum_type, const Declaration &decl, const char *name,
8451     const llvm::APSInt &value) {
8452 
8453   if (!enum_type || ConstString(name).IsEmpty())
8454     return nullptr;
8455 
8456   lldbassert(enum_type.GetTypeSystem().GetSharedPointer().get() ==
8457              static_cast<TypeSystem *>(this));
8458 
8459   lldb::opaque_compiler_type_t enum_opaque_compiler_type =
8460       enum_type.GetOpaqueQualType();
8461 
8462   if (!enum_opaque_compiler_type)
8463     return nullptr;
8464 
8465   clang::QualType enum_qual_type(
8466       GetCanonicalQualType(enum_opaque_compiler_type));
8467 
8468   const clang::Type *clang_type = enum_qual_type.getTypePtr();
8469 
8470   if (!clang_type)
8471     return nullptr;
8472 
8473   const clang::EnumType *enutype = llvm::dyn_cast<clang::EnumType>(clang_type);
8474 
8475   if (!enutype)
8476     return nullptr;
8477 
8478   clang::EnumConstantDecl *enumerator_decl =
8479       clang::EnumConstantDecl::CreateDeserialized(getASTContext(), 0);
8480   enumerator_decl->setDeclContext(enutype->getDecl());
8481   if (name && name[0])
8482     enumerator_decl->setDeclName(&getASTContext().Idents.get(name));
8483   enumerator_decl->setType(clang::QualType(enutype, 0));
8484   enumerator_decl->setInitVal(value);
8485   SetMemberOwningModule(enumerator_decl, enutype->getDecl());
8486 
8487   if (!enumerator_decl)
8488     return nullptr;
8489 
8490   enutype->getDecl()->addDecl(enumerator_decl);
8491 
8492   VerifyDecl(enumerator_decl);
8493   return enumerator_decl;
8494 }
8495 
8496 clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8497     const CompilerType &enum_type, const Declaration &decl, const char *name,
8498     int64_t enum_value, uint32_t enum_value_bit_size) {
8499   CompilerType underlying_type = GetEnumerationIntegerType(enum_type);
8500   bool is_signed = false;
8501   underlying_type.IsIntegerType(is_signed);
8502 
8503   llvm::APSInt value(enum_value_bit_size, is_signed);
8504   value = enum_value;
8505 
8506   return AddEnumerationValueToEnumerationType(enum_type, decl, name, value);
8507 }
8508 
8509 CompilerType TypeSystemClang::GetEnumerationIntegerType(CompilerType type) {
8510   clang::QualType qt(ClangUtil::GetQualType(type));
8511   const clang::Type *clang_type = qt.getTypePtrOrNull();
8512   const auto *enum_type = llvm::dyn_cast_or_null<clang::EnumType>(clang_type);
8513   if (!enum_type)
8514     return CompilerType();
8515 
8516   return GetType(enum_type->getDecl()->getIntegerType());
8517 }
8518 
8519 CompilerType
8520 TypeSystemClang::CreateMemberPointerType(const CompilerType &type,
8521                                          const CompilerType &pointee_type) {
8522   if (type && pointee_type.IsValid() &&
8523       type.GetTypeSystem() == pointee_type.GetTypeSystem()) {
8524     auto ts = type.GetTypeSystem();
8525     auto ast = ts.dyn_cast_or_null<TypeSystemClang>();
8526     if (!ast)
8527       return CompilerType();
8528     return ast->GetType(ast->getASTContext().getMemberPointerType(
8529         ClangUtil::GetQualType(pointee_type),
8530         ClangUtil::GetQualType(type).getTypePtr()));
8531   }
8532   return CompilerType();
8533 }
8534 
8535 // Dumping types
8536 #define DEPTH_INCREMENT 2
8537 
8538 #ifndef NDEBUG
8539 LLVM_DUMP_METHOD void
8540 TypeSystemClang::dump(lldb::opaque_compiler_type_t type) const {
8541   if (!type)
8542     return;
8543   clang::QualType qual_type(GetQualType(type));
8544   qual_type.dump();
8545 }
8546 #endif
8547 
8548 void TypeSystemClang::Dump(llvm::raw_ostream &output) {
8549   GetTranslationUnitDecl()->dump(output);
8550 }
8551 
8552 void TypeSystemClang::DumpFromSymbolFile(Stream &s,
8553                                          llvm::StringRef symbol_name) {
8554   SymbolFile *symfile = GetSymbolFile();
8555 
8556   if (!symfile)
8557     return;
8558 
8559   lldb_private::TypeList type_list;
8560   symfile->GetTypes(nullptr, eTypeClassAny, type_list);
8561   size_t ntypes = type_list.GetSize();
8562 
8563   for (size_t i = 0; i < ntypes; ++i) {
8564     TypeSP type = type_list.GetTypeAtIndex(i);
8565 
8566     if (!symbol_name.empty())
8567       if (symbol_name != type->GetName().GetStringRef())
8568         continue;
8569 
8570     s << type->GetName().AsCString() << "\n";
8571 
8572     CompilerType full_type = type->GetFullCompilerType();
8573     if (clang::TagDecl *tag_decl = GetAsTagDecl(full_type)) {
8574       tag_decl->dump(s.AsRawOstream());
8575       continue;
8576     }
8577     if (clang::TypedefNameDecl *typedef_decl = GetAsTypedefDecl(full_type)) {
8578       typedef_decl->dump(s.AsRawOstream());
8579       continue;
8580     }
8581     if (auto *objc_obj = llvm::dyn_cast<clang::ObjCObjectType>(
8582             ClangUtil::GetQualType(full_type).getTypePtr())) {
8583       if (clang::ObjCInterfaceDecl *interface_decl = objc_obj->getInterface()) {
8584         interface_decl->dump(s.AsRawOstream());
8585         continue;
8586       }
8587     }
8588     GetCanonicalQualType(full_type.GetOpaqueQualType())
8589         .dump(s.AsRawOstream(), getASTContext());
8590   }
8591 }
8592 
8593 void TypeSystemClang::DumpValue(
8594     lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s,
8595     lldb::Format format, const lldb_private::DataExtractor &data,
8596     lldb::offset_t data_byte_offset, size_t data_byte_size,
8597     uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool show_types,
8598     bool show_summary, bool verbose, uint32_t depth) {
8599   if (!type)
8600     return;
8601 
8602   clang::QualType qual_type(GetQualType(type));
8603   switch (qual_type->getTypeClass()) {
8604   case clang::Type::Record:
8605     if (GetCompleteType(type)) {
8606       const clang::RecordType *record_type =
8607           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
8608       const clang::RecordDecl *record_decl = record_type->getDecl();
8609       assert(record_decl);
8610       uint32_t field_bit_offset = 0;
8611       uint32_t field_byte_offset = 0;
8612       const clang::ASTRecordLayout &record_layout =
8613           getASTContext().getASTRecordLayout(record_decl);
8614       uint32_t child_idx = 0;
8615 
8616       const clang::CXXRecordDecl *cxx_record_decl =
8617           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
8618       if (cxx_record_decl) {
8619         // We might have base classes to print out first
8620         clang::CXXRecordDecl::base_class_const_iterator base_class,
8621             base_class_end;
8622         for (base_class = cxx_record_decl->bases_begin(),
8623             base_class_end = cxx_record_decl->bases_end();
8624              base_class != base_class_end; ++base_class) {
8625           const clang::CXXRecordDecl *base_class_decl =
8626               llvm::cast<clang::CXXRecordDecl>(
8627                   base_class->getType()->getAs<clang::RecordType>()->getDecl());
8628 
8629           // Skip empty base classes
8630           if (!verbose && !TypeSystemClang::RecordHasFields(base_class_decl))
8631             continue;
8632 
8633           if (base_class->isVirtual())
8634             field_bit_offset =
8635                 record_layout.getVBaseClassOffset(base_class_decl)
8636                     .getQuantity() *
8637                 8;
8638           else
8639             field_bit_offset = record_layout.getBaseClassOffset(base_class_decl)
8640                                    .getQuantity() *
8641                                8;
8642           field_byte_offset = field_bit_offset / 8;
8643           assert(field_bit_offset % 8 == 0);
8644           if (child_idx == 0)
8645             s->PutChar('{');
8646           else
8647             s->PutChar(',');
8648 
8649           clang::QualType base_class_qual_type = base_class->getType();
8650           std::string base_class_type_name(base_class_qual_type.getAsString());
8651 
8652           // Indent and print the base class type name
8653           s->Format("\n{0}{1}", llvm::fmt_repeat(" ", depth + DEPTH_INCREMENT),
8654                     base_class_type_name);
8655 
8656           clang::TypeInfo base_class_type_info =
8657               getASTContext().getTypeInfo(base_class_qual_type);
8658 
8659           // Dump the value of the member
8660           CompilerType base_clang_type = GetType(base_class_qual_type);
8661           base_clang_type.DumpValue(
8662               exe_ctx,
8663               s, // Stream to dump to
8664               base_clang_type
8665                   .GetFormat(), // The format with which to display the member
8666               data, // Data buffer containing all bytes for this type
8667               data_byte_offset + field_byte_offset, // Offset into "data" where
8668                                                     // to grab value from
8669               base_class_type_info.Width / 8, // Size of this type in bytes
8670               0,                              // Bitfield bit size
8671               0,                              // Bitfield bit offset
8672               show_types,   // Boolean indicating if we should show the variable
8673                             // types
8674               show_summary, // Boolean indicating if we should show a summary
8675                             // for the current type
8676               verbose,      // Verbose output?
8677               depth + DEPTH_INCREMENT); // Scope depth for any types that have
8678                                         // children
8679 
8680           ++child_idx;
8681         }
8682       }
8683       uint32_t field_idx = 0;
8684       clang::RecordDecl::field_iterator field, field_end;
8685       for (field = record_decl->field_begin(),
8686           field_end = record_decl->field_end();
8687            field != field_end; ++field, ++field_idx, ++child_idx) {
8688         // Print the starting squiggly bracket (if this is the first member) or
8689         // comma (for member 2 and beyond) for the struct/union/class member.
8690         if (child_idx == 0)
8691           s->PutChar('{');
8692         else
8693           s->PutChar(',');
8694 
8695         // Indent
8696         s->Printf("\n%*s", depth + DEPTH_INCREMENT, "");
8697 
8698         clang::QualType field_type = field->getType();
8699         // Print the member type if requested
8700         // Figure out the type byte size (field_type_info.first) and alignment
8701         // (field_type_info.second) from the AST context.
8702         clang::TypeInfo field_type_info =
8703             getASTContext().getTypeInfo(field_type);
8704         assert(field_idx < record_layout.getFieldCount());
8705         // Figure out the field offset within the current struct/union/class
8706         // type
8707         field_bit_offset = record_layout.getFieldOffset(field_idx);
8708         field_byte_offset = field_bit_offset / 8;
8709         uint32_t field_bitfield_bit_size = 0;
8710         uint32_t field_bitfield_bit_offset = 0;
8711         if (FieldIsBitfield(*field, field_bitfield_bit_size))
8712           field_bitfield_bit_offset = field_bit_offset % 8;
8713 
8714         if (show_types) {
8715           std::string field_type_name(field_type.getAsString());
8716           if (field_bitfield_bit_size > 0)
8717             s->Printf("(%s:%u) ", field_type_name.c_str(),
8718                       field_bitfield_bit_size);
8719           else
8720             s->Printf("(%s) ", field_type_name.c_str());
8721         }
8722         // Print the member name and equal sign
8723         s->Printf("%s = ", field->getNameAsString().c_str());
8724 
8725         // Dump the value of the member
8726         CompilerType field_clang_type = GetType(field_type);
8727         field_clang_type.DumpValue(
8728             exe_ctx,
8729             s, // Stream to dump to
8730             field_clang_type
8731                 .GetFormat(), // The format with which to display the member
8732             data,             // Data buffer containing all bytes for this type
8733             data_byte_offset + field_byte_offset, // Offset into "data" where to
8734                                                   // grab value from
8735             field_type_info.Width / 8,            // Size of this type in bytes
8736             field_bitfield_bit_size,              // Bitfield bit size
8737             field_bitfield_bit_offset,            // Bitfield bit offset
8738             show_types,   // Boolean indicating if we should show the variable
8739                           // types
8740             show_summary, // Boolean indicating if we should show a summary for
8741                           // the current type
8742             verbose,      // Verbose output?
8743             depth + DEPTH_INCREMENT); // Scope depth for any types that have
8744                                       // children
8745       }
8746 
8747       // Indent the trailing squiggly bracket
8748       if (child_idx > 0)
8749         s->Printf("\n%*s}", depth, "");
8750     }
8751     return;
8752 
8753   case clang::Type::Enum:
8754     if (GetCompleteType(type)) {
8755       const clang::EnumType *enutype =
8756           llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8757       const clang::EnumDecl *enum_decl = enutype->getDecl();
8758       assert(enum_decl);
8759       clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
8760       lldb::offset_t offset = data_byte_offset;
8761       const int64_t enum_value = data.GetMaxU64Bitfield(
8762           &offset, data_byte_size, bitfield_bit_size, bitfield_bit_offset);
8763       for (enum_pos = enum_decl->enumerator_begin(),
8764           enum_end_pos = enum_decl->enumerator_end();
8765            enum_pos != enum_end_pos; ++enum_pos) {
8766         if (enum_pos->getInitVal() == enum_value) {
8767           s->Printf("%s", enum_pos->getNameAsString().c_str());
8768           return;
8769         }
8770       }
8771       // If we have gotten here we didn't get find the enumerator in the enum
8772       // decl, so just print the integer.
8773       s->Printf("%" PRIi64, enum_value);
8774     }
8775     return;
8776 
8777   case clang::Type::ConstantArray: {
8778     const clang::ConstantArrayType *array =
8779         llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr());
8780     bool is_array_of_characters = false;
8781     clang::QualType element_qual_type = array->getElementType();
8782 
8783     const clang::Type *canonical_type =
8784         element_qual_type->getCanonicalTypeInternal().getTypePtr();
8785     if (canonical_type)
8786       is_array_of_characters = canonical_type->isCharType();
8787 
8788     const uint64_t element_count = array->getSize().getLimitedValue();
8789 
8790     clang::TypeInfo field_type_info =
8791         getASTContext().getTypeInfo(element_qual_type);
8792 
8793     uint32_t element_idx = 0;
8794     uint32_t element_offset = 0;
8795     uint64_t element_byte_size = field_type_info.Width / 8;
8796     uint32_t element_stride = element_byte_size;
8797 
8798     if (is_array_of_characters) {
8799       s->PutChar('"');
8800       DumpDataExtractor(data, s, data_byte_offset, lldb::eFormatChar,
8801                         element_byte_size, element_count, UINT32_MAX,
8802                         LLDB_INVALID_ADDRESS, 0, 0);
8803       s->PutChar('"');
8804       return;
8805     } else {
8806       CompilerType element_clang_type = GetType(element_qual_type);
8807       lldb::Format element_format = element_clang_type.GetFormat();
8808 
8809       for (element_idx = 0; element_idx < element_count; ++element_idx) {
8810         // Print the starting squiggly bracket (if this is the first member) or
8811         // comman (for member 2 and beyong) for the struct/union/class member.
8812         if (element_idx == 0)
8813           s->PutChar('{');
8814         else
8815           s->PutChar(',');
8816 
8817         // Indent and print the index
8818         s->Printf("\n%*s[%u] ", depth + DEPTH_INCREMENT, "", element_idx);
8819 
8820         // Figure out the field offset within the current struct/union/class
8821         // type
8822         element_offset = element_idx * element_stride;
8823 
8824         // Dump the value of the member
8825         element_clang_type.DumpValue(
8826             exe_ctx,
8827             s,              // Stream to dump to
8828             element_format, // The format with which to display the element
8829             data,           // Data buffer containing all bytes for this type
8830             data_byte_offset +
8831                 element_offset, // Offset into "data" where to grab value from
8832             element_byte_size,  // Size of this type in bytes
8833             0,                  // Bitfield bit size
8834             0,                  // Bitfield bit offset
8835             show_types,   // Boolean indicating if we should show the variable
8836                           // types
8837             show_summary, // Boolean indicating if we should show a summary for
8838                           // the current type
8839             verbose,      // Verbose output?
8840             depth + DEPTH_INCREMENT); // Scope depth for any types that have
8841                                       // children
8842       }
8843 
8844       // Indent the trailing squiggly bracket
8845       if (element_idx > 0)
8846         s->Printf("\n%*s}", depth, "");
8847     }
8848   }
8849     return;
8850 
8851   case clang::Type::Typedef: {
8852     clang::QualType typedef_qual_type =
8853         llvm::cast<clang::TypedefType>(qual_type)
8854             ->getDecl()
8855             ->getUnderlyingType();
8856 
8857     CompilerType typedef_clang_type = GetType(typedef_qual_type);
8858     lldb::Format typedef_format = typedef_clang_type.GetFormat();
8859     clang::TypeInfo typedef_type_info =
8860         getASTContext().getTypeInfo(typedef_qual_type);
8861     uint64_t typedef_byte_size = typedef_type_info.Width / 8;
8862 
8863     return typedef_clang_type.DumpValue(
8864         exe_ctx,
8865         s,                   // Stream to dump to
8866         typedef_format,      // The format with which to display the element
8867         data,                // Data buffer containing all bytes for this type
8868         data_byte_offset,    // Offset into "data" where to grab value from
8869         typedef_byte_size,   // Size of this type in bytes
8870         bitfield_bit_size,   // Bitfield bit size
8871         bitfield_bit_offset, // Bitfield bit offset
8872         show_types,   // Boolean indicating if we should show the variable types
8873         show_summary, // Boolean indicating if we should show a summary for the
8874                       // current type
8875         verbose,      // Verbose output?
8876         depth);       // Scope depth for any types that have children
8877   } break;
8878 
8879   case clang::Type::Auto: {
8880     clang::QualType elaborated_qual_type =
8881         llvm::cast<clang::AutoType>(qual_type)->getDeducedType();
8882     CompilerType elaborated_clang_type = GetType(elaborated_qual_type);
8883     lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
8884     clang::TypeInfo elaborated_type_info =
8885         getASTContext().getTypeInfo(elaborated_qual_type);
8886     uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
8887 
8888     return elaborated_clang_type.DumpValue(
8889         exe_ctx,
8890         s,                    // Stream to dump to
8891         elaborated_format,    // The format with which to display the element
8892         data,                 // Data buffer containing all bytes for this type
8893         data_byte_offset,     // Offset into "data" where to grab value from
8894         elaborated_byte_size, // Size of this type in bytes
8895         bitfield_bit_size,    // Bitfield bit size
8896         bitfield_bit_offset,  // Bitfield bit offset
8897         show_types,   // Boolean indicating if we should show the variable types
8898         show_summary, // Boolean indicating if we should show a summary for the
8899                       // current type
8900         verbose,      // Verbose output?
8901         depth);       // Scope depth for any types that have children
8902   } break;
8903 
8904   case clang::Type::Elaborated: {
8905     clang::QualType elaborated_qual_type =
8906         llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
8907     CompilerType elaborated_clang_type = GetType(elaborated_qual_type);
8908     lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
8909     clang::TypeInfo elaborated_type_info =
8910         getASTContext().getTypeInfo(elaborated_qual_type);
8911     uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
8912 
8913     return elaborated_clang_type.DumpValue(
8914         exe_ctx,
8915         s,                    // Stream to dump to
8916         elaborated_format,    // The format with which to display the element
8917         data,                 // Data buffer containing all bytes for this type
8918         data_byte_offset,     // Offset into "data" where to grab value from
8919         elaborated_byte_size, // Size of this type in bytes
8920         bitfield_bit_size,    // Bitfield bit size
8921         bitfield_bit_offset,  // Bitfield bit offset
8922         show_types,   // Boolean indicating if we should show the variable types
8923         show_summary, // Boolean indicating if we should show a summary for the
8924                       // current type
8925         verbose,      // Verbose output?
8926         depth);       // Scope depth for any types that have children
8927   } break;
8928 
8929   case clang::Type::Paren: {
8930     clang::QualType desugar_qual_type =
8931         llvm::cast<clang::ParenType>(qual_type)->desugar();
8932     CompilerType desugar_clang_type = GetType(desugar_qual_type);
8933 
8934     lldb::Format desugar_format = desugar_clang_type.GetFormat();
8935     clang::TypeInfo desugar_type_info =
8936         getASTContext().getTypeInfo(desugar_qual_type);
8937     uint64_t desugar_byte_size = desugar_type_info.Width / 8;
8938 
8939     return desugar_clang_type.DumpValue(
8940         exe_ctx,
8941         s,                   // Stream to dump to
8942         desugar_format,      // The format with which to display the element
8943         data,                // Data buffer containing all bytes for this type
8944         data_byte_offset,    // Offset into "data" where to grab value from
8945         desugar_byte_size,   // Size of this type in bytes
8946         bitfield_bit_size,   // Bitfield bit size
8947         bitfield_bit_offset, // Bitfield bit offset
8948         show_types,   // Boolean indicating if we should show the variable types
8949         show_summary, // Boolean indicating if we should show a summary for the
8950                       // current type
8951         verbose,      // Verbose output?
8952         depth);       // Scope depth for any types that have children
8953   } break;
8954 
8955   default:
8956     // We are down to a scalar type that we just need to display.
8957     DumpDataExtractor(data, s, data_byte_offset, format, data_byte_size, 1,
8958                       UINT32_MAX, LLDB_INVALID_ADDRESS, bitfield_bit_size,
8959                       bitfield_bit_offset);
8960 
8961     if (show_summary)
8962       DumpSummary(type, exe_ctx, s, data, data_byte_offset, data_byte_size);
8963     break;
8964   }
8965 }
8966 
8967 static bool DumpEnumValue(const clang::QualType &qual_type, Stream *s,
8968                           const DataExtractor &data, lldb::offset_t byte_offset,
8969                           size_t byte_size, uint32_t bitfield_bit_offset,
8970                           uint32_t bitfield_bit_size) {
8971   const clang::EnumType *enutype =
8972       llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8973   const clang::EnumDecl *enum_decl = enutype->getDecl();
8974   assert(enum_decl);
8975   lldb::offset_t offset = byte_offset;
8976   const uint64_t enum_svalue = data.GetMaxS64Bitfield(
8977       &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
8978   bool can_be_bitfield = true;
8979   uint64_t covered_bits = 0;
8980   int num_enumerators = 0;
8981 
8982   // Try to find an exact match for the value.
8983   // At the same time, we're applying a heuristic to determine whether we want
8984   // to print this enum as a bitfield. We're likely dealing with a bitfield if
8985   // every enumerator is either a one bit value or a superset of the previous
8986   // enumerators. Also 0 doesn't make sense when the enumerators are used as
8987   // flags.
8988   for (auto *enumerator : enum_decl->enumerators()) {
8989     uint64_t val = enumerator->getInitVal().getSExtValue();
8990     val = llvm::SignExtend64(val, 8*byte_size);
8991     if (llvm::popcount(val) != 1 && (val & ~covered_bits) != 0)
8992       can_be_bitfield = false;
8993     covered_bits |= val;
8994     ++num_enumerators;
8995     if (val == enum_svalue) {
8996       // Found an exact match, that's all we need to do.
8997       s->PutCString(enumerator->getNameAsString());
8998       return true;
8999     }
9000   }
9001 
9002   // Unsigned values make more sense for flags.
9003   offset = byte_offset;
9004   const uint64_t enum_uvalue = data.GetMaxU64Bitfield(
9005       &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
9006 
9007   // No exact match, but we don't think this is a bitfield. Print the value as
9008   // decimal.
9009   if (!can_be_bitfield) {
9010     if (qual_type->isSignedIntegerOrEnumerationType())
9011       s->Printf("%" PRIi64, enum_svalue);
9012     else
9013       s->Printf("%" PRIu64, enum_uvalue);
9014     return true;
9015   }
9016 
9017   uint64_t remaining_value = enum_uvalue;
9018   std::vector<std::pair<uint64_t, llvm::StringRef>> values;
9019   values.reserve(num_enumerators);
9020   for (auto *enumerator : enum_decl->enumerators())
9021     if (auto val = enumerator->getInitVal().getZExtValue())
9022       values.emplace_back(val, enumerator->getName());
9023 
9024   // Sort in reverse order of the number of the population count,  so that in
9025   // `enum {A, B, ALL = A|B }` we visit ALL first. Use a stable sort so that
9026   // A | C where A is declared before C is displayed in this order.
9027   std::stable_sort(values.begin(), values.end(),
9028                    [](const auto &a, const auto &b) {
9029                      return llvm::popcount(a.first) > llvm::popcount(b.first);
9030                    });
9031 
9032   for (const auto &val : values) {
9033     if ((remaining_value & val.first) != val.first)
9034       continue;
9035     remaining_value &= ~val.first;
9036     s->PutCString(val.second);
9037     if (remaining_value)
9038       s->PutCString(" | ");
9039   }
9040 
9041   // If there is a remainder that is not covered by the value, print it as hex.
9042   if (remaining_value)
9043     s->Printf("0x%" PRIx64, remaining_value);
9044 
9045   return true;
9046 }
9047 
9048 bool TypeSystemClang::DumpTypeValue(
9049     lldb::opaque_compiler_type_t type, Stream *s, lldb::Format format,
9050     const lldb_private::DataExtractor &data, lldb::offset_t byte_offset,
9051     size_t byte_size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
9052     ExecutionContextScope *exe_scope) {
9053   if (!type)
9054     return false;
9055   if (IsAggregateType(type)) {
9056     return false;
9057   } else {
9058     clang::QualType qual_type(GetQualType(type));
9059 
9060     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9061 
9062     if (type_class == clang::Type::Elaborated) {
9063       qual_type = llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
9064       return DumpTypeValue(qual_type.getAsOpaquePtr(), s, format, data, byte_offset, byte_size,
9065                            bitfield_bit_size, bitfield_bit_offset, exe_scope);
9066     }
9067 
9068     switch (type_class) {
9069     case clang::Type::Typedef: {
9070       clang::QualType typedef_qual_type =
9071           llvm::cast<clang::TypedefType>(qual_type)
9072               ->getDecl()
9073               ->getUnderlyingType();
9074       CompilerType typedef_clang_type = GetType(typedef_qual_type);
9075       if (format == eFormatDefault)
9076         format = typedef_clang_type.GetFormat();
9077       clang::TypeInfo typedef_type_info =
9078           getASTContext().getTypeInfo(typedef_qual_type);
9079       uint64_t typedef_byte_size = typedef_type_info.Width / 8;
9080 
9081       return typedef_clang_type.DumpTypeValue(
9082           s,
9083           format,            // The format with which to display the element
9084           data,              // Data buffer containing all bytes for this type
9085           byte_offset,       // Offset into "data" where to grab value from
9086           typedef_byte_size, // Size of this type in bytes
9087           bitfield_bit_size, // Size in bits of a bitfield value, if zero don't
9088                              // treat as a bitfield
9089           bitfield_bit_offset, // Offset in bits of a bitfield value if
9090                                // bitfield_bit_size != 0
9091           exe_scope);
9092     } break;
9093 
9094     case clang::Type::Enum:
9095       // If our format is enum or default, show the enumeration value as its
9096       // enumeration string value, else just display it as requested.
9097       if ((format == eFormatEnum || format == eFormatDefault) &&
9098           GetCompleteType(type))
9099         return DumpEnumValue(qual_type, s, data, byte_offset, byte_size,
9100                              bitfield_bit_offset, bitfield_bit_size);
9101       // format was not enum, just fall through and dump the value as
9102       // requested....
9103       [[fallthrough]];
9104 
9105     default:
9106       // We are down to a scalar type that we just need to display.
9107       {
9108         uint32_t item_count = 1;
9109         // A few formats, we might need to modify our size and count for
9110         // depending
9111         // on how we are trying to display the value...
9112         switch (format) {
9113         default:
9114         case eFormatBoolean:
9115         case eFormatBinary:
9116         case eFormatComplex:
9117         case eFormatCString: // NULL terminated C strings
9118         case eFormatDecimal:
9119         case eFormatEnum:
9120         case eFormatHex:
9121         case eFormatHexUppercase:
9122         case eFormatFloat:
9123         case eFormatOctal:
9124         case eFormatOSType:
9125         case eFormatUnsigned:
9126         case eFormatPointer:
9127         case eFormatVectorOfChar:
9128         case eFormatVectorOfSInt8:
9129         case eFormatVectorOfUInt8:
9130         case eFormatVectorOfSInt16:
9131         case eFormatVectorOfUInt16:
9132         case eFormatVectorOfSInt32:
9133         case eFormatVectorOfUInt32:
9134         case eFormatVectorOfSInt64:
9135         case eFormatVectorOfUInt64:
9136         case eFormatVectorOfFloat32:
9137         case eFormatVectorOfFloat64:
9138         case eFormatVectorOfUInt128:
9139           break;
9140 
9141         case eFormatChar:
9142         case eFormatCharPrintable:
9143         case eFormatCharArray:
9144         case eFormatBytes:
9145         case eFormatUnicode8:
9146         case eFormatBytesWithASCII:
9147           item_count = byte_size;
9148           byte_size = 1;
9149           break;
9150 
9151         case eFormatUnicode16:
9152           item_count = byte_size / 2;
9153           byte_size = 2;
9154           break;
9155 
9156         case eFormatUnicode32:
9157           item_count = byte_size / 4;
9158           byte_size = 4;
9159           break;
9160         }
9161         return DumpDataExtractor(data, s, byte_offset, format, byte_size,
9162                                  item_count, UINT32_MAX, LLDB_INVALID_ADDRESS,
9163                                  bitfield_bit_size, bitfield_bit_offset,
9164                                  exe_scope);
9165       }
9166       break;
9167     }
9168   }
9169   return false;
9170 }
9171 
9172 void TypeSystemClang::DumpSummary(lldb::opaque_compiler_type_t type,
9173                                   ExecutionContext *exe_ctx, Stream *s,
9174                                   const lldb_private::DataExtractor &data,
9175                                   lldb::offset_t data_byte_offset,
9176                                   size_t data_byte_size) {
9177   uint32_t length = 0;
9178   if (IsCStringType(type, length)) {
9179     if (exe_ctx) {
9180       Process *process = exe_ctx->GetProcessPtr();
9181       if (process) {
9182         lldb::offset_t offset = data_byte_offset;
9183         lldb::addr_t pointer_address = data.GetMaxU64(&offset, data_byte_size);
9184         std::vector<uint8_t> buf;
9185         if (length > 0)
9186           buf.resize(length);
9187         else
9188           buf.resize(256);
9189 
9190         DataExtractor cstr_data(&buf.front(), buf.size(),
9191                                 process->GetByteOrder(), 4);
9192         buf.back() = '\0';
9193         size_t bytes_read;
9194         size_t total_cstr_len = 0;
9195         Status error;
9196         while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(),
9197                                                  buf.size(), error)) > 0) {
9198           const size_t len = strlen((const char *)&buf.front());
9199           if (len == 0)
9200             break;
9201           if (total_cstr_len == 0)
9202             s->PutCString(" \"");
9203           DumpDataExtractor(cstr_data, s, 0, lldb::eFormatChar, 1, len,
9204                             UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0);
9205           total_cstr_len += len;
9206           if (len < buf.size())
9207             break;
9208           pointer_address += total_cstr_len;
9209         }
9210         if (total_cstr_len > 0)
9211           s->PutChar('"');
9212       }
9213     }
9214   }
9215 }
9216 
9217 void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
9218                                           lldb::DescriptionLevel level) {
9219   StreamFile s(stdout, false);
9220   DumpTypeDescription(type, &s, level);
9221 
9222   CompilerType ct(weak_from_this(), type);
9223   const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr();
9224   ClangASTMetadata *metadata = GetMetadata(clang_type);
9225   if (metadata) {
9226     metadata->Dump(&s);
9227   }
9228 }
9229 
9230 void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
9231                                           Stream *s,
9232                                           lldb::DescriptionLevel level) {
9233   if (type) {
9234     clang::QualType qual_type =
9235         RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
9236 
9237     llvm::SmallVector<char, 1024> buf;
9238     llvm::raw_svector_ostream llvm_ostrm(buf);
9239 
9240     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9241     switch (type_class) {
9242     case clang::Type::ObjCObject:
9243     case clang::Type::ObjCInterface: {
9244       GetCompleteType(type);
9245 
9246       auto *objc_class_type =
9247           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
9248       assert(objc_class_type);
9249       if (!objc_class_type)
9250         break;
9251       clang::ObjCInterfaceDecl *class_interface_decl =
9252             objc_class_type->getInterface();
9253       if (!class_interface_decl)
9254         break;
9255       if (level == eDescriptionLevelVerbose)
9256         class_interface_decl->dump(llvm_ostrm);
9257       else
9258         class_interface_decl->print(llvm_ostrm,
9259                                     getASTContext().getPrintingPolicy(),
9260                                     s->GetIndentLevel());
9261     } break;
9262 
9263     case clang::Type::Typedef: {
9264       auto *typedef_type = qual_type->getAs<clang::TypedefType>();
9265       if (!typedef_type)
9266         break;
9267       const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
9268       if (level == eDescriptionLevelVerbose)
9269         typedef_decl->dump(llvm_ostrm);
9270       else {
9271         std::string clang_typedef_name(GetTypeNameForDecl(typedef_decl));
9272         if (!clang_typedef_name.empty()) {
9273           s->PutCString("typedef ");
9274           s->PutCString(clang_typedef_name);
9275         }
9276       }
9277     } break;
9278 
9279     case clang::Type::Record: {
9280       GetCompleteType(type);
9281 
9282       auto *record_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr());
9283       const clang::RecordDecl *record_decl = record_type->getDecl();
9284       if (level == eDescriptionLevelVerbose)
9285         record_decl->dump(llvm_ostrm);
9286       else {
9287         record_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(),
9288                            s->GetIndentLevel());
9289       }
9290     } break;
9291 
9292     default: {
9293       if (auto *tag_type =
9294               llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr())) {
9295         if (clang::TagDecl *tag_decl = tag_type->getDecl()) {
9296           if (level == eDescriptionLevelVerbose)
9297             tag_decl->dump(llvm_ostrm);
9298           else
9299             tag_decl->print(llvm_ostrm, 0);
9300         }
9301       } else {
9302         if (level == eDescriptionLevelVerbose)
9303           qual_type->dump(llvm_ostrm, getASTContext());
9304         else {
9305           std::string clang_type_name(qual_type.getAsString());
9306           if (!clang_type_name.empty())
9307             s->PutCString(clang_type_name);
9308         }
9309       }
9310     }
9311     }
9312 
9313     if (buf.size() > 0) {
9314       s->Write(buf.data(), buf.size());
9315     }
9316 }
9317 }
9318 
9319 void TypeSystemClang::DumpTypeName(const CompilerType &type) {
9320   if (ClangUtil::IsClangType(type)) {
9321     clang::QualType qual_type(
9322         ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
9323 
9324     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9325     switch (type_class) {
9326     case clang::Type::Record: {
9327       const clang::CXXRecordDecl *cxx_record_decl =
9328           qual_type->getAsCXXRecordDecl();
9329       if (cxx_record_decl)
9330         printf("class %s", cxx_record_decl->getName().str().c_str());
9331     } break;
9332 
9333     case clang::Type::Enum: {
9334       clang::EnumDecl *enum_decl =
9335           llvm::cast<clang::EnumType>(qual_type)->getDecl();
9336       if (enum_decl) {
9337         printf("enum %s", enum_decl->getName().str().c_str());
9338       }
9339     } break;
9340 
9341     case clang::Type::ObjCObject:
9342     case clang::Type::ObjCInterface: {
9343       const clang::ObjCObjectType *objc_class_type =
9344           llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
9345       if (objc_class_type) {
9346         clang::ObjCInterfaceDecl *class_interface_decl =
9347             objc_class_type->getInterface();
9348         // We currently can't complete objective C types through the newly
9349         // added ASTContext because it only supports TagDecl objects right
9350         // now...
9351         if (class_interface_decl)
9352           printf("@class %s", class_interface_decl->getName().str().c_str());
9353       }
9354     } break;
9355 
9356     case clang::Type::Typedef:
9357       printf("typedef %s", llvm::cast<clang::TypedefType>(qual_type)
9358                                ->getDecl()
9359                                ->getName()
9360                                .str()
9361                                .c_str());
9362       break;
9363 
9364     case clang::Type::Auto:
9365       printf("auto ");
9366       return DumpTypeName(CompilerType(type.GetTypeSystem(),
9367                                        llvm::cast<clang::AutoType>(qual_type)
9368                                            ->getDeducedType()
9369                                            .getAsOpaquePtr()));
9370 
9371     case clang::Type::Elaborated:
9372       printf("elaborated ");
9373       return DumpTypeName(CompilerType(
9374           type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
9375                                     ->getNamedType()
9376                                     .getAsOpaquePtr()));
9377 
9378     case clang::Type::Paren:
9379       printf("paren ");
9380       return DumpTypeName(CompilerType(
9381           type.GetTypeSystem(),
9382           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
9383 
9384     default:
9385       printf("TypeSystemClang::DumpTypeName() type_class = %u", type_class);
9386       break;
9387     }
9388   }
9389 }
9390 
9391 clang::ClassTemplateDecl *TypeSystemClang::ParseClassTemplateDecl(
9392     clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
9393     lldb::AccessType access_type, const char *parent_name, int tag_decl_kind,
9394     const TypeSystemClang::TemplateParameterInfos &template_param_infos) {
9395   if (template_param_infos.IsValid()) {
9396     std::string template_basename(parent_name);
9397     // With -gsimple-template-names we may omit template parameters in the name.
9398     if (auto i = template_basename.find('<'); i != std::string::npos)
9399       template_basename.erase(i);
9400 
9401     return CreateClassTemplateDecl(decl_ctx, owning_module, access_type,
9402                                    template_basename.c_str(), tag_decl_kind,
9403                                    template_param_infos);
9404   }
9405   return nullptr;
9406 }
9407 
9408 void TypeSystemClang::CompleteTagDecl(clang::TagDecl *decl) {
9409   SymbolFile *sym_file = GetSymbolFile();
9410   if (sym_file) {
9411     CompilerType clang_type = GetTypeForDecl(decl);
9412     if (clang_type)
9413       sym_file->CompleteType(clang_type);
9414   }
9415 }
9416 
9417 void TypeSystemClang::CompleteObjCInterfaceDecl(
9418     clang::ObjCInterfaceDecl *decl) {
9419   SymbolFile *sym_file = GetSymbolFile();
9420   if (sym_file) {
9421     CompilerType clang_type = GetTypeForDecl(decl);
9422     if (clang_type)
9423       sym_file->CompleteType(clang_type);
9424   }
9425 }
9426 
9427 DWARFASTParser *TypeSystemClang::GetDWARFParser() {
9428   if (!m_dwarf_ast_parser_up)
9429     m_dwarf_ast_parser_up = std::make_unique<DWARFASTParserClang>(*this);
9430   return m_dwarf_ast_parser_up.get();
9431 }
9432 
9433 #ifdef LLDB_ENABLE_ALL
9434 PDBASTParser *TypeSystemClang::GetPDBParser() {
9435   if (!m_pdb_ast_parser_up)
9436     m_pdb_ast_parser_up = std::make_unique<PDBASTParser>(*this);
9437   return m_pdb_ast_parser_up.get();
9438 }
9439 
9440 npdb::PdbAstBuilder *TypeSystemClang::GetNativePDBParser() {
9441   if (!m_native_pdb_ast_parser_up)
9442     m_native_pdb_ast_parser_up = std::make_unique<npdb::PdbAstBuilder>(*this);
9443   return m_native_pdb_ast_parser_up.get();
9444 }
9445 #endif // LLDB_ENABLE_ALL
9446 
9447 bool TypeSystemClang::LayoutRecordType(
9448     const clang::RecordDecl *record_decl, uint64_t &bit_size,
9449     uint64_t &alignment,
9450     llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
9451     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9452         &base_offsets,
9453     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9454         &vbase_offsets) {
9455   lldb_private::ClangASTImporter *importer = nullptr;
9456   if (m_dwarf_ast_parser_up)
9457     importer = &m_dwarf_ast_parser_up->GetClangASTImporter();
9458 #ifdef LLDB_ENABLE_ALL
9459   if (!importer && m_pdb_ast_parser_up)
9460     importer = &m_pdb_ast_parser_up->GetClangASTImporter();
9461   if (!importer && m_native_pdb_ast_parser_up)
9462     importer = &m_native_pdb_ast_parser_up->GetClangASTImporter();
9463 #endif // LLDB_ENABLE_ALL
9464   if (!importer)
9465     return false;
9466 
9467   return importer->LayoutRecordType(record_decl, bit_size, alignment,
9468                                     field_offsets, base_offsets, vbase_offsets);
9469 }
9470 
9471 // CompilerDecl override functions
9472 
9473 ConstString TypeSystemClang::DeclGetName(void *opaque_decl) {
9474   if (opaque_decl) {
9475     clang::NamedDecl *nd =
9476         llvm::dyn_cast<NamedDecl>((clang::Decl *)opaque_decl);
9477     if (nd != nullptr)
9478       return ConstString(nd->getDeclName().getAsString());
9479   }
9480   return ConstString();
9481 }
9482 
9483 ConstString TypeSystemClang::DeclGetMangledName(void *opaque_decl) {
9484   if (opaque_decl) {
9485     clang::NamedDecl *nd =
9486         llvm::dyn_cast<clang::NamedDecl>((clang::Decl *)opaque_decl);
9487     if (nd != nullptr && !llvm::isa<clang::ObjCMethodDecl>(nd)) {
9488       clang::MangleContext *mc = getMangleContext();
9489       if (mc && mc->shouldMangleCXXName(nd)) {
9490         llvm::SmallVector<char, 1024> buf;
9491         llvm::raw_svector_ostream llvm_ostrm(buf);
9492         if (llvm::isa<clang::CXXConstructorDecl>(nd)) {
9493           mc->mangleName(
9494               clang::GlobalDecl(llvm::dyn_cast<clang::CXXConstructorDecl>(nd),
9495                                 Ctor_Complete),
9496               llvm_ostrm);
9497         } else if (llvm::isa<clang::CXXDestructorDecl>(nd)) {
9498           mc->mangleName(
9499               clang::GlobalDecl(llvm::dyn_cast<clang::CXXDestructorDecl>(nd),
9500                                 Dtor_Complete),
9501               llvm_ostrm);
9502         } else {
9503           mc->mangleName(nd, llvm_ostrm);
9504         }
9505         if (buf.size() > 0)
9506           return ConstString(buf.data(), buf.size());
9507       }
9508     }
9509   }
9510   return ConstString();
9511 }
9512 
9513 CompilerDeclContext TypeSystemClang::DeclGetDeclContext(void *opaque_decl) {
9514   if (opaque_decl)
9515     return CreateDeclContext(((clang::Decl *)opaque_decl)->getDeclContext());
9516   return CompilerDeclContext();
9517 }
9518 
9519 CompilerType TypeSystemClang::DeclGetFunctionReturnType(void *opaque_decl) {
9520   if (clang::FunctionDecl *func_decl =
9521           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9522     return GetType(func_decl->getReturnType());
9523   if (clang::ObjCMethodDecl *objc_method =
9524           llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9525     return GetType(objc_method->getReturnType());
9526   else
9527     return CompilerType();
9528 }
9529 
9530 size_t TypeSystemClang::DeclGetFunctionNumArguments(void *opaque_decl) {
9531   if (clang::FunctionDecl *func_decl =
9532           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9533     return func_decl->param_size();
9534   if (clang::ObjCMethodDecl *objc_method =
9535           llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9536     return objc_method->param_size();
9537   else
9538     return 0;
9539 }
9540 
9541 CompilerType TypeSystemClang::DeclGetFunctionArgumentType(void *opaque_decl,
9542                                                           size_t idx) {
9543   if (clang::FunctionDecl *func_decl =
9544           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) {
9545     if (idx < func_decl->param_size()) {
9546       ParmVarDecl *var_decl = func_decl->getParamDecl(idx);
9547       if (var_decl)
9548         return GetType(var_decl->getOriginalType());
9549     }
9550   } else if (clang::ObjCMethodDecl *objc_method =
9551                  llvm::dyn_cast<clang::ObjCMethodDecl>(
9552                      (clang::Decl *)opaque_decl)) {
9553     if (idx < objc_method->param_size())
9554       return GetType(objc_method->parameters()[idx]->getOriginalType());
9555   }
9556   return CompilerType();
9557 }
9558 
9559 // CompilerDeclContext functions
9560 
9561 std::vector<CompilerDecl> TypeSystemClang::DeclContextFindDeclByName(
9562     void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) {
9563   std::vector<CompilerDecl> found_decls;
9564   SymbolFile *symbol_file = GetSymbolFile();
9565   if (opaque_decl_ctx && symbol_file) {
9566     DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx;
9567     std::set<DeclContext *> searched;
9568     std::multimap<DeclContext *, DeclContext *> search_queue;
9569 
9570     for (clang::DeclContext *decl_context = root_decl_ctx;
9571          decl_context != nullptr && found_decls.empty();
9572          decl_context = decl_context->getParent()) {
9573       search_queue.insert(std::make_pair(decl_context, decl_context));
9574 
9575       for (auto it = search_queue.find(decl_context); it != search_queue.end();
9576            it++) {
9577         if (!searched.insert(it->second).second)
9578           continue;
9579         symbol_file->ParseDeclsForContext(
9580             CreateDeclContext(it->second));
9581 
9582         for (clang::Decl *child : it->second->decls()) {
9583           if (clang::UsingDirectiveDecl *ud =
9584                   llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9585             if (ignore_using_decls)
9586               continue;
9587             clang::DeclContext *from = ud->getCommonAncestor();
9588             if (searched.find(ud->getNominatedNamespace()) == searched.end())
9589               search_queue.insert(
9590                   std::make_pair(from, ud->getNominatedNamespace()));
9591           } else if (clang::UsingDecl *ud =
9592                          llvm::dyn_cast<clang::UsingDecl>(child)) {
9593             if (ignore_using_decls)
9594               continue;
9595             for (clang::UsingShadowDecl *usd : ud->shadows()) {
9596               clang::Decl *target = usd->getTargetDecl();
9597               if (clang::NamedDecl *nd =
9598                       llvm::dyn_cast<clang::NamedDecl>(target)) {
9599                 IdentifierInfo *ii = nd->getIdentifier();
9600                 if (ii != nullptr &&
9601                     ii->getName().equals(name.AsCString(nullptr)))
9602                   found_decls.push_back(GetCompilerDecl(nd));
9603               }
9604             }
9605           } else if (clang::NamedDecl *nd =
9606                          llvm::dyn_cast<clang::NamedDecl>(child)) {
9607             IdentifierInfo *ii = nd->getIdentifier();
9608             if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr)))
9609               found_decls.push_back(GetCompilerDecl(nd));
9610           }
9611         }
9612       }
9613     }
9614   }
9615   return found_decls;
9616 }
9617 
9618 // Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents,
9619 // and return the number of levels it took to find it, or
9620 // LLDB_INVALID_DECL_LEVEL if not found.  If the decl was imported via a using
9621 // declaration, its name and/or type, if set, will be used to check that the
9622 // decl found in the scope is a match.
9623 //
9624 // The optional name is required by languages (like C++) to handle using
9625 // declarations like:
9626 //
9627 //     void poo();
9628 //     namespace ns {
9629 //         void foo();
9630 //         void goo();
9631 //     }
9632 //     void bar() {
9633 //         using ns::foo;
9634 //         // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and
9635 //         // LLDB_INVALID_DECL_LEVEL for 'goo'.
9636 //     }
9637 //
9638 // The optional type is useful in the case that there's a specific overload
9639 // that we're looking for that might otherwise be shadowed, like:
9640 //
9641 //     void foo(int);
9642 //     namespace ns {
9643 //         void foo();
9644 //     }
9645 //     void bar() {
9646 //         using ns::foo;
9647 //         // CountDeclLevels returns 0 for { 'foo', void() },
9648 //         // 1 for { 'foo', void(int) }, and
9649 //         // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }.
9650 //     }
9651 //
9652 // NOTE: Because file statics are at the TranslationUnit along with globals, a
9653 // function at file scope will return the same level as a function at global
9654 // scope. Ideally we'd like to treat the file scope as an additional scope just
9655 // below the global scope.  More work needs to be done to recognise that, if
9656 // the decl we're trying to look up is static, we should compare its source
9657 // file with that of the current scope and return a lower number for it.
9658 uint32_t TypeSystemClang::CountDeclLevels(clang::DeclContext *frame_decl_ctx,
9659                                           clang::DeclContext *child_decl_ctx,
9660                                           ConstString *child_name,
9661                                           CompilerType *child_type) {
9662   SymbolFile *symbol_file = GetSymbolFile();
9663   if (frame_decl_ctx && symbol_file) {
9664     std::set<DeclContext *> searched;
9665     std::multimap<DeclContext *, DeclContext *> search_queue;
9666 
9667     // Get the lookup scope for the decl we're trying to find.
9668     clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent();
9669 
9670     // Look for it in our scope's decl context and its parents.
9671     uint32_t level = 0;
9672     for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr;
9673          decl_ctx = decl_ctx->getParent()) {
9674       if (!decl_ctx->isLookupContext())
9675         continue;
9676       if (decl_ctx == parent_decl_ctx)
9677         // Found it!
9678         return level;
9679       search_queue.insert(std::make_pair(decl_ctx, decl_ctx));
9680       for (auto it = search_queue.find(decl_ctx); it != search_queue.end();
9681            it++) {
9682         if (searched.find(it->second) != searched.end())
9683           continue;
9684 
9685         // Currently DWARF has one shared translation unit for all Decls at top
9686         // level, so this would erroneously find using statements anywhere.  So
9687         // don't look at the top-level translation unit.
9688         // TODO fix this and add a testcase that depends on it.
9689 
9690         if (llvm::isa<clang::TranslationUnitDecl>(it->second))
9691           continue;
9692 
9693         searched.insert(it->second);
9694         symbol_file->ParseDeclsForContext(
9695             CreateDeclContext(it->second));
9696 
9697         for (clang::Decl *child : it->second->decls()) {
9698           if (clang::UsingDirectiveDecl *ud =
9699                   llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9700             clang::DeclContext *ns = ud->getNominatedNamespace();
9701             if (ns == parent_decl_ctx)
9702               // Found it!
9703               return level;
9704             clang::DeclContext *from = ud->getCommonAncestor();
9705             if (searched.find(ns) == searched.end())
9706               search_queue.insert(std::make_pair(from, ns));
9707           } else if (child_name) {
9708             if (clang::UsingDecl *ud =
9709                     llvm::dyn_cast<clang::UsingDecl>(child)) {
9710               for (clang::UsingShadowDecl *usd : ud->shadows()) {
9711                 clang::Decl *target = usd->getTargetDecl();
9712                 clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(target);
9713                 if (!nd)
9714                   continue;
9715                 // Check names.
9716                 IdentifierInfo *ii = nd->getIdentifier();
9717                 if (ii == nullptr ||
9718                     !ii->getName().equals(child_name->AsCString(nullptr)))
9719                   continue;
9720                 // Check types, if one was provided.
9721                 if (child_type) {
9722                   CompilerType clang_type = GetTypeForDecl(nd);
9723                   if (!AreTypesSame(clang_type, *child_type,
9724                                     /*ignore_qualifiers=*/true))
9725                     continue;
9726                 }
9727                 // Found it!
9728                 return level;
9729               }
9730             }
9731           }
9732         }
9733       }
9734       ++level;
9735     }
9736   }
9737   return LLDB_INVALID_DECL_LEVEL;
9738 }
9739 
9740 ConstString TypeSystemClang::DeclContextGetName(void *opaque_decl_ctx) {
9741   if (opaque_decl_ctx) {
9742     clang::NamedDecl *named_decl =
9743         llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9744     if (named_decl)
9745       return ConstString(named_decl->getName());
9746   }
9747   return ConstString();
9748 }
9749 
9750 ConstString
9751 TypeSystemClang::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) {
9752   if (opaque_decl_ctx) {
9753     clang::NamedDecl *named_decl =
9754         llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9755     if (named_decl)
9756       return ConstString(GetTypeNameForDecl(named_decl));
9757   }
9758   return ConstString();
9759 }
9760 
9761 bool TypeSystemClang::DeclContextIsClassMethod(
9762     void *opaque_decl_ctx, lldb::LanguageType *language_ptr,
9763     bool *is_instance_method_ptr, ConstString *language_object_name_ptr) {
9764   if (opaque_decl_ctx) {
9765     clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9766     if (ObjCMethodDecl *objc_method =
9767             llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx)) {
9768       if (is_instance_method_ptr)
9769         *is_instance_method_ptr = objc_method->isInstanceMethod();
9770       if (language_ptr)
9771         *language_ptr = eLanguageTypeObjC;
9772       if (language_object_name_ptr)
9773         language_object_name_ptr->SetCString("self");
9774       return true;
9775     } else if (CXXMethodDecl *cxx_method =
9776                    llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx)) {
9777       if (is_instance_method_ptr)
9778         *is_instance_method_ptr = cxx_method->isInstance();
9779       if (language_ptr)
9780         *language_ptr = eLanguageTypeC_plus_plus;
9781       if (language_object_name_ptr)
9782         language_object_name_ptr->SetCString("this");
9783       return true;
9784     } else if (clang::FunctionDecl *function_decl =
9785                    llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
9786       ClangASTMetadata *metadata = GetMetadata(function_decl);
9787       if (metadata && metadata->HasObjectPtr()) {
9788         if (is_instance_method_ptr)
9789           *is_instance_method_ptr = true;
9790         if (language_ptr)
9791           *language_ptr = eLanguageTypeObjC;
9792         if (language_object_name_ptr)
9793           language_object_name_ptr->SetCString(metadata->GetObjectPtrName());
9794         return true;
9795       }
9796     }
9797   }
9798   return false;
9799 }
9800 
9801 bool TypeSystemClang::DeclContextIsContainedInLookup(
9802     void *opaque_decl_ctx, void *other_opaque_decl_ctx) {
9803   auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9804   auto *other = (clang::DeclContext *)other_opaque_decl_ctx;
9805 
9806   do {
9807     // A decl context always includes its own contents in its lookup.
9808     if (decl_ctx == other)
9809       return true;
9810 
9811     // If we have an inline namespace, then the lookup of the parent context
9812     // also includes the inline namespace contents.
9813   } while (other->isInlineNamespace() && (other = other->getParent()));
9814 
9815   return false;
9816 }
9817 
9818 static bool IsClangDeclContext(const CompilerDeclContext &dc) {
9819   return dc.IsValid() && isa<TypeSystemClang>(dc.GetTypeSystem());
9820 }
9821 
9822 clang::DeclContext *
9823 TypeSystemClang::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) {
9824   if (IsClangDeclContext(dc))
9825     return (clang::DeclContext *)dc.GetOpaqueDeclContext();
9826   return nullptr;
9827 }
9828 
9829 ObjCMethodDecl *
9830 TypeSystemClang::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) {
9831   if (IsClangDeclContext(dc))
9832     return llvm::dyn_cast<clang::ObjCMethodDecl>(
9833         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9834   return nullptr;
9835 }
9836 
9837 CXXMethodDecl *
9838 TypeSystemClang::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) {
9839   if (IsClangDeclContext(dc))
9840     return llvm::dyn_cast<clang::CXXMethodDecl>(
9841         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9842   return nullptr;
9843 }
9844 
9845 clang::FunctionDecl *
9846 TypeSystemClang::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) {
9847   if (IsClangDeclContext(dc))
9848     return llvm::dyn_cast<clang::FunctionDecl>(
9849         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9850   return nullptr;
9851 }
9852 
9853 clang::NamespaceDecl *
9854 TypeSystemClang::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) {
9855   if (IsClangDeclContext(dc))
9856     return llvm::dyn_cast<clang::NamespaceDecl>(
9857         (clang::DeclContext *)dc.GetOpaqueDeclContext());
9858   return nullptr;
9859 }
9860 
9861 ClangASTMetadata *
9862 TypeSystemClang::DeclContextGetMetaData(const CompilerDeclContext &dc,
9863                                         const Decl *object) {
9864   TypeSystemClang *ast = llvm::cast<TypeSystemClang>(dc.GetTypeSystem());
9865   return ast->GetMetadata(object);
9866 }
9867 
9868 clang::ASTContext *
9869 TypeSystemClang::DeclContextGetTypeSystemClang(const CompilerDeclContext &dc) {
9870   TypeSystemClang *ast =
9871       llvm::dyn_cast_or_null<TypeSystemClang>(dc.GetTypeSystem());
9872   if (ast)
9873     return &ast->getASTContext();
9874   return nullptr;
9875 }
9876 
9877 void TypeSystemClang::RequireCompleteType(CompilerType type) {
9878   // Technically, enums can be incomplete too, but we don't handle those as they
9879   // are emitted even under -flimit-debug-info.
9880   if (!TypeSystemClang::IsCXXClassType(type))
9881     return;
9882 
9883   if (type.GetCompleteType())
9884     return;
9885 
9886   // No complete definition in this module.  Mark the class as complete to
9887   // satisfy local ast invariants, but make a note of the fact that
9888   // it is not _really_ complete so we can later search for a definition in a
9889   // different module.
9890   // Since we provide layout assistance, layouts of types containing this class
9891   // will be correct even if we  are not able to find the definition elsewhere.
9892   bool started = TypeSystemClang::StartTagDeclarationDefinition(type);
9893   lldbassert(started && "Unable to start a class type definition.");
9894   TypeSystemClang::CompleteTagDeclarationDefinition(type);
9895   const clang::TagDecl *td = ClangUtil::GetAsTagDecl(type);
9896   auto ts = type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
9897   if (ts)
9898     ts->SetDeclIsForcefullyCompleted(td);
9899 }
9900 
9901 namespace {
9902 /// A specialized scratch AST used within ScratchTypeSystemClang.
9903 /// These are the ASTs backing the different IsolatedASTKinds. They behave
9904 /// like a normal ScratchTypeSystemClang but they don't own their own
9905 /// persistent  storage or target reference.
9906 class SpecializedScratchAST : public TypeSystemClang {
9907 public:
9908   /// \param name The display name of the TypeSystemClang instance.
9909   /// \param triple The triple used for the TypeSystemClang instance.
9910   /// \param ast_source The ClangASTSource that should be used to complete
9911   ///                   type information.
9912   SpecializedScratchAST(llvm::StringRef name, llvm::Triple triple,
9913                         std::unique_ptr<ClangASTSource> ast_source)
9914       : TypeSystemClang(name, triple),
9915         m_scratch_ast_source_up(std::move(ast_source)) {
9916     // Setup the ClangASTSource to complete this AST.
9917     m_scratch_ast_source_up->InstallASTContext(*this);
9918     llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9919         m_scratch_ast_source_up->CreateProxy());
9920     SetExternalSource(proxy_ast_source);
9921   }
9922 
9923   /// The ExternalASTSource that performs lookups and completes types.
9924   std::unique_ptr<ClangASTSource> m_scratch_ast_source_up;
9925 };
9926 } // namespace
9927 
9928 char ScratchTypeSystemClang::ID;
9929 const std::nullopt_t ScratchTypeSystemClang::DefaultAST = std::nullopt;
9930 
9931 ScratchTypeSystemClang::ScratchTypeSystemClang(Target &target,
9932                                                llvm::Triple triple)
9933     : TypeSystemClang("scratch ASTContext", triple), m_triple(triple),
9934       m_target_wp(target.shared_from_this()),
9935       m_persistent_variables(
9936           new ClangPersistentVariables(target.shared_from_this())) {
9937   m_scratch_ast_source_up = CreateASTSource();
9938   m_scratch_ast_source_up->InstallASTContext(*this);
9939   llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9940       m_scratch_ast_source_up->CreateProxy());
9941   SetExternalSource(proxy_ast_source);
9942 }
9943 
9944 void ScratchTypeSystemClang::Finalize() {
9945   TypeSystemClang::Finalize();
9946   m_scratch_ast_source_up.reset();
9947 }
9948 
9949 TypeSystemClangSP
9950 ScratchTypeSystemClang::GetForTarget(Target &target,
9951                                      std::optional<IsolatedASTKind> ast_kind,
9952                                      bool create_on_demand) {
9953   auto type_system_or_err = target.GetScratchTypeSystemForLanguage(
9954       lldb::eLanguageTypeC, create_on_demand);
9955   if (auto err = type_system_or_err.takeError()) {
9956     LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
9957                    "Couldn't get scratch TypeSystemClang");
9958     return nullptr;
9959   }
9960   auto ts_sp = *type_system_or_err;
9961   ScratchTypeSystemClang *scratch_ast =
9962       llvm::dyn_cast_or_null<ScratchTypeSystemClang>(ts_sp.get());
9963   if (!scratch_ast)
9964     return nullptr;
9965   // If no dedicated sub-AST was requested, just return the main AST.
9966   if (ast_kind == DefaultAST)
9967     return std::static_pointer_cast<TypeSystemClang>(ts_sp);
9968   // Search the sub-ASTs.
9969   return std::static_pointer_cast<TypeSystemClang>(
9970       scratch_ast->GetIsolatedAST(*ast_kind).shared_from_this());
9971 }
9972 
9973 /// Returns a human-readable name that uniquely identifiers the sub-AST kind.
9974 static llvm::StringRef
9975 GetNameForIsolatedASTKind(ScratchTypeSystemClang::IsolatedASTKind kind) {
9976   switch (kind) {
9977   case ScratchTypeSystemClang::IsolatedASTKind::CppModules:
9978     return "C++ modules";
9979   }
9980   llvm_unreachable("Unimplemented IsolatedASTKind?");
9981 }
9982 
9983 void ScratchTypeSystemClang::Dump(llvm::raw_ostream &output) {
9984   // First dump the main scratch AST.
9985   output << "State of scratch Clang type system:\n";
9986   TypeSystemClang::Dump(output);
9987 
9988   // Now sort the isolated sub-ASTs.
9989   typedef std::pair<IsolatedASTKey, TypeSystem *> KeyAndTS;
9990   std::vector<KeyAndTS> sorted_typesystems;
9991   for (const auto &a : m_isolated_asts)
9992     sorted_typesystems.emplace_back(a.first, a.second.get());
9993   llvm::stable_sort(sorted_typesystems, llvm::less_first());
9994 
9995   // Dump each sub-AST too.
9996   for (const auto &a : sorted_typesystems) {
9997     IsolatedASTKind kind =
9998         static_cast<ScratchTypeSystemClang::IsolatedASTKind>(a.first);
9999     output << "State of scratch Clang type subsystem "
10000            << GetNameForIsolatedASTKind(kind) << ":\n";
10001     a.second->Dump(output);
10002   }
10003 }
10004 
10005 UserExpression *ScratchTypeSystemClang::GetUserExpression(
10006     llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
10007     Expression::ResultType desired_type,
10008     const EvaluateExpressionOptions &options, ValueObject *ctx_obj) {
10009   TargetSP target_sp = m_target_wp.lock();
10010   if (!target_sp)
10011     return nullptr;
10012 
10013   return new ClangUserExpression(*target_sp.get(), expr, prefix, language,
10014                                  desired_type, options, ctx_obj);
10015 }
10016 
10017 FunctionCaller *ScratchTypeSystemClang::GetFunctionCaller(
10018     const CompilerType &return_type, const Address &function_address,
10019     const ValueList &arg_value_list, const char *name) {
10020   TargetSP target_sp = m_target_wp.lock();
10021   if (!target_sp)
10022     return nullptr;
10023 
10024   Process *process = target_sp->GetProcessSP().get();
10025   if (!process)
10026     return nullptr;
10027 
10028   return new ClangFunctionCaller(*process, return_type, function_address,
10029                                  arg_value_list, name);
10030 }
10031 
10032 std::unique_ptr<UtilityFunction>
10033 ScratchTypeSystemClang::CreateUtilityFunction(std::string text,
10034                                               std::string name) {
10035   TargetSP target_sp = m_target_wp.lock();
10036   if (!target_sp)
10037     return {};
10038 
10039   return std::make_unique<ClangUtilityFunction>(
10040       *target_sp.get(), std::move(text), std::move(name),
10041       target_sp->GetDebugUtilityExpression());
10042 }
10043 
10044 PersistentExpressionState *
10045 ScratchTypeSystemClang::GetPersistentExpressionState() {
10046   return m_persistent_variables.get();
10047 }
10048 
10049 void ScratchTypeSystemClang::ForgetSource(ASTContext *src_ctx,
10050                                           ClangASTImporter &importer) {
10051   // Remove it as a source from the main AST.
10052   importer.ForgetSource(&getASTContext(), src_ctx);
10053   // Remove it as a source from all created sub-ASTs.
10054   for (const auto &a : m_isolated_asts)
10055     importer.ForgetSource(&a.second->getASTContext(), src_ctx);
10056 }
10057 
10058 std::unique_ptr<ClangASTSource> ScratchTypeSystemClang::CreateASTSource() {
10059   return std::make_unique<ClangASTSource>(
10060       m_target_wp.lock()->shared_from_this(),
10061       m_persistent_variables->GetClangASTImporter());
10062 }
10063 
10064 static llvm::StringRef
10065 GetSpecializedASTName(ScratchTypeSystemClang::IsolatedASTKind feature) {
10066   switch (feature) {
10067   case ScratchTypeSystemClang::IsolatedASTKind::CppModules:
10068     return "scratch ASTContext for C++ module types";
10069   }
10070   llvm_unreachable("Unimplemented ASTFeature kind?");
10071 }
10072 
10073 TypeSystemClang &ScratchTypeSystemClang::GetIsolatedAST(
10074     ScratchTypeSystemClang::IsolatedASTKind feature) {
10075   auto found_ast = m_isolated_asts.find(feature);
10076   if (found_ast != m_isolated_asts.end())
10077     return *found_ast->second;
10078 
10079   // Couldn't find the requested sub-AST, so create it now.
10080   std::shared_ptr<TypeSystemClang> new_ast_sp =
10081       std::make_shared<SpecializedScratchAST>(GetSpecializedASTName(feature),
10082                                               m_triple, CreateASTSource());
10083   m_isolated_asts.insert({feature, new_ast_sp});
10084   return *new_ast_sp;
10085 }
10086 
10087 bool TypeSystemClang::IsForcefullyCompleted(lldb::opaque_compiler_type_t type) {
10088   if (type) {
10089     clang::QualType qual_type(GetQualType(type));
10090     const clang::RecordType *record_type =
10091         llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
10092     if (record_type) {
10093       const clang::RecordDecl *record_decl = record_type->getDecl();
10094       assert(record_decl);
10095       ClangASTMetadata *metadata = GetMetadata(record_decl);
10096       if (metadata)
10097         return metadata->IsForcefullyCompleted();
10098     }
10099   }
10100   return false;
10101 }
10102 
10103 bool TypeSystemClang::SetDeclIsForcefullyCompleted(const clang::TagDecl *td) {
10104   if (td == nullptr)
10105     return false;
10106   ClangASTMetadata *metadata = GetMetadata(td);
10107   if (metadata == nullptr)
10108     return false;
10109   m_has_forcefully_completed_types = true;
10110   metadata->SetIsForcefullyCompleted();
10111   return true;
10112 }
10113