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