ClangASTContext.cpp revision f85902c1ccc95b6e97b6d818243047992f79c4f3
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                                                         is_static,
1817                                                         SC_None,
1818                                                         is_inline,
1819                                                         false /*is_constexpr*/,
1820                                                         SourceLocation());
1821            }
1822            else if (num_params == 0)
1823            {
1824                // Conversion operators don't take params...
1825                cxx_method_decl = CXXConversionDecl::Create (*ast,
1826                                                             cxx_record_decl,
1827                                                             SourceLocation(),
1828                                                             DeclarationNameInfo (ast->DeclarationNames.getCXXConversionFunctionName (ast->getCanonicalType (function_Type->getResultType())), SourceLocation()),
1829                                                             method_qual_type,
1830                                                             NULL, // TypeSourceInfo *
1831                                                             is_inline,
1832                                                             is_explicit,
1833                                                             false /*is_constexpr*/,
1834                                                             SourceLocation());
1835            }
1836        }
1837
1838        if (cxx_method_decl == NULL)
1839        {
1840            cxx_method_decl = CXXMethodDecl::Create (*ast,
1841                                                     cxx_record_decl,
1842                                                     SourceLocation(),
1843                                                     DeclarationNameInfo (decl_name, SourceLocation()),
1844                                                     method_qual_type,
1845                                                     NULL, // TypeSourceInfo *
1846                                                     is_static,
1847                                                     SC_None,
1848                                                     is_inline,
1849                                                     false /*is_constexpr*/,
1850                                                     SourceLocation());
1851        }
1852    }
1853
1854    AccessSpecifier access_specifier = ConvertAccessTypeToAccessSpecifier (access);
1855
1856    cxx_method_decl->setAccess (access_specifier);
1857    cxx_method_decl->setVirtualAsWritten (is_virtual);
1858
1859    if (is_attr_used)
1860        cxx_method_decl->addAttr(::new (*ast) UsedAttr(SourceRange(), *ast));
1861
1862    // Populate the method decl with parameter decls
1863
1864    llvm::SmallVector<ParmVarDecl *, 12> params;
1865
1866    for (int param_index = 0;
1867         param_index < num_params;
1868         ++param_index)
1869    {
1870        params.push_back (ParmVarDecl::Create (*ast,
1871                                               cxx_method_decl,
1872                                               SourceLocation(),
1873                                               SourceLocation(),
1874                                               NULL, // anonymous
1875                                               method_function_prototype->getArgType(param_index),
1876                                               NULL,
1877                                               SC_None,
1878                                               SC_None,
1879                                               NULL));
1880    }
1881
1882    cxx_method_decl->setParams (ArrayRef<ParmVarDecl*>(params));
1883
1884    cxx_record_decl->addDecl (cxx_method_decl);
1885
1886    // Sometimes the debug info will mention a constructor (default/copy/move),
1887    // destructor, or assignment operator (copy/move) but there won't be any
1888    // version of this in the code. So we check if the function was artificially
1889    // generated and if it is trivial and this lets the compiler/backend know
1890    // that it can inline the IR for these when it needs to and we can avoid a
1891    // "missing function" error when running expressions.
1892
1893    if (is_artificial)
1894    {
1895        if (cxx_ctor_decl &&
1896            ((cxx_ctor_decl->isDefaultConstructor() && cxx_record_decl->hasTrivialDefaultConstructor ()) ||
1897             (cxx_ctor_decl->isCopyConstructor()    && cxx_record_decl->hasTrivialCopyConstructor    ()) ||
1898             (cxx_ctor_decl->isMoveConstructor()    && cxx_record_decl->hasTrivialMoveConstructor    ()) ))
1899        {
1900            cxx_ctor_decl->setDefaulted();
1901            cxx_ctor_decl->setTrivial(true);
1902        }
1903        else if (cxx_dtor_decl)
1904        {
1905            if (cxx_record_decl->hasTrivialDestructor())
1906            {
1907                cxx_dtor_decl->setDefaulted();
1908                cxx_dtor_decl->setTrivial(true);
1909            }
1910        }
1911        else if ((cxx_method_decl->isCopyAssignmentOperator() && cxx_record_decl->hasTrivialCopyAssignment()) ||
1912                 (cxx_method_decl->isMoveAssignmentOperator() && cxx_record_decl->hasTrivialMoveAssignment()))
1913        {
1914            cxx_method_decl->setDefaulted();
1915            cxx_method_decl->setTrivial(true);
1916        }
1917    }
1918
1919#ifdef LLDB_CONFIGURATION_DEBUG
1920    VerifyDecl(cxx_method_decl);
1921#endif
1922
1923//    printf ("decl->isPolymorphic()             = %i\n", cxx_record_decl->isPolymorphic());
1924//    printf ("decl->isAggregate()               = %i\n", cxx_record_decl->isAggregate());
1925//    printf ("decl->isPOD()                     = %i\n", cxx_record_decl->isPOD());
1926//    printf ("decl->isEmpty()                   = %i\n", cxx_record_decl->isEmpty());
1927//    printf ("decl->isAbstract()                = %i\n", cxx_record_decl->isAbstract());
1928//    printf ("decl->hasTrivialConstructor()     = %i\n", cxx_record_decl->hasTrivialConstructor());
1929//    printf ("decl->hasTrivialCopyConstructor() = %i\n", cxx_record_decl->hasTrivialCopyConstructor());
1930//    printf ("decl->hasTrivialCopyAssignment()  = %i\n", cxx_record_decl->hasTrivialCopyAssignment());
1931//    printf ("decl->hasTrivialDestructor()      = %i\n", cxx_record_decl->hasTrivialDestructor());
1932    return cxx_method_decl;
1933}
1934
1935clang::FieldDecl *
1936ClangASTContext::AddFieldToRecordType
1937(
1938    ASTContext *ast,
1939    clang_type_t record_clang_type,
1940    const char *name,
1941    clang_type_t field_type,
1942    AccessType access,
1943    uint32_t bitfield_bit_size
1944)
1945{
1946    if (record_clang_type == NULL || field_type == NULL)
1947        return NULL;
1948
1949    FieldDecl *field = NULL;
1950    IdentifierTable *identifier_table = &ast->Idents;
1951
1952    assert (ast != NULL);
1953    assert (identifier_table != NULL);
1954
1955    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
1956
1957    const clang::Type *clang_type = record_qual_type.getTypePtr();
1958    if (clang_type)
1959    {
1960        const RecordType *record_type = dyn_cast<RecordType>(clang_type);
1961
1962        if (record_type)
1963        {
1964            RecordDecl *record_decl = record_type->getDecl();
1965
1966            clang::Expr *bit_width = NULL;
1967            if (bitfield_bit_size != 0)
1968            {
1969                APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
1970                bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
1971            }
1972            field = FieldDecl::Create (*ast,
1973                                       record_decl,
1974                                       SourceLocation(),
1975                                       SourceLocation(),
1976                                       name ? &identifier_table->get(name) : NULL, // Identifier
1977                                       QualType::getFromOpaquePtr(field_type), // Field type
1978                                       NULL,            // TInfo *
1979                                       bit_width,       // BitWidth
1980                                       false,           // Mutable
1981                                       ICIS_NoInit);    // HasInit
1982
1983            if (!name) {
1984                // Determine whether this field corresponds to an anonymous
1985                // struct or union.
1986                if (const TagType *TagT = field->getType()->getAs<TagType>()) {
1987                  if (RecordDecl *Rec = dyn_cast<RecordDecl>(TagT->getDecl()))
1988                    if (!Rec->getDeclName()) {
1989                      Rec->setAnonymousStructOrUnion(true);
1990                      field->setImplicit();
1991
1992                    }
1993                }
1994            }
1995
1996            field->setAccess (ConvertAccessTypeToAccessSpecifier (access));
1997
1998            if (field)
1999            {
2000                record_decl->addDecl(field);
2001
2002#ifdef LLDB_CONFIGURATION_DEBUG
2003                VerifyDecl(field);
2004#endif
2005            }
2006        }
2007        else
2008        {
2009            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(clang_type);
2010            if (objc_class_type)
2011            {
2012                bool is_synthesized = false;
2013                field = ClangASTContext::AddObjCClassIVar (ast,
2014                                                   record_clang_type,
2015                                                   name,
2016                                                   field_type,
2017                                                   access,
2018                                                   bitfield_bit_size,
2019                                                   is_synthesized);
2020            }
2021        }
2022    }
2023    return field;
2024}
2025
2026static clang::AccessSpecifier UnifyAccessSpecifiers (clang::AccessSpecifier lhs,
2027                                                     clang::AccessSpecifier rhs)
2028{
2029    clang::AccessSpecifier ret = lhs;
2030
2031    // Make the access equal to the stricter of the field and the nested field's access
2032    switch (ret)
2033    {
2034        case clang::AS_none:
2035            break;
2036        case clang::AS_private:
2037            break;
2038        case clang::AS_protected:
2039            if (rhs == AS_private)
2040                ret = AS_private;
2041            break;
2042        case clang::AS_public:
2043            ret = rhs;
2044            break;
2045    }
2046
2047    return ret;
2048}
2049
2050void
2051ClangASTContext::BuildIndirectFields (clang::ASTContext *ast,
2052                                      lldb::clang_type_t record_clang_type)
2053{
2054    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
2055
2056    const RecordType *record_type = record_qual_type->getAs<RecordType>();
2057
2058    if (!record_type)
2059        return;
2060
2061    RecordDecl *record_decl = record_type->getDecl();
2062
2063    if (!record_decl)
2064        return;
2065
2066    typedef llvm::SmallVector <IndirectFieldDecl *, 1> IndirectFieldVector;
2067
2068    IndirectFieldVector indirect_fields;
2069    RecordDecl::field_iterator field_pos;
2070    RecordDecl::field_iterator field_end_pos = record_decl->field_end();
2071    RecordDecl::field_iterator last_field_pos = field_end_pos;
2072    for (field_pos = record_decl->field_begin(); field_pos != field_end_pos; last_field_pos = field_pos++)
2073    {
2074        if (field_pos->isAnonymousStructOrUnion())
2075        {
2076            QualType field_qual_type = field_pos->getType();
2077
2078            const RecordType *field_record_type = field_qual_type->getAs<RecordType>();
2079
2080            if (!field_record_type)
2081                continue;
2082
2083            RecordDecl *field_record_decl = field_record_type->getDecl();
2084
2085            if (!field_record_decl)
2086                continue;
2087
2088            for (RecordDecl::decl_iterator di = field_record_decl->decls_begin(), de = field_record_decl->decls_end();
2089                 di != de;
2090                 ++di)
2091            {
2092                if (FieldDecl *nested_field_decl = dyn_cast<FieldDecl>(*di))
2093                {
2094                    NamedDecl **chain = new (*ast) NamedDecl*[2];
2095                    chain[0] = *field_pos;
2096                    chain[1] = nested_field_decl;
2097                    IndirectFieldDecl *indirect_field = IndirectFieldDecl::Create(*ast,
2098                                                                                  record_decl,
2099                                                                                  SourceLocation(),
2100                                                                                  nested_field_decl->getIdentifier(),
2101                                                                                  nested_field_decl->getType(),
2102                                                                                  chain,
2103                                                                                  2);
2104
2105                    indirect_field->setAccess(UnifyAccessSpecifiers(field_pos->getAccess(),
2106                                                                    nested_field_decl->getAccess()));
2107
2108                    indirect_fields.push_back(indirect_field);
2109                }
2110                else if (IndirectFieldDecl *nested_indirect_field_decl = dyn_cast<IndirectFieldDecl>(*di))
2111                {
2112                    int nested_chain_size = nested_indirect_field_decl->getChainingSize();
2113                    NamedDecl **chain = new (*ast) NamedDecl*[nested_chain_size + 1];
2114                    chain[0] = *field_pos;
2115
2116                    int chain_index = 1;
2117                    for (IndirectFieldDecl::chain_iterator nci = nested_indirect_field_decl->chain_begin(),
2118                         nce = nested_indirect_field_decl->chain_end();
2119                         nci < nce;
2120                         ++nci)
2121                    {
2122                        chain[chain_index] = *nci;
2123                        chain_index++;
2124                    }
2125
2126                    IndirectFieldDecl *indirect_field = IndirectFieldDecl::Create(*ast,
2127                                                                                  record_decl,
2128                                                                                  SourceLocation(),
2129                                                                                  nested_indirect_field_decl->getIdentifier(),
2130                                                                                  nested_indirect_field_decl->getType(),
2131                                                                                  chain,
2132                                                                                  nested_chain_size + 1);
2133
2134                    indirect_field->setAccess(UnifyAccessSpecifiers(field_pos->getAccess(),
2135                                                                    nested_indirect_field_decl->getAccess()));
2136
2137                    indirect_fields.push_back(indirect_field);
2138                }
2139            }
2140        }
2141    }
2142
2143    // Check the last field to see if it has an incomplete array type as its
2144    // last member and if it does, the tell the record decl about it
2145    if (last_field_pos != field_end_pos)
2146    {
2147        if (last_field_pos->getType()->isIncompleteArrayType())
2148            record_decl->hasFlexibleArrayMember();
2149    }
2150
2151    for (IndirectFieldVector::iterator ifi = indirect_fields.begin(), ife = indirect_fields.end();
2152         ifi < ife;
2153         ++ifi)
2154    {
2155        record_decl->addDecl(*ifi);
2156    }
2157}
2158
2159bool
2160ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
2161{
2162    return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
2163}
2164
2165bool
2166ClangASTContext::FieldIsBitfield
2167(
2168    ASTContext *ast,
2169    FieldDecl* field,
2170    uint32_t& bitfield_bit_size
2171)
2172{
2173    if (ast == NULL || field == NULL)
2174        return false;
2175
2176    if (field->isBitField())
2177    {
2178        Expr* bit_width_expr = field->getBitWidth();
2179        if (bit_width_expr)
2180        {
2181            llvm::APSInt bit_width_apsint;
2182            if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast))
2183            {
2184                bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
2185                return true;
2186            }
2187        }
2188    }
2189    return false;
2190}
2191
2192bool
2193ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
2194{
2195    if (record_decl == NULL)
2196        return false;
2197
2198    if (!record_decl->field_empty())
2199        return true;
2200
2201    // No fields, lets check this is a CXX record and check the base classes
2202    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2203    if (cxx_record_decl)
2204    {
2205        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2206        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2207             base_class != base_class_end;
2208             ++base_class)
2209        {
2210            const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
2211            if (RecordHasFields(base_class_decl))
2212                return true;
2213        }
2214    }
2215    return false;
2216}
2217
2218void
2219ClangASTContext::SetDefaultAccessForRecordFields (clang_type_t clang_type, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities)
2220{
2221    if (clang_type)
2222    {
2223        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2224
2225        const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
2226        if (record_type)
2227        {
2228            RecordDecl *record_decl = record_type->getDecl();
2229            if (record_decl)
2230            {
2231                uint32_t field_idx;
2232                RecordDecl::field_iterator field, field_end;
2233                for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0;
2234                     field != field_end;
2235                     ++field, ++field_idx)
2236                {
2237                    // If no accessibility was assigned, assign the correct one
2238                    if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none)
2239                        field->setAccess ((AccessSpecifier)default_accessibility);
2240                }
2241            }
2242        }
2243    }
2244}
2245
2246#pragma mark C++ Base Classes
2247
2248CXXBaseSpecifier *
2249ClangASTContext::CreateBaseClassSpecifier (clang_type_t base_class_type, AccessType access, bool is_virtual, bool base_of_class)
2250{
2251    if (base_class_type)
2252        return new CXXBaseSpecifier (SourceRange(),
2253                                     is_virtual,
2254                                     base_of_class,
2255                                     ConvertAccessTypeToAccessSpecifier (access),
2256                                     getASTContext()->getTrivialTypeSourceInfo (QualType::getFromOpaquePtr(base_class_type)),
2257                                     SourceLocation());
2258    return NULL;
2259}
2260
2261void
2262ClangASTContext::DeleteBaseClassSpecifiers (CXXBaseSpecifier **base_classes, unsigned num_base_classes)
2263{
2264    for (unsigned i=0; i<num_base_classes; ++i)
2265    {
2266        delete base_classes[i];
2267        base_classes[i] = NULL;
2268    }
2269}
2270
2271bool
2272ClangASTContext::SetBaseClassesForClassType (clang_type_t class_clang_type, CXXBaseSpecifier const * const *base_classes, unsigned num_base_classes)
2273{
2274    if (class_clang_type)
2275    {
2276        CXXRecordDecl *cxx_record_decl = QualType::getFromOpaquePtr(class_clang_type)->getAsCXXRecordDecl();
2277        if (cxx_record_decl)
2278        {
2279            cxx_record_decl->setBases(base_classes, num_base_classes);
2280            return true;
2281        }
2282    }
2283    return false;
2284}
2285#pragma mark Objective C Classes
2286
2287clang_type_t
2288ClangASTContext::CreateObjCClass
2289(
2290    const char *name,
2291    DeclContext *decl_ctx,
2292    bool isForwardDecl,
2293    bool isInternal,
2294    ClangASTMetadata *metadata
2295)
2296{
2297    ASTContext *ast = getASTContext();
2298    assert (ast != NULL);
2299    assert (name && name[0]);
2300    if (decl_ctx == NULL)
2301        decl_ctx = ast->getTranslationUnitDecl();
2302
2303    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
2304    // we will need to update this code. I was told to currently always use
2305    // the CXXRecordDecl class since we often don't know from debug information
2306    // if something is struct or a class, so we default to always use the more
2307    // complete definition just in case.
2308    ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast,
2309                                                         decl_ctx,
2310                                                         SourceLocation(),
2311                                                         &ast->Idents.get(name),
2312                                                         NULL,
2313                                                         SourceLocation(),
2314                                                         /*isForwardDecl,*/
2315                                                         isInternal);
2316
2317    if (decl && metadata)
2318        SetMetadata(ast, decl, *metadata);
2319
2320    return ast->getObjCInterfaceType(decl).getAsOpaquePtr();
2321}
2322
2323bool
2324ClangASTContext::SetObjCSuperClass (clang_type_t class_opaque_type, clang_type_t super_opaque_type)
2325{
2326    if (class_opaque_type && super_opaque_type)
2327    {
2328        QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2329        QualType super_qual_type(QualType::getFromOpaquePtr(super_opaque_type));
2330        const clang::Type *class_type = class_qual_type.getTypePtr();
2331        const clang::Type *super_type = super_qual_type.getTypePtr();
2332        if (class_type && super_type)
2333        {
2334            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2335            const ObjCObjectType *objc_super_type = dyn_cast<ObjCObjectType>(super_type);
2336            if (objc_class_type && objc_super_type)
2337            {
2338                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2339                ObjCInterfaceDecl *super_interface_decl = objc_super_type->getInterface();
2340                if (class_interface_decl && super_interface_decl)
2341                {
2342                    class_interface_decl->setSuperClass(super_interface_decl);
2343                    return true;
2344                }
2345            }
2346        }
2347    }
2348    return false;
2349}
2350
2351
2352FieldDecl *
2353ClangASTContext::AddObjCClassIVar
2354(
2355    ASTContext *ast,
2356    clang_type_t class_opaque_type,
2357    const char *name,
2358    clang_type_t ivar_opaque_type,
2359    AccessType access,
2360    uint32_t bitfield_bit_size,
2361    bool is_synthesized
2362)
2363{
2364    if (class_opaque_type == NULL || ivar_opaque_type == NULL)
2365        return NULL;
2366
2367    ObjCIvarDecl *field = NULL;
2368
2369    IdentifierTable *identifier_table = &ast->Idents;
2370
2371    assert (ast != NULL);
2372    assert (identifier_table != NULL);
2373
2374    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2375
2376    const clang::Type *class_type = class_qual_type.getTypePtr();
2377    if (class_type)
2378    {
2379        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2380
2381        if (objc_class_type)
2382        {
2383            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2384
2385            if (class_interface_decl)
2386            {
2387                clang::Expr *bit_width = NULL;
2388                if (bitfield_bit_size != 0)
2389                {
2390                    APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
2391                    bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
2392                }
2393
2394                field = ObjCIvarDecl::Create (*ast,
2395                                              class_interface_decl,
2396                                              SourceLocation(),
2397                                              SourceLocation(),
2398                                              name ? &identifier_table->get(name) : NULL, // Identifier
2399                                              QualType::getFromOpaquePtr(ivar_opaque_type), // Field type
2400                                              NULL, // TypeSourceInfo *
2401                                              ConvertAccessTypeToObjCIvarAccessControl (access),
2402                                              bit_width,
2403                                              is_synthesized);
2404
2405                if (field)
2406                {
2407                    class_interface_decl->addDecl(field);
2408
2409#ifdef LLDB_CONFIGURATION_DEBUG
2410                    VerifyDecl(field);
2411#endif
2412
2413                    return field;
2414                }
2415            }
2416        }
2417    }
2418    return NULL;
2419}
2420
2421bool
2422ClangASTContext::AddObjCClassProperty
2423(
2424    ASTContext *ast,
2425    clang_type_t class_opaque_type,
2426    const char *property_name,
2427    clang_type_t property_opaque_type,
2428    ObjCIvarDecl *ivar_decl,
2429    const char *property_setter_name,
2430    const char *property_getter_name,
2431    uint32_t property_attributes,
2432    ClangASTMetadata *metadata
2433)
2434{
2435    if (class_opaque_type == NULL || property_name == NULL || property_name[0] == '\0')
2436        return false;
2437
2438    IdentifierTable *identifier_table = &ast->Idents;
2439
2440    assert (ast != NULL);
2441    assert (identifier_table != NULL);
2442
2443    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2444    const clang::Type *class_type = class_qual_type.getTypePtr();
2445    if (class_type)
2446    {
2447        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2448
2449        if (objc_class_type)
2450        {
2451            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2452
2453            clang_type_t property_opaque_type_to_access = NULL;
2454
2455            if (property_opaque_type)
2456                property_opaque_type_to_access = property_opaque_type;
2457            else if (ivar_decl)
2458                property_opaque_type_to_access = ivar_decl->getType().getAsOpaquePtr();
2459
2460            if (class_interface_decl && property_opaque_type_to_access)
2461            {
2462                clang::TypeSourceInfo *prop_type_source;
2463                if (ivar_decl)
2464                    prop_type_source = ast->getTrivialTypeSourceInfo (ivar_decl->getType());
2465                else
2466                    prop_type_source = ast->getTrivialTypeSourceInfo (QualType::getFromOpaquePtr(property_opaque_type));
2467
2468                ObjCPropertyDecl *property_decl = ObjCPropertyDecl::Create(*ast,
2469                                                                           class_interface_decl,
2470                                                                           SourceLocation(), // Source Location
2471                                                                           &identifier_table->get(property_name),
2472                                                                           SourceLocation(), //Source Location for AT
2473                                                                           SourceLocation(), //Source location for (
2474                                                                           prop_type_source
2475                                                                           );
2476
2477                if (property_decl)
2478                {
2479                    if (metadata)
2480                        SetMetadata(ast, property_decl, *metadata);
2481
2482                    class_interface_decl->addDecl (property_decl);
2483
2484                    Selector setter_sel, getter_sel;
2485
2486                    if (property_setter_name != NULL)
2487                    {
2488                        std::string property_setter_no_colon(property_setter_name, strlen(property_setter_name) - 1);
2489                        clang::IdentifierInfo *setter_ident = &identifier_table->get(property_setter_no_colon.c_str());
2490                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2491                    }
2492                    else if (!(property_attributes & DW_APPLE_PROPERTY_readonly))
2493                    {
2494                        std::string setter_sel_string("set");
2495                        setter_sel_string.push_back(::toupper(property_name[0]));
2496                        setter_sel_string.append(&property_name[1]);
2497                        clang::IdentifierInfo *setter_ident = &identifier_table->get(setter_sel_string.c_str());
2498                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2499                    }
2500                    property_decl->setSetterName(setter_sel);
2501                    property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_setter);
2502
2503                    if (property_getter_name != NULL)
2504                    {
2505                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_getter_name);
2506                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2507                    }
2508                    else
2509                    {
2510                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_name);
2511                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2512                    }
2513                    property_decl->setGetterName(getter_sel);
2514                    property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_getter);
2515
2516                    if (ivar_decl)
2517                        property_decl->setPropertyIvarDecl (ivar_decl);
2518
2519                    if (property_attributes & DW_APPLE_PROPERTY_readonly)
2520                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readonly);
2521                    if (property_attributes & DW_APPLE_PROPERTY_readwrite)
2522                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readwrite);
2523                    if (property_attributes & DW_APPLE_PROPERTY_assign)
2524                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_assign);
2525                    if (property_attributes & DW_APPLE_PROPERTY_retain)
2526                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_retain);
2527                    if (property_attributes & DW_APPLE_PROPERTY_copy)
2528                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_copy);
2529                    if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
2530                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_nonatomic);
2531
2532                    if (!getter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(getter_sel))
2533                    {
2534                        QualType result_type = QualType::getFromOpaquePtr(property_opaque_type_to_access);
2535
2536                        const bool isInstance = true;
2537                        const bool isVariadic = false;
2538                        const bool isSynthesized = false;
2539                        const bool isImplicitlyDeclared = true;
2540                        const bool isDefined = false;
2541                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2542                        const bool HasRelatedResultType = false;
2543
2544                        ObjCMethodDecl *getter = ObjCMethodDecl::Create(*ast,
2545                                                                        SourceLocation(),
2546                                                                        SourceLocation(),
2547                                                                        getter_sel,
2548                                                                        result_type,
2549                                                                        NULL,
2550                                                                        class_interface_decl,
2551                                                                        isInstance,
2552                                                                        isVariadic,
2553                                                                        isSynthesized,
2554                                                                        isImplicitlyDeclared,
2555                                                                        isDefined,
2556                                                                        impControl,
2557                                                                        HasRelatedResultType);
2558
2559                        if (getter && metadata)
2560                            SetMetadata(ast, getter, *metadata);
2561
2562                        getter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(), ArrayRef<SourceLocation>());
2563
2564                        class_interface_decl->addDecl(getter);
2565                    }
2566
2567                    if (!setter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(setter_sel))
2568                    {
2569                        QualType result_type = ast->VoidTy;
2570
2571                        const bool isInstance = true;
2572                        const bool isVariadic = false;
2573                        const bool isSynthesized = false;
2574                        const bool isImplicitlyDeclared = true;
2575                        const bool isDefined = false;
2576                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2577                        const bool HasRelatedResultType = false;
2578
2579                        ObjCMethodDecl *setter = ObjCMethodDecl::Create(*ast,
2580                                                                        SourceLocation(),
2581                                                                        SourceLocation(),
2582                                                                        setter_sel,
2583                                                                        result_type,
2584                                                                        NULL,
2585                                                                        class_interface_decl,
2586                                                                        isInstance,
2587                                                                        isVariadic,
2588                                                                        isSynthesized,
2589                                                                        isImplicitlyDeclared,
2590                                                                        isDefined,
2591                                                                        impControl,
2592                                                                        HasRelatedResultType);
2593
2594                        if (setter && metadata)
2595                            SetMetadata(ast, setter, *metadata);
2596
2597                        llvm::SmallVector<ParmVarDecl *, 1> params;
2598
2599                        params.push_back (ParmVarDecl::Create (*ast,
2600                                                               setter,
2601                                                               SourceLocation(),
2602                                                               SourceLocation(),
2603                                                               NULL, // anonymous
2604                                                               QualType::getFromOpaquePtr(property_opaque_type_to_access),
2605                                                               NULL,
2606                                                               SC_Auto,
2607                                                               SC_Auto,
2608                                                               NULL));
2609
2610                        setter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2611
2612                        class_interface_decl->addDecl(setter);
2613                    }
2614
2615                    return true;
2616                }
2617            }
2618        }
2619    }
2620    return false;
2621}
2622
2623bool
2624ClangASTContext::ObjCTypeHasIVars (clang_type_t class_opaque_type, bool check_superclass)
2625{
2626    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2627
2628    const clang::Type *class_type = class_qual_type.getTypePtr();
2629    if (class_type)
2630    {
2631        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2632
2633        if (objc_class_type)
2634            return ObjCDeclHasIVars (objc_class_type->getInterface(), check_superclass);
2635    }
2636    return false;
2637}
2638
2639bool
2640ClangASTContext::ObjCDeclHasIVars (ObjCInterfaceDecl *class_interface_decl, bool check_superclass)
2641{
2642    while (class_interface_decl)
2643    {
2644        if (class_interface_decl->ivar_size() > 0)
2645            return true;
2646
2647        if (check_superclass)
2648            class_interface_decl = class_interface_decl->getSuperClass();
2649        else
2650            break;
2651    }
2652    return false;
2653}
2654
2655ObjCMethodDecl *
2656ClangASTContext::AddMethodToObjCObjectType (ASTContext *ast,
2657                                            clang_type_t class_opaque_type,
2658                                            const char *name,  // the full symbol name as seen in the symbol table ("-[NString stringWithCString:]")
2659                                            clang_type_t method_opaque_type,
2660                                            lldb::AccessType access,
2661                                            bool is_artificial)
2662{
2663    if (class_opaque_type == NULL || method_opaque_type == NULL)
2664        return NULL;
2665
2666    IdentifierTable *identifier_table = &ast->Idents;
2667
2668    assert (ast != NULL);
2669    assert (identifier_table != NULL);
2670
2671    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2672
2673    const clang::Type *class_type = class_qual_type.getTypePtr();
2674    if (class_type == NULL)
2675        return NULL;
2676
2677    const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2678
2679    if (objc_class_type == NULL)
2680        return NULL;
2681
2682    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2683
2684    if (class_interface_decl == NULL)
2685        return NULL;
2686
2687    const char *selector_start = ::strchr (name, ' ');
2688    if (selector_start == NULL)
2689        return NULL;
2690
2691    selector_start++;
2692    llvm::SmallVector<IdentifierInfo *, 12> selector_idents;
2693
2694    size_t len = 0;
2695    const char *start;
2696    //printf ("name = '%s'\n", name);
2697
2698    unsigned num_selectors_with_args = 0;
2699    for (start = selector_start;
2700         start && *start != '\0' && *start != ']';
2701         start += len)
2702    {
2703        len = ::strcspn(start, ":]");
2704        bool has_arg = (start[len] == ':');
2705        if (has_arg)
2706            ++num_selectors_with_args;
2707        selector_idents.push_back (&identifier_table->get (StringRef (start, len)));
2708        if (has_arg)
2709            len += 1;
2710    }
2711
2712
2713    if (selector_idents.size() == 0)
2714        return 0;
2715
2716    clang::Selector method_selector = ast->Selectors.getSelector (num_selectors_with_args ? selector_idents.size() : 0,
2717                                                                          selector_idents.data());
2718
2719    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
2720
2721    // Populate the method decl with parameter decls
2722    const clang::Type *method_type(method_qual_type.getTypePtr());
2723
2724    if (method_type == NULL)
2725        return NULL;
2726
2727    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(method_type));
2728
2729    if (!method_function_prototype)
2730        return NULL;
2731
2732
2733    bool is_variadic = false;
2734    bool is_synthesized = false;
2735    bool is_defined = false;
2736    ObjCMethodDecl::ImplementationControl imp_control = ObjCMethodDecl::None;
2737
2738    const unsigned num_args = method_function_prototype->getNumArgs();
2739
2740    if (num_args != num_selectors_with_args)
2741        return NULL; // some debug information is corrupt.  We are not going to deal with it.
2742
2743    ObjCMethodDecl *objc_method_decl = ObjCMethodDecl::Create (*ast,
2744                                                               SourceLocation(), // beginLoc,
2745                                                               SourceLocation(), // endLoc,
2746                                                               method_selector,
2747                                                               method_function_prototype->getResultType(),
2748                                                               NULL, // TypeSourceInfo *ResultTInfo,
2749                                                               GetDeclContextForType (class_opaque_type),
2750                                                               name[0] == '-',
2751                                                               is_variadic,
2752                                                               is_synthesized,
2753                                                               true, // is_implicitly_declared; we force this to true because we don't have source locations
2754                                                               is_defined,
2755                                                               imp_control,
2756                                                               false /*has_related_result_type*/);
2757
2758
2759    if (objc_method_decl == NULL)
2760        return NULL;
2761
2762    if (num_args > 0)
2763    {
2764        llvm::SmallVector<ParmVarDecl *, 12> params;
2765
2766        for (int param_index = 0; param_index < num_args; ++param_index)
2767        {
2768            params.push_back (ParmVarDecl::Create (*ast,
2769                                                   objc_method_decl,
2770                                                   SourceLocation(),
2771                                                   SourceLocation(),
2772                                                   NULL, // anonymous
2773                                                   method_function_prototype->getArgType(param_index),
2774                                                   NULL,
2775                                                   SC_Auto,
2776                                                   SC_Auto,
2777                                                   NULL));
2778        }
2779
2780        objc_method_decl->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2781    }
2782
2783    class_interface_decl->addDecl (objc_method_decl);
2784
2785#ifdef LLDB_CONFIGURATION_DEBUG
2786    VerifyDecl(objc_method_decl);
2787#endif
2788
2789    return objc_method_decl;
2790}
2791
2792size_t
2793ClangASTContext::GetNumTemplateArguments (clang::ASTContext *ast, clang_type_t clang_type)
2794{
2795    if (clang_type)
2796    {
2797        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2798
2799        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2800        switch (type_class)
2801        {
2802            case clang::Type::Record:
2803                if (GetCompleteQualType (ast, qual_type))
2804                {
2805                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2806                    if (cxx_record_decl)
2807                    {
2808                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2809                        if (template_decl)
2810                            return template_decl->getTemplateArgs().size();
2811                    }
2812                }
2813                break;
2814
2815            case clang::Type::Typedef:
2816                return ClangASTContext::GetNumTemplateArguments (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
2817
2818            case clang::Type::Elaborated:
2819                return ClangASTContext::GetNumTemplateArguments (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
2820
2821            default:
2822                break;
2823        }
2824    }
2825    return 0;
2826}
2827
2828clang_type_t
2829ClangASTContext::GetTemplateArgument (clang::ASTContext *ast, clang_type_t clang_type, size_t arg_idx, lldb::TemplateArgumentKind &kind)
2830{
2831    if (clang_type)
2832    {
2833        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2834
2835        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2836        switch (type_class)
2837        {
2838            case clang::Type::Record:
2839                if (GetCompleteQualType (ast, qual_type))
2840                {
2841                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2842                    if (cxx_record_decl)
2843                    {
2844                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2845                        if (template_decl && arg_idx < template_decl->getTemplateArgs().size())
2846                        {
2847                            const TemplateArgument &template_arg = template_decl->getTemplateArgs()[arg_idx];
2848                            switch (template_arg.getKind())
2849                            {
2850                                case clang::TemplateArgument::Null:
2851                                    kind = eTemplateArgumentKindNull;
2852                                    return NULL;
2853
2854                                case clang::TemplateArgument::Type:
2855                                    kind = eTemplateArgumentKindType;
2856                                    return template_arg.getAsType().getAsOpaquePtr();
2857
2858                                case clang::TemplateArgument::Declaration:
2859                                    kind = eTemplateArgumentKindDeclaration;
2860                                    return NULL;
2861
2862                                case clang::TemplateArgument::Integral:
2863                                    kind = eTemplateArgumentKindIntegral;
2864                                    return template_arg.getIntegralType().getAsOpaquePtr();
2865
2866                                case clang::TemplateArgument::Template:
2867                                    kind = eTemplateArgumentKindTemplate;
2868                                    return NULL;
2869
2870                                case clang::TemplateArgument::TemplateExpansion:
2871                                    kind = eTemplateArgumentKindTemplateExpansion;
2872                                    return NULL;
2873
2874                                case clang::TemplateArgument::Expression:
2875                                    kind = eTemplateArgumentKindExpression;
2876                                    return NULL;
2877
2878                                case clang::TemplateArgument::Pack:
2879                                    kind = eTemplateArgumentKindPack;
2880                                    return NULL;
2881
2882                                default:
2883                                    assert (!"Unhandled TemplateArgument::ArgKind");
2884                                    kind = eTemplateArgumentKindNull;
2885                                    return NULL;
2886                            }
2887                        }
2888                    }
2889                }
2890                break;
2891
2892            case clang::Type::Typedef:
2893                return ClangASTContext::GetTemplateArgument (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), arg_idx, kind);
2894
2895            case clang::Type::Elaborated:
2896                return ClangASTContext::GetTemplateArgument (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), arg_idx, kind);
2897
2898            default:
2899                break;
2900        }
2901    }
2902    kind = eTemplateArgumentKindNull;
2903    return NULL;
2904}
2905
2906uint32_t
2907ClangASTContext::GetTypeInfo
2908(
2909    clang_type_t clang_type,
2910    clang::ASTContext *ast,
2911    clang_type_t *pointee_or_element_clang_type
2912)
2913{
2914    if (clang_type == NULL)
2915        return 0;
2916
2917    if (pointee_or_element_clang_type)
2918        *pointee_or_element_clang_type = NULL;
2919
2920    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2921
2922    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2923    switch (type_class)
2924    {
2925    case clang::Type::Builtin:
2926        switch (cast<clang::BuiltinType>(qual_type)->getKind())
2927        {
2928        case clang::BuiltinType::ObjCId:
2929        case clang::BuiltinType::ObjCClass:
2930            if (ast && pointee_or_element_clang_type)
2931                *pointee_or_element_clang_type = ast->ObjCBuiltinClassTy.getAsOpaquePtr();
2932            return eTypeIsBuiltIn | eTypeIsPointer | eTypeHasValue | eTypeIsObjC;
2933                break;
2934        case clang::BuiltinType::Bool:
2935        case clang::BuiltinType::Char_U:
2936        case clang::BuiltinType::UChar:
2937        case clang::BuiltinType::WChar_U:
2938        case clang::BuiltinType::Char16:
2939        case clang::BuiltinType::Char32:
2940        case clang::BuiltinType::UShort:
2941        case clang::BuiltinType::UInt:
2942        case clang::BuiltinType::ULong:
2943        case clang::BuiltinType::ULongLong:
2944        case clang::BuiltinType::UInt128:
2945        case clang::BuiltinType::Char_S:
2946        case clang::BuiltinType::SChar:
2947        case clang::BuiltinType::WChar_S:
2948        case clang::BuiltinType::Short:
2949        case clang::BuiltinType::Int:
2950        case clang::BuiltinType::Long:
2951        case clang::BuiltinType::LongLong:
2952        case clang::BuiltinType::Int128:
2953        case clang::BuiltinType::Float:
2954        case clang::BuiltinType::Double:
2955        case clang::BuiltinType::LongDouble:
2956                return eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar;
2957        default:
2958            break;
2959        }
2960        return eTypeIsBuiltIn | eTypeHasValue;
2961
2962    case clang::Type::BlockPointer:
2963        if (pointee_or_element_clang_type)
2964            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2965        return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
2966
2967    case clang::Type::Complex:                          return eTypeIsBuiltIn | eTypeHasValue;
2968
2969    case clang::Type::ConstantArray:
2970    case clang::Type::DependentSizedArray:
2971    case clang::Type::IncompleteArray:
2972    case clang::Type::VariableArray:
2973        if (pointee_or_element_clang_type)
2974            *pointee_or_element_clang_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
2975        return eTypeHasChildren | eTypeIsArray;
2976
2977    case clang::Type::DependentName:                    return 0;
2978    case clang::Type::DependentSizedExtVector:          return eTypeHasChildren | eTypeIsVector;
2979    case clang::Type::DependentTemplateSpecialization:  return eTypeIsTemplate;
2980    case clang::Type::Decltype:                         return 0;
2981
2982    case clang::Type::Enum:
2983        if (pointee_or_element_clang_type)
2984            *pointee_or_element_clang_type = cast<EnumType>(qual_type)->getDecl()->getIntegerType().getAsOpaquePtr();
2985        return eTypeIsEnumeration | eTypeHasValue;
2986
2987    case clang::Type::Elaborated:
2988        return ClangASTContext::GetTypeInfo (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
2989                                             ast,
2990                                             pointee_or_element_clang_type);
2991    case clang::Type::ExtVector:                        return eTypeHasChildren | eTypeIsVector;
2992    case clang::Type::FunctionProto:                    return eTypeIsFuncPrototype | eTypeHasValue;
2993    case clang::Type::FunctionNoProto:                  return eTypeIsFuncPrototype | eTypeHasValue;
2994    case clang::Type::InjectedClassName:                return 0;
2995
2996    case clang::Type::LValueReference:
2997    case clang::Type::RValueReference:
2998        if (pointee_or_element_clang_type)
2999            *pointee_or_element_clang_type = cast<ReferenceType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr();
3000        return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
3001
3002    case clang::Type::MemberPointer:                    return eTypeIsPointer   | eTypeIsMember | eTypeHasValue;
3003
3004    case clang::Type::ObjCObjectPointer:
3005        if (pointee_or_element_clang_type)
3006            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
3007        return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue;
3008
3009    case clang::Type::ObjCObject:                       return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3010    case clang::Type::ObjCInterface:                    return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3011
3012    case clang::Type::Pointer:
3013        if (pointee_or_element_clang_type)
3014            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
3015        return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
3016
3017    case clang::Type::Record:
3018        if (qual_type->getAsCXXRecordDecl())
3019            return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
3020        else
3021            return eTypeHasChildren | eTypeIsStructUnion;
3022        break;
3023    case clang::Type::SubstTemplateTypeParm:            return eTypeIsTemplate;
3024    case clang::Type::TemplateTypeParm:                 return eTypeIsTemplate;
3025    case clang::Type::TemplateSpecialization:           return eTypeIsTemplate;
3026
3027    case clang::Type::Typedef:
3028        return eTypeIsTypedef | ClangASTContext::GetTypeInfo (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3029                                                                  ast,
3030                                                                  pointee_or_element_clang_type);
3031
3032    case clang::Type::TypeOfExpr:                       return 0;
3033    case clang::Type::TypeOf:                           return 0;
3034    case clang::Type::UnresolvedUsing:                  return 0;
3035    case clang::Type::Vector:                           return eTypeHasChildren | eTypeIsVector;
3036    default:                                            return 0;
3037    }
3038    return 0;
3039}
3040
3041
3042#pragma mark Aggregate Types
3043
3044bool
3045ClangASTContext::IsAggregateType (clang_type_t clang_type)
3046{
3047    if (clang_type == NULL)
3048        return false;
3049
3050    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3051
3052    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3053    switch (type_class)
3054    {
3055    case clang::Type::IncompleteArray:
3056    case clang::Type::VariableArray:
3057    case clang::Type::ConstantArray:
3058    case clang::Type::ExtVector:
3059    case clang::Type::Vector:
3060    case clang::Type::Record:
3061    case clang::Type::ObjCObject:
3062    case clang::Type::ObjCInterface:
3063        return true;
3064    case clang::Type::Elaborated:
3065        return ClangASTContext::IsAggregateType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3066    case clang::Type::Typedef:
3067        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3068
3069    default:
3070        break;
3071    }
3072    // The clang type does have a value
3073    return false;
3074}
3075
3076uint32_t
3077ClangASTContext::GetNumChildren (clang::ASTContext *ast, clang_type_t clang_type, bool omit_empty_base_classes)
3078{
3079    if (clang_type == NULL)
3080        return 0;
3081
3082    uint32_t num_children = 0;
3083    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3084    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3085    switch (type_class)
3086    {
3087    case clang::Type::Builtin:
3088        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3089        {
3090        case clang::BuiltinType::ObjCId:    // child is Class
3091        case clang::BuiltinType::ObjCClass: // child is Class
3092            num_children = 1;
3093            break;
3094
3095        default:
3096            break;
3097        }
3098        break;
3099
3100    case clang::Type::Complex: return 0;
3101
3102    case clang::Type::Record:
3103        if (GetCompleteQualType (ast, qual_type))
3104        {
3105            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3106            const RecordDecl *record_decl = record_type->getDecl();
3107            assert(record_decl);
3108            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3109            if (cxx_record_decl)
3110            {
3111                if (omit_empty_base_classes)
3112                {
3113                    // Check each base classes to see if it or any of its
3114                    // base classes contain any fields. This can help
3115                    // limit the noise in variable views by not having to
3116                    // show base classes that contain no members.
3117                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3118                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3119                         base_class != base_class_end;
3120                         ++base_class)
3121                    {
3122                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3123
3124                        // Skip empty base classes
3125                        if (RecordHasFields(base_class_decl) == false)
3126                            continue;
3127
3128                        num_children++;
3129                    }
3130                }
3131                else
3132                {
3133                    // Include all base classes
3134                    num_children += cxx_record_decl->getNumBases();
3135                }
3136
3137            }
3138            RecordDecl::field_iterator field, field_end;
3139            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3140                ++num_children;
3141        }
3142        break;
3143
3144    case clang::Type::ObjCObject:
3145    case clang::Type::ObjCInterface:
3146        if (GetCompleteQualType (ast, qual_type))
3147        {
3148            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3149            assert (objc_class_type);
3150            if (objc_class_type)
3151            {
3152                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3153
3154                if (class_interface_decl)
3155                {
3156
3157                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3158                    if (superclass_interface_decl)
3159                    {
3160                        if (omit_empty_base_classes)
3161                        {
3162                            if (ClangASTContext::ObjCDeclHasIVars (superclass_interface_decl, true))
3163                                ++num_children;
3164                        }
3165                        else
3166                            ++num_children;
3167                    }
3168
3169                    num_children += class_interface_decl->ivar_size();
3170                }
3171            }
3172        }
3173        break;
3174
3175    case clang::Type::ObjCObjectPointer:
3176        {
3177            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(qual_type.getTypePtr());
3178            QualType pointee_type = pointer_type->getPointeeType();
3179            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3180                                                                             pointee_type.getAsOpaquePtr(),
3181                                                                             omit_empty_base_classes);
3182            // If this type points to a simple type, then it has 1 child
3183            if (num_pointee_children == 0)
3184                num_children = 1;
3185            else
3186                num_children = num_pointee_children;
3187        }
3188        break;
3189
3190    case clang::Type::ConstantArray:
3191        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
3192        break;
3193
3194    case clang::Type::Pointer:
3195        {
3196            const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
3197            QualType pointee_type (pointer_type->getPointeeType());
3198            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3199                                                                             pointee_type.getAsOpaquePtr(),
3200                                                                             omit_empty_base_classes);
3201            if (num_pointee_children == 0)
3202            {
3203                // We have a pointer to a pointee type that claims it has no children.
3204                // We will want to look at
3205                num_children = ClangASTContext::GetNumPointeeChildren (pointee_type.getAsOpaquePtr());
3206            }
3207            else
3208                num_children = num_pointee_children;
3209        }
3210        break;
3211
3212    case clang::Type::LValueReference:
3213    case clang::Type::RValueReference:
3214        {
3215            const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
3216            QualType pointee_type = reference_type->getPointeeType();
3217            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3218                                                                             pointee_type.getAsOpaquePtr(),
3219                                                                             omit_empty_base_classes);
3220            // If this type points to a simple type, then it has 1 child
3221            if (num_pointee_children == 0)
3222                num_children = 1;
3223            else
3224                num_children = num_pointee_children;
3225        }
3226        break;
3227
3228
3229    case clang::Type::Typedef:
3230        num_children = ClangASTContext::GetNumChildren (ast,
3231                                                        cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3232                                                        omit_empty_base_classes);
3233        break;
3234
3235    case clang::Type::Elaborated:
3236        num_children = ClangASTContext::GetNumChildren (ast,
3237                                                        cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3238                                                        omit_empty_base_classes);
3239        break;
3240
3241    default:
3242        break;
3243    }
3244    return num_children;
3245}
3246
3247uint32_t
3248ClangASTContext::GetNumDirectBaseClasses (clang::ASTContext *ast, clang_type_t clang_type)
3249{
3250    if (clang_type == NULL)
3251        return 0;
3252
3253    uint32_t count = 0;
3254    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3255    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3256    switch (type_class)
3257    {
3258        case clang::Type::Record:
3259            if (GetCompleteQualType (ast, qual_type))
3260            {
3261                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3262                if (cxx_record_decl)
3263                    count = cxx_record_decl->getNumBases();
3264            }
3265            break;
3266
3267        case clang::Type::ObjCObject:
3268        case clang::Type::ObjCInterface:
3269            if (GetCompleteQualType (ast, qual_type))
3270            {
3271                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3272                if (objc_class_type)
3273                {
3274                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3275
3276                    if (class_interface_decl && class_interface_decl->getSuperClass())
3277                        count = 1;
3278                }
3279            }
3280            break;
3281
3282
3283        case clang::Type::Typedef:
3284            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3285            break;
3286
3287        case clang::Type::Elaborated:
3288            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3289            break;
3290
3291        default:
3292            break;
3293    }
3294    return count;
3295}
3296
3297uint32_t
3298ClangASTContext::GetNumVirtualBaseClasses (clang::ASTContext *ast,
3299                                           clang_type_t clang_type)
3300{
3301    if (clang_type == NULL)
3302        return 0;
3303
3304    uint32_t count = 0;
3305    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3306    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3307    switch (type_class)
3308    {
3309        case clang::Type::Record:
3310            if (GetCompleteQualType (ast, qual_type))
3311            {
3312                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3313                if (cxx_record_decl)
3314                    count = cxx_record_decl->getNumVBases();
3315            }
3316            break;
3317
3318        case clang::Type::Typedef:
3319            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3320            break;
3321
3322        case clang::Type::Elaborated:
3323            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3324            break;
3325
3326        default:
3327            break;
3328    }
3329    return count;
3330}
3331
3332uint32_t
3333ClangASTContext::GetNumFields (clang::ASTContext *ast, clang_type_t clang_type)
3334{
3335    if (clang_type == NULL)
3336        return 0;
3337
3338    uint32_t count = 0;
3339    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3340    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3341    switch (type_class)
3342    {
3343        case clang::Type::Record:
3344            if (GetCompleteQualType (ast, qual_type))
3345            {
3346                const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
3347                if (record_type)
3348                {
3349                    RecordDecl *record_decl = record_type->getDecl();
3350                    if (record_decl)
3351                    {
3352                        uint32_t field_idx = 0;
3353                        RecordDecl::field_iterator field, field_end;
3354                        for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3355                            ++field_idx;
3356                        count = field_idx;
3357                    }
3358                }
3359            }
3360            break;
3361
3362        case clang::Type::Typedef:
3363            count = ClangASTContext::GetNumFields (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3364            break;
3365
3366        case clang::Type::Elaborated:
3367            count = ClangASTContext::GetNumFields (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3368            break;
3369
3370        case clang::Type::ObjCObject:
3371        case clang::Type::ObjCInterface:
3372            if (GetCompleteQualType (ast, qual_type))
3373            {
3374                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3375                if (objc_class_type)
3376                {
3377                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3378
3379                    if (class_interface_decl)
3380                        count = class_interface_decl->ivar_size();
3381                }
3382            }
3383            break;
3384
3385        default:
3386            break;
3387    }
3388    return count;
3389}
3390
3391clang_type_t
3392ClangASTContext::GetDirectBaseClassAtIndex (clang::ASTContext *ast,
3393                                            clang_type_t clang_type,
3394                                            size_t idx,
3395                                            uint32_t *bit_offset_ptr)
3396{
3397    if (clang_type == NULL)
3398        return 0;
3399
3400    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3401    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3402    switch (type_class)
3403    {
3404        case clang::Type::Record:
3405            if (GetCompleteQualType (ast, qual_type))
3406            {
3407                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3408                if (cxx_record_decl)
3409                {
3410                    uint32_t curr_idx = 0;
3411                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3412                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3413                         base_class != base_class_end;
3414                         ++base_class, ++curr_idx)
3415                    {
3416                        if (curr_idx == idx)
3417                        {
3418                            if (bit_offset_ptr)
3419                            {
3420                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3421                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3422//                                if (base_class->isVirtual())
3423//                                    *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3424//                                else
3425                                    *bit_offset_ptr = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3426                            }
3427                            return base_class->getType().getAsOpaquePtr();
3428                        }
3429                    }
3430                }
3431            }
3432            break;
3433
3434        case clang::Type::ObjCObject:
3435        case clang::Type::ObjCInterface:
3436            if (idx == 0 && GetCompleteQualType (ast, qual_type))
3437            {
3438                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3439                if (objc_class_type)
3440                {
3441                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3442
3443                    if (class_interface_decl)
3444                    {
3445                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3446                        if (superclass_interface_decl)
3447                        {
3448                            if (bit_offset_ptr)
3449                                *bit_offset_ptr = 0;
3450                            return ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr();
3451                        }
3452                    }
3453                }
3454            }
3455            break;
3456
3457
3458        case clang::Type::Typedef:
3459            return ClangASTContext::GetDirectBaseClassAtIndex (ast,
3460                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3461                                                               idx,
3462                                                               bit_offset_ptr);
3463
3464        case clang::Type::Elaborated:
3465            return  ClangASTContext::GetDirectBaseClassAtIndex (ast,
3466                                                                cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3467                                                                idx,
3468                                                                bit_offset_ptr);
3469
3470        default:
3471            break;
3472    }
3473    return NULL;
3474}
3475
3476clang_type_t
3477ClangASTContext::GetVirtualBaseClassAtIndex (clang::ASTContext *ast,
3478                                             clang_type_t clang_type,
3479                                             size_t idx,
3480                                             uint32_t *bit_offset_ptr)
3481{
3482    if (clang_type == NULL)
3483        return 0;
3484
3485    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3486    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3487    switch (type_class)
3488    {
3489        case clang::Type::Record:
3490            if (GetCompleteQualType (ast, qual_type))
3491            {
3492                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3493                if (cxx_record_decl)
3494                {
3495                    uint32_t curr_idx = 0;
3496                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3497                    for (base_class = cxx_record_decl->vbases_begin(), base_class_end = cxx_record_decl->vbases_end();
3498                         base_class != base_class_end;
3499                         ++base_class, ++curr_idx)
3500                    {
3501                        if (curr_idx == idx)
3502                        {
3503                            if (bit_offset_ptr)
3504                            {
3505                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3506                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3507                                *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3508
3509                            }
3510                            return base_class->getType().getAsOpaquePtr();
3511                        }
3512                    }
3513                }
3514            }
3515            break;
3516
3517        case clang::Type::Typedef:
3518            return ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3519                                                                cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3520                                                                idx,
3521                                                                bit_offset_ptr);
3522
3523        case clang::Type::Elaborated:
3524            return  ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3525                                                                 cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3526                                                                 idx,
3527                                                                 bit_offset_ptr);
3528
3529        default:
3530            break;
3531    }
3532    return NULL;
3533}
3534
3535clang_type_t
3536ClangASTContext::GetFieldAtIndex (clang::ASTContext *ast,
3537                                  clang_type_t clang_type,
3538                                  size_t idx,
3539                                  std::string& name,
3540                                  uint64_t *bit_offset_ptr,
3541                                  uint32_t *bitfield_bit_size_ptr,
3542                                  bool *is_bitfield_ptr)
3543{
3544    if (clang_type == NULL)
3545        return 0;
3546
3547    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3548    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3549    switch (type_class)
3550    {
3551        case clang::Type::Record:
3552            if (GetCompleteQualType (ast, qual_type))
3553            {
3554                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3555                const RecordDecl *record_decl = record_type->getDecl();
3556                uint32_t field_idx = 0;
3557                RecordDecl::field_iterator field, field_end;
3558                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx)
3559                {
3560                    if (idx == field_idx)
3561                    {
3562                        // Print the member type if requested
3563                        // Print the member name and equal sign
3564                        name.assign(field->getNameAsString());
3565
3566                        // Figure out the type byte size (field_type_info.first) and
3567                        // alignment (field_type_info.second) from the AST context.
3568                        if (bit_offset_ptr)
3569                        {
3570                            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3571                            *bit_offset_ptr = record_layout.getFieldOffset (field_idx);
3572                        }
3573
3574                        const bool is_bitfield = field->isBitField();
3575
3576                        if (bitfield_bit_size_ptr)
3577                        {
3578                            *bitfield_bit_size_ptr = 0;
3579
3580                            if (is_bitfield && ast)
3581                            {
3582                                Expr *bitfield_bit_size_expr = field->getBitWidth();
3583                                llvm::APSInt bitfield_apsint;
3584                                if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3585                                {
3586                                    *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3587                                }
3588                            }
3589                        }
3590                        if (is_bitfield_ptr)
3591                            *is_bitfield_ptr = is_bitfield;
3592
3593                        return field->getType().getAsOpaquePtr();
3594                    }
3595                }
3596            }
3597            break;
3598
3599        case clang::Type::ObjCObject:
3600        case clang::Type::ObjCInterface:
3601            if (GetCompleteQualType (ast, qual_type))
3602            {
3603                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3604                assert (objc_class_type);
3605                if (objc_class_type)
3606                {
3607                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3608
3609                    if (class_interface_decl)
3610                    {
3611                        if (idx < (class_interface_decl->ivar_size()))
3612                        {
3613                            ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
3614                            uint32_t ivar_idx = 0;
3615
3616                            for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++ivar_idx)
3617                            {
3618                                if (ivar_idx == idx)
3619                                {
3620                                    const ObjCIvarDecl* ivar_decl = *ivar_pos;
3621
3622                                    QualType ivar_qual_type(ivar_decl->getType());
3623
3624                                    name.assign(ivar_decl->getNameAsString());
3625
3626                                    if (bit_offset_ptr)
3627                                    {
3628                                        const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
3629                                        *bit_offset_ptr = interface_layout.getFieldOffset (ivar_idx);
3630                                    }
3631
3632                                    const bool is_bitfield = ivar_pos->isBitField();
3633
3634                                    if (bitfield_bit_size_ptr)
3635                                    {
3636                                        *bitfield_bit_size_ptr = 0;
3637
3638                                        if (is_bitfield && ast)
3639                                        {
3640                                            Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
3641                                            llvm::APSInt bitfield_apsint;
3642                                            if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3643                                            {
3644                                                *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3645                                            }
3646                                        }
3647                                    }
3648                                    if (is_bitfield_ptr)
3649                                        *is_bitfield_ptr = is_bitfield;
3650
3651                                    return ivar_qual_type.getAsOpaquePtr();
3652                                }
3653                            }
3654                        }
3655                    }
3656                }
3657            }
3658            break;
3659
3660
3661        case clang::Type::Typedef:
3662            return ClangASTContext::GetFieldAtIndex (ast,
3663                                                     cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3664                                                     idx,
3665                                                     name,
3666                                                     bit_offset_ptr,
3667                                                     bitfield_bit_size_ptr,
3668                                                     is_bitfield_ptr);
3669
3670        case clang::Type::Elaborated:
3671            return  ClangASTContext::GetFieldAtIndex (ast,
3672                                                      cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3673                                                      idx,
3674                                                      name,
3675                                                      bit_offset_ptr,
3676                                                      bitfield_bit_size_ptr,
3677                                                      is_bitfield_ptr);
3678
3679        default:
3680            break;
3681    }
3682    return NULL;
3683}
3684
3685size_t
3686ClangASTContext::GetIndexOfFieldWithName (clang::ASTContext *ast,
3687                                          lldb::clang_type_t clang_type,
3688                                          const char* name,
3689                                          lldb::clang_type_t* field_clang_type,
3690                                          uint64_t *bit_offset_ptr,
3691                                          uint32_t *bitfield_bit_size_ptr,
3692                                          bool *is_bitfield_ptr)
3693{
3694    auto count = ClangASTContext::GetNumFields(ast, clang_type);
3695    lldb::clang_type_t field_clang_type_internal;
3696    std::string field_name;
3697    for (auto index = 0; index < count; index++)
3698    {
3699        field_clang_type_internal = ClangASTContext::GetFieldAtIndex(ast, clang_type, index, field_name, bit_offset_ptr, bitfield_bit_size_ptr, is_bitfield_ptr);
3700        if ( strcmp(field_name.c_str(), name) == 0 )
3701        {
3702            if (field_clang_type)
3703                *field_clang_type = field_clang_type_internal;
3704            return index;
3705        }
3706    }
3707    return UINT32_MAX;
3708}
3709
3710lldb::BasicType
3711ClangASTContext::GetLLDBBasicTypeEnumeration (clang_type_t clang_type)
3712{
3713    if (clang_type)
3714    {
3715        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3716        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3717        if (type_class == clang::Type::Builtin)
3718        {
3719            switch (cast<clang::BuiltinType>(qual_type)->getKind())
3720            {
3721            case clang::BuiltinType::Void:      return eBasicTypeVoid;
3722            case clang::BuiltinType::Bool:      return eBasicTypeBool;
3723            case clang::BuiltinType::Char_S:    return eBasicTypeSignedChar;
3724            case clang::BuiltinType::Char_U:    return eBasicTypeUnsignedChar;
3725            case clang::BuiltinType::Char16:    return eBasicTypeChar16;
3726            case clang::BuiltinType::Char32:    return eBasicTypeChar32;
3727            case clang::BuiltinType::UChar:     return eBasicTypeUnsignedChar;
3728            case clang::BuiltinType::SChar:     return eBasicTypeSignedChar;
3729            case clang::BuiltinType::WChar_S:   return eBasicTypeSignedWChar;
3730            case clang::BuiltinType::WChar_U:   return eBasicTypeUnsignedWChar;
3731            case clang::BuiltinType::Short:     return eBasicTypeShort;
3732            case clang::BuiltinType::UShort:    return eBasicTypeUnsignedShort;
3733            case clang::BuiltinType::Int:       return eBasicTypeInt;
3734            case clang::BuiltinType::UInt:      return eBasicTypeUnsignedInt;
3735            case clang::BuiltinType::Long:      return eBasicTypeLong;
3736            case clang::BuiltinType::ULong:     return eBasicTypeUnsignedLong;
3737            case clang::BuiltinType::LongLong:  return eBasicTypeLongLong;
3738            case clang::BuiltinType::ULongLong: return eBasicTypeUnsignedLongLong;
3739            case clang::BuiltinType::Int128:    return eBasicTypeInt128;
3740            case clang::BuiltinType::UInt128:   return eBasicTypeUnsignedInt128;
3741
3742            case clang::BuiltinType::Half:      return eBasicTypeHalf;
3743            case clang::BuiltinType::Float:     return eBasicTypeFloat;
3744            case clang::BuiltinType::Double:    return eBasicTypeDouble;
3745            case clang::BuiltinType::LongDouble:return eBasicTypeLongDouble;
3746
3747            case clang::BuiltinType::NullPtr:   return eBasicTypeNullPtr;
3748            case clang::BuiltinType::ObjCId:    return eBasicTypeObjCID;
3749            case clang::BuiltinType::ObjCClass: return eBasicTypeObjCClass;
3750            case clang::BuiltinType::ObjCSel:   return eBasicTypeObjCSel;
3751            case clang::BuiltinType::Dependent:
3752            case clang::BuiltinType::Overload:
3753            case clang::BuiltinType::BoundMember:
3754            case clang::BuiltinType::PseudoObject:
3755            case clang::BuiltinType::UnknownAny:
3756            case clang::BuiltinType::BuiltinFn:
3757            case clang::BuiltinType::ARCUnbridgedCast:
3758            case clang::BuiltinType::OCLEvent:
3759            case clang::BuiltinType::OCLImage1d:
3760            case clang::BuiltinType::OCLImage1dArray:
3761            case clang::BuiltinType::OCLImage1dBuffer:
3762            case clang::BuiltinType::OCLImage2d:
3763            case clang::BuiltinType::OCLImage2dArray:
3764            case clang::BuiltinType::OCLImage3d:
3765            case clang::BuiltinType::OCLSampler:
3766                return eBasicTypeOther;
3767            }
3768        }
3769    }
3770
3771    return eBasicTypeInvalid;
3772}
3773
3774
3775
3776// If a pointer to a pointee type (the clang_type arg) says that it has no
3777// children, then we either need to trust it, or override it and return a
3778// different result. For example, an "int *" has one child that is an integer,
3779// but a function pointer doesn't have any children. Likewise if a Record type
3780// claims it has no children, then there really is nothing to show.
3781uint32_t
3782ClangASTContext::GetNumPointeeChildren (clang_type_t clang_type)
3783{
3784    if (clang_type == NULL)
3785        return 0;
3786
3787    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3788    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3789    switch (type_class)
3790    {
3791    case clang::Type::Builtin:
3792        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3793        {
3794        case clang::BuiltinType::UnknownAny:
3795        case clang::BuiltinType::Void:
3796        case clang::BuiltinType::NullPtr:
3797        case clang::BuiltinType::OCLEvent:
3798        case clang::BuiltinType::OCLImage1d:
3799        case clang::BuiltinType::OCLImage1dArray:
3800        case clang::BuiltinType::OCLImage1dBuffer:
3801        case clang::BuiltinType::OCLImage2d:
3802        case clang::BuiltinType::OCLImage2dArray:
3803        case clang::BuiltinType::OCLImage3d:
3804        case clang::BuiltinType::OCLSampler:
3805            return 0;
3806        case clang::BuiltinType::Bool:
3807        case clang::BuiltinType::Char_U:
3808        case clang::BuiltinType::UChar:
3809        case clang::BuiltinType::WChar_U:
3810        case clang::BuiltinType::Char16:
3811        case clang::BuiltinType::Char32:
3812        case clang::BuiltinType::UShort:
3813        case clang::BuiltinType::UInt:
3814        case clang::BuiltinType::ULong:
3815        case clang::BuiltinType::ULongLong:
3816        case clang::BuiltinType::UInt128:
3817        case clang::BuiltinType::Char_S:
3818        case clang::BuiltinType::SChar:
3819        case clang::BuiltinType::WChar_S:
3820        case clang::BuiltinType::Short:
3821        case clang::BuiltinType::Int:
3822        case clang::BuiltinType::Long:
3823        case clang::BuiltinType::LongLong:
3824        case clang::BuiltinType::Int128:
3825        case clang::BuiltinType::Float:
3826        case clang::BuiltinType::Double:
3827        case clang::BuiltinType::LongDouble:
3828        case clang::BuiltinType::Dependent:
3829        case clang::BuiltinType::Overload:
3830        case clang::BuiltinType::ObjCId:
3831        case clang::BuiltinType::ObjCClass:
3832        case clang::BuiltinType::ObjCSel:
3833        case clang::BuiltinType::BoundMember:
3834        case clang::BuiltinType::Half:
3835        case clang::BuiltinType::ARCUnbridgedCast:
3836        case clang::BuiltinType::PseudoObject:
3837        case clang::BuiltinType::BuiltinFn:
3838            return 1;
3839        }
3840        break;
3841
3842    case clang::Type::Complex:                  return 1;
3843    case clang::Type::Pointer:                  return 1;
3844    case clang::Type::BlockPointer:             return 0;   // If block pointers don't have debug info, then no children for them
3845    case clang::Type::LValueReference:          return 1;
3846    case clang::Type::RValueReference:          return 1;
3847    case clang::Type::MemberPointer:            return 0;
3848    case clang::Type::ConstantArray:            return 0;
3849    case clang::Type::IncompleteArray:          return 0;
3850    case clang::Type::VariableArray:            return 0;
3851    case clang::Type::DependentSizedArray:      return 0;
3852    case clang::Type::DependentSizedExtVector:  return 0;
3853    case clang::Type::Vector:                   return 0;
3854    case clang::Type::ExtVector:                return 0;
3855    case clang::Type::FunctionProto:            return 0;   // When we function pointers, they have no children...
3856    case clang::Type::FunctionNoProto:          return 0;   // When we function pointers, they have no children...
3857    case clang::Type::UnresolvedUsing:          return 0;
3858    case clang::Type::Paren:                    return 0;
3859    case clang::Type::Typedef:                  return ClangASTContext::GetNumPointeeChildren (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3860    case clang::Type::Elaborated:               return ClangASTContext::GetNumPointeeChildren (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3861    case clang::Type::TypeOfExpr:               return 0;
3862    case clang::Type::TypeOf:                   return 0;
3863    case clang::Type::Decltype:                 return 0;
3864    case clang::Type::Record:                   return 0;
3865    case clang::Type::Enum:                     return 1;
3866    case clang::Type::TemplateTypeParm:         return 1;
3867    case clang::Type::SubstTemplateTypeParm:    return 1;
3868    case clang::Type::TemplateSpecialization:   return 1;
3869    case clang::Type::InjectedClassName:        return 0;
3870    case clang::Type::DependentName:            return 1;
3871    case clang::Type::DependentTemplateSpecialization:  return 1;
3872    case clang::Type::ObjCObject:               return 0;
3873    case clang::Type::ObjCInterface:            return 0;
3874    case clang::Type::ObjCObjectPointer:        return 1;
3875    default:
3876        break;
3877    }
3878    return 0;
3879}
3880
3881clang_type_t
3882ClangASTContext::GetChildClangTypeAtIndex
3883(
3884    ExecutionContext *exe_ctx,
3885    const char *parent_name,
3886    clang_type_t parent_clang_type,
3887    size_t idx,
3888    bool transparent_pointers,
3889    bool omit_empty_base_classes,
3890    bool ignore_array_bounds,
3891    std::string& child_name,
3892    uint32_t &child_byte_size,
3893    int32_t &child_byte_offset,
3894    uint32_t &child_bitfield_bit_size,
3895    uint32_t &child_bitfield_bit_offset,
3896    bool &child_is_base_class,
3897    bool &child_is_deref_of_parent
3898)
3899{
3900    if (parent_clang_type)
3901
3902        return GetChildClangTypeAtIndex (exe_ctx,
3903                                         getASTContext(),
3904                                         parent_name,
3905                                         parent_clang_type,
3906                                         idx,
3907                                         transparent_pointers,
3908                                         omit_empty_base_classes,
3909                                         ignore_array_bounds,
3910                                         child_name,
3911                                         child_byte_size,
3912                                         child_byte_offset,
3913                                         child_bitfield_bit_size,
3914                                         child_bitfield_bit_offset,
3915                                         child_is_base_class,
3916                                         child_is_deref_of_parent);
3917    return NULL;
3918}
3919
3920clang_type_t
3921ClangASTContext::GetChildClangTypeAtIndex
3922(
3923    ExecutionContext *exe_ctx,
3924    ASTContext *ast,
3925    const char *parent_name,
3926    clang_type_t parent_clang_type,
3927    size_t idx,
3928    bool transparent_pointers,
3929    bool omit_empty_base_classes,
3930    bool ignore_array_bounds,
3931    std::string& child_name,
3932    uint32_t &child_byte_size,
3933    int32_t &child_byte_offset,
3934    uint32_t &child_bitfield_bit_size,
3935    uint32_t &child_bitfield_bit_offset,
3936    bool &child_is_base_class,
3937    bool &child_is_deref_of_parent
3938)
3939{
3940    if (parent_clang_type == NULL)
3941        return NULL;
3942
3943    QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
3944    const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass();
3945    child_bitfield_bit_size = 0;
3946    child_bitfield_bit_offset = 0;
3947    child_is_base_class = false;
3948
3949    const bool idx_is_valid = idx < ClangASTContext::GetNumChildren (ast, parent_clang_type, omit_empty_base_classes);
3950    uint32_t bit_offset;
3951    switch (parent_type_class)
3952    {
3953    case clang::Type::Builtin:
3954        if (idx_is_valid)
3955        {
3956            switch (cast<clang::BuiltinType>(parent_qual_type)->getKind())
3957            {
3958            case clang::BuiltinType::ObjCId:
3959            case clang::BuiltinType::ObjCClass:
3960                child_name = "isa";
3961                child_byte_size = ast->getTypeSize(ast->ObjCBuiltinClassTy) / CHAR_BIT;
3962                return ast->ObjCBuiltinClassTy.getAsOpaquePtr();
3963
3964            default:
3965                break;
3966            }
3967        }
3968        break;
3969
3970    case clang::Type::Record:
3971        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
3972        {
3973            const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
3974            const RecordDecl *record_decl = record_type->getDecl();
3975            assert(record_decl);
3976            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3977            uint32_t child_idx = 0;
3978
3979            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3980            if (cxx_record_decl)
3981            {
3982                // We might have base classes to print out first
3983                CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3984                for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3985                     base_class != base_class_end;
3986                     ++base_class)
3987                {
3988                    const CXXRecordDecl *base_class_decl = NULL;
3989
3990                    // Skip empty base classes
3991                    if (omit_empty_base_classes)
3992                    {
3993                        base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3994                        if (RecordHasFields(base_class_decl) == false)
3995                            continue;
3996                    }
3997
3998                    if (idx == child_idx)
3999                    {
4000                        if (base_class_decl == NULL)
4001                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4002
4003
4004                        if (base_class->isVirtual())
4005                            bit_offset = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
4006                        else
4007                            bit_offset = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
4008
4009                        // Base classes should be a multiple of 8 bits in size
4010                        child_byte_offset = bit_offset/8;
4011
4012                        child_name = ClangASTType::GetTypeNameForQualType(ast, base_class->getType());
4013
4014                        uint64_t clang_type_info_bit_size = ast->getTypeSize(base_class->getType());
4015
4016                        // Base classes bit sizes should be a multiple of 8 bits in size
4017                        assert (clang_type_info_bit_size % 8 == 0);
4018                        child_byte_size = clang_type_info_bit_size / 8;
4019                        child_is_base_class = true;
4020                        return base_class->getType().getAsOpaquePtr();
4021                    }
4022                    // We don't increment the child index in the for loop since we might
4023                    // be skipping empty base classes
4024                    ++child_idx;
4025                }
4026            }
4027            // Make sure index is in range...
4028            uint32_t field_idx = 0;
4029            RecordDecl::field_iterator field, field_end;
4030            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
4031            {
4032                if (idx == child_idx)
4033                {
4034                    // Print the member type if requested
4035                    // Print the member name and equal sign
4036                    child_name.assign(field->getNameAsString().c_str());
4037
4038                    // Figure out the type byte size (field_type_info.first) and
4039                    // alignment (field_type_info.second) from the AST context.
4040                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(field->getType());
4041                    assert(field_idx < record_layout.getFieldCount());
4042
4043                    child_byte_size = field_type_info.first / 8;
4044
4045                    // Figure out the field offset within the current struct/union/class type
4046                    bit_offset = record_layout.getFieldOffset (field_idx);
4047                    child_byte_offset = bit_offset / 8;
4048                    if (ClangASTContext::FieldIsBitfield (ast, *field, child_bitfield_bit_size))
4049                        child_bitfield_bit_offset = bit_offset % 8;
4050
4051                    return field->getType().getAsOpaquePtr();
4052                }
4053            }
4054        }
4055        break;
4056
4057    case clang::Type::ObjCObject:
4058    case clang::Type::ObjCInterface:
4059        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
4060        {
4061            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(parent_qual_type.getTypePtr());
4062            assert (objc_class_type);
4063            if (objc_class_type)
4064            {
4065                uint32_t child_idx = 0;
4066                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4067
4068                if (class_interface_decl)
4069                {
4070
4071                    const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
4072                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4073                    if (superclass_interface_decl)
4074                    {
4075                        if (omit_empty_base_classes)
4076                        {
4077                            if (ClangASTContext::GetNumChildren(ast, ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(), omit_empty_base_classes) > 0)
4078                            {
4079                                if (idx == 0)
4080                                {
4081                                    QualType ivar_qual_type(ast->getObjCInterfaceType(superclass_interface_decl));
4082
4083
4084                                    child_name.assign(superclass_interface_decl->getNameAsString().c_str());
4085
4086                                    std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4087
4088                                    child_byte_size = ivar_type_info.first / 8;
4089                                    child_byte_offset = 0;
4090                                    child_is_base_class = true;
4091
4092                                    return ivar_qual_type.getAsOpaquePtr();
4093                                }
4094
4095                                ++child_idx;
4096                            }
4097                        }
4098                        else
4099                            ++child_idx;
4100                    }
4101
4102                    const uint32_t superclass_idx = child_idx;
4103
4104                    if (idx < (child_idx + class_interface_decl->ivar_size()))
4105                    {
4106                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4107
4108                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
4109                        {
4110                            if (child_idx == idx)
4111                            {
4112                                ObjCIvarDecl* ivar_decl = *ivar_pos;
4113
4114                                QualType ivar_qual_type(ivar_decl->getType());
4115
4116                                child_name.assign(ivar_decl->getNameAsString().c_str());
4117
4118                                std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4119
4120                                child_byte_size = ivar_type_info.first / 8;
4121
4122                                // Figure out the field offset within the current struct/union/class type
4123                                // For ObjC objects, we can't trust the bit offset we get from the Clang AST, since
4124                                // that doesn't account for the space taken up by unbacked properties, or from
4125                                // the changing size of base classes that are newer than this class.
4126                                // So if we have a process around that we can ask about this object, do so.
4127                                child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
4128                                Process *process = NULL;
4129                                if (exe_ctx)
4130                                    process = exe_ctx->GetProcessPtr();
4131                                if (process)
4132                                {
4133                                    ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime();
4134                                    if (objc_runtime != NULL)
4135                                    {
4136                                        ClangASTType parent_ast_type (ast, parent_qual_type.getAsOpaquePtr());
4137                                        child_byte_offset = objc_runtime->GetByteOffsetForIvar (parent_ast_type, ivar_decl->getNameAsString().c_str());
4138                                    }
4139                                }
4140
4141                                // Setting this to UINT32_MAX to make sure we don't compute it twice...
4142                                bit_offset = UINT32_MAX;
4143
4144                                if (child_byte_offset == LLDB_INVALID_IVAR_OFFSET)
4145                                {
4146                                    bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4147                                    child_byte_offset = bit_offset / 8;
4148                                }
4149
4150                                // Note, the ObjC Ivar Byte offset is just that, it doesn't account for the bit offset
4151                                // of a bitfield within its containing object.  So regardless of where we get the byte
4152                                // offset from, we still need to get the bit offset for bitfields from the layout.
4153
4154                                if (ClangASTContext::FieldIsBitfield (ast, ivar_decl, child_bitfield_bit_size))
4155                                {
4156                                    if (bit_offset == UINT32_MAX)
4157                                        bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4158
4159                                    child_bitfield_bit_offset = bit_offset % 8;
4160                                }
4161                                return ivar_qual_type.getAsOpaquePtr();
4162                            }
4163                            ++child_idx;
4164                        }
4165                    }
4166                }
4167            }
4168        }
4169        break;
4170
4171    case clang::Type::ObjCObjectPointer:
4172        if (idx_is_valid)
4173        {
4174            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(parent_qual_type.getTypePtr());
4175            QualType pointee_type = pointer_type->getPointeeType();
4176
4177            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4178            {
4179                child_is_deref_of_parent = false;
4180                bool tmp_child_is_deref_of_parent = false;
4181                return GetChildClangTypeAtIndex (exe_ctx,
4182                                                 ast,
4183                                                 parent_name,
4184                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4185                                                 idx,
4186                                                 transparent_pointers,
4187                                                 omit_empty_base_classes,
4188                                                 ignore_array_bounds,
4189                                                 child_name,
4190                                                 child_byte_size,
4191                                                 child_byte_offset,
4192                                                 child_bitfield_bit_size,
4193                                                 child_bitfield_bit_offset,
4194                                                 child_is_base_class,
4195                                                 tmp_child_is_deref_of_parent);
4196            }
4197            else
4198            {
4199                child_is_deref_of_parent = true;
4200                if (parent_name)
4201                {
4202                    child_name.assign(1, '*');
4203                    child_name += parent_name;
4204                }
4205
4206                // We have a pointer to an simple type
4207                if (idx == 0 && GetCompleteQualType(ast, pointee_type))
4208                {
4209                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4210                    assert(clang_type_info.first % 8 == 0);
4211                    child_byte_size = clang_type_info.first / 8;
4212                    child_byte_offset = 0;
4213                    return pointee_type.getAsOpaquePtr();
4214                }
4215            }
4216        }
4217        break;
4218
4219        case clang::Type::ConstantArray:
4220        case clang::Type::IncompleteArray:
4221            if (ignore_array_bounds || idx_is_valid)
4222            {
4223                const ArrayType *array = cast<ArrayType>(parent_qual_type.getTypePtr());
4224                if (array)
4225                {
4226                    if (GetCompleteQualType (ast, array->getElementType()))
4227                    {
4228                        std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4229
4230                        char element_name[64];
4231                        ::snprintf (element_name, sizeof (element_name), "[%zu]", idx);
4232
4233                        child_name.assign(element_name);
4234                        assert(field_type_info.first % 8 == 0);
4235                        child_byte_size = field_type_info.first / 8;
4236                        child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
4237                        return array->getElementType().getAsOpaquePtr();
4238                    }
4239                }
4240            }
4241            break;
4242
4243
4244    case clang::Type::Pointer:
4245        if (idx_is_valid)
4246        {
4247            const PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
4248            QualType pointee_type = pointer_type->getPointeeType();
4249
4250            // Don't dereference "void *" pointers
4251            if (pointee_type->isVoidType())
4252                return NULL;
4253
4254            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4255            {
4256                child_is_deref_of_parent = false;
4257                bool tmp_child_is_deref_of_parent = false;
4258                return GetChildClangTypeAtIndex (exe_ctx,
4259                                                 ast,
4260                                                 parent_name,
4261                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4262                                                 idx,
4263                                                 transparent_pointers,
4264                                                 omit_empty_base_classes,
4265                                                 ignore_array_bounds,
4266                                                 child_name,
4267                                                 child_byte_size,
4268                                                 child_byte_offset,
4269                                                 child_bitfield_bit_size,
4270                                                 child_bitfield_bit_offset,
4271                                                 child_is_base_class,
4272                                                 tmp_child_is_deref_of_parent);
4273            }
4274            else
4275            {
4276                child_is_deref_of_parent = true;
4277
4278                if (parent_name)
4279                {
4280                    child_name.assign(1, '*');
4281                    child_name += parent_name;
4282                }
4283
4284                // We have a pointer to an simple type
4285                if (idx == 0)
4286                {
4287                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4288                    assert(clang_type_info.first % 8 == 0);
4289                    child_byte_size = clang_type_info.first / 8;
4290                    child_byte_offset = 0;
4291                    return pointee_type.getAsOpaquePtr();
4292                }
4293            }
4294        }
4295        break;
4296
4297    case clang::Type::LValueReference:
4298    case clang::Type::RValueReference:
4299        if (idx_is_valid)
4300        {
4301            const ReferenceType *reference_type = cast<ReferenceType>(parent_qual_type.getTypePtr());
4302            QualType pointee_type(reference_type->getPointeeType());
4303            clang_type_t pointee_clang_type = pointee_type.getAsOpaquePtr();
4304            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_clang_type))
4305            {
4306                child_is_deref_of_parent = false;
4307                bool tmp_child_is_deref_of_parent = false;
4308                return GetChildClangTypeAtIndex (exe_ctx,
4309                                                 ast,
4310                                                 parent_name,
4311                                                 pointee_clang_type,
4312                                                 idx,
4313                                                 transparent_pointers,
4314                                                 omit_empty_base_classes,
4315                                                 ignore_array_bounds,
4316                                                 child_name,
4317                                                 child_byte_size,
4318                                                 child_byte_offset,
4319                                                 child_bitfield_bit_size,
4320                                                 child_bitfield_bit_offset,
4321                                                 child_is_base_class,
4322                                                 tmp_child_is_deref_of_parent);
4323            }
4324            else
4325            {
4326                if (parent_name)
4327                {
4328                    child_name.assign(1, '&');
4329                    child_name += parent_name;
4330                }
4331
4332                // We have a pointer to an simple type
4333                if (idx == 0)
4334                {
4335                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4336                    assert(clang_type_info.first % 8 == 0);
4337                    child_byte_size = clang_type_info.first / 8;
4338                    child_byte_offset = 0;
4339                    return pointee_type.getAsOpaquePtr();
4340                }
4341            }
4342        }
4343        break;
4344
4345    case clang::Type::Typedef:
4346        return GetChildClangTypeAtIndex (exe_ctx,
4347                                         ast,
4348                                         parent_name,
4349                                         cast<TypedefType>(parent_qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4350                                         idx,
4351                                         transparent_pointers,
4352                                         omit_empty_base_classes,
4353                                         ignore_array_bounds,
4354                                         child_name,
4355                                         child_byte_size,
4356                                         child_byte_offset,
4357                                         child_bitfield_bit_size,
4358                                         child_bitfield_bit_offset,
4359                                         child_is_base_class,
4360                                         child_is_deref_of_parent);
4361        break;
4362
4363    case clang::Type::Elaborated:
4364        return GetChildClangTypeAtIndex (exe_ctx,
4365                                         ast,
4366                                         parent_name,
4367                                         cast<ElaboratedType>(parent_qual_type)->getNamedType().getAsOpaquePtr(),
4368                                         idx,
4369                                         transparent_pointers,
4370                                         omit_empty_base_classes,
4371                                         ignore_array_bounds,
4372                                         child_name,
4373                                         child_byte_size,
4374                                         child_byte_offset,
4375                                         child_bitfield_bit_size,
4376                                         child_bitfield_bit_offset,
4377                                         child_is_base_class,
4378                                         child_is_deref_of_parent);
4379
4380    default:
4381        break;
4382    }
4383    return NULL;
4384}
4385
4386static inline bool
4387BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
4388{
4389    return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
4390}
4391
4392static uint32_t
4393GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
4394{
4395    uint32_t num_bases = 0;
4396    if (cxx_record_decl)
4397    {
4398        if (omit_empty_base_classes)
4399        {
4400            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4401            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4402                 base_class != base_class_end;
4403                 ++base_class)
4404            {
4405                // Skip empty base classes
4406                if (omit_empty_base_classes)
4407                {
4408                    if (BaseSpecifierIsEmpty (base_class))
4409                        continue;
4410                }
4411                ++num_bases;
4412            }
4413        }
4414        else
4415            num_bases = cxx_record_decl->getNumBases();
4416    }
4417    return num_bases;
4418}
4419
4420
4421static uint32_t
4422GetIndexForRecordBase
4423(
4424    const RecordDecl *record_decl,
4425    const CXXBaseSpecifier *base_spec,
4426    bool omit_empty_base_classes
4427)
4428{
4429    uint32_t child_idx = 0;
4430
4431    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4432
4433//    const char *super_name = record_decl->getNameAsCString();
4434//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
4435//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
4436//
4437    if (cxx_record_decl)
4438    {
4439        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4440        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4441             base_class != base_class_end;
4442             ++base_class)
4443        {
4444            if (omit_empty_base_classes)
4445            {
4446                if (BaseSpecifierIsEmpty (base_class))
4447                    continue;
4448            }
4449
4450//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
4451//                    child_idx,
4452//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4453//
4454//
4455            if (base_class == base_spec)
4456                return child_idx;
4457            ++child_idx;
4458        }
4459    }
4460
4461    return UINT32_MAX;
4462}
4463
4464
4465static uint32_t
4466GetIndexForRecordChild
4467(
4468    const RecordDecl *record_decl,
4469    NamedDecl *canonical_decl,
4470    bool omit_empty_base_classes
4471)
4472{
4473    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
4474
4475//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4476//
4477////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
4478//    if (cxx_record_decl)
4479//    {
4480//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4481//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4482//             base_class != base_class_end;
4483//             ++base_class)
4484//        {
4485//            if (omit_empty_base_classes)
4486//            {
4487//                if (BaseSpecifierIsEmpty (base_class))
4488//                    continue;
4489//            }
4490//
4491////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
4492////                    record_decl->getNameAsCString(),
4493////                    canonical_decl->getNameAsCString(),
4494////                    child_idx,
4495////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4496//
4497//
4498//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4499//            if (curr_base_class_decl == canonical_decl)
4500//            {
4501//                return child_idx;
4502//            }
4503//            ++child_idx;
4504//        }
4505//    }
4506//
4507//    const uint32_t num_bases = child_idx;
4508    RecordDecl::field_iterator field, field_end;
4509    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4510         field != field_end;
4511         ++field, ++child_idx)
4512    {
4513//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
4514//                    record_decl->getNameAsCString(),
4515//                    canonical_decl->getNameAsCString(),
4516//                    child_idx - num_bases,
4517//                    field->getNameAsCString());
4518
4519        if (field->getCanonicalDecl() == canonical_decl)
4520            return child_idx;
4521    }
4522
4523    return UINT32_MAX;
4524}
4525
4526// Look for a child member (doesn't include base classes, but it does include
4527// their members) in the type hierarchy. Returns an index path into "clang_type"
4528// on how to reach the appropriate member.
4529//
4530//    class A
4531//    {
4532//    public:
4533//        int m_a;
4534//        int m_b;
4535//    };
4536//
4537//    class B
4538//    {
4539//    };
4540//
4541//    class C :
4542//        public B,
4543//        public A
4544//    {
4545//    };
4546//
4547// If we have a clang type that describes "class C", and we wanted to looked
4548// "m_b" in it:
4549//
4550// With omit_empty_base_classes == false we would get an integer array back with:
4551// { 1,  1 }
4552// The first index 1 is the child index for "class A" within class C
4553// The second index 1 is the child index for "m_b" within class A
4554//
4555// With omit_empty_base_classes == true we would get an integer array back with:
4556// { 0,  1 }
4557// 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)
4558// The second index 1 is the child index for "m_b" within class A
4559
4560size_t
4561ClangASTContext::GetIndexOfChildMemberWithName
4562(
4563    ASTContext *ast,
4564    clang_type_t clang_type,
4565    const char *name,
4566    bool omit_empty_base_classes,
4567    std::vector<uint32_t>& child_indexes
4568)
4569{
4570    if (clang_type && name && name[0])
4571    {
4572        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4573        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4574        switch (type_class)
4575        {
4576        case clang::Type::Record:
4577            if (GetCompleteQualType (ast, qual_type))
4578            {
4579                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4580                const RecordDecl *record_decl = record_type->getDecl();
4581
4582                assert(record_decl);
4583                uint32_t child_idx = 0;
4584
4585                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4586
4587                // Try and find a field that matches NAME
4588                RecordDecl::field_iterator field, field_end;
4589                StringRef name_sref(name);
4590                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4591                     field != field_end;
4592                     ++field, ++child_idx)
4593                {
4594                    if (field->getName().equals (name_sref))
4595                    {
4596                        // We have to add on the number of base classes to this index!
4597                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
4598                        return child_indexes.size();
4599                    }
4600                }
4601
4602                if (cxx_record_decl)
4603                {
4604                    const RecordDecl *parent_record_decl = cxx_record_decl;
4605
4606                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
4607
4608                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
4609                    // Didn't find things easily, lets let clang do its thang...
4610                    IdentifierInfo & ident_ref = ast->Idents.get(name_sref);
4611                    DeclarationName decl_name(&ident_ref);
4612
4613                    CXXBasePaths paths;
4614                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
4615                                                       decl_name.getAsOpaquePtr(),
4616                                                       paths))
4617                    {
4618                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
4619                        for (path = paths.begin(); path != path_end; ++path)
4620                        {
4621                            const size_t num_path_elements = path->size();
4622                            for (size_t e=0; e<num_path_elements; ++e)
4623                            {
4624                                CXXBasePathElement elem = (*path)[e];
4625
4626                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
4627                                if (child_idx == UINT32_MAX)
4628                                {
4629                                    child_indexes.clear();
4630                                    return 0;
4631                                }
4632                                else
4633                                {
4634                                    child_indexes.push_back (child_idx);
4635                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
4636                                }
4637                            }
4638                            for (NamedDecl *path_decl : path->Decls)
4639                            {
4640                                child_idx = GetIndexForRecordChild (parent_record_decl, path_decl, omit_empty_base_classes);
4641                                if (child_idx == UINT32_MAX)
4642                                {
4643                                    child_indexes.clear();
4644                                    return 0;
4645                                }
4646                                else
4647                                {
4648                                    child_indexes.push_back (child_idx);
4649                                }
4650                            }
4651                        }
4652                        return child_indexes.size();
4653                    }
4654                }
4655
4656            }
4657            break;
4658
4659        case clang::Type::ObjCObject:
4660        case clang::Type::ObjCInterface:
4661            if (GetCompleteQualType (ast, qual_type))
4662            {
4663                StringRef name_sref(name);
4664                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4665                assert (objc_class_type);
4666                if (objc_class_type)
4667                {
4668                    uint32_t child_idx = 0;
4669                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4670
4671                    if (class_interface_decl)
4672                    {
4673                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4674                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4675
4676                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4677                        {
4678                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4679
4680                            if (ivar_decl->getName().equals (name_sref))
4681                            {
4682                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4683                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4684                                    ++child_idx;
4685
4686                                child_indexes.push_back (child_idx);
4687                                return child_indexes.size();
4688                            }
4689                        }
4690
4691                        if (superclass_interface_decl)
4692                        {
4693                            // The super class index is always zero for ObjC classes,
4694                            // so we push it onto the child indexes in case we find
4695                            // an ivar in our superclass...
4696                            child_indexes.push_back (0);
4697
4698                            if (GetIndexOfChildMemberWithName (ast,
4699                                                               ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(),
4700                                                               name,
4701                                                               omit_empty_base_classes,
4702                                                               child_indexes))
4703                            {
4704                                // We did find an ivar in a superclass so just
4705                                // return the results!
4706                                return child_indexes.size();
4707                            }
4708
4709                            // We didn't find an ivar matching "name" in our
4710                            // superclass, pop the superclass zero index that
4711                            // we pushed on above.
4712                            child_indexes.pop_back();
4713                        }
4714                    }
4715                }
4716            }
4717            break;
4718
4719        case clang::Type::ObjCObjectPointer:
4720            {
4721                return GetIndexOfChildMemberWithName (ast,
4722                                                      cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4723                                                      name,
4724                                                      omit_empty_base_classes,
4725                                                      child_indexes);
4726            }
4727            break;
4728
4729
4730        case clang::Type::ConstantArray:
4731            {
4732//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4733//                const uint64_t element_count = array->getSize().getLimitedValue();
4734//
4735//                if (idx < element_count)
4736//                {
4737//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4738//
4739//                    char element_name[32];
4740//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4741//
4742//                    child_name.assign(element_name);
4743//                    assert(field_type_info.first % 8 == 0);
4744//                    child_byte_size = field_type_info.first / 8;
4745//                    child_byte_offset = idx * child_byte_size;
4746//                    return array->getElementType().getAsOpaquePtr();
4747//                }
4748            }
4749            break;
4750
4751//        case clang::Type::MemberPointerType:
4752//            {
4753//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4754//                QualType pointee_type = mem_ptr_type->getPointeeType();
4755//
4756//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4757//                {
4758//                    return GetIndexOfChildWithName (ast,
4759//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4760//                                                    name);
4761//                }
4762//            }
4763//            break;
4764//
4765        case clang::Type::LValueReference:
4766        case clang::Type::RValueReference:
4767            {
4768                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4769                QualType pointee_type = reference_type->getPointeeType();
4770
4771                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4772                {
4773                    return GetIndexOfChildMemberWithName (ast,
4774                                                          reference_type->getPointeeType().getAsOpaquePtr(),
4775                                                          name,
4776                                                          omit_empty_base_classes,
4777                                                          child_indexes);
4778                }
4779            }
4780            break;
4781
4782        case clang::Type::Pointer:
4783            {
4784                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4785                QualType pointee_type = pointer_type->getPointeeType();
4786
4787                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4788                {
4789                    return GetIndexOfChildMemberWithName (ast,
4790                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
4791                                                          name,
4792                                                          omit_empty_base_classes,
4793                                                          child_indexes);
4794                }
4795                else
4796                {
4797//                    if (parent_name)
4798//                    {
4799//                        child_name.assign(1, '*');
4800//                        child_name += parent_name;
4801//                    }
4802//
4803//                    // We have a pointer to an simple type
4804//                    if (idx == 0)
4805//                    {
4806//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4807//                        assert(clang_type_info.first % 8 == 0);
4808//                        child_byte_size = clang_type_info.first / 8;
4809//                        child_byte_offset = 0;
4810//                        return pointee_type.getAsOpaquePtr();
4811//                    }
4812                }
4813            }
4814            break;
4815
4816        case clang::Type::Typedef:
4817            return GetIndexOfChildMemberWithName (ast,
4818                                                  cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4819                                                  name,
4820                                                  omit_empty_base_classes,
4821                                                  child_indexes);
4822
4823        case clang::Type::Elaborated:
4824            return GetIndexOfChildMemberWithName (ast,
4825                                                  cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
4826                                                  name,
4827                                                  omit_empty_base_classes,
4828                                                  child_indexes);
4829
4830        default:
4831            break;
4832        }
4833    }
4834    return 0;
4835}
4836
4837
4838// Get the index of the child of "clang_type" whose name matches. This function
4839// doesn't descend into the children, but only looks one level deep and name
4840// matches can include base class names.
4841
4842uint32_t
4843ClangASTContext::GetIndexOfChildWithName
4844(
4845    ASTContext *ast,
4846    clang_type_t clang_type,
4847    const char *name,
4848    bool omit_empty_base_classes
4849)
4850{
4851    if (clang_type && name && name[0])
4852    {
4853        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4854
4855        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4856
4857        switch (type_class)
4858        {
4859        case clang::Type::Record:
4860            if (GetCompleteQualType (ast, qual_type))
4861            {
4862                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4863                const RecordDecl *record_decl = record_type->getDecl();
4864
4865                assert(record_decl);
4866                uint32_t child_idx = 0;
4867
4868                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4869
4870                if (cxx_record_decl)
4871                {
4872                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4873                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4874                         base_class != base_class_end;
4875                         ++base_class)
4876                    {
4877                        // Skip empty base classes
4878                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4879                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
4880                            continue;
4881
4882                        std::string base_class_type_name (ClangASTType::GetTypeNameForQualType(ast, base_class->getType()));
4883                        if (base_class_type_name.compare (name) == 0)
4884                            return child_idx;
4885                        ++child_idx;
4886                    }
4887                }
4888
4889                // Try and find a field that matches NAME
4890                RecordDecl::field_iterator field, field_end;
4891                StringRef name_sref(name);
4892                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4893                     field != field_end;
4894                     ++field, ++child_idx)
4895                {
4896                    if (field->getName().equals (name_sref))
4897                        return child_idx;
4898                }
4899
4900            }
4901            break;
4902
4903        case clang::Type::ObjCObject:
4904        case clang::Type::ObjCInterface:
4905            if (GetCompleteQualType (ast, qual_type))
4906            {
4907                StringRef name_sref(name);
4908                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4909                assert (objc_class_type);
4910                if (objc_class_type)
4911                {
4912                    uint32_t child_idx = 0;
4913                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4914
4915                    if (class_interface_decl)
4916                    {
4917                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4918                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4919
4920                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4921                        {
4922                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4923
4924                            if (ivar_decl->getName().equals (name_sref))
4925                            {
4926                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4927                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4928                                    ++child_idx;
4929
4930                                return child_idx;
4931                            }
4932                        }
4933
4934                        if (superclass_interface_decl)
4935                        {
4936                            if (superclass_interface_decl->getName().equals (name_sref))
4937                                return 0;
4938                        }
4939                    }
4940                }
4941            }
4942            break;
4943
4944        case clang::Type::ObjCObjectPointer:
4945            {
4946                return GetIndexOfChildWithName (ast,
4947                                                cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4948                                                name,
4949                                                omit_empty_base_classes);
4950            }
4951            break;
4952
4953        case clang::Type::ConstantArray:
4954            {
4955//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4956//                const uint64_t element_count = array->getSize().getLimitedValue();
4957//
4958//                if (idx < element_count)
4959//                {
4960//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4961//
4962//                    char element_name[32];
4963//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4964//
4965//                    child_name.assign(element_name);
4966//                    assert(field_type_info.first % 8 == 0);
4967//                    child_byte_size = field_type_info.first / 8;
4968//                    child_byte_offset = idx * child_byte_size;
4969//                    return array->getElementType().getAsOpaquePtr();
4970//                }
4971            }
4972            break;
4973
4974//        case clang::Type::MemberPointerType:
4975//            {
4976//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4977//                QualType pointee_type = mem_ptr_type->getPointeeType();
4978//
4979//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4980//                {
4981//                    return GetIndexOfChildWithName (ast,
4982//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4983//                                                    name);
4984//                }
4985//            }
4986//            break;
4987//
4988        case clang::Type::LValueReference:
4989        case clang::Type::RValueReference:
4990            {
4991                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4992                QualType pointee_type = reference_type->getPointeeType();
4993
4994                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4995                {
4996                    return GetIndexOfChildWithName (ast,
4997                                                    reference_type->getPointeeType().getAsOpaquePtr(),
4998                                                    name,
4999                                                    omit_empty_base_classes);
5000                }
5001            }
5002            break;
5003
5004        case clang::Type::Pointer:
5005            {
5006                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
5007                QualType pointee_type = pointer_type->getPointeeType();
5008
5009                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
5010                {
5011                    return GetIndexOfChildWithName (ast,
5012                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
5013                                                    name,
5014                                                    omit_empty_base_classes);
5015                }
5016                else
5017                {
5018//                    if (parent_name)
5019//                    {
5020//                        child_name.assign(1, '*');
5021//                        child_name += parent_name;
5022//                    }
5023//
5024//                    // We have a pointer to an simple type
5025//                    if (idx == 0)
5026//                    {
5027//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
5028//                        assert(clang_type_info.first % 8 == 0);
5029//                        child_byte_size = clang_type_info.first / 8;
5030//                        child_byte_offset = 0;
5031//                        return pointee_type.getAsOpaquePtr();
5032//                    }
5033                }
5034            }
5035            break;
5036
5037        case clang::Type::Elaborated:
5038            return GetIndexOfChildWithName (ast,
5039                                            cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5040                                            name,
5041                                            omit_empty_base_classes);
5042
5043        case clang::Type::Typedef:
5044            return GetIndexOfChildWithName (ast,
5045                                            cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5046                                            name,
5047                                            omit_empty_base_classes);
5048
5049        default:
5050            break;
5051        }
5052    }
5053    return UINT32_MAX;
5054}
5055
5056#pragma mark TagType
5057
5058bool
5059ClangASTContext::SetTagTypeKind (clang_type_t tag_clang_type, int kind)
5060{
5061    if (tag_clang_type)
5062    {
5063        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
5064        const clang::Type *clang_type = tag_qual_type.getTypePtr();
5065        if (clang_type)
5066        {
5067            const TagType *tag_type = dyn_cast<TagType>(clang_type);
5068            if (tag_type)
5069            {
5070                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
5071                if (tag_decl)
5072                {
5073                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
5074                    return true;
5075                }
5076            }
5077        }
5078    }
5079    return false;
5080}
5081
5082
5083#pragma mark DeclContext Functions
5084
5085DeclContext *
5086ClangASTContext::GetDeclContextForType (clang_type_t clang_type)
5087{
5088    if (clang_type == NULL)
5089        return NULL;
5090
5091    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
5092    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5093    switch (type_class)
5094    {
5095    case clang::Type::UnaryTransform:           break;
5096    case clang::Type::FunctionNoProto:          break;
5097    case clang::Type::FunctionProto:            break;
5098    case clang::Type::IncompleteArray:          break;
5099    case clang::Type::VariableArray:            break;
5100    case clang::Type::ConstantArray:            break;
5101    case clang::Type::DependentSizedArray:      break;
5102    case clang::Type::ExtVector:                break;
5103    case clang::Type::DependentSizedExtVector:  break;
5104    case clang::Type::Vector:                   break;
5105    case clang::Type::Builtin:                  break;
5106    case clang::Type::BlockPointer:             break;
5107    case clang::Type::Pointer:                  break;
5108    case clang::Type::LValueReference:          break;
5109    case clang::Type::RValueReference:          break;
5110    case clang::Type::MemberPointer:            break;
5111    case clang::Type::Complex:                  break;
5112    case clang::Type::ObjCObject:               break;
5113    case clang::Type::ObjCInterface:            return cast<ObjCObjectType>(qual_type.getTypePtr())->getInterface();
5114    case clang::Type::ObjCObjectPointer:        return ClangASTContext::GetDeclContextForType (cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr());
5115    case clang::Type::Record:                   return cast<RecordType>(qual_type)->getDecl();
5116    case clang::Type::Enum:                     return cast<EnumType>(qual_type)->getDecl();
5117    case clang::Type::Typedef:                  return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5118    case clang::Type::Elaborated:               return ClangASTContext::GetDeclContextForType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5119    case clang::Type::TypeOfExpr:               break;
5120    case clang::Type::TypeOf:                   break;
5121    case clang::Type::Decltype:                 break;
5122    //case clang::Type::QualifiedName:          break;
5123    case clang::Type::TemplateSpecialization:   break;
5124    case clang::Type::DependentTemplateSpecialization:  break;
5125    case clang::Type::TemplateTypeParm:         break;
5126    case clang::Type::SubstTemplateTypeParm:    break;
5127    case clang::Type::SubstTemplateTypeParmPack:break;
5128    case clang::Type::PackExpansion:            break;
5129    case clang::Type::UnresolvedUsing:          break;
5130    case clang::Type::Paren:                    break;
5131    case clang::Type::Attributed:               break;
5132    case clang::Type::Auto:                     break;
5133    case clang::Type::InjectedClassName:        break;
5134    case clang::Type::DependentName:            break;
5135    case clang::Type::Atomic:                   break;
5136    }
5137    // No DeclContext in this type...
5138    return NULL;
5139}
5140
5141#pragma mark Namespace Declarations
5142
5143NamespaceDecl *
5144ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
5145{
5146    NamespaceDecl *namespace_decl = NULL;
5147    ASTContext *ast = getASTContext();
5148    TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
5149    if (decl_ctx == NULL)
5150        decl_ctx = translation_unit_decl;
5151
5152    if (name)
5153    {
5154        IdentifierInfo &identifier_info = ast->Idents.get(name);
5155        DeclarationName decl_name (&identifier_info);
5156        clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
5157        for (NamedDecl *decl : result)
5158        {
5159            namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
5160            if (namespace_decl)
5161                return namespace_decl;
5162        }
5163
5164        namespace_decl = NamespaceDecl::Create(*ast,
5165                                               decl_ctx,
5166                                               false,
5167                                               SourceLocation(),
5168                                               SourceLocation(),
5169                                               &identifier_info,
5170                                               NULL);
5171
5172        decl_ctx->addDecl (namespace_decl);
5173    }
5174    else
5175    {
5176        if (decl_ctx == translation_unit_decl)
5177        {
5178            namespace_decl = translation_unit_decl->getAnonymousNamespace();
5179            if (namespace_decl)
5180                return namespace_decl;
5181
5182            namespace_decl = NamespaceDecl::Create(*ast,
5183                                                   decl_ctx,
5184                                                   false,
5185                                                   SourceLocation(),
5186                                                   SourceLocation(),
5187                                                   NULL,
5188                                                   NULL);
5189            translation_unit_decl->setAnonymousNamespace (namespace_decl);
5190            translation_unit_decl->addDecl (namespace_decl);
5191            assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
5192        }
5193        else
5194        {
5195            NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
5196            if (parent_namespace_decl)
5197            {
5198                namespace_decl = parent_namespace_decl->getAnonymousNamespace();
5199                if (namespace_decl)
5200                    return namespace_decl;
5201                namespace_decl = NamespaceDecl::Create(*ast,
5202                                                       decl_ctx,
5203                                                       false,
5204                                                       SourceLocation(),
5205                                                       SourceLocation(),
5206                                                       NULL,
5207                                                       NULL);
5208                parent_namespace_decl->setAnonymousNamespace (namespace_decl);
5209                parent_namespace_decl->addDecl (namespace_decl);
5210                assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
5211            }
5212            else
5213            {
5214                // BAD!!!
5215            }
5216        }
5217
5218
5219        if (namespace_decl)
5220        {
5221            // If we make it here, we are creating the anonymous namespace decl
5222            // for the first time, so we need to do the using directive magic
5223            // like SEMA does
5224            UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast,
5225                                                                                   decl_ctx,
5226                                                                                   SourceLocation(),
5227                                                                                   SourceLocation(),
5228                                                                                   NestedNameSpecifierLoc(),
5229                                                                                   SourceLocation(),
5230                                                                                   namespace_decl,
5231                                                                                   decl_ctx);
5232            using_directive_decl->setImplicit();
5233            decl_ctx->addDecl(using_directive_decl);
5234        }
5235    }
5236#ifdef LLDB_CONFIGURATION_DEBUG
5237    VerifyDecl(namespace_decl);
5238#endif
5239    return namespace_decl;
5240}
5241
5242
5243#pragma mark Function Types
5244
5245FunctionDecl *
5246ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx, const char *name, clang_type_t function_clang_type, int storage, bool is_inline)
5247{
5248    FunctionDecl *func_decl = NULL;
5249    ASTContext *ast = getASTContext();
5250    if (decl_ctx == NULL)
5251        decl_ctx = ast->getTranslationUnitDecl();
5252
5253    if (name && name[0])
5254    {
5255        func_decl = FunctionDecl::Create (*ast,
5256                                          decl_ctx,
5257                                          SourceLocation(),
5258                                          SourceLocation(),
5259                                          DeclarationName (&ast->Idents.get(name)),
5260                                          QualType::getFromOpaquePtr(function_clang_type),
5261                                          NULL,
5262                                          (FunctionDecl::StorageClass)storage,
5263                                          (FunctionDecl::StorageClass)storage,
5264                                          is_inline);
5265    }
5266    else
5267    {
5268        func_decl = FunctionDecl::Create (*ast,
5269                                          decl_ctx,
5270                                          SourceLocation(),
5271                                          SourceLocation(),
5272                                          DeclarationName (),
5273                                          QualType::getFromOpaquePtr(function_clang_type),
5274                                          NULL,
5275                                          (FunctionDecl::StorageClass)storage,
5276                                          (FunctionDecl::StorageClass)storage,
5277                                          is_inline);
5278    }
5279    if (func_decl)
5280        decl_ctx->addDecl (func_decl);
5281
5282#ifdef LLDB_CONFIGURATION_DEBUG
5283    VerifyDecl(func_decl);
5284#endif
5285
5286    return func_decl;
5287}
5288
5289clang_type_t
5290ClangASTContext::CreateFunctionType (ASTContext *ast,
5291                                     clang_type_t result_type,
5292                                     clang_type_t *args,
5293                                     unsigned num_args,
5294                                     bool is_variadic,
5295                                     unsigned type_quals)
5296{
5297    assert (ast != NULL);
5298    std::vector<QualType> qual_type_args;
5299    for (unsigned i=0; i<num_args; ++i)
5300        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
5301
5302    // TODO: Detect calling convention in DWARF?
5303    FunctionProtoType::ExtProtoInfo proto_info;
5304    proto_info.Variadic = is_variadic;
5305    proto_info.ExceptionSpecType = EST_None;
5306    proto_info.TypeQuals = type_quals;
5307    proto_info.RefQualifier = RQ_None;
5308    proto_info.NumExceptions = 0;
5309    proto_info.Exceptions = NULL;
5310
5311    return ast->getFunctionType (QualType::getFromOpaquePtr(result_type),
5312                                 qual_type_args,
5313                                 proto_info).getAsOpaquePtr();
5314}
5315
5316ParmVarDecl *
5317ClangASTContext::CreateParameterDeclaration (const char *name, clang_type_t param_type, int storage)
5318{
5319    ASTContext *ast = getASTContext();
5320    assert (ast != NULL);
5321    return ParmVarDecl::Create(*ast,
5322                                ast->getTranslationUnitDecl(),
5323                                SourceLocation(),
5324                                SourceLocation(),
5325                                name && name[0] ? &ast->Idents.get(name) : NULL,
5326                                QualType::getFromOpaquePtr(param_type),
5327                                NULL,
5328                                (VarDecl::StorageClass)storage,
5329                                (VarDecl::StorageClass)storage,
5330                                0);
5331}
5332
5333void
5334ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
5335{
5336    if (function_decl)
5337        function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
5338}
5339
5340
5341#pragma mark Array Types
5342
5343clang_type_t
5344ClangASTContext::CreateArrayType (clang_type_t element_type, size_t element_count)
5345{
5346    if (element_type)
5347    {
5348        ASTContext *ast = getASTContext();
5349        assert (ast != NULL);
5350        llvm::APInt ap_element_count (64, element_count);
5351        if (element_count == 0)
5352        {
5353            return ast->getIncompleteArrayType(QualType::getFromOpaquePtr(element_type),
5354                                               ArrayType::Normal,
5355                                               0).getAsOpaquePtr();
5356
5357        }
5358        else
5359        {
5360            return ast->getConstantArrayType(QualType::getFromOpaquePtr(element_type),
5361                                                     ap_element_count,
5362                                                     ArrayType::Normal,
5363                                                     0).getAsOpaquePtr(); // ElemQuals
5364        }
5365    }
5366    return NULL;
5367}
5368
5369
5370#pragma mark TagDecl
5371
5372bool
5373ClangASTContext::StartTagDeclarationDefinition (clang_type_t clang_type)
5374{
5375    if (clang_type)
5376    {
5377        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5378        const clang::Type *t = qual_type.getTypePtr();
5379        if (t)
5380        {
5381            const TagType *tag_type = dyn_cast<TagType>(t);
5382            if (tag_type)
5383            {
5384                TagDecl *tag_decl = tag_type->getDecl();
5385                if (tag_decl)
5386                {
5387                    tag_decl->startDefinition();
5388                    return true;
5389                }
5390            }
5391
5392            const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(t);
5393            if (object_type)
5394            {
5395                ObjCInterfaceDecl *interface_decl = object_type->getInterface();
5396                if (interface_decl)
5397                {
5398                    interface_decl->startDefinition();
5399                    return true;
5400                }
5401            }
5402        }
5403    }
5404    return false;
5405}
5406
5407bool
5408ClangASTContext::CompleteTagDeclarationDefinition (clang_type_t clang_type)
5409{
5410    if (clang_type)
5411    {
5412        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5413
5414        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
5415
5416        if (cxx_record_decl)
5417        {
5418            cxx_record_decl->completeDefinition();
5419
5420            return true;
5421        }
5422
5423        const EnumType *enum_type = dyn_cast<EnumType>(qual_type.getTypePtr());
5424
5425        if (enum_type)
5426        {
5427            EnumDecl *enum_decl = enum_type->getDecl();
5428
5429            if (enum_decl)
5430            {
5431                /// TODO This really needs to be fixed.
5432
5433                unsigned NumPositiveBits = 1;
5434                unsigned NumNegativeBits = 0;
5435
5436                ASTContext *ast = getASTContext();
5437
5438                QualType promotion_qual_type;
5439                // If the enum integer type is less than an integer in bit width,
5440                // then we must promote it to an integer size.
5441                if (ast->getTypeSize(enum_decl->getIntegerType()) < ast->getTypeSize(ast->IntTy))
5442                {
5443                    if (enum_decl->getIntegerType()->isSignedIntegerType())
5444                        promotion_qual_type = ast->IntTy;
5445                    else
5446                        promotion_qual_type = ast->UnsignedIntTy;
5447                }
5448                else
5449                    promotion_qual_type = enum_decl->getIntegerType();
5450
5451                enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits);
5452                return true;
5453            }
5454        }
5455    }
5456    return false;
5457}
5458
5459
5460#pragma mark Enumeration Types
5461
5462clang_type_t
5463ClangASTContext::CreateEnumerationType
5464(
5465    const char *name,
5466    DeclContext *decl_ctx,
5467    const Declaration &decl,
5468    clang_type_t integer_qual_type
5469)
5470{
5471    // TODO: Do something intelligent with the Declaration object passed in
5472    // like maybe filling in the SourceLocation with it...
5473    ASTContext *ast = getASTContext();
5474    assert (ast != NULL);
5475
5476    // TODO: ask about these...
5477//    const bool IsScoped = false;
5478//    const bool IsFixed = false;
5479
5480    EnumDecl *enum_decl = EnumDecl::Create (*ast,
5481                                            decl_ctx,
5482                                            SourceLocation(),
5483                                            SourceLocation(),
5484                                            name && name[0] ? &ast->Idents.get(name) : NULL,
5485                                            NULL,
5486                                            false,  // IsScoped
5487                                            false,  // IsScopedUsingClassTag
5488                                            false); // IsFixed
5489
5490
5491    if (enum_decl)
5492    {
5493        // TODO: check if we should be setting the promotion type too?
5494        enum_decl->setIntegerType(QualType::getFromOpaquePtr (integer_qual_type));
5495
5496        enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
5497
5498        return ast->getTagDeclType(enum_decl).getAsOpaquePtr();
5499    }
5500    return NULL;
5501}
5502
5503clang_type_t
5504ClangASTContext::GetEnumerationIntegerType (clang_type_t enum_clang_type)
5505{
5506    QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5507
5508    const clang::Type *clang_type = enum_qual_type.getTypePtr();
5509    if (clang_type)
5510    {
5511        const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5512        if (enum_type)
5513        {
5514            EnumDecl *enum_decl = enum_type->getDecl();
5515            if (enum_decl)
5516                return enum_decl->getIntegerType().getAsOpaquePtr();
5517        }
5518    }
5519    return NULL;
5520}
5521bool
5522ClangASTContext::AddEnumerationValueToEnumerationType
5523(
5524    clang_type_t enum_clang_type,
5525    clang_type_t enumerator_clang_type,
5526    const Declaration &decl,
5527    const char *name,
5528    int64_t enum_value,
5529    uint32_t enum_value_bit_size
5530)
5531{
5532    if (enum_clang_type && enumerator_clang_type && name)
5533    {
5534        // TODO: Do something intelligent with the Declaration object passed in
5535        // like maybe filling in the SourceLocation with it...
5536        ASTContext *ast = getASTContext();
5537        IdentifierTable *identifier_table = getIdentifierTable();
5538
5539        assert (ast != NULL);
5540        assert (identifier_table != NULL);
5541        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5542
5543        bool is_signed = false;
5544        IsIntegerType (enumerator_clang_type, is_signed);
5545        const clang::Type *clang_type = enum_qual_type.getTypePtr();
5546        if (clang_type)
5547        {
5548            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5549
5550            if (enum_type)
5551            {
5552                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, is_signed);
5553                enum_llvm_apsint = enum_value;
5554                EnumConstantDecl *enumerator_decl =
5555                    EnumConstantDecl::Create (*ast,
5556                                              enum_type->getDecl(),
5557                                              SourceLocation(),
5558                                              name ? &identifier_table->get(name) : NULL,    // Identifier
5559                                              QualType::getFromOpaquePtr(enumerator_clang_type),
5560                                              NULL,
5561                                              enum_llvm_apsint);
5562
5563                if (enumerator_decl)
5564                {
5565                    enum_type->getDecl()->addDecl(enumerator_decl);
5566
5567#ifdef LLDB_CONFIGURATION_DEBUG
5568                    VerifyDecl(enumerator_decl);
5569#endif
5570
5571                    return true;
5572                }
5573            }
5574        }
5575    }
5576    return false;
5577}
5578
5579#pragma mark Pointers & References
5580
5581clang_type_t
5582ClangASTContext::CreatePointerType (clang_type_t clang_type)
5583{
5584    return CreatePointerType (getASTContext(), clang_type);
5585}
5586
5587clang_type_t
5588ClangASTContext::CreatePointerType (clang::ASTContext *ast, clang_type_t clang_type)
5589{
5590    if (ast && clang_type)
5591    {
5592        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5593
5594        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5595        switch (type_class)
5596        {
5597        case clang::Type::ObjCObject:
5598        case clang::Type::ObjCInterface:
5599            return ast->getObjCObjectPointerType(qual_type).getAsOpaquePtr();
5600
5601        default:
5602            return ast->getPointerType(qual_type).getAsOpaquePtr();
5603        }
5604    }
5605    return NULL;
5606}
5607
5608clang_type_t
5609ClangASTContext::CreateLValueReferenceType (clang::ASTContext *ast,
5610                                            clang_type_t clang_type)
5611{
5612    if (clang_type)
5613        return ast->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5614    return NULL;
5615}
5616
5617clang_type_t
5618ClangASTContext::CreateRValueReferenceType (clang::ASTContext *ast,
5619                                            clang_type_t clang_type)
5620{
5621    if (clang_type)
5622        return ast->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5623    return NULL;
5624}
5625
5626clang_type_t
5627ClangASTContext::CreateMemberPointerType (clang_type_t clang_pointee_type, clang_type_t clang_class_type)
5628{
5629    if (clang_pointee_type && clang_pointee_type)
5630        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
5631                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
5632    return NULL;
5633}
5634
5635uint64_t
5636ClangASTContext::GetPointerBitSize ()
5637{
5638    ASTContext *ast = getASTContext();
5639    return ast->getTypeSize(ast->VoidPtrTy);
5640}
5641
5642bool
5643ClangASTContext::IsPossibleDynamicType (clang::ASTContext *ast,
5644                                        clang_type_t clang_type,
5645                                        clang_type_t *dynamic_pointee_type,
5646                                        bool check_cplusplus,
5647                                        bool check_objc)
5648{
5649    QualType pointee_qual_type;
5650    if (clang_type)
5651    {
5652        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5653        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5654        bool success = false;
5655        switch (type_class)
5656        {
5657            case clang::Type::Builtin:
5658                if (check_objc && cast<clang::BuiltinType>(qual_type)->getKind() == clang::BuiltinType::ObjCId)
5659                {
5660                    if (dynamic_pointee_type)
5661                        *dynamic_pointee_type = clang_type;
5662                    return true;
5663                }
5664                break;
5665
5666            case clang::Type::ObjCObjectPointer:
5667                if (check_objc)
5668                {
5669                    if (dynamic_pointee_type)
5670                        *dynamic_pointee_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5671                    return true;
5672                }
5673                break;
5674
5675            case clang::Type::Pointer:
5676                pointee_qual_type = cast<PointerType>(qual_type)->getPointeeType();
5677                success = true;
5678                break;
5679
5680            case clang::Type::LValueReference:
5681            case clang::Type::RValueReference:
5682                pointee_qual_type = cast<ReferenceType>(qual_type)->getPointeeType();
5683                success = true;
5684                break;
5685
5686            case clang::Type::Typedef:
5687                return ClangASTContext::IsPossibleDynamicType (ast,
5688                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5689                                                               dynamic_pointee_type,
5690                                                               check_cplusplus,
5691                                                               check_objc);
5692
5693            case clang::Type::Elaborated:
5694                return ClangASTContext::IsPossibleDynamicType (ast,
5695                                                               cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5696                                                               dynamic_pointee_type,
5697                                                               check_cplusplus,
5698                                                               check_objc);
5699
5700            default:
5701                break;
5702        }
5703
5704        if (success)
5705        {
5706            // Check to make sure what we are pointing too is a possible dynamic C++ type
5707            // We currently accept any "void *" (in case we have a class that has been
5708            // watered down to an opaque pointer) and virtual C++ classes.
5709            const clang::Type::TypeClass pointee_type_class = pointee_qual_type->getTypeClass();
5710            switch (pointee_type_class)
5711            {
5712                case clang::Type::Builtin:
5713                    switch (cast<clang::BuiltinType>(pointee_qual_type)->getKind())
5714                    {
5715                        case clang::BuiltinType::UnknownAny:
5716                        case clang::BuiltinType::Void:
5717                            if (dynamic_pointee_type)
5718                                *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5719                            return true;
5720
5721                        case clang::BuiltinType::NullPtr:
5722                        case clang::BuiltinType::Bool:
5723                        case clang::BuiltinType::Char_U:
5724                        case clang::BuiltinType::UChar:
5725                        case clang::BuiltinType::WChar_U:
5726                        case clang::BuiltinType::Char16:
5727                        case clang::BuiltinType::Char32:
5728                        case clang::BuiltinType::UShort:
5729                        case clang::BuiltinType::UInt:
5730                        case clang::BuiltinType::ULong:
5731                        case clang::BuiltinType::ULongLong:
5732                        case clang::BuiltinType::UInt128:
5733                        case clang::BuiltinType::Char_S:
5734                        case clang::BuiltinType::SChar:
5735                        case clang::BuiltinType::WChar_S:
5736                        case clang::BuiltinType::Short:
5737                        case clang::BuiltinType::Int:
5738                        case clang::BuiltinType::Long:
5739                        case clang::BuiltinType::LongLong:
5740                        case clang::BuiltinType::Int128:
5741                        case clang::BuiltinType::Float:
5742                        case clang::BuiltinType::Double:
5743                        case clang::BuiltinType::LongDouble:
5744                        case clang::BuiltinType::Dependent:
5745                        case clang::BuiltinType::Overload:
5746                        case clang::BuiltinType::ObjCId:
5747                        case clang::BuiltinType::ObjCClass:
5748                        case clang::BuiltinType::ObjCSel:
5749                        case clang::BuiltinType::BoundMember:
5750                        case clang::BuiltinType::Half:
5751                        case clang::BuiltinType::ARCUnbridgedCast:
5752                        case clang::BuiltinType::PseudoObject:
5753                        case clang::BuiltinType::BuiltinFn:
5754                        case clang::BuiltinType::OCLEvent:
5755                        case clang::BuiltinType::OCLImage1d:
5756                        case clang::BuiltinType::OCLImage1dArray:
5757                        case clang::BuiltinType::OCLImage1dBuffer:
5758                        case clang::BuiltinType::OCLImage2d:
5759                        case clang::BuiltinType::OCLImage2dArray:
5760                        case clang::BuiltinType::OCLImage3d:
5761                        case clang::BuiltinType::OCLSampler:
5762                            break;
5763                    }
5764                    break;
5765
5766                case clang::Type::Record:
5767                    if (check_cplusplus)
5768                    {
5769                        CXXRecordDecl *cxx_record_decl = pointee_qual_type->getAsCXXRecordDecl();
5770                        if (cxx_record_decl)
5771                        {
5772                            bool is_complete = cxx_record_decl->isCompleteDefinition();
5773
5774                            if (is_complete)
5775                                success = cxx_record_decl->isDynamicClass();
5776                            else
5777                            {
5778                                ClangASTMetadata *metadata = GetMetadata (ast, cxx_record_decl);
5779                                if (metadata)
5780                                    success = metadata->GetIsDynamicCXXType();
5781                                else
5782                                {
5783                                    is_complete = ClangASTContext::GetCompleteType (ast, pointee_qual_type.getAsOpaquePtr());
5784                                    if (is_complete)
5785                                        success = cxx_record_decl->isDynamicClass();
5786                                    else
5787                                        success = false;
5788                                }
5789                            }
5790
5791                            if (success)
5792                            {
5793                                if (dynamic_pointee_type)
5794                                    *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5795                                return true;
5796                            }
5797                        }
5798                    }
5799                    break;
5800
5801                case clang::Type::ObjCObject:
5802                case clang::Type::ObjCInterface:
5803                    if (check_objc)
5804                    {
5805                        if (dynamic_pointee_type)
5806                            *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5807                        return true;
5808                    }
5809                    break;
5810
5811                default:
5812                    break;
5813            }
5814        }
5815    }
5816    if (dynamic_pointee_type)
5817        *dynamic_pointee_type = NULL;
5818    return false;
5819}
5820
5821
5822bool
5823ClangASTContext::IsPossibleCPlusPlusDynamicType (clang::ASTContext *ast, clang_type_t clang_type, clang_type_t *dynamic_pointee_type)
5824{
5825    return IsPossibleDynamicType (ast,
5826                                  clang_type,
5827                                  dynamic_pointee_type,
5828                                  true,     // Check for dynamic C++ types
5829                                  false);   // Check for dynamic ObjC types
5830}
5831
5832bool
5833ClangASTContext::IsReferenceType (clang_type_t clang_type, clang_type_t *target_type)
5834{
5835    if (clang_type == NULL)
5836        return false;
5837
5838    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5839    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5840
5841    switch (type_class)
5842    {
5843    case clang::Type::LValueReference:
5844        if (target_type)
5845            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5846        return true;
5847    case clang::Type::RValueReference:
5848        if (target_type)
5849            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5850        return true;
5851    case clang::Type::Typedef:
5852        return ClangASTContext::IsReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5853    case clang::Type::Elaborated:
5854        return ClangASTContext::IsReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5855    default:
5856        break;
5857    }
5858
5859    return false;
5860}
5861
5862bool
5863ClangASTContext::IsPointerOrReferenceType (clang_type_t clang_type, clang_type_t*target_type)
5864{
5865    if (clang_type == NULL)
5866        return false;
5867
5868    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5869    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5870    switch (type_class)
5871    {
5872    case clang::Type::Builtin:
5873        switch (cast<clang::BuiltinType>(qual_type)->getKind())
5874        {
5875        default:
5876            break;
5877        case clang::BuiltinType::ObjCId:
5878        case clang::BuiltinType::ObjCClass:
5879            return true;
5880        }
5881        return false;
5882    case clang::Type::ObjCObjectPointer:
5883        if (target_type)
5884            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5885        return true;
5886    case clang::Type::BlockPointer:
5887        if (target_type)
5888            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5889        return true;
5890    case clang::Type::Pointer:
5891        if (target_type)
5892            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5893        return true;
5894    case clang::Type::MemberPointer:
5895        if (target_type)
5896            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5897        return true;
5898    case clang::Type::LValueReference:
5899        if (target_type)
5900            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5901        return true;
5902    case clang::Type::RValueReference:
5903        if (target_type)
5904            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5905        return true;
5906    case clang::Type::Typedef:
5907        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5908    case clang::Type::Elaborated:
5909        return ClangASTContext::IsPointerOrReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5910    default:
5911        break;
5912    }
5913    return false;
5914}
5915
5916bool
5917ClangASTContext::IsIntegerType (clang_type_t clang_type, bool &is_signed)
5918{
5919    if (!clang_type)
5920        return false;
5921
5922    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5923    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
5924
5925    if (builtin_type)
5926    {
5927        if (builtin_type->isInteger())
5928        {
5929            is_signed = builtin_type->isSignedInteger();
5930            return true;
5931        }
5932    }
5933
5934    return false;
5935}
5936
5937bool
5938ClangASTContext::IsPointerType (clang_type_t clang_type, clang_type_t *target_type)
5939{
5940    if (target_type)
5941        *target_type = NULL;
5942
5943    if (clang_type)
5944    {
5945        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5946        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5947        switch (type_class)
5948        {
5949        case clang::Type::Builtin:
5950            switch (cast<clang::BuiltinType>(qual_type)->getKind())
5951            {
5952            default:
5953                break;
5954            case clang::BuiltinType::ObjCId:
5955            case clang::BuiltinType::ObjCClass:
5956                return true;
5957            }
5958            return false;
5959        case clang::Type::ObjCObjectPointer:
5960            if (target_type)
5961                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5962            return true;
5963        case clang::Type::BlockPointer:
5964            if (target_type)
5965                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5966            return true;
5967        case clang::Type::Pointer:
5968            if (target_type)
5969                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5970            return true;
5971        case clang::Type::MemberPointer:
5972            if (target_type)
5973                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5974            return true;
5975        case clang::Type::Typedef:
5976            return ClangASTContext::IsPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), target_type);
5977        case clang::Type::Elaborated:
5978            return ClangASTContext::IsPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), target_type);
5979        default:
5980            break;
5981        }
5982    }
5983    return false;
5984}
5985
5986bool
5987ClangASTContext::IsFloatingPointType (clang_type_t clang_type, uint32_t &count, bool &is_complex)
5988{
5989    if (clang_type)
5990    {
5991        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5992
5993        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
5994        {
5995            clang::BuiltinType::Kind kind = BT->getKind();
5996            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
5997            {
5998                count = 1;
5999                is_complex = false;
6000                return true;
6001            }
6002        }
6003        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
6004        {
6005            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
6006            {
6007                count = 2;
6008                is_complex = true;
6009                return true;
6010            }
6011        }
6012        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
6013        {
6014            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
6015            {
6016                count = VT->getNumElements();
6017                is_complex = false;
6018                return true;
6019            }
6020        }
6021    }
6022    return false;
6023}
6024
6025bool
6026ClangASTContext::IsScalarType (lldb::clang_type_t clang_type)
6027{
6028    bool is_signed;
6029    if (ClangASTContext::IsIntegerType(clang_type, is_signed))
6030        return true;
6031
6032    uint32_t count;
6033    bool is_complex;
6034    return ClangASTContext::IsFloatingPointType(clang_type, count, is_complex) && !is_complex;
6035}
6036
6037bool
6038ClangASTContext::IsPointerToScalarType (lldb::clang_type_t clang_type)
6039{
6040    if (!IsPointerType(clang_type))
6041        return false;
6042
6043    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6044    lldb::clang_type_t pointee_type = qual_type.getTypePtr()->getPointeeType().getAsOpaquePtr();
6045    return IsScalarType(pointee_type);
6046}
6047
6048bool
6049ClangASTContext::IsArrayOfScalarType (lldb::clang_type_t clang_type)
6050{
6051    clang_type = GetAsArrayType(clang_type, NULL, NULL, NULL);
6052
6053    if (clang_type == 0)
6054        return false;
6055
6056    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6057    lldb::clang_type_t item_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
6058    return IsScalarType(item_type);
6059}
6060
6061
6062bool
6063ClangASTContext::GetCXXClassName (clang_type_t clang_type, std::string &class_name)
6064{
6065    if (clang_type)
6066    {
6067        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6068
6069        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
6070        if (cxx_record_decl)
6071        {
6072            class_name.assign (cxx_record_decl->getIdentifier()->getNameStart());
6073            return true;
6074        }
6075    }
6076    class_name.clear();
6077    return false;
6078}
6079
6080
6081bool
6082ClangASTContext::IsCXXClassType (clang_type_t clang_type)
6083{
6084    if (clang_type)
6085    {
6086        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6087        if (qual_type->getAsCXXRecordDecl() != NULL)
6088            return true;
6089    }
6090    return false;
6091}
6092
6093bool
6094ClangASTContext::IsBeingDefined (lldb::clang_type_t clang_type)
6095{
6096    if (clang_type)
6097    {
6098        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6099        const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type);
6100        if (tag_type)
6101            return tag_type->isBeingDefined();
6102    }
6103    return false;
6104}
6105
6106bool
6107ClangASTContext::IsObjCClassType (clang_type_t clang_type)
6108{
6109    if (clang_type)
6110    {
6111        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6112        if (qual_type->isObjCObjectOrInterfaceType())
6113            return true;
6114    }
6115    return false;
6116}
6117
6118bool
6119ClangASTContext::IsObjCObjectPointerType (lldb::clang_type_t clang_type, clang_type_t *class_type)
6120{
6121    if (clang_type)
6122    {
6123        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6124        if (qual_type->isObjCObjectPointerType())
6125        {
6126            if (class_type)
6127            {
6128                *class_type = NULL;
6129
6130                if (!qual_type->isObjCClassType() &&
6131                    !qual_type->isObjCIdType())
6132                {
6133                    const ObjCObjectPointerType *obj_pointer_type = dyn_cast<ObjCObjectPointerType>(qual_type);
6134                    if (!obj_pointer_type)
6135                        *class_type = NULL;
6136                    else
6137                        *class_type = QualType(obj_pointer_type->getInterfaceType(), 0).getAsOpaquePtr();
6138                }
6139            }
6140            return true;
6141        }
6142    }
6143    return false;
6144}
6145
6146bool
6147ClangASTContext::GetObjCClassName (lldb::clang_type_t clang_type,
6148                                   std::string &class_name)
6149{
6150    if (!clang_type)
6151        return false;
6152
6153    const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(QualType::getFromOpaquePtr(clang_type));
6154    if (!object_type)
6155        return false;
6156
6157    const ObjCInterfaceDecl *interface = object_type->getInterface();
6158    if (!interface)
6159        return false;
6160
6161    class_name = interface->getNameAsString();
6162    return true;
6163}
6164
6165bool
6166ClangASTContext::IsCharType (clang_type_t clang_type)
6167{
6168    if (clang_type)
6169        return QualType::getFromOpaquePtr(clang_type)->isCharType();
6170    return false;
6171}
6172
6173bool
6174ClangASTContext::IsCStringType (clang_type_t clang_type, uint32_t &length)
6175{
6176    clang_type_t pointee_or_element_clang_type = NULL;
6177    Flags type_flags (ClangASTContext::GetTypeInfo (clang_type, NULL, &pointee_or_element_clang_type));
6178
6179    if (pointee_or_element_clang_type == NULL)
6180        return false;
6181
6182    if (type_flags.AnySet (eTypeIsArray | eTypeIsPointer))
6183    {
6184        QualType pointee_or_element_qual_type (QualType::getFromOpaquePtr (pointee_or_element_clang_type));
6185
6186        if (pointee_or_element_qual_type.getUnqualifiedType()->isCharType())
6187        {
6188            QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6189            if (type_flags.Test (eTypeIsArray))
6190            {
6191                // We know the size of the array and it could be a C string
6192                // since it is an array of characters
6193                length = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
6194                return true;
6195            }
6196            else
6197            {
6198                length = 0;
6199                return true;
6200            }
6201
6202        }
6203    }
6204    return false;
6205}
6206
6207bool
6208ClangASTContext::IsFunctionPointerType (clang_type_t clang_type)
6209{
6210    if (clang_type)
6211    {
6212        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6213
6214        if (qual_type->isFunctionPointerType())
6215            return true;
6216
6217        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6218        switch (type_class)
6219        {
6220        default:
6221            break;
6222        case clang::Type::Typedef:
6223            return ClangASTContext::IsFunctionPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6224        case clang::Type::Elaborated:
6225            return ClangASTContext::IsFunctionPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6226
6227        case clang::Type::LValueReference:
6228        case clang::Type::RValueReference:
6229            {
6230                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
6231                if (reference_type)
6232                    return ClangASTContext::IsFunctionPointerType (reference_type->getPointeeType().getAsOpaquePtr());
6233            }
6234            break;
6235        }
6236    }
6237    return false;
6238}
6239
6240size_t
6241ClangASTContext::GetArraySize (clang_type_t clang_type)
6242{
6243    if (clang_type)
6244    {
6245        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
6246        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6247        switch (type_class)
6248        {
6249        case clang::Type::ConstantArray:
6250            {
6251                const ConstantArrayType *array = cast<ConstantArrayType>(QualType::getFromOpaquePtr(clang_type).getTypePtr());
6252                if (array)
6253                    return array->getSize().getLimitedValue();
6254            }
6255            break;
6256
6257        case clang::Type::Typedef:
6258            return ClangASTContext::GetArraySize(cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6259
6260        case clang::Type::Elaborated:
6261            return ClangASTContext::GetArraySize(cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6262
6263        default:
6264            break;
6265        }
6266    }
6267    return 0;
6268}
6269
6270clang_type_t
6271ClangASTContext::GetAsArrayType (clang_type_t clang_type, clang_type_t*member_type, uint64_t *size, bool *is_incomplete)
6272{
6273    if (is_incomplete)
6274        *is_incomplete = false;
6275    if (!clang_type)
6276        return 0;
6277
6278    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6279
6280    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6281    switch (type_class)
6282    {
6283    default:
6284        break;
6285
6286    case clang::Type::ConstantArray:
6287        if (member_type)
6288            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6289        if (size)
6290            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULLONG_MAX);
6291        return clang_type;
6292
6293    case clang::Type::IncompleteArray:
6294        if (member_type)
6295            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6296        if (size)
6297            *size = 0;
6298        if (is_incomplete)
6299            *is_incomplete = true;
6300        return clang_type;
6301
6302    case clang::Type::VariableArray:
6303        if (member_type)
6304            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6305        if (size)
6306            *size = 0;
6307        return clang_type;
6308
6309    case clang::Type::DependentSizedArray:
6310        if (member_type)
6311            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6312        if (size)
6313            *size = 0;
6314        return clang_type;
6315
6316    case clang::Type::Typedef:
6317        return ClangASTContext::GetAsArrayType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
6318                                                member_type,
6319                                                size,
6320                                                is_incomplete);
6321
6322    case clang::Type::Elaborated:
6323        return ClangASTContext::GetAsArrayType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
6324                                                member_type,
6325                                                size,
6326                                                is_incomplete);
6327    }
6328    return 0;
6329}
6330
6331
6332#pragma mark Typedefs
6333
6334clang_type_t
6335ClangASTContext::CreateTypedefType (const char *name, clang_type_t clang_type, DeclContext *decl_ctx)
6336{
6337    if (clang_type)
6338    {
6339        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6340        ASTContext *ast = getASTContext();
6341        IdentifierTable *identifier_table = getIdentifierTable();
6342        assert (ast != NULL);
6343        assert (identifier_table != NULL);
6344        if (decl_ctx == NULL)
6345            decl_ctx = ast->getTranslationUnitDecl();
6346        TypedefDecl *decl = TypedefDecl::Create (*ast,
6347                                                 decl_ctx,
6348                                                 SourceLocation(),
6349                                                 SourceLocation(),
6350                                                 name ? &identifier_table->get(name) : NULL, // Identifier
6351                                                 ast->getTrivialTypeSourceInfo(qual_type));
6352
6353        //decl_ctx->addDecl (decl);
6354
6355        decl->setAccess(AS_public); // TODO respect proper access specifier
6356
6357        // Get a uniqued QualType for the typedef decl type
6358        return ast->getTypedefType (decl).getAsOpaquePtr();
6359    }
6360    return NULL;
6361}
6362
6363// Disable this for now since I can't seem to get a nicely formatted float
6364// out of the APFloat class without just getting the float, double or quad
6365// and then using a formatted print on it which defeats the purpose. We ideally
6366// would like to get perfect string values for any kind of float semantics
6367// so we can support remote targets. The code below also requires a patch to
6368// llvm::APInt.
6369//bool
6370//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)
6371//{
6372//  uint32_t count = 0;
6373//  bool is_complex = false;
6374//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6375//  {
6376//      unsigned num_bytes_per_float = byte_size / count;
6377//      unsigned num_bits_per_float = num_bytes_per_float * 8;
6378//
6379//      float_str.clear();
6380//      uint32_t i;
6381//      for (i=0; i<count; i++)
6382//      {
6383//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
6384//          bool is_ieee = false;
6385//          APFloat ap_float(ap_int, is_ieee);
6386//          char s[1024];
6387//          unsigned int hex_digits = 0;
6388//          bool upper_case = false;
6389//
6390//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
6391//          {
6392//              if (i > 0)
6393//                  float_str.append(", ");
6394//              float_str.append(s);
6395//              if (i == 1 && is_complex)
6396//                  float_str.append(1, 'i');
6397//          }
6398//      }
6399//      return !float_str.empty();
6400//  }
6401//  return false;
6402//}
6403
6404size_t
6405ClangASTContext::ConvertStringToFloatValue (ASTContext *ast, clang_type_t clang_type, const char *s, uint8_t *dst, size_t dst_size)
6406{
6407    if (clang_type)
6408    {
6409        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6410        uint32_t count = 0;
6411        bool is_complex = false;
6412        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6413        {
6414            // TODO: handle complex and vector types
6415            if (count != 1)
6416                return false;
6417
6418            StringRef s_sref(s);
6419            APFloat ap_float(ast->getFloatTypeSemantics(qual_type), s_sref);
6420
6421            const uint64_t bit_size = ast->getTypeSize (qual_type);
6422            const uint64_t byte_size = bit_size / 8;
6423            if (dst_size >= byte_size)
6424            {
6425                if (bit_size == sizeof(float)*8)
6426                {
6427                    float float32 = ap_float.convertToFloat();
6428                    ::memcpy (dst, &float32, byte_size);
6429                    return byte_size;
6430                }
6431                else if (bit_size >= 64)
6432                {
6433                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
6434                    ::memcpy (dst, ap_int.getRawData(), byte_size);
6435                    return byte_size;
6436                }
6437            }
6438        }
6439    }
6440    return 0;
6441}
6442
6443unsigned
6444ClangASTContext::GetTypeQualifiers(clang_type_t clang_type)
6445{
6446    assert (clang_type);
6447
6448    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6449
6450    return qual_type.getQualifiers().getCVRQualifiers();
6451}
6452
6453bool
6454ClangASTContext::GetCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6455{
6456    if (clang_type == NULL)
6457        return false;
6458
6459    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type));
6460}
6461
6462
6463bool
6464ClangASTContext::GetCompleteType (clang_type_t clang_type)
6465{
6466    return ClangASTContext::GetCompleteType (getASTContext(), clang_type);
6467}
6468
6469bool
6470ClangASTContext::IsCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6471{
6472    if (clang_type == NULL)
6473        return false;
6474
6475    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type), false); // just check but don't let it actually complete
6476}
6477
6478
6479bool
6480ClangASTContext::IsCompleteType (clang_type_t clang_type)
6481{
6482    return ClangASTContext::IsCompleteType (getASTContext(), clang_type);
6483}
6484
6485bool
6486ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
6487                                  clang::Decl *decl)
6488{
6489    if (!decl)
6490        return false;
6491
6492    ExternalASTSource *ast_source = ast->getExternalSource();
6493
6494    if (!ast_source)
6495        return false;
6496
6497    if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
6498    {
6499        if (tag_decl->isCompleteDefinition())
6500            return true;
6501
6502        if (!tag_decl->hasExternalLexicalStorage())
6503            return false;
6504
6505        ast_source->CompleteType(tag_decl);
6506
6507        return !tag_decl->getTypeForDecl()->isIncompleteType();
6508    }
6509    else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
6510    {
6511        if (objc_interface_decl->getDefinition())
6512            return true;
6513
6514        if (!objc_interface_decl->hasExternalLexicalStorage())
6515            return false;
6516
6517        ast_source->CompleteType(objc_interface_decl);
6518
6519        return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
6520    }
6521    else
6522    {
6523        return false;
6524    }
6525}
6526
6527void
6528ClangASTContext::SetMetadataAsUserID (const void *object,
6529                                      user_id_t user_id)
6530{
6531    ClangASTMetadata meta_data;
6532    meta_data.SetUserID (user_id);
6533    SetMetadata (object, meta_data);
6534}
6535
6536void
6537ClangASTContext::SetMetadata (clang::ASTContext *ast,
6538                              const void *object,
6539                              ClangASTMetadata &metadata)
6540{
6541    ClangExternalASTSourceCommon *external_source =
6542        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6543
6544    if (external_source)
6545        external_source->SetMetadata(object, metadata);
6546}
6547
6548ClangASTMetadata *
6549ClangASTContext::GetMetadata (clang::ASTContext *ast,
6550                              const void *object)
6551{
6552    ClangExternalASTSourceCommon *external_source =
6553        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6554
6555    if (external_source && external_source->HasMetadata(object))
6556        return external_source->GetMetadata(object);
6557    else
6558        return NULL;
6559}
6560
6561clang::DeclContext *
6562ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
6563{
6564    return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
6565}
6566
6567clang::DeclContext *
6568ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
6569{
6570    return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
6571}
6572
6573
6574bool
6575ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx,
6576                                                   lldb::LanguageType &language,
6577                                                   bool &is_instance_method,
6578                                                   ConstString &language_object_name)
6579{
6580    language_object_name.Clear();
6581    language = eLanguageTypeUnknown;
6582    is_instance_method = false;
6583
6584    if (decl_ctx)
6585    {
6586        if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx))
6587        {
6588            if (method_decl->isStatic())
6589            {
6590                is_instance_method = false;
6591            }
6592            else
6593            {
6594                language_object_name.SetCString("this");
6595                is_instance_method = true;
6596            }
6597            language = eLanguageTypeC_plus_plus;
6598            return true;
6599        }
6600        else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx))
6601        {
6602            // Both static and instance methods have a "self" object in objective C
6603            language_object_name.SetCString("self");
6604            if (method_decl->isInstanceMethod())
6605            {
6606                is_instance_method = true;
6607            }
6608            else
6609            {
6610                is_instance_method = false;
6611            }
6612            language = eLanguageTypeObjC;
6613            return true;
6614        }
6615        else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx))
6616        {
6617            ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), function_decl);
6618            if (metadata && metadata->HasObjectPtr())
6619            {
6620                language_object_name.SetCString (metadata->GetObjectPtrName());
6621                language = eLanguageTypeObjC;
6622                is_instance_method = true;
6623            }
6624            return true;
6625        }
6626    }
6627    return false;
6628}
6629
6630