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