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