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