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