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