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