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