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