ClangASTContext.cpp revision 70c6cf4b614cd79a54cf1a8696f7b4c963229868
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 <string>
15
16// Other libraries and framework includes
17
18// Clang headers like to use NDEBUG inside of them to enable/disable debug
19// releated features using "#ifndef NDEBUG" preprocessor blocks to do one thing
20// or another. This is bad because it means that if clang was built in release
21// mode, it assumes that you are building in release mode which is not always
22// the case. You can end up with functions that are defined as empty in header
23// files when NDEBUG is not defined, and this can cause link errors with the
24// clang .a files that you have since you might be missing functions in the .a
25// file. So we have to define NDEBUG when including clang headers to avoid any
26// mismatches. This is covered by rdar://problem/8691220
27
28#if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
29#define LLDB_DEFINED_NDEBUG_FOR_CLANG
30#define NDEBUG
31// Need to include assert.h so it is as clang would expect it to be (disabled)
32#include <assert.h>
33#endif
34
35#include "clang/AST/ASTContext.h"
36#include "clang/AST/ASTImporter.h"
37#include "clang/AST/CXXInheritance.h"
38#include "clang/AST/DeclObjC.h"
39#include "clang/AST/DeclTemplate.h"
40#include "clang/AST/RecordLayout.h"
41#include "clang/AST/Type.h"
42#include "clang/Basic/Builtins.h"
43#include "clang/Basic/Diagnostic.h"
44#include "clang/Basic/FileManager.h"
45#include "clang/Basic/FileSystemOptions.h"
46#include "clang/Basic/SourceManager.h"
47#include "clang/Basic/TargetInfo.h"
48#include "clang/Basic/TargetOptions.h"
49#include "clang/Frontend/FrontendOptions.h"
50#include "clang/Frontend/LangStandard.h"
51
52#ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
53#undef NDEBUG
54#undef LLDB_DEFINED_NDEBUG_FOR_CLANG
55// Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
56#include <assert.h>
57#endif
58
59#include "lldb/Core/ArchSpec.h"
60#include "lldb/Core/dwarf.h"
61#include "lldb/Core/Flags.h"
62#include "lldb/Core/Log.h"
63#include "lldb/Core/RegularExpression.h"
64#include "lldb/Expression/ASTDumper.h"
65#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
66#include "lldb/Symbol/VerifyDecl.h"
67#include "lldb/Target/ExecutionContext.h"
68#include "lldb/Target/Process.h"
69#include "lldb/Target/ObjCLanguageRuntime.h"
70
71
72#include <stdio.h>
73
74using namespace lldb;
75using namespace lldb_private;
76using namespace llvm;
77using namespace clang;
78
79
80static bool
81GetCompleteQualType (clang::ASTContext *ast, clang::QualType qual_type)
82{
83    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
84    switch (type_class)
85    {
86    case clang::Type::ConstantArray:
87        {
88            const clang::ArrayType *array_type = dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
89
90            if (array_type)
91                return GetCompleteQualType (ast, array_type->getElementType());
92        }
93        break;
94
95    case clang::Type::Record:
96    case clang::Type::Enum:
97        {
98            const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type.getTypePtr());
99            if (tag_type)
100            {
101                clang::TagDecl *tag_decl = tag_type->getDecl();
102                if (tag_decl)
103                {
104                    if (tag_decl->getDefinition())
105                        return true;
106
107                    if (tag_decl->hasExternalLexicalStorage())
108                    {
109                        if (ast)
110                        {
111                            ExternalASTSource *external_ast_source = ast->getExternalSource();
112                            if (external_ast_source)
113                            {
114                                external_ast_source->CompleteType(tag_decl);
115                                return !tag_type->isIncompleteType();
116                            }
117                        }
118                    }
119                    return false;
120                }
121            }
122
123        }
124        break;
125
126    case clang::Type::ObjCObject:
127    case clang::Type::ObjCInterface:
128        {
129            const clang::ObjCObjectType *objc_class_type = dyn_cast<clang::ObjCObjectType>(qual_type);
130            if (objc_class_type)
131            {
132                clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
133                // We currently can't complete objective C types through the newly added ASTContext
134                // because it only supports TagDecl objects right now...
135                if (class_interface_decl)
136                {
137                    if (class_interface_decl->getDefinition())
138                        return true;
139
140                    if (class_interface_decl->hasExternalLexicalStorage())
141                    {
142                        if (ast)
143                        {
144                            ExternalASTSource *external_ast_source = ast->getExternalSource();
145                            if (external_ast_source)
146                            {
147                                external_ast_source->CompleteType (class_interface_decl);
148                                return !objc_class_type->isIncompleteType();
149                            }
150                        }
151                    }
152                    return false;
153                }
154            }
155        }
156        break;
157
158    case clang::Type::Typedef:
159        return GetCompleteQualType (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType());
160
161    case clang::Type::Elaborated:
162        return GetCompleteQualType (ast, cast<ElaboratedType>(qual_type)->getNamedType());
163
164    default:
165        break;
166    }
167
168    return true;
169}
170
171
172static AccessSpecifier
173ConvertAccessTypeToAccessSpecifier (AccessType access)
174{
175    switch (access)
176    {
177    default:               break;
178    case eAccessNone:      return AS_none;
179    case eAccessPublic:    return AS_public;
180    case eAccessPrivate:   return AS_private;
181    case eAccessProtected: return AS_protected;
182    }
183    return AS_none;
184}
185
186static ObjCIvarDecl::AccessControl
187ConvertAccessTypeToObjCIvarAccessControl (AccessType access)
188{
189    switch (access)
190    {
191    default:               break;
192    case eAccessNone:      return ObjCIvarDecl::None;
193    case eAccessPublic:    return ObjCIvarDecl::Public;
194    case eAccessPrivate:   return ObjCIvarDecl::Private;
195    case eAccessProtected: return ObjCIvarDecl::Protected;
196    case eAccessPackage:   return ObjCIvarDecl::Package;
197    }
198    return ObjCIvarDecl::None;
199}
200
201
202static void
203ParseLangArgs
204(
205    LangOptions &Opts,
206    InputKind IK
207)
208{
209    // FIXME: Cleanup per-file based stuff.
210
211    // Set some properties which depend soley on the input kind; it would be nice
212    // to move these to the language standard, and have the driver resolve the
213    // input kind + language standard.
214    if (IK == IK_Asm) {
215        Opts.AsmPreprocessor = 1;
216    } else if (IK == IK_ObjC ||
217               IK == IK_ObjCXX ||
218               IK == IK_PreprocessedObjC ||
219               IK == IK_PreprocessedObjCXX) {
220        Opts.ObjC1 = Opts.ObjC2 = 1;
221    }
222
223    LangStandard::Kind LangStd = LangStandard::lang_unspecified;
224
225    if (LangStd == LangStandard::lang_unspecified) {
226        // Based on the base language, pick one.
227        switch (IK) {
228            case IK_None:
229            case IK_AST:
230            case IK_LLVM_IR:
231                assert (!"Invalid input kind!");
232            case IK_OpenCL:
233                LangStd = LangStandard::lang_opencl;
234                break;
235            case IK_CUDA:
236                LangStd = LangStandard::lang_cuda;
237                break;
238            case IK_Asm:
239            case IK_C:
240            case IK_PreprocessedC:
241            case IK_ObjC:
242            case IK_PreprocessedObjC:
243                LangStd = LangStandard::lang_gnu99;
244                break;
245            case IK_CXX:
246            case IK_PreprocessedCXX:
247            case IK_ObjCXX:
248            case IK_PreprocessedObjCXX:
249                LangStd = LangStandard::lang_gnucxx98;
250                break;
251        }
252    }
253
254    const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
255    Opts.BCPLComment = Std.hasBCPLComments();
256    Opts.C99 = Std.isC99();
257    Opts.CPlusPlus = Std.isCPlusPlus();
258    Opts.CPlusPlus0x = Std.isCPlusPlus0x();
259    Opts.Digraphs = Std.hasDigraphs();
260    Opts.GNUMode = Std.isGNUMode();
261    Opts.GNUInline = !Std.isC99();
262    Opts.HexFloats = Std.hasHexFloats();
263    Opts.ImplicitInt = Std.hasImplicitInt();
264
265    // OpenCL has some additional defaults.
266    if (LangStd == LangStandard::lang_opencl) {
267        Opts.OpenCL = 1;
268        Opts.AltiVec = 1;
269        Opts.CXXOperatorNames = 1;
270        Opts.LaxVectorConversions = 1;
271    }
272
273    // OpenCL and C++ both have bool, true, false keywords.
274    Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
275
276//    if (Opts.CPlusPlus)
277//        Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
278//
279//    if (Args.hasArg(OPT_fobjc_gc_only))
280//        Opts.setGCMode(LangOptions::GCOnly);
281//    else if (Args.hasArg(OPT_fobjc_gc))
282//        Opts.setGCMode(LangOptions::HybridGC);
283//
284//    if (Args.hasArg(OPT_print_ivar_layout))
285//        Opts.ObjCGCBitmapPrint = 1;
286//
287//    if (Args.hasArg(OPT_faltivec))
288//        Opts.AltiVec = 1;
289//
290//    if (Args.hasArg(OPT_pthread))
291//        Opts.POSIXThreads = 1;
292//
293//    llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
294//                                          "default");
295//    if (Vis == "default")
296        Opts.setVisibilityMode(DefaultVisibility);
297//    else if (Vis == "hidden")
298//        Opts.setVisibilityMode(LangOptions::Hidden);
299//    else if (Vis == "protected")
300//        Opts.setVisibilityMode(LangOptions::Protected);
301//    else
302//        Diags.Report(diag::err_drv_invalid_value)
303//        << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
304
305//    Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
306
307    // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
308    // is specified, or -std is set to a conforming mode.
309    Opts.Trigraphs = !Opts.GNUMode;
310//    if (Args.hasArg(OPT_trigraphs))
311//        Opts.Trigraphs = 1;
312//
313//    Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
314//                                     OPT_fno_dollars_in_identifiers,
315//                                     !Opts.AsmPreprocessor);
316//    Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
317//    Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
318//    Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
319//    if (Args.hasArg(OPT_fno_lax_vector_conversions))
320//        Opts.LaxVectorConversions = 0;
321//    Opts.Exceptions = Args.hasArg(OPT_fexceptions);
322//    Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
323//    Opts.Blocks = Args.hasArg(OPT_fblocks);
324//    Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
325//    Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
326//    Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
327//    Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
328//    Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
329//    Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
330//    Opts.AccessControl = Args.hasArg(OPT_faccess_control);
331//    Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
332//    Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
333//    Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
334//                                                 Diags);
335//    Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
336//    Opts.ObjCConstantStringClass = getLastArgValue(Args,
337//                                                   OPT_fconstant_string_class);
338//    Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
339//    Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
340//    Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
341//    Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
342//    Opts.Static = Args.hasArg(OPT_static_define);
343    Opts.OptimizeSize = 0;
344
345    // FIXME: Eliminate this dependency.
346//    unsigned Opt =
347//    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
348//    Opts.Optimize = Opt != 0;
349    unsigned Opt = 0;
350
351    // This is the __NO_INLINE__ define, which just depends on things like the
352    // optimization level and -fno-inline, not actually whether the backend has
353    // inlining enabled.
354    //
355    // FIXME: This is affected by other options (-fno-inline).
356    Opts.NoInline = !Opt;
357
358//    unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
359//    switch (SSP) {
360//        default:
361//            Diags.Report(diag::err_drv_invalid_value)
362//            << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
363//            break;
364//        case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
365//        case 1: Opts.setStackProtectorMode(LangOptions::SSPOn);  break;
366//        case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
367//    }
368}
369
370
371ClangASTContext::ClangASTContext (const char *target_triple) :
372    m_target_triple(),
373    m_ast_ap(),
374    m_language_options_ap(),
375    m_source_manager_ap(),
376    m_diagnostics_engine_ap(),
377    m_target_options_ap(),
378    m_target_info_ap(),
379    m_identifier_table_ap(),
380    m_selector_table_ap(),
381    m_builtins_ap(),
382    m_callback_tag_decl (NULL),
383    m_callback_objc_decl (NULL),
384    m_callback_baton (NULL)
385
386{
387    if (target_triple && target_triple[0])
388        SetTargetTriple (target_triple);
389}
390
391//----------------------------------------------------------------------
392// Destructor
393//----------------------------------------------------------------------
394ClangASTContext::~ClangASTContext()
395{
396    m_builtins_ap.reset();
397    m_selector_table_ap.reset();
398    m_identifier_table_ap.reset();
399    m_target_info_ap.reset();
400    m_target_options_ap.reset();
401    m_diagnostics_engine_ap.reset();
402    m_source_manager_ap.reset();
403    m_language_options_ap.reset();
404    m_ast_ap.reset();
405}
406
407
408void
409ClangASTContext::Clear()
410{
411    m_ast_ap.reset();
412    m_language_options_ap.reset();
413    m_source_manager_ap.reset();
414    m_diagnostics_engine_ap.reset();
415    m_target_options_ap.reset();
416    m_target_info_ap.reset();
417    m_identifier_table_ap.reset();
418    m_selector_table_ap.reset();
419    m_builtins_ap.reset();
420}
421
422const char *
423ClangASTContext::GetTargetTriple ()
424{
425    return m_target_triple.c_str();
426}
427
428void
429ClangASTContext::SetTargetTriple (const char *target_triple)
430{
431    Clear();
432    m_target_triple.assign(target_triple);
433}
434
435void
436ClangASTContext::SetArchitecture (const ArchSpec &arch)
437{
438    SetTargetTriple(arch.GetTriple().str().c_str());
439}
440
441bool
442ClangASTContext::HasExternalSource ()
443{
444    ASTContext *ast = getASTContext();
445    if (ast)
446        return ast->getExternalSource () != NULL;
447    return false;
448}
449
450void
451ClangASTContext::SetExternalSource (llvm::OwningPtr<ExternalASTSource> &ast_source_ap)
452{
453    ASTContext *ast = getASTContext();
454    if (ast)
455    {
456        ast->setExternalSource (ast_source_ap);
457        ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
458        //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
459    }
460}
461
462void
463ClangASTContext::RemoveExternalSource ()
464{
465    ASTContext *ast = getASTContext();
466
467    if (ast)
468    {
469        llvm::OwningPtr<ExternalASTSource> empty_ast_source_ap;
470        ast->setExternalSource (empty_ast_source_ap);
471        ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
472        //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false);
473    }
474}
475
476
477
478ASTContext *
479ClangASTContext::getASTContext()
480{
481    if (m_ast_ap.get() == NULL)
482    {
483        m_ast_ap.reset(new ASTContext (*getLanguageOptions(),
484                                       *getSourceManager(),
485                                       getTargetInfo(),
486                                       *getIdentifierTable(),
487                                       *getSelectorTable(),
488                                       *getBuiltinContext(),
489                                       0));
490
491        if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton)
492        {
493            m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage();
494            //m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage();
495        }
496
497        m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false);
498    }
499    return m_ast_ap.get();
500}
501
502Builtin::Context *
503ClangASTContext::getBuiltinContext()
504{
505    if (m_builtins_ap.get() == NULL)
506        m_builtins_ap.reset (new Builtin::Context());
507    return m_builtins_ap.get();
508}
509
510IdentifierTable *
511ClangASTContext::getIdentifierTable()
512{
513    if (m_identifier_table_ap.get() == NULL)
514        m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), NULL));
515    return m_identifier_table_ap.get();
516}
517
518LangOptions *
519ClangASTContext::getLanguageOptions()
520{
521    if (m_language_options_ap.get() == NULL)
522    {
523        m_language_options_ap.reset(new LangOptions());
524        ParseLangArgs(*m_language_options_ap, IK_ObjCXX);
525//        InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
526    }
527    return m_language_options_ap.get();
528}
529
530SelectorTable *
531ClangASTContext::getSelectorTable()
532{
533    if (m_selector_table_ap.get() == NULL)
534        m_selector_table_ap.reset (new SelectorTable());
535    return m_selector_table_ap.get();
536}
537
538clang::FileManager *
539ClangASTContext::getFileManager()
540{
541    if (m_file_manager_ap.get() == NULL)
542    {
543        clang::FileSystemOptions file_system_options;
544        m_file_manager_ap.reset(new clang::FileManager(file_system_options));
545    }
546    return m_file_manager_ap.get();
547}
548
549clang::SourceManager *
550ClangASTContext::getSourceManager()
551{
552    if (m_source_manager_ap.get() == NULL)
553        m_source_manager_ap.reset(new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
554    return m_source_manager_ap.get();
555}
556
557clang::DiagnosticsEngine *
558ClangASTContext::getDiagnosticsEngine()
559{
560    if (m_diagnostics_engine_ap.get() == NULL)
561    {
562        llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
563        m_diagnostics_engine_ap.reset(new DiagnosticsEngine(diag_id_sp));
564    }
565    return m_diagnostics_engine_ap.get();
566}
567
568class NullDiagnosticConsumer : public DiagnosticConsumer
569{
570public:
571    NullDiagnosticConsumer ()
572    {
573        m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
574    }
575
576    void HandleDiagnostic (DiagnosticsEngine::Level DiagLevel, const Diagnostic &info)
577    {
578        if (m_log)
579        {
580            llvm::SmallVector<char, 32> diag_str(10);
581            info.FormatDiagnostic(diag_str);
582            diag_str.push_back('\0');
583            m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
584        }
585    }
586
587    DiagnosticConsumer *clone (DiagnosticsEngine &Diags) const
588    {
589        return new NullDiagnosticConsumer ();
590    }
591private:
592    LogSP m_log;
593};
594
595DiagnosticConsumer *
596ClangASTContext::getDiagnosticConsumer()
597{
598    if (m_diagnostic_consumer_ap.get() == NULL)
599        m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer);
600
601    return m_diagnostic_consumer_ap.get();
602}
603
604TargetOptions *
605ClangASTContext::getTargetOptions()
606{
607    if (m_target_options_ap.get() == NULL && !m_target_triple.empty())
608    {
609        m_target_options_ap.reset (new TargetOptions());
610        if (m_target_options_ap.get())
611            m_target_options_ap->Triple = m_target_triple;
612    }
613    return m_target_options_ap.get();
614}
615
616
617TargetInfo *
618ClangASTContext::getTargetInfo()
619{
620    // target_triple should be something like "x86_64-apple-darwin10"
621    if (m_target_info_ap.get() == NULL && !m_target_triple.empty())
622        m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), *getTargetOptions()));
623    return m_target_info_ap.get();
624}
625
626#pragma mark Basic Types
627
628static inline bool
629QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast, QualType qual_type)
630{
631    uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
632    if (qual_type_bit_size == bit_size)
633        return true;
634    return false;
635}
636
637clang_type_t
638ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (Encoding encoding, uint32_t bit_size)
639{
640    ASTContext *ast = getASTContext();
641
642    assert (ast != NULL);
643
644    return GetBuiltinTypeForEncodingAndBitSize (ast, encoding, bit_size);
645}
646
647clang_type_t
648ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (ASTContext *ast, Encoding encoding, uint32_t bit_size)
649{
650    if (!ast)
651        return NULL;
652
653    switch (encoding)
654    {
655    case eEncodingInvalid:
656        if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
657            return ast->VoidPtrTy.getAsOpaquePtr();
658        break;
659
660    case eEncodingUint:
661        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
662            return ast->UnsignedCharTy.getAsOpaquePtr();
663        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
664            return ast->UnsignedShortTy.getAsOpaquePtr();
665        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
666            return ast->UnsignedIntTy.getAsOpaquePtr();
667        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
668            return ast->UnsignedLongTy.getAsOpaquePtr();
669        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
670            return ast->UnsignedLongLongTy.getAsOpaquePtr();
671        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
672            return ast->UnsignedInt128Ty.getAsOpaquePtr();
673        break;
674
675    case eEncodingSint:
676        if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
677            return ast->CharTy.getAsOpaquePtr();
678        if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
679            return ast->ShortTy.getAsOpaquePtr();
680        if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
681            return ast->IntTy.getAsOpaquePtr();
682        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
683            return ast->LongTy.getAsOpaquePtr();
684        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
685            return ast->LongLongTy.getAsOpaquePtr();
686        if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
687            return ast->Int128Ty.getAsOpaquePtr();
688        break;
689
690    case eEncodingIEEE754:
691        if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
692            return ast->FloatTy.getAsOpaquePtr();
693        if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
694            return ast->DoubleTy.getAsOpaquePtr();
695        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
696            return ast->LongDoubleTy.getAsOpaquePtr();
697        break;
698
699    case eEncodingVector:
700    default:
701        break;
702    }
703
704    return NULL;
705}
706
707clang_type_t
708ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
709{
710    ASTContext *ast = getASTContext();
711
712    #define streq(a,b) strcmp(a,b) == 0
713    assert (ast != NULL);
714    if (ast)
715    {
716        switch (dw_ate)
717        {
718        default:
719            break;
720
721        case DW_ATE_address:
722            if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
723                return ast->VoidPtrTy.getAsOpaquePtr();
724            break;
725
726        case DW_ATE_boolean:
727            if (QualTypeMatchesBitSize (bit_size, ast, ast->BoolTy))
728                return ast->BoolTy.getAsOpaquePtr();
729            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
730                return ast->UnsignedCharTy.getAsOpaquePtr();
731            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
732                return ast->UnsignedShortTy.getAsOpaquePtr();
733            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
734                return ast->UnsignedIntTy.getAsOpaquePtr();
735            break;
736
737        case DW_ATE_lo_user:
738            // This has been seen to mean DW_AT_complex_integer
739            if (type_name)
740            {
741                if (::strstr(type_name, "complex"))
742                {
743                    clang_type_t complex_int_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("int", DW_ATE_signed, bit_size/2);
744                    return ast->getComplexType (QualType::getFromOpaquePtr(complex_int_clang_type)).getAsOpaquePtr();
745                }
746            }
747            break;
748
749        case DW_ATE_complex_float:
750            if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatComplexTy))
751                return ast->FloatComplexTy.getAsOpaquePtr();
752            else if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleComplexTy))
753                return ast->DoubleComplexTy.getAsOpaquePtr();
754            else if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleComplexTy))
755                return ast->LongDoubleComplexTy.getAsOpaquePtr();
756            else
757            {
758                clang_type_t complex_float_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("float", DW_ATE_float, bit_size/2);
759                return ast->getComplexType (QualType::getFromOpaquePtr(complex_float_clang_type)).getAsOpaquePtr();
760            }
761            break;
762
763        case DW_ATE_float:
764            if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
765                return ast->FloatTy.getAsOpaquePtr();
766            if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
767                return ast->DoubleTy.getAsOpaquePtr();
768            if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
769                return ast->LongDoubleTy.getAsOpaquePtr();
770            break;
771
772        case DW_ATE_signed:
773            if (type_name)
774            {
775                if (strstr(type_name, "long long"))
776                {
777                    if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
778                        return ast->LongLongTy.getAsOpaquePtr();
779                }
780                else if (strstr(type_name, "long"))
781                {
782                    if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
783                        return ast->LongTy.getAsOpaquePtr();
784                }
785                else if (strstr(type_name, "short"))
786                {
787                    if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
788                        return ast->ShortTy.getAsOpaquePtr();
789                }
790                else if (strstr(type_name, "char"))
791                {
792                    if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
793                        return ast->CharTy.getAsOpaquePtr();
794                    if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
795                        return ast->SignedCharTy.getAsOpaquePtr();
796                }
797                else if (strstr(type_name, "int"))
798                {
799                    if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
800                        return ast->IntTy.getAsOpaquePtr();
801                    if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
802                        return ast->Int128Ty.getAsOpaquePtr();
803                }
804                else if (streq(type_name, "wchar_t"))
805                {
806                    if (QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy))
807                        return ast->WCharTy.getAsOpaquePtr();
808                }
809                else if (streq(type_name, "void"))
810                {
811                    if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidTy))
812                        return ast->VoidTy.getAsOpaquePtr();
813                }
814            }
815            // We weren't able to match up a type name, just search by size
816            if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
817                return ast->CharTy.getAsOpaquePtr();
818            if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
819                return ast->ShortTy.getAsOpaquePtr();
820            if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
821                return ast->IntTy.getAsOpaquePtr();
822            if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
823                return ast->LongTy.getAsOpaquePtr();
824            if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
825                return ast->LongLongTy.getAsOpaquePtr();
826            if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
827                return ast->Int128Ty.getAsOpaquePtr();
828            break;
829
830        case DW_ATE_signed_char:
831            if (type_name)
832            {
833                if (streq(type_name, "signed char"))
834                {
835                    if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
836                        return ast->SignedCharTy.getAsOpaquePtr();
837                }
838            }
839            if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
840                return ast->CharTy.getAsOpaquePtr();
841            if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
842                return ast->SignedCharTy.getAsOpaquePtr();
843            break;
844
845        case DW_ATE_unsigned:
846            if (type_name)
847            {
848                if (strstr(type_name, "long long"))
849                {
850                    if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
851                        return ast->UnsignedLongLongTy.getAsOpaquePtr();
852                }
853                else if (strstr(type_name, "long"))
854                {
855                    if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
856                        return ast->UnsignedLongTy.getAsOpaquePtr();
857                }
858                else if (strstr(type_name, "short"))
859                {
860                    if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
861                        return ast->UnsignedShortTy.getAsOpaquePtr();
862                }
863                else if (strstr(type_name, "char"))
864                {
865                    if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
866                        return ast->UnsignedCharTy.getAsOpaquePtr();
867                }
868                else if (strstr(type_name, "int"))
869                {
870                    if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
871                        return ast->UnsignedIntTy.getAsOpaquePtr();
872                    if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
873                        return ast->UnsignedInt128Ty.getAsOpaquePtr();
874                }
875            }
876            // We weren't able to match up a type name, just search by size
877            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
878                return ast->UnsignedCharTy.getAsOpaquePtr();
879            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
880                return ast->UnsignedShortTy.getAsOpaquePtr();
881            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
882                return ast->UnsignedIntTy.getAsOpaquePtr();
883            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
884                return ast->UnsignedLongTy.getAsOpaquePtr();
885            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
886                return ast->UnsignedLongLongTy.getAsOpaquePtr();
887            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
888                return ast->UnsignedInt128Ty.getAsOpaquePtr();
889            break;
890
891        case DW_ATE_unsigned_char:
892            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
893                return ast->UnsignedCharTy.getAsOpaquePtr();
894            if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
895                return ast->UnsignedShortTy.getAsOpaquePtr();
896            break;
897
898        case DW_ATE_imaginary_float:
899            break;
900
901        case DW_ATE_UTF:
902            if (type_name)
903            {
904                if (streq(type_name, "char16_t"))
905                {
906                    return ast->Char16Ty.getAsOpaquePtr();
907                }
908                else if (streq(type_name, "char32_t"))
909                {
910                    return ast->Char32Ty.getAsOpaquePtr();
911                }
912            }
913            break;
914        }
915    }
916    // This assert should fire for anything that we don't catch above so we know
917    // to fix any issues we run into.
918    if (type_name)
919    {
920        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);
921    }
922    else
923    {
924        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);
925    }
926    return NULL;
927}
928
929clang_type_t
930ClangASTContext::GetBuiltInType_void(ASTContext *ast)
931{
932    return ast->VoidTy.getAsOpaquePtr();
933}
934
935clang_type_t
936ClangASTContext::GetBuiltInType_bool()
937{
938    return getASTContext()->BoolTy.getAsOpaquePtr();
939}
940
941clang_type_t
942ClangASTContext::GetBuiltInType_objc_id()
943{
944    return getASTContext()->getObjCIdType().getAsOpaquePtr();
945}
946
947clang_type_t
948ClangASTContext::GetBuiltInType_objc_Class()
949{
950    return getASTContext()->getObjCClassType().getAsOpaquePtr();
951}
952
953clang_type_t
954ClangASTContext::GetBuiltInType_objc_selector()
955{
956    return getASTContext()->getObjCSelType().getAsOpaquePtr();
957}
958
959clang_type_t
960ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast)
961{
962    return ast->UnknownAnyTy.getAsOpaquePtr();
963}
964
965clang_type_t
966ClangASTContext::GetCStringType (bool is_const)
967{
968    QualType char_type(getASTContext()->CharTy);
969
970    if (is_const)
971        char_type.addConst();
972
973    return getASTContext()->getPointerType(char_type).getAsOpaquePtr();
974}
975
976clang_type_t
977ClangASTContext::GetVoidPtrType (bool is_const)
978{
979    return GetVoidPtrType(getASTContext(), is_const);
980}
981
982clang_type_t
983ClangASTContext::GetVoidPtrType (ASTContext *ast, bool is_const)
984{
985    QualType void_ptr_type(ast->VoidPtrTy);
986
987    if (is_const)
988        void_ptr_type.addConst();
989
990    return void_ptr_type.getAsOpaquePtr();
991}
992
993clang::DeclContext *
994ClangASTContext::GetTranslationUnitDecl (clang::ASTContext *ast)
995{
996    return ast->getTranslationUnitDecl();
997}
998
999clang_type_t
1000ClangASTContext::CopyType (ASTContext *dst_ast,
1001                           ASTContext *src_ast,
1002                           clang_type_t clang_type)
1003{
1004    FileSystemOptions file_system_options;
1005    FileManager file_manager (file_system_options);
1006    ASTImporter importer(*dst_ast, file_manager,
1007                         *src_ast, file_manager,
1008                         false);
1009
1010    QualType src (QualType::getFromOpaquePtr(clang_type));
1011    QualType dst (importer.Import(src));
1012
1013    return dst.getAsOpaquePtr();
1014}
1015
1016
1017clang::Decl *
1018ClangASTContext::CopyDecl (ASTContext *dst_ast,
1019                           ASTContext *src_ast,
1020                           clang::Decl *source_decl)
1021{
1022    FileSystemOptions file_system_options;
1023    FileManager file_manager (file_system_options);
1024    ASTImporter importer(*dst_ast, file_manager,
1025                         *src_ast, file_manager,
1026                         false);
1027
1028    return importer.Import(source_decl);
1029}
1030
1031bool
1032ClangASTContext::AreTypesSame(ASTContext *ast,
1033             clang_type_t type1,
1034             clang_type_t type2,
1035             bool ignore_qualifiers)
1036{
1037    QualType type1_qual = QualType::getFromOpaquePtr(type1);
1038    QualType type2_qual = QualType::getFromOpaquePtr(type2);
1039
1040    if (ignore_qualifiers)
1041    {
1042        type1_qual = type1_qual.getUnqualifiedType();
1043        type2_qual = type2_qual.getUnqualifiedType();
1044    }
1045
1046    return ast->hasSameType (type1_qual,
1047                             type2_qual);
1048}
1049
1050#pragma mark CVR modifiers
1051
1052clang_type_t
1053ClangASTContext::AddConstModifier (clang_type_t clang_type)
1054{
1055    if (clang_type)
1056    {
1057        QualType result(QualType::getFromOpaquePtr(clang_type));
1058        result.addConst();
1059        return result.getAsOpaquePtr();
1060    }
1061    return NULL;
1062}
1063
1064clang_type_t
1065ClangASTContext::AddRestrictModifier (clang_type_t clang_type)
1066{
1067    if (clang_type)
1068    {
1069        QualType result(QualType::getFromOpaquePtr(clang_type));
1070        result.getQualifiers().setRestrict (true);
1071        return result.getAsOpaquePtr();
1072    }
1073    return NULL;
1074}
1075
1076clang_type_t
1077ClangASTContext::AddVolatileModifier (clang_type_t clang_type)
1078{
1079    if (clang_type)
1080    {
1081        QualType result(QualType::getFromOpaquePtr(clang_type));
1082        result.getQualifiers().setVolatile (true);
1083        return result.getAsOpaquePtr();
1084    }
1085    return NULL;
1086}
1087
1088
1089clang_type_t
1090ClangASTContext::GetTypeForDecl (TagDecl *decl)
1091{
1092    // No need to call the getASTContext() accessor (which can create the AST
1093    // if it isn't created yet, because we can't have created a decl in this
1094    // AST if our AST didn't already exist...
1095    if (m_ast_ap.get())
1096        return m_ast_ap->getTagDeclType(decl).getAsOpaquePtr();
1097    return NULL;
1098}
1099
1100clang_type_t
1101ClangASTContext::GetTypeForDecl (ObjCInterfaceDecl *decl)
1102{
1103    // No need to call the getASTContext() accessor (which can create the AST
1104    // if it isn't created yet, because we can't have created a decl in this
1105    // AST if our AST didn't already exist...
1106    if (m_ast_ap.get())
1107        return m_ast_ap->getObjCInterfaceType(decl).getAsOpaquePtr();
1108    return NULL;
1109}
1110
1111#pragma mark Structure, Unions, Classes
1112
1113clang_type_t
1114ClangASTContext::CreateRecordType (DeclContext *decl_ctx, AccessType access_type, const char *name, int kind, LanguageType language)
1115{
1116    ASTContext *ast = getASTContext();
1117    assert (ast != NULL);
1118
1119    if (decl_ctx == NULL)
1120        decl_ctx = ast->getTranslationUnitDecl();
1121
1122
1123    if (language == eLanguageTypeObjC || language == eLanguageTypeObjC_plus_plus)
1124    {
1125        bool isForwardDecl = true;
1126        bool isInternal = false;
1127        return CreateObjCClass (name, decl_ctx, isForwardDecl, isInternal);
1128    }
1129
1130    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1131    // we will need to update this code. I was told to currently always use
1132    // the CXXRecordDecl class since we often don't know from debug information
1133    // if something is struct or a class, so we default to always use the more
1134    // complete definition just in case.
1135    CXXRecordDecl *decl = CXXRecordDecl::Create (*ast,
1136                                                 (TagDecl::TagKind)kind,
1137                                                 decl_ctx,
1138                                                 SourceLocation(),
1139                                                 SourceLocation(),
1140                                                 name && name[0] ? &ast->Idents.get(name) : NULL);
1141
1142    if (!name)
1143        decl->setAnonymousStructOrUnion(true);
1144
1145    if (decl_ctx)
1146    {
1147        if (access_type != eAccessNone)
1148            decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1149        decl_ctx->addDecl (decl);
1150    }
1151    return ast->getTagDeclType(decl).getAsOpaquePtr();
1152}
1153
1154static TemplateParameterList *
1155CreateTemplateParameterList (ASTContext *ast,
1156                             const ClangASTContext::TemplateParameterInfos &template_param_infos,
1157                             llvm::SmallVector<NamedDecl *, 8> &template_param_decls)
1158{
1159    const bool parameter_pack = false;
1160    const bool is_typename = false;
1161    const unsigned depth = 0;
1162    const size_t num_template_params = template_param_infos.GetSize();
1163    for (size_t i=0; i<num_template_params; ++i)
1164    {
1165        const char *name = template_param_infos.names[i];
1166        if (template_param_infos.args[i].getAsIntegral())
1167        {
1168            template_param_decls.push_back (NonTypeTemplateParmDecl::Create (*ast,
1169                                                                             ast->getTranslationUnitDecl(), // Is this the right decl context?, SourceLocation StartLoc,
1170                                                                             SourceLocation(),
1171                                                                             SourceLocation(),
1172                                                                             depth,
1173                                                                             i,
1174                                                                             &ast->Idents.get(name),
1175                                                                             template_param_infos.args[i].getIntegralType(),
1176                                                                             parameter_pack,
1177                                                                             NULL));
1178
1179        }
1180        else
1181        {
1182            template_param_decls.push_back (TemplateTypeParmDecl::Create (*ast,
1183                                                                          ast->getTranslationUnitDecl(), // Is this the right decl context?
1184                                                                          SourceLocation(),
1185                                                                          SourceLocation(),
1186                                                                          depth,
1187                                                                          i,
1188                                                                          &ast->Idents.get(name),
1189                                                                          is_typename,
1190                                                                          parameter_pack));
1191        }
1192    }
1193
1194    TemplateParameterList *template_param_list = TemplateParameterList::Create (*ast,
1195                                                                                SourceLocation(),
1196                                                                                SourceLocation(),
1197                                                                                &template_param_decls.front(),
1198                                                                                template_param_decls.size(),
1199                                                                                SourceLocation());
1200    return template_param_list;
1201}
1202
1203clang::FunctionTemplateDecl *
1204ClangASTContext::CreateFunctionTemplateDecl (clang::DeclContext *decl_ctx,
1205                                             clang::FunctionDecl *func_decl,
1206                                             const char *name,
1207                                             const TemplateParameterInfos &template_param_infos)
1208{
1209//    /// \brief Create a function template node.
1210    ASTContext *ast = getASTContext();
1211
1212    llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1213
1214    TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1215                                                                              template_param_infos,
1216                                                                              template_param_decls);
1217    FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create (*ast,
1218                                                                         decl_ctx,
1219                                                                         func_decl->getLocation(),
1220                                                                         func_decl->getDeclName(),
1221                                                                         template_param_list,
1222                                                                         func_decl);
1223
1224    for (size_t i=0, template_param_decl_count = template_param_decls.size();
1225         i < template_param_decl_count;
1226         ++i)
1227    {
1228        // TODO: verify which decl context we should put template_param_decls into..
1229        template_param_decls[i]->setDeclContext (func_decl);
1230    }
1231
1232    return func_tmpl_decl;
1233}
1234
1235void
1236ClangASTContext::CreateFunctionTemplateSpecializationInfo (FunctionDecl *func_decl,
1237                                                           clang::FunctionTemplateDecl *func_tmpl_decl,
1238                                                           const TemplateParameterInfos &infos)
1239{
1240    TemplateArgumentList template_args (TemplateArgumentList::OnStack,
1241                                        infos.args.data(),
1242                                        infos.args.size());
1243
1244    func_decl->setFunctionTemplateSpecialization (func_tmpl_decl,
1245                                                  &template_args,
1246                                                  NULL);
1247}
1248
1249
1250ClassTemplateDecl *
1251ClangASTContext::CreateClassTemplateDecl (DeclContext *decl_ctx,
1252                                          lldb::AccessType access_type,
1253                                          const char *class_name,
1254                                          int kind,
1255                                          const TemplateParameterInfos &template_param_infos)
1256{
1257    ASTContext *ast = getASTContext();
1258
1259    ClassTemplateDecl *class_template_decl = NULL;
1260    if (decl_ctx == NULL)
1261        decl_ctx = ast->getTranslationUnitDecl();
1262
1263    IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1264    DeclarationName decl_name (&identifier_info);
1265
1266    clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1267    for (clang::DeclContext::lookup_iterator pos = result.first, end = result.second; pos != end; ++pos)
1268    {
1269        class_template_decl = dyn_cast<clang::ClassTemplateDecl>(*pos);
1270        if (class_template_decl)
1271            return class_template_decl;
1272    }
1273
1274    llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1275
1276    TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1277                                                                              template_param_infos,
1278                                                                              template_param_decls);
1279
1280    CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create (*ast,
1281                                                              (TagDecl::TagKind)kind,
1282                                                              decl_ctx,  // What decl context do we use here? TU? The actual decl context?
1283                                                              SourceLocation(),
1284                                                              SourceLocation(),
1285                                                              &identifier_info);
1286
1287    for (size_t i=0, template_param_decl_count = template_param_decls.size();
1288         i < template_param_decl_count;
1289         ++i)
1290    {
1291        template_param_decls[i]->setDeclContext (template_cxx_decl);
1292    }
1293
1294    // With templated classes, we say that a class is templated with
1295    // specializations, but that the bare class has no functions.
1296    template_cxx_decl->startDefinition();
1297    template_cxx_decl->completeDefinition();
1298
1299    class_template_decl = ClassTemplateDecl::Create (*ast,
1300                                                     decl_ctx,  // What decl context do we use here? TU? The actual decl context?
1301                                                     SourceLocation(),
1302                                                     decl_name,
1303                                                     template_param_list,
1304                                                     template_cxx_decl,
1305                                                     NULL);
1306
1307    if (class_template_decl)
1308    {
1309        if (access_type != eAccessNone)
1310            class_template_decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1311
1312        //if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1313        //    CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1314
1315        decl_ctx->addDecl (class_template_decl);
1316
1317#ifdef LLDB_CONFIGURATION_DEBUG
1318        VerifyDecl(class_template_decl);
1319#endif
1320    }
1321
1322    return class_template_decl;
1323}
1324
1325
1326ClassTemplateSpecializationDecl *
1327ClangASTContext::CreateClassTemplateSpecializationDecl (DeclContext *decl_ctx,
1328                                                        ClassTemplateDecl *class_template_decl,
1329                                                        int kind,
1330                                                        const TemplateParameterInfos &template_param_infos)
1331{
1332    ASTContext *ast = getASTContext();
1333    ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::Create (*ast,
1334                                                                                                                   (TagDecl::TagKind)kind,
1335                                                                                                                   decl_ctx,
1336                                                                                                                   SourceLocation(),
1337                                                                                                                   SourceLocation(),
1338                                                                                                                   class_template_decl,
1339                                                                                                                   &template_param_infos.args.front(),
1340                                                                                                                   template_param_infos.args.size(),
1341                                                                                                                   NULL);
1342
1343    return class_template_specialization_decl;
1344}
1345
1346lldb::clang_type_t
1347ClangASTContext::CreateClassTemplateSpecializationType (ClassTemplateSpecializationDecl *class_template_specialization_decl)
1348{
1349    if (class_template_specialization_decl)
1350    {
1351        ASTContext *ast = getASTContext();
1352        if (ast)
1353            return ast->getTagDeclType(class_template_specialization_decl).getAsOpaquePtr();
1354    }
1355    return NULL;
1356}
1357
1358bool
1359ClangASTContext::SetHasExternalStorage (clang_type_t clang_type, bool has_extern)
1360{
1361    if (clang_type == NULL)
1362        return false;
1363
1364    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
1365
1366    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
1367    switch (type_class)
1368    {
1369    case clang::Type::Record:
1370        {
1371            CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
1372            if (cxx_record_decl)
1373            {
1374                cxx_record_decl->setHasExternalLexicalStorage (has_extern);
1375                cxx_record_decl->setHasExternalVisibleStorage (has_extern);
1376                return true;
1377            }
1378        }
1379        break;
1380
1381    case clang::Type::Enum:
1382        {
1383            EnumDecl *enum_decl = cast<EnumType>(qual_type)->getDecl();
1384            if (enum_decl)
1385            {
1386                enum_decl->setHasExternalLexicalStorage (has_extern);
1387                enum_decl->setHasExternalVisibleStorage (has_extern);
1388                return true;
1389            }
1390        }
1391        break;
1392
1393    case clang::Type::ObjCObject:
1394    case clang::Type::ObjCInterface:
1395        {
1396            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
1397            assert (objc_class_type);
1398            if (objc_class_type)
1399            {
1400                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
1401
1402                if (class_interface_decl)
1403                {
1404                    class_interface_decl->setHasExternalLexicalStorage (has_extern);
1405                    class_interface_decl->setHasExternalVisibleStorage (has_extern);
1406                    return true;
1407                }
1408            }
1409        }
1410        break;
1411
1412    case clang::Type::Typedef:
1413        return ClangASTContext::SetHasExternalStorage (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), has_extern);
1414
1415    case clang::Type::Elaborated:
1416        return ClangASTContext::SetHasExternalStorage (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), has_extern);
1417
1418    default:
1419        break;
1420    }
1421    return false;
1422}
1423
1424static bool
1425IsOperator (const char *name, OverloadedOperatorKind &op_kind)
1426{
1427    if (name == NULL || name[0] == '\0')
1428        return false;
1429
1430#define OPERATOR_PREFIX "operator"
1431#define OPERATOR_PREFIX_LENGTH (sizeof (OPERATOR_PREFIX) - 1)
1432
1433    const char *post_op_name = NULL;
1434
1435    bool no_space = true;
1436
1437    if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
1438        return false;
1439
1440    post_op_name = name + OPERATOR_PREFIX_LENGTH;
1441
1442    if (post_op_name[0] == ' ')
1443    {
1444        post_op_name++;
1445        no_space = false;
1446    }
1447
1448#undef OPERATOR_PREFIX
1449#undef OPERATOR_PREFIX_LENGTH
1450
1451    // This is an operator, set the overloaded operator kind to invalid
1452    // in case this is a conversion operator...
1453    op_kind = NUM_OVERLOADED_OPERATORS;
1454
1455    switch (post_op_name[0])
1456    {
1457    default:
1458        if (no_space)
1459            return false;
1460        break;
1461    case 'n':
1462        if (no_space)
1463            return false;
1464        if  (strcmp (post_op_name, "new") == 0)
1465            op_kind = OO_New;
1466        else if (strcmp (post_op_name, "new[]") == 0)
1467            op_kind = OO_Array_New;
1468        break;
1469
1470    case 'd':
1471        if (no_space)
1472            return false;
1473        if (strcmp (post_op_name, "delete") == 0)
1474            op_kind = OO_Delete;
1475        else if (strcmp (post_op_name, "delete[]") == 0)
1476            op_kind = OO_Array_Delete;
1477        break;
1478
1479    case '+':
1480        if (post_op_name[1] == '\0')
1481            op_kind = OO_Plus;
1482        else if (post_op_name[2] == '\0')
1483        {
1484            if (post_op_name[1] == '=')
1485                op_kind = OO_PlusEqual;
1486            else if (post_op_name[1] == '+')
1487                op_kind = OO_PlusPlus;
1488        }
1489        break;
1490
1491    case '-':
1492        if (post_op_name[1] == '\0')
1493            op_kind = OO_Minus;
1494        else if (post_op_name[2] == '\0')
1495        {
1496            switch (post_op_name[1])
1497            {
1498            case '=': op_kind = OO_MinusEqual; break;
1499            case '-': op_kind = OO_MinusMinus; break;
1500            case '>': op_kind = OO_Arrow; break;
1501            }
1502        }
1503        else if (post_op_name[3] == '\0')
1504        {
1505            if (post_op_name[2] == '*')
1506                op_kind = OO_ArrowStar; break;
1507        }
1508        break;
1509
1510    case '*':
1511        if (post_op_name[1] == '\0')
1512            op_kind = OO_Star;
1513        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1514            op_kind = OO_StarEqual;
1515        break;
1516
1517    case '/':
1518        if (post_op_name[1] == '\0')
1519            op_kind = OO_Slash;
1520        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1521            op_kind = OO_SlashEqual;
1522        break;
1523
1524    case '%':
1525        if (post_op_name[1] == '\0')
1526            op_kind = OO_Percent;
1527        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1528            op_kind = OO_PercentEqual;
1529        break;
1530
1531
1532    case '^':
1533        if (post_op_name[1] == '\0')
1534            op_kind = OO_Caret;
1535        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1536            op_kind = OO_CaretEqual;
1537        break;
1538
1539    case '&':
1540        if (post_op_name[1] == '\0')
1541            op_kind = OO_Amp;
1542        else if (post_op_name[2] == '\0')
1543        {
1544            switch (post_op_name[1])
1545            {
1546            case '=': op_kind = OO_AmpEqual; break;
1547            case '&': op_kind = OO_AmpAmp; break;
1548            }
1549        }
1550        break;
1551
1552    case '|':
1553        if (post_op_name[1] == '\0')
1554            op_kind = OO_Pipe;
1555        else if (post_op_name[2] == '\0')
1556        {
1557            switch (post_op_name[1])
1558            {
1559            case '=': op_kind = OO_PipeEqual; break;
1560            case '|': op_kind = OO_PipePipe; break;
1561            }
1562        }
1563        break;
1564
1565    case '~':
1566        if (post_op_name[1] == '\0')
1567            op_kind = OO_Tilde;
1568        break;
1569
1570    case '!':
1571        if (post_op_name[1] == '\0')
1572            op_kind = OO_Exclaim;
1573        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1574            op_kind = OO_ExclaimEqual;
1575        break;
1576
1577    case '=':
1578        if (post_op_name[1] == '\0')
1579            op_kind = OO_Equal;
1580        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1581            op_kind = OO_EqualEqual;
1582        break;
1583
1584    case '<':
1585        if (post_op_name[1] == '\0')
1586            op_kind = OO_Less;
1587        else if (post_op_name[2] == '\0')
1588        {
1589            switch (post_op_name[1])
1590            {
1591            case '<': op_kind = OO_LessLess; break;
1592            case '=': op_kind = OO_LessEqual; break;
1593            }
1594        }
1595        else if (post_op_name[3] == '\0')
1596        {
1597            if (post_op_name[2] == '=')
1598                op_kind = OO_LessLessEqual;
1599        }
1600        break;
1601
1602    case '>':
1603        if (post_op_name[1] == '\0')
1604            op_kind = OO_Greater;
1605        else if (post_op_name[2] == '\0')
1606        {
1607            switch (post_op_name[1])
1608            {
1609            case '>': op_kind = OO_GreaterGreater; break;
1610            case '=': op_kind = OO_GreaterEqual; break;
1611            }
1612        }
1613        else if (post_op_name[1] == '>' &&
1614                 post_op_name[2] == '=' &&
1615                 post_op_name[3] == '\0')
1616        {
1617                op_kind = OO_GreaterGreaterEqual;
1618        }
1619        break;
1620
1621    case ',':
1622        if (post_op_name[1] == '\0')
1623            op_kind = OO_Comma;
1624        break;
1625
1626    case '(':
1627        if (post_op_name[1] == ')' && post_op_name[2] == '\0')
1628            op_kind = OO_Call;
1629        break;
1630
1631    case '[':
1632        if (post_op_name[1] == ']' && post_op_name[2] == '\0')
1633            op_kind = OO_Subscript;
1634        break;
1635    }
1636
1637    return true;
1638}
1639
1640static inline bool
1641check_op_param (uint32_t op_kind, bool unary, bool binary, uint32_t num_params)
1642{
1643    // Special-case call since it can take any number of operands
1644    if(op_kind == OO_Call)
1645        return true;
1646
1647    // The parameter count doens't include "this"
1648    if (num_params == 0)
1649        return unary;
1650    if (num_params == 1)
1651        return binary;
1652    else
1653    return false;
1654}
1655
1656bool
1657ClangASTContext::CheckOverloadedOperatorKindParameterCount (uint32_t op_kind, uint32_t num_params)
1658{
1659    switch (op_kind)
1660    {
1661    default:
1662        break;
1663    // C++ standard allows any number of arguments to new/delete
1664    case OO_New:
1665    case OO_Array_New:
1666    case OO_Delete:
1667    case OO_Array_Delete:
1668        return true;
1669    }
1670
1671#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) case OO_##Name: return check_op_param (op_kind, Unary, Binary, num_params);
1672    switch (op_kind)
1673    {
1674#include "clang/Basic/OperatorKinds.def"
1675        default: break;
1676    }
1677    return false;
1678}
1679
1680CXXMethodDecl *
1681ClangASTContext::AddMethodToCXXRecordType
1682(
1683    ASTContext *ast,
1684    clang_type_t record_opaque_type,
1685    const char *name,
1686    clang_type_t method_opaque_type,
1687    lldb::AccessType access,
1688    bool is_virtual,
1689    bool is_static,
1690    bool is_inline,
1691    bool is_explicit,
1692    bool is_attr_used,
1693    bool is_artificial
1694)
1695{
1696    if (!record_opaque_type || !method_opaque_type || !name)
1697        return NULL;
1698
1699    assert(ast);
1700
1701    IdentifierTable *identifier_table = &ast->Idents;
1702
1703    assert(identifier_table);
1704
1705    QualType record_qual_type(QualType::getFromOpaquePtr(record_opaque_type));
1706
1707    CXXRecordDecl *cxx_record_decl = record_qual_type->getAsCXXRecordDecl();
1708
1709    if (cxx_record_decl == NULL)
1710        return NULL;
1711
1712    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
1713
1714    CXXMethodDecl *cxx_method_decl = NULL;
1715
1716    DeclarationName decl_name (&identifier_table->get(name));
1717
1718    const clang::FunctionType *function_Type = dyn_cast<FunctionType>(method_qual_type.getTypePtr());
1719
1720    if (function_Type == NULL)
1721        return NULL;
1722
1723    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(function_Type));
1724
1725    if (!method_function_prototype)
1726        return NULL;
1727
1728    unsigned int num_params = method_function_prototype->getNumArgs();
1729
1730    CXXDestructorDecl *cxx_dtor_decl(NULL);
1731    CXXConstructorDecl *cxx_ctor_decl(NULL);
1732
1733    if (name[0] == '~')
1734    {
1735        cxx_dtor_decl = CXXDestructorDecl::Create (*ast,
1736                                                   cxx_record_decl,
1737                                                   SourceLocation(),
1738                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXDestructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1739                                                   method_qual_type,
1740                                                   NULL,
1741                                                   is_inline,
1742                                                   is_artificial);
1743        cxx_method_decl = cxx_dtor_decl;
1744    }
1745    else if (decl_name == cxx_record_decl->getDeclName())
1746    {
1747       cxx_ctor_decl = CXXConstructorDecl::Create (*ast,
1748                                                   cxx_record_decl,
1749                                                   SourceLocation(),
1750                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXConstructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1751                                                   method_qual_type,
1752                                                   NULL, // TypeSourceInfo *
1753                                                   is_explicit,
1754                                                   is_inline,
1755                                                   is_artificial,
1756                                                   false /*is_constexpr*/);
1757        cxx_method_decl = cxx_ctor_decl;
1758    }
1759    else
1760    {
1761
1762        OverloadedOperatorKind op_kind = NUM_OVERLOADED_OPERATORS;
1763        if (IsOperator (name, op_kind))
1764        {
1765            if (op_kind != NUM_OVERLOADED_OPERATORS)
1766            {
1767                // Check the number of operator parameters. Sometimes we have
1768                // seen bad DWARF that doesn't correctly describe operators and
1769                // if we try to create a methed and add it to the class, clang
1770                // will assert and crash, so we need to make sure things are
1771                // acceptable.
1772                if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount (op_kind, num_params))
1773                    return NULL;
1774                cxx_method_decl = CXXMethodDecl::Create (*ast,
1775                                                         cxx_record_decl,
1776                                                         SourceLocation(),
1777                                                         DeclarationNameInfo (ast->DeclarationNames.getCXXOperatorName (op_kind), SourceLocation()),
1778                                                         method_qual_type,
1779                                                         NULL, // TypeSourceInfo *
1780                                                         is_static,
1781                                                         SC_None,
1782                                                         is_inline,
1783                                                         false /*is_constexpr*/,
1784                                                         SourceLocation());
1785            }
1786            else if (num_params == 0)
1787            {
1788                // Conversion operators don't take params...
1789                cxx_method_decl = CXXConversionDecl::Create (*ast,
1790                                                             cxx_record_decl,
1791                                                             SourceLocation(),
1792                                                             DeclarationNameInfo (ast->DeclarationNames.getCXXConversionFunctionName (ast->getCanonicalType (function_Type->getResultType())), SourceLocation()),
1793                                                             method_qual_type,
1794                                                             NULL, // TypeSourceInfo *
1795                                                             is_inline,
1796                                                             is_explicit,
1797                                                             false /*is_constexpr*/,
1798                                                             SourceLocation());
1799            }
1800        }
1801
1802        if (cxx_method_decl == NULL)
1803        {
1804            cxx_method_decl = CXXMethodDecl::Create (*ast,
1805                                                     cxx_record_decl,
1806                                                     SourceLocation(),
1807                                                     DeclarationNameInfo (decl_name, SourceLocation()),
1808                                                     method_qual_type,
1809                                                     NULL, // TypeSourceInfo *
1810                                                     is_static,
1811                                                     SC_None,
1812                                                     is_inline,
1813                                                     false /*is_constexpr*/,
1814                                                     SourceLocation());
1815        }
1816    }
1817
1818    AccessSpecifier access_specifier = ConvertAccessTypeToAccessSpecifier (access);
1819
1820    cxx_method_decl->setAccess (access_specifier);
1821    cxx_method_decl->setVirtualAsWritten (is_virtual);
1822
1823    if (is_attr_used)
1824        cxx_method_decl->addAttr(::new (*ast) UsedAttr(SourceRange(), *ast));
1825
1826    // Populate the method decl with parameter decls
1827
1828    llvm::SmallVector<ParmVarDecl *, 12> params;
1829
1830    for (int param_index = 0;
1831         param_index < num_params;
1832         ++param_index)
1833    {
1834        params.push_back (ParmVarDecl::Create (*ast,
1835                                               cxx_method_decl,
1836                                               SourceLocation(),
1837                                               SourceLocation(),
1838                                               NULL, // anonymous
1839                                               method_function_prototype->getArgType(param_index),
1840                                               NULL,
1841                                               SC_None,
1842                                               SC_None,
1843                                               NULL));
1844    }
1845
1846    cxx_method_decl->setParams (ArrayRef<ParmVarDecl*>(params));
1847
1848    cxx_record_decl->addDecl (cxx_method_decl);
1849
1850    // Sometimes the debug info will mention a constructor (default/copy/move),
1851    // destructor, or assignment operator (copy/move) but there won't be any
1852    // version of this in the code. So we check if the function was artificially
1853    // generated and if it is trivial and this lets the compiler/backend know
1854    // that it can inline the IR for these when it needs to and we can avoid a
1855    // "missing function" error when running expressions.
1856
1857    if (is_artificial)
1858    {
1859        if (cxx_ctor_decl &&
1860            ((cxx_ctor_decl->isDefaultConstructor() && cxx_record_decl->hasTrivialDefaultConstructor ()) ||
1861             (cxx_ctor_decl->isCopyConstructor()    && cxx_record_decl->hasTrivialCopyConstructor    ()) ||
1862             (cxx_ctor_decl->isMoveConstructor()    && cxx_record_decl->hasTrivialMoveConstructor    ()) ))
1863        {
1864            cxx_ctor_decl->setDefaulted();
1865            cxx_ctor_decl->setTrivial(true);
1866        }
1867        else if (cxx_dtor_decl)
1868        {
1869            if (cxx_record_decl->hasTrivialDestructor())
1870            {
1871                cxx_dtor_decl->setDefaulted();
1872                cxx_dtor_decl->setTrivial(true);
1873            }
1874        }
1875        else if ((cxx_method_decl->isCopyAssignmentOperator() && cxx_record_decl->hasTrivialCopyAssignment()) ||
1876                 (cxx_method_decl->isMoveAssignmentOperator() && cxx_record_decl->hasTrivialMoveAssignment()))
1877        {
1878            cxx_method_decl->setDefaulted();
1879            cxx_method_decl->setTrivial(true);
1880        }
1881    }
1882
1883#ifdef LLDB_CONFIGURATION_DEBUG
1884    VerifyDecl(cxx_method_decl);
1885#endif
1886
1887//    printf ("decl->isPolymorphic()             = %i\n", cxx_record_decl->isPolymorphic());
1888//    printf ("decl->isAggregate()               = %i\n", cxx_record_decl->isAggregate());
1889//    printf ("decl->isPOD()                     = %i\n", cxx_record_decl->isPOD());
1890//    printf ("decl->isEmpty()                   = %i\n", cxx_record_decl->isEmpty());
1891//    printf ("decl->isAbstract()                = %i\n", cxx_record_decl->isAbstract());
1892//    printf ("decl->hasTrivialConstructor()     = %i\n", cxx_record_decl->hasTrivialConstructor());
1893//    printf ("decl->hasTrivialCopyConstructor() = %i\n", cxx_record_decl->hasTrivialCopyConstructor());
1894//    printf ("decl->hasTrivialCopyAssignment()  = %i\n", cxx_record_decl->hasTrivialCopyAssignment());
1895//    printf ("decl->hasTrivialDestructor()      = %i\n", cxx_record_decl->hasTrivialDestructor());
1896    return cxx_method_decl;
1897}
1898
1899clang::FieldDecl *
1900ClangASTContext::AddFieldToRecordType
1901(
1902    ASTContext *ast,
1903    clang_type_t record_clang_type,
1904    const char *name,
1905    clang_type_t field_type,
1906    AccessType access,
1907    uint32_t bitfield_bit_size
1908)
1909{
1910    if (record_clang_type == NULL || field_type == NULL)
1911        return NULL;
1912
1913    FieldDecl *field = NULL;
1914    IdentifierTable *identifier_table = &ast->Idents;
1915
1916    assert (ast != NULL);
1917    assert (identifier_table != NULL);
1918
1919    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
1920
1921    const clang::Type *clang_type = record_qual_type.getTypePtr();
1922    if (clang_type)
1923    {
1924        const RecordType *record_type = dyn_cast<RecordType>(clang_type);
1925
1926        if (record_type)
1927        {
1928            RecordDecl *record_decl = record_type->getDecl();
1929
1930            clang::Expr *bit_width = NULL;
1931            if (bitfield_bit_size != 0)
1932            {
1933                APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
1934                bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
1935            }
1936            field = FieldDecl::Create (*ast,
1937                                                  record_decl,
1938                                                  SourceLocation(),
1939                                                  SourceLocation(),
1940                                                  name ? &identifier_table->get(name) : NULL, // Identifier
1941                                                  QualType::getFromOpaquePtr(field_type), // Field type
1942                                                  NULL,       // TInfo *
1943                                                  bit_width,  // BitWidth
1944                                                  false,      // Mutable
1945                                                  false);     // HasInit
1946
1947            field->setAccess (ConvertAccessTypeToAccessSpecifier (access));
1948
1949            if (field)
1950            {
1951                record_decl->addDecl(field);
1952
1953#ifdef LLDB_CONFIGURATION_DEBUG
1954                VerifyDecl(field);
1955#endif
1956            }
1957        }
1958        else
1959        {
1960            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(clang_type);
1961            if (objc_class_type)
1962            {
1963                bool is_synthesized = false;
1964                field = ClangASTContext::AddObjCClassIVar (ast,
1965                                                   record_clang_type,
1966                                                   name,
1967                                                   field_type,
1968                                                   access,
1969                                                   bitfield_bit_size,
1970                                                   is_synthesized);
1971            }
1972        }
1973    }
1974    return field;
1975}
1976
1977bool
1978ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
1979{
1980    return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
1981}
1982
1983bool
1984ClangASTContext::FieldIsBitfield
1985(
1986    ASTContext *ast,
1987    FieldDecl* field,
1988    uint32_t& bitfield_bit_size
1989)
1990{
1991    if (ast == NULL || field == NULL)
1992        return false;
1993
1994    if (field->isBitField())
1995    {
1996        Expr* bit_width_expr = field->getBitWidth();
1997        if (bit_width_expr)
1998        {
1999            llvm::APSInt bit_width_apsint;
2000            if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast))
2001            {
2002                bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
2003                return true;
2004            }
2005        }
2006    }
2007    return false;
2008}
2009
2010bool
2011ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
2012{
2013    if (record_decl == NULL)
2014        return false;
2015
2016    if (!record_decl->field_empty())
2017        return true;
2018
2019    // No fields, lets check this is a CXX record and check the base classes
2020    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2021    if (cxx_record_decl)
2022    {
2023        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2024        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2025             base_class != base_class_end;
2026             ++base_class)
2027        {
2028            const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
2029            if (RecordHasFields(base_class_decl))
2030                return true;
2031        }
2032    }
2033    return false;
2034}
2035
2036void
2037ClangASTContext::SetDefaultAccessForRecordFields (clang_type_t clang_type, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities)
2038{
2039    if (clang_type)
2040    {
2041        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2042
2043        const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
2044        if (record_type)
2045        {
2046            RecordDecl *record_decl = record_type->getDecl();
2047            if (record_decl)
2048            {
2049                uint32_t field_idx;
2050                RecordDecl::field_iterator field, field_end;
2051                for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0;
2052                     field != field_end;
2053                     ++field, ++field_idx)
2054                {
2055                    // If no accessibility was assigned, assign the correct one
2056                    if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none)
2057                        field->setAccess ((AccessSpecifier)default_accessibility);
2058                }
2059            }
2060        }
2061    }
2062}
2063
2064#pragma mark C++ Base Classes
2065
2066CXXBaseSpecifier *
2067ClangASTContext::CreateBaseClassSpecifier (clang_type_t base_class_type, AccessType access, bool is_virtual, bool base_of_class)
2068{
2069    if (base_class_type)
2070        return new CXXBaseSpecifier (SourceRange(),
2071                                     is_virtual,
2072                                     base_of_class,
2073                                     ConvertAccessTypeToAccessSpecifier (access),
2074                                     getASTContext()->CreateTypeSourceInfo (QualType::getFromOpaquePtr(base_class_type)),
2075                                     SourceLocation());
2076    return NULL;
2077}
2078
2079void
2080ClangASTContext::DeleteBaseClassSpecifiers (CXXBaseSpecifier **base_classes, unsigned num_base_classes)
2081{
2082    for (unsigned i=0; i<num_base_classes; ++i)
2083    {
2084        delete base_classes[i];
2085        base_classes[i] = NULL;
2086    }
2087}
2088
2089bool
2090ClangASTContext::SetBaseClassesForClassType (clang_type_t class_clang_type, CXXBaseSpecifier const * const *base_classes, unsigned num_base_classes)
2091{
2092    if (class_clang_type)
2093    {
2094        CXXRecordDecl *cxx_record_decl = QualType::getFromOpaquePtr(class_clang_type)->getAsCXXRecordDecl();
2095        if (cxx_record_decl)
2096        {
2097            cxx_record_decl->setBases(base_classes, num_base_classes);
2098            return true;
2099        }
2100    }
2101    return false;
2102}
2103#pragma mark Objective C Classes
2104
2105clang_type_t
2106ClangASTContext::CreateObjCClass
2107(
2108    const char *name,
2109    DeclContext *decl_ctx,
2110    bool isForwardDecl,
2111    bool isInternal
2112)
2113{
2114    ASTContext *ast = getASTContext();
2115    assert (ast != NULL);
2116    assert (name && name[0]);
2117    if (decl_ctx == NULL)
2118        decl_ctx = ast->getTranslationUnitDecl();
2119
2120    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
2121    // we will need to update this code. I was told to currently always use
2122    // the CXXRecordDecl class since we often don't know from debug information
2123    // if something is struct or a class, so we default to always use the more
2124    // complete definition just in case.
2125    ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast,
2126                                                         decl_ctx,
2127                                                         SourceLocation(),
2128                                                         &ast->Idents.get(name),
2129                                                         NULL,
2130                                                         SourceLocation(),
2131                                                         /*isForwardDecl,*/
2132                                                         isInternal);
2133
2134    return ast->getObjCInterfaceType(decl).getAsOpaquePtr();
2135}
2136
2137bool
2138ClangASTContext::SetObjCSuperClass (clang_type_t class_opaque_type, clang_type_t super_opaque_type)
2139{
2140    if (class_opaque_type && super_opaque_type)
2141    {
2142        QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2143        QualType super_qual_type(QualType::getFromOpaquePtr(super_opaque_type));
2144        const clang::Type *class_type = class_qual_type.getTypePtr();
2145        const clang::Type *super_type = super_qual_type.getTypePtr();
2146        if (class_type && super_type)
2147        {
2148            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2149            const ObjCObjectType *objc_super_type = dyn_cast<ObjCObjectType>(super_type);
2150            if (objc_class_type && objc_super_type)
2151            {
2152                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2153                ObjCInterfaceDecl *super_interface_decl = objc_super_type->getInterface();
2154                if (class_interface_decl && super_interface_decl)
2155                {
2156                    class_interface_decl->setSuperClass(super_interface_decl);
2157                    return true;
2158                }
2159            }
2160        }
2161    }
2162    return false;
2163}
2164
2165
2166FieldDecl *
2167ClangASTContext::AddObjCClassIVar
2168(
2169    ASTContext *ast,
2170    clang_type_t class_opaque_type,
2171    const char *name,
2172    clang_type_t ivar_opaque_type,
2173    AccessType access,
2174    uint32_t bitfield_bit_size,
2175    bool is_synthesized
2176)
2177{
2178    if (class_opaque_type == NULL || ivar_opaque_type == NULL)
2179        return NULL;
2180
2181    ObjCIvarDecl *field = NULL;
2182
2183    IdentifierTable *identifier_table = &ast->Idents;
2184
2185    assert (ast != NULL);
2186    assert (identifier_table != NULL);
2187
2188    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2189
2190    const clang::Type *class_type = class_qual_type.getTypePtr();
2191    if (class_type)
2192    {
2193        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2194
2195        if (objc_class_type)
2196        {
2197            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2198
2199            if (class_interface_decl)
2200            {
2201                clang::Expr *bit_width = NULL;
2202                if (bitfield_bit_size != 0)
2203                {
2204                    APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
2205                    bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
2206                }
2207
2208                field = ObjCIvarDecl::Create (*ast,
2209                                              class_interface_decl,
2210                                              SourceLocation(),
2211                                              SourceLocation(),
2212                                              &identifier_table->get(name), // Identifier
2213                                              QualType::getFromOpaquePtr(ivar_opaque_type), // Field type
2214                                              NULL, // TypeSourceInfo *
2215                                              ConvertAccessTypeToObjCIvarAccessControl (access),
2216                                              bit_width,
2217                                              is_synthesized);
2218
2219                if (field)
2220                {
2221                    class_interface_decl->addDecl(field);
2222
2223#ifdef LLDB_CONFIGURATION_DEBUG
2224                    VerifyDecl(field);
2225#endif
2226
2227                    return field;
2228                }
2229            }
2230        }
2231    }
2232    return NULL;
2233}
2234
2235bool
2236ClangASTContext::AddObjCClassProperty
2237(
2238    ASTContext *ast,
2239    clang_type_t class_opaque_type,
2240    const char *property_name,
2241    clang_type_t property_opaque_type,
2242    ObjCIvarDecl *ivar_decl,
2243    const char *property_setter_name,
2244    const char *property_getter_name,
2245    uint32_t property_attributes
2246)
2247{
2248    if (class_opaque_type == NULL || property_name == NULL || property_name[0] == '\0')
2249        return false;
2250
2251    IdentifierTable *identifier_table = &ast->Idents;
2252
2253    assert (ast != NULL);
2254    assert (identifier_table != NULL);
2255
2256    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2257    const clang::Type *class_type = class_qual_type.getTypePtr();
2258    if (class_type)
2259    {
2260        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2261
2262        if (objc_class_type)
2263        {
2264            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2265
2266            clang_type_t property_opaque_type_to_access;
2267
2268            if (property_opaque_type)
2269                property_opaque_type_to_access = property_opaque_type;
2270            else if (ivar_decl)
2271                property_opaque_type_to_access = ivar_decl->getType().getAsOpaquePtr();
2272
2273            // FIXME: For now, we don't know how to add properties if we don't have their associated ivar.
2274            if (class_interface_decl && property_opaque_type_to_access)
2275            {
2276                clang::TypeSourceInfo *prop_type_source;
2277                if (ivar_decl)
2278                    prop_type_source = ast->CreateTypeSourceInfo (ivar_decl->getType());
2279                else
2280                    prop_type_source = ast->CreateTypeSourceInfo (QualType::getFromOpaquePtr(property_opaque_type));
2281
2282                ObjCPropertyDecl *property_decl = ObjCPropertyDecl::Create(*ast,
2283                                                                           class_interface_decl,
2284                                                                           SourceLocation(), // Source Location
2285                                                                           &identifier_table->get(property_name),
2286                                                                           SourceLocation(), //Source Location for AT
2287                                                                           prop_type_source
2288                                                                           );
2289                if (property_decl)
2290                {
2291                    class_interface_decl->addDecl (property_decl);
2292
2293                    Selector setter_sel, getter_sel;
2294
2295                    if (property_setter_name != NULL)
2296                    {
2297                        std::string property_setter_no_colon(property_setter_name, strlen(property_setter_name) - 1);
2298                        clang::IdentifierInfo *setter_ident = &identifier_table->get(property_setter_no_colon.c_str());
2299                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2300                        property_decl->setSetterName(setter_sel);
2301                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_setter);
2302                    }
2303                    else if (!(property_attributes & DW_APPLE_PROPERTY_readonly))
2304                    {
2305                        std::string setter_sel_string("set");
2306                        setter_sel_string.push_back(::toupper(property_name[0]));
2307                        setter_sel_string.append(&property_name[1]);
2308                        clang::IdentifierInfo *setter_ident = &identifier_table->get(setter_sel_string.c_str());
2309                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2310                    }
2311
2312                    if (property_getter_name != NULL)
2313                    {
2314                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_getter_name);
2315                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2316                        property_decl->setGetterName(getter_sel);
2317                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_getter);
2318                    }
2319                    else
2320                    {
2321                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_name);
2322                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2323                    }
2324
2325                    if (ivar_decl)
2326                        property_decl->setPropertyIvarDecl (ivar_decl);
2327
2328                    if (property_attributes & DW_APPLE_PROPERTY_readonly)
2329                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readonly);
2330                    if (property_attributes & DW_APPLE_PROPERTY_readwrite)
2331                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readwrite);
2332                    if (property_attributes & DW_APPLE_PROPERTY_assign)
2333                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_assign);
2334                    if (property_attributes & DW_APPLE_PROPERTY_retain)
2335                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_retain);
2336                    if (property_attributes & DW_APPLE_PROPERTY_copy)
2337                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_copy);
2338                    if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
2339                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_nonatomic);
2340
2341                    if (!getter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(getter_sel))
2342                    {
2343                        QualType result_type = QualType::getFromOpaquePtr(property_opaque_type_to_access);
2344
2345                        const bool isInstance = true;
2346                        const bool isVariadic = false;
2347                        const bool isSynthesized = false;
2348                        const bool isImplicitlyDeclared = true;
2349                        const bool isDefined = false;
2350                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2351                        const bool HasRelatedResultType = false;
2352
2353                        ObjCMethodDecl *getter = ObjCMethodDecl::Create(*ast,
2354                                                                        SourceLocation(),
2355                                                                        SourceLocation(),
2356                                                                        getter_sel,
2357                                                                        result_type,
2358                                                                        NULL,
2359                                                                        class_interface_decl,
2360                                                                        isInstance,
2361                                                                        isVariadic,
2362                                                                        isSynthesized,
2363                                                                        isImplicitlyDeclared,
2364                                                                        isDefined,
2365                                                                        impControl,
2366                                                                        HasRelatedResultType);
2367
2368                        getter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(), ArrayRef<SourceLocation>());
2369
2370                        class_interface_decl->addDecl(getter);
2371                    }
2372
2373                    if (!setter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(setter_sel))
2374                    {
2375                        QualType result_type = ast->VoidTy;
2376
2377                        const bool isInstance = true;
2378                        const bool isVariadic = false;
2379                        const bool isSynthesized = false;
2380                        const bool isImplicitlyDeclared = true;
2381                        const bool isDefined = false;
2382                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2383                        const bool HasRelatedResultType = false;
2384
2385                        ObjCMethodDecl *setter = ObjCMethodDecl::Create(*ast,
2386                                                                        SourceLocation(),
2387                                                                        SourceLocation(),
2388                                                                        setter_sel,
2389                                                                        result_type,
2390                                                                        NULL,
2391                                                                        class_interface_decl,
2392                                                                        isInstance,
2393                                                                        isVariadic,
2394                                                                        isSynthesized,
2395                                                                        isImplicitlyDeclared,
2396                                                                        isDefined,
2397                                                                        impControl,
2398                                                                        HasRelatedResultType);
2399
2400                        llvm::SmallVector<ParmVarDecl *, 1> params;
2401
2402                        params.push_back (ParmVarDecl::Create (*ast,
2403                                                               setter,
2404                                                               SourceLocation(),
2405                                                               SourceLocation(),
2406                                                               NULL, // anonymous
2407                                                               QualType::getFromOpaquePtr(property_opaque_type_to_access),
2408                                                               NULL,
2409                                                               SC_Auto,
2410                                                               SC_Auto,
2411                                                               NULL));
2412
2413                        setter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2414
2415                        class_interface_decl->addDecl(setter);
2416                    }
2417
2418                    return true;
2419                }
2420            }
2421        }
2422    }
2423    return false;
2424}
2425
2426bool
2427ClangASTContext::ObjCTypeHasIVars (clang_type_t class_opaque_type, bool check_superclass)
2428{
2429    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2430
2431    const clang::Type *class_type = class_qual_type.getTypePtr();
2432    if (class_type)
2433    {
2434        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2435
2436        if (objc_class_type)
2437            return ObjCDeclHasIVars (objc_class_type->getInterface(), check_superclass);
2438    }
2439    return false;
2440}
2441
2442bool
2443ClangASTContext::ObjCDeclHasIVars (ObjCInterfaceDecl *class_interface_decl, bool check_superclass)
2444{
2445    while (class_interface_decl)
2446    {
2447        if (class_interface_decl->ivar_size() > 0)
2448            return true;
2449
2450        if (check_superclass)
2451            class_interface_decl = class_interface_decl->getSuperClass();
2452        else
2453            break;
2454    }
2455    return false;
2456}
2457
2458ObjCMethodDecl *
2459ClangASTContext::AddMethodToObjCObjectType
2460(
2461    ASTContext *ast,
2462    clang_type_t class_opaque_type,
2463    const char *name,  // the full symbol name as seen in the symbol table ("-[NString stringWithCString:]")
2464    clang_type_t method_opaque_type,
2465    lldb::AccessType access
2466)
2467{
2468    if (class_opaque_type == NULL || method_opaque_type == NULL)
2469        return NULL;
2470
2471    IdentifierTable *identifier_table = &ast->Idents;
2472
2473    assert (ast != NULL);
2474    assert (identifier_table != NULL);
2475
2476    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2477
2478    const clang::Type *class_type = class_qual_type.getTypePtr();
2479    if (class_type == NULL)
2480        return NULL;
2481
2482    const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2483
2484    if (objc_class_type == NULL)
2485        return NULL;
2486
2487    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2488
2489    if (class_interface_decl == NULL)
2490        return NULL;
2491
2492    const char *selector_start = ::strchr (name, ' ');
2493    if (selector_start == NULL)
2494        return NULL;
2495
2496    selector_start++;
2497    if (!(::isalpha (selector_start[0]) || selector_start[0] == '_'))
2498        return NULL;
2499    llvm::SmallVector<IdentifierInfo *, 12> selector_idents;
2500
2501    size_t len = 0;
2502    const char *start;
2503    //printf ("name = '%s'\n", name);
2504
2505    unsigned num_selectors_with_args = 0;
2506    for (start = selector_start;
2507         start && *start != '\0' && *start != ']';
2508         start += len)
2509    {
2510        len = ::strcspn(start, ":]");
2511        bool has_arg = (start[len] == ':');
2512        if (has_arg)
2513            ++num_selectors_with_args;
2514        selector_idents.push_back (&identifier_table->get (StringRef (start, len)));
2515        if (has_arg)
2516            len += 1;
2517    }
2518
2519
2520    if (selector_idents.size() == 0)
2521        return 0;
2522
2523    clang::Selector method_selector = ast->Selectors.getSelector (num_selectors_with_args ? selector_idents.size() : 0,
2524                                                                          selector_idents.data());
2525
2526    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
2527
2528    // Populate the method decl with parameter decls
2529    const clang::Type *method_type(method_qual_type.getTypePtr());
2530
2531    if (method_type == NULL)
2532        return NULL;
2533
2534    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(method_type));
2535
2536    if (!method_function_prototype)
2537        return NULL;
2538
2539
2540    bool is_variadic = false;
2541    bool is_synthesized = false;
2542    bool is_defined = false;
2543    ObjCMethodDecl::ImplementationControl imp_control = ObjCMethodDecl::None;
2544
2545    const unsigned num_args = method_function_prototype->getNumArgs();
2546
2547    ObjCMethodDecl *objc_method_decl = ObjCMethodDecl::Create (*ast,
2548                                                               SourceLocation(), // beginLoc,
2549                                                               SourceLocation(), // endLoc,
2550                                                               method_selector,
2551                                                               method_function_prototype->getResultType(),
2552                                                               NULL, // TypeSourceInfo *ResultTInfo,
2553                                                               GetDeclContextForType (class_opaque_type),
2554                                                               name[0] == '-',
2555                                                               is_variadic,
2556                                                               is_synthesized,
2557                                                               true, // is_implicitly_declared
2558                                                               is_defined,
2559                                                               imp_control,
2560                                                               false /*has_related_result_type*/);
2561
2562
2563    if (objc_method_decl == NULL)
2564        return NULL;
2565
2566    if (num_args > 0)
2567    {
2568        llvm::SmallVector<ParmVarDecl *, 12> params;
2569
2570        for (int param_index = 0; param_index < num_args; ++param_index)
2571        {
2572            params.push_back (ParmVarDecl::Create (*ast,
2573                                                   objc_method_decl,
2574                                                   SourceLocation(),
2575                                                   SourceLocation(),
2576                                                   NULL, // anonymous
2577                                                   method_function_prototype->getArgType(param_index),
2578                                                   NULL,
2579                                                   SC_Auto,
2580                                                   SC_Auto,
2581                                                   NULL));
2582        }
2583
2584        objc_method_decl->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2585    }
2586
2587    class_interface_decl->addDecl (objc_method_decl);
2588
2589#ifdef LLDB_CONFIGURATION_DEBUG
2590    VerifyDecl(objc_method_decl);
2591#endif
2592
2593    return objc_method_decl;
2594}
2595
2596size_t
2597ClangASTContext::GetNumTemplateArguments (clang::ASTContext *ast, clang_type_t clang_type)
2598{
2599    if (clang_type)
2600    {
2601        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2602
2603        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2604        switch (type_class)
2605        {
2606            case clang::Type::Record:
2607                if (GetCompleteQualType (ast, qual_type))
2608                {
2609                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2610                    if (cxx_record_decl)
2611                    {
2612                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2613                        if (template_decl)
2614                            return template_decl->getTemplateArgs().size();
2615                    }
2616                }
2617                break;
2618
2619            case clang::Type::Typedef:
2620                return ClangASTContext::GetNumTemplateArguments (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
2621            default:
2622                break;
2623        }
2624    }
2625    return 0;
2626}
2627
2628clang_type_t
2629ClangASTContext::GetTemplateArgument (clang::ASTContext *ast, clang_type_t clang_type, size_t arg_idx, lldb::TemplateArgumentKind &kind)
2630{
2631    if (clang_type)
2632    {
2633        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2634
2635        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2636        switch (type_class)
2637        {
2638            case clang::Type::Record:
2639                if (GetCompleteQualType (ast, qual_type))
2640                {
2641                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2642                    if (cxx_record_decl)
2643                    {
2644                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2645                        if (template_decl && arg_idx < template_decl->getTemplateArgs().size())
2646                        {
2647                            const TemplateArgument &template_arg = template_decl->getTemplateArgs()[arg_idx];
2648                            switch (template_arg.getKind())
2649                            {
2650                                case clang::TemplateArgument::Null:
2651                                    kind = eTemplateArgumentKindNull;
2652                                    return NULL;
2653
2654                                case clang::TemplateArgument::Type:
2655                                    kind = eTemplateArgumentKindType;
2656                                    return template_arg.getAsType().getAsOpaquePtr();
2657
2658                                case clang::TemplateArgument::Declaration:
2659                                    kind = eTemplateArgumentKindDeclaration;
2660                                    return NULL;
2661
2662                                case clang::TemplateArgument::Integral:
2663                                    kind = eTemplateArgumentKindIntegral;
2664                                    return template_arg.getIntegralType().getAsOpaquePtr();
2665
2666                                case clang::TemplateArgument::Template:
2667                                    kind = eTemplateArgumentKindTemplate;
2668                                    return NULL;
2669
2670                                case clang::TemplateArgument::TemplateExpansion:
2671                                    kind = eTemplateArgumentKindTemplateExpansion;
2672                                    return NULL;
2673
2674                                case clang::TemplateArgument::Expression:
2675                                    kind = eTemplateArgumentKindExpression;
2676                                    return NULL;
2677
2678                                case clang::TemplateArgument::Pack:
2679                                    kind = eTemplateArgumentKindPack;
2680                                    return NULL;
2681
2682                                default:
2683                                    assert (!"Unhandled TemplateArgument::ArgKind");
2684                                    kind = eTemplateArgumentKindNull;
2685                                    return NULL;
2686                            }
2687                        }
2688                    }
2689                }
2690                break;
2691
2692            case clang::Type::Typedef:
2693                return ClangASTContext::GetTemplateArgument (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), arg_idx, kind);
2694            default:
2695                break;
2696        }
2697    }
2698    kind = eTemplateArgumentKindNull;
2699    return NULL;
2700}
2701
2702uint32_t
2703ClangASTContext::GetTypeInfo
2704(
2705    clang_type_t clang_type,
2706    clang::ASTContext *ast,
2707    clang_type_t *pointee_or_element_clang_type
2708)
2709{
2710    if (clang_type == NULL)
2711        return 0;
2712
2713    if (pointee_or_element_clang_type)
2714        *pointee_or_element_clang_type = NULL;
2715
2716    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2717
2718    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2719    switch (type_class)
2720    {
2721    case clang::Type::Builtin:
2722        switch (cast<clang::BuiltinType>(qual_type)->getKind())
2723        {
2724        case clang::BuiltinType::ObjCId:
2725        case clang::BuiltinType::ObjCClass:
2726            if (ast && pointee_or_element_clang_type)
2727                *pointee_or_element_clang_type = ast->ObjCBuiltinClassTy.getAsOpaquePtr();
2728            return eTypeIsBuiltIn | eTypeIsPointer | eTypeHasValue;
2729                break;
2730        case clang::BuiltinType::Bool:
2731        case clang::BuiltinType::Char_U:
2732        case clang::BuiltinType::UChar:
2733        case clang::BuiltinType::WChar_U:
2734        case clang::BuiltinType::Char16:
2735        case clang::BuiltinType::Char32:
2736        case clang::BuiltinType::UShort:
2737        case clang::BuiltinType::UInt:
2738        case clang::BuiltinType::ULong:
2739        case clang::BuiltinType::ULongLong:
2740        case clang::BuiltinType::UInt128:
2741        case clang::BuiltinType::Char_S:
2742        case clang::BuiltinType::SChar:
2743        case clang::BuiltinType::WChar_S:
2744        case clang::BuiltinType::Short:
2745        case clang::BuiltinType::Int:
2746        case clang::BuiltinType::Long:
2747        case clang::BuiltinType::LongLong:
2748        case clang::BuiltinType::Int128:
2749        case clang::BuiltinType::Float:
2750        case clang::BuiltinType::Double:
2751        case clang::BuiltinType::LongDouble:
2752                return eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar;
2753        default:
2754            break;
2755        }
2756        return eTypeIsBuiltIn | eTypeHasValue;
2757
2758    case clang::Type::BlockPointer:
2759        if (pointee_or_element_clang_type)
2760            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2761        return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
2762
2763    case clang::Type::Complex:                          return eTypeIsBuiltIn | eTypeHasValue;
2764
2765    case clang::Type::ConstantArray:
2766    case clang::Type::DependentSizedArray:
2767    case clang::Type::IncompleteArray:
2768    case clang::Type::VariableArray:
2769        if (pointee_or_element_clang_type)
2770            *pointee_or_element_clang_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
2771        return eTypeHasChildren | eTypeIsArray;
2772
2773    case clang::Type::DependentName:                    return 0;
2774    case clang::Type::DependentSizedExtVector:          return eTypeHasChildren | eTypeIsVector;
2775    case clang::Type::DependentTemplateSpecialization:  return eTypeIsTemplate;
2776    case clang::Type::Decltype:                         return 0;
2777
2778    case clang::Type::Enum:
2779        if (pointee_or_element_clang_type)
2780            *pointee_or_element_clang_type = cast<EnumType>(qual_type)->getDecl()->getIntegerType().getAsOpaquePtr();
2781        return eTypeIsEnumeration | eTypeHasValue;
2782
2783    case clang::Type::Elaborated:
2784        return ClangASTContext::GetTypeInfo (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
2785                                             ast,
2786                                             pointee_or_element_clang_type);
2787    case clang::Type::ExtVector:                        return eTypeHasChildren | eTypeIsVector;
2788    case clang::Type::FunctionProto:                    return eTypeIsFuncPrototype | eTypeHasValue;
2789    case clang::Type::FunctionNoProto:                  return eTypeIsFuncPrototype | eTypeHasValue;
2790    case clang::Type::InjectedClassName:                return 0;
2791
2792    case clang::Type::LValueReference:
2793    case clang::Type::RValueReference:
2794        if (pointee_or_element_clang_type)
2795            *pointee_or_element_clang_type = cast<ReferenceType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr();
2796        return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
2797
2798    case clang::Type::MemberPointer:                    return eTypeIsPointer   | eTypeIsMember | eTypeHasValue;
2799
2800    case clang::Type::ObjCObjectPointer:
2801        if (pointee_or_element_clang_type)
2802            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2803        return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue;
2804
2805    case clang::Type::ObjCObject:                       return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
2806    case clang::Type::ObjCInterface:                    return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
2807
2808    case clang::Type::Pointer:
2809        if (pointee_or_element_clang_type)
2810            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2811        return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
2812
2813    case clang::Type::Record:
2814        if (qual_type->getAsCXXRecordDecl())
2815            return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
2816        else
2817            return eTypeHasChildren | eTypeIsStructUnion;
2818        break;
2819    case clang::Type::SubstTemplateTypeParm:            return eTypeIsTemplate;
2820    case clang::Type::TemplateTypeParm:                 return eTypeIsTemplate;
2821    case clang::Type::TemplateSpecialization:           return eTypeIsTemplate;
2822
2823    case clang::Type::Typedef:
2824        return eTypeIsTypedef | ClangASTContext::GetTypeInfo (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
2825                                                                  ast,
2826                                                                  pointee_or_element_clang_type);
2827
2828    case clang::Type::TypeOfExpr:                       return 0;
2829    case clang::Type::TypeOf:                           return 0;
2830    case clang::Type::UnresolvedUsing:                  return 0;
2831    case clang::Type::Vector:                           return eTypeHasChildren | eTypeIsVector;
2832    default:                                            return 0;
2833    }
2834    return 0;
2835}
2836
2837
2838#pragma mark Aggregate Types
2839
2840bool
2841ClangASTContext::IsAggregateType (clang_type_t clang_type)
2842{
2843    if (clang_type == NULL)
2844        return false;
2845
2846    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2847
2848    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2849    switch (type_class)
2850    {
2851    case clang::Type::IncompleteArray:
2852    case clang::Type::VariableArray:
2853    case clang::Type::ConstantArray:
2854    case clang::Type::ExtVector:
2855    case clang::Type::Vector:
2856    case clang::Type::Record:
2857    case clang::Type::ObjCObject:
2858    case clang::Type::ObjCInterface:
2859        return true;
2860    case clang::Type::Elaborated:
2861        return ClangASTContext::IsAggregateType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
2862    case clang::Type::Typedef:
2863        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
2864
2865    default:
2866        break;
2867    }
2868    // The clang type does have a value
2869    return false;
2870}
2871
2872uint32_t
2873ClangASTContext::GetNumChildren (clang::ASTContext *ast, clang_type_t clang_type, bool omit_empty_base_classes)
2874{
2875    if (clang_type == NULL)
2876        return 0;
2877
2878    uint32_t num_children = 0;
2879    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2880    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2881    switch (type_class)
2882    {
2883    case clang::Type::Builtin:
2884        switch (cast<clang::BuiltinType>(qual_type)->getKind())
2885        {
2886        case clang::BuiltinType::ObjCId:    // child is Class
2887        case clang::BuiltinType::ObjCClass: // child is Class
2888            num_children = 1;
2889            break;
2890
2891        default:
2892            break;
2893        }
2894        break;
2895
2896    case clang::Type::Complex: return 0;
2897
2898    case clang::Type::Record:
2899        if (GetCompleteQualType (ast, qual_type))
2900        {
2901            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
2902            const RecordDecl *record_decl = record_type->getDecl();
2903            assert(record_decl);
2904            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2905            if (cxx_record_decl)
2906            {
2907                if (omit_empty_base_classes)
2908                {
2909                    // Check each base classes to see if it or any of its
2910                    // base classes contain any fields. This can help
2911                    // limit the noise in variable views by not having to
2912                    // show base classes that contain no members.
2913                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2914                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2915                         base_class != base_class_end;
2916                         ++base_class)
2917                    {
2918                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
2919
2920                        // Skip empty base classes
2921                        if (RecordHasFields(base_class_decl) == false)
2922                            continue;
2923
2924                        num_children++;
2925                    }
2926                }
2927                else
2928                {
2929                    // Include all base classes
2930                    num_children += cxx_record_decl->getNumBases();
2931                }
2932
2933            }
2934            RecordDecl::field_iterator field, field_end;
2935            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
2936                ++num_children;
2937        }
2938        break;
2939
2940    case clang::Type::ObjCObject:
2941    case clang::Type::ObjCInterface:
2942        if (GetCompleteQualType (ast, qual_type))
2943        {
2944            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
2945            assert (objc_class_type);
2946            if (objc_class_type)
2947            {
2948                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2949
2950                if (class_interface_decl)
2951                {
2952
2953                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
2954                    if (superclass_interface_decl)
2955                    {
2956                        if (omit_empty_base_classes)
2957                        {
2958                            if (ClangASTContext::ObjCDeclHasIVars (superclass_interface_decl, true))
2959                                ++num_children;
2960                        }
2961                        else
2962                            ++num_children;
2963                    }
2964
2965                    num_children += class_interface_decl->ivar_size();
2966                }
2967            }
2968        }
2969        break;
2970
2971    case clang::Type::ObjCObjectPointer:
2972        {
2973            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(qual_type.getTypePtr());
2974            QualType pointee_type = pointer_type->getPointeeType();
2975            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
2976                                                                             pointee_type.getAsOpaquePtr(),
2977                                                                             omit_empty_base_classes);
2978            // If this type points to a simple type, then it has 1 child
2979            if (num_pointee_children == 0)
2980                num_children = 1;
2981            else
2982                num_children = num_pointee_children;
2983        }
2984        break;
2985
2986    case clang::Type::ConstantArray:
2987        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
2988        break;
2989
2990    case clang::Type::Pointer:
2991        {
2992            const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
2993            QualType pointee_type (pointer_type->getPointeeType());
2994            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
2995                                                                             pointee_type.getAsOpaquePtr(),
2996                                                                             omit_empty_base_classes);
2997            if (num_pointee_children == 0)
2998            {
2999                // We have a pointer to a pointee type that claims it has no children.
3000                // We will want to look at
3001                num_children = ClangASTContext::GetNumPointeeChildren (pointee_type.getAsOpaquePtr());
3002            }
3003            else
3004                num_children = num_pointee_children;
3005        }
3006        break;
3007
3008    case clang::Type::LValueReference:
3009    case clang::Type::RValueReference:
3010        {
3011            const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
3012            QualType pointee_type = reference_type->getPointeeType();
3013            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3014                                                                             pointee_type.getAsOpaquePtr(),
3015                                                                             omit_empty_base_classes);
3016            // If this type points to a simple type, then it has 1 child
3017            if (num_pointee_children == 0)
3018                num_children = 1;
3019            else
3020                num_children = num_pointee_children;
3021        }
3022        break;
3023
3024
3025    case clang::Type::Typedef:
3026        num_children = ClangASTContext::GetNumChildren (ast,
3027                                                        cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3028                                                        omit_empty_base_classes);
3029        break;
3030
3031    case clang::Type::Elaborated:
3032        num_children = ClangASTContext::GetNumChildren (ast,
3033                                                        cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3034                                                        omit_empty_base_classes);
3035        break;
3036
3037    default:
3038        break;
3039    }
3040    return num_children;
3041}
3042
3043uint32_t
3044ClangASTContext::GetNumDirectBaseClasses (clang::ASTContext *ast, clang_type_t clang_type)
3045{
3046    if (clang_type == NULL)
3047        return 0;
3048
3049    uint32_t count = 0;
3050    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3051    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3052    switch (type_class)
3053    {
3054        case clang::Type::Record:
3055            if (GetCompleteQualType (ast, qual_type))
3056            {
3057                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3058                if (cxx_record_decl)
3059                    count = cxx_record_decl->getNumBases();
3060            }
3061            break;
3062
3063        case clang::Type::ObjCObject:
3064        case clang::Type::ObjCInterface:
3065            if (GetCompleteQualType (ast, qual_type))
3066            {
3067                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3068                if (objc_class_type)
3069                {
3070                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3071
3072                    if (class_interface_decl && class_interface_decl->getSuperClass())
3073                        count = 1;
3074                }
3075            }
3076            break;
3077
3078
3079        case clang::Type::Typedef:
3080            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3081            break;
3082
3083        case clang::Type::Elaborated:
3084            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3085            break;
3086
3087        default:
3088            break;
3089    }
3090    return count;
3091}
3092
3093uint32_t
3094ClangASTContext::GetNumVirtualBaseClasses (clang::ASTContext *ast,
3095                                           clang_type_t clang_type)
3096{
3097    if (clang_type == NULL)
3098        return 0;
3099
3100    uint32_t count = 0;
3101    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3102    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3103    switch (type_class)
3104    {
3105        case clang::Type::Record:
3106            if (GetCompleteQualType (ast, qual_type))
3107            {
3108                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3109                if (cxx_record_decl)
3110                    count = cxx_record_decl->getNumVBases();
3111            }
3112            break;
3113
3114        case clang::Type::Typedef:
3115            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3116            break;
3117
3118        case clang::Type::Elaborated:
3119            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3120            break;
3121
3122        default:
3123            break;
3124    }
3125    return count;
3126}
3127
3128uint32_t
3129ClangASTContext::GetNumFields (clang::ASTContext *ast, clang_type_t clang_type)
3130{
3131    if (clang_type == NULL)
3132        return 0;
3133
3134    uint32_t count = 0;
3135    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3136    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3137    switch (type_class)
3138    {
3139        case clang::Type::Record:
3140            if (GetCompleteQualType (ast, qual_type))
3141            {
3142                const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
3143                if (record_type)
3144                {
3145                    RecordDecl *record_decl = record_type->getDecl();
3146                    if (record_decl)
3147                    {
3148                        uint32_t field_idx = 0;
3149                        RecordDecl::field_iterator field, field_end;
3150                        for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3151                            ++field_idx;
3152                        count = field_idx;
3153                    }
3154                }
3155            }
3156            break;
3157
3158        case clang::Type::Typedef:
3159            count = ClangASTContext::GetNumFields (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3160            break;
3161
3162        case clang::Type::Elaborated:
3163            count = ClangASTContext::GetNumFields (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3164            break;
3165
3166        case clang::Type::ObjCObject:
3167        case clang::Type::ObjCInterface:
3168            if (GetCompleteQualType (ast, qual_type))
3169            {
3170                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3171                if (objc_class_type)
3172                {
3173                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3174
3175                    if (class_interface_decl)
3176                        count = class_interface_decl->ivar_size();
3177                }
3178            }
3179            break;
3180
3181        default:
3182            break;
3183    }
3184    return count;
3185}
3186
3187clang_type_t
3188ClangASTContext::GetDirectBaseClassAtIndex (clang::ASTContext *ast,
3189                                            clang_type_t clang_type,
3190                                            uint32_t idx,
3191                                            uint32_t *bit_offset_ptr)
3192{
3193    if (clang_type == NULL)
3194        return 0;
3195
3196    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3197    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3198    switch (type_class)
3199    {
3200        case clang::Type::Record:
3201            if (GetCompleteQualType (ast, qual_type))
3202            {
3203                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3204                if (cxx_record_decl)
3205                {
3206                    uint32_t curr_idx = 0;
3207                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3208                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3209                         base_class != base_class_end;
3210                         ++base_class, ++curr_idx)
3211                    {
3212                        if (curr_idx == idx)
3213                        {
3214                            if (bit_offset_ptr)
3215                            {
3216                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3217                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3218//                                if (base_class->isVirtual())
3219//                                    *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3220//                                else
3221                                    *bit_offset_ptr = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3222                            }
3223                            return base_class->getType().getAsOpaquePtr();
3224                        }
3225                    }
3226                }
3227            }
3228            break;
3229
3230        case clang::Type::ObjCObject:
3231        case clang::Type::ObjCInterface:
3232            if (idx == 0 && GetCompleteQualType (ast, qual_type))
3233            {
3234                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3235                if (objc_class_type)
3236                {
3237                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3238
3239                    if (class_interface_decl)
3240                    {
3241                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3242                        if (superclass_interface_decl)
3243                        {
3244                            if (bit_offset_ptr)
3245                                *bit_offset_ptr = 0;
3246                            return ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr();
3247                        }
3248                    }
3249                }
3250            }
3251            break;
3252
3253
3254        case clang::Type::Typedef:
3255            return ClangASTContext::GetDirectBaseClassAtIndex (ast,
3256                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3257                                                               idx,
3258                                                               bit_offset_ptr);
3259
3260        case clang::Type::Elaborated:
3261            return  ClangASTContext::GetDirectBaseClassAtIndex (ast,
3262                                                                cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3263                                                                idx,
3264                                                                bit_offset_ptr);
3265
3266        default:
3267            break;
3268    }
3269    return NULL;
3270}
3271
3272clang_type_t
3273ClangASTContext::GetVirtualBaseClassAtIndex (clang::ASTContext *ast,
3274                                             clang_type_t clang_type,
3275                                             uint32_t idx,
3276                                             uint32_t *bit_offset_ptr)
3277{
3278    if (clang_type == NULL)
3279        return 0;
3280
3281    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3282    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3283    switch (type_class)
3284    {
3285        case clang::Type::Record:
3286            if (GetCompleteQualType (ast, qual_type))
3287            {
3288                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3289                if (cxx_record_decl)
3290                {
3291                    uint32_t curr_idx = 0;
3292                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3293                    for (base_class = cxx_record_decl->vbases_begin(), base_class_end = cxx_record_decl->vbases_end();
3294                         base_class != base_class_end;
3295                         ++base_class, ++curr_idx)
3296                    {
3297                        if (curr_idx == idx)
3298                        {
3299                            if (bit_offset_ptr)
3300                            {
3301                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3302                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3303                                *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3304
3305                            }
3306                            return base_class->getType().getAsOpaquePtr();
3307                        }
3308                    }
3309                }
3310            }
3311            break;
3312
3313        case clang::Type::Typedef:
3314            return ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3315                                                                cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3316                                                                idx,
3317                                                                bit_offset_ptr);
3318
3319        case clang::Type::Elaborated:
3320            return  ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3321                                                                 cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3322                                                                 idx,
3323                                                                 bit_offset_ptr);
3324
3325        default:
3326            break;
3327    }
3328    return NULL;
3329}
3330
3331clang_type_t
3332ClangASTContext::GetFieldAtIndex (clang::ASTContext *ast,
3333                                  clang_type_t clang_type,
3334                                  uint32_t idx,
3335                                  std::string& name,
3336                                  uint32_t *bit_offset_ptr)
3337{
3338    if (clang_type == NULL)
3339        return 0;
3340
3341    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3342    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3343    switch (type_class)
3344    {
3345        case clang::Type::Record:
3346            if (GetCompleteQualType (ast, qual_type))
3347            {
3348                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3349                const RecordDecl *record_decl = record_type->getDecl();
3350                uint32_t field_idx = 0;
3351                RecordDecl::field_iterator field, field_end;
3352                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx)
3353                {
3354                    if (idx == field_idx)
3355                    {
3356                        // Print the member type if requested
3357                        // Print the member name and equal sign
3358                        name.assign(field->getNameAsString());
3359
3360                        // Figure out the type byte size (field_type_info.first) and
3361                        // alignment (field_type_info.second) from the AST context.
3362                        if (bit_offset_ptr)
3363                        {
3364                            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3365                            *bit_offset_ptr = record_layout.getFieldOffset (field_idx);
3366                        }
3367
3368                        return field->getType().getAsOpaquePtr();
3369                    }
3370                }
3371            }
3372            break;
3373
3374        case clang::Type::ObjCObject:
3375        case clang::Type::ObjCInterface:
3376            if (GetCompleteQualType (ast, qual_type))
3377            {
3378                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3379                assert (objc_class_type);
3380                if (objc_class_type)
3381                {
3382                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3383
3384                    if (class_interface_decl)
3385                    {
3386                        if (idx < (class_interface_decl->ivar_size()))
3387                        {
3388                            ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
3389                            uint32_t ivar_idx = 0;
3390
3391                            for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++ivar_idx)
3392                            {
3393                                if (ivar_idx == idx)
3394                                {
3395                                    const ObjCIvarDecl* ivar_decl = *ivar_pos;
3396
3397                                    QualType ivar_qual_type(ivar_decl->getType());
3398
3399                                    name.assign(ivar_decl->getNameAsString());
3400
3401                                    if (bit_offset_ptr)
3402                                    {
3403                                        const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
3404                                        *bit_offset_ptr = interface_layout.getFieldOffset (ivar_idx);
3405                                    }
3406
3407                                    return ivar_qual_type.getAsOpaquePtr();
3408                                }
3409                            }
3410                        }
3411                    }
3412                }
3413            }
3414            break;
3415
3416
3417        case clang::Type::Typedef:
3418            return ClangASTContext::GetFieldAtIndex (ast,
3419                                                     cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3420                                                     idx,
3421                                                     name,
3422                                                     bit_offset_ptr);
3423
3424        case clang::Type::Elaborated:
3425            return  ClangASTContext::GetFieldAtIndex (ast,
3426                                                      cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3427                                                      idx,
3428                                                      name,
3429                                                      bit_offset_ptr);
3430
3431        default:
3432            break;
3433    }
3434    return NULL;
3435}
3436
3437
3438// If a pointer to a pointee type (the clang_type arg) says that it has no
3439// children, then we either need to trust it, or override it and return a
3440// different result. For example, an "int *" has one child that is an integer,
3441// but a function pointer doesn't have any children. Likewise if a Record type
3442// claims it has no children, then there really is nothing to show.
3443uint32_t
3444ClangASTContext::GetNumPointeeChildren (clang_type_t clang_type)
3445{
3446    if (clang_type == NULL)
3447        return 0;
3448
3449    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3450    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3451    switch (type_class)
3452    {
3453    case clang::Type::Builtin:
3454        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3455        {
3456        case clang::BuiltinType::UnknownAny:
3457        case clang::BuiltinType::Void:
3458        case clang::BuiltinType::NullPtr:
3459            return 0;
3460        case clang::BuiltinType::Bool:
3461        case clang::BuiltinType::Char_U:
3462        case clang::BuiltinType::UChar:
3463        case clang::BuiltinType::WChar_U:
3464        case clang::BuiltinType::Char16:
3465        case clang::BuiltinType::Char32:
3466        case clang::BuiltinType::UShort:
3467        case clang::BuiltinType::UInt:
3468        case clang::BuiltinType::ULong:
3469        case clang::BuiltinType::ULongLong:
3470        case clang::BuiltinType::UInt128:
3471        case clang::BuiltinType::Char_S:
3472        case clang::BuiltinType::SChar:
3473        case clang::BuiltinType::WChar_S:
3474        case clang::BuiltinType::Short:
3475        case clang::BuiltinType::Int:
3476        case clang::BuiltinType::Long:
3477        case clang::BuiltinType::LongLong:
3478        case clang::BuiltinType::Int128:
3479        case clang::BuiltinType::Float:
3480        case clang::BuiltinType::Double:
3481        case clang::BuiltinType::LongDouble:
3482        case clang::BuiltinType::Dependent:
3483        case clang::BuiltinType::Overload:
3484        case clang::BuiltinType::ObjCId:
3485        case clang::BuiltinType::ObjCClass:
3486        case clang::BuiltinType::ObjCSel:
3487        case clang::BuiltinType::BoundMember:
3488        case clang::BuiltinType::Half:
3489        case clang::BuiltinType::ARCUnbridgedCast:
3490        case clang::BuiltinType::PseudoObject:
3491            return 1;
3492        }
3493        break;
3494
3495    case clang::Type::Complex:                  return 1;
3496    case clang::Type::Pointer:                  return 1;
3497    case clang::Type::BlockPointer:             return 0;   // If block pointers don't have debug info, then no children for them
3498    case clang::Type::LValueReference:          return 1;
3499    case clang::Type::RValueReference:          return 1;
3500    case clang::Type::MemberPointer:            return 0;
3501    case clang::Type::ConstantArray:            return 0;
3502    case clang::Type::IncompleteArray:          return 0;
3503    case clang::Type::VariableArray:            return 0;
3504    case clang::Type::DependentSizedArray:      return 0;
3505    case clang::Type::DependentSizedExtVector:  return 0;
3506    case clang::Type::Vector:                   return 0;
3507    case clang::Type::ExtVector:                return 0;
3508    case clang::Type::FunctionProto:            return 0;   // When we function pointers, they have no children...
3509    case clang::Type::FunctionNoProto:          return 0;   // When we function pointers, they have no children...
3510    case clang::Type::UnresolvedUsing:          return 0;
3511    case clang::Type::Paren:                    return 0;
3512    case clang::Type::Typedef:                  return ClangASTContext::GetNumPointeeChildren (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3513    case clang::Type::Elaborated:               return ClangASTContext::GetNumPointeeChildren (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3514    case clang::Type::TypeOfExpr:               return 0;
3515    case clang::Type::TypeOf:                   return 0;
3516    case clang::Type::Decltype:                 return 0;
3517    case clang::Type::Record:                   return 0;
3518    case clang::Type::Enum:                     return 1;
3519    case clang::Type::TemplateTypeParm:         return 1;
3520    case clang::Type::SubstTemplateTypeParm:    return 1;
3521    case clang::Type::TemplateSpecialization:   return 1;
3522    case clang::Type::InjectedClassName:        return 0;
3523    case clang::Type::DependentName:            return 1;
3524    case clang::Type::DependentTemplateSpecialization:  return 1;
3525    case clang::Type::ObjCObject:               return 0;
3526    case clang::Type::ObjCInterface:            return 0;
3527    case clang::Type::ObjCObjectPointer:        return 1;
3528    default:
3529        break;
3530    }
3531    return 0;
3532}
3533
3534clang_type_t
3535ClangASTContext::GetChildClangTypeAtIndex
3536(
3537    ExecutionContext *exe_ctx,
3538    const char *parent_name,
3539    clang_type_t parent_clang_type,
3540    uint32_t idx,
3541    bool transparent_pointers,
3542    bool omit_empty_base_classes,
3543    bool ignore_array_bounds,
3544    std::string& child_name,
3545    uint32_t &child_byte_size,
3546    int32_t &child_byte_offset,
3547    uint32_t &child_bitfield_bit_size,
3548    uint32_t &child_bitfield_bit_offset,
3549    bool &child_is_base_class,
3550    bool &child_is_deref_of_parent
3551)
3552{
3553    if (parent_clang_type)
3554
3555        return GetChildClangTypeAtIndex (exe_ctx,
3556                                         getASTContext(),
3557                                         parent_name,
3558                                         parent_clang_type,
3559                                         idx,
3560                                         transparent_pointers,
3561                                         omit_empty_base_classes,
3562                                         ignore_array_bounds,
3563                                         child_name,
3564                                         child_byte_size,
3565                                         child_byte_offset,
3566                                         child_bitfield_bit_size,
3567                                         child_bitfield_bit_offset,
3568                                         child_is_base_class,
3569                                         child_is_deref_of_parent);
3570    return NULL;
3571}
3572
3573clang_type_t
3574ClangASTContext::GetChildClangTypeAtIndex
3575(
3576    ExecutionContext *exe_ctx,
3577    ASTContext *ast,
3578    const char *parent_name,
3579    clang_type_t parent_clang_type,
3580    uint32_t idx,
3581    bool transparent_pointers,
3582    bool omit_empty_base_classes,
3583    bool ignore_array_bounds,
3584    std::string& child_name,
3585    uint32_t &child_byte_size,
3586    int32_t &child_byte_offset,
3587    uint32_t &child_bitfield_bit_size,
3588    uint32_t &child_bitfield_bit_offset,
3589    bool &child_is_base_class,
3590    bool &child_is_deref_of_parent
3591)
3592{
3593    if (parent_clang_type == NULL)
3594        return NULL;
3595
3596    if (idx < ClangASTContext::GetNumChildren (ast, parent_clang_type, omit_empty_base_classes))
3597    {
3598        uint32_t bit_offset;
3599        child_bitfield_bit_size = 0;
3600        child_bitfield_bit_offset = 0;
3601        child_is_base_class = false;
3602        QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
3603        const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass();
3604        switch (parent_type_class)
3605        {
3606        case clang::Type::Builtin:
3607            switch (cast<clang::BuiltinType>(parent_qual_type)->getKind())
3608            {
3609            case clang::BuiltinType::ObjCId:
3610            case clang::BuiltinType::ObjCClass:
3611                child_name = "isa";
3612                child_byte_size = ast->getTypeSize(ast->ObjCBuiltinClassTy) / CHAR_BIT;
3613                return ast->ObjCBuiltinClassTy.getAsOpaquePtr();
3614
3615            default:
3616                break;
3617            }
3618            break;
3619
3620        case clang::Type::Record:
3621            if (GetCompleteQualType (ast, parent_qual_type))
3622            {
3623                const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
3624                const RecordDecl *record_decl = record_type->getDecl();
3625                assert(record_decl);
3626                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3627                uint32_t child_idx = 0;
3628
3629                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3630                if (cxx_record_decl)
3631                {
3632                    // We might have base classes to print out first
3633                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3634                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3635                         base_class != base_class_end;
3636                         ++base_class)
3637                    {
3638                        const CXXRecordDecl *base_class_decl = NULL;
3639
3640                        // Skip empty base classes
3641                        if (omit_empty_base_classes)
3642                        {
3643                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3644                            if (RecordHasFields(base_class_decl) == false)
3645                                continue;
3646                        }
3647
3648                        if (idx == child_idx)
3649                        {
3650                            if (base_class_decl == NULL)
3651                                base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3652
3653
3654                            if (base_class->isVirtual())
3655                                bit_offset = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3656                            else
3657                                bit_offset = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3658
3659                            // Base classes should be a multiple of 8 bits in size
3660                            child_byte_offset = bit_offset/8;
3661
3662                            child_name = ClangASTType::GetTypeNameForQualType(base_class->getType());
3663
3664                            uint64_t clang_type_info_bit_size = ast->getTypeSize(base_class->getType());
3665
3666                            // Base classes bit sizes should be a multiple of 8 bits in size
3667                            assert (clang_type_info_bit_size % 8 == 0);
3668                            child_byte_size = clang_type_info_bit_size / 8;
3669                            child_is_base_class = true;
3670                            return base_class->getType().getAsOpaquePtr();
3671                        }
3672                        // We don't increment the child index in the for loop since we might
3673                        // be skipping empty base classes
3674                        ++child_idx;
3675                    }
3676                }
3677                // Make sure index is in range...
3678                uint32_t field_idx = 0;
3679                RecordDecl::field_iterator field, field_end;
3680                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
3681                {
3682                    if (idx == child_idx)
3683                    {
3684                        // Print the member type if requested
3685                        // Print the member name and equal sign
3686                        child_name.assign(field->getNameAsString().c_str());
3687
3688                        // Figure out the type byte size (field_type_info.first) and
3689                        // alignment (field_type_info.second) from the AST context.
3690                        std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(field->getType());
3691                        assert(field_idx < record_layout.getFieldCount());
3692
3693                        child_byte_size = field_type_info.first / 8;
3694
3695                        // Figure out the field offset within the current struct/union/class type
3696                        bit_offset = record_layout.getFieldOffset (field_idx);
3697                        child_byte_offset = bit_offset / 8;
3698                        if (ClangASTContext::FieldIsBitfield (ast, *field, child_bitfield_bit_size))
3699                            child_bitfield_bit_offset = bit_offset % 8;
3700
3701                        return field->getType().getAsOpaquePtr();
3702                    }
3703                }
3704            }
3705            break;
3706
3707        case clang::Type::ObjCObject:
3708        case clang::Type::ObjCInterface:
3709            if (GetCompleteQualType (ast, parent_qual_type))
3710            {
3711                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(parent_qual_type.getTypePtr());
3712                assert (objc_class_type);
3713                if (objc_class_type)
3714                {
3715                    uint32_t child_idx = 0;
3716                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3717
3718                    if (class_interface_decl)
3719                    {
3720
3721                        const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
3722                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3723                        if (superclass_interface_decl)
3724                        {
3725                            if (omit_empty_base_classes)
3726                            {
3727                                if (ClangASTContext::GetNumChildren(ast, ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(), omit_empty_base_classes) > 0)
3728                                {
3729                                    if (idx == 0)
3730                                    {
3731                                        QualType ivar_qual_type(ast->getObjCInterfaceType(superclass_interface_decl));
3732
3733
3734                                        child_name.assign(superclass_interface_decl->getNameAsString().c_str());
3735
3736                                        std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
3737
3738                                        child_byte_size = ivar_type_info.first / 8;
3739                                        child_byte_offset = 0;
3740                                        child_is_base_class = true;
3741
3742                                        return ivar_qual_type.getAsOpaquePtr();
3743                                    }
3744
3745                                    ++child_idx;
3746                                }
3747                            }
3748                            else
3749                                ++child_idx;
3750                        }
3751
3752                        const uint32_t superclass_idx = child_idx;
3753
3754                        if (idx < (child_idx + class_interface_decl->ivar_size()))
3755                        {
3756                            ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
3757
3758                            for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
3759                            {
3760                                if (child_idx == idx)
3761                                {
3762                                    ObjCIvarDecl* ivar_decl = *ivar_pos;
3763
3764                                    QualType ivar_qual_type(ivar_decl->getType());
3765
3766                                    child_name.assign(ivar_decl->getNameAsString().c_str());
3767
3768                                    std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
3769
3770                                    child_byte_size = ivar_type_info.first / 8;
3771
3772                                    // Figure out the field offset within the current struct/union/class type
3773                                    // For ObjC objects, we can't trust the bit offset we get from the Clang AST, since
3774                                    // that doesn't account for the space taken up by unbacked properties, or from
3775                                    // the changing size of base classes that are newer than this class.
3776                                    // So if we have a process around that we can ask about this object, do so.
3777                                    child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
3778                                    Process *process = NULL;
3779                                    if (exe_ctx)
3780                                        process = exe_ctx->GetProcessPtr();
3781                                    if (process)
3782                                    {
3783                                        ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime();
3784                                        if (objc_runtime != NULL)
3785                                        {
3786                                            ClangASTType parent_ast_type (ast, parent_qual_type.getAsOpaquePtr());
3787                                            child_byte_offset = objc_runtime->GetByteOffsetForIvar (parent_ast_type, ivar_decl->getNameAsString().c_str());
3788                                        }
3789                                    }
3790
3791                                    // Setting this to UINT32_MAX to make sure we don't compute it twice...
3792                                    bit_offset = UINT32_MAX;
3793
3794                                    if (child_byte_offset == LLDB_INVALID_IVAR_OFFSET)
3795                                    {
3796                                        bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
3797                                        child_byte_offset = bit_offset / 8;
3798                                    }
3799
3800                                    // Note, the ObjC Ivar Byte offset is just that, it doesn't account for the bit offset
3801                                    // of a bitfield within its containing object.  So regardless of where we get the byte
3802                                    // offset from, we still need to get the bit offset for bitfields from the layout.
3803
3804                                    if (ClangASTContext::FieldIsBitfield (ast, ivar_decl, child_bitfield_bit_size))
3805                                    {
3806                                        if (bit_offset == UINT32_MAX)
3807                                            bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
3808
3809                                        child_bitfield_bit_offset = bit_offset % 8;
3810                                    }
3811                                    return ivar_qual_type.getAsOpaquePtr();
3812                                }
3813                                ++child_idx;
3814                            }
3815                        }
3816                    }
3817                }
3818            }
3819            break;
3820
3821        case clang::Type::ObjCObjectPointer:
3822            {
3823                const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(parent_qual_type.getTypePtr());
3824                QualType pointee_type = pointer_type->getPointeeType();
3825
3826                if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
3827                {
3828                    child_is_deref_of_parent = false;
3829                    bool tmp_child_is_deref_of_parent = false;
3830                    return GetChildClangTypeAtIndex (exe_ctx,
3831                                                     ast,
3832                                                     parent_name,
3833                                                     pointer_type->getPointeeType().getAsOpaquePtr(),
3834                                                     idx,
3835                                                     transparent_pointers,
3836                                                     omit_empty_base_classes,
3837                                                     ignore_array_bounds,
3838                                                     child_name,
3839                                                     child_byte_size,
3840                                                     child_byte_offset,
3841                                                     child_bitfield_bit_size,
3842                                                     child_bitfield_bit_offset,
3843                                                     child_is_base_class,
3844                                                     tmp_child_is_deref_of_parent);
3845                }
3846                else
3847                {
3848                    child_is_deref_of_parent = true;
3849                    if (parent_name)
3850                    {
3851                        child_name.assign(1, '*');
3852                        child_name += parent_name;
3853                    }
3854
3855                    // We have a pointer to an simple type
3856                    if (idx == 0 && GetCompleteQualType(ast, pointee_type))
3857                    {
3858                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
3859                        assert(clang_type_info.first % 8 == 0);
3860                        child_byte_size = clang_type_info.first / 8;
3861                        child_byte_offset = 0;
3862                        return pointee_type.getAsOpaquePtr();
3863                    }
3864                }
3865            }
3866            break;
3867
3868        case clang::Type::ConstantArray:
3869            {
3870                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
3871                const uint64_t element_count = array->getSize().getLimitedValue();
3872
3873                if (ignore_array_bounds || idx < element_count)
3874                {
3875                    if (GetCompleteQualType (ast, array->getElementType()))
3876                    {
3877                        std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
3878
3879                        char element_name[64];
3880                        ::snprintf (element_name, sizeof (element_name), "[%u]", idx);
3881
3882                        child_name.assign(element_name);
3883                        assert(field_type_info.first % 8 == 0);
3884                        child_byte_size = field_type_info.first / 8;
3885                        child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
3886                        return array->getElementType().getAsOpaquePtr();
3887                    }
3888                }
3889            }
3890            break;
3891
3892        case clang::Type::Pointer:
3893            {
3894                const PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
3895                QualType pointee_type = pointer_type->getPointeeType();
3896
3897                // Don't dereference "void *" pointers
3898                if (pointee_type->isVoidType())
3899                    return NULL;
3900
3901                if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
3902                {
3903                    child_is_deref_of_parent = false;
3904                    bool tmp_child_is_deref_of_parent = false;
3905                    return GetChildClangTypeAtIndex (exe_ctx,
3906                                                     ast,
3907                                                     parent_name,
3908                                                     pointer_type->getPointeeType().getAsOpaquePtr(),
3909                                                     idx,
3910                                                     transparent_pointers,
3911                                                     omit_empty_base_classes,
3912                                                     ignore_array_bounds,
3913                                                     child_name,
3914                                                     child_byte_size,
3915                                                     child_byte_offset,
3916                                                     child_bitfield_bit_size,
3917                                                     child_bitfield_bit_offset,
3918                                                     child_is_base_class,
3919                                                     tmp_child_is_deref_of_parent);
3920                }
3921                else
3922                {
3923                    child_is_deref_of_parent = true;
3924
3925                    if (parent_name)
3926                    {
3927                        child_name.assign(1, '*');
3928                        child_name += parent_name;
3929                    }
3930
3931                    // We have a pointer to an simple type
3932                    if (idx == 0)
3933                    {
3934                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
3935                        assert(clang_type_info.first % 8 == 0);
3936                        child_byte_size = clang_type_info.first / 8;
3937                        child_byte_offset = 0;
3938                        return pointee_type.getAsOpaquePtr();
3939                    }
3940                }
3941            }
3942            break;
3943
3944        case clang::Type::LValueReference:
3945        case clang::Type::RValueReference:
3946            {
3947                const ReferenceType *reference_type = cast<ReferenceType>(parent_qual_type.getTypePtr());
3948                QualType pointee_type(reference_type->getPointeeType());
3949                clang_type_t pointee_clang_type = pointee_type.getAsOpaquePtr();
3950                if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_clang_type))
3951                {
3952                    child_is_deref_of_parent = false;
3953                    bool tmp_child_is_deref_of_parent = false;
3954                    return GetChildClangTypeAtIndex (exe_ctx,
3955                                                     ast,
3956                                                     parent_name,
3957                                                     pointee_clang_type,
3958                                                     idx,
3959                                                     transparent_pointers,
3960                                                     omit_empty_base_classes,
3961                                                     ignore_array_bounds,
3962                                                     child_name,
3963                                                     child_byte_size,
3964                                                     child_byte_offset,
3965                                                     child_bitfield_bit_size,
3966                                                     child_bitfield_bit_offset,
3967                                                     child_is_base_class,
3968                                                     tmp_child_is_deref_of_parent);
3969                }
3970                else
3971                {
3972                    if (parent_name)
3973                    {
3974                        child_name.assign(1, '&');
3975                        child_name += parent_name;
3976                    }
3977
3978                    // We have a pointer to an simple type
3979                    if (idx == 0)
3980                    {
3981                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
3982                        assert(clang_type_info.first % 8 == 0);
3983                        child_byte_size = clang_type_info.first / 8;
3984                        child_byte_offset = 0;
3985                        return pointee_type.getAsOpaquePtr();
3986                    }
3987                }
3988            }
3989            break;
3990
3991        case clang::Type::Typedef:
3992            return GetChildClangTypeAtIndex (exe_ctx,
3993                                             ast,
3994                                             parent_name,
3995                                             cast<TypedefType>(parent_qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3996                                             idx,
3997                                             transparent_pointers,
3998                                             omit_empty_base_classes,
3999                                             ignore_array_bounds,
4000                                             child_name,
4001                                             child_byte_size,
4002                                             child_byte_offset,
4003                                             child_bitfield_bit_size,
4004                                             child_bitfield_bit_offset,
4005                                             child_is_base_class,
4006                                             child_is_deref_of_parent);
4007            break;
4008
4009        case clang::Type::Elaborated:
4010            return GetChildClangTypeAtIndex (exe_ctx,
4011                                             ast,
4012                                             parent_name,
4013                                             cast<ElaboratedType>(parent_qual_type)->getNamedType().getAsOpaquePtr(),
4014                                             idx,
4015                                             transparent_pointers,
4016                                             omit_empty_base_classes,
4017                                             ignore_array_bounds,
4018                                             child_name,
4019                                             child_byte_size,
4020                                             child_byte_offset,
4021                                             child_bitfield_bit_size,
4022                                             child_bitfield_bit_offset,
4023                                             child_is_base_class,
4024                                             child_is_deref_of_parent);
4025
4026        default:
4027            break;
4028        }
4029    }
4030    return NULL;
4031}
4032
4033static inline bool
4034BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
4035{
4036    return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
4037}
4038
4039static uint32_t
4040GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
4041{
4042    uint32_t num_bases = 0;
4043    if (cxx_record_decl)
4044    {
4045        if (omit_empty_base_classes)
4046        {
4047            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4048            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4049                 base_class != base_class_end;
4050                 ++base_class)
4051            {
4052                // Skip empty base classes
4053                if (omit_empty_base_classes)
4054                {
4055                    if (BaseSpecifierIsEmpty (base_class))
4056                        continue;
4057                }
4058                ++num_bases;
4059            }
4060        }
4061        else
4062            num_bases = cxx_record_decl->getNumBases();
4063    }
4064    return num_bases;
4065}
4066
4067
4068static uint32_t
4069GetIndexForRecordBase
4070(
4071    const RecordDecl *record_decl,
4072    const CXXBaseSpecifier *base_spec,
4073    bool omit_empty_base_classes
4074)
4075{
4076    uint32_t child_idx = 0;
4077
4078    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4079
4080//    const char *super_name = record_decl->getNameAsCString();
4081//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
4082//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
4083//
4084    if (cxx_record_decl)
4085    {
4086        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4087        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4088             base_class != base_class_end;
4089             ++base_class)
4090        {
4091            if (omit_empty_base_classes)
4092            {
4093                if (BaseSpecifierIsEmpty (base_class))
4094                    continue;
4095            }
4096
4097//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
4098//                    child_idx,
4099//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4100//
4101//
4102            if (base_class == base_spec)
4103                return child_idx;
4104            ++child_idx;
4105        }
4106    }
4107
4108    return UINT32_MAX;
4109}
4110
4111
4112static uint32_t
4113GetIndexForRecordChild
4114(
4115    const RecordDecl *record_decl,
4116    NamedDecl *canonical_decl,
4117    bool omit_empty_base_classes
4118)
4119{
4120    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
4121
4122//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4123//
4124////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
4125//    if (cxx_record_decl)
4126//    {
4127//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4128//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4129//             base_class != base_class_end;
4130//             ++base_class)
4131//        {
4132//            if (omit_empty_base_classes)
4133//            {
4134//                if (BaseSpecifierIsEmpty (base_class))
4135//                    continue;
4136//            }
4137//
4138////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
4139////                    record_decl->getNameAsCString(),
4140////                    canonical_decl->getNameAsCString(),
4141////                    child_idx,
4142////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4143//
4144//
4145//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4146//            if (curr_base_class_decl == canonical_decl)
4147//            {
4148//                return child_idx;
4149//            }
4150//            ++child_idx;
4151//        }
4152//    }
4153//
4154//    const uint32_t num_bases = child_idx;
4155    RecordDecl::field_iterator field, field_end;
4156    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4157         field != field_end;
4158         ++field, ++child_idx)
4159    {
4160//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
4161//                    record_decl->getNameAsCString(),
4162//                    canonical_decl->getNameAsCString(),
4163//                    child_idx - num_bases,
4164//                    field->getNameAsCString());
4165
4166        if (field->getCanonicalDecl() == canonical_decl)
4167            return child_idx;
4168    }
4169
4170    return UINT32_MAX;
4171}
4172
4173// Look for a child member (doesn't include base classes, but it does include
4174// their members) in the type hierarchy. Returns an index path into "clang_type"
4175// on how to reach the appropriate member.
4176//
4177//    class A
4178//    {
4179//    public:
4180//        int m_a;
4181//        int m_b;
4182//    };
4183//
4184//    class B
4185//    {
4186//    };
4187//
4188//    class C :
4189//        public B,
4190//        public A
4191//    {
4192//    };
4193//
4194// If we have a clang type that describes "class C", and we wanted to looked
4195// "m_b" in it:
4196//
4197// With omit_empty_base_classes == false we would get an integer array back with:
4198// { 1,  1 }
4199// The first index 1 is the child index for "class A" within class C
4200// The second index 1 is the child index for "m_b" within class A
4201//
4202// With omit_empty_base_classes == true we would get an integer array back with:
4203// { 0,  1 }
4204// 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)
4205// The second index 1 is the child index for "m_b" within class A
4206
4207size_t
4208ClangASTContext::GetIndexOfChildMemberWithName
4209(
4210    ASTContext *ast,
4211    clang_type_t clang_type,
4212    const char *name,
4213    bool omit_empty_base_classes,
4214    std::vector<uint32_t>& child_indexes
4215)
4216{
4217    if (clang_type && name && name[0])
4218    {
4219        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4220        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4221        switch (type_class)
4222        {
4223        case clang::Type::Record:
4224            if (GetCompleteQualType (ast, qual_type))
4225            {
4226                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4227                const RecordDecl *record_decl = record_type->getDecl();
4228
4229                assert(record_decl);
4230                uint32_t child_idx = 0;
4231
4232                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4233
4234                // Try and find a field that matches NAME
4235                RecordDecl::field_iterator field, field_end;
4236                StringRef name_sref(name);
4237                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4238                     field != field_end;
4239                     ++field, ++child_idx)
4240                {
4241                    if (field->getName().equals (name_sref))
4242                    {
4243                        // We have to add on the number of base classes to this index!
4244                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
4245                        return child_indexes.size();
4246                    }
4247                }
4248
4249                if (cxx_record_decl)
4250                {
4251                    const RecordDecl *parent_record_decl = cxx_record_decl;
4252
4253                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
4254
4255                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
4256                    // Didn't find things easily, lets let clang do its thang...
4257                    IdentifierInfo & ident_ref = ast->Idents.get(name_sref);
4258                    DeclarationName decl_name(&ident_ref);
4259
4260                    CXXBasePaths paths;
4261                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
4262                                                       decl_name.getAsOpaquePtr(),
4263                                                       paths))
4264                    {
4265                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
4266                        for (path = paths.begin(); path != path_end; ++path)
4267                        {
4268                            const size_t num_path_elements = path->size();
4269                            for (size_t e=0; e<num_path_elements; ++e)
4270                            {
4271                                CXXBasePathElement elem = (*path)[e];
4272
4273                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
4274                                if (child_idx == UINT32_MAX)
4275                                {
4276                                    child_indexes.clear();
4277                                    return 0;
4278                                }
4279                                else
4280                                {
4281                                    child_indexes.push_back (child_idx);
4282                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
4283                                }
4284                            }
4285                            DeclContext::lookup_iterator named_decl_pos;
4286                            for (named_decl_pos = path->Decls.first;
4287                                 named_decl_pos != path->Decls.second && parent_record_decl;
4288                                 ++named_decl_pos)
4289                            {
4290                                //printf ("path[%zu] = %s\n", child_indexes.size(), (*named_decl_pos)->getNameAsCString());
4291
4292                                child_idx = GetIndexForRecordChild (parent_record_decl, *named_decl_pos, omit_empty_base_classes);
4293                                if (child_idx == UINT32_MAX)
4294                                {
4295                                    child_indexes.clear();
4296                                    return 0;
4297                                }
4298                                else
4299                                {
4300                                    child_indexes.push_back (child_idx);
4301                                }
4302                            }
4303                        }
4304                        return child_indexes.size();
4305                    }
4306                }
4307
4308            }
4309            break;
4310
4311        case clang::Type::ObjCObject:
4312        case clang::Type::ObjCInterface:
4313            if (GetCompleteQualType (ast, qual_type))
4314            {
4315                StringRef name_sref(name);
4316                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4317                assert (objc_class_type);
4318                if (objc_class_type)
4319                {
4320                    uint32_t child_idx = 0;
4321                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4322
4323                    if (class_interface_decl)
4324                    {
4325                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4326                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4327
4328                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4329                        {
4330                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4331
4332                            if (ivar_decl->getName().equals (name_sref))
4333                            {
4334                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4335                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4336                                    ++child_idx;
4337
4338                                child_indexes.push_back (child_idx);
4339                                return child_indexes.size();
4340                            }
4341                        }
4342
4343                        if (superclass_interface_decl)
4344                        {
4345                            // The super class index is always zero for ObjC classes,
4346                            // so we push it onto the child indexes in case we find
4347                            // an ivar in our superclass...
4348                            child_indexes.push_back (0);
4349
4350                            if (GetIndexOfChildMemberWithName (ast,
4351                                                               ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(),
4352                                                               name,
4353                                                               omit_empty_base_classes,
4354                                                               child_indexes))
4355                            {
4356                                // We did find an ivar in a superclass so just
4357                                // return the results!
4358                                return child_indexes.size();
4359                            }
4360
4361                            // We didn't find an ivar matching "name" in our
4362                            // superclass, pop the superclass zero index that
4363                            // we pushed on above.
4364                            child_indexes.pop_back();
4365                        }
4366                    }
4367                }
4368            }
4369            break;
4370
4371        case clang::Type::ObjCObjectPointer:
4372            {
4373                return GetIndexOfChildMemberWithName (ast,
4374                                                      cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4375                                                      name,
4376                                                      omit_empty_base_classes,
4377                                                      child_indexes);
4378            }
4379            break;
4380
4381
4382        case clang::Type::ConstantArray:
4383            {
4384//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4385//                const uint64_t element_count = array->getSize().getLimitedValue();
4386//
4387//                if (idx < element_count)
4388//                {
4389//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4390//
4391//                    char element_name[32];
4392//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4393//
4394//                    child_name.assign(element_name);
4395//                    assert(field_type_info.first % 8 == 0);
4396//                    child_byte_size = field_type_info.first / 8;
4397//                    child_byte_offset = idx * child_byte_size;
4398//                    return array->getElementType().getAsOpaquePtr();
4399//                }
4400            }
4401            break;
4402
4403//        case clang::Type::MemberPointerType:
4404//            {
4405//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4406//                QualType pointee_type = mem_ptr_type->getPointeeType();
4407//
4408//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4409//                {
4410//                    return GetIndexOfChildWithName (ast,
4411//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4412//                                                    name);
4413//                }
4414//            }
4415//            break;
4416//
4417        case clang::Type::LValueReference:
4418        case clang::Type::RValueReference:
4419            {
4420                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4421                QualType pointee_type = reference_type->getPointeeType();
4422
4423                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4424                {
4425                    return GetIndexOfChildMemberWithName (ast,
4426                                                          reference_type->getPointeeType().getAsOpaquePtr(),
4427                                                          name,
4428                                                          omit_empty_base_classes,
4429                                                          child_indexes);
4430                }
4431            }
4432            break;
4433
4434        case clang::Type::Pointer:
4435            {
4436                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4437                QualType pointee_type = pointer_type->getPointeeType();
4438
4439                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4440                {
4441                    return GetIndexOfChildMemberWithName (ast,
4442                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
4443                                                          name,
4444                                                          omit_empty_base_classes,
4445                                                          child_indexes);
4446                }
4447                else
4448                {
4449//                    if (parent_name)
4450//                    {
4451//                        child_name.assign(1, '*');
4452//                        child_name += parent_name;
4453//                    }
4454//
4455//                    // We have a pointer to an simple type
4456//                    if (idx == 0)
4457//                    {
4458//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4459//                        assert(clang_type_info.first % 8 == 0);
4460//                        child_byte_size = clang_type_info.first / 8;
4461//                        child_byte_offset = 0;
4462//                        return pointee_type.getAsOpaquePtr();
4463//                    }
4464                }
4465            }
4466            break;
4467
4468        case clang::Type::Typedef:
4469            return GetIndexOfChildMemberWithName (ast,
4470                                                  cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4471                                                  name,
4472                                                  omit_empty_base_classes,
4473                                                  child_indexes);
4474
4475        default:
4476            break;
4477        }
4478    }
4479    return 0;
4480}
4481
4482
4483// Get the index of the child of "clang_type" whose name matches. This function
4484// doesn't descend into the children, but only looks one level deep and name
4485// matches can include base class names.
4486
4487uint32_t
4488ClangASTContext::GetIndexOfChildWithName
4489(
4490    ASTContext *ast,
4491    clang_type_t clang_type,
4492    const char *name,
4493    bool omit_empty_base_classes
4494)
4495{
4496    if (clang_type && name && name[0])
4497    {
4498        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4499
4500        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4501
4502        switch (type_class)
4503        {
4504        case clang::Type::Record:
4505            if (GetCompleteQualType (ast, qual_type))
4506            {
4507                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4508                const RecordDecl *record_decl = record_type->getDecl();
4509
4510                assert(record_decl);
4511                uint32_t child_idx = 0;
4512
4513                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4514
4515                if (cxx_record_decl)
4516                {
4517                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4518                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4519                         base_class != base_class_end;
4520                         ++base_class)
4521                    {
4522                        // Skip empty base classes
4523                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4524                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
4525                            continue;
4526
4527                        std::string base_class_type_name (ClangASTType::GetTypeNameForQualType(base_class->getType()));
4528                        if (base_class_type_name.compare (name) == 0)
4529                            return child_idx;
4530                        ++child_idx;
4531                    }
4532                }
4533
4534                // Try and find a field that matches NAME
4535                RecordDecl::field_iterator field, field_end;
4536                StringRef name_sref(name);
4537                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4538                     field != field_end;
4539                     ++field, ++child_idx)
4540                {
4541                    if (field->getName().equals (name_sref))
4542                        return child_idx;
4543                }
4544
4545            }
4546            break;
4547
4548        case clang::Type::ObjCObject:
4549        case clang::Type::ObjCInterface:
4550            if (GetCompleteQualType (ast, qual_type))
4551            {
4552                StringRef name_sref(name);
4553                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4554                assert (objc_class_type);
4555                if (objc_class_type)
4556                {
4557                    uint32_t child_idx = 0;
4558                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4559
4560                    if (class_interface_decl)
4561                    {
4562                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4563                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4564
4565                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
4566                        {
4567                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4568
4569                            if (ivar_decl->getName().equals (name_sref))
4570                            {
4571                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4572                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4573                                    ++child_idx;
4574
4575                                return child_idx;
4576                            }
4577                        }
4578
4579                        if (superclass_interface_decl)
4580                        {
4581                            if (superclass_interface_decl->getName().equals (name_sref))
4582                                return 0;
4583                        }
4584                    }
4585                }
4586            }
4587            break;
4588
4589        case clang::Type::ObjCObjectPointer:
4590            {
4591                return GetIndexOfChildWithName (ast,
4592                                                cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4593                                                name,
4594                                                omit_empty_base_classes);
4595            }
4596            break;
4597
4598        case clang::Type::ConstantArray:
4599            {
4600//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4601//                const uint64_t element_count = array->getSize().getLimitedValue();
4602//
4603//                if (idx < element_count)
4604//                {
4605//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4606//
4607//                    char element_name[32];
4608//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4609//
4610//                    child_name.assign(element_name);
4611//                    assert(field_type_info.first % 8 == 0);
4612//                    child_byte_size = field_type_info.first / 8;
4613//                    child_byte_offset = idx * child_byte_size;
4614//                    return array->getElementType().getAsOpaquePtr();
4615//                }
4616            }
4617            break;
4618
4619//        case clang::Type::MemberPointerType:
4620//            {
4621//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4622//                QualType pointee_type = mem_ptr_type->getPointeeType();
4623//
4624//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4625//                {
4626//                    return GetIndexOfChildWithName (ast,
4627//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4628//                                                    name);
4629//                }
4630//            }
4631//            break;
4632//
4633        case clang::Type::LValueReference:
4634        case clang::Type::RValueReference:
4635            {
4636                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4637                QualType pointee_type = reference_type->getPointeeType();
4638
4639                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4640                {
4641                    return GetIndexOfChildWithName (ast,
4642                                                    reference_type->getPointeeType().getAsOpaquePtr(),
4643                                                    name,
4644                                                    omit_empty_base_classes);
4645                }
4646            }
4647            break;
4648
4649        case clang::Type::Pointer:
4650            {
4651                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4652                QualType pointee_type = pointer_type->getPointeeType();
4653
4654                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4655                {
4656                    return GetIndexOfChildWithName (ast,
4657                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
4658                                                    name,
4659                                                    omit_empty_base_classes);
4660                }
4661                else
4662                {
4663//                    if (parent_name)
4664//                    {
4665//                        child_name.assign(1, '*');
4666//                        child_name += parent_name;
4667//                    }
4668//
4669//                    // We have a pointer to an simple type
4670//                    if (idx == 0)
4671//                    {
4672//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4673//                        assert(clang_type_info.first % 8 == 0);
4674//                        child_byte_size = clang_type_info.first / 8;
4675//                        child_byte_offset = 0;
4676//                        return pointee_type.getAsOpaquePtr();
4677//                    }
4678                }
4679            }
4680            break;
4681
4682        case clang::Type::Typedef:
4683            return GetIndexOfChildWithName (ast,
4684                                            cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4685                                            name,
4686                                            omit_empty_base_classes);
4687
4688        default:
4689            break;
4690        }
4691    }
4692    return UINT32_MAX;
4693}
4694
4695#pragma mark TagType
4696
4697bool
4698ClangASTContext::SetTagTypeKind (clang_type_t tag_clang_type, int kind)
4699{
4700    if (tag_clang_type)
4701    {
4702        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
4703        const clang::Type *clang_type = tag_qual_type.getTypePtr();
4704        if (clang_type)
4705        {
4706            const TagType *tag_type = dyn_cast<TagType>(clang_type);
4707            if (tag_type)
4708            {
4709                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
4710                if (tag_decl)
4711                {
4712                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
4713                    return true;
4714                }
4715            }
4716        }
4717    }
4718    return false;
4719}
4720
4721
4722#pragma mark DeclContext Functions
4723
4724DeclContext *
4725ClangASTContext::GetDeclContextForType (clang_type_t clang_type)
4726{
4727    if (clang_type == NULL)
4728        return NULL;
4729
4730    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4731    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4732    switch (type_class)
4733    {
4734    case clang::Type::UnaryTransform:           break;
4735    case clang::Type::FunctionNoProto:          break;
4736    case clang::Type::FunctionProto:            break;
4737    case clang::Type::IncompleteArray:          break;
4738    case clang::Type::VariableArray:            break;
4739    case clang::Type::ConstantArray:            break;
4740    case clang::Type::DependentSizedArray:      break;
4741    case clang::Type::ExtVector:                break;
4742    case clang::Type::DependentSizedExtVector:  break;
4743    case clang::Type::Vector:                   break;
4744    case clang::Type::Builtin:                  break;
4745    case clang::Type::BlockPointer:             break;
4746    case clang::Type::Pointer:                  break;
4747    case clang::Type::LValueReference:          break;
4748    case clang::Type::RValueReference:          break;
4749    case clang::Type::MemberPointer:            break;
4750    case clang::Type::Complex:                  break;
4751    case clang::Type::ObjCObject:               break;
4752    case clang::Type::ObjCInterface:            return cast<ObjCObjectType>(qual_type.getTypePtr())->getInterface();
4753    case clang::Type::ObjCObjectPointer:        return ClangASTContext::GetDeclContextForType (cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr());
4754    case clang::Type::Record:                   return cast<RecordType>(qual_type)->getDecl();
4755    case clang::Type::Enum:                     return cast<EnumType>(qual_type)->getDecl();
4756    case clang::Type::Typedef:                  return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
4757    case clang::Type::Elaborated:               return ClangASTContext::GetDeclContextForType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
4758    case clang::Type::TypeOfExpr:               break;
4759    case clang::Type::TypeOf:                   break;
4760    case clang::Type::Decltype:                 break;
4761    //case clang::Type::QualifiedName:          break;
4762    case clang::Type::TemplateSpecialization:   break;
4763    case clang::Type::DependentTemplateSpecialization:  break;
4764    case clang::Type::TemplateTypeParm:         break;
4765    case clang::Type::SubstTemplateTypeParm:    break;
4766    case clang::Type::SubstTemplateTypeParmPack:break;
4767    case clang::Type::PackExpansion:            break;
4768    case clang::Type::UnresolvedUsing:          break;
4769    case clang::Type::Paren:                    break;
4770    case clang::Type::Attributed:               break;
4771    case clang::Type::Auto:                     break;
4772    case clang::Type::InjectedClassName:        break;
4773    case clang::Type::DependentName:            break;
4774    case clang::Type::Atomic:                   break;
4775    }
4776    // No DeclContext in this type...
4777    return NULL;
4778}
4779
4780#pragma mark Namespace Declarations
4781
4782NamespaceDecl *
4783ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
4784{
4785    NamespaceDecl *namespace_decl = NULL;
4786    ASTContext *ast = getASTContext();
4787    TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
4788    if (decl_ctx == NULL)
4789        decl_ctx = translation_unit_decl;
4790
4791    if (name)
4792    {
4793        IdentifierInfo &identifier_info = ast->Idents.get(name);
4794        DeclarationName decl_name (&identifier_info);
4795        clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
4796        for (clang::DeclContext::lookup_iterator pos = result.first, end = result.second; pos != end; ++pos)
4797        {
4798            namespace_decl = dyn_cast<clang::NamespaceDecl>(*pos);
4799            if (namespace_decl)
4800                return namespace_decl;
4801        }
4802
4803        namespace_decl = NamespaceDecl::Create(*ast,
4804                                               decl_ctx,
4805                                               false,
4806                                               SourceLocation(),
4807                                               SourceLocation(),
4808                                               &identifier_info,
4809                                               NULL);
4810
4811        decl_ctx->addDecl (namespace_decl);
4812    }
4813    else
4814    {
4815        if (decl_ctx == translation_unit_decl)
4816        {
4817            namespace_decl = translation_unit_decl->getAnonymousNamespace();
4818            if (namespace_decl)
4819                return namespace_decl;
4820
4821            namespace_decl = NamespaceDecl::Create(*ast,
4822                                                   decl_ctx,
4823                                                   false,
4824                                                   SourceLocation(),
4825                                                   SourceLocation(),
4826                                                   NULL,
4827                                                   NULL);
4828            translation_unit_decl->setAnonymousNamespace (namespace_decl);
4829            translation_unit_decl->addDecl (namespace_decl);
4830            assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
4831        }
4832        else
4833        {
4834            NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
4835            if (parent_namespace_decl)
4836            {
4837                namespace_decl = parent_namespace_decl->getAnonymousNamespace();
4838                if (namespace_decl)
4839                    return namespace_decl;
4840                namespace_decl = NamespaceDecl::Create(*ast,
4841                                                       decl_ctx,
4842                                                       false,
4843                                                       SourceLocation(),
4844                                                       SourceLocation(),
4845                                                       NULL,
4846                                                       NULL);
4847                parent_namespace_decl->setAnonymousNamespace (namespace_decl);
4848                parent_namespace_decl->addDecl (namespace_decl);
4849                assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
4850            }
4851            else
4852            {
4853                // BAD!!!
4854            }
4855        }
4856
4857
4858        if (namespace_decl)
4859        {
4860            // If we make it here, we are creating the anonymous namespace decl
4861            // for the first time, so we need to do the using directive magic
4862            // like SEMA does
4863            UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast,
4864                                                                                   decl_ctx,
4865                                                                                   SourceLocation(),
4866                                                                                   SourceLocation(),
4867                                                                                   NestedNameSpecifierLoc(),
4868                                                                                   SourceLocation(),
4869                                                                                   namespace_decl,
4870                                                                                   decl_ctx);
4871            using_directive_decl->setImplicit();
4872            decl_ctx->addDecl(using_directive_decl);
4873        }
4874    }
4875#ifdef LLDB_CONFIGURATION_DEBUG
4876    VerifyDecl(namespace_decl);
4877#endif
4878    return namespace_decl;
4879}
4880
4881
4882#pragma mark Function Types
4883
4884FunctionDecl *
4885ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx, const char *name, clang_type_t function_clang_type, int storage, bool is_inline)
4886{
4887    FunctionDecl *func_decl = NULL;
4888    ASTContext *ast = getASTContext();
4889    if (decl_ctx == NULL)
4890        decl_ctx = ast->getTranslationUnitDecl();
4891
4892    if (name && name[0])
4893    {
4894        func_decl = FunctionDecl::Create (*ast,
4895                                          decl_ctx,
4896                                          SourceLocation(),
4897                                          SourceLocation(),
4898                                          DeclarationName (&ast->Idents.get(name)),
4899                                          QualType::getFromOpaquePtr(function_clang_type),
4900                                          NULL,
4901                                          (FunctionDecl::StorageClass)storage,
4902                                          (FunctionDecl::StorageClass)storage,
4903                                          is_inline);
4904    }
4905    else
4906    {
4907        func_decl = FunctionDecl::Create (*ast,
4908                                          decl_ctx,
4909                                          SourceLocation(),
4910                                          SourceLocation(),
4911                                          DeclarationName (),
4912                                          QualType::getFromOpaquePtr(function_clang_type),
4913                                          NULL,
4914                                          (FunctionDecl::StorageClass)storage,
4915                                          (FunctionDecl::StorageClass)storage,
4916                                          is_inline);
4917    }
4918    if (func_decl)
4919        decl_ctx->addDecl (func_decl);
4920
4921#ifdef LLDB_CONFIGURATION_DEBUG
4922    VerifyDecl(func_decl);
4923#endif
4924
4925    return func_decl;
4926}
4927
4928clang_type_t
4929ClangASTContext::CreateFunctionType (ASTContext *ast,
4930                                     clang_type_t result_type,
4931                                     clang_type_t *args,
4932                                     unsigned num_args,
4933                                     bool is_variadic,
4934                                     unsigned type_quals)
4935{
4936    assert (ast != NULL);
4937    std::vector<QualType> qual_type_args;
4938    for (unsigned i=0; i<num_args; ++i)
4939        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
4940
4941    // TODO: Detect calling convention in DWARF?
4942    FunctionProtoType::ExtProtoInfo proto_info;
4943    proto_info.Variadic = is_variadic;
4944    proto_info.ExceptionSpecType = EST_None;
4945    proto_info.TypeQuals = type_quals;
4946    proto_info.RefQualifier = RQ_None;
4947    proto_info.NumExceptions = 0;
4948    proto_info.Exceptions = NULL;
4949
4950    return ast->getFunctionType (QualType::getFromOpaquePtr(result_type),
4951                                 qual_type_args.empty() ? NULL : &qual_type_args.front(),
4952                                 qual_type_args.size(),
4953                                 proto_info).getAsOpaquePtr();    // NoReturn);
4954}
4955
4956ParmVarDecl *
4957ClangASTContext::CreateParameterDeclaration (const char *name, clang_type_t param_type, int storage)
4958{
4959    ASTContext *ast = getASTContext();
4960    assert (ast != NULL);
4961    return ParmVarDecl::Create(*ast,
4962                                ast->getTranslationUnitDecl(),
4963                                SourceLocation(),
4964                                SourceLocation(),
4965                                name && name[0] ? &ast->Idents.get(name) : NULL,
4966                                QualType::getFromOpaquePtr(param_type),
4967                                NULL,
4968                                (VarDecl::StorageClass)storage,
4969                                (VarDecl::StorageClass)storage,
4970                                0);
4971}
4972
4973void
4974ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
4975{
4976    if (function_decl)
4977        function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
4978}
4979
4980
4981#pragma mark Array Types
4982
4983clang_type_t
4984ClangASTContext::CreateArrayType (clang_type_t element_type, size_t element_count, uint32_t bit_stride)
4985{
4986    if (element_type)
4987    {
4988        ASTContext *ast = getASTContext();
4989        assert (ast != NULL);
4990        llvm::APInt ap_element_count (64, element_count);
4991        return ast->getConstantArrayType(QualType::getFromOpaquePtr(element_type),
4992                                                 ap_element_count,
4993                                                 ArrayType::Normal,
4994                                                 0).getAsOpaquePtr(); // ElemQuals
4995    }
4996    return NULL;
4997}
4998
4999
5000#pragma mark TagDecl
5001
5002bool
5003ClangASTContext::StartTagDeclarationDefinition (clang_type_t clang_type)
5004{
5005    if (clang_type)
5006    {
5007        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5008        const clang::Type *t = qual_type.getTypePtr();
5009        if (t)
5010        {
5011            const TagType *tag_type = dyn_cast<TagType>(t);
5012            if (tag_type)
5013            {
5014                TagDecl *tag_decl = tag_type->getDecl();
5015                if (tag_decl)
5016                {
5017                    tag_decl->startDefinition();
5018                    return true;
5019                }
5020            }
5021
5022            const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(t);
5023            if (object_type)
5024            {
5025                ObjCInterfaceDecl *interface_decl = object_type->getInterface();
5026                if (interface_decl)
5027                {
5028                    interface_decl->startDefinition();
5029                    return true;
5030                }
5031            }
5032        }
5033    }
5034    return false;
5035}
5036
5037bool
5038ClangASTContext::CompleteTagDeclarationDefinition (clang_type_t clang_type)
5039{
5040    if (clang_type)
5041    {
5042        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5043
5044        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
5045
5046        if (cxx_record_decl)
5047        {
5048            cxx_record_decl->completeDefinition();
5049
5050            return true;
5051        }
5052
5053        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type);
5054
5055        if (objc_class_type)
5056        {
5057            // ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
5058            // class_interface_decl->completeDefinition();
5059        }
5060
5061        const EnumType *enum_type = dyn_cast<EnumType>(qual_type.getTypePtr());
5062
5063        if (enum_type)
5064        {
5065            EnumDecl *enum_decl = enum_type->getDecl();
5066
5067            if (enum_decl)
5068            {
5069                /// TODO This really needs to be fixed.
5070
5071                unsigned NumPositiveBits = 1;
5072                unsigned NumNegativeBits = 0;
5073
5074                ASTContext *ast = getASTContext();
5075
5076                QualType promotion_qual_type;
5077                // If the enum integer type is less than an integer in bit width,
5078                // then we must promote it to an integer size.
5079                if (ast->getTypeSize(enum_decl->getIntegerType()) < ast->getTypeSize(ast->IntTy))
5080                {
5081                    if (enum_decl->getIntegerType()->isSignedIntegerType())
5082                        promotion_qual_type = ast->IntTy;
5083                    else
5084                        promotion_qual_type = ast->UnsignedIntTy;
5085                }
5086                else
5087                    promotion_qual_type = enum_decl->getIntegerType();
5088
5089                enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits);
5090                return true;
5091            }
5092        }
5093    }
5094    return false;
5095}
5096
5097
5098#pragma mark Enumeration Types
5099
5100clang_type_t
5101ClangASTContext::CreateEnumerationType
5102(
5103    const char *name,
5104    DeclContext *decl_ctx,
5105    const Declaration &decl,
5106    clang_type_t integer_qual_type
5107)
5108{
5109    // TODO: Do something intelligent with the Declaration object passed in
5110    // like maybe filling in the SourceLocation with it...
5111    ASTContext *ast = getASTContext();
5112    assert (ast != NULL);
5113
5114    // TODO: ask about these...
5115//    const bool IsScoped = false;
5116//    const bool IsFixed = false;
5117
5118    EnumDecl *enum_decl = EnumDecl::Create (*ast,
5119                                            decl_ctx,
5120                                            SourceLocation(),
5121                                            SourceLocation(),
5122                                            name && name[0] ? &ast->Idents.get(name) : NULL,
5123                                            NULL,
5124                                            false,  // IsScoped
5125                                            false,  // IsScopedUsingClassTag
5126                                            false); // IsFixed
5127
5128
5129    if (enum_decl)
5130    {
5131        // TODO: check if we should be setting the promotion type too?
5132        enum_decl->setIntegerType(QualType::getFromOpaquePtr (integer_qual_type));
5133
5134        enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
5135
5136        return ast->getTagDeclType(enum_decl).getAsOpaquePtr();
5137    }
5138    return NULL;
5139}
5140
5141clang_type_t
5142ClangASTContext::GetEnumerationIntegerType (clang_type_t enum_clang_type)
5143{
5144    QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5145
5146    const clang::Type *clang_type = enum_qual_type.getTypePtr();
5147    if (clang_type)
5148    {
5149        const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5150        if (enum_type)
5151        {
5152            EnumDecl *enum_decl = enum_type->getDecl();
5153            if (enum_decl)
5154                return enum_decl->getIntegerType().getAsOpaquePtr();
5155        }
5156    }
5157    return NULL;
5158}
5159bool
5160ClangASTContext::AddEnumerationValueToEnumerationType
5161(
5162    clang_type_t enum_clang_type,
5163    clang_type_t enumerator_clang_type,
5164    const Declaration &decl,
5165    const char *name,
5166    int64_t enum_value,
5167    uint32_t enum_value_bit_size
5168)
5169{
5170    if (enum_clang_type && enumerator_clang_type && name)
5171    {
5172        // TODO: Do something intelligent with the Declaration object passed in
5173        // like maybe filling in the SourceLocation with it...
5174        ASTContext *ast = getASTContext();
5175        IdentifierTable *identifier_table = getIdentifierTable();
5176
5177        assert (ast != NULL);
5178        assert (identifier_table != NULL);
5179        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5180
5181        const clang::Type *clang_type = enum_qual_type.getTypePtr();
5182        if (clang_type)
5183        {
5184            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5185
5186            if (enum_type)
5187            {
5188                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, false);
5189                enum_llvm_apsint = enum_value;
5190                EnumConstantDecl *enumerator_decl =
5191                    EnumConstantDecl::Create (*ast,
5192                                              enum_type->getDecl(),
5193                                              SourceLocation(),
5194                                              name ? &identifier_table->get(name) : NULL,    // Identifier
5195                                              QualType::getFromOpaquePtr(enumerator_clang_type),
5196                                              NULL,
5197                                              enum_llvm_apsint);
5198
5199                if (enumerator_decl)
5200                {
5201                    enum_type->getDecl()->addDecl(enumerator_decl);
5202
5203#ifdef LLDB_CONFIGURATION_DEBUG
5204                    VerifyDecl(enumerator_decl);
5205#endif
5206
5207                    return true;
5208                }
5209            }
5210        }
5211    }
5212    return false;
5213}
5214
5215#pragma mark Pointers & References
5216
5217clang_type_t
5218ClangASTContext::CreatePointerType (clang_type_t clang_type)
5219{
5220    return CreatePointerType (getASTContext(), clang_type);
5221}
5222
5223clang_type_t
5224ClangASTContext::CreatePointerType (clang::ASTContext *ast, clang_type_t clang_type)
5225{
5226    if (ast && clang_type)
5227    {
5228        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5229
5230        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5231        switch (type_class)
5232        {
5233        case clang::Type::ObjCObject:
5234        case clang::Type::ObjCInterface:
5235            return ast->getObjCObjectPointerType(qual_type).getAsOpaquePtr();
5236
5237        default:
5238            return ast->getPointerType(qual_type).getAsOpaquePtr();
5239        }
5240    }
5241    return NULL;
5242}
5243
5244clang_type_t
5245ClangASTContext::CreateLValueReferenceType (clang::ASTContext *ast,
5246                                            clang_type_t clang_type)
5247{
5248    if (clang_type)
5249        return ast->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5250    return NULL;
5251}
5252
5253clang_type_t
5254ClangASTContext::CreateRValueReferenceType (clang::ASTContext *ast,
5255                                            clang_type_t clang_type)
5256{
5257    if (clang_type)
5258        return ast->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5259    return NULL;
5260}
5261
5262clang_type_t
5263ClangASTContext::CreateMemberPointerType (clang_type_t clang_pointee_type, clang_type_t clang_class_type)
5264{
5265    if (clang_pointee_type && clang_pointee_type)
5266        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
5267                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
5268    return NULL;
5269}
5270
5271uint32_t
5272ClangASTContext::GetPointerBitSize ()
5273{
5274    ASTContext *ast = getASTContext();
5275    return ast->getTypeSize(ast->VoidPtrTy);
5276}
5277
5278bool
5279ClangASTContext::IsPossibleDynamicType (clang::ASTContext *ast, clang_type_t clang_type, clang_type_t *dynamic_pointee_type)
5280{
5281    QualType pointee_qual_type;
5282    if (clang_type)
5283    {
5284        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5285        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5286        bool success = false;
5287        switch (type_class)
5288        {
5289            case clang::Type::Builtin:
5290                if (cast<clang::BuiltinType>(qual_type)->getKind() == clang::BuiltinType::ObjCId)
5291                {
5292                    if (dynamic_pointee_type)
5293                        *dynamic_pointee_type = clang_type;
5294                    return true;
5295                }
5296                break;
5297
5298            case clang::Type::ObjCObjectPointer:
5299                if (dynamic_pointee_type)
5300                    *dynamic_pointee_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5301                return true;
5302
5303            case clang::Type::Pointer:
5304                pointee_qual_type = cast<PointerType>(qual_type)->getPointeeType();
5305                success = true;
5306                break;
5307
5308            case clang::Type::LValueReference:
5309            case clang::Type::RValueReference:
5310                pointee_qual_type = cast<ReferenceType>(qual_type)->getPointeeType();
5311                success = true;
5312                break;
5313
5314            case clang::Type::Typedef:
5315                return ClangASTContext::IsPossibleDynamicType (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), dynamic_pointee_type);
5316
5317            case clang::Type::Elaborated:
5318                return ClangASTContext::IsPossibleDynamicType (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), dynamic_pointee_type);
5319
5320            default:
5321                break;
5322        }
5323
5324        if (success)
5325        {
5326            // Check to make sure what we are pointing too is a possible dynamic C++ type
5327            // We currently accept any "void *" (in case we have a class that has been
5328            // watered down to an opaque pointer) and virtual C++ classes.
5329            const clang::Type::TypeClass pointee_type_class = pointee_qual_type->getTypeClass();
5330            switch (pointee_type_class)
5331            {
5332                case clang::Type::Builtin:
5333                    switch (cast<clang::BuiltinType>(pointee_qual_type)->getKind())
5334                    {
5335                        case clang::BuiltinType::UnknownAny:
5336                        case clang::BuiltinType::Void:
5337                            if (dynamic_pointee_type)
5338                                *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5339                            return true;
5340
5341                        case clang::BuiltinType::NullPtr:
5342                        case clang::BuiltinType::Bool:
5343                        case clang::BuiltinType::Char_U:
5344                        case clang::BuiltinType::UChar:
5345                        case clang::BuiltinType::WChar_U:
5346                        case clang::BuiltinType::Char16:
5347                        case clang::BuiltinType::Char32:
5348                        case clang::BuiltinType::UShort:
5349                        case clang::BuiltinType::UInt:
5350                        case clang::BuiltinType::ULong:
5351                        case clang::BuiltinType::ULongLong:
5352                        case clang::BuiltinType::UInt128:
5353                        case clang::BuiltinType::Char_S:
5354                        case clang::BuiltinType::SChar:
5355                        case clang::BuiltinType::WChar_S:
5356                        case clang::BuiltinType::Short:
5357                        case clang::BuiltinType::Int:
5358                        case clang::BuiltinType::Long:
5359                        case clang::BuiltinType::LongLong:
5360                        case clang::BuiltinType::Int128:
5361                        case clang::BuiltinType::Float:
5362                        case clang::BuiltinType::Double:
5363                        case clang::BuiltinType::LongDouble:
5364                        case clang::BuiltinType::Dependent:
5365                        case clang::BuiltinType::Overload:
5366                        case clang::BuiltinType::ObjCId:
5367                        case clang::BuiltinType::ObjCClass:
5368                        case clang::BuiltinType::ObjCSel:
5369                        case clang::BuiltinType::BoundMember:
5370                        case clang::BuiltinType::Half:
5371                        case clang::BuiltinType::ARCUnbridgedCast:
5372                        case clang::BuiltinType::PseudoObject:
5373                            break;
5374                    }
5375                    break;
5376
5377                case clang::Type::Record:
5378                    {
5379                        CXXRecordDecl *cxx_record_decl = pointee_qual_type->getAsCXXRecordDecl();
5380                        if (cxx_record_decl)
5381                        {
5382                            if (GetCompleteQualType (ast, pointee_qual_type))
5383                            {
5384                                success = cxx_record_decl->isDynamicClass();
5385                            }
5386                            else
5387                            {
5388                                // We failed to get the complete type, so we have to
5389                                // treat this as a void * which we might possibly be
5390                                // able to complete
5391                                success = true;
5392                            }
5393                            if (success)
5394                            {
5395                                if (dynamic_pointee_type)
5396                                    *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5397                                return true;
5398                            }
5399                        }
5400                    }
5401                    break;
5402
5403                case clang::Type::ObjCObject:
5404                case clang::Type::ObjCInterface:
5405                    {
5406                        const clang::ObjCObjectType *objc_class_type = pointee_qual_type->getAsObjCQualifiedInterfaceType();
5407                        if (objc_class_type)
5408                        {
5409                            GetCompleteQualType (ast, pointee_qual_type);
5410                            if (dynamic_pointee_type)
5411                                *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5412                            return true;
5413                        }
5414                    }
5415                    break;
5416
5417                default:
5418                    break;
5419            }
5420        }
5421    }
5422    if (dynamic_pointee_type)
5423        *dynamic_pointee_type = NULL;
5424    return false;
5425}
5426
5427
5428bool
5429ClangASTContext::IsPossibleCPlusPlusDynamicType (clang::ASTContext *ast, clang_type_t clang_type, clang_type_t *dynamic_pointee_type)
5430{
5431    QualType pointee_qual_type;
5432    if (clang_type)
5433    {
5434        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5435        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5436        bool success = false;
5437        switch (type_class)
5438        {
5439            case clang::Type::Pointer:
5440                pointee_qual_type = cast<PointerType>(qual_type)->getPointeeType();
5441                success = true;
5442                break;
5443
5444            case clang::Type::LValueReference:
5445            case clang::Type::RValueReference:
5446                pointee_qual_type = cast<ReferenceType>(qual_type)->getPointeeType();
5447                success = true;
5448                break;
5449
5450            case clang::Type::Typedef:
5451                return ClangASTContext::IsPossibleCPlusPlusDynamicType (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), dynamic_pointee_type);
5452
5453            case clang::Type::Elaborated:
5454                return ClangASTContext::IsPossibleCPlusPlusDynamicType (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5455
5456            default:
5457                break;
5458        }
5459
5460        if (success)
5461        {
5462            // Check to make sure what we are pointing too is a possible dynamic C++ type
5463            // We currently accept any "void *" (in case we have a class that has been
5464            // watered down to an opaque pointer) and virtual C++ classes.
5465            const clang::Type::TypeClass pointee_type_class = pointee_qual_type->getTypeClass();
5466            switch (pointee_type_class)
5467            {
5468            case clang::Type::Builtin:
5469                switch (cast<clang::BuiltinType>(pointee_qual_type)->getKind())
5470                {
5471                    case clang::BuiltinType::UnknownAny:
5472                    case clang::BuiltinType::Void:
5473                        if (dynamic_pointee_type)
5474                            *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5475                        return true;
5476
5477                    case clang::BuiltinType::NullPtr:
5478                    case clang::BuiltinType::Bool:
5479                    case clang::BuiltinType::Char_U:
5480                    case clang::BuiltinType::UChar:
5481                    case clang::BuiltinType::WChar_U:
5482                    case clang::BuiltinType::Char16:
5483                    case clang::BuiltinType::Char32:
5484                    case clang::BuiltinType::UShort:
5485                    case clang::BuiltinType::UInt:
5486                    case clang::BuiltinType::ULong:
5487                    case clang::BuiltinType::ULongLong:
5488                    case clang::BuiltinType::UInt128:
5489                    case clang::BuiltinType::Char_S:
5490                    case clang::BuiltinType::SChar:
5491                    case clang::BuiltinType::WChar_S:
5492                    case clang::BuiltinType::Short:
5493                    case clang::BuiltinType::Int:
5494                    case clang::BuiltinType::Long:
5495                    case clang::BuiltinType::LongLong:
5496                    case clang::BuiltinType::Int128:
5497                    case clang::BuiltinType::Float:
5498                    case clang::BuiltinType::Double:
5499                    case clang::BuiltinType::LongDouble:
5500                    case clang::BuiltinType::Dependent:
5501                    case clang::BuiltinType::Overload:
5502                    case clang::BuiltinType::ObjCId:
5503                    case clang::BuiltinType::ObjCClass:
5504                    case clang::BuiltinType::ObjCSel:
5505                    case clang::BuiltinType::BoundMember:
5506                    case clang::BuiltinType::Half:
5507                    case clang::BuiltinType::ARCUnbridgedCast:
5508                    case clang::BuiltinType::PseudoObject:
5509                        break;
5510                }
5511                break;
5512            case clang::Type::Record:
5513                {
5514                    CXXRecordDecl *cxx_record_decl = pointee_qual_type->getAsCXXRecordDecl();
5515                    if (cxx_record_decl)
5516                    {
5517                        if (GetCompleteQualType (ast, pointee_qual_type))
5518                        {
5519                            success = cxx_record_decl->isDynamicClass();
5520                        }
5521                        else
5522                        {
5523                            // We failed to get the complete type, so we have to
5524                            // treat this as a void * which we might possibly be
5525                            // able to complete
5526                            success = true;
5527                        }
5528                        if (success)
5529                        {
5530                            if (dynamic_pointee_type)
5531                                *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5532                            return true;
5533                        }
5534                    }
5535                }
5536                break;
5537
5538            default:
5539                break;
5540            }
5541        }
5542    }
5543    if (dynamic_pointee_type)
5544        *dynamic_pointee_type = NULL;
5545    return false;
5546}
5547
5548bool
5549ClangASTContext::IsReferenceType (clang_type_t clang_type, clang_type_t *target_type)
5550{
5551    if (clang_type == NULL)
5552        return false;
5553
5554    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5555    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5556
5557    switch (type_class)
5558    {
5559    case clang::Type::LValueReference:
5560        if (target_type)
5561            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5562        return true;
5563    case clang::Type::RValueReference:
5564        if (target_type)
5565            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5566        return true;
5567    case clang::Type::Typedef:
5568        return ClangASTContext::IsReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5569    case clang::Type::Elaborated:
5570        return ClangASTContext::IsReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5571    default:
5572        break;
5573    }
5574
5575    return false;
5576}
5577
5578bool
5579ClangASTContext::IsPointerOrReferenceType (clang_type_t clang_type, clang_type_t*target_type)
5580{
5581    if (clang_type == NULL)
5582        return false;
5583
5584    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5585    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5586    switch (type_class)
5587    {
5588    case clang::Type::Builtin:
5589        switch (cast<clang::BuiltinType>(qual_type)->getKind())
5590        {
5591        default:
5592            break;
5593        case clang::BuiltinType::ObjCId:
5594        case clang::BuiltinType::ObjCClass:
5595            return true;
5596        }
5597        return false;
5598    case clang::Type::ObjCObjectPointer:
5599        if (target_type)
5600            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5601        return true;
5602    case clang::Type::BlockPointer:
5603        if (target_type)
5604            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5605        return true;
5606    case clang::Type::Pointer:
5607        if (target_type)
5608            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5609        return true;
5610    case clang::Type::MemberPointer:
5611        if (target_type)
5612            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5613        return true;
5614    case clang::Type::LValueReference:
5615        if (target_type)
5616            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5617        return true;
5618    case clang::Type::RValueReference:
5619        if (target_type)
5620            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5621        return true;
5622    case clang::Type::Typedef:
5623        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5624    case clang::Type::Elaborated:
5625        return ClangASTContext::IsPointerOrReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5626    default:
5627        break;
5628    }
5629    return false;
5630}
5631
5632bool
5633ClangASTContext::IsIntegerType (clang_type_t clang_type, bool &is_signed)
5634{
5635    if (!clang_type)
5636        return false;
5637
5638    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5639    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
5640
5641    if (builtin_type)
5642    {
5643        if (builtin_type->isInteger())
5644        {
5645            is_signed = builtin_type->isSignedInteger();
5646            return true;
5647        }
5648    }
5649
5650    return false;
5651}
5652
5653bool
5654ClangASTContext::IsPointerType (clang_type_t clang_type, clang_type_t *target_type)
5655{
5656    if (target_type)
5657        *target_type = NULL;
5658
5659    if (clang_type)
5660    {
5661        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5662        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5663        switch (type_class)
5664        {
5665        case clang::Type::Builtin:
5666            switch (cast<clang::BuiltinType>(qual_type)->getKind())
5667            {
5668            default:
5669                break;
5670            case clang::BuiltinType::ObjCId:
5671            case clang::BuiltinType::ObjCClass:
5672                return true;
5673            }
5674            return false;
5675        case clang::Type::ObjCObjectPointer:
5676            if (target_type)
5677                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5678            return true;
5679        case clang::Type::BlockPointer:
5680            if (target_type)
5681                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5682            return true;
5683        case clang::Type::Pointer:
5684            if (target_type)
5685                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5686            return true;
5687        case clang::Type::MemberPointer:
5688            if (target_type)
5689                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5690            return true;
5691        case clang::Type::Typedef:
5692            return ClangASTContext::IsPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), target_type);
5693        case clang::Type::Elaborated:
5694            return ClangASTContext::IsPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), target_type);
5695        default:
5696            break;
5697        }
5698    }
5699    return false;
5700}
5701
5702bool
5703ClangASTContext::IsFloatingPointType (clang_type_t clang_type, uint32_t &count, bool &is_complex)
5704{
5705    if (clang_type)
5706    {
5707        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5708
5709        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
5710        {
5711            clang::BuiltinType::Kind kind = BT->getKind();
5712            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
5713            {
5714                count = 1;
5715                is_complex = false;
5716                return true;
5717            }
5718        }
5719        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
5720        {
5721            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
5722            {
5723                count = 2;
5724                is_complex = true;
5725                return true;
5726            }
5727        }
5728        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
5729        {
5730            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
5731            {
5732                count = VT->getNumElements();
5733                is_complex = false;
5734                return true;
5735            }
5736        }
5737    }
5738    return false;
5739}
5740
5741bool
5742ClangASTContext::IsScalarType (lldb::clang_type_t clang_type)
5743{
5744    bool is_signed;
5745    if (ClangASTContext::IsIntegerType(clang_type, is_signed))
5746        return true;
5747
5748    uint32_t count;
5749    bool is_complex;
5750    return ClangASTContext::IsFloatingPointType(clang_type, count, is_complex) && !is_complex;
5751}
5752
5753bool
5754ClangASTContext::IsPointerToScalarType (lldb::clang_type_t clang_type)
5755{
5756    if (!IsPointerType(clang_type))
5757        return false;
5758
5759    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5760    lldb::clang_type_t pointee_type = qual_type.getTypePtr()->getPointeeType().getAsOpaquePtr();
5761    return IsScalarType(pointee_type);
5762}
5763
5764bool
5765ClangASTContext::IsArrayOfScalarType (lldb::clang_type_t clang_type)
5766{
5767    clang_type = GetAsArrayType(clang_type);
5768
5769    if (clang_type == 0)
5770        return false;
5771
5772    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5773    lldb::clang_type_t item_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
5774    return IsScalarType(item_type);
5775}
5776
5777
5778bool
5779ClangASTContext::GetCXXClassName (clang_type_t clang_type, std::string &class_name)
5780{
5781    if (clang_type)
5782    {
5783        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5784
5785        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
5786        if (cxx_record_decl)
5787        {
5788            class_name.assign (cxx_record_decl->getIdentifier()->getNameStart());
5789            return true;
5790        }
5791    }
5792    class_name.clear();
5793    return false;
5794}
5795
5796
5797bool
5798ClangASTContext::IsCXXClassType (clang_type_t clang_type)
5799{
5800    if (clang_type)
5801    {
5802        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5803        if (qual_type->getAsCXXRecordDecl() != NULL)
5804            return true;
5805    }
5806    return false;
5807}
5808
5809bool
5810ClangASTContext::IsBeingDefined (lldb::clang_type_t clang_type)
5811{
5812    if (clang_type)
5813    {
5814        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5815        const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type);
5816        if (tag_type)
5817            return tag_type->isBeingDefined();
5818    }
5819    return false;
5820}
5821
5822bool
5823ClangASTContext::IsObjCClassType (clang_type_t clang_type)
5824{
5825    if (clang_type)
5826    {
5827        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5828        if (qual_type->isObjCObjectOrInterfaceType())
5829            return true;
5830    }
5831    return false;
5832}
5833
5834
5835bool
5836ClangASTContext::IsCharType (clang_type_t clang_type)
5837{
5838    if (clang_type)
5839        return QualType::getFromOpaquePtr(clang_type)->isCharType();
5840    return false;
5841}
5842
5843bool
5844ClangASTContext::IsCStringType (clang_type_t clang_type, uint32_t &length)
5845{
5846    clang_type_t pointee_or_element_clang_type = NULL;
5847    Flags type_flags (ClangASTContext::GetTypeInfo (clang_type, NULL, &pointee_or_element_clang_type));
5848
5849    if (pointee_or_element_clang_type == NULL)
5850        return false;
5851
5852    if (type_flags.AnySet (eTypeIsArray | eTypeIsPointer))
5853    {
5854        QualType pointee_or_element_qual_type (QualType::getFromOpaquePtr (pointee_or_element_clang_type));
5855
5856        if (pointee_or_element_qual_type.getUnqualifiedType()->isCharType())
5857        {
5858            QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5859            if (type_flags.Test (eTypeIsArray))
5860            {
5861                // We know the size of the array and it could be a C string
5862                // since it is an array of characters
5863                length = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
5864                return true;
5865            }
5866            else
5867            {
5868                length = 0;
5869                return true;
5870            }
5871
5872        }
5873    }
5874    return false;
5875}
5876
5877bool
5878ClangASTContext::IsFunctionPointerType (clang_type_t clang_type)
5879{
5880    if (clang_type)
5881    {
5882        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5883
5884        if (qual_type->isFunctionPointerType())
5885            return true;
5886
5887        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5888        switch (type_class)
5889        {
5890        default:
5891            break;
5892        case clang::Type::Typedef:
5893            return ClangASTContext::IsFunctionPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5894        case clang::Type::Elaborated:
5895            return ClangASTContext::IsFunctionPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5896
5897        case clang::Type::LValueReference:
5898        case clang::Type::RValueReference:
5899            {
5900                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
5901                if (reference_type)
5902                    return ClangASTContext::IsFunctionPointerType (reference_type->getPointeeType().getAsOpaquePtr());
5903            }
5904            break;
5905        }
5906    }
5907    return false;
5908}
5909
5910size_t
5911ClangASTContext::GetArraySize (clang_type_t clang_type)
5912{
5913    if (clang_type)
5914    {
5915        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
5916        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5917        switch (type_class)
5918        {
5919        case clang::Type::ConstantArray:
5920            {
5921                const ConstantArrayType *array = cast<ConstantArrayType>(QualType::getFromOpaquePtr(clang_type).getTypePtr());
5922                if (array)
5923                    return array->getSize().getLimitedValue();
5924            }
5925            break;
5926
5927        case clang::Type::Typedef:
5928            return ClangASTContext::GetArraySize(cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5929
5930        case clang::Type::Elaborated:
5931            return ClangASTContext::GetArraySize(cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5932
5933        default:
5934            break;
5935        }
5936    }
5937    return 0;
5938}
5939
5940clang_type_t
5941ClangASTContext::GetAsArrayType (clang_type_t clang_type, clang_type_t*member_type, uint64_t *size)
5942{
5943    if (!clang_type)
5944        return 0;
5945
5946    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5947
5948    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5949    switch (type_class)
5950    {
5951    default:
5952        break;
5953
5954    case clang::Type::ConstantArray:
5955        if (member_type)
5956            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
5957        if (size)
5958            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULLONG_MAX);
5959        return clang_type;
5960
5961    case clang::Type::IncompleteArray:
5962        if (member_type)
5963            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
5964        if (size)
5965            *size = 0;
5966        return clang_type;
5967
5968    case clang::Type::VariableArray:
5969        if (member_type)
5970            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
5971        if (size)
5972            *size = 0;
5973        return clang_type;
5974
5975    case clang::Type::DependentSizedArray:
5976        if (member_type)
5977            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
5978        if (size)
5979            *size = 0;
5980        return clang_type;
5981
5982    case clang::Type::Typedef:
5983        return ClangASTContext::GetAsArrayType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5984                                                member_type,
5985                                                size);
5986
5987    case clang::Type::Elaborated:
5988        return ClangASTContext::GetAsArrayType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5989                                                member_type,
5990                                                size);
5991    }
5992    return 0;
5993}
5994
5995
5996#pragma mark Typedefs
5997
5998clang_type_t
5999ClangASTContext::CreateTypedefType (const char *name, clang_type_t clang_type, DeclContext *decl_ctx)
6000{
6001    if (clang_type)
6002    {
6003        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6004        ASTContext *ast = getASTContext();
6005        IdentifierTable *identifier_table = getIdentifierTable();
6006        assert (ast != NULL);
6007        assert (identifier_table != NULL);
6008        if (decl_ctx == NULL)
6009            decl_ctx = ast->getTranslationUnitDecl();
6010        TypedefDecl *decl = TypedefDecl::Create (*ast,
6011                                                 decl_ctx,
6012                                                 SourceLocation(),
6013                                                 SourceLocation(),
6014                                                 name ? &identifier_table->get(name) : NULL, // Identifier
6015                                                 ast->CreateTypeSourceInfo(qual_type));
6016
6017        //decl_ctx->addDecl (decl);
6018
6019        decl->setAccess(AS_public); // TODO respect proper access specifier
6020
6021        // Get a uniqued QualType for the typedef decl type
6022        return ast->getTypedefType (decl).getAsOpaquePtr();
6023    }
6024    return NULL;
6025}
6026
6027// Disable this for now since I can't seem to get a nicely formatted float
6028// out of the APFloat class without just getting the float, double or quad
6029// and then using a formatted print on it which defeats the purpose. We ideally
6030// would like to get perfect string values for any kind of float semantics
6031// so we can support remote targets. The code below also requires a patch to
6032// llvm::APInt.
6033//bool
6034//ClangASTContext::ConvertFloatValueToString (ASTContext *ast, clang_type_t clang_type, const uint8_t* bytes, size_t byte_size, int apint_byte_order, std::string &float_str)
6035//{
6036//  uint32_t count = 0;
6037//  bool is_complex = false;
6038//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6039//  {
6040//      unsigned num_bytes_per_float = byte_size / count;
6041//      unsigned num_bits_per_float = num_bytes_per_float * 8;
6042//
6043//      float_str.clear();
6044//      uint32_t i;
6045//      for (i=0; i<count; i++)
6046//      {
6047//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
6048//          bool is_ieee = false;
6049//          APFloat ap_float(ap_int, is_ieee);
6050//          char s[1024];
6051//          unsigned int hex_digits = 0;
6052//          bool upper_case = false;
6053//
6054//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
6055//          {
6056//              if (i > 0)
6057//                  float_str.append(", ");
6058//              float_str.append(s);
6059//              if (i == 1 && is_complex)
6060//                  float_str.append(1, 'i');
6061//          }
6062//      }
6063//      return !float_str.empty();
6064//  }
6065//  return false;
6066//}
6067
6068size_t
6069ClangASTContext::ConvertStringToFloatValue (ASTContext *ast, clang_type_t clang_type, const char *s, uint8_t *dst, size_t dst_size)
6070{
6071    if (clang_type)
6072    {
6073        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6074        uint32_t count = 0;
6075        bool is_complex = false;
6076        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6077        {
6078            // TODO: handle complex and vector types
6079            if (count != 1)
6080                return false;
6081
6082            StringRef s_sref(s);
6083            APFloat ap_float(ast->getFloatTypeSemantics(qual_type), s_sref);
6084
6085            const uint64_t bit_size = ast->getTypeSize (qual_type);
6086            const uint64_t byte_size = bit_size / 8;
6087            if (dst_size >= byte_size)
6088            {
6089                if (bit_size == sizeof(float)*8)
6090                {
6091                    float float32 = ap_float.convertToFloat();
6092                    ::memcpy (dst, &float32, byte_size);
6093                    return byte_size;
6094                }
6095                else if (bit_size >= 64)
6096                {
6097                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
6098                    ::memcpy (dst, ap_int.getRawData(), byte_size);
6099                    return byte_size;
6100                }
6101            }
6102        }
6103    }
6104    return 0;
6105}
6106
6107unsigned
6108ClangASTContext::GetTypeQualifiers(clang_type_t clang_type)
6109{
6110    assert (clang_type);
6111
6112    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6113
6114    return qual_type.getQualifiers().getCVRQualifiers();
6115}
6116
6117uint64_t
6118GetTypeFlags(clang::ASTContext *ast, lldb::clang_type_t clang_type)
6119{
6120    assert (clang_type);
6121
6122    clang::ExternalASTSource *external_ast_source = ast->getExternalSource();
6123
6124    if (!external_ast_source)
6125        return 0;
6126
6127    ClangExternalASTSourceCommon *common_ast_source = static_cast<ClangExternalASTSourceCommon*>(external_ast_source);
6128
6129    return common_ast_source->GetMetadata((uintptr_t)clang_type);
6130}
6131
6132void
6133SetTypeFlags(clang::ASTContext *ast, lldb::clang_type_t clang_type, uint64_t flags)
6134{
6135    assert (clang_type);
6136
6137    clang::ExternalASTSource *external_ast_source = ast->getExternalSource();
6138
6139    if (!external_ast_source)
6140        return;
6141
6142    ClangExternalASTSourceCommon *common_ast_source = static_cast<ClangExternalASTSourceCommon*>(external_ast_source);
6143
6144    return common_ast_source->SetMetadata((uintptr_t)clang_type, flags);
6145}
6146
6147bool
6148ClangASTContext::GetCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6149{
6150    if (clang_type == NULL)
6151        return false;
6152
6153    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type));
6154}
6155
6156
6157bool
6158ClangASTContext::GetCompleteType (clang_type_t clang_type)
6159{
6160    return ClangASTContext::GetCompleteType (getASTContext(), clang_type);
6161}
6162
6163bool
6164ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
6165                                  clang::Decl *decl)
6166{
6167    if (!decl)
6168        return false;
6169
6170    ExternalASTSource *ast_source = ast->getExternalSource();
6171
6172    if (!ast_source)
6173        return false;
6174
6175    if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
6176    {
6177        if (tag_decl->getDefinition())
6178            return true;
6179
6180        if (!tag_decl->hasExternalLexicalStorage())
6181            return false;
6182
6183        ast_source->CompleteType(tag_decl);
6184
6185        return !tag_decl->getTypeForDecl()->isIncompleteType();
6186    }
6187    else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
6188    {
6189        if (objc_interface_decl->getDefinition())
6190            return true;
6191
6192        if (!objc_interface_decl->hasExternalLexicalStorage())
6193            return false;
6194
6195        ast_source->CompleteType(objc_interface_decl);
6196
6197        return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
6198    }
6199    else
6200    {
6201        return false;
6202    }
6203}
6204
6205clang::DeclContext *
6206ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
6207{
6208    return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
6209}
6210
6211clang::DeclContext *
6212ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
6213{
6214    return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
6215}
6216
6217