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