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