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