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