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