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