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