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