]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/lldb/source/Symbol/ClangASTContext.cpp
MFC r355940:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / lldb / source / Symbol / ClangASTContext.cpp
1 //===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "lldb/Symbol/ClangASTContext.h"
10
11 #include "llvm/Support/FormatAdapters.h"
12 #include "llvm/Support/FormatVariadic.h"
13
14 #include <mutex>
15 #include <string>
16 #include <vector>
17
18
19 // Clang headers like to use NDEBUG inside of them to enable/disable debug
20 // related features using "#ifndef NDEBUG" preprocessor blocks to do one thing
21 // or another. This is bad because it means that if clang was built in release
22 // mode, it assumes that you are building in release mode which is not always
23 // the case. You can end up with functions that are defined as empty in header
24 // files when NDEBUG is not defined, and this can cause link errors with the
25 // clang .a files that you have since you might be missing functions in the .a
26 // file. So we have to define NDEBUG when including clang headers to avoid any
27 // mismatches. This is covered by rdar://problem/8691220
28
29 #if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
30 #define LLDB_DEFINED_NDEBUG_FOR_CLANG
31 #define NDEBUG
32 // Need to include assert.h so it is as clang would expect it to be (disabled)
33 #include <assert.h>
34 #endif
35
36 #include "clang/AST/ASTContext.h"
37 #include "clang/AST/ASTImporter.h"
38 #include "clang/AST/Attr.h"
39 #include "clang/AST/CXXInheritance.h"
40 #include "clang/AST/DeclObjC.h"
41 #include "clang/AST/DeclTemplate.h"
42 #include "clang/AST/Mangle.h"
43 #include "clang/AST/RecordLayout.h"
44 #include "clang/AST/Type.h"
45 #include "clang/AST/VTableBuilder.h"
46 #include "clang/Basic/Builtins.h"
47 #include "clang/Basic/Diagnostic.h"
48 #include "clang/Basic/FileManager.h"
49 #include "clang/Basic/FileSystemOptions.h"
50 #include "clang/Basic/SourceManager.h"
51 #include "clang/Basic/TargetInfo.h"
52 #include "clang/Basic/TargetOptions.h"
53 #include "clang/Frontend/FrontendOptions.h"
54 #include "clang/Frontend/LangStandard.h"
55 #include "clang/Sema/Sema.h"
56
57 #ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
58 #undef NDEBUG
59 #undef LLDB_DEFINED_NDEBUG_FOR_CLANG
60 // Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
61 #include <assert.h>
62 #endif
63
64 #include "llvm/Support/Signals.h"
65 #include "llvm/Support/Threading.h"
66
67 #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
68 #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
69 #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
70 #include "lldb/Utility/ArchSpec.h"
71 #include "lldb/Utility/Flags.h"
72
73 #include "lldb/Core/DumpDataExtractor.h"
74 #include "lldb/Core/Module.h"
75 #include "lldb/Core/PluginManager.h"
76 #include "lldb/Core/StreamFile.h"
77 #include "lldb/Core/ThreadSafeDenseMap.h"
78 #include "lldb/Core/UniqueCStringMap.h"
79 #include "lldb/Symbol/ClangASTContext.h"
80 #include "lldb/Symbol/ClangASTImporter.h"
81 #include "lldb/Symbol/ClangExternalASTSourceCallbacks.h"
82 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
83 #include "lldb/Symbol/ClangUtil.h"
84 #include "lldb/Symbol/ObjectFile.h"
85 #include "lldb/Symbol/SymbolFile.h"
86 #include "lldb/Symbol/VerifyDecl.h"
87 #include "lldb/Target/ExecutionContext.h"
88 #include "lldb/Target/Language.h"
89 #include "lldb/Target/Process.h"
90 #include "lldb/Target/Target.h"
91 #include "lldb/Utility/DataExtractor.h"
92 #include "lldb/Utility/LLDBAssert.h"
93 #include "lldb/Utility/Log.h"
94 #include "lldb/Utility/RegularExpression.h"
95 #include "lldb/Utility/Scalar.h"
96
97 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
98 #include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
99 #ifdef LLDB_ENABLE_ALL
100 #include "Plugins/SymbolFile/PDB/PDBASTParser.h"
101 #endif // LLDB_ENABLE_ALL
102
103 #include <stdio.h>
104
105 #include <mutex>
106
107 using namespace lldb;
108 using namespace lldb_private;
109 using namespace llvm;
110 using namespace clang;
111
112 namespace {
113 static inline bool
114 ClangASTContextSupportsLanguage(lldb::LanguageType language) {
115   return language == eLanguageTypeUnknown || // Clang is the default type system
116          Language::LanguageIsC(language) ||
117          Language::LanguageIsCPlusPlus(language) ||
118          Language::LanguageIsObjC(language) ||
119          Language::LanguageIsPascal(language) ||
120          // Use Clang for Rust until there is a proper language plugin for it
121          language == eLanguageTypeRust ||
122          language == eLanguageTypeExtRenderScript ||
123          // Use Clang for D until there is a proper language plugin for it
124          language == eLanguageTypeD ||
125          // Open Dylan compiler debug info is designed to be Clang-compatible
126          language == eLanguageTypeDylan;
127 }
128
129 // Checks whether m1 is an overload of m2 (as opposed to an override). This is
130 // called by addOverridesForMethod to distinguish overrides (which share a
131 // vtable entry) from overloads (which require distinct entries).
132 bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) {
133   // FIXME: This should detect covariant return types, but currently doesn't.
134   lldbassert(&m1->getASTContext() == &m2->getASTContext() &&
135              "Methods should have the same AST context");
136   clang::ASTContext &context = m1->getASTContext();
137
138   const auto *m1Type = llvm::cast<clang::FunctionProtoType>(
139       context.getCanonicalType(m1->getType()));
140
141   const auto *m2Type = llvm::cast<clang::FunctionProtoType>(
142       context.getCanonicalType(m2->getType()));
143
144   auto compareArgTypes = [&context](const clang::QualType &m1p,
145                                     const clang::QualType &m2p) {
146     return context.hasSameType(m1p.getUnqualifiedType(),
147                                m2p.getUnqualifiedType());
148   };
149
150   // FIXME: In C++14 and later, we can just pass m2Type->param_type_end()
151   //        as a fourth parameter to std::equal().
152   return (m1->getNumParams() != m2->getNumParams()) ||
153          !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(),
154                      m2Type->param_type_begin(), compareArgTypes);
155 }
156
157 // If decl is a virtual method, walk the base classes looking for methods that
158 // decl overrides. This table of overridden methods is used by IRGen to
159 // determine the vtable layout for decl's parent class.
160 void addOverridesForMethod(clang::CXXMethodDecl *decl) {
161   if (!decl->isVirtual())
162     return;
163
164   clang::CXXBasePaths paths;
165
166   auto find_overridden_methods =
167       [decl](const clang::CXXBaseSpecifier *specifier,
168              clang::CXXBasePath &path) {
169         if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>(
170                 specifier->getType()->getAs<clang::RecordType>()->getDecl())) {
171
172           clang::DeclarationName name = decl->getDeclName();
173
174           // If this is a destructor, check whether the base class destructor is
175           // virtual.
176           if (name.getNameKind() == clang::DeclarationName::CXXDestructorName)
177             if (auto *baseDtorDecl = base_record->getDestructor()) {
178               if (baseDtorDecl->isVirtual()) {
179                 path.Decls = baseDtorDecl;
180                 return true;
181               } else
182                 return false;
183             }
184
185           // Otherwise, search for name in the base class.
186           for (path.Decls = base_record->lookup(name); !path.Decls.empty();
187                path.Decls = path.Decls.slice(1)) {
188             if (auto *method_decl =
189                     llvm::dyn_cast<clang::CXXMethodDecl>(path.Decls.front()))
190               if (method_decl->isVirtual() && !isOverload(decl, method_decl)) {
191                 path.Decls = method_decl;
192                 return true;
193               }
194           }
195         }
196
197         return false;
198       };
199
200   if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) {
201     for (auto *overridden_decl : paths.found_decls())
202       decl->addOverriddenMethod(
203           llvm::cast<clang::CXXMethodDecl>(overridden_decl));
204   }
205 }
206 }
207
208 static lldb::addr_t GetVTableAddress(Process &process,
209                                      VTableContextBase &vtable_ctx,
210                                      ValueObject &valobj,
211                                      const ASTRecordLayout &record_layout) {
212   // Retrieve type info
213   CompilerType pointee_type;
214   CompilerType this_type(valobj.GetCompilerType());
215   uint32_t type_info = this_type.GetTypeInfo(&pointee_type);
216   if (!type_info)
217     return LLDB_INVALID_ADDRESS;
218
219   // Check if it's a pointer or reference
220   bool ptr_or_ref = false;
221   if (type_info & (eTypeIsPointer | eTypeIsReference)) {
222     ptr_or_ref = true;
223     type_info = pointee_type.GetTypeInfo();
224   }
225
226   // We process only C++ classes
227   const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus;
228   if ((type_info & cpp_class) != cpp_class)
229     return LLDB_INVALID_ADDRESS;
230
231   // Calculate offset to VTable pointer
232   lldb::offset_t vbtable_ptr_offset =
233       vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity()
234                                : 0;
235
236   if (ptr_or_ref) {
237     // We have a pointer / ref to object, so read
238     // VTable pointer from process memory
239
240     if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad)
241       return LLDB_INVALID_ADDRESS;
242
243     auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
244     if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS)
245       return LLDB_INVALID_ADDRESS;
246
247     vbtable_ptr_addr += vbtable_ptr_offset;
248
249     Status err;
250     return process.ReadPointerFromMemory(vbtable_ptr_addr, err);
251   }
252
253   // We have an object already read from process memory,
254   // so just extract VTable pointer from it
255
256   DataExtractor data;
257   Status err;
258   auto size = valobj.GetData(data, err);
259   if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size)
260     return LLDB_INVALID_ADDRESS;
261
262   return data.GetPointer(&vbtable_ptr_offset);
263 }
264
265 static int64_t ReadVBaseOffsetFromVTable(Process &process,
266                                          VTableContextBase &vtable_ctx,
267                                          lldb::addr_t vtable_ptr,
268                                          const CXXRecordDecl *cxx_record_decl,
269                                          const CXXRecordDecl *base_class_decl) {
270   if (vtable_ctx.isMicrosoft()) {
271     clang::MicrosoftVTableContext &msoft_vtable_ctx =
272         static_cast<clang::MicrosoftVTableContext &>(vtable_ctx);
273
274     // Get the index into the virtual base table. The
275     // index is the index in uint32_t from vbtable_ptr
276     const unsigned vbtable_index =
277         msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl);
278     const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4;
279     Status err;
280     return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX,
281                                                err);
282   }
283
284   clang::ItaniumVTableContext &itanium_vtable_ctx =
285       static_cast<clang::ItaniumVTableContext &>(vtable_ctx);
286
287   clang::CharUnits base_offset_offset =
288       itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl,
289                                                     base_class_decl);
290   const lldb::addr_t base_offset_addr =
291       vtable_ptr + base_offset_offset.getQuantity();
292   const uint32_t base_offset_size = process.GetAddressByteSize();
293   Status err;
294   return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size,
295                                              INT64_MAX, err);
296 }
297
298 static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx,
299                               ValueObject &valobj,
300                               const ASTRecordLayout &record_layout,
301                               const CXXRecordDecl *cxx_record_decl,
302                               const CXXRecordDecl *base_class_decl,
303                               int32_t &bit_offset) {
304   ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
305   Process *process = exe_ctx.GetProcessPtr();
306   if (!process)
307     return false;
308
309   lldb::addr_t vtable_ptr =
310       GetVTableAddress(*process, vtable_ctx, valobj, record_layout);
311   if (vtable_ptr == LLDB_INVALID_ADDRESS)
312     return false;
313
314   auto base_offset = ReadVBaseOffsetFromVTable(
315       *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl);
316   if (base_offset == INT64_MAX)
317     return false;
318
319   bit_offset = base_offset * 8;
320
321   return true;
322 }
323
324 typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, ClangASTContext *>
325     ClangASTMap;
326
327 static ClangASTMap &GetASTMap() {
328   static ClangASTMap *g_map_ptr = nullptr;
329   static llvm::once_flag g_once_flag;
330   llvm::call_once(g_once_flag, []() {
331     g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
332   });
333   return *g_map_ptr;
334 }
335
336 bool ClangASTContext::IsOperator(const char *name,
337                                  clang::OverloadedOperatorKind &op_kind) {
338   if (name == nullptr || name[0] == '\0')
339     return false;
340
341 #define OPERATOR_PREFIX "operator"
342 #define OPERATOR_PREFIX_LENGTH (sizeof(OPERATOR_PREFIX) - 1)
343
344   const char *post_op_name = nullptr;
345
346   bool no_space = true;
347
348   if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
349     return false;
350
351   post_op_name = name + OPERATOR_PREFIX_LENGTH;
352
353   if (post_op_name[0] == ' ') {
354     post_op_name++;
355     no_space = false;
356   }
357
358 #undef OPERATOR_PREFIX
359 #undef OPERATOR_PREFIX_LENGTH
360
361   // This is an operator, set the overloaded operator kind to invalid in case
362   // this is a conversion operator...
363   op_kind = clang::NUM_OVERLOADED_OPERATORS;
364
365   switch (post_op_name[0]) {
366   default:
367     if (no_space)
368       return false;
369     break;
370   case 'n':
371     if (no_space)
372       return false;
373     if (strcmp(post_op_name, "new") == 0)
374       op_kind = clang::OO_New;
375     else if (strcmp(post_op_name, "new[]") == 0)
376       op_kind = clang::OO_Array_New;
377     break;
378
379   case 'd':
380     if (no_space)
381       return false;
382     if (strcmp(post_op_name, "delete") == 0)
383       op_kind = clang::OO_Delete;
384     else if (strcmp(post_op_name, "delete[]") == 0)
385       op_kind = clang::OO_Array_Delete;
386     break;
387
388   case '+':
389     if (post_op_name[1] == '\0')
390       op_kind = clang::OO_Plus;
391     else if (post_op_name[2] == '\0') {
392       if (post_op_name[1] == '=')
393         op_kind = clang::OO_PlusEqual;
394       else if (post_op_name[1] == '+')
395         op_kind = clang::OO_PlusPlus;
396     }
397     break;
398
399   case '-':
400     if (post_op_name[1] == '\0')
401       op_kind = clang::OO_Minus;
402     else if (post_op_name[2] == '\0') {
403       switch (post_op_name[1]) {
404       case '=':
405         op_kind = clang::OO_MinusEqual;
406         break;
407       case '-':
408         op_kind = clang::OO_MinusMinus;
409         break;
410       case '>':
411         op_kind = clang::OO_Arrow;
412         break;
413       }
414     } else if (post_op_name[3] == '\0') {
415       if (post_op_name[2] == '*')
416         op_kind = clang::OO_ArrowStar;
417       break;
418     }
419     break;
420
421   case '*':
422     if (post_op_name[1] == '\0')
423       op_kind = clang::OO_Star;
424     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
425       op_kind = clang::OO_StarEqual;
426     break;
427
428   case '/':
429     if (post_op_name[1] == '\0')
430       op_kind = clang::OO_Slash;
431     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
432       op_kind = clang::OO_SlashEqual;
433     break;
434
435   case '%':
436     if (post_op_name[1] == '\0')
437       op_kind = clang::OO_Percent;
438     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
439       op_kind = clang::OO_PercentEqual;
440     break;
441
442   case '^':
443     if (post_op_name[1] == '\0')
444       op_kind = clang::OO_Caret;
445     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
446       op_kind = clang::OO_CaretEqual;
447     break;
448
449   case '&':
450     if (post_op_name[1] == '\0')
451       op_kind = clang::OO_Amp;
452     else if (post_op_name[2] == '\0') {
453       switch (post_op_name[1]) {
454       case '=':
455         op_kind = clang::OO_AmpEqual;
456         break;
457       case '&':
458         op_kind = clang::OO_AmpAmp;
459         break;
460       }
461     }
462     break;
463
464   case '|':
465     if (post_op_name[1] == '\0')
466       op_kind = clang::OO_Pipe;
467     else if (post_op_name[2] == '\0') {
468       switch (post_op_name[1]) {
469       case '=':
470         op_kind = clang::OO_PipeEqual;
471         break;
472       case '|':
473         op_kind = clang::OO_PipePipe;
474         break;
475       }
476     }
477     break;
478
479   case '~':
480     if (post_op_name[1] == '\0')
481       op_kind = clang::OO_Tilde;
482     break;
483
484   case '!':
485     if (post_op_name[1] == '\0')
486       op_kind = clang::OO_Exclaim;
487     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
488       op_kind = clang::OO_ExclaimEqual;
489     break;
490
491   case '=':
492     if (post_op_name[1] == '\0')
493       op_kind = clang::OO_Equal;
494     else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
495       op_kind = clang::OO_EqualEqual;
496     break;
497
498   case '<':
499     if (post_op_name[1] == '\0')
500       op_kind = clang::OO_Less;
501     else if (post_op_name[2] == '\0') {
502       switch (post_op_name[1]) {
503       case '<':
504         op_kind = clang::OO_LessLess;
505         break;
506       case '=':
507         op_kind = clang::OO_LessEqual;
508         break;
509       }
510     } else if (post_op_name[3] == '\0') {
511       if (post_op_name[2] == '=')
512         op_kind = clang::OO_LessLessEqual;
513     }
514     break;
515
516   case '>':
517     if (post_op_name[1] == '\0')
518       op_kind = clang::OO_Greater;
519     else if (post_op_name[2] == '\0') {
520       switch (post_op_name[1]) {
521       case '>':
522         op_kind = clang::OO_GreaterGreater;
523         break;
524       case '=':
525         op_kind = clang::OO_GreaterEqual;
526         break;
527       }
528     } else if (post_op_name[1] == '>' && post_op_name[2] == '=' &&
529                post_op_name[3] == '\0') {
530       op_kind = clang::OO_GreaterGreaterEqual;
531     }
532     break;
533
534   case ',':
535     if (post_op_name[1] == '\0')
536       op_kind = clang::OO_Comma;
537     break;
538
539   case '(':
540     if (post_op_name[1] == ')' && post_op_name[2] == '\0')
541       op_kind = clang::OO_Call;
542     break;
543
544   case '[':
545     if (post_op_name[1] == ']' && post_op_name[2] == '\0')
546       op_kind = clang::OO_Subscript;
547     break;
548   }
549
550   return true;
551 }
552
553 clang::AccessSpecifier
554 ClangASTContext::ConvertAccessTypeToAccessSpecifier(AccessType access) {
555   switch (access) {
556   default:
557     break;
558   case eAccessNone:
559     return AS_none;
560   case eAccessPublic:
561     return AS_public;
562   case eAccessPrivate:
563     return AS_private;
564   case eAccessProtected:
565     return AS_protected;
566   }
567   return AS_none;
568 }
569
570 static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) {
571   // FIXME: Cleanup per-file based stuff.
572
573   // Set some properties which depend solely on the input kind; it would be
574   // nice to move these to the language standard, and have the driver resolve
575   // the input kind + language standard.
576   if (IK.getLanguage() == InputKind::Asm) {
577     Opts.AsmPreprocessor = 1;
578   } else if (IK.isObjectiveC()) {
579     Opts.ObjC = 1;
580   }
581
582   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
583
584   if (LangStd == LangStandard::lang_unspecified) {
585     // Based on the base language, pick one.
586     switch (IK.getLanguage()) {
587     case InputKind::Unknown:
588     case InputKind::LLVM_IR:
589     case InputKind::RenderScript:
590       llvm_unreachable("Invalid input kind!");
591     case InputKind::OpenCL:
592       LangStd = LangStandard::lang_opencl10;
593       break;
594     case InputKind::CUDA:
595       LangStd = LangStandard::lang_cuda;
596       break;
597     case InputKind::Asm:
598     case InputKind::C:
599     case InputKind::ObjC:
600       LangStd = LangStandard::lang_gnu99;
601       break;
602     case InputKind::CXX:
603     case InputKind::ObjCXX:
604       LangStd = LangStandard::lang_gnucxx98;
605       break;
606     case InputKind::HIP:
607       LangStd = LangStandard::lang_hip;
608       break;
609     }
610   }
611
612   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
613   Opts.LineComment = Std.hasLineComments();
614   Opts.C99 = Std.isC99();
615   Opts.CPlusPlus = Std.isCPlusPlus();
616   Opts.CPlusPlus11 = Std.isCPlusPlus11();
617   Opts.Digraphs = Std.hasDigraphs();
618   Opts.GNUMode = Std.isGNUMode();
619   Opts.GNUInline = !Std.isC99();
620   Opts.HexFloats = Std.hasHexFloats();
621   Opts.ImplicitInt = Std.hasImplicitInt();
622
623   Opts.WChar = true;
624
625   // OpenCL has some additional defaults.
626   if (LangStd == LangStandard::lang_opencl10) {
627     Opts.OpenCL = 1;
628     Opts.AltiVec = 1;
629     Opts.CXXOperatorNames = 1;
630     Opts.LaxVectorConversions = 1;
631   }
632
633   // OpenCL and C++ both have bool, true, false keywords.
634   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
635
636   Opts.setValueVisibilityMode(DefaultVisibility);
637
638   // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
639   // specified, or -std is set to a conforming mode.
640   Opts.Trigraphs = !Opts.GNUMode;
641   Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
642   Opts.OptimizeSize = 0;
643
644   // FIXME: Eliminate this dependency.
645   //    unsigned Opt =
646   //    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
647   //    Opts.Optimize = Opt != 0;
648   unsigned Opt = 0;
649
650   // This is the __NO_INLINE__ define, which just depends on things like the
651   // optimization level and -fno-inline, not actually whether the backend has
652   // inlining enabled.
653   //
654   // FIXME: This is affected by other options (-fno-inline).
655   Opts.NoInlineDefine = !Opt;
656 }
657
658 ClangASTContext::ClangASTContext(const char *target_triple)
659     : TypeSystem(TypeSystem::eKindClang), m_target_triple(), m_ast_up(),
660       m_language_options_up(), m_source_manager_up(), m_diagnostics_engine_up(),
661       m_target_options_rp(), m_target_info_up(), m_identifier_table_up(),
662       m_selector_table_up(), m_builtins_up(), m_callback_tag_decl(nullptr),
663       m_callback_objc_decl(nullptr), m_callback_baton(nullptr),
664       m_pointer_byte_size(0), m_ast_owned(false) {
665   if (target_triple && target_triple[0])
666     SetTargetTriple(target_triple);
667 }
668
669 // Destructor
670 ClangASTContext::~ClangASTContext() { Finalize(); }
671
672 ConstString ClangASTContext::GetPluginNameStatic() {
673   return ConstString("clang");
674 }
675
676 ConstString ClangASTContext::GetPluginName() {
677   return ClangASTContext::GetPluginNameStatic();
678 }
679
680 uint32_t ClangASTContext::GetPluginVersion() { return 1; }
681
682 lldb::TypeSystemSP ClangASTContext::CreateInstance(lldb::LanguageType language,
683                                                    lldb_private::Module *module,
684                                                    Target *target) {
685   if (ClangASTContextSupportsLanguage(language)) {
686     ArchSpec arch;
687     if (module)
688       arch = module->GetArchitecture();
689     else if (target)
690       arch = target->GetArchitecture();
691
692     if (arch.IsValid()) {
693       ArchSpec fixed_arch = arch;
694       // LLVM wants this to be set to iOS or MacOSX; if we're working on
695       // a bare-boards type image, change the triple for llvm's benefit.
696       if (fixed_arch.GetTriple().getVendor() == llvm::Triple::Apple &&
697           fixed_arch.GetTriple().getOS() == llvm::Triple::UnknownOS) {
698         if (fixed_arch.GetTriple().getArch() == llvm::Triple::arm ||
699             fixed_arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
700             fixed_arch.GetTriple().getArch() == llvm::Triple::thumb) {
701           fixed_arch.GetTriple().setOS(llvm::Triple::IOS);
702         } else {
703           fixed_arch.GetTriple().setOS(llvm::Triple::MacOSX);
704         }
705       }
706
707       if (module) {
708         std::shared_ptr<ClangASTContext> ast_sp(new ClangASTContext);
709         if (ast_sp) {
710           ast_sp->SetArchitecture(fixed_arch);
711         }
712         return ast_sp;
713       } else if (target && target->IsValid()) {
714         std::shared_ptr<ClangASTContextForExpressions> ast_sp(
715             new ClangASTContextForExpressions(*target));
716         if (ast_sp) {
717           ast_sp->SetArchitecture(fixed_arch);
718           ast_sp->m_scratch_ast_source_up.reset(
719               new ClangASTSource(target->shared_from_this()));
720           lldbassert(ast_sp->getFileManager());
721           ast_sp->m_scratch_ast_source_up->InstallASTContext(
722               *ast_sp->getASTContext(), *ast_sp->getFileManager(), true);
723           llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
724               ast_sp->m_scratch_ast_source_up->CreateProxy());
725           ast_sp->SetExternalSource(proxy_ast_source);
726           return ast_sp;
727         }
728       }
729     }
730   }
731   return lldb::TypeSystemSP();
732 }
733
734 void ClangASTContext::EnumerateSupportedLanguages(
735     std::set<lldb::LanguageType> &languages_for_types,
736     std::set<lldb::LanguageType> &languages_for_expressions) {
737   static std::vector<lldb::LanguageType> s_supported_languages_for_types(
738       {lldb::eLanguageTypeC89, lldb::eLanguageTypeC, lldb::eLanguageTypeC11,
739        lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeC99,
740        lldb::eLanguageTypeObjC, lldb::eLanguageTypeObjC_plus_plus,
741        lldb::eLanguageTypeC_plus_plus_03, lldb::eLanguageTypeC_plus_plus_11,
742        lldb::eLanguageTypeC11, lldb::eLanguageTypeC_plus_plus_14});
743
744   static std::vector<lldb::LanguageType> s_supported_languages_for_expressions(
745       {lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC_plus_plus,
746        lldb::eLanguageTypeC_plus_plus_03, lldb::eLanguageTypeC_plus_plus_11,
747        lldb::eLanguageTypeC_plus_plus_14});
748
749   languages_for_types.insert(s_supported_languages_for_types.begin(),
750                              s_supported_languages_for_types.end());
751   languages_for_expressions.insert(
752       s_supported_languages_for_expressions.begin(),
753       s_supported_languages_for_expressions.end());
754 }
755
756 void ClangASTContext::Initialize() {
757   PluginManager::RegisterPlugin(GetPluginNameStatic(),
758                                 "clang base AST context plug-in",
759                                 CreateInstance, EnumerateSupportedLanguages);
760 }
761
762 void ClangASTContext::Terminate() {
763   PluginManager::UnregisterPlugin(CreateInstance);
764 }
765
766 void ClangASTContext::Finalize() {
767   if (m_ast_up) {
768     GetASTMap().Erase(m_ast_up.get());
769     if (!m_ast_owned)
770       m_ast_up.release();
771   }
772
773   m_builtins_up.reset();
774   m_selector_table_up.reset();
775   m_identifier_table_up.reset();
776   m_target_info_up.reset();
777   m_target_options_rp.reset();
778   m_diagnostics_engine_up.reset();
779   m_source_manager_up.reset();
780   m_language_options_up.reset();
781   m_ast_up.reset();
782   m_scratch_ast_source_up.reset();
783 }
784
785 void ClangASTContext::Clear() {
786   m_ast_up.reset();
787   m_language_options_up.reset();
788   m_source_manager_up.reset();
789   m_diagnostics_engine_up.reset();
790   m_target_options_rp.reset();
791   m_target_info_up.reset();
792   m_identifier_table_up.reset();
793   m_selector_table_up.reset();
794   m_builtins_up.reset();
795   m_pointer_byte_size = 0;
796 }
797
798 void ClangASTContext::setSema(Sema *s) {
799   // Ensure that the new sema actually belongs to our ASTContext.
800   assert(s == nullptr || &s->getASTContext() == m_ast_up.get());
801   m_sema = s;
802 }
803
804 const char *ClangASTContext::GetTargetTriple() {
805   return m_target_triple.c_str();
806 }
807
808 void ClangASTContext::SetTargetTriple(const char *target_triple) {
809   Clear();
810   m_target_triple.assign(target_triple);
811 }
812
813 void ClangASTContext::SetArchitecture(const ArchSpec &arch) {
814   SetTargetTriple(arch.GetTriple().str().c_str());
815 }
816
817 bool ClangASTContext::HasExternalSource() {
818   ASTContext *ast = getASTContext();
819   if (ast)
820     return ast->getExternalSource() != nullptr;
821   return false;
822 }
823
824 void ClangASTContext::SetExternalSource(
825     llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
826   ASTContext *ast = getASTContext();
827   if (ast) {
828     ast->setExternalSource(ast_source_up);
829     ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
830   }
831 }
832
833 void ClangASTContext::RemoveExternalSource() {
834   ASTContext *ast = getASTContext();
835
836   if (ast) {
837     llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_up;
838     ast->setExternalSource(empty_ast_source_up);
839     ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
840   }
841 }
842
843 void ClangASTContext::setASTContext(clang::ASTContext *ast_ctx) {
844   if (!m_ast_owned) {
845     m_ast_up.release();
846   }
847   m_ast_owned = false;
848   m_ast_up.reset(ast_ctx);
849   GetASTMap().Insert(ast_ctx, this);
850 }
851
852 ASTContext *ClangASTContext::getASTContext() {
853   if (m_ast_up == nullptr) {
854     m_ast_owned = true;
855     m_ast_up.reset(new ASTContext(*getLanguageOptions(), *getSourceManager(),
856                                   *getIdentifierTable(), *getSelectorTable(),
857                                   *getBuiltinContext()));
858
859     m_ast_up->getDiagnostics().setClient(getDiagnosticConsumer(), false);
860
861     // This can be NULL if we don't know anything about the architecture or if
862     // the target for an architecture isn't enabled in the llvm/clang that we
863     // built
864     TargetInfo *target_info = getTargetInfo();
865     if (target_info)
866       m_ast_up->InitBuiltinTypes(*target_info);
867
868     if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton) {
869       m_ast_up->getTranslationUnitDecl()->setHasExternalLexicalStorage();
870       // m_ast_up->getTranslationUnitDecl()->setHasExternalVisibleStorage();
871     }
872
873     GetASTMap().Insert(m_ast_up.get(), this);
874
875     llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
876         new ClangExternalASTSourceCallbacks(
877             ClangASTContext::CompleteTagDecl,
878             ClangASTContext::CompleteObjCInterfaceDecl, nullptr,
879             ClangASTContext::LayoutRecordType, this));
880     SetExternalSource(ast_source_up);
881   }
882   return m_ast_up.get();
883 }
884
885 ClangASTContext *ClangASTContext::GetASTContext(clang::ASTContext *ast) {
886   ClangASTContext *clang_ast = GetASTMap().Lookup(ast);
887   return clang_ast;
888 }
889
890 Builtin::Context *ClangASTContext::getBuiltinContext() {
891   if (m_builtins_up == nullptr)
892     m_builtins_up.reset(new Builtin::Context());
893   return m_builtins_up.get();
894 }
895
896 IdentifierTable *ClangASTContext::getIdentifierTable() {
897   if (m_identifier_table_up == nullptr)
898     m_identifier_table_up.reset(
899         new IdentifierTable(*ClangASTContext::getLanguageOptions(), nullptr));
900   return m_identifier_table_up.get();
901 }
902
903 LangOptions *ClangASTContext::getLanguageOptions() {
904   if (m_language_options_up == nullptr) {
905     m_language_options_up.reset(new LangOptions());
906     ParseLangArgs(*m_language_options_up, InputKind::ObjCXX, GetTargetTriple());
907     //        InitializeLangOptions(*m_language_options_up, InputKind::ObjCXX);
908   }
909   return m_language_options_up.get();
910 }
911
912 SelectorTable *ClangASTContext::getSelectorTable() {
913   if (m_selector_table_up == nullptr)
914     m_selector_table_up.reset(new SelectorTable());
915   return m_selector_table_up.get();
916 }
917
918 clang::FileManager *ClangASTContext::getFileManager() {
919   if (m_file_manager_up == nullptr) {
920     clang::FileSystemOptions file_system_options;
921     m_file_manager_up.reset(new clang::FileManager(
922         file_system_options, FileSystem::Instance().GetVirtualFileSystem()));
923   }
924   return m_file_manager_up.get();
925 }
926
927 clang::SourceManager *ClangASTContext::getSourceManager() {
928   if (m_source_manager_up == nullptr)
929     m_source_manager_up.reset(
930         new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
931   return m_source_manager_up.get();
932 }
933
934 clang::DiagnosticsEngine *ClangASTContext::getDiagnosticsEngine() {
935   if (m_diagnostics_engine_up == nullptr) {
936     llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
937     m_diagnostics_engine_up.reset(
938         new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
939   }
940   return m_diagnostics_engine_up.get();
941 }
942
943 clang::MangleContext *ClangASTContext::getMangleContext() {
944   if (m_mangle_ctx_up == nullptr)
945     m_mangle_ctx_up.reset(getASTContext()->createMangleContext());
946   return m_mangle_ctx_up.get();
947 }
948
949 class NullDiagnosticConsumer : public DiagnosticConsumer {
950 public:
951   NullDiagnosticConsumer() {
952     m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
953   }
954
955   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
956                         const clang::Diagnostic &info) override {
957     if (m_log) {
958       llvm::SmallVector<char, 32> diag_str(10);
959       info.FormatDiagnostic(diag_str);
960       diag_str.push_back('\0');
961       m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
962     }
963   }
964
965   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
966     return new NullDiagnosticConsumer();
967   }
968
969 private:
970   Log *m_log;
971 };
972
973 DiagnosticConsumer *ClangASTContext::getDiagnosticConsumer() {
974   if (m_diagnostic_consumer_up == nullptr)
975     m_diagnostic_consumer_up.reset(new NullDiagnosticConsumer);
976
977   return m_diagnostic_consumer_up.get();
978 }
979
980 std::shared_ptr<clang::TargetOptions> &ClangASTContext::getTargetOptions() {
981   if (m_target_options_rp == nullptr && !m_target_triple.empty()) {
982     m_target_options_rp = std::make_shared<clang::TargetOptions>();
983     if (m_target_options_rp != nullptr)
984       m_target_options_rp->Triple = m_target_triple;
985   }
986   return m_target_options_rp;
987 }
988
989 TargetInfo *ClangASTContext::getTargetInfo() {
990   // target_triple should be something like "x86_64-apple-macosx"
991   if (m_target_info_up == nullptr && !m_target_triple.empty())
992     m_target_info_up.reset(TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(),
993                                                         getTargetOptions()));
994   return m_target_info_up.get();
995 }
996
997 #pragma mark Basic Types
998
999 static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
1000                                           ASTContext *ast, QualType qual_type) {
1001   uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
1002   return qual_type_bit_size == bit_size;
1003 }
1004
1005 CompilerType
1006 ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
1007                                                      size_t bit_size) {
1008   return ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
1009       getASTContext(), encoding, bit_size);
1010 }
1011
1012 CompilerType ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
1013     ASTContext *ast, Encoding encoding, uint32_t bit_size) {
1014   if (!ast)
1015     return CompilerType();
1016   switch (encoding) {
1017   case eEncodingInvalid:
1018     if (QualTypeMatchesBitSize(bit_size, ast, ast->VoidPtrTy))
1019       return CompilerType(ast, ast->VoidPtrTy);
1020     break;
1021
1022   case eEncodingUint:
1023     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1024       return CompilerType(ast, ast->UnsignedCharTy);
1025     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1026       return CompilerType(ast, ast->UnsignedShortTy);
1027     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1028       return CompilerType(ast, ast->UnsignedIntTy);
1029     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
1030       return CompilerType(ast, ast->UnsignedLongTy);
1031     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
1032       return CompilerType(ast, ast->UnsignedLongLongTy);
1033     if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
1034       return CompilerType(ast, ast->UnsignedInt128Ty);
1035     break;
1036
1037   case eEncodingSint:
1038     if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
1039       return CompilerType(ast, ast->SignedCharTy);
1040     if (QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
1041       return CompilerType(ast, ast->ShortTy);
1042     if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
1043       return CompilerType(ast, ast->IntTy);
1044     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
1045       return CompilerType(ast, ast->LongTy);
1046     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
1047       return CompilerType(ast, ast->LongLongTy);
1048     if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
1049       return CompilerType(ast, ast->Int128Ty);
1050     break;
1051
1052   case eEncodingIEEE754:
1053     if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
1054       return CompilerType(ast, ast->FloatTy);
1055     if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
1056       return CompilerType(ast, ast->DoubleTy);
1057     if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
1058       return CompilerType(ast, ast->LongDoubleTy);
1059     if (QualTypeMatchesBitSize(bit_size, ast, ast->HalfTy))
1060       return CompilerType(ast, ast->HalfTy);
1061     break;
1062
1063   case eEncodingVector:
1064     // Sanity check that bit_size is a multiple of 8's.
1065     if (bit_size && !(bit_size & 0x7u))
1066       return CompilerType(
1067           ast, ast->getExtVectorType(ast->UnsignedCharTy, bit_size / 8));
1068     break;
1069   }
1070
1071   return CompilerType();
1072 }
1073
1074 lldb::BasicType
1075 ClangASTContext::GetBasicTypeEnumeration(ConstString name) {
1076   if (name) {
1077     typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
1078     static TypeNameToBasicTypeMap g_type_map;
1079     static llvm::once_flag g_once_flag;
1080     llvm::call_once(g_once_flag, []() {
1081       // "void"
1082       g_type_map.Append(ConstString("void"), eBasicTypeVoid);
1083
1084       // "char"
1085       g_type_map.Append(ConstString("char"), eBasicTypeChar);
1086       g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar);
1087       g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar);
1088       g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar);
1089       g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar);
1090       g_type_map.Append(ConstString("unsigned wchar_t"),
1091                         eBasicTypeUnsignedWChar);
1092       // "short"
1093       g_type_map.Append(ConstString("short"), eBasicTypeShort);
1094       g_type_map.Append(ConstString("short int"), eBasicTypeShort);
1095       g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort);
1096       g_type_map.Append(ConstString("unsigned short int"),
1097                         eBasicTypeUnsignedShort);
1098
1099       // "int"
1100       g_type_map.Append(ConstString("int"), eBasicTypeInt);
1101       g_type_map.Append(ConstString("signed int"), eBasicTypeInt);
1102       g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt);
1103       g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt);
1104
1105       // "long"
1106       g_type_map.Append(ConstString("long"), eBasicTypeLong);
1107       g_type_map.Append(ConstString("long int"), eBasicTypeLong);
1108       g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong);
1109       g_type_map.Append(ConstString("unsigned long int"),
1110                         eBasicTypeUnsignedLong);
1111
1112       // "long long"
1113       g_type_map.Append(ConstString("long long"), eBasicTypeLongLong);
1114       g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong);
1115       g_type_map.Append(ConstString("unsigned long long"),
1116                         eBasicTypeUnsignedLongLong);
1117       g_type_map.Append(ConstString("unsigned long long int"),
1118                         eBasicTypeUnsignedLongLong);
1119
1120       // "int128"
1121       g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128);
1122       g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128);
1123
1124       // Miscellaneous
1125       g_type_map.Append(ConstString("bool"), eBasicTypeBool);
1126       g_type_map.Append(ConstString("float"), eBasicTypeFloat);
1127       g_type_map.Append(ConstString("double"), eBasicTypeDouble);
1128       g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble);
1129       g_type_map.Append(ConstString("id"), eBasicTypeObjCID);
1130       g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel);
1131       g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr);
1132       g_type_map.Sort();
1133     });
1134
1135     return g_type_map.Find(name, eBasicTypeInvalid);
1136   }
1137   return eBasicTypeInvalid;
1138 }
1139
1140 CompilerType ClangASTContext::GetBasicType(ASTContext *ast,
1141                                            ConstString name) {
1142   if (ast) {
1143     lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration(name);
1144     return ClangASTContext::GetBasicType(ast, basic_type);
1145   }
1146   return CompilerType();
1147 }
1148
1149 uint32_t ClangASTContext::GetPointerByteSize() {
1150   if (m_pointer_byte_size == 0)
1151     if (auto size = GetBasicType(lldb::eBasicTypeVoid)
1152                         .GetPointerType()
1153                         .GetByteSize(nullptr))
1154       m_pointer_byte_size = *size;
1155   return m_pointer_byte_size;
1156 }
1157
1158 CompilerType ClangASTContext::GetBasicType(lldb::BasicType basic_type) {
1159   return GetBasicType(getASTContext(), basic_type);
1160 }
1161
1162 CompilerType ClangASTContext::GetBasicType(ASTContext *ast,
1163                                            lldb::BasicType basic_type) {
1164   if (!ast)
1165     return CompilerType();
1166   lldb::opaque_compiler_type_t clang_type =
1167       GetOpaqueCompilerType(ast, basic_type);
1168
1169   if (clang_type)
1170     return CompilerType(GetASTContext(ast), clang_type);
1171   return CompilerType();
1172 }
1173
1174 CompilerType ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize(
1175     const char *type_name, uint32_t dw_ate, uint32_t bit_size) {
1176   ASTContext *ast = getASTContext();
1177
1178 #define streq(a, b) strcmp(a, b) == 0
1179   assert(ast != nullptr);
1180   if (ast) {
1181     switch (dw_ate) {
1182     default:
1183       break;
1184
1185     case DW_ATE_address:
1186       if (QualTypeMatchesBitSize(bit_size, ast, ast->VoidPtrTy))
1187         return CompilerType(ast, ast->VoidPtrTy);
1188       break;
1189
1190     case DW_ATE_boolean:
1191       if (QualTypeMatchesBitSize(bit_size, ast, ast->BoolTy))
1192         return CompilerType(ast, ast->BoolTy);
1193       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1194         return CompilerType(ast, ast->UnsignedCharTy);
1195       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1196         return CompilerType(ast, ast->UnsignedShortTy);
1197       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1198         return CompilerType(ast, ast->UnsignedIntTy);
1199       break;
1200
1201     case DW_ATE_lo_user:
1202       // This has been seen to mean DW_AT_complex_integer
1203       if (type_name) {
1204         if (::strstr(type_name, "complex")) {
1205           CompilerType complex_int_clang_type =
1206               GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
1207                                                        bit_size / 2);
1208           return CompilerType(ast, ast->getComplexType(ClangUtil::GetQualType(
1209                                        complex_int_clang_type)));
1210         }
1211       }
1212       break;
1213
1214     case DW_ATE_complex_float:
1215       if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatComplexTy))
1216         return CompilerType(ast, ast->FloatComplexTy);
1217       else if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleComplexTy))
1218         return CompilerType(ast, ast->DoubleComplexTy);
1219       else if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleComplexTy))
1220         return CompilerType(ast, ast->LongDoubleComplexTy);
1221       else {
1222         CompilerType complex_float_clang_type =
1223             GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
1224                                                      bit_size / 2);
1225         return CompilerType(ast, ast->getComplexType(ClangUtil::GetQualType(
1226                                      complex_float_clang_type)));
1227       }
1228       break;
1229
1230     case DW_ATE_float:
1231       if (streq(type_name, "float") &&
1232           QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
1233         return CompilerType(ast, ast->FloatTy);
1234       if (streq(type_name, "double") &&
1235           QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
1236         return CompilerType(ast, ast->DoubleTy);
1237       if (streq(type_name, "long double") &&
1238           QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
1239         return CompilerType(ast, ast->LongDoubleTy);
1240       // Fall back to not requiring a name match
1241       if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
1242         return CompilerType(ast, ast->FloatTy);
1243       if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
1244         return CompilerType(ast, ast->DoubleTy);
1245       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
1246         return CompilerType(ast, ast->LongDoubleTy);
1247       if (QualTypeMatchesBitSize(bit_size, ast, ast->HalfTy))
1248         return CompilerType(ast, ast->HalfTy);
1249       break;
1250
1251     case DW_ATE_signed:
1252       if (type_name) {
1253         if (streq(type_name, "wchar_t") &&
1254             QualTypeMatchesBitSize(bit_size, ast, ast->WCharTy) &&
1255             (getTargetInfo() &&
1256              TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1257           return CompilerType(ast, ast->WCharTy);
1258         if (streq(type_name, "void") &&
1259             QualTypeMatchesBitSize(bit_size, ast, ast->VoidTy))
1260           return CompilerType(ast, ast->VoidTy);
1261         if (strstr(type_name, "long long") &&
1262             QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
1263           return CompilerType(ast, ast->LongLongTy);
1264         if (strstr(type_name, "long") &&
1265             QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
1266           return CompilerType(ast, ast->LongTy);
1267         if (strstr(type_name, "short") &&
1268             QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
1269           return CompilerType(ast, ast->ShortTy);
1270         if (strstr(type_name, "char")) {
1271           if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1272             return CompilerType(ast, ast->CharTy);
1273           if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
1274             return CompilerType(ast, ast->SignedCharTy);
1275         }
1276         if (strstr(type_name, "int")) {
1277           if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
1278             return CompilerType(ast, ast->IntTy);
1279           if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
1280             return CompilerType(ast, ast->Int128Ty);
1281         }
1282       }
1283       // We weren't able to match up a type name, just search by size
1284       if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1285         return CompilerType(ast, ast->CharTy);
1286       if (QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
1287         return CompilerType(ast, ast->ShortTy);
1288       if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
1289         return CompilerType(ast, ast->IntTy);
1290       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
1291         return CompilerType(ast, ast->LongTy);
1292       if (QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
1293         return CompilerType(ast, ast->LongLongTy);
1294       if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
1295         return CompilerType(ast, ast->Int128Ty);
1296       break;
1297
1298     case DW_ATE_signed_char:
1299       if (ast->getLangOpts().CharIsSigned && type_name &&
1300           streq(type_name, "char")) {
1301         if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1302           return CompilerType(ast, ast->CharTy);
1303       }
1304       if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
1305         return CompilerType(ast, ast->SignedCharTy);
1306       break;
1307
1308     case DW_ATE_unsigned:
1309       if (type_name) {
1310         if (streq(type_name, "wchar_t")) {
1311           if (QualTypeMatchesBitSize(bit_size, ast, ast->WCharTy)) {
1312             if (!(getTargetInfo() &&
1313                   TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1314               return CompilerType(ast, ast->WCharTy);
1315           }
1316         }
1317         if (strstr(type_name, "long long")) {
1318           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
1319             return CompilerType(ast, ast->UnsignedLongLongTy);
1320         } else if (strstr(type_name, "long")) {
1321           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
1322             return CompilerType(ast, ast->UnsignedLongTy);
1323         } else if (strstr(type_name, "short")) {
1324           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1325             return CompilerType(ast, ast->UnsignedShortTy);
1326         } else if (strstr(type_name, "char")) {
1327           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1328             return CompilerType(ast, ast->UnsignedCharTy);
1329         } else if (strstr(type_name, "int")) {
1330           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1331             return CompilerType(ast, ast->UnsignedIntTy);
1332           if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
1333             return CompilerType(ast, ast->UnsignedInt128Ty);
1334         }
1335       }
1336       // We weren't able to match up a type name, just search by size
1337       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1338         return CompilerType(ast, ast->UnsignedCharTy);
1339       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1340         return CompilerType(ast, ast->UnsignedShortTy);
1341       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
1342         return CompilerType(ast, ast->UnsignedIntTy);
1343       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
1344         return CompilerType(ast, ast->UnsignedLongTy);
1345       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
1346         return CompilerType(ast, ast->UnsignedLongLongTy);
1347       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
1348         return CompilerType(ast, ast->UnsignedInt128Ty);
1349       break;
1350
1351     case DW_ATE_unsigned_char:
1352       if (!ast->getLangOpts().CharIsSigned && type_name &&
1353           streq(type_name, "char")) {
1354         if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
1355           return CompilerType(ast, ast->CharTy);
1356       }
1357       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
1358         return CompilerType(ast, ast->UnsignedCharTy);
1359       if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
1360         return CompilerType(ast, ast->UnsignedShortTy);
1361       break;
1362
1363     case DW_ATE_imaginary_float:
1364       break;
1365
1366     case DW_ATE_UTF:
1367       if (type_name) {
1368         if (streq(type_name, "char16_t")) {
1369           return CompilerType(ast, ast->Char16Ty);
1370         } else if (streq(type_name, "char32_t")) {
1371           return CompilerType(ast, ast->Char32Ty);
1372         }
1373       }
1374       break;
1375     }
1376   }
1377   // This assert should fire for anything that we don't catch above so we know
1378   // to fix any issues we run into.
1379   if (type_name) {
1380     Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
1381                                            "DW_TAG_base_type '%s' encoded with "
1382                                            "DW_ATE = 0x%x, bit_size = %u\n",
1383                     type_name, dw_ate, bit_size);
1384   } else {
1385     Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
1386                                            "DW_TAG_base_type encoded with "
1387                                            "DW_ATE = 0x%x, bit_size = %u\n",
1388                     dw_ate, bit_size);
1389   }
1390   return CompilerType();
1391 }
1392
1393 CompilerType ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast) {
1394   if (ast)
1395     return CompilerType(ast, ast->UnknownAnyTy);
1396   return CompilerType();
1397 }
1398
1399 CompilerType ClangASTContext::GetCStringType(bool is_const) {
1400   ASTContext *ast = getASTContext();
1401   QualType char_type(ast->CharTy);
1402
1403   if (is_const)
1404     char_type.addConst();
1405
1406   return CompilerType(ast, ast->getPointerType(char_type));
1407 }
1408
1409 clang::DeclContext *
1410 ClangASTContext::GetTranslationUnitDecl(clang::ASTContext *ast) {
1411   return ast->getTranslationUnitDecl();
1412 }
1413
1414 clang::Decl *ClangASTContext::CopyDecl(ASTContext *dst_ast, ASTContext *src_ast,
1415                                        clang::Decl *source_decl) {
1416   FileSystemOptions file_system_options;
1417   FileManager file_manager(file_system_options);
1418   ASTImporter importer(*dst_ast, file_manager, *src_ast, file_manager, false);
1419
1420   if (llvm::Expected<clang::Decl *> ret_or_error =
1421           importer.Import(source_decl)) {
1422     return *ret_or_error;
1423   } else {
1424     Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
1425     LLDB_LOG_ERROR(log, ret_or_error.takeError(), "Couldn't import decl: {0}");
1426     return nullptr;
1427   }
1428 }
1429
1430 bool ClangASTContext::AreTypesSame(CompilerType type1, CompilerType type2,
1431                                    bool ignore_qualifiers) {
1432   ClangASTContext *ast =
1433       llvm::dyn_cast_or_null<ClangASTContext>(type1.GetTypeSystem());
1434   if (!ast || ast != type2.GetTypeSystem())
1435     return false;
1436
1437   if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1438     return true;
1439
1440   QualType type1_qual = ClangUtil::GetQualType(type1);
1441   QualType type2_qual = ClangUtil::GetQualType(type2);
1442
1443   if (ignore_qualifiers) {
1444     type1_qual = type1_qual.getUnqualifiedType();
1445     type2_qual = type2_qual.getUnqualifiedType();
1446   }
1447
1448   return ast->getASTContext()->hasSameType(type1_qual, type2_qual);
1449 }
1450
1451 CompilerType ClangASTContext::GetTypeForDecl(clang::NamedDecl *decl) {
1452   if (clang::ObjCInterfaceDecl *interface_decl =
1453           llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1454     return GetTypeForDecl(interface_decl);
1455   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1456     return GetTypeForDecl(tag_decl);
1457   return CompilerType();
1458 }
1459
1460 CompilerType ClangASTContext::GetTypeForDecl(TagDecl *decl) {
1461   // No need to call the getASTContext() accessor (which can create the AST if
1462   // it isn't created yet, because we can't have created a decl in this
1463   // AST if our AST didn't already exist...
1464   ASTContext *ast = &decl->getASTContext();
1465   if (ast)
1466     return CompilerType(ast, ast->getTagDeclType(decl));
1467   return CompilerType();
1468 }
1469
1470 CompilerType ClangASTContext::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1471   // No need to call the getASTContext() accessor (which can create the AST if
1472   // it isn't created yet, because we can't have created a decl in this
1473   // AST if our AST didn't already exist...
1474   ASTContext *ast = &decl->getASTContext();
1475   if (ast)
1476     return CompilerType(ast, ast->getObjCInterfaceType(decl));
1477   return CompilerType();
1478 }
1479
1480 #pragma mark Structure, Unions, Classes
1481
1482 CompilerType ClangASTContext::CreateRecordType(DeclContext *decl_ctx,
1483                                                AccessType access_type,
1484                                                const char *name, int kind,
1485                                                LanguageType language,
1486                                                ClangASTMetadata *metadata) {
1487   ASTContext *ast = getASTContext();
1488   assert(ast != nullptr);
1489
1490   if (decl_ctx == nullptr)
1491     decl_ctx = ast->getTranslationUnitDecl();
1492
1493   if (language == eLanguageTypeObjC ||
1494       language == eLanguageTypeObjC_plus_plus) {
1495     bool isForwardDecl = true;
1496     bool isInternal = false;
1497     return CreateObjCClass(name, decl_ctx, isForwardDecl, isInternal, metadata);
1498   }
1499
1500   // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1501   // we will need to update this code. I was told to currently always use the
1502   // CXXRecordDecl class since we often don't know from debug information if
1503   // something is struct or a class, so we default to always use the more
1504   // complete definition just in case.
1505
1506   bool is_anonymous = (!name) || (!name[0]);
1507
1508   CXXRecordDecl *decl = CXXRecordDecl::Create(
1509       *ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(),
1510       SourceLocation(), is_anonymous ? nullptr : &ast->Idents.get(name));
1511
1512   if (is_anonymous)
1513     decl->setAnonymousStructOrUnion(true);
1514
1515   if (decl) {
1516     if (metadata)
1517       SetMetadata(ast, decl, *metadata);
1518
1519     if (access_type != eAccessNone)
1520       decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1521
1522     if (decl_ctx)
1523       decl_ctx->addDecl(decl);
1524
1525     return CompilerType(ast, ast->getTagDeclType(decl));
1526   }
1527   return CompilerType();
1528 }
1529
1530 namespace {
1531   bool IsValueParam(const clang::TemplateArgument &argument) {
1532     return argument.getKind() == TemplateArgument::Integral;
1533   }
1534 }
1535
1536 static TemplateParameterList *CreateTemplateParameterList(
1537     ASTContext *ast,
1538     const ClangASTContext::TemplateParameterInfos &template_param_infos,
1539     llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1540   const bool parameter_pack = false;
1541   const bool is_typename = false;
1542   const unsigned depth = 0;
1543   const size_t num_template_params = template_param_infos.args.size();
1544   DeclContext *const decl_context =
1545       ast->getTranslationUnitDecl(); // Is this the right decl context?,
1546   for (size_t i = 0; i < num_template_params; ++i) {
1547     const char *name = template_param_infos.names[i];
1548
1549     IdentifierInfo *identifier_info = nullptr;
1550     if (name && name[0])
1551       identifier_info = &ast->Idents.get(name);
1552     if (IsValueParam(template_param_infos.args[i])) {
1553       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1554           *ast, decl_context,
1555           SourceLocation(), SourceLocation(), depth, i, identifier_info,
1556           template_param_infos.args[i].getIntegralType(), parameter_pack,
1557           nullptr));
1558
1559     } else {
1560       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1561           *ast, decl_context,
1562           SourceLocation(), SourceLocation(), depth, i, identifier_info,
1563           is_typename, parameter_pack));
1564     }
1565   }
1566
1567   if (template_param_infos.packed_args) {
1568     IdentifierInfo *identifier_info = nullptr;
1569     if (template_param_infos.pack_name && template_param_infos.pack_name[0])
1570       identifier_info = &ast->Idents.get(template_param_infos.pack_name);
1571     const bool parameter_pack_true = true;
1572
1573     if (!template_param_infos.packed_args->args.empty() &&
1574         IsValueParam(template_param_infos.packed_args->args[0])) {
1575       template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1576           *ast, decl_context, SourceLocation(), SourceLocation(), depth,
1577           num_template_params, identifier_info,
1578           template_param_infos.packed_args->args[0].getIntegralType(),
1579           parameter_pack_true, nullptr));
1580     } else {
1581       template_param_decls.push_back(TemplateTypeParmDecl::Create(
1582           *ast, decl_context, SourceLocation(), SourceLocation(), depth,
1583           num_template_params, identifier_info, is_typename,
1584           parameter_pack_true));
1585     }
1586   }
1587   clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1588   TemplateParameterList *template_param_list = TemplateParameterList::Create(
1589       *ast, SourceLocation(), SourceLocation(), template_param_decls,
1590       SourceLocation(), requires_clause);
1591   return template_param_list;
1592 }
1593
1594 clang::FunctionTemplateDecl *ClangASTContext::CreateFunctionTemplateDecl(
1595     clang::DeclContext *decl_ctx, clang::FunctionDecl *func_decl,
1596     const char *name, const TemplateParameterInfos &template_param_infos) {
1597   //    /// Create a function template node.
1598   ASTContext *ast = getASTContext();
1599
1600   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1601
1602   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1603       ast, template_param_infos, template_param_decls);
1604   FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create(
1605       *ast, decl_ctx, func_decl->getLocation(), func_decl->getDeclName(),
1606       template_param_list, func_decl);
1607
1608   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1609        i < template_param_decl_count; ++i) {
1610     // TODO: verify which decl context we should put template_param_decls into..
1611     template_param_decls[i]->setDeclContext(func_decl);
1612   }
1613
1614   return func_tmpl_decl;
1615 }
1616
1617 void ClangASTContext::CreateFunctionTemplateSpecializationInfo(
1618     FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1619     const TemplateParameterInfos &infos) {
1620   TemplateArgumentList *template_args_ptr =
1621       TemplateArgumentList::CreateCopy(func_decl->getASTContext(), infos.args);
1622
1623   func_decl->setFunctionTemplateSpecialization(func_tmpl_decl,
1624                                                template_args_ptr, nullptr);
1625 }
1626
1627 ClassTemplateDecl *ClangASTContext::CreateClassTemplateDecl(
1628     DeclContext *decl_ctx, lldb::AccessType access_type, const char *class_name,
1629     int kind, const TemplateParameterInfos &template_param_infos) {
1630   ASTContext *ast = getASTContext();
1631
1632   ClassTemplateDecl *class_template_decl = nullptr;
1633   if (decl_ctx == nullptr)
1634     decl_ctx = ast->getTranslationUnitDecl();
1635
1636   IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1637   DeclarationName decl_name(&identifier_info);
1638
1639   clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1640
1641   for (NamedDecl *decl : result) {
1642     class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1643     if (class_template_decl)
1644       return class_template_decl;
1645   }
1646
1647   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1648
1649   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1650       ast, template_param_infos, template_param_decls);
1651
1652   CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create(
1653       *ast, (TagDecl::TagKind)kind,
1654       decl_ctx, // What decl context do we use here? TU? The actual decl
1655                 // context?
1656       SourceLocation(), SourceLocation(), &identifier_info);
1657
1658   for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1659        i < template_param_decl_count; ++i) {
1660     template_param_decls[i]->setDeclContext(template_cxx_decl);
1661   }
1662
1663   // With templated classes, we say that a class is templated with
1664   // specializations, but that the bare class has no functions.
1665   // template_cxx_decl->startDefinition();
1666   // template_cxx_decl->completeDefinition();
1667
1668   class_template_decl = ClassTemplateDecl::Create(
1669       *ast,
1670       decl_ctx, // What decl context do we use here? TU? The actual decl
1671                 // context?
1672       SourceLocation(), decl_name, template_param_list, template_cxx_decl);
1673   template_cxx_decl->setDescribedClassTemplate(class_template_decl);
1674
1675   if (class_template_decl) {
1676     if (access_type != eAccessNone)
1677       class_template_decl->setAccess(
1678           ConvertAccessTypeToAccessSpecifier(access_type));
1679
1680     // if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1681     //    CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1682
1683     decl_ctx->addDecl(class_template_decl);
1684
1685 #ifdef LLDB_CONFIGURATION_DEBUG
1686     VerifyDecl(class_template_decl);
1687 #endif
1688   }
1689
1690   return class_template_decl;
1691 }
1692
1693 TemplateTemplateParmDecl *
1694 ClangASTContext::CreateTemplateTemplateParmDecl(const char *template_name) {
1695   ASTContext *ast = getASTContext();
1696
1697   auto *decl_ctx = ast->getTranslationUnitDecl();
1698
1699   IdentifierInfo &identifier_info = ast->Idents.get(template_name);
1700   llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1701
1702   ClangASTContext::TemplateParameterInfos template_param_infos;
1703   TemplateParameterList *template_param_list = CreateTemplateParameterList(
1704       ast, template_param_infos, template_param_decls);
1705
1706   // LLDB needs to create those decls only to be able to display a
1707   // type that includes a template template argument. Only the name matters for
1708   // this purpose, so we use dummy values for the other characterisitcs of the
1709   // type.
1710   return TemplateTemplateParmDecl::Create(
1711       *ast, decl_ctx, SourceLocation(),
1712       /*Depth*/ 0, /*Position*/ 0,
1713       /*IsParameterPack*/ false, &identifier_info, template_param_list);
1714 }
1715
1716 ClassTemplateSpecializationDecl *
1717 ClangASTContext::CreateClassTemplateSpecializationDecl(
1718     DeclContext *decl_ctx, ClassTemplateDecl *class_template_decl, int kind,
1719     const TemplateParameterInfos &template_param_infos) {
1720   ASTContext *ast = getASTContext();
1721   llvm::SmallVector<clang::TemplateArgument, 2> args(
1722       template_param_infos.args.size() +
1723       (template_param_infos.packed_args ? 1 : 0));
1724   std::copy(template_param_infos.args.begin(), template_param_infos.args.end(),
1725             args.begin());
1726   if (template_param_infos.packed_args) {
1727     args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1728         *ast, template_param_infos.packed_args->args);
1729   }
1730   ClassTemplateSpecializationDecl *class_template_specialization_decl =
1731       ClassTemplateSpecializationDecl::Create(
1732           *ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(),
1733           SourceLocation(), class_template_decl, args,
1734           nullptr);
1735
1736   class_template_specialization_decl->setSpecializationKind(
1737       TSK_ExplicitSpecialization);
1738
1739   return class_template_specialization_decl;
1740 }
1741
1742 CompilerType ClangASTContext::CreateClassTemplateSpecializationType(
1743     ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1744   if (class_template_specialization_decl) {
1745     ASTContext *ast = getASTContext();
1746     if (ast)
1747       return CompilerType(
1748           ast, ast->getTagDeclType(class_template_specialization_decl));
1749   }
1750   return CompilerType();
1751 }
1752
1753 static inline bool check_op_param(bool is_method,
1754                                   clang::OverloadedOperatorKind op_kind,
1755                                   bool unary, bool binary,
1756                                   uint32_t num_params) {
1757   // Special-case call since it can take any number of operands
1758   if (op_kind == OO_Call)
1759     return true;
1760
1761   // The parameter count doesn't include "this"
1762   if (is_method)
1763     ++num_params;
1764   if (num_params == 1)
1765     return unary;
1766   if (num_params == 2)
1767     return binary;
1768   else
1769     return false;
1770 }
1771
1772 bool ClangASTContext::CheckOverloadedOperatorKindParameterCount(
1773     bool is_method, clang::OverloadedOperatorKind op_kind,
1774     uint32_t num_params) {
1775   switch (op_kind) {
1776   default:
1777     break;
1778   // C++ standard allows any number of arguments to new/delete
1779   case OO_New:
1780   case OO_Array_New:
1781   case OO_Delete:
1782   case OO_Array_Delete:
1783     return true;
1784   }
1785
1786 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
1787   case OO_##Name:                                                              \
1788     return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1789   switch (op_kind) {
1790 #include "clang/Basic/OperatorKinds.def"
1791   default:
1792     break;
1793   }
1794   return false;
1795 }
1796
1797 clang::AccessSpecifier
1798 ClangASTContext::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
1799                                        clang::AccessSpecifier rhs) {
1800   // Make the access equal to the stricter of the field and the nested field's
1801   // access
1802   if (lhs == AS_none || rhs == AS_none)
1803     return AS_none;
1804   if (lhs == AS_private || rhs == AS_private)
1805     return AS_private;
1806   if (lhs == AS_protected || rhs == AS_protected)
1807     return AS_protected;
1808   return AS_public;
1809 }
1810
1811 bool ClangASTContext::FieldIsBitfield(FieldDecl *field,
1812                                       uint32_t &bitfield_bit_size) {
1813   return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
1814 }
1815
1816 bool ClangASTContext::FieldIsBitfield(ASTContext *ast, FieldDecl *field,
1817                                       uint32_t &bitfield_bit_size) {
1818   if (ast == nullptr || field == nullptr)
1819     return false;
1820
1821   if (field->isBitField()) {
1822     Expr *bit_width_expr = field->getBitWidth();
1823     if (bit_width_expr) {
1824       llvm::APSInt bit_width_apsint;
1825       if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast)) {
1826         bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
1827         return true;
1828       }
1829     }
1830   }
1831   return false;
1832 }
1833
1834 bool ClangASTContext::RecordHasFields(const RecordDecl *record_decl) {
1835   if (record_decl == nullptr)
1836     return false;
1837
1838   if (!record_decl->field_empty())
1839     return true;
1840
1841   // No fields, lets check this is a CXX record and check the base classes
1842   const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1843   if (cxx_record_decl) {
1844     CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1845     for (base_class = cxx_record_decl->bases_begin(),
1846         base_class_end = cxx_record_decl->bases_end();
1847          base_class != base_class_end; ++base_class) {
1848       const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1849           base_class->getType()->getAs<RecordType>()->getDecl());
1850       if (RecordHasFields(base_class_decl))
1851         return true;
1852     }
1853   }
1854   return false;
1855 }
1856
1857 #pragma mark Objective-C Classes
1858
1859 CompilerType ClangASTContext::CreateObjCClass(const char *name,
1860                                               DeclContext *decl_ctx,
1861                                               bool isForwardDecl,
1862                                               bool isInternal,
1863                                               ClangASTMetadata *metadata) {
1864   ASTContext *ast = getASTContext();
1865   assert(ast != nullptr);
1866   assert(name && name[0]);
1867   if (decl_ctx == nullptr)
1868     decl_ctx = ast->getTranslationUnitDecl();
1869
1870   ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create(
1871       *ast, decl_ctx, SourceLocation(), &ast->Idents.get(name), nullptr,
1872       nullptr, SourceLocation(),
1873       /*isForwardDecl,*/
1874       isInternal);
1875
1876   if (decl && metadata)
1877     SetMetadata(ast, decl, *metadata);
1878
1879   return CompilerType(ast, ast->getObjCInterfaceType(decl));
1880 }
1881
1882 static inline bool BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1883   return !ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl());
1884 }
1885
1886 uint32_t
1887 ClangASTContext::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1888                                    bool omit_empty_base_classes) {
1889   uint32_t num_bases = 0;
1890   if (cxx_record_decl) {
1891     if (omit_empty_base_classes) {
1892       CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1893       for (base_class = cxx_record_decl->bases_begin(),
1894           base_class_end = cxx_record_decl->bases_end();
1895            base_class != base_class_end; ++base_class) {
1896         // Skip empty base classes
1897         if (omit_empty_base_classes) {
1898           if (BaseSpecifierIsEmpty(base_class))
1899             continue;
1900         }
1901         ++num_bases;
1902       }
1903     } else
1904       num_bases = cxx_record_decl->getNumBases();
1905   }
1906   return num_bases;
1907 }
1908
1909 #pragma mark Namespace Declarations
1910
1911 NamespaceDecl *ClangASTContext::GetUniqueNamespaceDeclaration(
1912     const char *name, DeclContext *decl_ctx, bool is_inline) {
1913   NamespaceDecl *namespace_decl = nullptr;
1914   ASTContext *ast = getASTContext();
1915   TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl();
1916   if (decl_ctx == nullptr)
1917     decl_ctx = translation_unit_decl;
1918
1919   if (name) {
1920     IdentifierInfo &identifier_info = ast->Idents.get(name);
1921     DeclarationName decl_name(&identifier_info);
1922     clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1923     for (NamedDecl *decl : result) {
1924       namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1925       if (namespace_decl)
1926         return namespace_decl;
1927     }
1928
1929     namespace_decl =
1930         NamespaceDecl::Create(*ast, decl_ctx, is_inline, SourceLocation(),
1931                               SourceLocation(), &identifier_info, nullptr);
1932
1933     decl_ctx->addDecl(namespace_decl);
1934   } else {
1935     if (decl_ctx == translation_unit_decl) {
1936       namespace_decl = translation_unit_decl->getAnonymousNamespace();
1937       if (namespace_decl)
1938         return namespace_decl;
1939
1940       namespace_decl =
1941           NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
1942                                 SourceLocation(), nullptr, nullptr);
1943       translation_unit_decl->setAnonymousNamespace(namespace_decl);
1944       translation_unit_decl->addDecl(namespace_decl);
1945       assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
1946     } else {
1947       NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1948       if (parent_namespace_decl) {
1949         namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1950         if (namespace_decl)
1951           return namespace_decl;
1952         namespace_decl =
1953             NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
1954                                   SourceLocation(), nullptr, nullptr);
1955         parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1956         parent_namespace_decl->addDecl(namespace_decl);
1957         assert(namespace_decl ==
1958                parent_namespace_decl->getAnonymousNamespace());
1959       } else {
1960         assert(false && "GetUniqueNamespaceDeclaration called with no name and "
1961                         "no namespace as decl_ctx");
1962       }
1963     }
1964   }
1965 #ifdef LLDB_CONFIGURATION_DEBUG
1966   VerifyDecl(namespace_decl);
1967 #endif
1968   return namespace_decl;
1969 }
1970
1971 NamespaceDecl *ClangASTContext::GetUniqueNamespaceDeclaration(
1972     clang::ASTContext *ast, const char *name, clang::DeclContext *decl_ctx,
1973     bool is_inline) {
1974   ClangASTContext *ast_ctx = ClangASTContext::GetASTContext(ast);
1975   if (ast_ctx == nullptr)
1976     return nullptr;
1977
1978   return ast_ctx->GetUniqueNamespaceDeclaration(name, decl_ctx, is_inline);
1979 }
1980
1981 clang::BlockDecl *
1982 ClangASTContext::CreateBlockDeclaration(clang::DeclContext *ctx) {
1983   if (ctx != nullptr) {
1984     clang::BlockDecl *decl = clang::BlockDecl::Create(*getASTContext(), ctx,
1985                                                       clang::SourceLocation());
1986     ctx->addDecl(decl);
1987     return decl;
1988   }
1989   return nullptr;
1990 }
1991
1992 clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1993                                         clang::DeclContext *right,
1994                                         clang::DeclContext *root) {
1995   if (root == nullptr)
1996     return nullptr;
1997
1998   std::set<clang::DeclContext *> path_left;
1999   for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
2000     path_left.insert(d);
2001
2002   for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
2003     if (path_left.find(d) != path_left.end())
2004       return d;
2005
2006   return nullptr;
2007 }
2008
2009 clang::UsingDirectiveDecl *ClangASTContext::CreateUsingDirectiveDeclaration(
2010     clang::DeclContext *decl_ctx, clang::NamespaceDecl *ns_decl) {
2011   if (decl_ctx != nullptr && ns_decl != nullptr) {
2012     clang::TranslationUnitDecl *translation_unit =
2013         (clang::TranslationUnitDecl *)GetTranslationUnitDecl(getASTContext());
2014     clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
2015         *getASTContext(), decl_ctx, clang::SourceLocation(),
2016         clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
2017         clang::SourceLocation(), ns_decl,
2018         FindLCABetweenDecls(decl_ctx, ns_decl, translation_unit));
2019     decl_ctx->addDecl(using_decl);
2020     return using_decl;
2021   }
2022   return nullptr;
2023 }
2024
2025 clang::UsingDecl *
2026 ClangASTContext::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
2027                                         clang::NamedDecl *target) {
2028   if (current_decl_ctx != nullptr && target != nullptr) {
2029     clang::UsingDecl *using_decl = clang::UsingDecl::Create(
2030         *getASTContext(), current_decl_ctx, clang::SourceLocation(),
2031         clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
2032     clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
2033         *getASTContext(), current_decl_ctx, clang::SourceLocation(), using_decl,
2034         target);
2035     using_decl->addShadowDecl(shadow_decl);
2036     current_decl_ctx->addDecl(using_decl);
2037     return using_decl;
2038   }
2039   return nullptr;
2040 }
2041
2042 clang::VarDecl *ClangASTContext::CreateVariableDeclaration(
2043     clang::DeclContext *decl_context, const char *name, clang::QualType type) {
2044   if (decl_context != nullptr) {
2045     clang::VarDecl *var_decl = clang::VarDecl::Create(
2046         *getASTContext(), decl_context, clang::SourceLocation(),
2047         clang::SourceLocation(),
2048         name && name[0] ? &getASTContext()->Idents.getOwn(name) : nullptr, type,
2049         nullptr, clang::SC_None);
2050     var_decl->setAccess(clang::AS_public);
2051     decl_context->addDecl(var_decl);
2052     return var_decl;
2053   }
2054   return nullptr;
2055 }
2056
2057 lldb::opaque_compiler_type_t
2058 ClangASTContext::GetOpaqueCompilerType(clang::ASTContext *ast,
2059                                        lldb::BasicType basic_type) {
2060   switch (basic_type) {
2061   case eBasicTypeVoid:
2062     return ast->VoidTy.getAsOpaquePtr();
2063   case eBasicTypeChar:
2064     return ast->CharTy.getAsOpaquePtr();
2065   case eBasicTypeSignedChar:
2066     return ast->SignedCharTy.getAsOpaquePtr();
2067   case eBasicTypeUnsignedChar:
2068     return ast->UnsignedCharTy.getAsOpaquePtr();
2069   case eBasicTypeWChar:
2070     return ast->getWCharType().getAsOpaquePtr();
2071   case eBasicTypeSignedWChar:
2072     return ast->getSignedWCharType().getAsOpaquePtr();
2073   case eBasicTypeUnsignedWChar:
2074     return ast->getUnsignedWCharType().getAsOpaquePtr();
2075   case eBasicTypeChar16:
2076     return ast->Char16Ty.getAsOpaquePtr();
2077   case eBasicTypeChar32:
2078     return ast->Char32Ty.getAsOpaquePtr();
2079   case eBasicTypeShort:
2080     return ast->ShortTy.getAsOpaquePtr();
2081   case eBasicTypeUnsignedShort:
2082     return ast->UnsignedShortTy.getAsOpaquePtr();
2083   case eBasicTypeInt:
2084     return ast->IntTy.getAsOpaquePtr();
2085   case eBasicTypeUnsignedInt:
2086     return ast->UnsignedIntTy.getAsOpaquePtr();
2087   case eBasicTypeLong:
2088     return ast->LongTy.getAsOpaquePtr();
2089   case eBasicTypeUnsignedLong:
2090     return ast->UnsignedLongTy.getAsOpaquePtr();
2091   case eBasicTypeLongLong:
2092     return ast->LongLongTy.getAsOpaquePtr();
2093   case eBasicTypeUnsignedLongLong:
2094     return ast->UnsignedLongLongTy.getAsOpaquePtr();
2095   case eBasicTypeInt128:
2096     return ast->Int128Ty.getAsOpaquePtr();
2097   case eBasicTypeUnsignedInt128:
2098     return ast->UnsignedInt128Ty.getAsOpaquePtr();
2099   case eBasicTypeBool:
2100     return ast->BoolTy.getAsOpaquePtr();
2101   case eBasicTypeHalf:
2102     return ast->HalfTy.getAsOpaquePtr();
2103   case eBasicTypeFloat:
2104     return ast->FloatTy.getAsOpaquePtr();
2105   case eBasicTypeDouble:
2106     return ast->DoubleTy.getAsOpaquePtr();
2107   case eBasicTypeLongDouble:
2108     return ast->LongDoubleTy.getAsOpaquePtr();
2109   case eBasicTypeFloatComplex:
2110     return ast->FloatComplexTy.getAsOpaquePtr();
2111   case eBasicTypeDoubleComplex:
2112     return ast->DoubleComplexTy.getAsOpaquePtr();
2113   case eBasicTypeLongDoubleComplex:
2114     return ast->LongDoubleComplexTy.getAsOpaquePtr();
2115   case eBasicTypeObjCID:
2116     return ast->getObjCIdType().getAsOpaquePtr();
2117   case eBasicTypeObjCClass:
2118     return ast->getObjCClassType().getAsOpaquePtr();
2119   case eBasicTypeObjCSel:
2120     return ast->getObjCSelType().getAsOpaquePtr();
2121   case eBasicTypeNullPtr:
2122     return ast->NullPtrTy.getAsOpaquePtr();
2123   default:
2124     return nullptr;
2125   }
2126 }
2127
2128 #pragma mark Function Types
2129
2130 clang::DeclarationName
2131 ClangASTContext::GetDeclarationName(const char *name,
2132                                     const CompilerType &function_clang_type) {
2133   if (!name || !name[0])
2134     return clang::DeclarationName();
2135
2136   clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
2137   if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
2138     return DeclarationName(&getASTContext()->Idents.get(
2139         name)); // Not operator, but a regular function.
2140
2141   // Check the number of operator parameters. Sometimes we have seen bad DWARF
2142   // that doesn't correctly describe operators and if we try to create a method
2143   // and add it to the class, clang will assert and crash, so we need to make
2144   // sure things are acceptable.
2145   clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
2146   const clang::FunctionProtoType *function_type =
2147       llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
2148   if (function_type == nullptr)
2149     return clang::DeclarationName();
2150
2151   const bool is_method = false;
2152   const unsigned int num_params = function_type->getNumParams();
2153   if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
2154           is_method, op_kind, num_params))
2155     return clang::DeclarationName();
2156
2157   return getASTContext()->DeclarationNames.getCXXOperatorName(op_kind);
2158 }
2159
2160 FunctionDecl *ClangASTContext::CreateFunctionDeclaration(
2161     DeclContext *decl_ctx, const char *name,
2162     const CompilerType &function_clang_type, int storage, bool is_inline) {
2163   FunctionDecl *func_decl = nullptr;
2164   ASTContext *ast = getASTContext();
2165   if (decl_ctx == nullptr)
2166     decl_ctx = ast->getTranslationUnitDecl();
2167
2168   const bool hasWrittenPrototype = true;
2169   const bool isConstexprSpecified = false;
2170
2171   clang::DeclarationName declarationName =
2172       GetDeclarationName(name, function_clang_type);
2173   func_decl = FunctionDecl::Create(
2174       *ast, decl_ctx, SourceLocation(), SourceLocation(), declarationName,
2175       ClangUtil::GetQualType(function_clang_type), nullptr,
2176       (clang::StorageClass)storage, is_inline, hasWrittenPrototype,
2177       isConstexprSpecified ? CSK_constexpr : CSK_unspecified);
2178   if (func_decl)
2179     decl_ctx->addDecl(func_decl);
2180
2181 #ifdef LLDB_CONFIGURATION_DEBUG
2182   VerifyDecl(func_decl);
2183 #endif
2184
2185   return func_decl;
2186 }
2187
2188 CompilerType ClangASTContext::CreateFunctionType(
2189     ASTContext *ast, const CompilerType &result_type, const CompilerType *args,
2190     unsigned num_args, bool is_variadic, unsigned type_quals,
2191     clang::CallingConv cc) {
2192   if (ast == nullptr)
2193     return CompilerType(); // invalid AST
2194
2195   if (!result_type || !ClangUtil::IsClangType(result_type))
2196     return CompilerType(); // invalid return type
2197
2198   std::vector<QualType> qual_type_args;
2199   if (num_args > 0 && args == nullptr)
2200     return CompilerType(); // invalid argument array passed in
2201
2202   // Verify that all arguments are valid and the right type
2203   for (unsigned i = 0; i < num_args; ++i) {
2204     if (args[i]) {
2205       // Make sure we have a clang type in args[i] and not a type from another
2206       // language whose name might match
2207       const bool is_clang_type = ClangUtil::IsClangType(args[i]);
2208       lldbassert(is_clang_type);
2209       if (is_clang_type)
2210         qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
2211       else
2212         return CompilerType(); //  invalid argument type (must be a clang type)
2213     } else
2214       return CompilerType(); // invalid argument type (empty)
2215   }
2216
2217   // TODO: Detect calling convention in DWARF?
2218   FunctionProtoType::ExtProtoInfo proto_info;
2219   proto_info.ExtInfo = cc;
2220   proto_info.Variadic = is_variadic;
2221   proto_info.ExceptionSpec = EST_None;
2222   proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals);
2223   proto_info.RefQualifier = RQ_None;
2224
2225   return CompilerType(ast,
2226                       ast->getFunctionType(ClangUtil::GetQualType(result_type),
2227                                            qual_type_args, proto_info));
2228 }
2229
2230 ParmVarDecl *ClangASTContext::CreateParameterDeclaration(
2231     clang::DeclContext *decl_ctx, const char *name,
2232     const CompilerType &param_type, int storage) {
2233   ASTContext *ast = getASTContext();
2234   assert(ast != nullptr);
2235   auto *decl =
2236       ParmVarDecl::Create(*ast, decl_ctx, SourceLocation(), SourceLocation(),
2237                           name && name[0] ? &ast->Idents.get(name) : nullptr,
2238                           ClangUtil::GetQualType(param_type), nullptr,
2239                           (clang::StorageClass)storage, nullptr);
2240   decl_ctx->addDecl(decl);
2241   return decl;
2242 }
2243
2244 void ClangASTContext::SetFunctionParameters(FunctionDecl *function_decl,
2245                                             ParmVarDecl **params,
2246                                             unsigned num_params) {
2247   if (function_decl)
2248     function_decl->setParams(ArrayRef<ParmVarDecl *>(params, num_params));
2249 }
2250
2251 CompilerType
2252 ClangASTContext::CreateBlockPointerType(const CompilerType &function_type) {
2253   QualType block_type = m_ast_up->getBlockPointerType(
2254       clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2255
2256   return CompilerType(this, block_type.getAsOpaquePtr());
2257 }
2258
2259 #pragma mark Array Types
2260
2261 CompilerType ClangASTContext::CreateArrayType(const CompilerType &element_type,
2262                                               size_t element_count,
2263                                               bool is_vector) {
2264   if (element_type.IsValid()) {
2265     ASTContext *ast = getASTContext();
2266     assert(ast != nullptr);
2267
2268     if (is_vector) {
2269       return CompilerType(
2270           ast, ast->getExtVectorType(ClangUtil::GetQualType(element_type),
2271                                      element_count));
2272     } else {
2273
2274       llvm::APInt ap_element_count(64, element_count);
2275       if (element_count == 0) {
2276         return CompilerType(ast, ast->getIncompleteArrayType(
2277                                      ClangUtil::GetQualType(element_type),
2278                                      clang::ArrayType::Normal, 0));
2279       } else {
2280         return CompilerType(
2281             ast, ast->getConstantArrayType(ClangUtil::GetQualType(element_type),
2282                                            ap_element_count,
2283                                            clang::ArrayType::Normal, 0));
2284       }
2285     }
2286   }
2287   return CompilerType();
2288 }
2289
2290 CompilerType ClangASTContext::CreateStructForIdentifier(
2291     ConstString type_name,
2292     const std::initializer_list<std::pair<const char *, CompilerType>>
2293         &type_fields,
2294     bool packed) {
2295   CompilerType type;
2296   if (!type_name.IsEmpty() &&
2297       (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2298           .IsValid()) {
2299     lldbassert(0 && "Trying to create a type for an existing name");
2300     return type;
2301   }
2302
2303   type = CreateRecordType(nullptr, lldb::eAccessPublic, type_name.GetCString(),
2304                           clang::TTK_Struct, lldb::eLanguageTypeC);
2305   StartTagDeclarationDefinition(type);
2306   for (const auto &field : type_fields)
2307     AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2308                          0);
2309   if (packed)
2310     SetIsPacked(type);
2311   CompleteTagDeclarationDefinition(type);
2312   return type;
2313 }
2314
2315 CompilerType ClangASTContext::GetOrCreateStructForIdentifier(
2316     ConstString type_name,
2317     const std::initializer_list<std::pair<const char *, CompilerType>>
2318         &type_fields,
2319     bool packed) {
2320   CompilerType type;
2321   if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2322     return type;
2323
2324   return CreateStructForIdentifier(type_name, type_fields, packed);
2325 }
2326
2327 #pragma mark Enumeration Types
2328
2329 CompilerType
2330 ClangASTContext::CreateEnumerationType(const char *name, DeclContext *decl_ctx,
2331                                        const Declaration &decl,
2332                                        const CompilerType &integer_clang_type,
2333                                        bool is_scoped) {
2334   // TODO: Do something intelligent with the Declaration object passed in
2335   // like maybe filling in the SourceLocation with it...
2336   ASTContext *ast = getASTContext();
2337
2338   // TODO: ask about these...
2339   //    const bool IsFixed = false;
2340
2341   EnumDecl *enum_decl = EnumDecl::Create(
2342       *ast, decl_ctx, SourceLocation(), SourceLocation(),
2343       name && name[0] ? &ast->Idents.get(name) : nullptr, nullptr,
2344       is_scoped, // IsScoped
2345       is_scoped, // IsScopedUsingClassTag
2346       false);    // IsFixed
2347
2348   if (enum_decl) {
2349     if (decl_ctx)
2350       decl_ctx->addDecl(enum_decl);
2351
2352     // TODO: check if we should be setting the promotion type too?
2353     enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2354
2355     enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2356
2357     return CompilerType(ast, ast->getTagDeclType(enum_decl));
2358   }
2359   return CompilerType();
2360 }
2361
2362 CompilerType ClangASTContext::GetIntTypeFromBitSize(clang::ASTContext *ast,
2363                                                     size_t bit_size,
2364                                                     bool is_signed) {
2365   if (ast) {
2366     if (is_signed) {
2367       if (bit_size == ast->getTypeSize(ast->SignedCharTy))
2368         return CompilerType(ast, ast->SignedCharTy);
2369
2370       if (bit_size == ast->getTypeSize(ast->ShortTy))
2371         return CompilerType(ast, ast->ShortTy);
2372
2373       if (bit_size == ast->getTypeSize(ast->IntTy))
2374         return CompilerType(ast, ast->IntTy);
2375
2376       if (bit_size == ast->getTypeSize(ast->LongTy))
2377         return CompilerType(ast, ast->LongTy);
2378
2379       if (bit_size == ast->getTypeSize(ast->LongLongTy))
2380         return CompilerType(ast, ast->LongLongTy);
2381
2382       if (bit_size == ast->getTypeSize(ast->Int128Ty))
2383         return CompilerType(ast, ast->Int128Ty);
2384     } else {
2385       if (bit_size == ast->getTypeSize(ast->UnsignedCharTy))
2386         return CompilerType(ast, ast->UnsignedCharTy);
2387
2388       if (bit_size == ast->getTypeSize(ast->UnsignedShortTy))
2389         return CompilerType(ast, ast->UnsignedShortTy);
2390
2391       if (bit_size == ast->getTypeSize(ast->UnsignedIntTy))
2392         return CompilerType(ast, ast->UnsignedIntTy);
2393
2394       if (bit_size == ast->getTypeSize(ast->UnsignedLongTy))
2395         return CompilerType(ast, ast->UnsignedLongTy);
2396
2397       if (bit_size == ast->getTypeSize(ast->UnsignedLongLongTy))
2398         return CompilerType(ast, ast->UnsignedLongLongTy);
2399
2400       if (bit_size == ast->getTypeSize(ast->UnsignedInt128Ty))
2401         return CompilerType(ast, ast->UnsignedInt128Ty);
2402     }
2403   }
2404   return CompilerType();
2405 }
2406
2407 CompilerType ClangASTContext::GetPointerSizedIntType(clang::ASTContext *ast,
2408                                                      bool is_signed) {
2409   if (ast)
2410     return GetIntTypeFromBitSize(ast, ast->getTypeSize(ast->VoidPtrTy),
2411                                  is_signed);
2412   return CompilerType();
2413 }
2414
2415 void ClangASTContext::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2416   if (decl_ctx) {
2417     DumpDeclContextHiearchy(decl_ctx->getParent());
2418
2419     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2420     if (named_decl) {
2421       printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2422              named_decl->getDeclName().getAsString().c_str());
2423     } else {
2424       printf("%20s\n", decl_ctx->getDeclKindName());
2425     }
2426   }
2427 }
2428
2429 void ClangASTContext::DumpDeclHiearchy(clang::Decl *decl) {
2430   if (decl == nullptr)
2431     return;
2432   DumpDeclContextHiearchy(decl->getDeclContext());
2433
2434   clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2435   if (record_decl) {
2436     printf("%20s: %s%s\n", decl->getDeclKindName(),
2437            record_decl->getDeclName().getAsString().c_str(),
2438            record_decl->isInjectedClassName() ? " (injected class name)" : "");
2439
2440   } else {
2441     clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2442     if (named_decl) {
2443       printf("%20s: %s\n", decl->getDeclKindName(),
2444              named_decl->getDeclName().getAsString().c_str());
2445     } else {
2446       printf("%20s\n", decl->getDeclKindName());
2447     }
2448   }
2449 }
2450
2451 bool ClangASTContext::DeclsAreEquivalent(clang::Decl *lhs_decl,
2452                                          clang::Decl *rhs_decl) {
2453   if (lhs_decl && rhs_decl) {
2454     // Make sure the decl kinds match first
2455     const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind();
2456     const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind();
2457
2458     if (lhs_decl_kind == rhs_decl_kind) {
2459       // Now check that the decl contexts kinds are all equivalent before we
2460       // have to check any names of the decl contexts...
2461       clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext();
2462       clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext();
2463       if (lhs_decl_ctx && rhs_decl_ctx) {
2464         while (true) {
2465           if (lhs_decl_ctx && rhs_decl_ctx) {
2466             const clang::Decl::Kind lhs_decl_ctx_kind =
2467                 lhs_decl_ctx->getDeclKind();
2468             const clang::Decl::Kind rhs_decl_ctx_kind =
2469                 rhs_decl_ctx->getDeclKind();
2470             if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) {
2471               lhs_decl_ctx = lhs_decl_ctx->getParent();
2472               rhs_decl_ctx = rhs_decl_ctx->getParent();
2473
2474               if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr)
2475                 break;
2476             } else
2477               return false;
2478           } else
2479             return false;
2480         }
2481
2482         // Now make sure the name of the decls match
2483         clang::NamedDecl *lhs_named_decl =
2484             llvm::dyn_cast<clang::NamedDecl>(lhs_decl);
2485         clang::NamedDecl *rhs_named_decl =
2486             llvm::dyn_cast<clang::NamedDecl>(rhs_decl);
2487         if (lhs_named_decl && rhs_named_decl) {
2488           clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName();
2489           clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName();
2490           if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2491             if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2492               return false;
2493           } else
2494             return false;
2495         } else
2496           return false;
2497
2498         // We know that the decl context kinds all match, so now we need to
2499         // make sure the names match as well
2500         lhs_decl_ctx = lhs_decl->getDeclContext();
2501         rhs_decl_ctx = rhs_decl->getDeclContext();
2502         while (true) {
2503           switch (lhs_decl_ctx->getDeclKind()) {
2504           case clang::Decl::TranslationUnit:
2505             // We don't care about the translation unit names
2506             return true;
2507           default: {
2508             clang::NamedDecl *lhs_named_decl =
2509                 llvm::dyn_cast<clang::NamedDecl>(lhs_decl_ctx);
2510             clang::NamedDecl *rhs_named_decl =
2511                 llvm::dyn_cast<clang::NamedDecl>(rhs_decl_ctx);
2512             if (lhs_named_decl && rhs_named_decl) {
2513               clang::DeclarationName lhs_decl_name =
2514                   lhs_named_decl->getDeclName();
2515               clang::DeclarationName rhs_decl_name =
2516                   rhs_named_decl->getDeclName();
2517               if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2518                 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2519                   return false;
2520               } else
2521                 return false;
2522             } else
2523               return false;
2524           } break;
2525           }
2526           lhs_decl_ctx = lhs_decl_ctx->getParent();
2527           rhs_decl_ctx = rhs_decl_ctx->getParent();
2528         }
2529       }
2530     }
2531   }
2532   return false;
2533 }
2534 bool ClangASTContext::GetCompleteDecl(clang::ASTContext *ast,
2535                                       clang::Decl *decl) {
2536   if (!decl)
2537     return false;
2538
2539   ExternalASTSource *ast_source = ast->getExternalSource();
2540
2541   if (!ast_source)
2542     return false;
2543
2544   if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2545     if (tag_decl->isCompleteDefinition())
2546       return true;
2547
2548     if (!tag_decl->hasExternalLexicalStorage())
2549       return false;
2550
2551     ast_source->CompleteType(tag_decl);
2552
2553     return !tag_decl->getTypeForDecl()->isIncompleteType();
2554   } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2555                  llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2556     if (objc_interface_decl->getDefinition())
2557       return true;
2558
2559     if (!objc_interface_decl->hasExternalLexicalStorage())
2560       return false;
2561
2562     ast_source->CompleteType(objc_interface_decl);
2563
2564     return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2565   } else {
2566     return false;
2567   }
2568 }
2569
2570 void ClangASTContext::SetMetadataAsUserID(const void *object,
2571                                           user_id_t user_id) {
2572   ClangASTMetadata meta_data;
2573   meta_data.SetUserID(user_id);
2574   SetMetadata(object, meta_data);
2575 }
2576
2577 void ClangASTContext::SetMetadata(clang::ASTContext *ast, const void *object,
2578                                   ClangASTMetadata &metadata) {
2579   ClangExternalASTSourceCommon *external_source =
2580       ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2581
2582   if (external_source)
2583     external_source->SetMetadata(object, metadata);
2584 }
2585
2586 ClangASTMetadata *ClangASTContext::GetMetadata(clang::ASTContext *ast,
2587                                                const void *object) {
2588   ClangExternalASTSourceCommon *external_source =
2589       ClangExternalASTSourceCommon::Lookup(ast->getExternalSource());
2590
2591   if (external_source && external_source->HasMetadata(object))
2592     return external_source->GetMetadata(object);
2593   else
2594     return nullptr;
2595 }
2596
2597 clang::DeclContext *
2598 ClangASTContext::GetAsDeclContext(clang::CXXMethodDecl *cxx_method_decl) {
2599   return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
2600 }
2601
2602 clang::DeclContext *
2603 ClangASTContext::GetAsDeclContext(clang::ObjCMethodDecl *objc_method_decl) {
2604   return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
2605 }
2606
2607 bool ClangASTContext::SetTagTypeKind(clang::QualType tag_qual_type,
2608                                      int kind) const {
2609   const clang::Type *clang_type = tag_qual_type.getTypePtr();
2610   if (clang_type) {
2611     const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(clang_type);
2612     if (tag_type) {
2613       clang::TagDecl *tag_decl =
2614           llvm::dyn_cast<clang::TagDecl>(tag_type->getDecl());
2615       if (tag_decl) {
2616         tag_decl->setTagKind((clang::TagDecl::TagKind)kind);
2617         return true;
2618       }
2619     }
2620   }
2621   return false;
2622 }
2623
2624 bool ClangASTContext::SetDefaultAccessForRecordFields(
2625     clang::RecordDecl *record_decl, int default_accessibility,
2626     int *assigned_accessibilities, size_t num_assigned_accessibilities) {
2627   if (record_decl) {
2628     uint32_t field_idx;
2629     clang::RecordDecl::field_iterator field, field_end;
2630     for (field = record_decl->field_begin(),
2631         field_end = record_decl->field_end(), field_idx = 0;
2632          field != field_end; ++field, ++field_idx) {
2633       // If no accessibility was assigned, assign the correct one
2634       if (field_idx < num_assigned_accessibilities &&
2635           assigned_accessibilities[field_idx] == clang::AS_none)
2636         field->setAccess((clang::AccessSpecifier)default_accessibility);
2637     }
2638     return true;
2639   }
2640   return false;
2641 }
2642
2643 clang::DeclContext *
2644 ClangASTContext::GetDeclContextForType(const CompilerType &type) {
2645   return GetDeclContextForType(ClangUtil::GetQualType(type));
2646 }
2647
2648 clang::DeclContext *
2649 ClangASTContext::GetDeclContextForType(clang::QualType type) {
2650   if (type.isNull())
2651     return nullptr;
2652
2653   clang::QualType qual_type = type.getCanonicalType();
2654   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2655   switch (type_class) {
2656   case clang::Type::ObjCInterface:
2657     return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2658         ->getInterface();
2659   case clang::Type::ObjCObjectPointer:
2660     return GetDeclContextForType(
2661         llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2662             ->getPointeeType());
2663   case clang::Type::Record:
2664     return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2665   case clang::Type::Enum:
2666     return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2667   case clang::Type::Typedef:
2668     return GetDeclContextForType(llvm::cast<clang::TypedefType>(qual_type)
2669                                      ->getDecl()
2670                                      ->getUnderlyingType());
2671   case clang::Type::Auto:
2672     return GetDeclContextForType(
2673         llvm::cast<clang::AutoType>(qual_type)->getDeducedType());
2674   case clang::Type::Elaborated:
2675     return GetDeclContextForType(
2676         llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType());
2677   case clang::Type::Paren:
2678     return GetDeclContextForType(
2679         llvm::cast<clang::ParenType>(qual_type)->desugar());
2680   default:
2681     break;
2682   }
2683   // No DeclContext in this type...
2684   return nullptr;
2685 }
2686
2687 static bool GetCompleteQualType(clang::ASTContext *ast,
2688                                 clang::QualType qual_type,
2689                                 bool allow_completion = true) {
2690   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2691   switch (type_class) {
2692   case clang::Type::ConstantArray:
2693   case clang::Type::IncompleteArray:
2694   case clang::Type::VariableArray: {
2695     const clang::ArrayType *array_type =
2696         llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2697
2698     if (array_type)
2699       return GetCompleteQualType(ast, array_type->getElementType(),
2700                                  allow_completion);
2701   } break;
2702   case clang::Type::Record: {
2703     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2704     if (cxx_record_decl) {
2705       if (cxx_record_decl->hasExternalLexicalStorage()) {
2706         const bool is_complete = cxx_record_decl->isCompleteDefinition();
2707         const bool fields_loaded =
2708             cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2709         if (is_complete && fields_loaded)
2710           return true;
2711
2712         if (!allow_completion)
2713           return false;
2714
2715         // Call the field_begin() accessor to for it to use the external source
2716         // to load the fields...
2717         clang::ExternalASTSource *external_ast_source =
2718             ast->getExternalSource();
2719         if (external_ast_source) {
2720           external_ast_source->CompleteType(cxx_record_decl);
2721           if (cxx_record_decl->isCompleteDefinition()) {
2722             cxx_record_decl->field_begin();
2723             cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2724           }
2725         }
2726       }
2727     }
2728     const clang::TagType *tag_type =
2729         llvm::cast<clang::TagType>(qual_type.getTypePtr());
2730     return !tag_type->isIncompleteType();
2731   } break;
2732
2733   case clang::Type::Enum: {
2734     const clang::TagType *tag_type =
2735         llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
2736     if (tag_type) {
2737       clang::TagDecl *tag_decl = tag_type->getDecl();
2738       if (tag_decl) {
2739         if (tag_decl->getDefinition())
2740           return true;
2741
2742         if (!allow_completion)
2743           return false;
2744
2745         if (tag_decl->hasExternalLexicalStorage()) {
2746           if (ast) {
2747             clang::ExternalASTSource *external_ast_source =
2748                 ast->getExternalSource();
2749             if (external_ast_source) {
2750               external_ast_source->CompleteType(tag_decl);
2751               return !tag_type->isIncompleteType();
2752             }
2753           }
2754         }
2755         return false;
2756       }
2757     }
2758
2759   } break;
2760   case clang::Type::ObjCObject:
2761   case clang::Type::ObjCInterface: {
2762     const clang::ObjCObjectType *objc_class_type =
2763         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
2764     if (objc_class_type) {
2765       clang::ObjCInterfaceDecl *class_interface_decl =
2766           objc_class_type->getInterface();
2767       // We currently can't complete objective C types through the newly added
2768       // ASTContext because it only supports TagDecl objects right now...
2769       if (class_interface_decl) {
2770         if (class_interface_decl->getDefinition())
2771           return true;
2772
2773         if (!allow_completion)
2774           return false;
2775
2776         if (class_interface_decl->hasExternalLexicalStorage()) {
2777           if (ast) {
2778             clang::ExternalASTSource *external_ast_source =
2779                 ast->getExternalSource();
2780             if (external_ast_source) {
2781               external_ast_source->CompleteType(class_interface_decl);
2782               return !objc_class_type->isIncompleteType();
2783             }
2784           }
2785         }
2786         return false;
2787       }
2788     }
2789   } break;
2790
2791   case clang::Type::Typedef:
2792     return GetCompleteQualType(ast, llvm::cast<clang::TypedefType>(qual_type)
2793                                         ->getDecl()
2794                                         ->getUnderlyingType(),
2795                                allow_completion);
2796
2797   case clang::Type::Auto:
2798     return GetCompleteQualType(
2799         ast, llvm::cast<clang::AutoType>(qual_type)->getDeducedType(),
2800         allow_completion);
2801
2802   case clang::Type::Elaborated:
2803     return GetCompleteQualType(
2804         ast, llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType(),
2805         allow_completion);
2806
2807   case clang::Type::Paren:
2808     return GetCompleteQualType(
2809         ast, llvm::cast<clang::ParenType>(qual_type)->desugar(),
2810         allow_completion);
2811
2812   case clang::Type::Attributed:
2813     return GetCompleteQualType(
2814         ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2815         allow_completion);
2816
2817   default:
2818     break;
2819   }
2820
2821   return true;
2822 }
2823
2824 static clang::ObjCIvarDecl::AccessControl
2825 ConvertAccessTypeToObjCIvarAccessControl(AccessType access) {
2826   switch (access) {
2827   case eAccessNone:
2828     return clang::ObjCIvarDecl::None;
2829   case eAccessPublic:
2830     return clang::ObjCIvarDecl::Public;
2831   case eAccessPrivate:
2832     return clang::ObjCIvarDecl::Private;
2833   case eAccessProtected:
2834     return clang::ObjCIvarDecl::Protected;
2835   case eAccessPackage:
2836     return clang::ObjCIvarDecl::Package;
2837   }
2838   return clang::ObjCIvarDecl::None;
2839 }
2840
2841 // Tests
2842
2843 bool ClangASTContext::IsAggregateType(lldb::opaque_compiler_type_t type) {
2844   clang::QualType qual_type(GetCanonicalQualType(type));
2845
2846   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2847   switch (type_class) {
2848   case clang::Type::IncompleteArray:
2849   case clang::Type::VariableArray:
2850   case clang::Type::ConstantArray:
2851   case clang::Type::ExtVector:
2852   case clang::Type::Vector:
2853   case clang::Type::Record:
2854   case clang::Type::ObjCObject:
2855   case clang::Type::ObjCInterface:
2856     return true;
2857   case clang::Type::Auto:
2858     return IsAggregateType(llvm::cast<clang::AutoType>(qual_type)
2859                                ->getDeducedType()
2860                                .getAsOpaquePtr());
2861   case clang::Type::Elaborated:
2862     return IsAggregateType(llvm::cast<clang::ElaboratedType>(qual_type)
2863                                ->getNamedType()
2864                                .getAsOpaquePtr());
2865   case clang::Type::Typedef:
2866     return IsAggregateType(llvm::cast<clang::TypedefType>(qual_type)
2867                                ->getDecl()
2868                                ->getUnderlyingType()
2869                                .getAsOpaquePtr());
2870   case clang::Type::Paren:
2871     return IsAggregateType(
2872         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
2873   default:
2874     break;
2875   }
2876   // The clang type does have a value
2877   return false;
2878 }
2879
2880 bool ClangASTContext::IsAnonymousType(lldb::opaque_compiler_type_t type) {
2881   clang::QualType qual_type(GetCanonicalQualType(type));
2882
2883   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2884   switch (type_class) {
2885   case clang::Type::Record: {
2886     if (const clang::RecordType *record_type =
2887             llvm::dyn_cast_or_null<clang::RecordType>(
2888                 qual_type.getTypePtrOrNull())) {
2889       if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2890         return record_decl->isAnonymousStructOrUnion();
2891       }
2892     }
2893     break;
2894   }
2895   case clang::Type::Auto:
2896     return IsAnonymousType(llvm::cast<clang::AutoType>(qual_type)
2897                                ->getDeducedType()
2898                                .getAsOpaquePtr());
2899   case clang::Type::Elaborated:
2900     return IsAnonymousType(llvm::cast<clang::ElaboratedType>(qual_type)
2901                                ->getNamedType()
2902                                .getAsOpaquePtr());
2903   case clang::Type::Typedef:
2904     return IsAnonymousType(llvm::cast<clang::TypedefType>(qual_type)
2905                                ->getDecl()
2906                                ->getUnderlyingType()
2907                                .getAsOpaquePtr());
2908   case clang::Type::Paren:
2909     return IsAnonymousType(
2910         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
2911   default:
2912     break;
2913   }
2914   // The clang type does have a value
2915   return false;
2916 }
2917
2918 bool ClangASTContext::IsArrayType(lldb::opaque_compiler_type_t type,
2919                                   CompilerType *element_type_ptr,
2920                                   uint64_t *size, bool *is_incomplete) {
2921   clang::QualType qual_type(GetCanonicalQualType(type));
2922
2923   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2924   switch (type_class) {
2925   default:
2926     break;
2927
2928   case clang::Type::ConstantArray:
2929     if (element_type_ptr)
2930       element_type_ptr->SetCompilerType(
2931           getASTContext(),
2932           llvm::cast<clang::ConstantArrayType>(qual_type)->getElementType());
2933     if (size)
2934       *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2935                   ->getSize()
2936                   .getLimitedValue(ULLONG_MAX);
2937     if (is_incomplete)
2938       *is_incomplete = false;
2939     return true;
2940
2941   case clang::Type::IncompleteArray:
2942     if (element_type_ptr)
2943       element_type_ptr->SetCompilerType(
2944           getASTContext(),
2945           llvm::cast<clang::IncompleteArrayType>(qual_type)->getElementType());
2946     if (size)
2947       *size = 0;
2948     if (is_incomplete)
2949       *is_incomplete = true;
2950     return true;
2951
2952   case clang::Type::VariableArray:
2953     if (element_type_ptr)
2954       element_type_ptr->SetCompilerType(
2955           getASTContext(),
2956           llvm::cast<clang::VariableArrayType>(qual_type)->getElementType());
2957     if (size)
2958       *size = 0;
2959     if (is_incomplete)
2960       *is_incomplete = false;
2961     return true;
2962
2963   case clang::Type::DependentSizedArray:
2964     if (element_type_ptr)
2965       element_type_ptr->SetCompilerType(
2966           getASTContext(), llvm::cast<clang::DependentSizedArrayType>(qual_type)
2967                                ->getElementType());
2968     if (size)
2969       *size = 0;
2970     if (is_incomplete)
2971       *is_incomplete = false;
2972     return true;
2973
2974   case clang::Type::Typedef:
2975     return IsArrayType(llvm::cast<clang::TypedefType>(qual_type)
2976                            ->getDecl()
2977                            ->getUnderlyingType()
2978                            .getAsOpaquePtr(),
2979                        element_type_ptr, size, is_incomplete);
2980   case clang::Type::Auto:
2981     return IsArrayType(llvm::cast<clang::AutoType>(qual_type)
2982                            ->getDeducedType()
2983                            .getAsOpaquePtr(),
2984                        element_type_ptr, size, is_incomplete);
2985   case clang::Type::Elaborated:
2986     return IsArrayType(llvm::cast<clang::ElaboratedType>(qual_type)
2987                            ->getNamedType()
2988                            .getAsOpaquePtr(),
2989                        element_type_ptr, size, is_incomplete);
2990   case clang::Type::Paren:
2991     return IsArrayType(
2992         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
2993         element_type_ptr, size, is_incomplete);
2994   }
2995   if (element_type_ptr)
2996     element_type_ptr->Clear();
2997   if (size)
2998     *size = 0;
2999   if (is_incomplete)
3000     *is_incomplete = false;
3001   return false;
3002 }
3003
3004 bool ClangASTContext::IsVectorType(lldb::opaque_compiler_type_t type,
3005                                    CompilerType *element_type, uint64_t *size) {
3006   clang::QualType qual_type(GetCanonicalQualType(type));
3007
3008   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3009   switch (type_class) {
3010   case clang::Type::Vector: {
3011     const clang::VectorType *vector_type =
3012         qual_type->getAs<clang::VectorType>();
3013     if (vector_type) {
3014       if (size)
3015         *size = vector_type->getNumElements();
3016       if (element_type)
3017         *element_type =
3018             CompilerType(getASTContext(), vector_type->getElementType());
3019     }
3020     return true;
3021   } break;
3022   case clang::Type::ExtVector: {
3023     const clang::ExtVectorType *ext_vector_type =
3024         qual_type->getAs<clang::ExtVectorType>();
3025     if (ext_vector_type) {
3026       if (size)
3027         *size = ext_vector_type->getNumElements();
3028       if (element_type)
3029         *element_type =
3030             CompilerType(getASTContext(), ext_vector_type->getElementType());
3031     }
3032     return true;
3033   }
3034   default:
3035     break;
3036   }
3037   return false;
3038 }
3039
3040 bool ClangASTContext::IsRuntimeGeneratedType(
3041     lldb::opaque_compiler_type_t type) {
3042   clang::DeclContext *decl_ctx = ClangASTContext::GetASTContext(getASTContext())
3043                                      ->GetDeclContextForType(GetQualType(type));
3044   if (!decl_ctx)
3045     return false;
3046
3047   if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
3048     return false;
3049
3050   clang::ObjCInterfaceDecl *result_iface_decl =
3051       llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
3052
3053   ClangASTMetadata *ast_metadata =
3054       ClangASTContext::GetMetadata(getASTContext(), result_iface_decl);
3055   if (!ast_metadata)
3056     return false;
3057   return (ast_metadata->GetISAPtr() != 0);
3058 }
3059
3060 bool ClangASTContext::IsCharType(lldb::opaque_compiler_type_t type) {
3061   return GetQualType(type).getUnqualifiedType()->isCharType();
3062 }
3063
3064 bool ClangASTContext::IsCompleteType(lldb::opaque_compiler_type_t type) {
3065   const bool allow_completion = false;
3066   return GetCompleteQualType(getASTContext(), GetQualType(type),
3067                              allow_completion);
3068 }
3069
3070 bool ClangASTContext::IsConst(lldb::opaque_compiler_type_t type) {
3071   return GetQualType(type).isConstQualified();
3072 }
3073
3074 bool ClangASTContext::IsCStringType(lldb::opaque_compiler_type_t type,
3075                                     uint32_t &length) {
3076   CompilerType pointee_or_element_clang_type;
3077   length = 0;
3078   Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
3079
3080   if (!pointee_or_element_clang_type.IsValid())
3081     return false;
3082
3083   if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
3084     if (pointee_or_element_clang_type.IsCharType()) {
3085       if (type_flags.Test(eTypeIsArray)) {
3086         // We know the size of the array and it could be a C string since it is
3087         // an array of characters
3088         length = llvm::cast<clang::ConstantArrayType>(
3089                      GetCanonicalQualType(type).getTypePtr())
3090                      ->getSize()
3091                      .getLimitedValue();
3092       }
3093       return true;
3094     }
3095   }
3096   return false;
3097 }
3098
3099 bool ClangASTContext::IsFunctionType(lldb::opaque_compiler_type_t type,
3100                                      bool *is_variadic_ptr) {
3101   if (type) {
3102     clang::QualType qual_type(GetCanonicalQualType(type));
3103
3104     if (qual_type->isFunctionType()) {
3105       if (is_variadic_ptr) {
3106         const clang::FunctionProtoType *function_proto_type =
3107             llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3108         if (function_proto_type)
3109           *is_variadic_ptr = function_proto_type->isVariadic();
3110         else
3111           *is_variadic_ptr = false;
3112       }
3113       return true;
3114     }
3115
3116     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3117     switch (type_class) {
3118     default:
3119       break;
3120     case clang::Type::Typedef:
3121       return IsFunctionType(llvm::cast<clang::TypedefType>(qual_type)
3122                                 ->getDecl()
3123                                 ->getUnderlyingType()
3124                                 .getAsOpaquePtr(),
3125                             nullptr);
3126     case clang::Type::Auto:
3127       return IsFunctionType(llvm::cast<clang::AutoType>(qual_type)
3128                                 ->getDeducedType()
3129                                 .getAsOpaquePtr(),
3130                             nullptr);
3131     case clang::Type::Elaborated:
3132       return IsFunctionType(llvm::cast<clang::ElaboratedType>(qual_type)
3133                                 ->getNamedType()
3134                                 .getAsOpaquePtr(),
3135                             nullptr);
3136     case clang::Type::Paren:
3137       return IsFunctionType(
3138           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3139           nullptr);
3140     case clang::Type::LValueReference:
3141     case clang::Type::RValueReference: {
3142       const clang::ReferenceType *reference_type =
3143           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3144       if (reference_type)
3145         return IsFunctionType(reference_type->getPointeeType().getAsOpaquePtr(),
3146                               nullptr);
3147     } break;
3148     }
3149   }
3150   return false;
3151 }
3152
3153 // Used to detect "Homogeneous Floating-point Aggregates"
3154 uint32_t
3155 ClangASTContext::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
3156                                         CompilerType *base_type_ptr) {
3157   if (!type)
3158     return 0;
3159
3160   clang::QualType qual_type(GetCanonicalQualType(type));
3161   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3162   switch (type_class) {
3163   case clang::Type::Record:
3164     if (GetCompleteType(type)) {
3165       const clang::CXXRecordDecl *cxx_record_decl =
3166           qual_type->getAsCXXRecordDecl();
3167       if (cxx_record_decl) {
3168         if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
3169           return 0;
3170       }
3171       const clang::RecordType *record_type =
3172           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3173       if (record_type) {
3174         const clang::RecordDecl *record_decl = record_type->getDecl();
3175         if (record_decl) {
3176           // We are looking for a structure that contains only floating point
3177           // types
3178           clang::RecordDecl::field_iterator field_pos,
3179               field_end = record_decl->field_end();
3180           uint32_t num_fields = 0;
3181           bool is_hva = false;
3182           bool is_hfa = false;
3183           clang::QualType base_qual_type;
3184           uint64_t base_bitwidth = 0;
3185           for (field_pos = record_decl->field_begin(); field_pos != field_end;
3186                ++field_pos) {
3187             clang::QualType field_qual_type = field_pos->getType();
3188             uint64_t field_bitwidth = getASTContext()->getTypeSize(qual_type);
3189             if (field_qual_type->isFloatingType()) {
3190               if (field_qual_type->isComplexType())
3191                 return 0;
3192               else {
3193                 if (num_fields == 0)
3194                   base_qual_type = field_qual_type;
3195                 else {
3196                   if (is_hva)
3197                     return 0;
3198                   is_hfa = true;
3199                   if (field_qual_type.getTypePtr() !=
3200                       base_qual_type.getTypePtr())
3201                     return 0;
3202                 }
3203               }
3204             } else if (field_qual_type->isVectorType() ||
3205                        field_qual_type->isExtVectorType()) {
3206               if (num_fields == 0) {
3207                 base_qual_type = field_qual_type;
3208                 base_bitwidth = field_bitwidth;
3209               } else {
3210                 if (is_hfa)
3211                   return 0;
3212                 is_hva = true;
3213                 if (base_bitwidth != field_bitwidth)
3214                   return 0;
3215                 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3216                   return 0;
3217               }
3218             } else
3219               return 0;
3220             ++num_fields;
3221           }
3222           if (base_type_ptr)
3223             *base_type_ptr = CompilerType(getASTContext(), base_qual_type);
3224           return num_fields;
3225         }
3226       }
3227     }
3228     break;
3229
3230   case clang::Type::Typedef:
3231     return IsHomogeneousAggregate(llvm::cast<clang::TypedefType>(qual_type)
3232                                       ->getDecl()
3233                                       ->getUnderlyingType()
3234                                       .getAsOpaquePtr(),
3235                                   base_type_ptr);
3236
3237   case clang::Type::Auto:
3238     return IsHomogeneousAggregate(llvm::cast<clang::AutoType>(qual_type)
3239                                       ->getDeducedType()
3240                                       .getAsOpaquePtr(),
3241                                   base_type_ptr);
3242
3243   case clang::Type::Elaborated:
3244     return IsHomogeneousAggregate(llvm::cast<clang::ElaboratedType>(qual_type)
3245                                       ->getNamedType()
3246                                       .getAsOpaquePtr(),
3247                                   base_type_ptr);
3248   default:
3249     break;
3250   }
3251   return 0;
3252 }
3253
3254 size_t ClangASTContext::GetNumberOfFunctionArguments(
3255     lldb::opaque_compiler_type_t type) {
3256   if (type) {
3257     clang::QualType qual_type(GetCanonicalQualType(type));
3258     const clang::FunctionProtoType *func =
3259         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3260     if (func)
3261       return func->getNumParams();
3262   }
3263   return 0;
3264 }
3265
3266 CompilerType
3267 ClangASTContext::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
3268                                             const size_t index) {
3269   if (type) {
3270     clang::QualType qual_type(GetQualType(type));
3271     const clang::FunctionProtoType *func =
3272         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3273     if (func) {
3274       if (index < func->getNumParams())
3275         return CompilerType(getASTContext(), func->getParamType(index));
3276     }
3277   }
3278   return CompilerType();
3279 }
3280
3281 bool ClangASTContext::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
3282   if (type) {
3283     clang::QualType qual_type(GetCanonicalQualType(type));
3284
3285     if (qual_type->isFunctionPointerType())
3286       return true;
3287
3288     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3289     switch (type_class) {
3290     default:
3291       break;
3292     case clang::Type::Typedef:
3293       return IsFunctionPointerType(llvm::cast<clang::TypedefType>(qual_type)
3294                                        ->getDecl()
3295                                        ->getUnderlyingType()
3296                                        .getAsOpaquePtr());
3297     case clang::Type::Auto:
3298       return IsFunctionPointerType(llvm::cast<clang::AutoType>(qual_type)
3299                                        ->getDeducedType()
3300                                        .getAsOpaquePtr());
3301     case clang::Type::Elaborated:
3302       return IsFunctionPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3303                                        ->getNamedType()
3304                                        .getAsOpaquePtr());
3305     case clang::Type::Paren:
3306       return IsFunctionPointerType(
3307           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
3308
3309     case clang::Type::LValueReference:
3310     case clang::Type::RValueReference: {
3311       const clang::ReferenceType *reference_type =
3312           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3313       if (reference_type)
3314         return IsFunctionPointerType(
3315             reference_type->getPointeeType().getAsOpaquePtr());
3316     } break;
3317     }
3318   }
3319   return false;
3320 }
3321
3322 bool ClangASTContext::IsBlockPointerType(
3323     lldb::opaque_compiler_type_t type,
3324     CompilerType *function_pointer_type_ptr) {
3325   if (type) {
3326     clang::QualType qual_type(GetCanonicalQualType(type));
3327
3328     if (qual_type->isBlockPointerType()) {
3329       if (function_pointer_type_ptr) {
3330         const clang::BlockPointerType *block_pointer_type =
3331             qual_type->getAs<clang::BlockPointerType>();
3332         QualType pointee_type = block_pointer_type->getPointeeType();
3333         QualType function_pointer_type = m_ast_up->getPointerType(pointee_type);
3334         *function_pointer_type_ptr =
3335             CompilerType(getASTContext(), function_pointer_type);
3336       }
3337       return true;
3338     }
3339
3340     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3341     switch (type_class) {
3342     default:
3343       break;
3344     case clang::Type::Typedef:
3345       return IsBlockPointerType(llvm::cast<clang::TypedefType>(qual_type)
3346                                     ->getDecl()
3347                                     ->getUnderlyingType()
3348                                     .getAsOpaquePtr(),
3349                                 function_pointer_type_ptr);
3350     case clang::Type::Auto:
3351       return IsBlockPointerType(llvm::cast<clang::AutoType>(qual_type)
3352                                     ->getDeducedType()
3353                                     .getAsOpaquePtr(),
3354                                 function_pointer_type_ptr);
3355     case clang::Type::Elaborated:
3356       return IsBlockPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3357                                     ->getNamedType()
3358                                     .getAsOpaquePtr(),
3359                                 function_pointer_type_ptr);
3360     case clang::Type::Paren:
3361       return IsBlockPointerType(
3362           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3363           function_pointer_type_ptr);
3364
3365     case clang::Type::LValueReference:
3366     case clang::Type::RValueReference: {
3367       const clang::ReferenceType *reference_type =
3368           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3369       if (reference_type)
3370         return IsBlockPointerType(
3371             reference_type->getPointeeType().getAsOpaquePtr(),
3372             function_pointer_type_ptr);
3373     } break;
3374     }
3375   }
3376   return false;
3377 }
3378
3379 bool ClangASTContext::IsIntegerType(lldb::opaque_compiler_type_t type,
3380                                     bool &is_signed) {
3381   if (!type)
3382     return false;
3383
3384   clang::QualType qual_type(GetCanonicalQualType(type));
3385   const clang::BuiltinType *builtin_type =
3386       llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3387
3388   if (builtin_type) {
3389     if (builtin_type->isInteger()) {
3390       is_signed = builtin_type->isSignedInteger();
3391       return true;
3392     }
3393   }
3394
3395   return false;
3396 }
3397
3398 bool ClangASTContext::IsEnumerationType(lldb::opaque_compiler_type_t type,
3399                                         bool &is_signed) {
3400   if (type) {
3401     const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3402         GetCanonicalQualType(type)->getCanonicalTypeInternal());
3403
3404     if (enum_type) {
3405       IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3406                     is_signed);
3407       return true;
3408     }
3409   }
3410
3411   return false;
3412 }
3413
3414 bool ClangASTContext::IsPointerType(lldb::opaque_compiler_type_t type,
3415                                     CompilerType *pointee_type) {
3416   if (type) {
3417     clang::QualType qual_type(GetCanonicalQualType(type));
3418     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3419     switch (type_class) {
3420     case clang::Type::Builtin:
3421       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3422       default:
3423         break;
3424       case clang::BuiltinType::ObjCId:
3425       case clang::BuiltinType::ObjCClass:
3426         return true;
3427       }
3428       return false;
3429     case clang::Type::ObjCObjectPointer:
3430       if (pointee_type)
3431         pointee_type->SetCompilerType(
3432             getASTContext(), llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3433                                  ->getPointeeType());
3434       return true;
3435     case clang::Type::BlockPointer:
3436       if (pointee_type)
3437         pointee_type->SetCompilerType(
3438             getASTContext(),
3439             llvm::cast<clang::BlockPointerType>(qual_type)->getPointeeType());
3440       return true;
3441     case clang::Type::Pointer:
3442       if (pointee_type)
3443         pointee_type->SetCompilerType(
3444             getASTContext(),
3445             llvm::cast<clang::PointerType>(qual_type)->getPointeeType());
3446       return true;
3447     case clang::Type::MemberPointer:
3448       if (pointee_type)
3449         pointee_type->SetCompilerType(
3450             getASTContext(),
3451             llvm::cast<clang::MemberPointerType>(qual_type)->getPointeeType());
3452       return true;
3453     case clang::Type::Typedef:
3454       return IsPointerType(llvm::cast<clang::TypedefType>(qual_type)
3455                                ->getDecl()
3456                                ->getUnderlyingType()
3457                                .getAsOpaquePtr(),
3458                            pointee_type);
3459     case clang::Type::Auto:
3460       return IsPointerType(llvm::cast<clang::AutoType>(qual_type)
3461                                ->getDeducedType()
3462                                .getAsOpaquePtr(),
3463                            pointee_type);
3464     case clang::Type::Elaborated:
3465       return IsPointerType(llvm::cast<clang::ElaboratedType>(qual_type)
3466                                ->getNamedType()
3467                                .getAsOpaquePtr(),
3468                            pointee_type);
3469     case clang::Type::Paren:
3470       return IsPointerType(
3471           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3472           pointee_type);
3473     default:
3474       break;
3475     }
3476   }
3477   if (pointee_type)
3478     pointee_type->Clear();
3479   return false;
3480 }
3481
3482 bool ClangASTContext::IsPointerOrReferenceType(
3483     lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3484   if (type) {
3485     clang::QualType qual_type(GetCanonicalQualType(type));
3486     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3487     switch (type_class) {
3488     case clang::Type::Builtin:
3489       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3490       default:
3491         break;
3492       case clang::BuiltinType::ObjCId:
3493       case clang::BuiltinType::ObjCClass:
3494         return true;
3495       }
3496       return false;
3497     case clang::Type::ObjCObjectPointer:
3498       if (pointee_type)
3499         pointee_type->SetCompilerType(
3500             getASTContext(), llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3501                                  ->getPointeeType());
3502       return true;
3503     case clang::Type::BlockPointer:
3504       if (pointee_type)
3505         pointee_type->SetCompilerType(
3506             getASTContext(),
3507             llvm::cast<clang::BlockPointerType>(qual_type)->getPointeeType());
3508       return true;
3509     case clang::Type::Pointer:
3510       if (pointee_type)
3511         pointee_type->SetCompilerType(
3512             getASTContext(),
3513             llvm::cast<clang::PointerType>(qual_type)->getPointeeType());
3514       return true;
3515     case clang::Type::MemberPointer:
3516       if (pointee_type)
3517         pointee_type->SetCompilerType(
3518             getASTContext(),
3519             llvm::cast<clang::MemberPointerType>(qual_type)->getPointeeType());
3520       return true;
3521     case clang::Type::LValueReference:
3522       if (pointee_type)
3523         pointee_type->SetCompilerType(
3524             getASTContext(),
3525             llvm::cast<clang::LValueReferenceType>(qual_type)->desugar());
3526       return true;
3527     case clang::Type::RValueReference:
3528       if (pointee_type)
3529         pointee_type->SetCompilerType(
3530             getASTContext(),
3531             llvm::cast<clang::RValueReferenceType>(qual_type)->desugar());
3532       return true;
3533     case clang::Type::Typedef:
3534       return IsPointerOrReferenceType(llvm::cast<clang::TypedefType>(qual_type)
3535                                           ->getDecl()
3536                                           ->getUnderlyingType()
3537                                           .getAsOpaquePtr(),
3538                                       pointee_type);
3539     case clang::Type::Auto:
3540       return IsPointerOrReferenceType(llvm::cast<clang::AutoType>(qual_type)
3541                                           ->getDeducedType()
3542                                           .getAsOpaquePtr(),
3543                                       pointee_type);
3544     case clang::Type::Elaborated:
3545       return IsPointerOrReferenceType(
3546           llvm::cast<clang::ElaboratedType>(qual_type)
3547               ->getNamedType()
3548               .getAsOpaquePtr(),
3549           pointee_type);
3550     case clang::Type::Paren:
3551       return IsPointerOrReferenceType(
3552           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3553           pointee_type);
3554     default:
3555       break;
3556     }
3557   }
3558   if (pointee_type)
3559     pointee_type->Clear();
3560   return false;
3561 }
3562
3563 bool ClangASTContext::IsReferenceType(lldb::opaque_compiler_type_t type,
3564                                       CompilerType *pointee_type,
3565                                       bool *is_rvalue) {
3566   if (type) {
3567     clang::QualType qual_type(GetCanonicalQualType(type));
3568     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3569
3570     switch (type_class) {
3571     case clang::Type::LValueReference:
3572       if (pointee_type)
3573         pointee_type->SetCompilerType(
3574             getASTContext(),
3575             llvm::cast<clang::LValueReferenceType>(qual_type)->desugar());
3576       if (is_rvalue)
3577         *is_rvalue = false;
3578       return true;
3579     case clang::Type::RValueReference:
3580       if (pointee_type)
3581         pointee_type->SetCompilerType(
3582             getASTContext(),
3583             llvm::cast<clang::RValueReferenceType>(qual_type)->desugar());
3584       if (is_rvalue)
3585         *is_rvalue = true;
3586       return true;
3587     case clang::Type::Typedef:
3588       return IsReferenceType(llvm::cast<clang::TypedefType>(qual_type)
3589                                  ->getDecl()
3590                                  ->getUnderlyingType()
3591                                  .getAsOpaquePtr(),
3592                              pointee_type, is_rvalue);
3593     case clang::Type::Auto:
3594       return IsReferenceType(llvm::cast<clang::AutoType>(qual_type)
3595                                  ->getDeducedType()
3596                                  .getAsOpaquePtr(),
3597                              pointee_type, is_rvalue);
3598     case clang::Type::Elaborated:
3599       return IsReferenceType(llvm::cast<clang::ElaboratedType>(qual_type)
3600                                  ->getNamedType()
3601                                  .getAsOpaquePtr(),
3602                              pointee_type, is_rvalue);
3603     case clang::Type::Paren:
3604       return IsReferenceType(
3605           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3606           pointee_type, is_rvalue);
3607
3608     default:
3609       break;
3610     }
3611   }
3612   if (pointee_type)
3613     pointee_type->Clear();
3614   return false;
3615 }
3616
3617 bool ClangASTContext::IsFloatingPointType(lldb::opaque_compiler_type_t type,
3618                                           uint32_t &count, bool &is_complex) {
3619   if (type) {
3620     clang::QualType qual_type(GetCanonicalQualType(type));
3621
3622     if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3623             qual_type->getCanonicalTypeInternal())) {
3624       clang::BuiltinType::Kind kind = BT->getKind();
3625       if (kind >= clang::BuiltinType::Float &&
3626           kind <= clang::BuiltinType::LongDouble) {
3627         count = 1;
3628         is_complex = false;
3629         return true;
3630       }
3631     } else if (const clang::ComplexType *CT =
3632                    llvm::dyn_cast<clang::ComplexType>(
3633                        qual_type->getCanonicalTypeInternal())) {
3634       if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3635                               is_complex)) {
3636         count = 2;
3637         is_complex = true;
3638         return true;
3639       }
3640     } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3641                    qual_type->getCanonicalTypeInternal())) {
3642       if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3643                               is_complex)) {
3644         count = VT->getNumElements();
3645         is_complex = false;
3646         return true;
3647       }
3648     }
3649   }
3650   count = 0;
3651   is_complex = false;
3652   return false;
3653 }
3654
3655 bool ClangASTContext::IsDefined(lldb::opaque_compiler_type_t type) {
3656   if (!type)
3657     return false;
3658
3659   clang::QualType qual_type(GetQualType(type));
3660   const clang::TagType *tag_type =
3661       llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3662   if (tag_type) {
3663     clang::TagDecl *tag_decl = tag_type->getDecl();
3664     if (tag_decl)
3665       return tag_decl->isCompleteDefinition();
3666     return false;
3667   } else {
3668     const clang::ObjCObjectType *objc_class_type =
3669         llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3670     if (objc_class_type) {
3671       clang::ObjCInterfaceDecl *class_interface_decl =
3672           objc_class_type->getInterface();
3673       if (class_interface_decl)
3674         return class_interface_decl->getDefinition() != nullptr;
3675       return false;
3676     }
3677   }
3678   return true;
3679 }
3680
3681 bool ClangASTContext::IsObjCClassType(const CompilerType &type) {
3682   if (type) {
3683     clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3684
3685     const clang::ObjCObjectPointerType *obj_pointer_type =
3686         llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3687
3688     if (obj_pointer_type)
3689       return obj_pointer_type->isObjCClassType();
3690   }
3691   return false;
3692 }
3693
3694 bool ClangASTContext::IsObjCObjectOrInterfaceType(const CompilerType &type) {
3695   if (ClangUtil::IsClangType(type))
3696     return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3697   return false;
3698 }
3699
3700 bool ClangASTContext::IsClassType(lldb::opaque_compiler_type_t type) {
3701   if (!type)
3702     return false;
3703   clang::QualType qual_type(GetCanonicalQualType(type));
3704   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3705   return (type_class == clang::Type::Record);
3706 }
3707
3708 bool ClangASTContext::IsEnumType(lldb::opaque_compiler_type_t type) {
3709   if (!type)
3710     return false;
3711   clang::QualType qual_type(GetCanonicalQualType(type));
3712   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3713   return (type_class == clang::Type::Enum);
3714 }
3715
3716 bool ClangASTContext::IsPolymorphicClass(lldb::opaque_compiler_type_t type) {
3717   if (type) {
3718     clang::QualType qual_type(GetCanonicalQualType(type));
3719     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3720     switch (type_class) {
3721     case clang::Type::Record:
3722       if (GetCompleteType(type)) {
3723         const clang::RecordType *record_type =
3724             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3725         const clang::RecordDecl *record_decl = record_type->getDecl();
3726         if (record_decl) {
3727           const clang::CXXRecordDecl *cxx_record_decl =
3728               llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3729           if (cxx_record_decl)
3730             return cxx_record_decl->isPolymorphic();
3731         }
3732       }
3733       break;
3734
3735     default:
3736       break;
3737     }
3738   }
3739   return false;
3740 }
3741
3742 bool ClangASTContext::IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
3743                                             CompilerType *dynamic_pointee_type,
3744                                             bool check_cplusplus,
3745                                             bool check_objc) {
3746   clang::QualType pointee_qual_type;
3747   if (type) {
3748     clang::QualType qual_type(GetCanonicalQualType(type));
3749     bool success = false;
3750     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3751     switch (type_class) {
3752     case clang::Type::Builtin:
3753       if (check_objc &&
3754           llvm::cast<clang::BuiltinType>(qual_type)->getKind() ==
3755               clang::BuiltinType::ObjCId) {
3756         if (dynamic_pointee_type)
3757           dynamic_pointee_type->SetCompilerType(this, type);
3758         return true;
3759       }
3760       break;
3761
3762     case clang::Type::ObjCObjectPointer:
3763       if (check_objc) {
3764         if (auto objc_pointee_type =
3765                 qual_type->getPointeeType().getTypePtrOrNull()) {
3766           if (auto objc_object_type =
3767                   llvm::dyn_cast_or_null<clang::ObjCObjectType>(
3768                       objc_pointee_type)) {
3769             if (objc_object_type->isObjCClass())
3770               return false;
3771           }
3772         }
3773         if (dynamic_pointee_type)
3774           dynamic_pointee_type->SetCompilerType(
3775               getASTContext(),
3776               llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3777                   ->getPointeeType());
3778         return true;
3779       }
3780       break;
3781
3782     case clang::Type::Pointer:
3783       pointee_qual_type =
3784           llvm::cast<clang::PointerType>(qual_type)->getPointeeType();
3785       success = true;
3786       break;
3787
3788     case clang::Type::LValueReference:
3789     case clang::Type::RValueReference:
3790       pointee_qual_type =
3791           llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType();
3792       success = true;
3793       break;
3794
3795     case clang::Type::Typedef:
3796       return IsPossibleDynamicType(llvm::cast<clang::TypedefType>(qual_type)
3797                                        ->getDecl()
3798                                        ->getUnderlyingType()
3799                                        .getAsOpaquePtr(),
3800                                    dynamic_pointee_type, check_cplusplus,
3801                                    check_objc);
3802
3803     case clang::Type::Auto:
3804       return IsPossibleDynamicType(llvm::cast<clang::AutoType>(qual_type)
3805                                        ->getDeducedType()
3806                                        .getAsOpaquePtr(),
3807                                    dynamic_pointee_type, check_cplusplus,
3808                                    check_objc);
3809
3810     case clang::Type::Elaborated:
3811       return IsPossibleDynamicType(llvm::cast<clang::ElaboratedType>(qual_type)
3812                                        ->getNamedType()
3813                                        .getAsOpaquePtr(),
3814                                    dynamic_pointee_type, check_cplusplus,
3815                                    check_objc);
3816
3817     case clang::Type::Paren:
3818       return IsPossibleDynamicType(
3819           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
3820           dynamic_pointee_type, check_cplusplus, check_objc);
3821     default:
3822       break;
3823     }
3824
3825     if (success) {
3826       // Check to make sure what we are pointing too is a possible dynamic C++
3827       // type We currently accept any "void *" (in case we have a class that
3828       // has been watered down to an opaque pointer) and virtual C++ classes.
3829       const clang::Type::TypeClass pointee_type_class =
3830           pointee_qual_type.getCanonicalType()->getTypeClass();
3831       switch (pointee_type_class) {
3832       case clang::Type::Builtin:
3833         switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) {
3834         case clang::BuiltinType::UnknownAny:
3835         case clang::BuiltinType::Void:
3836           if (dynamic_pointee_type)
3837             dynamic_pointee_type->SetCompilerType(getASTContext(),
3838                                                   pointee_qual_type);
3839           return true;
3840         default:
3841           break;
3842         }
3843         break;
3844
3845       case clang::Type::Record:
3846         if (check_cplusplus) {
3847           clang::CXXRecordDecl *cxx_record_decl =
3848               pointee_qual_type->getAsCXXRecordDecl();
3849           if (cxx_record_decl) {
3850             bool is_complete = cxx_record_decl->isCompleteDefinition();
3851
3852             if (is_complete)
3853               success = cxx_record_decl->isDynamicClass();
3854             else {
3855               ClangASTMetadata *metadata = ClangASTContext::GetMetadata(
3856                   getASTContext(), cxx_record_decl);
3857               if (metadata)
3858                 success = metadata->GetIsDynamicCXXType();
3859               else {
3860                 is_complete = CompilerType(getASTContext(), pointee_qual_type)
3861                                   .GetCompleteType();
3862                 if (is_complete)
3863                   success = cxx_record_decl->isDynamicClass();
3864                 else
3865                   success = false;
3866               }
3867             }
3868
3869             if (success) {
3870               if (dynamic_pointee_type)
3871                 dynamic_pointee_type->SetCompilerType(getASTContext(),
3872                                                       pointee_qual_type);
3873               return true;
3874             }
3875           }
3876         }
3877         break;
3878
3879       case clang::Type::ObjCObject:
3880       case clang::Type::ObjCInterface:
3881         if (check_objc) {
3882           if (dynamic_pointee_type)
3883             dynamic_pointee_type->SetCompilerType(getASTContext(),
3884                                                   pointee_qual_type);
3885           return true;
3886         }
3887         break;
3888
3889       default:
3890         break;
3891       }
3892     }
3893   }
3894   if (dynamic_pointee_type)
3895     dynamic_pointee_type->Clear();
3896   return false;
3897 }
3898
3899 bool ClangASTContext::IsScalarType(lldb::opaque_compiler_type_t type) {
3900   if (!type)
3901     return false;
3902
3903   return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3904 }
3905
3906 bool ClangASTContext::IsTypedefType(lldb::opaque_compiler_type_t type) {
3907   if (!type)
3908     return false;
3909   return GetQualType(type)->getTypeClass() == clang::Type::Typedef;
3910 }
3911
3912 bool ClangASTContext::IsVoidType(lldb::opaque_compiler_type_t type) {
3913   if (!type)
3914     return false;
3915   return GetCanonicalQualType(type)->isVoidType();
3916 }
3917
3918 bool ClangASTContext::CanPassInRegisters(const CompilerType &type) {
3919   if (auto *record_decl =
3920       ClangASTContext::GetAsRecordDecl(type)) {
3921     return record_decl->canPassInRegisters();
3922   }
3923   return false;
3924 }
3925
3926 bool ClangASTContext::SupportsLanguage(lldb::LanguageType language) {
3927   return ClangASTContextSupportsLanguage(language);
3928 }
3929
3930 bool ClangASTContext::GetCXXClassName(const CompilerType &type,
3931                                       std::string &class_name) {
3932   if (type) {
3933     clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3934     if (!qual_type.isNull()) {
3935       clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3936       if (cxx_record_decl) {
3937         class_name.assign(cxx_record_decl->getIdentifier()->getNameStart());
3938         return true;
3939       }
3940     }
3941   }
3942   class_name.clear();
3943   return false;
3944 }
3945
3946 bool ClangASTContext::IsCXXClassType(const CompilerType &type) {
3947   if (!type)
3948     return false;
3949
3950   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3951   return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr;
3952 }
3953
3954 bool ClangASTContext::IsBeingDefined(lldb::opaque_compiler_type_t type) {
3955   if (!type)
3956     return false;
3957   clang::QualType qual_type(GetCanonicalQualType(type));
3958   const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type);
3959   if (tag_type)
3960     return tag_type->isBeingDefined();
3961   return false;
3962 }
3963
3964 bool ClangASTContext::IsObjCObjectPointerType(const CompilerType &type,
3965                                               CompilerType *class_type_ptr) {
3966   if (!type)
3967     return false;
3968
3969   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3970
3971   if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) {
3972     if (class_type_ptr) {
3973       if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) {
3974         const clang::ObjCObjectPointerType *obj_pointer_type =
3975             llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3976         if (obj_pointer_type == nullptr)
3977           class_type_ptr->Clear();
3978         else
3979           class_type_ptr->SetCompilerType(
3980               type.GetTypeSystem(),
3981               clang::QualType(obj_pointer_type->getInterfaceType(), 0)
3982                   .getAsOpaquePtr());
3983       }
3984     }
3985     return true;
3986   }
3987   if (class_type_ptr)
3988     class_type_ptr->Clear();
3989   return false;
3990 }
3991
3992 bool ClangASTContext::GetObjCClassName(const CompilerType &type,
3993                                        std::string &class_name) {
3994   if (!type)
3995     return false;
3996
3997   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3998
3999   const clang::ObjCObjectType *object_type =
4000       llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
4001   if (object_type) {
4002     const clang::ObjCInterfaceDecl *interface = object_type->getInterface();
4003     if (interface) {
4004       class_name = interface->getNameAsString();
4005       return true;
4006     }
4007   }
4008   return false;
4009 }
4010
4011 // Type Completion
4012
4013 bool ClangASTContext::GetCompleteType(lldb::opaque_compiler_type_t type) {
4014   if (!type)
4015     return false;
4016   const bool allow_completion = true;
4017   return GetCompleteQualType(getASTContext(), GetQualType(type),
4018                              allow_completion);
4019 }
4020
4021 ConstString ClangASTContext::GetTypeName(lldb::opaque_compiler_type_t type) {
4022   std::string type_name;
4023   if (type) {
4024     clang::PrintingPolicy printing_policy(getASTContext()->getPrintingPolicy());
4025     clang::QualType qual_type(GetQualType(type));
4026     printing_policy.SuppressTagKeyword = true;
4027     const clang::TypedefType *typedef_type =
4028         qual_type->getAs<clang::TypedefType>();
4029     if (typedef_type) {
4030       const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
4031       type_name = typedef_decl->getQualifiedNameAsString();
4032     } else {
4033       type_name = qual_type.getAsString(printing_policy);
4034     }
4035   }
4036   return ConstString(type_name);
4037 }
4038
4039 uint32_t
4040 ClangASTContext::GetTypeInfo(lldb::opaque_compiler_type_t type,
4041                              CompilerType *pointee_or_element_clang_type) {
4042   if (!type)
4043     return 0;
4044
4045   if (pointee_or_element_clang_type)
4046     pointee_or_element_clang_type->Clear();
4047
4048   clang::QualType qual_type(GetQualType(type));
4049
4050   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4051   switch (type_class) {
4052   case clang::Type::Attributed:
4053     return GetTypeInfo(
4054         qual_type->getAs<clang::AttributedType>()
4055             ->getModifiedType().getAsOpaquePtr(),
4056         pointee_or_element_clang_type);
4057   case clang::Type::Builtin: {
4058     const clang::BuiltinType *builtin_type = llvm::dyn_cast<clang::BuiltinType>(
4059         qual_type->getCanonicalTypeInternal());
4060
4061     uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
4062     switch (builtin_type->getKind()) {
4063     case clang::BuiltinType::ObjCId:
4064     case clang::BuiltinType::ObjCClass:
4065       if (pointee_or_element_clang_type)
4066         pointee_or_element_clang_type->SetCompilerType(
4067             getASTContext(), getASTContext()->ObjCBuiltinClassTy);
4068       builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
4069       break;
4070
4071     case clang::BuiltinType::ObjCSel:
4072       if (pointee_or_element_clang_type)
4073         pointee_or_element_clang_type->SetCompilerType(getASTContext(),
4074                                                        getASTContext()->CharTy);
4075       builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
4076       break;
4077
4078     case clang::BuiltinType::Bool:
4079     case clang::BuiltinType::Char_U:
4080     case clang::BuiltinType::UChar:
4081     case clang::BuiltinType::WChar_U:
4082     case clang::BuiltinType::Char16:
4083     case clang::BuiltinType::Char32:
4084     case clang::BuiltinType::UShort:
4085     case clang::BuiltinType::UInt:
4086     case clang::BuiltinType::ULong:
4087     case clang::BuiltinType::ULongLong:
4088     case clang::BuiltinType::UInt128:
4089     case clang::BuiltinType::Char_S:
4090     case clang::BuiltinType::SChar:
4091     case clang::BuiltinType::WChar_S:
4092     case clang::BuiltinType::Short:
4093     case clang::BuiltinType::Int:
4094     case clang::BuiltinType::Long:
4095     case clang::BuiltinType::LongLong:
4096     case clang::BuiltinType::Int128:
4097     case clang::BuiltinType::Float:
4098     case clang::BuiltinType::Double:
4099     case clang::BuiltinType::LongDouble:
4100       builtin_type_flags |= eTypeIsScalar;
4101       if (builtin_type->isInteger()) {
4102         builtin_type_flags |= eTypeIsInteger;
4103         if (builtin_type->isSignedInteger())
4104           builtin_type_flags |= eTypeIsSigned;
4105       } else if (builtin_type->isFloatingPoint())
4106         builtin_type_flags |= eTypeIsFloat;
4107       break;
4108     default:
4109       break;
4110     }
4111     return builtin_type_flags;
4112   }
4113
4114   case clang::Type::BlockPointer:
4115     if (pointee_or_element_clang_type)
4116       pointee_or_element_clang_type->SetCompilerType(
4117           getASTContext(), qual_type->getPointeeType());
4118     return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
4119
4120   case clang::Type::Complex: {
4121     uint32_t complex_type_flags =
4122         eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
4123     const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>(
4124         qual_type->getCanonicalTypeInternal());
4125     if (complex_type) {
4126       clang::QualType complex_element_type(complex_type->getElementType());
4127       if (complex_element_type->isIntegerType())
4128         complex_type_flags |= eTypeIsFloat;
4129       else if (complex_element_type->isFloatingType())
4130         complex_type_flags |= eTypeIsInteger;
4131     }
4132     return complex_type_flags;
4133   } break;
4134
4135   case clang::Type::ConstantArray:
4136   case clang::Type::DependentSizedArray:
4137   case clang::Type::IncompleteArray:
4138   case clang::Type::VariableArray:
4139     if (pointee_or_element_clang_type)
4140       pointee_or_element_clang_type->SetCompilerType(
4141           getASTContext(), llvm::cast<clang::ArrayType>(qual_type.getTypePtr())
4142                                ->getElementType());
4143     return eTypeHasChildren | eTypeIsArray;
4144
4145   case clang::Type::DependentName:
4146     return 0;
4147   case clang::Type::DependentSizedExtVector:
4148     return eTypeHasChildren | eTypeIsVector;
4149   case clang::Type::DependentTemplateSpecialization:
4150     return eTypeIsTemplate;
4151   case clang::Type::Decltype:
4152     return CompilerType(
4153                getASTContext(),
4154                llvm::cast<clang::DecltypeType>(qual_type)->getUnderlyingType())
4155         .GetTypeInfo(pointee_or_element_clang_type);
4156
4157   case clang::Type::Enum:
4158     if (pointee_or_element_clang_type)
4159       pointee_or_element_clang_type->SetCompilerType(
4160           getASTContext(),
4161           llvm::cast<clang::EnumType>(qual_type)->getDecl()->getIntegerType());
4162     return eTypeIsEnumeration | eTypeHasValue;
4163
4164   case clang::Type::Auto:
4165     return CompilerType(
4166                getASTContext(),
4167                llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
4168         .GetTypeInfo(pointee_or_element_clang_type);
4169   case clang::Type::Elaborated:
4170     return CompilerType(
4171                getASTContext(),
4172                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
4173         .GetTypeInfo(pointee_or_element_clang_type);
4174   case clang::Type::Paren:
4175     return CompilerType(getASTContext(),
4176                         llvm::cast<clang::ParenType>(qual_type)->desugar())
4177         .GetTypeInfo(pointee_or_element_clang_type);
4178
4179   case clang::Type::FunctionProto:
4180     return eTypeIsFuncPrototype | eTypeHasValue;
4181   case clang::Type::FunctionNoProto:
4182     return eTypeIsFuncPrototype | eTypeHasValue;
4183   case clang::Type::InjectedClassName:
4184     return 0;
4185
4186   case clang::Type::LValueReference:
4187   case clang::Type::RValueReference:
4188     if (pointee_or_element_clang_type)
4189       pointee_or_element_clang_type->SetCompilerType(
4190           getASTContext(),
4191           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr())
4192               ->getPointeeType());
4193     return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
4194
4195   case clang::Type::MemberPointer:
4196     return eTypeIsPointer | eTypeIsMember | eTypeHasValue;
4197
4198   case clang::Type::ObjCObjectPointer:
4199     if (pointee_or_element_clang_type)
4200       pointee_or_element_clang_type->SetCompilerType(
4201           getASTContext(), qual_type->getPointeeType());
4202     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer |
4203            eTypeHasValue;
4204
4205   case clang::Type::ObjCObject:
4206     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
4207   case clang::Type::ObjCInterface:
4208     return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
4209
4210   case clang::Type::Pointer:
4211     if (pointee_or_element_clang_type)
4212       pointee_or_element_clang_type->SetCompilerType(
4213           getASTContext(), qual_type->getPointeeType());
4214     return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
4215
4216   case clang::Type::Record:
4217     if (qual_type->getAsCXXRecordDecl())
4218       return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
4219     else
4220       return eTypeHasChildren | eTypeIsStructUnion;
4221     break;
4222   case clang::Type::SubstTemplateTypeParm:
4223     return eTypeIsTemplate;
4224   case clang::Type::TemplateTypeParm:
4225     return eTypeIsTemplate;
4226   case clang::Type::TemplateSpecialization:
4227     return eTypeIsTemplate;
4228
4229   case clang::Type::Typedef:
4230     return eTypeIsTypedef |
4231            CompilerType(getASTContext(),
4232                         llvm::cast<clang::TypedefType>(qual_type)
4233                             ->getDecl()
4234                             ->getUnderlyingType())
4235                .GetTypeInfo(pointee_or_element_clang_type);
4236   case clang::Type::TypeOfExpr:
4237     return CompilerType(getASTContext(),
4238                         llvm::cast<clang::TypeOfExprType>(qual_type)
4239                             ->getUnderlyingExpr()
4240                             ->getType())
4241         .GetTypeInfo(pointee_or_element_clang_type);
4242   case clang::Type::TypeOf:
4243     return CompilerType(
4244                getASTContext(),
4245                llvm::cast<clang::TypeOfType>(qual_type)->getUnderlyingType())
4246         .GetTypeInfo(pointee_or_element_clang_type);
4247   case clang::Type::UnresolvedUsing:
4248     return 0;
4249
4250   case clang::Type::ExtVector:
4251   case clang::Type::Vector: {
4252     uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
4253     const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>(
4254         qual_type->getCanonicalTypeInternal());
4255     if (vector_type) {
4256       if (vector_type->isIntegerType())
4257         vector_type_flags |= eTypeIsFloat;
4258       else if (vector_type->isFloatingType())
4259         vector_type_flags |= eTypeIsInteger;
4260     }
4261     return vector_type_flags;
4262   }
4263   default:
4264     return 0;
4265   }
4266   return 0;
4267 }
4268
4269 lldb::LanguageType
4270 ClangASTContext::GetMinimumLanguage(lldb::opaque_compiler_type_t type) {
4271   if (!type)
4272     return lldb::eLanguageTypeC;
4273
4274   // If the type is a reference, then resolve it to what it refers to first:
4275   clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType());
4276   if (qual_type->isAnyPointerType()) {
4277     if (qual_type->isObjCObjectPointerType())
4278       return lldb::eLanguageTypeObjC;
4279     if (qual_type->getPointeeCXXRecordDecl())
4280       return lldb::eLanguageTypeC_plus_plus;
4281
4282     clang::QualType pointee_type(qual_type->getPointeeType());
4283     if (pointee_type->getPointeeCXXRecordDecl())
4284       return lldb::eLanguageTypeC_plus_plus;
4285     if (pointee_type->isObjCObjectOrInterfaceType())
4286       return lldb::eLanguageTypeObjC;
4287     if (pointee_type->isObjCClassType())
4288       return lldb::eLanguageTypeObjC;
4289     if (pointee_type.getTypePtr() ==
4290         getASTContext()->ObjCBuiltinIdTy.getTypePtr())
4291       return lldb::eLanguageTypeObjC;
4292   } else {
4293     if (qual_type->isObjCObjectOrInterfaceType())
4294       return lldb::eLanguageTypeObjC;
4295     if (qual_type->getAsCXXRecordDecl())
4296       return lldb::eLanguageTypeC_plus_plus;
4297     switch (qual_type->getTypeClass()) {
4298     default:
4299       break;
4300     case clang::Type::Builtin:
4301       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4302       default:
4303       case clang::BuiltinType::Void:
4304       case clang::BuiltinType::Bool:
4305       case clang::BuiltinType::Char_U:
4306       case clang::BuiltinType::UChar:
4307       case clang::BuiltinType::WChar_U:
4308       case clang::BuiltinType::Char16:
4309       case clang::BuiltinType::Char32:
4310       case clang::BuiltinType::UShort:
4311       case clang::BuiltinType::UInt:
4312       case clang::BuiltinType::ULong:
4313       case clang::BuiltinType::ULongLong:
4314       case clang::BuiltinType::UInt128:
4315       case clang::BuiltinType::Char_S:
4316       case clang::BuiltinType::SChar:
4317       case clang::BuiltinType::WChar_S:
4318       case clang::BuiltinType::Short:
4319       case clang::BuiltinType::Int:
4320       case clang::BuiltinType::Long:
4321       case clang::BuiltinType::LongLong:
4322       case clang::BuiltinType::Int128:
4323       case clang::BuiltinType::Float:
4324       case clang::BuiltinType::Double:
4325       case clang::BuiltinType::LongDouble:
4326         break;
4327
4328       case clang::BuiltinType::NullPtr:
4329         return eLanguageTypeC_plus_plus;
4330
4331       case clang::BuiltinType::ObjCId:
4332       case clang::BuiltinType::ObjCClass:
4333       case clang::BuiltinType::ObjCSel:
4334         return eLanguageTypeObjC;
4335
4336       case clang::BuiltinType::Dependent:
4337       case clang::BuiltinType::Overload:
4338       case clang::BuiltinType::BoundMember:
4339       case clang::BuiltinType::UnknownAny:
4340         break;
4341       }
4342       break;
4343     case clang::Type::Typedef:
4344       return CompilerType(getASTContext(),
4345                           llvm::cast<clang::TypedefType>(qual_type)
4346                               ->getDecl()
4347                               ->getUnderlyingType())
4348           .GetMinimumLanguage();
4349     }
4350   }
4351   return lldb::eLanguageTypeC;
4352 }
4353
4354 lldb::TypeClass
4355 ClangASTContext::GetTypeClass(lldb::opaque_compiler_type_t type) {
4356   if (!type)
4357     return lldb::eTypeClassInvalid;
4358
4359   clang::QualType qual_type(GetQualType(type));
4360
4361   switch (qual_type->getTypeClass()) {
4362   case clang::Type::UnaryTransform:
4363     break;
4364   case clang::Type::FunctionNoProto:
4365     return lldb::eTypeClassFunction;
4366   case clang::Type::FunctionProto:
4367     return lldb::eTypeClassFunction;
4368   case clang::Type::IncompleteArray:
4369     return lldb::eTypeClassArray;
4370   case clang::Type::VariableArray:
4371     return lldb::eTypeClassArray;
4372   case clang::Type::ConstantArray:
4373     return lldb::eTypeClassArray;
4374   case clang::Type::DependentSizedArray:
4375     return lldb::eTypeClassArray;
4376   case clang::Type::DependentSizedExtVector:
4377     return lldb::eTypeClassVector;
4378   case clang::Type::DependentVector:
4379     return lldb::eTypeClassVector;
4380   case clang::Type::ExtVector:
4381     return lldb::eTypeClassVector;
4382   case clang::Type::Vector:
4383     return lldb::eTypeClassVector;
4384   case clang::Type::Builtin:
4385     return lldb::eTypeClassBuiltin;
4386   case clang::Type::ObjCObjectPointer:
4387     return lldb::eTypeClassObjCObjectPointer;
4388   case clang::Type::BlockPointer:
4389     return lldb::eTypeClassBlockPointer;
4390   case clang::Type::Pointer:
4391     return lldb::eTypeClassPointer;
4392   case clang::Type::LValueReference:
4393     return lldb::eTypeClassReference;
4394   case clang::Type::RValueReference:
4395     return lldb::eTypeClassReference;
4396   case clang::Type::MemberPointer:
4397     return lldb::eTypeClassMemberPointer;
4398   case clang::Type::Complex:
4399     if (qual_type->isComplexType())
4400       return lldb::eTypeClassComplexFloat;
4401     else
4402       return lldb::eTypeClassComplexInteger;
4403   case clang::Type::ObjCObject:
4404     return lldb::eTypeClassObjCObject;
4405   case clang::Type::ObjCInterface:
4406     return lldb::eTypeClassObjCInterface;
4407   case clang::Type::Record: {
4408     const clang::RecordType *record_type =
4409         llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4410     const clang::RecordDecl *record_decl = record_type->getDecl();
4411     if (record_decl->isUnion())
4412       return lldb::eTypeClassUnion;
4413     else if (record_decl->isStruct())
4414       return lldb::eTypeClassStruct;
4415     else
4416       return lldb::eTypeClassClass;
4417   } break;
4418   case clang::Type::Enum:
4419     return lldb::eTypeClassEnumeration;
4420   case clang::Type::Typedef:
4421     return lldb::eTypeClassTypedef;
4422   case clang::Type::UnresolvedUsing:
4423     break;
4424   case clang::Type::Paren:
4425     return CompilerType(getASTContext(),
4426                         llvm::cast<clang::ParenType>(qual_type)->desugar())
4427         .GetTypeClass();
4428   case clang::Type::Auto:
4429     return CompilerType(
4430                getASTContext(),
4431                llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
4432         .GetTypeClass();
4433   case clang::Type::Elaborated:
4434     return CompilerType(
4435                getASTContext(),
4436                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
4437         .GetTypeClass();
4438
4439   case clang::Type::Attributed:
4440     break;
4441   case clang::Type::TemplateTypeParm:
4442     break;
4443   case clang::Type::SubstTemplateTypeParm:
4444     break;
4445   case clang::Type::SubstTemplateTypeParmPack:
4446     break;
4447   case clang::Type::InjectedClassName:
4448     break;
4449   case clang::Type::DependentName:
4450     break;
4451   case clang::Type::DependentTemplateSpecialization:
4452     break;
4453   case clang::Type::PackExpansion:
4454     break;
4455
4456   case clang::Type::TypeOfExpr:
4457     return CompilerType(getASTContext(),
4458                         llvm::cast<clang::TypeOfExprType>(qual_type)
4459                             ->getUnderlyingExpr()
4460                             ->getType())
4461         .GetTypeClass();
4462   case clang::Type::TypeOf:
4463     return CompilerType(
4464                getASTContext(),
4465                llvm::cast<clang::TypeOfType>(qual_type)->getUnderlyingType())
4466         .GetTypeClass();
4467   case clang::Type::Decltype:
4468     return CompilerType(
4469                getASTContext(),
4470                llvm::cast<clang::TypeOfType>(qual_type)->getUnderlyingType())
4471         .GetTypeClass();
4472   case clang::Type::TemplateSpecialization:
4473     break;
4474   case clang::Type::DeducedTemplateSpecialization:
4475     break;
4476   case clang::Type::Atomic:
4477     break;
4478   case clang::Type::Pipe:
4479     break;
4480
4481   // pointer type decayed from an array or function type.
4482   case clang::Type::Decayed:
4483     break;
4484   case clang::Type::Adjusted:
4485     break;
4486   case clang::Type::ObjCTypeParam:
4487     break;
4488
4489   case clang::Type::DependentAddressSpace:
4490     break;
4491   case clang::Type::MacroQualified:
4492     break;
4493   }
4494   // We don't know hot to display this type...
4495   return lldb::eTypeClassOther;
4496 }
4497
4498 unsigned ClangASTContext::GetTypeQualifiers(lldb::opaque_compiler_type_t type) {
4499   if (type)
4500     return GetQualType(type).getQualifiers().getCVRQualifiers();
4501   return 0;
4502 }
4503
4504 // Creating related types
4505
4506 CompilerType
4507 ClangASTContext::GetArrayElementType(lldb::opaque_compiler_type_t type,
4508                                      uint64_t *stride) {
4509   if (type) {
4510     clang::QualType qual_type(GetCanonicalQualType(type));
4511
4512     const clang::Type *array_eletype =
4513         qual_type.getTypePtr()->getArrayElementTypeNoTypeQual();
4514
4515     if (!array_eletype)
4516       return CompilerType();
4517
4518     CompilerType element_type(getASTContext(),
4519                               array_eletype->getCanonicalTypeUnqualified());
4520
4521     // TODO: the real stride will be >= this value.. find the real one!
4522     if (stride)
4523       if (Optional<uint64_t> size = element_type.GetByteSize(nullptr))
4524         *stride = *size;
4525
4526     return element_type;
4527   }
4528   return CompilerType();
4529 }
4530
4531 CompilerType ClangASTContext::GetArrayType(lldb::opaque_compiler_type_t type,
4532                                            uint64_t size) {
4533   if (type) {
4534     clang::QualType qual_type(GetCanonicalQualType(type));
4535     if (clang::ASTContext *ast_ctx = getASTContext()) {
4536       if (size != 0)
4537         return CompilerType(
4538             ast_ctx, ast_ctx->getConstantArrayType(
4539                          qual_type, llvm::APInt(64, size),
4540                          clang::ArrayType::ArraySizeModifier::Normal, 0));
4541       else
4542         return CompilerType(
4543             ast_ctx,
4544             ast_ctx->getIncompleteArrayType(
4545                 qual_type, clang::ArrayType::ArraySizeModifier::Normal, 0));
4546     }
4547   }
4548
4549   return CompilerType();
4550 }
4551
4552 CompilerType
4553 ClangASTContext::GetCanonicalType(lldb::opaque_compiler_type_t type) {
4554   if (type)
4555     return CompilerType(getASTContext(), GetCanonicalQualType(type));
4556   return CompilerType();
4557 }
4558
4559 static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast,
4560                                                     clang::QualType qual_type) {
4561   if (qual_type->isPointerType())
4562     qual_type = ast->getPointerType(
4563         GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType()));
4564   else
4565     qual_type = qual_type.getUnqualifiedType();
4566   qual_type.removeLocalConst();
4567   qual_type.removeLocalRestrict();
4568   qual_type.removeLocalVolatile();
4569   return qual_type;
4570 }
4571
4572 CompilerType
4573 ClangASTContext::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) {
4574   if (type)
4575     return CompilerType(
4576         getASTContext(),
4577         GetFullyUnqualifiedType_Impl(getASTContext(), GetQualType(type)));
4578   return CompilerType();
4579 }
4580
4581 int ClangASTContext::GetFunctionArgumentCount(
4582     lldb::opaque_compiler_type_t type) {
4583   if (type) {
4584     const clang::FunctionProtoType *func =
4585         llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type));
4586     if (func)
4587       return func->getNumParams();
4588   }
4589   return -1;
4590 }
4591
4592 CompilerType ClangASTContext::GetFunctionArgumentTypeAtIndex(
4593     lldb::opaque_compiler_type_t type, size_t idx) {
4594   if (type) {
4595     const clang::FunctionProtoType *func =
4596         llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type));
4597     if (func) {
4598       const uint32_t num_args = func->getNumParams();
4599       if (idx < num_args)
4600         return CompilerType(getASTContext(), func->getParamType(idx));
4601     }
4602   }
4603   return CompilerType();
4604 }
4605
4606 CompilerType
4607 ClangASTContext::GetFunctionReturnType(lldb::opaque_compiler_type_t type) {
4608   if (type) {
4609     clang::QualType qual_type(GetQualType(type));
4610     const clang::FunctionProtoType *func =
4611         llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
4612     if (func)
4613       return CompilerType(getASTContext(), func->getReturnType());
4614   }
4615   return CompilerType();
4616 }
4617
4618 size_t
4619 ClangASTContext::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) {
4620   size_t num_functions = 0;
4621   if (type) {
4622     clang::QualType qual_type(GetCanonicalQualType(type));
4623     switch (qual_type->getTypeClass()) {
4624     case clang::Type::Record:
4625       if (GetCompleteQualType(getASTContext(), qual_type)) {
4626         const clang::RecordType *record_type =
4627             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4628         const clang::RecordDecl *record_decl = record_type->getDecl();
4629         assert(record_decl);
4630         const clang::CXXRecordDecl *cxx_record_decl =
4631             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4632         if (cxx_record_decl)
4633           num_functions = std::distance(cxx_record_decl->method_begin(),
4634                                         cxx_record_decl->method_end());
4635       }
4636       break;
4637
4638     case clang::Type::ObjCObjectPointer: {
4639       const clang::ObjCObjectPointerType *objc_class_type =
4640           qual_type->getAs<clang::ObjCObjectPointerType>();
4641       const clang::ObjCInterfaceType *objc_interface_type =
4642           objc_class_type->getInterfaceType();
4643       if (objc_interface_type &&
4644           GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4645               const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4646         clang::ObjCInterfaceDecl *class_interface_decl =
4647             objc_interface_type->getDecl();
4648         if (class_interface_decl) {
4649           num_functions = std::distance(class_interface_decl->meth_begin(),
4650                                         class_interface_decl->meth_end());
4651         }
4652       }
4653       break;
4654     }
4655
4656     case clang::Type::ObjCObject:
4657     case clang::Type::ObjCInterface:
4658       if (GetCompleteType(type)) {
4659         const clang::ObjCObjectType *objc_class_type =
4660             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4661         if (objc_class_type) {
4662           clang::ObjCInterfaceDecl *class_interface_decl =
4663               objc_class_type->getInterface();
4664           if (class_interface_decl)
4665             num_functions = std::distance(class_interface_decl->meth_begin(),
4666                                           class_interface_decl->meth_end());
4667         }
4668       }
4669       break;
4670
4671     case clang::Type::Typedef:
4672       return CompilerType(getASTContext(),
4673                           llvm::cast<clang::TypedefType>(qual_type)
4674                               ->getDecl()
4675                               ->getUnderlyingType())
4676           .GetNumMemberFunctions();
4677
4678     case clang::Type::Auto:
4679       return CompilerType(
4680                  getASTContext(),
4681                  llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
4682           .GetNumMemberFunctions();
4683
4684     case clang::Type::Elaborated:
4685       return CompilerType(
4686                  getASTContext(),
4687                  llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
4688           .GetNumMemberFunctions();
4689
4690     case clang::Type::Paren:
4691       return CompilerType(getASTContext(),
4692                           llvm::cast<clang::ParenType>(qual_type)->desugar())
4693           .GetNumMemberFunctions();
4694
4695     default:
4696       break;
4697     }
4698   }
4699   return num_functions;
4700 }
4701
4702 TypeMemberFunctionImpl
4703 ClangASTContext::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
4704                                           size_t idx) {
4705   std::string name;
4706   MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
4707   CompilerType clang_type;
4708   CompilerDecl clang_decl;
4709   if (type) {
4710     clang::QualType qual_type(GetCanonicalQualType(type));
4711     switch (qual_type->getTypeClass()) {
4712     case clang::Type::Record:
4713       if (GetCompleteQualType(getASTContext(), qual_type)) {
4714         const clang::RecordType *record_type =
4715             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4716         const clang::RecordDecl *record_decl = record_type->getDecl();
4717         assert(record_decl);
4718         const clang::CXXRecordDecl *cxx_record_decl =
4719             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4720         if (cxx_record_decl) {
4721           auto method_iter = cxx_record_decl->method_begin();
4722           auto method_end = cxx_record_decl->method_end();
4723           if (idx <
4724               static_cast<size_t>(std::distance(method_iter, method_end))) {
4725             std::advance(method_iter, idx);
4726             clang::CXXMethodDecl *cxx_method_decl =
4727                 method_iter->getCanonicalDecl();
4728             if (cxx_method_decl) {
4729               name = cxx_method_decl->getDeclName().getAsString();
4730               if (cxx_method_decl->isStatic())
4731                 kind = lldb::eMemberFunctionKindStaticMethod;
4732               else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4733                 kind = lldb::eMemberFunctionKindConstructor;
4734               else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4735                 kind = lldb::eMemberFunctionKindDestructor;
4736               else
4737                 kind = lldb::eMemberFunctionKindInstanceMethod;
4738               clang_type = CompilerType(
4739                   this, cxx_method_decl->getType().getAsOpaquePtr());
4740               clang_decl = CompilerDecl(this, cxx_method_decl);
4741             }
4742           }
4743         }
4744       }
4745       break;
4746
4747     case clang::Type::ObjCObjectPointer: {
4748       const clang::ObjCObjectPointerType *objc_class_type =
4749           qual_type->getAs<clang::ObjCObjectPointerType>();
4750       const clang::ObjCInterfaceType *objc_interface_type =
4751           objc_class_type->getInterfaceType();
4752       if (objc_interface_type &&
4753           GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4754               const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4755         clang::ObjCInterfaceDecl *class_interface_decl =
4756             objc_interface_type->getDecl();
4757         if (class_interface_decl) {
4758           auto method_iter = class_interface_decl->meth_begin();
4759           auto method_end = class_interface_decl->meth_end();
4760           if (idx <
4761               static_cast<size_t>(std::distance(method_iter, method_end))) {
4762             std::advance(method_iter, idx);
4763             clang::ObjCMethodDecl *objc_method_decl =
4764                 method_iter->getCanonicalDecl();
4765             if (objc_method_decl) {
4766               clang_decl = CompilerDecl(this, objc_method_decl);
4767               name = objc_method_decl->getSelector().getAsString();
4768               if (objc_method_decl->isClassMethod())
4769                 kind = lldb::eMemberFunctionKindStaticMethod;
4770               else
4771                 kind = lldb::eMemberFunctionKindInstanceMethod;
4772             }
4773           }
4774         }
4775       }
4776       break;
4777     }
4778
4779     case clang::Type::ObjCObject:
4780     case clang::Type::ObjCInterface:
4781       if (GetCompleteType(type)) {
4782         const clang::ObjCObjectType *objc_class_type =
4783             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4784         if (objc_class_type) {
4785           clang::ObjCInterfaceDecl *class_interface_decl =
4786               objc_class_type->getInterface();
4787           if (class_interface_decl) {
4788             auto method_iter = class_interface_decl->meth_begin();
4789             auto method_end = class_interface_decl->meth_end();
4790             if (idx <
4791                 static_cast<size_t>(std::distance(method_iter, method_end))) {
4792               std::advance(method_iter, idx);
4793               clang::ObjCMethodDecl *objc_method_decl =
4794                   method_iter->getCanonicalDecl();
4795               if (objc_method_decl) {
4796                 clang_decl = CompilerDecl(this, objc_method_decl);
4797                 name = objc_method_decl->getSelector().getAsString();
4798                 if (objc_method_decl->isClassMethod())
4799                   kind = lldb::eMemberFunctionKindStaticMethod;
4800                 else
4801                   kind = lldb::eMemberFunctionKindInstanceMethod;
4802               }
4803             }
4804           }
4805         }
4806       }
4807       break;
4808
4809     case clang::Type::Typedef:
4810       return GetMemberFunctionAtIndex(llvm::cast<clang::TypedefType>(qual_type)
4811                                           ->getDecl()
4812                                           ->getUnderlyingType()
4813                                           .getAsOpaquePtr(),
4814                                       idx);
4815
4816     case clang::Type::Auto:
4817       return GetMemberFunctionAtIndex(llvm::cast<clang::AutoType>(qual_type)
4818                                           ->getDeducedType()
4819                                           .getAsOpaquePtr(),
4820                                       idx);
4821
4822     case clang::Type::Elaborated:
4823       return GetMemberFunctionAtIndex(
4824           llvm::cast<clang::ElaboratedType>(qual_type)
4825               ->getNamedType()
4826               .getAsOpaquePtr(),
4827           idx);
4828
4829     case clang::Type::Paren:
4830       return GetMemberFunctionAtIndex(
4831           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
4832           idx);
4833
4834     default:
4835       break;
4836     }
4837   }
4838
4839   if (kind == eMemberFunctionKindUnknown)
4840     return TypeMemberFunctionImpl();
4841   else
4842     return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind);
4843 }
4844
4845 CompilerType
4846 ClangASTContext::GetNonReferenceType(lldb::opaque_compiler_type_t type) {
4847   if (type)
4848     return CompilerType(getASTContext(),
4849                         GetQualType(type).getNonReferenceType());
4850   return CompilerType();
4851 }
4852
4853 CompilerType ClangASTContext::CreateTypedefType(
4854     const CompilerType &type, const char *typedef_name,
4855     const CompilerDeclContext &compiler_decl_ctx) {
4856   if (type && typedef_name && typedef_name[0]) {
4857     ClangASTContext *ast =
4858         llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
4859     if (!ast)
4860       return CompilerType();
4861     clang::ASTContext *clang_ast = ast->getASTContext();
4862     clang::QualType qual_type(ClangUtil::GetQualType(type));
4863
4864     clang::DeclContext *decl_ctx =
4865         ClangASTContext::DeclContextGetAsDeclContext(compiler_decl_ctx);
4866     if (decl_ctx == nullptr)
4867       decl_ctx = ast->getASTContext()->getTranslationUnitDecl();
4868
4869     clang::TypedefDecl *decl = clang::TypedefDecl::Create(
4870         *clang_ast, decl_ctx, clang::SourceLocation(), clang::SourceLocation(),
4871         &clang_ast->Idents.get(typedef_name),
4872         clang_ast->getTrivialTypeSourceInfo(qual_type));
4873
4874     decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4875
4876     decl_ctx->addDecl(decl);
4877
4878     // Get a uniqued clang::QualType for the typedef decl type
4879     return CompilerType(clang_ast, clang_ast->getTypedefType(decl));
4880   }
4881   return CompilerType();
4882 }
4883
4884 CompilerType
4885 ClangASTContext::GetPointeeType(lldb::opaque_compiler_type_t type) {
4886   if (type) {
4887     clang::QualType qual_type(GetQualType(type));
4888     return CompilerType(getASTContext(),
4889                         qual_type.getTypePtr()->getPointeeType());
4890   }
4891   return CompilerType();
4892 }
4893
4894 CompilerType
4895 ClangASTContext::GetPointerType(lldb::opaque_compiler_type_t type) {
4896   if (type) {
4897     clang::QualType qual_type(GetQualType(type));
4898
4899     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4900     switch (type_class) {
4901     case clang::Type::ObjCObject:
4902     case clang::Type::ObjCInterface:
4903       return CompilerType(getASTContext(),
4904                           getASTContext()->getObjCObjectPointerType(qual_type));
4905
4906     default:
4907       return CompilerType(getASTContext(),
4908                           getASTContext()->getPointerType(qual_type));
4909     }
4910   }
4911   return CompilerType();
4912 }
4913
4914 CompilerType
4915 ClangASTContext::GetLValueReferenceType(lldb::opaque_compiler_type_t type) {
4916   if (type)
4917     return CompilerType(this, getASTContext()
4918                                   ->getLValueReferenceType(GetQualType(type))
4919                                   .getAsOpaquePtr());
4920   else
4921     return CompilerType();
4922 }
4923
4924 CompilerType
4925 ClangASTContext::GetRValueReferenceType(lldb::opaque_compiler_type_t type) {
4926   if (type)
4927     return CompilerType(this, getASTContext()
4928                                   ->getRValueReferenceType(GetQualType(type))
4929                                   .getAsOpaquePtr());
4930   else
4931     return CompilerType();
4932 }
4933
4934 CompilerType
4935 ClangASTContext::AddConstModifier(lldb::opaque_compiler_type_t type) {
4936   if (type) {
4937     clang::QualType result(GetQualType(type));
4938     result.addConst();
4939     return CompilerType(this, result.getAsOpaquePtr());
4940   }
4941   return CompilerType();
4942 }
4943
4944 CompilerType
4945 ClangASTContext::AddVolatileModifier(lldb::opaque_compiler_type_t type) {
4946   if (type) {
4947     clang::QualType result(GetQualType(type));
4948     result.addVolatile();
4949     return CompilerType(this, result.getAsOpaquePtr());
4950   }
4951   return CompilerType();
4952 }
4953
4954 CompilerType
4955 ClangASTContext::AddRestrictModifier(lldb::opaque_compiler_type_t type) {
4956   if (type) {
4957     clang::QualType result(GetQualType(type));
4958     result.addRestrict();
4959     return CompilerType(this, result.getAsOpaquePtr());
4960   }
4961   return CompilerType();
4962 }
4963
4964 CompilerType
4965 ClangASTContext::CreateTypedef(lldb::opaque_compiler_type_t type,
4966                                const char *typedef_name,
4967                                const CompilerDeclContext &compiler_decl_ctx) {
4968   if (type) {
4969     clang::ASTContext *clang_ast = getASTContext();
4970     clang::QualType qual_type(GetQualType(type));
4971
4972     clang::DeclContext *decl_ctx =
4973         ClangASTContext::DeclContextGetAsDeclContext(compiler_decl_ctx);
4974     if (decl_ctx == nullptr)
4975       decl_ctx = getASTContext()->getTranslationUnitDecl();
4976
4977     clang::TypedefDecl *decl = clang::TypedefDecl::Create(
4978         *clang_ast, decl_ctx, clang::SourceLocation(), clang::SourceLocation(),
4979         &clang_ast->Idents.get(typedef_name),
4980         clang_ast->getTrivialTypeSourceInfo(qual_type));
4981
4982     clang::TagDecl *tdecl = nullptr;
4983     if (!qual_type.isNull()) {
4984       if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>())
4985         tdecl = rt->getDecl();
4986       if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>())
4987         tdecl = et->getDecl();
4988     }
4989
4990     // Check whether this declaration is an anonymous struct, union, or enum,
4991     // hidden behind a typedef. If so, we try to check whether we have a
4992     // typedef tag to attach to the original record declaration
4993     if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl())
4994       tdecl->setTypedefNameForAnonDecl(decl);
4995
4996     decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4997
4998     // Get a uniqued clang::QualType for the typedef decl type
4999     return CompilerType(this, clang_ast->getTypedefType(decl).getAsOpaquePtr());
5000   }
5001   return CompilerType();
5002 }
5003
5004 CompilerType
5005 ClangASTContext::GetTypedefedType(lldb::opaque_compiler_type_t type) {
5006   if (type) {
5007     const clang::TypedefType *typedef_type =
5008         llvm::dyn_cast<clang::TypedefType>(GetQualType(type));
5009     if (typedef_type)
5010       return CompilerType(getASTContext(),
5011                           typedef_type->getDecl()->getUnderlyingType());
5012   }
5013   return CompilerType();
5014 }
5015
5016 // Create related types using the current type's AST
5017
5018 CompilerType ClangASTContext::GetBasicTypeFromAST(lldb::BasicType basic_type) {
5019   return ClangASTContext::GetBasicType(getASTContext(), basic_type);
5020 }
5021 // Exploring the type
5022
5023 Optional<uint64_t>
5024 ClangASTContext::GetBitSize(lldb::opaque_compiler_type_t type,
5025                             ExecutionContextScope *exe_scope) {
5026   if (GetCompleteType(type)) {
5027     clang::QualType qual_type(GetCanonicalQualType(type));
5028     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5029     switch (type_class) {
5030     case clang::Type::Record:
5031       if (GetCompleteType(type))
5032         return getASTContext()->getTypeSize(qual_type);
5033       else
5034         return None;
5035       break;
5036
5037     case clang::Type::ObjCInterface:
5038     case clang::Type::ObjCObject: {
5039       ExecutionContext exe_ctx(exe_scope);
5040       Process *process = exe_ctx.GetProcessPtr();
5041       if (process) {
5042         ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
5043         if (objc_runtime) {
5044           uint64_t bit_size = 0;
5045           if (objc_runtime->GetTypeBitSize(
5046                   CompilerType(getASTContext(), qual_type), bit_size))
5047             return bit_size;
5048         }
5049       } else {
5050         static bool g_printed = false;
5051         if (!g_printed) {
5052           StreamString s;
5053           DumpTypeDescription(type, &s);
5054
5055           llvm::outs() << "warning: trying to determine the size of type ";
5056           llvm::outs() << s.GetString() << "\n";
5057           llvm::outs() << "without a valid ExecutionContext. this is not "
5058                           "reliable. please file a bug against LLDB.\n";
5059           llvm::outs() << "backtrace:\n";
5060           llvm::sys::PrintStackTrace(llvm::outs());
5061           llvm::outs() << "\n";
5062           g_printed = true;
5063         }
5064       }
5065     }
5066       LLVM_FALLTHROUGH;
5067     default:
5068       const uint32_t bit_size = getASTContext()->getTypeSize(qual_type);
5069       if (bit_size == 0) {
5070         if (qual_type->isIncompleteArrayType())
5071           return getASTContext()->getTypeSize(
5072               qual_type->getArrayElementTypeNoTypeQual()
5073                   ->getCanonicalTypeUnqualified());
5074       }
5075       if (qual_type->isObjCObjectOrInterfaceType())
5076         return bit_size +
5077                getASTContext()->getTypeSize(
5078                    getASTContext()->ObjCBuiltinClassTy);
5079       // Function types actually have a size of 0, that's not an error.
5080       if (qual_type->isFunctionProtoType())
5081         return bit_size;
5082       if (bit_size)
5083         return bit_size;
5084     }
5085   }
5086   return None;
5087 }
5088
5089 size_t ClangASTContext::GetTypeBitAlign(lldb::opaque_compiler_type_t type) {
5090   if (GetCompleteType(type))
5091     return getASTContext()->getTypeAlign(GetQualType(type));
5092   return 0;
5093 }
5094
5095 lldb::Encoding ClangASTContext::GetEncoding(lldb::opaque_compiler_type_t type,
5096                                             uint64_t &count) {
5097   if (!type)
5098     return lldb::eEncodingInvalid;
5099
5100   count = 1;
5101   clang::QualType qual_type(GetCanonicalQualType(type));
5102
5103   switch (qual_type->getTypeClass()) {
5104   case clang::Type::UnaryTransform:
5105     break;
5106
5107   case clang::Type::FunctionNoProto:
5108   case clang::Type::FunctionProto:
5109     break;
5110
5111   case clang::Type::IncompleteArray:
5112   case clang::Type::VariableArray:
5113     break;
5114
5115   case clang::Type::ConstantArray:
5116     break;
5117
5118   case clang::Type::DependentVector:
5119   case clang::Type::ExtVector:
5120   case clang::Type::Vector:
5121     // TODO: Set this to more than one???
5122     break;
5123
5124   case clang::Type::Builtin:
5125     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5126     case clang::BuiltinType::Void:
5127       break;
5128
5129     case clang::BuiltinType::Bool:
5130     case clang::BuiltinType::Char_S:
5131     case clang::BuiltinType::SChar:
5132     case clang::BuiltinType::WChar_S:
5133     case clang::BuiltinType::Short:
5134     case clang::BuiltinType::Int:
5135     case clang::BuiltinType::Long:
5136     case clang::BuiltinType::LongLong:
5137     case clang::BuiltinType::Int128:
5138       return lldb::eEncodingSint;
5139
5140     case clang::BuiltinType::Char_U:
5141     case clang::BuiltinType::UChar:
5142     case clang::BuiltinType::WChar_U:
5143     case clang::BuiltinType::Char8:
5144     case clang::BuiltinType::Char16:
5145     case clang::BuiltinType::Char32:
5146     case clang::BuiltinType::UShort:
5147     case clang::BuiltinType::UInt:
5148     case clang::BuiltinType::ULong:
5149     case clang::BuiltinType::ULongLong:
5150     case clang::BuiltinType::UInt128:
5151       return lldb::eEncodingUint;
5152
5153     // Fixed point types. Note that they are currently ignored.
5154     case clang::BuiltinType::ShortAccum:
5155     case clang::BuiltinType::Accum:
5156     case clang::BuiltinType::LongAccum:
5157     case clang::BuiltinType::UShortAccum:
5158     case clang::BuiltinType::UAccum:
5159     case clang::BuiltinType::ULongAccum:
5160     case clang::BuiltinType::ShortFract:
5161     case clang::BuiltinType::Fract:
5162     case clang::BuiltinType::LongFract:
5163     case clang::BuiltinType::UShortFract:
5164     case clang::BuiltinType::UFract:
5165     case clang::BuiltinType::ULongFract:
5166     case clang::BuiltinType::SatShortAccum:
5167     case clang::BuiltinType::SatAccum:
5168     case clang::BuiltinType::SatLongAccum:
5169     case clang::BuiltinType::SatUShortAccum:
5170     case clang::BuiltinType::SatUAccum:
5171     case clang::BuiltinType::SatULongAccum:
5172     case clang::BuiltinType::SatShortFract:
5173     case clang::BuiltinType::SatFract:
5174     case clang::BuiltinType::SatLongFract:
5175     case clang::BuiltinType::SatUShortFract:
5176     case clang::BuiltinType::SatUFract:
5177     case clang::BuiltinType::SatULongFract:
5178       break;
5179
5180     case clang::BuiltinType::Half:
5181     case clang::BuiltinType::Float:
5182     case clang::BuiltinType::Float16:
5183     case clang::BuiltinType::Float128:
5184     case clang::BuiltinType::Double:
5185     case clang::BuiltinType::LongDouble:
5186       return lldb::eEncodingIEEE754;
5187
5188     case clang::BuiltinType::ObjCClass:
5189     case clang::BuiltinType::ObjCId:
5190     case clang::BuiltinType::ObjCSel:
5191       return lldb::eEncodingUint;
5192
5193     case clang::BuiltinType::NullPtr:
5194       return lldb::eEncodingUint;
5195
5196     case clang::BuiltinType::Kind::ARCUnbridgedCast:
5197     case clang::BuiltinType::Kind::BoundMember:
5198     case clang::BuiltinType::Kind::BuiltinFn:
5199     case clang::BuiltinType::Kind::Dependent:
5200     case clang::BuiltinType::Kind::OCLClkEvent:
5201     case clang::BuiltinType::Kind::OCLEvent:
5202     case clang::BuiltinType::Kind::OCLImage1dRO:
5203     case clang::BuiltinType::Kind::OCLImage1dWO:
5204     case clang::BuiltinType::Kind::OCLImage1dRW:
5205     case clang::BuiltinType::Kind::OCLImage1dArrayRO:
5206     case clang::BuiltinType::Kind::OCLImage1dArrayWO:
5207     case clang::BuiltinType::Kind::OCLImage1dArrayRW:
5208     case clang::BuiltinType::Kind::OCLImage1dBufferRO:
5209     case clang::BuiltinType::Kind::OCLImage1dBufferWO:
5210     case clang::BuiltinType::Kind::OCLImage1dBufferRW:
5211     case clang::BuiltinType::Kind::OCLImage2dRO:
5212     case clang::BuiltinType::Kind::OCLImage2dWO:
5213     case clang::BuiltinType::Kind::OCLImage2dRW:
5214     case clang::BuiltinType::Kind::OCLImage2dArrayRO:
5215     case clang::BuiltinType::Kind::OCLImage2dArrayWO:
5216     case clang::BuiltinType::Kind::OCLImage2dArrayRW:
5217     case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO:
5218     case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO:
5219     case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW:
5220     case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO:
5221     case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO:
5222     case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW:
5223     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO:
5224     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO:
5225     case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW:
5226     case clang::BuiltinType::Kind::OCLImage2dDepthRO:
5227     case clang::BuiltinType::Kind::OCLImage2dDepthWO:
5228     case clang::BuiltinType::Kind::OCLImage2dDepthRW:
5229     case clang::BuiltinType::Kind::OCLImage2dMSAARO:
5230     case clang::BuiltinType::Kind::OCLImage2dMSAAWO:
5231     case clang::BuiltinType::Kind::OCLImage2dMSAARW:
5232     case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO:
5233     case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO:
5234     case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW:
5235     case clang::BuiltinType::Kind::OCLImage3dRO:
5236     case clang::BuiltinType::Kind::OCLImage3dWO:
5237     case clang::BuiltinType::Kind::OCLImage3dRW:
5238     case clang::BuiltinType::Kind::OCLQueue:
5239     case clang::BuiltinType::Kind::OCLReserveID:
5240     case clang::BuiltinType::Kind::OCLSampler:
5241     case clang::BuiltinType::Kind::OMPArraySection:
5242     case clang::BuiltinType::Kind::Overload:
5243     case clang::BuiltinType::Kind::PseudoObject:
5244     case clang::BuiltinType::Kind::UnknownAny:
5245       break;
5246
5247     case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
5248     case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
5249     case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
5250     case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
5251     case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
5252     case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
5253     case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
5254     case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
5255     case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout:
5256     case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout:
5257     case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin:
5258     case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin:
5259       break;
5260     }
5261     break;
5262   // All pointer types are represented as unsigned integer encodings. We may
5263   // nee to add a eEncodingPointer if we ever need to know the difference
5264   case clang::Type::ObjCObjectPointer:
5265   case clang::Type::BlockPointer:
5266   case clang::Type::Pointer:
5267   case clang::Type::LValueReference:
5268   case clang::Type::RValueReference:
5269   case clang::Type::MemberPointer:
5270     return lldb::eEncodingUint;
5271   case clang::Type::Complex: {
5272     lldb::Encoding encoding = lldb::eEncodingIEEE754;
5273     if (qual_type->isComplexType())
5274       encoding = lldb::eEncodingIEEE754;
5275     else {
5276       const clang::ComplexType *complex_type =
5277           qual_type->getAsComplexIntegerType();
5278       if (complex_type)
5279         encoding = CompilerType(getASTContext(), complex_type->getElementType())
5280                        .GetEncoding(count);
5281       else
5282         encoding = lldb::eEncodingSint;
5283     }
5284     count = 2;
5285     return encoding;
5286   }
5287
5288   case clang::Type::ObjCInterface:
5289     break;
5290   case clang::Type::Record:
5291     break;
5292   case clang::Type::Enum:
5293     return lldb::eEncodingSint;
5294   case clang::Type::Typedef:
5295     return CompilerType(getASTContext(),
5296                         llvm::cast<clang::TypedefType>(qual_type)
5297                             ->getDecl()
5298                             ->getUnderlyingType())
5299         .GetEncoding(count);
5300
5301   case clang::Type::Auto:
5302     return CompilerType(
5303                getASTContext(),
5304                llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
5305         .GetEncoding(count);
5306
5307   case clang::Type::Elaborated:
5308     return CompilerType(
5309                getASTContext(),
5310                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5311         .GetEncoding(count);
5312
5313   case clang::Type::Paren:
5314     return CompilerType(getASTContext(),
5315                         llvm::cast<clang::ParenType>(qual_type)->desugar())
5316         .GetEncoding(count);
5317   case clang::Type::TypeOfExpr:
5318     return CompilerType(getASTContext(),
5319                         llvm::cast<clang::TypeOfExprType>(qual_type)
5320                             ->getUnderlyingExpr()
5321                             ->getType())
5322         .GetEncoding(count);
5323   case clang::Type::TypeOf:
5324     return CompilerType(
5325                getASTContext(),
5326                llvm::cast<clang::TypeOfType>(qual_type)->getUnderlyingType())
5327         .GetEncoding(count);
5328   case clang::Type::Decltype:
5329     return CompilerType(
5330                getASTContext(),
5331                llvm::cast<clang::DecltypeType>(qual_type)->getUnderlyingType())
5332         .GetEncoding(count);
5333   case clang::Type::DependentSizedArray:
5334   case clang::Type::DependentSizedExtVector:
5335   case clang::Type::UnresolvedUsing:
5336   case clang::Type::Attributed:
5337   case clang::Type::TemplateTypeParm:
5338   case clang::Type::SubstTemplateTypeParm:
5339   case clang::Type::SubstTemplateTypeParmPack:
5340   case clang::Type::InjectedClassName:
5341   case clang::Type::DependentName:
5342   case clang::Type::DependentTemplateSpecialization:
5343   case clang::Type::PackExpansion:
5344   case clang::Type::ObjCObject:
5345
5346   case clang::Type::TemplateSpecialization:
5347   case clang::Type::DeducedTemplateSpecialization:
5348   case clang::Type::Atomic:
5349   case clang::Type::Adjusted:
5350   case clang::Type::Pipe:
5351     break;
5352
5353   // pointer type decayed from an array or function type.
5354   case clang::Type::Decayed:
5355     break;
5356   case clang::Type::ObjCTypeParam:
5357     break;
5358
5359   case clang::Type::DependentAddressSpace:
5360     break;
5361   case clang::Type::MacroQualified:
5362     break;
5363   }
5364   count = 0;
5365   return lldb::eEncodingInvalid;
5366 }
5367
5368 lldb::Format ClangASTContext::GetFormat(lldb::opaque_compiler_type_t type) {
5369   if (!type)
5370     return lldb::eFormatDefault;
5371
5372   clang::QualType qual_type(GetCanonicalQualType(type));
5373
5374   switch (qual_type->getTypeClass()) {
5375   case clang::Type::UnaryTransform:
5376     break;
5377
5378   case clang::Type::FunctionNoProto:
5379   case clang::Type::FunctionProto:
5380     break;
5381
5382   case clang::Type::IncompleteArray:
5383   case clang::Type::VariableArray:
5384     break;
5385
5386   case clang::Type::ConstantArray:
5387     return lldb::eFormatVoid; // no value
5388
5389   case clang::Type::DependentVector:
5390   case clang::Type::ExtVector:
5391   case clang::Type::Vector:
5392     break;
5393
5394   case clang::Type::Builtin:
5395     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5396     // default: assert(0 && "Unknown builtin type!");
5397     case clang::BuiltinType::UnknownAny:
5398     case clang::BuiltinType::Void:
5399     case clang::BuiltinType::BoundMember:
5400       break;
5401
5402     case clang::BuiltinType::Bool:
5403       return lldb::eFormatBoolean;
5404     case clang::BuiltinType::Char_S:
5405     case clang::BuiltinType::SChar:
5406     case clang::BuiltinType::WChar_S:
5407     case clang::BuiltinType::Char_U:
5408     case clang::BuiltinType::UChar:
5409     case clang::BuiltinType::WChar_U:
5410       return lldb::eFormatChar;
5411     case clang::BuiltinType::Char16:
5412       return lldb::eFormatUnicode16;
5413     case clang::BuiltinType::Char32:
5414       return lldb::eFormatUnicode32;
5415     case clang::BuiltinType::UShort:
5416       return lldb::eFormatUnsigned;
5417     case clang::BuiltinType::Short:
5418       return lldb::eFormatDecimal;
5419     case clang::BuiltinType::UInt:
5420       return lldb::eFormatUnsigned;
5421     case clang::BuiltinType::Int:
5422       return lldb::eFormatDecimal;
5423     case clang::BuiltinType::ULong:
5424       return lldb::eFormatUnsigned;
5425     case clang::BuiltinType::Long:
5426       return lldb::eFormatDecimal;
5427     case clang::BuiltinType::ULongLong:
5428       return lldb::eFormatUnsigned;
5429     case clang::BuiltinType::LongLong:
5430       return lldb::eFormatDecimal;
5431     case clang::BuiltinType::UInt128:
5432       return lldb::eFormatUnsigned;
5433     case clang::BuiltinType::Int128:
5434       return lldb::eFormatDecimal;
5435     case clang::BuiltinType::Half:
5436     case clang::BuiltinType::Float:
5437     case clang::BuiltinType::Double:
5438     case clang::BuiltinType::LongDouble:
5439       return lldb::eFormatFloat;
5440     default:
5441       return lldb::eFormatHex;
5442     }
5443     break;
5444   case clang::Type::ObjCObjectPointer:
5445     return lldb::eFormatHex;
5446   case clang::Type::BlockPointer:
5447     return lldb::eFormatHex;
5448   case clang::Type::Pointer:
5449     return lldb::eFormatHex;
5450   case clang::Type::LValueReference:
5451   case clang::Type::RValueReference:
5452     return lldb::eFormatHex;
5453   case clang::Type::MemberPointer:
5454     break;
5455   case clang::Type::Complex: {
5456     if (qual_type->isComplexType())
5457       return lldb::eFormatComplex;
5458     else
5459       return lldb::eFormatComplexInteger;
5460   }
5461   case clang::Type::ObjCInterface:
5462     break;
5463   case clang::Type::Record:
5464     break;
5465   case clang::Type::Enum:
5466     return lldb::eFormatEnum;
5467   case clang::Type::Typedef:
5468     return CompilerType(getASTContext(),
5469                         llvm::cast<clang::TypedefType>(qual_type)
5470                             ->getDecl()
5471                             ->getUnderlyingType())
5472         .GetFormat();
5473   case clang::Type::Auto:
5474     return CompilerType(getASTContext(),
5475                         llvm::cast<clang::AutoType>(qual_type)->desugar())
5476         .GetFormat();
5477   case clang::Type::Paren:
5478     return CompilerType(getASTContext(),
5479                         llvm::cast<clang::ParenType>(qual_type)->desugar())
5480         .GetFormat();
5481   case clang::Type::Elaborated:
5482     return CompilerType(
5483                getASTContext(),
5484                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5485         .GetFormat();
5486   case clang::Type::TypeOfExpr:
5487     return CompilerType(getASTContext(),
5488                         llvm::cast<clang::TypeOfExprType>(qual_type)
5489                             ->getUnderlyingExpr()
5490                             ->getType())
5491         .GetFormat();
5492   case clang::Type::TypeOf:
5493     return CompilerType(
5494                getASTContext(),
5495                llvm::cast<clang::TypeOfType>(qual_type)->getUnderlyingType())
5496         .GetFormat();
5497   case clang::Type::Decltype:
5498     return CompilerType(
5499                getASTContext(),
5500                llvm::cast<clang::DecltypeType>(qual_type)->getUnderlyingType())
5501         .GetFormat();
5502   case clang::Type::DependentSizedArray:
5503   case clang::Type::DependentSizedExtVector:
5504   case clang::Type::UnresolvedUsing:
5505   case clang::Type::Attributed:
5506   case clang::Type::TemplateTypeParm:
5507   case clang::Type::SubstTemplateTypeParm:
5508   case clang::Type::SubstTemplateTypeParmPack:
5509   case clang::Type::InjectedClassName:
5510   case clang::Type::DependentName:
5511   case clang::Type::DependentTemplateSpecialization:
5512   case clang::Type::PackExpansion:
5513   case clang::Type::ObjCObject:
5514
5515   case clang::Type::TemplateSpecialization:
5516   case clang::Type::DeducedTemplateSpecialization:
5517   case clang::Type::Atomic:
5518   case clang::Type::Adjusted:
5519   case clang::Type::Pipe:
5520     break;
5521
5522   // pointer type decayed from an array or function type.
5523   case clang::Type::Decayed:
5524     break;
5525   case clang::Type::ObjCTypeParam:
5526     break;
5527
5528   case clang::Type::DependentAddressSpace:
5529     break;
5530   case clang::Type::MacroQualified:
5531     break;
5532   }
5533   // We don't know hot to display this type...
5534   return lldb::eFormatBytes;
5535 }
5536
5537 static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl,
5538                              bool check_superclass) {
5539   while (class_interface_decl) {
5540     if (class_interface_decl->ivar_size() > 0)
5541       return true;
5542
5543     if (check_superclass)
5544       class_interface_decl = class_interface_decl->getSuperClass();
5545     else
5546       break;
5547   }
5548   return false;
5549 }
5550
5551 static Optional<SymbolFile::ArrayInfo>
5552 GetDynamicArrayInfo(ClangASTContext &ast, SymbolFile *sym_file,
5553                     clang::QualType qual_type,
5554                     const ExecutionContext *exe_ctx) {
5555   if (qual_type->isIncompleteArrayType())
5556     if (auto *metadata = ast.GetMetadata(qual_type.getAsOpaquePtr()))
5557       return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(),
5558                                                  exe_ctx);
5559   return llvm::None;
5560 }
5561
5562 uint32_t ClangASTContext::GetNumChildren(lldb::opaque_compiler_type_t type,
5563                                          bool omit_empty_base_classes,
5564                                          const ExecutionContext *exe_ctx) {
5565   if (!type)
5566     return 0;
5567
5568   uint32_t num_children = 0;
5569   clang::QualType qual_type(GetQualType(type));
5570   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5571   switch (type_class) {
5572   case clang::Type::Builtin:
5573     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5574     case clang::BuiltinType::ObjCId:    // child is Class
5575     case clang::BuiltinType::ObjCClass: // child is Class
5576       num_children = 1;
5577       break;
5578
5579     default:
5580       break;
5581     }
5582     break;
5583
5584   case clang::Type::Complex:
5585     return 0;
5586   case clang::Type::Record:
5587     if (GetCompleteQualType(getASTContext(), qual_type)) {
5588       const clang::RecordType *record_type =
5589           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5590       const clang::RecordDecl *record_decl = record_type->getDecl();
5591       assert(record_decl);
5592       const clang::CXXRecordDecl *cxx_record_decl =
5593           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
5594       if (cxx_record_decl) {
5595         if (omit_empty_base_classes) {
5596           // Check each base classes to see if it or any of its base classes
5597           // contain any fields. This can help limit the noise in variable
5598           // views by not having to show base classes that contain no members.
5599           clang::CXXRecordDecl::base_class_const_iterator base_class,
5600               base_class_end;
5601           for (base_class = cxx_record_decl->bases_begin(),
5602               base_class_end = cxx_record_decl->bases_end();
5603                base_class != base_class_end; ++base_class) {
5604             const clang::CXXRecordDecl *base_class_decl =
5605                 llvm::cast<clang::CXXRecordDecl>(
5606                     base_class->getType()
5607                         ->getAs<clang::RecordType>()
5608                         ->getDecl());
5609
5610             // Skip empty base classes
5611             if (!ClangASTContext::RecordHasFields(base_class_decl))
5612               continue;
5613
5614             num_children++;
5615           }
5616         } else {
5617           // Include all base classes
5618           num_children += cxx_record_decl->getNumBases();
5619         }
5620       }
5621       clang::RecordDecl::field_iterator field, field_end;
5622       for (field = record_decl->field_begin(),
5623           field_end = record_decl->field_end();
5624            field != field_end; ++field)
5625         ++num_children;
5626     }
5627     break;
5628
5629   case clang::Type::ObjCObject:
5630   case clang::Type::ObjCInterface:
5631     if (GetCompleteQualType(getASTContext(), qual_type)) {
5632       const clang::ObjCObjectType *objc_class_type =
5633           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5634       assert(objc_class_type);
5635       if (objc_class_type) {
5636         clang::ObjCInterfaceDecl *class_interface_decl =
5637             objc_class_type->getInterface();
5638
5639         if (class_interface_decl) {
5640
5641           clang::ObjCInterfaceDecl *superclass_interface_decl =
5642               class_interface_decl->getSuperClass();
5643           if (superclass_interface_decl) {
5644             if (omit_empty_base_classes) {
5645               if (ObjCDeclHasIVars(superclass_interface_decl, true))
5646                 ++num_children;
5647             } else
5648               ++num_children;
5649           }
5650
5651           num_children += class_interface_decl->ivar_size();
5652         }
5653       }
5654     }
5655     break;
5656
5657   case clang::Type::ObjCObjectPointer: {
5658     const clang::ObjCObjectPointerType *pointer_type =
5659         llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr());
5660     clang::QualType pointee_type = pointer_type->getPointeeType();
5661     uint32_t num_pointee_children =
5662         CompilerType(getASTContext(), pointee_type)
5663             .GetNumChildren(omit_empty_base_classes, exe_ctx);
5664     // If this type points to a simple type, then it has 1 child
5665     if (num_pointee_children == 0)
5666       num_children = 1;
5667     else
5668       num_children = num_pointee_children;
5669   } break;
5670
5671   case clang::Type::Vector:
5672   case clang::Type::ExtVector:
5673     num_children =
5674         llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements();
5675     break;
5676
5677   case clang::Type::ConstantArray:
5678     num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr())
5679                        ->getSize()
5680                        .getLimitedValue();
5681     break;
5682   case clang::Type::IncompleteArray:
5683     if (auto array_info =
5684             GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx))
5685       // Only 1-dimensional arrays are supported.
5686       num_children = array_info->element_orders.size()
5687                          ? array_info->element_orders.back()
5688                          : 0;
5689     break;
5690
5691   case clang::Type::Pointer: {
5692     const clang::PointerType *pointer_type =
5693         llvm::cast<clang::PointerType>(qual_type.getTypePtr());
5694     clang::QualType pointee_type(pointer_type->getPointeeType());
5695     uint32_t num_pointee_children =
5696         CompilerType(getASTContext(), pointee_type)
5697       .GetNumChildren(omit_empty_base_classes, exe_ctx);
5698     if (num_pointee_children == 0) {
5699       // We have a pointer to a pointee type that claims it has no children. We
5700       // will want to look at
5701       num_children = GetNumPointeeChildren(pointee_type);
5702     } else
5703       num_children = num_pointee_children;
5704   } break;
5705
5706   case clang::Type::LValueReference:
5707   case clang::Type::RValueReference: {
5708     const clang::ReferenceType *reference_type =
5709         llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
5710     clang::QualType pointee_type = reference_type->getPointeeType();
5711     uint32_t num_pointee_children =
5712         CompilerType(getASTContext(), pointee_type)
5713             .GetNumChildren(omit_empty_base_classes, exe_ctx);
5714     // If this type points to a simple type, then it has 1 child
5715     if (num_pointee_children == 0)
5716       num_children = 1;
5717     else
5718       num_children = num_pointee_children;
5719   } break;
5720
5721   case clang::Type::Typedef:
5722     num_children =
5723         CompilerType(getASTContext(), llvm::cast<clang::TypedefType>(qual_type)
5724                                           ->getDecl()
5725                                           ->getUnderlyingType())
5726             .GetNumChildren(omit_empty_base_classes, exe_ctx);
5727     break;
5728
5729   case clang::Type::Auto:
5730     num_children =
5731         CompilerType(getASTContext(),
5732                      llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
5733             .GetNumChildren(omit_empty_base_classes, exe_ctx);
5734     break;
5735
5736   case clang::Type::Elaborated:
5737     num_children =
5738         CompilerType(
5739             getASTContext(),
5740             llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5741             .GetNumChildren(omit_empty_base_classes, exe_ctx);
5742     break;
5743
5744   case clang::Type::Paren:
5745     num_children =
5746         CompilerType(getASTContext(),
5747                      llvm::cast<clang::ParenType>(qual_type)->desugar())
5748             .GetNumChildren(omit_empty_base_classes, exe_ctx);
5749     break;
5750   default:
5751     break;
5752   }
5753   return num_children;
5754 }
5755
5756 CompilerType ClangASTContext::GetBuiltinTypeByName(ConstString name) {
5757   return GetBasicType(GetBasicTypeEnumeration(name));
5758 }
5759
5760 lldb::BasicType
5761 ClangASTContext::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) {
5762   if (type) {
5763     clang::QualType qual_type(GetQualType(type));
5764     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5765     if (type_class == clang::Type::Builtin) {
5766       switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5767       case clang::BuiltinType::Void:
5768         return eBasicTypeVoid;
5769       case clang::BuiltinType::Bool:
5770         return eBasicTypeBool;
5771       case clang::BuiltinType::Char_S:
5772         return eBasicTypeSignedChar;
5773       case clang::BuiltinType::Char_U:
5774         return eBasicTypeUnsignedChar;
5775       case clang::BuiltinType::Char16:
5776         return eBasicTypeChar16;
5777       case clang::BuiltinType::Char32:
5778         return eBasicTypeChar32;
5779       case clang::BuiltinType::UChar:
5780         return eBasicTypeUnsignedChar;
5781       case clang::BuiltinType::SChar:
5782         return eBasicTypeSignedChar;
5783       case clang::BuiltinType::WChar_S:
5784         return eBasicTypeSignedWChar;
5785       case clang::BuiltinType::WChar_U:
5786         return eBasicTypeUnsignedWChar;
5787       case clang::BuiltinType::Short:
5788         return eBasicTypeShort;
5789       case clang::BuiltinType::UShort:
5790         return eBasicTypeUnsignedShort;
5791       case clang::BuiltinType::Int:
5792         return eBasicTypeInt;
5793       case clang::BuiltinType::UInt:
5794         return eBasicTypeUnsignedInt;
5795       case clang::BuiltinType::Long:
5796         return eBasicTypeLong;
5797       case clang::BuiltinType::ULong:
5798         return eBasicTypeUnsignedLong;
5799       case clang::BuiltinType::LongLong:
5800         return eBasicTypeLongLong;
5801       case clang::BuiltinType::ULongLong:
5802         return eBasicTypeUnsignedLongLong;
5803       case clang::BuiltinType::Int128:
5804         return eBasicTypeInt128;
5805       case clang::BuiltinType::UInt128:
5806         return eBasicTypeUnsignedInt128;
5807
5808       case clang::BuiltinType::Half:
5809         return eBasicTypeHalf;
5810       case clang::BuiltinType::Float:
5811         return eBasicTypeFloat;
5812       case clang::BuiltinType::Double:
5813         return eBasicTypeDouble;
5814       case clang::BuiltinType::LongDouble:
5815         return eBasicTypeLongDouble;
5816
5817       case clang::BuiltinType::NullPtr:
5818         return eBasicTypeNullPtr;
5819       case clang::BuiltinType::ObjCId:
5820         return eBasicTypeObjCID;
5821       case clang::BuiltinType::ObjCClass:
5822         return eBasicTypeObjCClass;
5823       case clang::BuiltinType::ObjCSel:
5824         return eBasicTypeObjCSel;
5825       default:
5826         return eBasicTypeOther;
5827       }
5828     }
5829   }
5830   return eBasicTypeInvalid;
5831 }
5832
5833 void ClangASTContext::ForEachEnumerator(
5834     lldb::opaque_compiler_type_t type,
5835     std::function<bool(const CompilerType &integer_type,
5836                        ConstString name,
5837                        const llvm::APSInt &value)> const &callback) {
5838   const clang::EnumType *enum_type =
5839       llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type));
5840   if (enum_type) {
5841     const clang::EnumDecl *enum_decl = enum_type->getDecl();
5842     if (enum_decl) {
5843       CompilerType integer_type(this,
5844                                 enum_decl->getIntegerType().getAsOpaquePtr());
5845
5846       clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
5847       for (enum_pos = enum_decl->enumerator_begin(),
5848           enum_end_pos = enum_decl->enumerator_end();
5849            enum_pos != enum_end_pos; ++enum_pos) {
5850         ConstString name(enum_pos->getNameAsString().c_str());
5851         if (!callback(integer_type, name, enum_pos->getInitVal()))
5852           break;
5853       }
5854     }
5855   }
5856 }
5857
5858 #pragma mark Aggregate Types
5859
5860 uint32_t ClangASTContext::GetNumFields(lldb::opaque_compiler_type_t type) {
5861   if (!type)
5862     return 0;
5863
5864   uint32_t count = 0;
5865   clang::QualType qual_type(GetCanonicalQualType(type));
5866   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5867   switch (type_class) {
5868   case clang::Type::Record:
5869     if (GetCompleteType(type)) {
5870       const clang::RecordType *record_type =
5871           llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
5872       if (record_type) {
5873         clang::RecordDecl *record_decl = record_type->getDecl();
5874         if (record_decl) {
5875           uint32_t field_idx = 0;
5876           clang::RecordDecl::field_iterator field, field_end;
5877           for (field = record_decl->field_begin(),
5878               field_end = record_decl->field_end();
5879                field != field_end; ++field)
5880             ++field_idx;
5881           count = field_idx;
5882         }
5883       }
5884     }
5885     break;
5886
5887   case clang::Type::Typedef:
5888     count =
5889         CompilerType(getASTContext(), llvm::cast<clang::TypedefType>(qual_type)
5890                                           ->getDecl()
5891                                           ->getUnderlyingType())
5892             .GetNumFields();
5893     break;
5894
5895   case clang::Type::Auto:
5896     count =
5897         CompilerType(getASTContext(),
5898                      llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
5899             .GetNumFields();
5900     break;
5901
5902   case clang::Type::Elaborated:
5903     count = CompilerType(
5904                 getASTContext(),
5905                 llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
5906                 .GetNumFields();
5907     break;
5908
5909   case clang::Type::Paren:
5910     count = CompilerType(getASTContext(),
5911                          llvm::cast<clang::ParenType>(qual_type)->desugar())
5912                 .GetNumFields();
5913     break;
5914
5915   case clang::Type::ObjCObjectPointer: {
5916     const clang::ObjCObjectPointerType *objc_class_type =
5917         qual_type->getAs<clang::ObjCObjectPointerType>();
5918     const clang::ObjCInterfaceType *objc_interface_type =
5919         objc_class_type->getInterfaceType();
5920     if (objc_interface_type &&
5921         GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5922             const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5923       clang::ObjCInterfaceDecl *class_interface_decl =
5924           objc_interface_type->getDecl();
5925       if (class_interface_decl) {
5926         count = class_interface_decl->ivar_size();
5927       }
5928     }
5929     break;
5930   }
5931
5932   case clang::Type::ObjCObject:
5933   case clang::Type::ObjCInterface:
5934     if (GetCompleteType(type)) {
5935       const clang::ObjCObjectType *objc_class_type =
5936           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5937       if (objc_class_type) {
5938         clang::ObjCInterfaceDecl *class_interface_decl =
5939             objc_class_type->getInterface();
5940
5941         if (class_interface_decl)
5942           count = class_interface_decl->ivar_size();
5943       }
5944     }
5945     break;
5946
5947   default:
5948     break;
5949   }
5950   return count;
5951 }
5952
5953 static lldb::opaque_compiler_type_t
5954 GetObjCFieldAtIndex(clang::ASTContext *ast,
5955                     clang::ObjCInterfaceDecl *class_interface_decl, size_t idx,
5956                     std::string &name, uint64_t *bit_offset_ptr,
5957                     uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) {
5958   if (class_interface_decl) {
5959     if (idx < (class_interface_decl->ivar_size())) {
5960       clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
5961           ivar_end = class_interface_decl->ivar_end();
5962       uint32_t ivar_idx = 0;
5963
5964       for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end;
5965            ++ivar_pos, ++ivar_idx) {
5966         if (ivar_idx == idx) {
5967           const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
5968
5969           clang::QualType ivar_qual_type(ivar_decl->getType());
5970
5971           name.assign(ivar_decl->getNameAsString());
5972
5973           if (bit_offset_ptr) {
5974             const clang::ASTRecordLayout &interface_layout =
5975                 ast->getASTObjCInterfaceLayout(class_interface_decl);
5976             *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx);
5977           }
5978
5979           const bool is_bitfield = ivar_pos->isBitField();
5980
5981           if (bitfield_bit_size_ptr) {
5982             *bitfield_bit_size_ptr = 0;
5983
5984             if (is_bitfield && ast) {
5985               clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
5986               clang::Expr::EvalResult result;
5987               if (bitfield_bit_size_expr &&
5988                   bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) {
5989                 llvm::APSInt bitfield_apsint = result.Val.getInt();
5990                 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5991               }
5992             }
5993           }
5994           if (is_bitfield_ptr)
5995             *is_bitfield_ptr = is_bitfield;
5996
5997           return ivar_qual_type.getAsOpaquePtr();
5998         }
5999       }
6000     }
6001   }
6002   return nullptr;
6003 }
6004
6005 CompilerType ClangASTContext::GetFieldAtIndex(lldb::opaque_compiler_type_t type,
6006                                               size_t idx, std::string &name,
6007                                               uint64_t *bit_offset_ptr,
6008                                               uint32_t *bitfield_bit_size_ptr,
6009                                               bool *is_bitfield_ptr) {
6010   if (!type)
6011     return CompilerType();
6012
6013   clang::QualType qual_type(GetCanonicalQualType(type));
6014   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6015   switch (type_class) {
6016   case clang::Type::Record:
6017     if (GetCompleteType(type)) {
6018       const clang::RecordType *record_type =
6019           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6020       const clang::RecordDecl *record_decl = record_type->getDecl();
6021       uint32_t field_idx = 0;
6022       clang::RecordDecl::field_iterator field, field_end;
6023       for (field = record_decl->field_begin(),
6024           field_end = record_decl->field_end();
6025            field != field_end; ++field, ++field_idx) {
6026         if (idx == field_idx) {
6027           // Print the member type if requested
6028           // Print the member name and equal sign
6029           name.assign(field->getNameAsString());
6030
6031           // Figure out the type byte size (field_type_info.first) and
6032           // alignment (field_type_info.second) from the AST context.
6033           if (bit_offset_ptr) {
6034             const clang::ASTRecordLayout &record_layout =
6035                 getASTContext()->getASTRecordLayout(record_decl);
6036             *bit_offset_ptr = record_layout.getFieldOffset(field_idx);
6037           }
6038
6039           const bool is_bitfield = field->isBitField();
6040
6041           if (bitfield_bit_size_ptr) {
6042             *bitfield_bit_size_ptr = 0;
6043
6044             if (is_bitfield) {
6045               clang::Expr *bitfield_bit_size_expr = field->getBitWidth();
6046               clang::Expr::EvalResult result;
6047               if (bitfield_bit_size_expr &&
6048                   bitfield_bit_size_expr->EvaluateAsInt(result,
6049                                                         *getASTContext())) {
6050                 llvm::APSInt bitfield_apsint = result.Val.getInt();
6051                 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
6052               }
6053             }
6054           }
6055           if (is_bitfield_ptr)
6056             *is_bitfield_ptr = is_bitfield;
6057
6058           return CompilerType(getASTContext(), field->getType());
6059         }
6060       }
6061     }
6062     break;
6063
6064   case clang::Type::ObjCObjectPointer: {
6065     const clang::ObjCObjectPointerType *objc_class_type =
6066         qual_type->getAs<clang::ObjCObjectPointerType>();
6067     const clang::ObjCInterfaceType *objc_interface_type =
6068         objc_class_type->getInterfaceType();
6069     if (objc_interface_type &&
6070         GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
6071             const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
6072       clang::ObjCInterfaceDecl *class_interface_decl =
6073           objc_interface_type->getDecl();
6074       if (class_interface_decl) {
6075         return CompilerType(
6076             this, GetObjCFieldAtIndex(getASTContext(), class_interface_decl,
6077                                       idx, name, bit_offset_ptr,
6078                                       bitfield_bit_size_ptr, is_bitfield_ptr));
6079       }
6080     }
6081     break;
6082   }
6083
6084   case clang::Type::ObjCObject:
6085   case clang::Type::ObjCInterface:
6086     if (GetCompleteType(type)) {
6087       const clang::ObjCObjectType *objc_class_type =
6088           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
6089       assert(objc_class_type);
6090       if (objc_class_type) {
6091         clang::ObjCInterfaceDecl *class_interface_decl =
6092             objc_class_type->getInterface();
6093         return CompilerType(
6094             this, GetObjCFieldAtIndex(getASTContext(), class_interface_decl,
6095                                       idx, name, bit_offset_ptr,
6096                                       bitfield_bit_size_ptr, is_bitfield_ptr));
6097       }
6098     }
6099     break;
6100
6101   case clang::Type::Typedef:
6102     return CompilerType(getASTContext(),
6103                         llvm::cast<clang::TypedefType>(qual_type)
6104                             ->getDecl()
6105                             ->getUnderlyingType())
6106         .GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
6107                          is_bitfield_ptr);
6108
6109   case clang::Type::Auto:
6110     return CompilerType(
6111                getASTContext(),
6112                llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
6113         .GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
6114                          is_bitfield_ptr);
6115
6116   case clang::Type::Elaborated:
6117     return CompilerType(
6118                getASTContext(),
6119                llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
6120         .GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
6121                          is_bitfield_ptr);
6122
6123   case clang::Type::Paren:
6124     return CompilerType(getASTContext(),
6125                         llvm::cast<clang::ParenType>(qual_type)->desugar())
6126         .GetFieldAtIndex(idx, name, bit_offset_ptr, bitfield_bit_size_ptr,
6127                          is_bitfield_ptr);
6128
6129   default:
6130     break;
6131   }
6132   return CompilerType();
6133 }
6134
6135 uint32_t
6136 ClangASTContext::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) {
6137   uint32_t count = 0;
6138   clang::QualType qual_type(GetCanonicalQualType(type));
6139   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6140   switch (type_class) {
6141   case clang::Type::Record:
6142     if (GetCompleteType(type)) {
6143       const clang::CXXRecordDecl *cxx_record_decl =
6144           qual_type->getAsCXXRecordDecl();
6145       if (cxx_record_decl)
6146         count = cxx_record_decl->getNumBases();
6147     }
6148     break;
6149
6150   case clang::Type::ObjCObjectPointer:
6151     count = GetPointeeType(type).GetNumDirectBaseClasses();
6152     break;
6153
6154   case clang::Type::ObjCObject:
6155     if (GetCompleteType(type)) {
6156       const clang::ObjCObjectType *objc_class_type =
6157           qual_type->getAsObjCQualifiedInterfaceType();
6158       if (objc_class_type) {
6159         clang::ObjCInterfaceDecl *class_interface_decl =
6160             objc_class_type->getInterface();
6161
6162         if (class_interface_decl && class_interface_decl->getSuperClass())
6163           count = 1;
6164       }
6165     }
6166     break;
6167   case clang::Type::ObjCInterface:
6168     if (GetCompleteType(type)) {
6169       const clang::ObjCInterfaceType *objc_interface_type =
6170           qual_type->getAs<clang::ObjCInterfaceType>();
6171       if (objc_interface_type) {
6172         clang::ObjCInterfaceDecl *class_interface_decl =
6173             objc_interface_type->getInterface();
6174
6175         if (class_interface_decl && class_interface_decl->getSuperClass())
6176           count = 1;
6177       }
6178     }
6179     break;
6180
6181   case clang::Type::Typedef:
6182     count = GetNumDirectBaseClasses(llvm::cast<clang::TypedefType>(qual_type)
6183                                         ->getDecl()
6184                                         ->getUnderlyingType()
6185                                         .getAsOpaquePtr());
6186     break;
6187
6188   case clang::Type::Auto:
6189     count = GetNumDirectBaseClasses(llvm::cast<clang::AutoType>(qual_type)
6190                                         ->getDeducedType()
6191                                         .getAsOpaquePtr());
6192     break;
6193
6194   case clang::Type::Elaborated:
6195     count = GetNumDirectBaseClasses(llvm::cast<clang::ElaboratedType>(qual_type)
6196                                         ->getNamedType()
6197                                         .getAsOpaquePtr());
6198     break;
6199
6200   case clang::Type::Paren:
6201     return GetNumDirectBaseClasses(
6202         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
6203
6204   default:
6205     break;
6206   }
6207   return count;
6208 }
6209
6210 uint32_t
6211 ClangASTContext::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) {
6212   uint32_t count = 0;
6213   clang::QualType qual_type(GetCanonicalQualType(type));
6214   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6215   switch (type_class) {
6216   case clang::Type::Record:
6217     if (GetCompleteType(type)) {
6218       const clang::CXXRecordDecl *cxx_record_decl =
6219           qual_type->getAsCXXRecordDecl();
6220       if (cxx_record_decl)
6221         count = cxx_record_decl->getNumVBases();
6222     }
6223     break;
6224
6225   case clang::Type::Typedef:
6226     count = GetNumVirtualBaseClasses(llvm::cast<clang::TypedefType>(qual_type)
6227                                          ->getDecl()
6228                                          ->getUnderlyingType()
6229                                          .getAsOpaquePtr());
6230     break;
6231
6232   case clang::Type::Auto:
6233     count = GetNumVirtualBaseClasses(llvm::cast<clang::AutoType>(qual_type)
6234                                          ->getDeducedType()
6235                                          .getAsOpaquePtr());
6236     break;
6237
6238   case clang::Type::Elaborated:
6239     count =
6240         GetNumVirtualBaseClasses(llvm::cast<clang::ElaboratedType>(qual_type)
6241                                      ->getNamedType()
6242                                      .getAsOpaquePtr());
6243     break;
6244
6245   case clang::Type::Paren:
6246     count = GetNumVirtualBaseClasses(
6247         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
6248     break;
6249
6250   default:
6251     break;
6252   }
6253   return count;
6254 }
6255
6256 CompilerType ClangASTContext::GetDirectBaseClassAtIndex(
6257     lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
6258   clang::QualType qual_type(GetCanonicalQualType(type));
6259   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6260   switch (type_class) {
6261   case clang::Type::Record:
6262     if (GetCompleteType(type)) {
6263       const clang::CXXRecordDecl *cxx_record_decl =
6264           qual_type->getAsCXXRecordDecl();
6265       if (cxx_record_decl) {
6266         uint32_t curr_idx = 0;
6267         clang::CXXRecordDecl::base_class_const_iterator base_class,
6268             base_class_end;
6269         for (base_class = cxx_record_decl->bases_begin(),
6270             base_class_end = cxx_record_decl->bases_end();
6271              base_class != base_class_end; ++base_class, ++curr_idx) {
6272           if (curr_idx == idx) {
6273             if (bit_offset_ptr) {
6274               const clang::ASTRecordLayout &record_layout =
6275                   getASTContext()->getASTRecordLayout(cxx_record_decl);
6276               const clang::CXXRecordDecl *base_class_decl =
6277                   llvm::cast<clang::CXXRecordDecl>(
6278                       base_class->getType()
6279                           ->getAs<clang::RecordType>()
6280                           ->getDecl());
6281               if (base_class->isVirtual())
6282                 *bit_offset_ptr =
6283                     record_layout.getVBaseClassOffset(base_class_decl)
6284                         .getQuantity() *
6285                     8;
6286               else
6287                 *bit_offset_ptr =
6288                     record_layout.getBaseClassOffset(base_class_decl)
6289                         .getQuantity() *
6290                     8;
6291             }
6292             return CompilerType(this, base_class->getType().getAsOpaquePtr());
6293           }
6294         }
6295       }
6296     }
6297     break;
6298
6299   case clang::Type::ObjCObjectPointer:
6300     return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr);
6301
6302   case clang::Type::ObjCObject:
6303     if (idx == 0 && GetCompleteType(type)) {
6304       const clang::ObjCObjectType *objc_class_type =
6305           qual_type->getAsObjCQualifiedInterfaceType();
6306       if (objc_class_type) {
6307         clang::ObjCInterfaceDecl *class_interface_decl =
6308             objc_class_type->getInterface();
6309
6310         if (class_interface_decl) {
6311           clang::ObjCInterfaceDecl *superclass_interface_decl =
6312               class_interface_decl->getSuperClass();
6313           if (superclass_interface_decl) {
6314             if (bit_offset_ptr)
6315               *bit_offset_ptr = 0;
6316             return CompilerType(getASTContext(),
6317                                 getASTContext()->getObjCInterfaceType(
6318                                     superclass_interface_decl));
6319           }
6320         }
6321       }
6322     }
6323     break;
6324   case clang::Type::ObjCInterface:
6325     if (idx == 0 && GetCompleteType(type)) {
6326       const clang::ObjCObjectType *objc_interface_type =
6327           qual_type->getAs<clang::ObjCInterfaceType>();
6328       if (objc_interface_type) {
6329         clang::ObjCInterfaceDecl *class_interface_decl =
6330             objc_interface_type->getInterface();
6331
6332         if (class_interface_decl) {
6333           clang::ObjCInterfaceDecl *superclass_interface_decl =
6334               class_interface_decl->getSuperClass();
6335           if (superclass_interface_decl) {
6336             if (bit_offset_ptr)
6337               *bit_offset_ptr = 0;
6338             return CompilerType(getASTContext(),
6339                                 getASTContext()->getObjCInterfaceType(
6340                                     superclass_interface_decl));
6341           }
6342         }
6343       }
6344     }
6345     break;
6346
6347   case clang::Type::Typedef:
6348     return GetDirectBaseClassAtIndex(llvm::cast<clang::TypedefType>(qual_type)
6349                                          ->getDecl()
6350                                          ->getUnderlyingType()
6351                                          .getAsOpaquePtr(),
6352                                      idx, bit_offset_ptr);
6353
6354   case clang::Type::Auto:
6355     return GetDirectBaseClassAtIndex(llvm::cast<clang::AutoType>(qual_type)
6356                                          ->getDeducedType()
6357                                          .getAsOpaquePtr(),
6358                                      idx, bit_offset_ptr);
6359
6360   case clang::Type::Elaborated:
6361     return GetDirectBaseClassAtIndex(
6362         llvm::cast<clang::ElaboratedType>(qual_type)
6363             ->getNamedType()
6364             .getAsOpaquePtr(),
6365         idx, bit_offset_ptr);
6366
6367   case clang::Type::Paren:
6368     return GetDirectBaseClassAtIndex(
6369         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
6370         idx, bit_offset_ptr);
6371
6372   default:
6373     break;
6374   }
6375   return CompilerType();
6376 }
6377
6378 CompilerType ClangASTContext::GetVirtualBaseClassAtIndex(
6379     lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
6380   clang::QualType qual_type(GetCanonicalQualType(type));
6381   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6382   switch (type_class) {
6383   case clang::Type::Record:
6384     if (GetCompleteType(type)) {
6385       const clang::CXXRecordDecl *cxx_record_decl =
6386           qual_type->getAsCXXRecordDecl();
6387       if (cxx_record_decl) {
6388         uint32_t curr_idx = 0;
6389         clang::CXXRecordDecl::base_class_const_iterator base_class,
6390             base_class_end;
6391         for (base_class = cxx_record_decl->vbases_begin(),
6392             base_class_end = cxx_record_decl->vbases_end();
6393              base_class != base_class_end; ++base_class, ++curr_idx) {
6394           if (curr_idx == idx) {
6395             if (bit_offset_ptr) {
6396               const clang::ASTRecordLayout &record_layout =
6397                   getASTContext()->getASTRecordLayout(cxx_record_decl);
6398               const clang::CXXRecordDecl *base_class_decl =
6399                   llvm::cast<clang::CXXRecordDecl>(
6400                       base_class->getType()
6401                           ->getAs<clang::RecordType>()
6402                           ->getDecl());
6403               *bit_offset_ptr =
6404                   record_layout.getVBaseClassOffset(base_class_decl)
6405                       .getQuantity() *
6406                   8;
6407             }
6408             return CompilerType(this, base_class->getType().getAsOpaquePtr());
6409           }
6410         }
6411       }
6412     }
6413     break;
6414
6415   case clang::Type::Typedef:
6416     return GetVirtualBaseClassAtIndex(llvm::cast<clang::TypedefType>(qual_type)
6417                                           ->getDecl()
6418                                           ->getUnderlyingType()
6419                                           .getAsOpaquePtr(),
6420                                       idx, bit_offset_ptr);
6421
6422   case clang::Type::Auto:
6423     return GetVirtualBaseClassAtIndex(llvm::cast<clang::AutoType>(qual_type)
6424                                           ->getDeducedType()
6425                                           .getAsOpaquePtr(),
6426                                       idx, bit_offset_ptr);
6427
6428   case clang::Type::Elaborated:
6429     return GetVirtualBaseClassAtIndex(
6430         llvm::cast<clang::ElaboratedType>(qual_type)
6431             ->getNamedType()
6432             .getAsOpaquePtr(),
6433         idx, bit_offset_ptr);
6434
6435   case clang::Type::Paren:
6436     return GetVirtualBaseClassAtIndex(
6437         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
6438         idx, bit_offset_ptr);
6439
6440   default:
6441     break;
6442   }
6443   return CompilerType();
6444 }
6445
6446 // If a pointer to a pointee type (the clang_type arg) says that it has no
6447 // children, then we either need to trust it, or override it and return a
6448 // different result. For example, an "int *" has one child that is an integer,
6449 // but a function pointer doesn't have any children. Likewise if a Record type
6450 // claims it has no children, then there really is nothing to show.
6451 uint32_t ClangASTContext::GetNumPointeeChildren(clang::QualType type) {
6452   if (type.isNull())
6453     return 0;
6454
6455   clang::QualType qual_type(type.getCanonicalType());
6456   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6457   switch (type_class) {
6458   case clang::Type::Builtin:
6459     switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
6460     case clang::BuiltinType::UnknownAny:
6461     case clang::BuiltinType::Void:
6462     case clang::BuiltinType::NullPtr:
6463     case clang::BuiltinType::OCLEvent:
6464     case clang::BuiltinType::OCLImage1dRO:
6465     case clang::BuiltinType::OCLImage1dWO:
6466     case clang::BuiltinType::OCLImage1dRW:
6467     case clang::BuiltinType::OCLImage1dArrayRO:
6468     case clang::BuiltinType::OCLImage1dArrayWO:
6469     case clang::BuiltinType::OCLImage1dArrayRW:
6470     case clang::BuiltinType::OCLImage1dBufferRO:
6471     case clang::BuiltinType::OCLImage1dBufferWO:
6472     case clang::BuiltinType::OCLImage1dBufferRW:
6473     case clang::BuiltinType::OCLImage2dRO:
6474     case clang::BuiltinType::OCLImage2dWO:
6475     case clang::BuiltinType::OCLImage2dRW:
6476     case clang::BuiltinType::OCLImage2dArrayRO:
6477     case clang::BuiltinType::OCLImage2dArrayWO:
6478     case clang::BuiltinType::OCLImage2dArrayRW:
6479     case clang::BuiltinType::OCLImage3dRO:
6480     case clang::BuiltinType::OCLImage3dWO:
6481     case clang::BuiltinType::OCLImage3dRW:
6482     case clang::BuiltinType::OCLSampler:
6483       return 0;
6484     case clang::BuiltinType::Bool:
6485     case clang::BuiltinType::Char_U:
6486     case clang::BuiltinType::UChar:
6487     case clang::BuiltinType::WChar_U:
6488     case clang::BuiltinType::Char16:
6489     case clang::BuiltinType::Char32:
6490     case clang::BuiltinType::UShort:
6491     case clang::BuiltinType::UInt:
6492     case clang::BuiltinType::ULong:
6493     case clang::BuiltinType::ULongLong:
6494     case clang::BuiltinType::UInt128:
6495     case clang::BuiltinType::Char_S:
6496     case clang::BuiltinType::SChar:
6497     case clang::BuiltinType::WChar_S:
6498     case clang::BuiltinType::Short:
6499     case clang::BuiltinType::Int:
6500     case clang::BuiltinType::Long:
6501     case clang::BuiltinType::LongLong:
6502     case clang::BuiltinType::Int128:
6503     case clang::BuiltinType::Float:
6504     case clang::BuiltinType::Double:
6505     case clang::BuiltinType::LongDouble:
6506     case clang::BuiltinType::Dependent:
6507     case clang::BuiltinType::Overload:
6508     case clang::BuiltinType::ObjCId:
6509     case clang::BuiltinType::ObjCClass:
6510     case clang::BuiltinType::ObjCSel:
6511     case clang::BuiltinType::BoundMember:
6512     case clang::BuiltinType::Half:
6513     case clang::BuiltinType::ARCUnbridgedCast:
6514     case clang::BuiltinType::PseudoObject:
6515     case clang::BuiltinType::BuiltinFn:
6516     case clang::BuiltinType::OMPArraySection:
6517       return 1;
6518     default:
6519       return 0;
6520     }
6521     break;
6522
6523   case clang::Type::Complex:
6524     return 1;
6525   case clang::Type::Pointer:
6526     return 1;
6527   case clang::Type::BlockPointer:
6528     return 0; // If block pointers don't have debug info, then no children for
6529               // them
6530   case clang::Type::LValueReference:
6531     return 1;
6532   case clang::Type::RValueReference:
6533     return 1;
6534   case clang::Type::MemberPointer:
6535     return 0;
6536   case clang::Type::ConstantArray:
6537     return 0;
6538   case clang::Type::IncompleteArray:
6539     return 0;
6540   case clang::Type::VariableArray:
6541     return 0;
6542   case clang::Type::DependentSizedArray:
6543     return 0;
6544   case clang::Type::DependentSizedExtVector:
6545     return 0;
6546   case clang::Type::Vector:
6547     return 0;
6548   case clang::Type::ExtVector:
6549     return 0;
6550   case clang::Type::FunctionProto:
6551     return 0; // When we function pointers, they have no children...
6552   case clang::Type::FunctionNoProto:
6553     return 0; // When we function pointers, they have no children...
6554   case clang::Type::UnresolvedUsing:
6555     return 0;
6556   case clang::Type::Paren:
6557     return GetNumPointeeChildren(
6558         llvm::cast<clang::ParenType>(qual_type)->desugar());
6559   case clang::Type::Typedef:
6560     return GetNumPointeeChildren(llvm::cast<clang::TypedefType>(qual_type)
6561                                      ->getDecl()
6562                                      ->getUnderlyingType());
6563   case clang::Type::Auto:
6564     return GetNumPointeeChildren(
6565         llvm::cast<clang::AutoType>(qual_type)->getDeducedType());
6566   case clang::Type::Elaborated:
6567     return GetNumPointeeChildren(
6568         llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType());
6569   case clang::Type::TypeOfExpr:
6570     return GetNumPointeeChildren(llvm::cast<clang::TypeOfExprType>(qual_type)
6571                                      ->getUnderlyingExpr()
6572                                      ->getType());
6573   case clang::Type::TypeOf:
6574     return GetNumPointeeChildren(
6575         llvm::cast<clang::TypeOfType>(qual_type)->getUnderlyingType());
6576   case clang::Type::Decltype:
6577     return GetNumPointeeChildren(
6578         llvm::cast<clang::DecltypeType>(qual_type)->getUnderlyingType());
6579   case clang::Type::Record:
6580     return 0;
6581   case clang::Type::Enum:
6582     return 1;
6583   case clang::Type::TemplateTypeParm:
6584     return 1;
6585   case clang::Type::SubstTemplateTypeParm:
6586     return 1;
6587   case clang::Type::TemplateSpecialization:
6588     return 1;
6589   case clang::Type::InjectedClassName:
6590     return 0;
6591   case clang::Type::DependentName:
6592     return 1;
6593   case clang::Type::DependentTemplateSpecialization:
6594     return 1;
6595   case clang::Type::ObjCObject:
6596     return 0;
6597   case clang::Type::ObjCInterface:
6598     return 0;
6599   case clang::Type::ObjCObjectPointer:
6600     return 1;
6601   default:
6602     break;
6603   }
6604   return 0;
6605 }
6606
6607 CompilerType ClangASTContext::GetChildCompilerTypeAtIndex(
6608     lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
6609     bool transparent_pointers, bool omit_empty_base_classes,
6610     bool ignore_array_bounds, std::string &child_name,
6611     uint32_t &child_byte_size, int32_t &child_byte_offset,
6612     uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
6613     bool &child_is_base_class, bool &child_is_deref_of_parent,
6614     ValueObject *valobj, uint64_t &language_flags) {
6615   if (!type)
6616     return CompilerType();
6617
6618   auto get_exe_scope = [&exe_ctx]() {
6619     return exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
6620   };
6621
6622   clang::QualType parent_qual_type(GetCanonicalQualType(type));
6623   const clang::Type::TypeClass parent_type_class =
6624       parent_qual_type->getTypeClass();
6625   child_bitfield_bit_size = 0;
6626   child_bitfield_bit_offset = 0;
6627   child_is_base_class = false;
6628   language_flags = 0;
6629
6630   const bool idx_is_valid =
6631       idx < GetNumChildren(type, omit_empty_base_classes, exe_ctx);
6632   int32_t bit_offset;
6633   switch (parent_type_class) {
6634   case clang::Type::Builtin:
6635     if (idx_is_valid) {
6636       switch (llvm::cast<clang::BuiltinType>(parent_qual_type)->getKind()) {
6637       case clang::BuiltinType::ObjCId:
6638       case clang::BuiltinType::ObjCClass:
6639         child_name = "isa";
6640         child_byte_size =
6641             getASTContext()->getTypeSize(getASTContext()->ObjCBuiltinClassTy) /
6642             CHAR_BIT;
6643         return CompilerType(getASTContext(),
6644                             getASTContext()->ObjCBuiltinClassTy);
6645
6646       default:
6647         break;
6648       }
6649     }
6650     break;
6651
6652   case clang::Type::Record:
6653     if (idx_is_valid && GetCompleteType(type)) {
6654       const clang::RecordType *record_type =
6655           llvm::cast<clang::RecordType>(parent_qual_type.getTypePtr());
6656       const clang::RecordDecl *record_decl = record_type->getDecl();
6657       assert(record_decl);
6658       const clang::ASTRecordLayout &record_layout =
6659           getASTContext()->getASTRecordLayout(record_decl);
6660       uint32_t child_idx = 0;
6661
6662       const clang::CXXRecordDecl *cxx_record_decl =
6663           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6664       if (cxx_record_decl) {
6665         // We might have base classes to print out first
6666         clang::CXXRecordDecl::base_class_const_iterator base_class,
6667             base_class_end;
6668         for (base_class = cxx_record_decl->bases_begin(),
6669             base_class_end = cxx_record_decl->bases_end();
6670              base_class != base_class_end; ++base_class) {
6671           const clang::CXXRecordDecl *base_class_decl = nullptr;
6672
6673           // Skip empty base classes
6674           if (omit_empty_base_classes) {
6675             base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6676                 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6677             if (!ClangASTContext::RecordHasFields(base_class_decl))
6678               continue;
6679           }
6680
6681           if (idx == child_idx) {
6682             if (base_class_decl == nullptr)
6683               base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6684                   base_class->getType()->getAs<clang::RecordType>()->getDecl());
6685
6686             if (base_class->isVirtual()) {
6687               bool handled = false;
6688               if (valobj) {
6689                 clang::VTableContextBase *vtable_ctx =
6690                     getASTContext()->getVTableContext();
6691                 if (vtable_ctx)
6692                   handled = GetVBaseBitOffset(*vtable_ctx, *valobj,
6693                                               record_layout, cxx_record_decl,
6694                                               base_class_decl, bit_offset);
6695               }
6696               if (!handled)
6697                 bit_offset = record_layout.getVBaseClassOffset(base_class_decl)
6698                                  .getQuantity() *
6699                              8;
6700             } else
6701               bit_offset = record_layout.getBaseClassOffset(base_class_decl)
6702                                .getQuantity() *
6703                            8;
6704
6705             // Base classes should be a multiple of 8 bits in size
6706             child_byte_offset = bit_offset / 8;
6707             CompilerType base_class_clang_type(getASTContext(),
6708                                                base_class->getType());
6709             child_name = base_class_clang_type.GetTypeName().AsCString("");
6710             Optional<uint64_t> size =
6711                 base_class_clang_type.GetBitSize(get_exe_scope());
6712             if (!size)
6713               return {};
6714             uint64_t base_class_clang_type_bit_size = *size;
6715
6716             // Base classes bit sizes should be a multiple of 8 bits in size
6717             assert(base_class_clang_type_bit_size % 8 == 0);
6718             child_byte_size = base_class_clang_type_bit_size / 8;
6719             child_is_base_class = true;
6720             return base_class_clang_type;
6721           }
6722           // We don't increment the child index in the for loop since we might
6723           // be skipping empty base classes
6724           ++child_idx;
6725         }
6726       }
6727       // Make sure index is in range...
6728       uint32_t field_idx = 0;
6729       clang::RecordDecl::field_iterator field, field_end;
6730       for (field = record_decl->field_begin(),
6731           field_end = record_decl->field_end();
6732            field != field_end; ++field, ++field_idx, ++child_idx) {
6733         if (idx == child_idx) {
6734           // Print the member type if requested
6735           // Print the member name and equal sign
6736           child_name.assign(field->getNameAsString());
6737
6738           // Figure out the type byte size (field_type_info.first) and
6739           // alignment (field_type_info.second) from the AST context.
6740           CompilerType field_clang_type(getASTContext(), field->getType());
6741           assert(field_idx < record_layout.getFieldCount());
6742           Optional<uint64_t> size =
6743               field_clang_type.GetByteSize(get_exe_scope());
6744           if (!size)
6745             return {};
6746           child_byte_size = *size;
6747           const uint32_t child_bit_size = child_byte_size * 8;
6748
6749           // Figure out the field offset within the current struct/union/class
6750           // type
6751           bit_offset = record_layout.getFieldOffset(field_idx);
6752           if (ClangASTContext::FieldIsBitfield(getASTContext(), *field,
6753                                                child_bitfield_bit_size)) {
6754             child_bitfield_bit_offset = bit_offset % child_bit_size;
6755             const uint32_t child_bit_offset =
6756                 bit_offset - child_bitfield_bit_offset;
6757             child_byte_offset = child_bit_offset / 8;
6758           } else {
6759             child_byte_offset = bit_offset / 8;
6760           }
6761
6762           return field_clang_type;
6763         }
6764       }
6765     }
6766     break;
6767
6768   case clang::Type::ObjCObject:
6769   case clang::Type::ObjCInterface:
6770     if (idx_is_valid && GetCompleteType(type)) {
6771       const clang::ObjCObjectType *objc_class_type =
6772           llvm::dyn_cast<clang::ObjCObjectType>(parent_qual_type.getTypePtr());
6773       assert(objc_class_type);
6774       if (objc_class_type) {
6775         uint32_t child_idx = 0;
6776         clang::ObjCInterfaceDecl *class_interface_decl =
6777             objc_class_type->getInterface();
6778
6779         if (class_interface_decl) {
6780
6781           const clang::ASTRecordLayout &interface_layout =
6782               getASTContext()->getASTObjCInterfaceLayout(class_interface_decl);
6783           clang::ObjCInterfaceDecl *superclass_interface_decl =
6784               class_interface_decl->getSuperClass();
6785           if (superclass_interface_decl) {
6786             if (omit_empty_base_classes) {
6787               CompilerType base_class_clang_type(
6788                   getASTContext(), getASTContext()->getObjCInterfaceType(
6789                                        superclass_interface_decl));
6790               if (base_class_clang_type.GetNumChildren(omit_empty_base_classes,
6791                                                        exe_ctx) > 0) {
6792                 if (idx == 0) {
6793                   clang::QualType ivar_qual_type(
6794                       getASTContext()->getObjCInterfaceType(
6795                           superclass_interface_decl));
6796
6797                   child_name.assign(
6798                       superclass_interface_decl->getNameAsString());
6799
6800                   clang::TypeInfo ivar_type_info =
6801                       getASTContext()->getTypeInfo(ivar_qual_type.getTypePtr());
6802
6803                   child_byte_size = ivar_type_info.Width / 8;
6804                   child_byte_offset = 0;
6805                   child_is_base_class = true;
6806
6807                   return CompilerType(getASTContext(), ivar_qual_type);
6808                 }
6809
6810                 ++child_idx;
6811               }
6812             } else
6813               ++child_idx;
6814           }
6815
6816           const uint32_t superclass_idx = child_idx;
6817
6818           if (idx < (child_idx + class_interface_decl->ivar_size())) {
6819             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6820                 ivar_end = class_interface_decl->ivar_end();
6821
6822             for (ivar_pos = class_interface_decl->ivar_begin();
6823                  ivar_pos != ivar_end; ++ivar_pos) {
6824               if (child_idx == idx) {
6825                 clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6826
6827                 clang::QualType ivar_qual_type(ivar_decl->getType());
6828
6829                 child_name.assign(ivar_decl->getNameAsString());
6830
6831                 clang::TypeInfo ivar_type_info =
6832                     getASTContext()->getTypeInfo(ivar_qual_type.getTypePtr());
6833
6834                 child_byte_size = ivar_type_info.Width / 8;
6835
6836                 // Figure out the field offset within the current
6837                 // struct/union/class type For ObjC objects, we can't trust the
6838                 // bit offset we get from the Clang AST, since that doesn't
6839                 // account for the space taken up by unbacked properties, or
6840                 // from the changing size of base classes that are newer than
6841                 // this class. So if we have a process around that we can ask
6842                 // about this object, do so.
6843                 child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
6844                 Process *process = nullptr;
6845                 if (exe_ctx)
6846                   process = exe_ctx->GetProcessPtr();
6847                 if (process) {
6848                   ObjCLanguageRuntime *objc_runtime =
6849                       ObjCLanguageRuntime::Get(*process);
6850                   if (objc_runtime != nullptr) {
6851                     CompilerType parent_ast_type(getASTContext(),
6852                                                  parent_qual_type);
6853                     child_byte_offset = objc_runtime->GetByteOffsetForIvar(
6854                         parent_ast_type, ivar_decl->getNameAsString().c_str());
6855                   }
6856                 }
6857
6858                 // Setting this to INT32_MAX to make sure we don't compute it
6859                 // twice...
6860                 bit_offset = INT32_MAX;
6861
6862                 if (child_byte_offset ==
6863                     static_cast<int32_t>(LLDB_INVALID_IVAR_OFFSET)) {
6864                   bit_offset = interface_layout.getFieldOffset(child_idx -
6865                                                                superclass_idx);
6866                   child_byte_offset = bit_offset / 8;
6867                 }
6868
6869                 // Note, the ObjC Ivar Byte offset is just that, it doesn't
6870                 // account for the bit offset of a bitfield within its
6871                 // containing object.  So regardless of where we get the byte
6872                 // offset from, we still need to get the bit offset for
6873                 // bitfields from the layout.
6874
6875                 if (ClangASTContext::FieldIsBitfield(getASTContext(), ivar_decl,
6876                                                      child_bitfield_bit_size)) {
6877                   if (bit_offset == INT32_MAX)
6878                     bit_offset = interface_layout.getFieldOffset(
6879                         child_idx - superclass_idx);
6880
6881                   child_bitfield_bit_offset = bit_offset % 8;
6882                 }
6883                 return CompilerType(getASTContext(), ivar_qual_type);
6884               }
6885               ++child_idx;
6886             }
6887           }
6888         }
6889       }
6890     }
6891     break;
6892
6893   case clang::Type::ObjCObjectPointer:
6894     if (idx_is_valid) {
6895       CompilerType pointee_clang_type(GetPointeeType(type));
6896
6897       if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6898         child_is_deref_of_parent = false;
6899         bool tmp_child_is_deref_of_parent = false;
6900         return pointee_clang_type.GetChildCompilerTypeAtIndex(
6901             exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6902             ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6903             child_bitfield_bit_size, child_bitfield_bit_offset,
6904             child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6905             language_flags);
6906       } else {
6907         child_is_deref_of_parent = true;
6908         const char *parent_name =
6909             valobj ? valobj->GetName().GetCString() : nullptr;
6910         if (parent_name) {
6911           child_name.assign(1, '*');
6912           child_name += parent_name;
6913         }
6914
6915         // We have a pointer to an simple type
6916         if (idx == 0 && pointee_clang_type.GetCompleteType()) {
6917           if (Optional<uint64_t> size =
6918                   pointee_clang_type.GetByteSize(get_exe_scope())) {
6919             child_byte_size = *size;
6920             child_byte_offset = 0;
6921             return pointee_clang_type;
6922           }
6923         }
6924       }
6925     }
6926     break;
6927
6928   case clang::Type::Vector:
6929   case clang::Type::ExtVector:
6930     if (idx_is_valid) {
6931       const clang::VectorType *array =
6932           llvm::cast<clang::VectorType>(parent_qual_type.getTypePtr());
6933       if (array) {
6934         CompilerType element_type(getASTContext(), array->getElementType());
6935         if (element_type.GetCompleteType()) {
6936           char element_name[64];
6937           ::snprintf(element_name, sizeof(element_name), "[%" PRIu64 "]",
6938                      static_cast<uint64_t>(idx));
6939           child_name.assign(element_name);
6940           if (Optional<uint64_t> size =
6941                   element_type.GetByteSize(get_exe_scope())) {
6942             child_byte_size = *size;
6943             child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6944             return element_type;
6945           }
6946         }
6947       }
6948     }
6949     break;
6950
6951   case clang::Type::ConstantArray:
6952   case clang::Type::IncompleteArray:
6953     if (ignore_array_bounds || idx_is_valid) {
6954       const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe();
6955       if (array) {
6956         CompilerType element_type(getASTContext(), array->getElementType());
6957         if (element_type.GetCompleteType()) {
6958           child_name = llvm::formatv("[{0}]", idx);
6959           if (Optional<uint64_t> size =
6960                   element_type.GetByteSize(get_exe_scope())) {
6961             child_byte_size = *size;
6962             child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6963             return element_type;
6964           }
6965         }
6966       }
6967     }
6968     break;
6969
6970   case clang::Type::Pointer: {
6971     CompilerType pointee_clang_type(GetPointeeType(type));
6972
6973     // Don't dereference "void *" pointers
6974     if (pointee_clang_type.IsVoidType())
6975       return CompilerType();
6976
6977     if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6978       child_is_deref_of_parent = false;
6979       bool tmp_child_is_deref_of_parent = false;
6980       return pointee_clang_type.GetChildCompilerTypeAtIndex(
6981           exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6982           ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6983           child_bitfield_bit_size, child_bitfield_bit_offset,
6984           child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6985           language_flags);
6986     } else {
6987       child_is_deref_of_parent = true;
6988
6989       const char *parent_name =
6990           valobj ? valobj->GetName().GetCString() : nullptr;
6991       if (parent_name) {
6992         child_name.assign(1, '*');
6993         child_name += parent_name;
6994       }
6995
6996       // We have a pointer to an simple type
6997       if (idx == 0) {
6998         if (Optional<uint64_t> size =
6999                 pointee_clang_type.GetByteSize(get_exe_scope())) {
7000           child_byte_size = *size;
7001           child_byte_offset = 0;
7002           return pointee_clang_type;
7003         }
7004       }
7005     }
7006     break;
7007   }
7008
7009   case clang::Type::LValueReference:
7010   case clang::Type::RValueReference:
7011     if (idx_is_valid) {
7012       const clang::ReferenceType *reference_type =
7013           llvm::cast<clang::ReferenceType>(parent_qual_type.getTypePtr());
7014       CompilerType pointee_clang_type(getASTContext(),
7015                                       reference_type->getPointeeType());
7016       if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
7017         child_is_deref_of_parent = false;
7018         bool tmp_child_is_deref_of_parent = false;
7019         return pointee_clang_type.GetChildCompilerTypeAtIndex(
7020             exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
7021             ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
7022             child_bitfield_bit_size, child_bitfield_bit_offset,
7023             child_is_base_class, tmp_child_is_deref_of_parent, valobj,
7024             language_flags);
7025       } else {
7026         const char *parent_name =
7027             valobj ? valobj->GetName().GetCString() : nullptr;
7028         if (parent_name) {
7029           child_name.assign(1, '&');
7030           child_name += parent_name;
7031         }
7032
7033         // We have a pointer to an simple type
7034         if (idx == 0) {
7035           if (Optional<uint64_t> size =
7036                   pointee_clang_type.GetByteSize(get_exe_scope())) {
7037             child_byte_size = *size;
7038             child_byte_offset = 0;
7039             return pointee_clang_type;
7040           }
7041         }
7042       }
7043     }
7044     break;
7045
7046   case clang::Type::Typedef: {
7047     CompilerType typedefed_clang_type(
7048         getASTContext(), llvm::cast<clang::TypedefType>(parent_qual_type)
7049                              ->getDecl()
7050                              ->getUnderlyingType());
7051     return typedefed_clang_type.GetChildCompilerTypeAtIndex(
7052         exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
7053         ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
7054         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
7055         child_is_deref_of_parent, valobj, language_flags);
7056   } break;
7057
7058   case clang::Type::Auto: {
7059     CompilerType elaborated_clang_type(
7060         getASTContext(),
7061         llvm::cast<clang::AutoType>(parent_qual_type)->getDeducedType());
7062     return elaborated_clang_type.GetChildCompilerTypeAtIndex(
7063         exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
7064         ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
7065         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
7066         child_is_deref_of_parent, valobj, language_flags);
7067   }
7068
7069   case clang::Type::Elaborated: {
7070     CompilerType elaborated_clang_type(
7071         getASTContext(),
7072         llvm::cast<clang::ElaboratedType>(parent_qual_type)->getNamedType());
7073     return elaborated_clang_type.GetChildCompilerTypeAtIndex(
7074         exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
7075         ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
7076         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
7077         child_is_deref_of_parent, valobj, language_flags);
7078   }
7079
7080   case clang::Type::Paren: {
7081     CompilerType paren_clang_type(
7082         getASTContext(),
7083         llvm::cast<clang::ParenType>(parent_qual_type)->desugar());
7084     return paren_clang_type.GetChildCompilerTypeAtIndex(
7085         exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
7086         ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
7087         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
7088         child_is_deref_of_parent, valobj, language_flags);
7089   }
7090
7091   default:
7092     break;
7093   }
7094   return CompilerType();
7095 }
7096
7097 static uint32_t GetIndexForRecordBase(const clang::RecordDecl *record_decl,
7098                                       const clang::CXXBaseSpecifier *base_spec,
7099                                       bool omit_empty_base_classes) {
7100   uint32_t child_idx = 0;
7101
7102   const clang::CXXRecordDecl *cxx_record_decl =
7103       llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
7104
7105   //    const char *super_name = record_decl->getNameAsCString();
7106   //    const char *base_name =
7107   //    base_spec->getType()->getAs<clang::RecordType>()->getDecl()->getNameAsCString();
7108   //    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
7109   //
7110   if (cxx_record_decl) {
7111     clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
7112     for (base_class = cxx_record_decl->bases_begin(),
7113         base_class_end = cxx_record_decl->bases_end();
7114          base_class != base_class_end; ++base_class) {
7115       if (omit_empty_base_classes) {
7116         if (BaseSpecifierIsEmpty(base_class))
7117           continue;
7118       }
7119
7120       //            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
7121       //            super_name, base_name,
7122       //                    child_idx,
7123       //                    base_class->getType()->getAs<clang::RecordType>()->getDecl()->getNameAsCString());
7124       //
7125       //
7126       if (base_class == base_spec)
7127         return child_idx;
7128       ++child_idx;
7129     }
7130   }
7131
7132   return UINT32_MAX;
7133 }
7134
7135 static uint32_t GetIndexForRecordChild(const clang::RecordDecl *record_decl,
7136                                        clang::NamedDecl *canonical_decl,
7137                                        bool omit_empty_base_classes) {
7138   uint32_t child_idx = ClangASTContext::GetNumBaseClasses(
7139       llvm::dyn_cast<clang::CXXRecordDecl>(record_decl),
7140       omit_empty_base_classes);
7141
7142   clang::RecordDecl::field_iterator field, field_end;
7143   for (field = record_decl->field_begin(), field_end = record_decl->field_end();
7144        field != field_end; ++field, ++child_idx) {
7145     if (field->getCanonicalDecl() == canonical_decl)
7146       return child_idx;
7147   }
7148
7149   return UINT32_MAX;
7150 }
7151
7152 // Look for a child member (doesn't include base classes, but it does include
7153 // their members) in the type hierarchy. Returns an index path into
7154 // "clang_type" on how to reach the appropriate member.
7155 //
7156 //    class A
7157 //    {
7158 //    public:
7159 //        int m_a;
7160 //        int m_b;
7161 //    };
7162 //
7163 //    class B
7164 //    {
7165 //    };
7166 //
7167 //    class C :
7168 //        public B,
7169 //        public A
7170 //    {
7171 //    };
7172 //
7173 // If we have a clang type that describes "class C", and we wanted to looked
7174 // "m_b" in it:
7175 //
7176 // With omit_empty_base_classes == false we would get an integer array back
7177 // with: { 1,  1 } The first index 1 is the child index for "class A" within
7178 // class C The second index 1 is the child index for "m_b" within class A
7179 //
7180 // With omit_empty_base_classes == true we would get an integer array back
7181 // with: { 0,  1 } The first index 0 is the child index for "class A" within
7182 // class C (since class B doesn't have any members it doesn't count) The second
7183 // index 1 is the child index for "m_b" within class A
7184
7185 size_t ClangASTContext::GetIndexOfChildMemberWithName(
7186     lldb::opaque_compiler_type_t type, const char *name,
7187     bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) {
7188   if (type && name && name[0]) {
7189     clang::QualType qual_type(GetCanonicalQualType(type));
7190     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7191     switch (type_class) {
7192     case clang::Type::Record:
7193       if (GetCompleteType(type)) {
7194         const clang::RecordType *record_type =
7195             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
7196         const clang::RecordDecl *record_decl = record_type->getDecl();
7197
7198         assert(record_decl);
7199         uint32_t child_idx = 0;
7200
7201         const clang::CXXRecordDecl *cxx_record_decl =
7202             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
7203
7204         // Try and find a field that matches NAME
7205         clang::RecordDecl::field_iterator field, field_end;
7206         llvm::StringRef name_sref(name);
7207         for (field = record_decl->field_begin(),
7208             field_end = record_decl->field_end();
7209              field != field_end; ++field, ++child_idx) {
7210           llvm::StringRef field_name = field->getName();
7211           if (field_name.empty()) {
7212             CompilerType field_type(getASTContext(), field->getType());
7213             child_indexes.push_back(child_idx);
7214             if (field_type.GetIndexOfChildMemberWithName(
7215                     name, omit_empty_base_classes, child_indexes))
7216               return child_indexes.size();
7217             child_indexes.pop_back();
7218
7219           } else if (field_name.equals(name_sref)) {
7220             // We have to add on the number of base classes to this index!
7221             child_indexes.push_back(
7222                 child_idx + ClangASTContext::GetNumBaseClasses(
7223                                 cxx_record_decl, omit_empty_base_classes));
7224             return child_indexes.size();
7225           }
7226         }
7227
7228         if (cxx_record_decl) {
7229           const clang::RecordDecl *parent_record_decl = cxx_record_decl;
7230
7231           // printf ("parent = %s\n", parent_record_decl->getNameAsCString());
7232
7233           // const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
7234           // Didn't find things easily, lets let clang do its thang...
7235           clang::IdentifierInfo &ident_ref =
7236               getASTContext()->Idents.get(name_sref);
7237           clang::DeclarationName decl_name(&ident_ref);
7238
7239           clang::CXXBasePaths paths;
7240           if (cxx_record_decl->lookupInBases(
7241                   [decl_name](const clang::CXXBaseSpecifier *specifier,
7242                               clang::CXXBasePath &path) {
7243                     return clang::CXXRecordDecl::FindOrdinaryMember(
7244                         specifier, path, decl_name);
7245                   },
7246                   paths)) {
7247             clang::CXXBasePaths::const_paths_iterator path,
7248                 path_end = paths.end();
7249             for (path = paths.begin(); path != path_end; ++path) {
7250               const size_t num_path_elements = path->size();
7251               for (size_t e = 0; e < num_path_elements; ++e) {
7252                 clang::CXXBasePathElement elem = (*path)[e];
7253
7254                 child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base,
7255                                                   omit_empty_base_classes);
7256                 if (child_idx == UINT32_MAX) {
7257                   child_indexes.clear();
7258                   return 0;
7259                 } else {
7260                   child_indexes.push_back(child_idx);
7261                   parent_record_decl = llvm::cast<clang::RecordDecl>(
7262                       elem.Base->getType()
7263                           ->getAs<clang::RecordType>()
7264                           ->getDecl());
7265                 }
7266               }
7267               for (clang::NamedDecl *path_decl : path->Decls) {
7268                 child_idx = GetIndexForRecordChild(
7269                     parent_record_decl, path_decl, omit_empty_base_classes);
7270                 if (child_idx == UINT32_MAX) {
7271                   child_indexes.clear();
7272                   return 0;
7273                 } else {
7274                   child_indexes.push_back(child_idx);
7275                 }
7276               }
7277             }
7278             return child_indexes.size();
7279           }
7280         }
7281       }
7282       break;
7283
7284     case clang::Type::ObjCObject:
7285     case clang::Type::ObjCInterface:
7286       if (GetCompleteType(type)) {
7287         llvm::StringRef name_sref(name);
7288         const clang::ObjCObjectType *objc_class_type =
7289             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
7290         assert(objc_class_type);
7291         if (objc_class_type) {
7292           uint32_t child_idx = 0;
7293           clang::ObjCInterfaceDecl *class_interface_decl =
7294               objc_class_type->getInterface();
7295
7296           if (class_interface_decl) {
7297             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
7298                 ivar_end = class_interface_decl->ivar_end();
7299             clang::ObjCInterfaceDecl *superclass_interface_decl =
7300                 class_interface_decl->getSuperClass();
7301
7302             for (ivar_pos = class_interface_decl->ivar_begin();
7303                  ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
7304               const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
7305
7306               if (ivar_decl->getName().equals(name_sref)) {
7307                 if ((!omit_empty_base_classes && superclass_interface_decl) ||
7308                     (omit_empty_base_classes &&
7309                      ObjCDeclHasIVars(superclass_interface_decl, true)))
7310                   ++child_idx;
7311
7312                 child_indexes.push_back(child_idx);
7313                 return child_indexes.size();
7314               }
7315             }
7316
7317             if (superclass_interface_decl) {
7318               // The super class index is always zero for ObjC classes, so we
7319               // push it onto the child indexes in case we find an ivar in our
7320               // superclass...
7321               child_indexes.push_back(0);
7322
7323               CompilerType superclass_clang_type(
7324                   getASTContext(), getASTContext()->getObjCInterfaceType(
7325                                        superclass_interface_decl));
7326               if (superclass_clang_type.GetIndexOfChildMemberWithName(
7327                       name, omit_empty_base_classes, child_indexes)) {
7328                 // We did find an ivar in a superclass so just return the
7329                 // results!
7330                 return child_indexes.size();
7331               }
7332
7333               // We didn't find an ivar matching "name" in our superclass, pop
7334               // the superclass zero index that we pushed on above.
7335               child_indexes.pop_back();
7336             }
7337           }
7338         }
7339       }
7340       break;
7341
7342     case clang::Type::ObjCObjectPointer: {
7343       CompilerType objc_object_clang_type(
7344           getASTContext(),
7345           llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
7346               ->getPointeeType());
7347       return objc_object_clang_type.GetIndexOfChildMemberWithName(
7348           name, omit_empty_base_classes, child_indexes);
7349     } break;
7350
7351     case clang::Type::ConstantArray: {
7352       //                const clang::ConstantArrayType *array =
7353       //                llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
7354       //                const uint64_t element_count =
7355       //                array->getSize().getLimitedValue();
7356       //
7357       //                if (idx < element_count)
7358       //                {
7359       //                    std::pair<uint64_t, unsigned> field_type_info =
7360       //                    ast->getTypeInfo(array->getElementType());
7361       //
7362       //                    char element_name[32];
7363       //                    ::snprintf (element_name, sizeof (element_name),
7364       //                    "%s[%u]", parent_name ? parent_name : "", idx);
7365       //
7366       //                    child_name.assign(element_name);
7367       //                    assert(field_type_info.first % 8 == 0);
7368       //                    child_byte_size = field_type_info.first / 8;
7369       //                    child_byte_offset = idx * child_byte_size;
7370       //                    return array->getElementType().getAsOpaquePtr();
7371       //                }
7372     } break;
7373
7374     //        case clang::Type::MemberPointerType:
7375     //            {
7376     //                MemberPointerType *mem_ptr_type =
7377     //                llvm::cast<MemberPointerType>(qual_type.getTypePtr());
7378     //                clang::QualType pointee_type =
7379     //                mem_ptr_type->getPointeeType();
7380     //
7381     //                if (ClangASTContext::IsAggregateType
7382     //                (pointee_type.getAsOpaquePtr()))
7383     //                {
7384     //                    return GetIndexOfChildWithName (ast,
7385     //                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
7386     //                                                    name);
7387     //                }
7388     //            }
7389     //            break;
7390     //
7391     case clang::Type::LValueReference:
7392     case clang::Type::RValueReference: {
7393       const clang::ReferenceType *reference_type =
7394           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
7395       clang::QualType pointee_type(reference_type->getPointeeType());
7396       CompilerType pointee_clang_type(getASTContext(), pointee_type);
7397
7398       if (pointee_clang_type.IsAggregateType()) {
7399         return pointee_clang_type.GetIndexOfChildMemberWithName(
7400             name, omit_empty_base_classes, child_indexes);
7401       }
7402     } break;
7403
7404     case clang::Type::Pointer: {
7405       CompilerType pointee_clang_type(GetPointeeType(type));
7406
7407       if (pointee_clang_type.IsAggregateType()) {
7408         return pointee_clang_type.GetIndexOfChildMemberWithName(
7409             name, omit_empty_base_classes, child_indexes);
7410       }
7411     } break;
7412
7413     case clang::Type::Typedef:
7414       return CompilerType(getASTContext(),
7415                           llvm::cast<clang::TypedefType>(qual_type)
7416                               ->getDecl()
7417                               ->getUnderlyingType())
7418           .GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
7419                                          child_indexes);
7420
7421     case clang::Type::Auto:
7422       return CompilerType(
7423                  getASTContext(),
7424                  llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
7425           .GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
7426                                          child_indexes);
7427
7428     case clang::Type::Elaborated:
7429       return CompilerType(
7430                  getASTContext(),
7431                  llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
7432           .GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
7433                                          child_indexes);
7434
7435     case clang::Type::Paren:
7436       return CompilerType(getASTContext(),
7437                           llvm::cast<clang::ParenType>(qual_type)->desugar())
7438           .GetIndexOfChildMemberWithName(name, omit_empty_base_classes,
7439                                          child_indexes);
7440
7441     default:
7442       break;
7443     }
7444   }
7445   return 0;
7446 }
7447
7448 // Get the index of the child of "clang_type" whose name matches. This function
7449 // doesn't descend into the children, but only looks one level deep and name
7450 // matches can include base class names.
7451
7452 uint32_t
7453 ClangASTContext::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
7454                                          const char *name,
7455                                          bool omit_empty_base_classes) {
7456   if (type && name && name[0]) {
7457     clang::QualType qual_type(GetCanonicalQualType(type));
7458
7459     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7460
7461     switch (type_class) {
7462     case clang::Type::Record:
7463       if (GetCompleteType(type)) {
7464         const clang::RecordType *record_type =
7465             llvm::cast<clang::RecordType>(qual_type.getTypePtr());
7466         const clang::RecordDecl *record_decl = record_type->getDecl();
7467
7468         assert(record_decl);
7469         uint32_t child_idx = 0;
7470
7471         const clang::CXXRecordDecl *cxx_record_decl =
7472             llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
7473
7474         if (cxx_record_decl) {
7475           clang::CXXRecordDecl::base_class_const_iterator base_class,
7476               base_class_end;
7477           for (base_class = cxx_record_decl->bases_begin(),
7478               base_class_end = cxx_record_decl->bases_end();
7479                base_class != base_class_end; ++base_class) {
7480             // Skip empty base classes
7481             clang::CXXRecordDecl *base_class_decl =
7482                 llvm::cast<clang::CXXRecordDecl>(
7483                     base_class->getType()
7484                         ->getAs<clang::RecordType>()
7485                         ->getDecl());
7486             if (omit_empty_base_classes &&
7487                 !ClangASTContext::RecordHasFields(base_class_decl))
7488               continue;
7489
7490             CompilerType base_class_clang_type(getASTContext(),
7491                                                base_class->getType());
7492             std::string base_class_type_name(
7493                 base_class_clang_type.GetTypeName().AsCString(""));
7494             if (base_class_type_name == name)
7495               return child_idx;
7496             ++child_idx;
7497           }
7498         }
7499
7500         // Try and find a field that matches NAME
7501         clang::RecordDecl::field_iterator field, field_end;
7502         llvm::StringRef name_sref(name);
7503         for (field = record_decl->field_begin(),
7504             field_end = record_decl->field_end();
7505              field != field_end; ++field, ++child_idx) {
7506           if (field->getName().equals(name_sref))
7507             return child_idx;
7508         }
7509       }
7510       break;
7511
7512     case clang::Type::ObjCObject:
7513     case clang::Type::ObjCInterface:
7514       if (GetCompleteType(type)) {
7515         llvm::StringRef name_sref(name);
7516         const clang::ObjCObjectType *objc_class_type =
7517             llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
7518         assert(objc_class_type);
7519         if (objc_class_type) {
7520           uint32_t child_idx = 0;
7521           clang::ObjCInterfaceDecl *class_interface_decl =
7522               objc_class_type->getInterface();
7523
7524           if (class_interface_decl) {
7525             clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
7526                 ivar_end = class_interface_decl->ivar_end();
7527             clang::ObjCInterfaceDecl *superclass_interface_decl =
7528                 class_interface_decl->getSuperClass();
7529
7530             for (ivar_pos = class_interface_decl->ivar_begin();
7531                  ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
7532               const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
7533
7534               if (ivar_decl->getName().equals(name_sref)) {
7535                 if ((!omit_empty_base_classes && superclass_interface_decl) ||
7536                     (omit_empty_base_classes &&
7537                      ObjCDeclHasIVars(superclass_interface_decl, true)))
7538                   ++child_idx;
7539
7540                 return child_idx;
7541               }
7542             }
7543
7544             if (superclass_interface_decl) {
7545               if (superclass_interface_decl->getName().equals(name_sref))
7546                 return 0;
7547             }
7548           }
7549         }
7550       }
7551       break;
7552
7553     case clang::Type::ObjCObjectPointer: {
7554       CompilerType pointee_clang_type(
7555           getASTContext(),
7556           llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
7557               ->getPointeeType());
7558       return pointee_clang_type.GetIndexOfChildWithName(
7559           name, omit_empty_base_classes);
7560     } break;
7561
7562     case clang::Type::ConstantArray: {
7563       //                const clang::ConstantArrayType *array =
7564       //                llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
7565       //                const uint64_t element_count =
7566       //                array->getSize().getLimitedValue();
7567       //
7568       //                if (idx < element_count)
7569       //                {
7570       //                    std::pair<uint64_t, unsigned> field_type_info =
7571       //                    ast->getTypeInfo(array->getElementType());
7572       //
7573       //                    char element_name[32];
7574       //                    ::snprintf (element_name, sizeof (element_name),
7575       //                    "%s[%u]", parent_name ? parent_name : "", idx);
7576       //
7577       //                    child_name.assign(element_name);
7578       //                    assert(field_type_info.first % 8 == 0);
7579       //                    child_byte_size = field_type_info.first / 8;
7580       //                    child_byte_offset = idx * child_byte_size;
7581       //                    return array->getElementType().getAsOpaquePtr();
7582       //                }
7583     } break;
7584
7585     //        case clang::Type::MemberPointerType:
7586     //            {
7587     //                MemberPointerType *mem_ptr_type =
7588     //                llvm::cast<MemberPointerType>(qual_type.getTypePtr());
7589     //                clang::QualType pointee_type =
7590     //                mem_ptr_type->getPointeeType();
7591     //
7592     //                if (ClangASTContext::IsAggregateType
7593     //                (pointee_type.getAsOpaquePtr()))
7594     //                {
7595     //                    return GetIndexOfChildWithName (ast,
7596     //                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
7597     //                                                    name);
7598     //                }
7599     //            }
7600     //            break;
7601     //
7602     case clang::Type::LValueReference:
7603     case clang::Type::RValueReference: {
7604       const clang::ReferenceType *reference_type =
7605           llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
7606       CompilerType pointee_type(getASTContext(),
7607                                 reference_type->getPointeeType());
7608
7609       if (pointee_type.IsAggregateType()) {
7610         return pointee_type.GetIndexOfChildWithName(name,
7611                                                     omit_empty_base_classes);
7612       }
7613     } break;
7614
7615     case clang::Type::Pointer: {
7616       const clang::PointerType *pointer_type =
7617           llvm::cast<clang::PointerType>(qual_type.getTypePtr());
7618       CompilerType pointee_type(getASTContext(),
7619                                 pointer_type->getPointeeType());
7620
7621       if (pointee_type.IsAggregateType()) {
7622         return pointee_type.GetIndexOfChildWithName(name,
7623                                                     omit_empty_base_classes);
7624       } else {
7625         //                    if (parent_name)
7626         //                    {
7627         //                        child_name.assign(1, '*');
7628         //                        child_name += parent_name;
7629         //                    }
7630         //
7631         //                    // We have a pointer to an simple type
7632         //                    if (idx == 0)
7633         //                    {
7634         //                        std::pair<uint64_t, unsigned> clang_type_info
7635         //                        = ast->getTypeInfo(pointee_type);
7636         //                        assert(clang_type_info.first % 8 == 0);
7637         //                        child_byte_size = clang_type_info.first / 8;
7638         //                        child_byte_offset = 0;
7639         //                        return pointee_type.getAsOpaquePtr();
7640         //                    }
7641       }
7642     } break;
7643
7644     case clang::Type::Auto:
7645       return CompilerType(
7646                  getASTContext(),
7647                  llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
7648           .GetIndexOfChildWithName(name, omit_empty_base_classes);
7649
7650     case clang::Type::Elaborated:
7651       return CompilerType(
7652                  getASTContext(),
7653                  llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
7654           .GetIndexOfChildWithName(name, omit_empty_base_classes);
7655
7656     case clang::Type::Paren:
7657       return CompilerType(getASTContext(),
7658                           llvm::cast<clang::ParenType>(qual_type)->desugar())
7659           .GetIndexOfChildWithName(name, omit_empty_base_classes);
7660
7661     case clang::Type::Typedef:
7662       return CompilerType(getASTContext(),
7663                           llvm::cast<clang::TypedefType>(qual_type)
7664                               ->getDecl()
7665                               ->getUnderlyingType())
7666           .GetIndexOfChildWithName(name, omit_empty_base_classes);
7667
7668     default:
7669       break;
7670     }
7671   }
7672   return UINT32_MAX;
7673 }
7674
7675 size_t
7676 ClangASTContext::GetNumTemplateArguments(lldb::opaque_compiler_type_t type) {
7677   if (!type)
7678     return 0;
7679
7680   clang::QualType qual_type(GetCanonicalQualType(type));
7681   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7682   switch (type_class) {
7683   case clang::Type::Record:
7684     if (GetCompleteType(type)) {
7685       const clang::CXXRecordDecl *cxx_record_decl =
7686           qual_type->getAsCXXRecordDecl();
7687       if (cxx_record_decl) {
7688         const clang::ClassTemplateSpecializationDecl *template_decl =
7689             llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7690                 cxx_record_decl);
7691         if (template_decl)
7692           return template_decl->getTemplateArgs().size();
7693       }
7694     }
7695     break;
7696
7697   case clang::Type::Typedef:
7698     return (CompilerType(getASTContext(),
7699                          llvm::cast<clang::TypedefType>(qual_type)
7700                              ->getDecl()
7701                              ->getUnderlyingType()))
7702         .GetNumTemplateArguments();
7703
7704   case clang::Type::Auto:
7705     return (CompilerType(
7706                 getASTContext(),
7707                 llvm::cast<clang::AutoType>(qual_type)->getDeducedType()))
7708         .GetNumTemplateArguments();
7709
7710   case clang::Type::Elaborated:
7711     return (CompilerType(
7712                 getASTContext(),
7713                 llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType()))
7714         .GetNumTemplateArguments();
7715
7716   case clang::Type::Paren:
7717     return (CompilerType(getASTContext(),
7718                          llvm::cast<clang::ParenType>(qual_type)->desugar()))
7719         .GetNumTemplateArguments();
7720
7721   default:
7722     break;
7723   }
7724
7725   return 0;
7726 }
7727
7728 const clang::ClassTemplateSpecializationDecl *
7729 ClangASTContext::GetAsTemplateSpecialization(
7730     lldb::opaque_compiler_type_t type) {
7731   if (!type)
7732     return nullptr;
7733
7734   clang::QualType qual_type(GetCanonicalQualType(type));
7735   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7736   switch (type_class) {
7737   case clang::Type::Record: {
7738     if (! GetCompleteType(type))
7739       return nullptr;
7740     const clang::CXXRecordDecl *cxx_record_decl =
7741         qual_type->getAsCXXRecordDecl();
7742     if (!cxx_record_decl)
7743       return nullptr;
7744     return llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
7745         cxx_record_decl);
7746   }
7747
7748   case clang::Type::Typedef:
7749     return GetAsTemplateSpecialization(llvm::cast<clang::TypedefType>(qual_type)
7750                                            ->getDecl()
7751                                            ->getUnderlyingType()
7752                                            .getAsOpaquePtr());
7753
7754   case clang::Type::Auto:
7755     return GetAsTemplateSpecialization(llvm::cast<clang::AutoType>(qual_type)
7756                                            ->getDeducedType()
7757                                            .getAsOpaquePtr());
7758
7759   case clang::Type::Elaborated:
7760     return GetAsTemplateSpecialization(
7761         llvm::cast<clang::ElaboratedType>(qual_type)
7762             ->getNamedType()
7763             .getAsOpaquePtr());
7764
7765   case clang::Type::Paren:
7766     return GetAsTemplateSpecialization(
7767         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr());
7768
7769   default:
7770     return nullptr;
7771   }
7772 }
7773
7774 lldb::TemplateArgumentKind
7775 ClangASTContext::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
7776                                          size_t arg_idx) {
7777   const clang::ClassTemplateSpecializationDecl *template_decl =
7778       GetAsTemplateSpecialization(type);
7779   if (! template_decl || arg_idx >= template_decl->getTemplateArgs().size())
7780     return eTemplateArgumentKindNull;
7781
7782   switch (template_decl->getTemplateArgs()[arg_idx].getKind()) {
7783   case clang::TemplateArgument::Null:
7784     return eTemplateArgumentKindNull;
7785
7786   case clang::TemplateArgument::NullPtr:
7787     return eTemplateArgumentKindNullPtr;
7788
7789   case clang::TemplateArgument::Type:
7790     return eTemplateArgumentKindType;
7791
7792   case clang::TemplateArgument::Declaration:
7793     return eTemplateArgumentKindDeclaration;
7794
7795   case clang::TemplateArgument::Integral:
7796     return eTemplateArgumentKindIntegral;
7797
7798   case clang::TemplateArgument::Template:
7799     return eTemplateArgumentKindTemplate;
7800
7801   case clang::TemplateArgument::TemplateExpansion:
7802     return eTemplateArgumentKindTemplateExpansion;
7803
7804   case clang::TemplateArgument::Expression:
7805     return eTemplateArgumentKindExpression;
7806
7807   case clang::TemplateArgument::Pack:
7808     return eTemplateArgumentKindPack;
7809   }
7810   llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind");
7811 }
7812
7813 CompilerType
7814 ClangASTContext::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
7815                                          size_t idx) {
7816   const clang::ClassTemplateSpecializationDecl *template_decl =
7817       GetAsTemplateSpecialization(type);
7818   if (!template_decl || idx >= template_decl->getTemplateArgs().size())
7819     return CompilerType();
7820
7821   const clang::TemplateArgument &template_arg =
7822       template_decl->getTemplateArgs()[idx];
7823   if (template_arg.getKind() != clang::TemplateArgument::Type)
7824     return CompilerType();
7825
7826   return CompilerType(getASTContext(), template_arg.getAsType());
7827 }
7828
7829 Optional<CompilerType::IntegralTemplateArgument>
7830 ClangASTContext::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
7831                                              size_t idx) {
7832   const clang::ClassTemplateSpecializationDecl *template_decl =
7833       GetAsTemplateSpecialization(type);
7834   if (! template_decl || idx >= template_decl->getTemplateArgs().size())
7835     return llvm::None;
7836
7837   const clang::TemplateArgument &template_arg =
7838       template_decl->getTemplateArgs()[idx];
7839   if (template_arg.getKind() != clang::TemplateArgument::Integral)
7840     return llvm::None;
7841
7842   return {{template_arg.getAsIntegral(),
7843            CompilerType(getASTContext(), template_arg.getIntegralType())}};
7844 }
7845
7846 CompilerType ClangASTContext::GetTypeForFormatters(void *type) {
7847   if (type)
7848     return ClangUtil::RemoveFastQualifiers(CompilerType(this, type));
7849   return CompilerType();
7850 }
7851
7852 clang::EnumDecl *ClangASTContext::GetAsEnumDecl(const CompilerType &type) {
7853   const clang::EnumType *enutype =
7854       llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type));
7855   if (enutype)
7856     return enutype->getDecl();
7857   return nullptr;
7858 }
7859
7860 clang::RecordDecl *ClangASTContext::GetAsRecordDecl(const CompilerType &type) {
7861   const clang::RecordType *record_type =
7862       llvm::dyn_cast<clang::RecordType>(ClangUtil::GetCanonicalQualType(type));
7863   if (record_type)
7864     return record_type->getDecl();
7865   return nullptr;
7866 }
7867
7868 clang::TagDecl *ClangASTContext::GetAsTagDecl(const CompilerType &type) {
7869   return ClangUtil::GetAsTagDecl(type);
7870 }
7871
7872 clang::TypedefNameDecl *
7873 ClangASTContext::GetAsTypedefDecl(const CompilerType &type) {
7874   const clang::TypedefType *typedef_type =
7875       llvm::dyn_cast<clang::TypedefType>(ClangUtil::GetQualType(type));
7876   if (typedef_type)
7877     return typedef_type->getDecl();
7878   return nullptr;
7879 }
7880
7881 clang::CXXRecordDecl *
7882 ClangASTContext::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) {
7883   return GetCanonicalQualType(type)->getAsCXXRecordDecl();
7884 }
7885
7886 clang::ObjCInterfaceDecl *
7887 ClangASTContext::GetAsObjCInterfaceDecl(const CompilerType &type) {
7888   const clang::ObjCObjectType *objc_class_type =
7889       llvm::dyn_cast<clang::ObjCObjectType>(
7890           ClangUtil::GetCanonicalQualType(type));
7891   if (objc_class_type)
7892     return objc_class_type->getInterface();
7893   return nullptr;
7894 }
7895
7896 clang::FieldDecl *ClangASTContext::AddFieldToRecordType(
7897     const CompilerType &type, llvm::StringRef name,
7898     const CompilerType &field_clang_type, AccessType access,
7899     uint32_t bitfield_bit_size) {
7900   if (!type.IsValid() || !field_clang_type.IsValid())
7901     return nullptr;
7902   ClangASTContext *ast =
7903       llvm::dyn_cast_or_null<ClangASTContext>(type.GetTypeSystem());
7904   if (!ast)
7905     return nullptr;
7906   clang::ASTContext *clang_ast = ast->getASTContext();
7907   clang::IdentifierInfo *ident = nullptr;
7908   if (!name.empty())
7909     ident = &clang_ast->Idents.get(name);
7910
7911   clang::FieldDecl *field = nullptr;
7912
7913   clang::Expr *bit_width = nullptr;
7914   if (bitfield_bit_size != 0) {
7915     llvm::APInt bitfield_bit_size_apint(
7916         clang_ast->getTypeSize(clang_ast->IntTy), bitfield_bit_size);
7917     bit_width = new (*clang_ast)
7918         clang::IntegerLiteral(*clang_ast, bitfield_bit_size_apint,
7919                               clang_ast->IntTy, clang::SourceLocation());
7920   }
7921
7922   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7923   if (record_decl) {
7924     field = clang::FieldDecl::Create(
7925         *clang_ast, record_decl, clang::SourceLocation(),
7926         clang::SourceLocation(),
7927         ident,                                    // Identifier
7928         ClangUtil::GetQualType(field_clang_type), // Field type
7929         nullptr,                                  // TInfo *
7930         bit_width,                                // BitWidth
7931         false,                                    // Mutable
7932         clang::ICIS_NoInit);                      // HasInit
7933
7934     if (name.empty()) {
7935       // Determine whether this field corresponds to an anonymous struct or
7936       // union.
7937       if (const clang::TagType *TagT =
7938               field->getType()->getAs<clang::TagType>()) {
7939         if (clang::RecordDecl *Rec =
7940                 llvm::dyn_cast<clang::RecordDecl>(TagT->getDecl()))
7941           if (!Rec->getDeclName()) {
7942             Rec->setAnonymousStructOrUnion(true);
7943             field->setImplicit();
7944           }
7945       }
7946     }
7947
7948     if (field) {
7949       field->setAccess(
7950           ClangASTContext::ConvertAccessTypeToAccessSpecifier(access));
7951
7952       record_decl->addDecl(field);
7953
7954 #ifdef LLDB_CONFIGURATION_DEBUG
7955       VerifyDecl(field);
7956 #endif
7957     }
7958   } else {
7959     clang::ObjCInterfaceDecl *class_interface_decl =
7960         ast->GetAsObjCInterfaceDecl(type);
7961
7962     if (class_interface_decl) {
7963       const bool is_synthesized = false;
7964
7965       field_clang_type.GetCompleteType();
7966
7967       field = clang::ObjCIvarDecl::Create(
7968           *clang_ast, class_interface_decl, clang::SourceLocation(),
7969           clang::SourceLocation(),
7970           ident,                                    // Identifier
7971           ClangUtil::GetQualType(field_clang_type), // Field type
7972           nullptr,                                  // TypeSourceInfo *
7973           ConvertAccessTypeToObjCIvarAccessControl(access), bit_width,
7974           is_synthesized);
7975
7976       if (field) {
7977         class_interface_decl->addDecl(field);
7978
7979 #ifdef LLDB_CONFIGURATION_DEBUG
7980         VerifyDecl(field);
7981 #endif
7982       }
7983     }
7984   }
7985   return field;
7986 }
7987
7988 void ClangASTContext::BuildIndirectFields(const CompilerType &type) {
7989   if (!type)
7990     return;
7991
7992   ClangASTContext *ast = llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
7993   if (!ast)
7994     return;
7995
7996   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7997
7998   if (!record_decl)
7999     return;
8000
8001   typedef llvm::SmallVector<clang::IndirectFieldDecl *, 1> IndirectFieldVector;
8002
8003   IndirectFieldVector indirect_fields;
8004   clang::RecordDecl::field_iterator field_pos;
8005   clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end();
8006   clang::RecordDecl::field_iterator last_field_pos = field_end_pos;
8007   for (field_pos = record_decl->field_begin(); field_pos != field_end_pos;
8008        last_field_pos = field_pos++) {
8009     if (field_pos->isAnonymousStructOrUnion()) {
8010       clang::QualType field_qual_type = field_pos->getType();
8011
8012       const clang::RecordType *field_record_type =
8013           field_qual_type->getAs<clang::RecordType>();
8014
8015       if (!field_record_type)
8016         continue;
8017
8018       clang::RecordDecl *field_record_decl = field_record_type->getDecl();
8019
8020       if (!field_record_decl)
8021         continue;
8022
8023       for (clang::RecordDecl::decl_iterator
8024                di = field_record_decl->decls_begin(),
8025                de = field_record_decl->decls_end();
8026            di != de; ++di) {
8027         if (clang::FieldDecl *nested_field_decl =
8028                 llvm::dyn_cast<clang::FieldDecl>(*di)) {
8029           clang::NamedDecl **chain =
8030               new (*ast->getASTContext()) clang::NamedDecl *[2];
8031           chain[0] = *field_pos;
8032           chain[1] = nested_field_decl;
8033           clang::IndirectFieldDecl *indirect_field =
8034               clang::IndirectFieldDecl::Create(
8035                   *ast->getASTContext(), record_decl, clang::SourceLocation(),
8036                   nested_field_decl->getIdentifier(),
8037                   nested_field_decl->getType(), {chain, 2});
8038
8039           indirect_field->setImplicit();
8040
8041           indirect_field->setAccess(ClangASTContext::UnifyAccessSpecifiers(
8042               field_pos->getAccess(), nested_field_decl->getAccess()));
8043
8044           indirect_fields.push_back(indirect_field);
8045         } else if (clang::IndirectFieldDecl *nested_indirect_field_decl =
8046                        llvm::dyn_cast<clang::IndirectFieldDecl>(*di)) {
8047           size_t nested_chain_size =
8048               nested_indirect_field_decl->getChainingSize();
8049           clang::NamedDecl **chain = new (*ast->getASTContext())
8050               clang::NamedDecl *[nested_chain_size + 1];
8051           chain[0] = *field_pos;
8052
8053           int chain_index = 1;
8054           for (clang::IndirectFieldDecl::chain_iterator
8055                    nci = nested_indirect_field_decl->chain_begin(),
8056                    nce = nested_indirect_field_decl->chain_end();
8057                nci < nce; ++nci) {
8058             chain[chain_index] = *nci;
8059             chain_index++;
8060           }
8061
8062           clang::IndirectFieldDecl *indirect_field =
8063               clang::IndirectFieldDecl::Create(
8064                   *ast->getASTContext(), record_decl, clang::SourceLocation(),
8065                   nested_indirect_field_decl->getIdentifier(),
8066                   nested_indirect_field_decl->getType(),
8067                   {chain, nested_chain_size + 1});
8068
8069           indirect_field->setImplicit();
8070
8071           indirect_field->setAccess(ClangASTContext::UnifyAccessSpecifiers(
8072               field_pos->getAccess(), nested_indirect_field_decl->getAccess()));
8073
8074           indirect_fields.push_back(indirect_field);
8075         }
8076       }
8077     }
8078   }
8079
8080   // Check the last field to see if it has an incomplete array type as its last
8081   // member and if it does, the tell the record decl about it
8082   if (last_field_pos != field_end_pos) {
8083     if (last_field_pos->getType()->isIncompleteArrayType())
8084       record_decl->hasFlexibleArrayMember();
8085   }
8086
8087   for (IndirectFieldVector::iterator ifi = indirect_fields.begin(),
8088                                      ife = indirect_fields.end();
8089        ifi < ife; ++ifi) {
8090     record_decl->addDecl(*ifi);
8091   }
8092 }
8093
8094 void ClangASTContext::SetIsPacked(const CompilerType &type) {
8095   if (type) {
8096     ClangASTContext *ast =
8097         llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8098     if (ast) {
8099       clang::RecordDecl *record_decl = GetAsRecordDecl(type);
8100
8101       if (!record_decl)
8102         return;
8103
8104       record_decl->addAttr(
8105           clang::PackedAttr::CreateImplicit(*ast->getASTContext()));
8106     }
8107   }
8108 }
8109
8110 clang::VarDecl *ClangASTContext::AddVariableToRecordType(
8111     const CompilerType &type, llvm::StringRef name,
8112     const CompilerType &var_type, AccessType access) {
8113   if (!type.IsValid() || !var_type.IsValid())
8114     return nullptr;
8115
8116   ClangASTContext *ast = llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8117   if (!ast)
8118     return nullptr;
8119
8120   clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
8121   if (!record_decl)
8122     return nullptr;
8123
8124   clang::VarDecl *var_decl = nullptr;
8125   clang::IdentifierInfo *ident = nullptr;
8126   if (!name.empty())
8127     ident = &ast->getASTContext()->Idents.get(name);
8128
8129   var_decl = clang::VarDecl::Create(
8130       *ast->getASTContext(),            // ASTContext &
8131       record_decl,                      // DeclContext *
8132       clang::SourceLocation(),          // clang::SourceLocation StartLoc
8133       clang::SourceLocation(),          // clang::SourceLocation IdLoc
8134       ident,                            // clang::IdentifierInfo *
8135       ClangUtil::GetQualType(var_type), // Variable clang::QualType
8136       nullptr,                          // TypeSourceInfo *
8137       clang::SC_Static);                // StorageClass
8138   if (!var_decl)
8139     return nullptr;
8140
8141   var_decl->setAccess(
8142       ClangASTContext::ConvertAccessTypeToAccessSpecifier(access));
8143   record_decl->addDecl(var_decl);
8144
8145 #ifdef LLDB_CONFIGURATION_DEBUG
8146   VerifyDecl(var_decl);
8147 #endif
8148
8149   return var_decl;
8150 }
8151
8152 clang::CXXMethodDecl *ClangASTContext::AddMethodToCXXRecordType(
8153     lldb::opaque_compiler_type_t type, const char *name, const char *mangled_name,
8154     const CompilerType &method_clang_type, lldb::AccessType access,
8155     bool is_virtual, bool is_static, bool is_inline, bool is_explicit,
8156     bool is_attr_used, bool is_artificial) {
8157   if (!type || !method_clang_type.IsValid() || name == nullptr ||
8158       name[0] == '\0')
8159     return nullptr;
8160
8161   clang::QualType record_qual_type(GetCanonicalQualType(type));
8162
8163   clang::CXXRecordDecl *cxx_record_decl =
8164       record_qual_type->getAsCXXRecordDecl();
8165
8166   if (cxx_record_decl == nullptr)
8167     return nullptr;
8168
8169   clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
8170
8171   clang::CXXMethodDecl *cxx_method_decl = nullptr;
8172
8173   clang::DeclarationName decl_name(&getASTContext()->Idents.get(name));
8174
8175   const clang::FunctionType *function_type =
8176       llvm::dyn_cast<clang::FunctionType>(method_qual_type.getTypePtr());
8177
8178   if (function_type == nullptr)
8179     return nullptr;
8180
8181   const clang::FunctionProtoType *method_function_prototype(
8182       llvm::dyn_cast<clang::FunctionProtoType>(function_type));
8183
8184   if (!method_function_prototype)
8185     return nullptr;
8186
8187   unsigned int num_params = method_function_prototype->getNumParams();
8188
8189   clang::CXXDestructorDecl *cxx_dtor_decl(nullptr);
8190   clang::CXXConstructorDecl *cxx_ctor_decl(nullptr);
8191
8192   if (is_artificial)
8193     return nullptr; // skip everything artificial
8194
8195   const clang::ExplicitSpecifier explicit_spec(
8196       nullptr /*expr*/, is_explicit
8197                             ? clang::ExplicitSpecKind::ResolvedTrue
8198                             : clang::ExplicitSpecKind::ResolvedFalse);
8199   if (name[0] == '~') {
8200     cxx_dtor_decl = clang::CXXDestructorDecl::Create(
8201         *getASTContext(), cxx_record_decl, clang::SourceLocation(),
8202         clang::DeclarationNameInfo(
8203             getASTContext()->DeclarationNames.getCXXDestructorName(
8204                 getASTContext()->getCanonicalType(record_qual_type)),
8205             clang::SourceLocation()),
8206         method_qual_type, nullptr, is_inline, is_artificial);
8207     cxx_method_decl = cxx_dtor_decl;
8208   } else if (decl_name == cxx_record_decl->getDeclName()) {
8209     cxx_ctor_decl = clang::CXXConstructorDecl::Create(
8210         *getASTContext(), cxx_record_decl, clang::SourceLocation(),
8211         clang::DeclarationNameInfo(
8212             getASTContext()->DeclarationNames.getCXXConstructorName(
8213                 getASTContext()->getCanonicalType(record_qual_type)),
8214             clang::SourceLocation()),
8215         method_qual_type,
8216         nullptr, // TypeSourceInfo *
8217         explicit_spec, is_inline, is_artificial, CSK_unspecified);
8218     cxx_method_decl = cxx_ctor_decl;
8219   } else {
8220     clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None;
8221     clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
8222
8223     if (IsOperator(name, op_kind)) {
8224       if (op_kind != clang::NUM_OVERLOADED_OPERATORS) {
8225         // Check the number of operator parameters. Sometimes we have seen bad
8226         // DWARF that doesn't correctly describe operators and if we try to
8227         // create a method and add it to the class, clang will assert and
8228         // crash, so we need to make sure things are acceptable.
8229         const bool is_method = true;
8230         if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
8231                 is_method, op_kind, num_params))
8232           return nullptr;
8233         cxx_method_decl = clang::CXXMethodDecl::Create(
8234             *getASTContext(), cxx_record_decl, clang::SourceLocation(),
8235             clang::DeclarationNameInfo(
8236                 getASTContext()->DeclarationNames.getCXXOperatorName(op_kind),
8237                 clang::SourceLocation()),
8238             method_qual_type,
8239             nullptr, // TypeSourceInfo *
8240             SC, is_inline, CSK_unspecified, clang::SourceLocation());
8241       } else if (num_params == 0) {
8242         // Conversion operators don't take params...
8243         cxx_method_decl = clang::CXXConversionDecl::Create(
8244             *getASTContext(), cxx_record_decl, clang::SourceLocation(),
8245             clang::DeclarationNameInfo(
8246                 getASTContext()->DeclarationNames.getCXXConversionFunctionName(
8247                     getASTContext()->getCanonicalType(
8248                         function_type->getReturnType())),
8249                 clang::SourceLocation()),
8250             method_qual_type,
8251             nullptr, // TypeSourceInfo *
8252             is_inline, explicit_spec, CSK_unspecified,
8253             clang::SourceLocation());
8254       }
8255     }
8256
8257     if (cxx_method_decl == nullptr) {
8258       cxx_method_decl = clang::CXXMethodDecl::Create(
8259           *getASTContext(), cxx_record_decl, clang::SourceLocation(),
8260           clang::DeclarationNameInfo(decl_name, clang::SourceLocation()),
8261           method_qual_type,
8262           nullptr, // TypeSourceInfo *
8263           SC, is_inline, CSK_unspecified, clang::SourceLocation());
8264     }
8265   }
8266
8267   clang::AccessSpecifier access_specifier =
8268       ClangASTContext::ConvertAccessTypeToAccessSpecifier(access);
8269
8270   cxx_method_decl->setAccess(access_specifier);
8271   cxx_method_decl->setVirtualAsWritten(is_virtual);
8272
8273   if (is_attr_used)
8274     cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(*getASTContext()));
8275
8276   if (mangled_name != nullptr) {
8277     cxx_method_decl->addAttr(
8278         clang::AsmLabelAttr::CreateImplicit(*getASTContext(), mangled_name));
8279   }
8280
8281   // Populate the method decl with parameter decls
8282
8283   llvm::SmallVector<clang::ParmVarDecl *, 12> params;
8284
8285   for (unsigned param_index = 0; param_index < num_params; ++param_index) {
8286     params.push_back(clang::ParmVarDecl::Create(
8287         *getASTContext(), cxx_method_decl, clang::SourceLocation(),
8288         clang::SourceLocation(),
8289         nullptr, // anonymous
8290         method_function_prototype->getParamType(param_index), nullptr,
8291         clang::SC_None, nullptr));
8292   }
8293
8294   cxx_method_decl->setParams(llvm::ArrayRef<clang::ParmVarDecl *>(params));
8295
8296   cxx_record_decl->addDecl(cxx_method_decl);
8297
8298   // Sometimes the debug info will mention a constructor (default/copy/move),
8299   // destructor, or assignment operator (copy/move) but there won't be any
8300   // version of this in the code. So we check if the function was artificially
8301   // generated and if it is trivial and this lets the compiler/backend know
8302   // that it can inline the IR for these when it needs to and we can avoid a
8303   // "missing function" error when running expressions.
8304
8305   if (is_artificial) {
8306     if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() &&
8307                            cxx_record_decl->hasTrivialDefaultConstructor()) ||
8308                           (cxx_ctor_decl->isCopyConstructor() &&
8309                            cxx_record_decl->hasTrivialCopyConstructor()) ||
8310                           (cxx_ctor_decl->isMoveConstructor() &&
8311                            cxx_record_decl->hasTrivialMoveConstructor()))) {
8312       cxx_ctor_decl->setDefaulted();
8313       cxx_ctor_decl->setTrivial(true);
8314     } else if (cxx_dtor_decl) {
8315       if (cxx_record_decl->hasTrivialDestructor()) {
8316         cxx_dtor_decl->setDefaulted();
8317         cxx_dtor_decl->setTrivial(true);
8318       }
8319     } else if ((cxx_method_decl->isCopyAssignmentOperator() &&
8320                 cxx_record_decl->hasTrivialCopyAssignment()) ||
8321                (cxx_method_decl->isMoveAssignmentOperator() &&
8322                 cxx_record_decl->hasTrivialMoveAssignment())) {
8323       cxx_method_decl->setDefaulted();
8324       cxx_method_decl->setTrivial(true);
8325     }
8326   }
8327
8328 #ifdef LLDB_CONFIGURATION_DEBUG
8329   VerifyDecl(cxx_method_decl);
8330 #endif
8331
8332   //    printf ("decl->isPolymorphic()             = %i\n",
8333   //    cxx_record_decl->isPolymorphic());
8334   //    printf ("decl->isAggregate()               = %i\n",
8335   //    cxx_record_decl->isAggregate());
8336   //    printf ("decl->isPOD()                     = %i\n",
8337   //    cxx_record_decl->isPOD());
8338   //    printf ("decl->isEmpty()                   = %i\n",
8339   //    cxx_record_decl->isEmpty());
8340   //    printf ("decl->isAbstract()                = %i\n",
8341   //    cxx_record_decl->isAbstract());
8342   //    printf ("decl->hasTrivialConstructor()     = %i\n",
8343   //    cxx_record_decl->hasTrivialConstructor());
8344   //    printf ("decl->hasTrivialCopyConstructor() = %i\n",
8345   //    cxx_record_decl->hasTrivialCopyConstructor());
8346   //    printf ("decl->hasTrivialCopyAssignment()  = %i\n",
8347   //    cxx_record_decl->hasTrivialCopyAssignment());
8348   //    printf ("decl->hasTrivialDestructor()      = %i\n",
8349   //    cxx_record_decl->hasTrivialDestructor());
8350   return cxx_method_decl;
8351 }
8352
8353 void ClangASTContext::AddMethodOverridesForCXXRecordType(
8354     lldb::opaque_compiler_type_t type) {
8355   if (auto *record = GetAsCXXRecordDecl(type))
8356     for (auto *method : record->methods())
8357       addOverridesForMethod(method);
8358 }
8359
8360 #pragma mark C++ Base Classes
8361
8362 std::unique_ptr<clang::CXXBaseSpecifier>
8363 ClangASTContext::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
8364                                           AccessType access, bool is_virtual,
8365                                           bool base_of_class) {
8366   if (!type)
8367     return nullptr;
8368
8369   return llvm::make_unique<clang::CXXBaseSpecifier>(
8370       clang::SourceRange(), is_virtual, base_of_class,
8371       ClangASTContext::ConvertAccessTypeToAccessSpecifier(access),
8372       getASTContext()->getTrivialTypeSourceInfo(GetQualType(type)),
8373       clang::SourceLocation());
8374 }
8375
8376 bool ClangASTContext::TransferBaseClasses(
8377     lldb::opaque_compiler_type_t type,
8378     std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases) {
8379   if (!type)
8380     return false;
8381   clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type);
8382   if (!cxx_record_decl)
8383     return false;
8384   std::vector<clang::CXXBaseSpecifier *> raw_bases;
8385   raw_bases.reserve(bases.size());
8386
8387   // Clang will make a copy of them, so it's ok that we pass pointers that we're
8388   // about to destroy.
8389   for (auto &b : bases)
8390     raw_bases.push_back(b.get());
8391   cxx_record_decl->setBases(raw_bases.data(), raw_bases.size());
8392   return true;
8393 }
8394
8395 bool ClangASTContext::SetObjCSuperClass(
8396     const CompilerType &type, const CompilerType &superclass_clang_type) {
8397   ClangASTContext *ast =
8398       llvm::dyn_cast_or_null<ClangASTContext>(type.GetTypeSystem());
8399   if (!ast)
8400     return false;
8401   clang::ASTContext *clang_ast = ast->getASTContext();
8402
8403   if (type && superclass_clang_type.IsValid() &&
8404       superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) {
8405     clang::ObjCInterfaceDecl *class_interface_decl =
8406         GetAsObjCInterfaceDecl(type);
8407     clang::ObjCInterfaceDecl *super_interface_decl =
8408         GetAsObjCInterfaceDecl(superclass_clang_type);
8409     if (class_interface_decl && super_interface_decl) {
8410       class_interface_decl->setSuperClass(clang_ast->getTrivialTypeSourceInfo(
8411           clang_ast->getObjCInterfaceType(super_interface_decl)));
8412       return true;
8413     }
8414   }
8415   return false;
8416 }
8417
8418 bool ClangASTContext::AddObjCClassProperty(
8419     const CompilerType &type, const char *property_name,
8420     const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl,
8421     const char *property_setter_name, const char *property_getter_name,
8422     uint32_t property_attributes, ClangASTMetadata *metadata) {
8423   if (!type || !property_clang_type.IsValid() || property_name == nullptr ||
8424       property_name[0] == '\0')
8425     return false;
8426   ClangASTContext *ast = llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8427   if (!ast)
8428     return false;
8429   clang::ASTContext *clang_ast = ast->getASTContext();
8430
8431   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8432
8433   if (class_interface_decl) {
8434     CompilerType property_clang_type_to_access;
8435
8436     if (property_clang_type.IsValid())
8437       property_clang_type_to_access = property_clang_type;
8438     else if (ivar_decl)
8439       property_clang_type_to_access =
8440           CompilerType(clang_ast, ivar_decl->getType());
8441
8442     if (class_interface_decl && property_clang_type_to_access.IsValid()) {
8443       clang::TypeSourceInfo *prop_type_source;
8444       if (ivar_decl)
8445         prop_type_source =
8446             clang_ast->getTrivialTypeSourceInfo(ivar_decl->getType());
8447       else
8448         prop_type_source = clang_ast->getTrivialTypeSourceInfo(
8449             ClangUtil::GetQualType(property_clang_type));
8450
8451       clang::ObjCPropertyDecl *property_decl = clang::ObjCPropertyDecl::Create(
8452           *clang_ast, class_interface_decl,
8453           clang::SourceLocation(), // Source Location
8454           &clang_ast->Idents.get(property_name),
8455           clang::SourceLocation(), // Source Location for AT
8456           clang::SourceLocation(), // Source location for (
8457           ivar_decl ? ivar_decl->getType()
8458                     : ClangUtil::GetQualType(property_clang_type),
8459           prop_type_source);
8460
8461       if (property_decl) {
8462         if (metadata)
8463           ClangASTContext::SetMetadata(clang_ast, property_decl, *metadata);
8464
8465         class_interface_decl->addDecl(property_decl);
8466
8467         clang::Selector setter_sel, getter_sel;
8468
8469         if (property_setter_name != nullptr) {
8470           std::string property_setter_no_colon(
8471               property_setter_name, strlen(property_setter_name) - 1);
8472           clang::IdentifierInfo *setter_ident =
8473               &clang_ast->Idents.get(property_setter_no_colon);
8474           setter_sel = clang_ast->Selectors.getSelector(1, &setter_ident);
8475         } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) {
8476           std::string setter_sel_string("set");
8477           setter_sel_string.push_back(::toupper(property_name[0]));
8478           setter_sel_string.append(&property_name[1]);
8479           clang::IdentifierInfo *setter_ident =
8480               &clang_ast->Idents.get(setter_sel_string);
8481           setter_sel = clang_ast->Selectors.getSelector(1, &setter_ident);
8482         }
8483         property_decl->setSetterName(setter_sel);
8484         property_decl->setPropertyAttributes(
8485             clang::ObjCPropertyDecl::OBJC_PR_setter);
8486
8487         if (property_getter_name != nullptr) {
8488           clang::IdentifierInfo *getter_ident =
8489               &clang_ast->Idents.get(property_getter_name);
8490           getter_sel = clang_ast->Selectors.getSelector(0, &getter_ident);
8491         } else {
8492           clang::IdentifierInfo *getter_ident =
8493               &clang_ast->Idents.get(property_name);
8494           getter_sel = clang_ast->Selectors.getSelector(0, &getter_ident);
8495         }
8496         property_decl->setGetterName(getter_sel);
8497         property_decl->setPropertyAttributes(
8498             clang::ObjCPropertyDecl::OBJC_PR_getter);
8499
8500         if (ivar_decl)
8501           property_decl->setPropertyIvarDecl(ivar_decl);
8502
8503         if (property_attributes & DW_APPLE_PROPERTY_readonly)
8504           property_decl->setPropertyAttributes(
8505               clang::ObjCPropertyDecl::OBJC_PR_readonly);
8506         if (property_attributes & DW_APPLE_PROPERTY_readwrite)
8507           property_decl->setPropertyAttributes(
8508               clang::ObjCPropertyDecl::OBJC_PR_readwrite);
8509         if (property_attributes & DW_APPLE_PROPERTY_assign)
8510           property_decl->setPropertyAttributes(
8511               clang::ObjCPropertyDecl::OBJC_PR_assign);
8512         if (property_attributes & DW_APPLE_PROPERTY_retain)
8513           property_decl->setPropertyAttributes(
8514               clang::ObjCPropertyDecl::OBJC_PR_retain);
8515         if (property_attributes & DW_APPLE_PROPERTY_copy)
8516           property_decl->setPropertyAttributes(
8517               clang::ObjCPropertyDecl::OBJC_PR_copy);
8518         if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
8519           property_decl->setPropertyAttributes(
8520               clang::ObjCPropertyDecl::OBJC_PR_nonatomic);
8521         if (property_attributes & clang::ObjCPropertyDecl::OBJC_PR_nullability)
8522           property_decl->setPropertyAttributes(
8523               clang::ObjCPropertyDecl::OBJC_PR_nullability);
8524         if (property_attributes &
8525             clang::ObjCPropertyDecl::OBJC_PR_null_resettable)
8526           property_decl->setPropertyAttributes(
8527               clang::ObjCPropertyDecl::OBJC_PR_null_resettable);
8528         if (property_attributes & clang::ObjCPropertyDecl::OBJC_PR_class)
8529           property_decl->setPropertyAttributes(
8530               clang::ObjCPropertyDecl::OBJC_PR_class);
8531
8532         const bool isInstance =
8533             (property_attributes & clang::ObjCPropertyDecl::OBJC_PR_class) == 0;
8534
8535         if (!getter_sel.isNull() &&
8536             !(isInstance
8537                   ? class_interface_decl->lookupInstanceMethod(getter_sel)
8538                   : class_interface_decl->lookupClassMethod(getter_sel))) {
8539           const bool isVariadic = false;
8540           const bool isSynthesized = false;
8541           const bool isImplicitlyDeclared = true;
8542           const bool isDefined = false;
8543           const clang::ObjCMethodDecl::ImplementationControl impControl =
8544               clang::ObjCMethodDecl::None;
8545           const bool HasRelatedResultType = false;
8546
8547           clang::ObjCMethodDecl *getter = clang::ObjCMethodDecl::Create(
8548               *clang_ast, clang::SourceLocation(), clang::SourceLocation(),
8549               getter_sel, ClangUtil::GetQualType(property_clang_type_to_access),
8550               nullptr, class_interface_decl, isInstance, isVariadic,
8551               isSynthesized, isImplicitlyDeclared, isDefined, impControl,
8552               HasRelatedResultType);
8553
8554           if (getter && metadata)
8555             ClangASTContext::SetMetadata(clang_ast, getter, *metadata);
8556
8557           if (getter) {
8558             getter->setMethodParams(*clang_ast,
8559                                     llvm::ArrayRef<clang::ParmVarDecl *>(),
8560                                     llvm::ArrayRef<clang::SourceLocation>());
8561
8562             class_interface_decl->addDecl(getter);
8563           }
8564         }
8565
8566         if (!setter_sel.isNull() &&
8567             !(isInstance
8568                   ? class_interface_decl->lookupInstanceMethod(setter_sel)
8569                   : class_interface_decl->lookupClassMethod(setter_sel))) {
8570           clang::QualType result_type = clang_ast->VoidTy;
8571           const bool isVariadic = false;
8572           const bool isSynthesized = false;
8573           const bool isImplicitlyDeclared = true;
8574           const bool isDefined = false;
8575           const clang::ObjCMethodDecl::ImplementationControl impControl =
8576               clang::ObjCMethodDecl::None;
8577           const bool HasRelatedResultType = false;
8578
8579           clang::ObjCMethodDecl *setter = clang::ObjCMethodDecl::Create(
8580               *clang_ast, clang::SourceLocation(), clang::SourceLocation(),
8581               setter_sel, result_type, nullptr, class_interface_decl,
8582               isInstance, isVariadic, isSynthesized, isImplicitlyDeclared,
8583               isDefined, impControl, HasRelatedResultType);
8584
8585           if (setter && metadata)
8586             ClangASTContext::SetMetadata(clang_ast, setter, *metadata);
8587
8588           llvm::SmallVector<clang::ParmVarDecl *, 1> params;
8589
8590           params.push_back(clang::ParmVarDecl::Create(
8591               *clang_ast, setter, clang::SourceLocation(),
8592               clang::SourceLocation(),
8593               nullptr, // anonymous
8594               ClangUtil::GetQualType(property_clang_type_to_access), nullptr,
8595               clang::SC_Auto, nullptr));
8596
8597           if (setter) {
8598             setter->setMethodParams(
8599                 *clang_ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
8600                 llvm::ArrayRef<clang::SourceLocation>());
8601
8602             class_interface_decl->addDecl(setter);
8603           }
8604         }
8605
8606         return true;
8607       }
8608     }
8609   }
8610   return false;
8611 }
8612
8613 bool ClangASTContext::IsObjCClassTypeAndHasIVars(const CompilerType &type,
8614                                                  bool check_superclass) {
8615   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8616   if (class_interface_decl)
8617     return ObjCDeclHasIVars(class_interface_decl, check_superclass);
8618   return false;
8619 }
8620
8621 clang::ObjCMethodDecl *ClangASTContext::AddMethodToObjCObjectType(
8622     const CompilerType &type,
8623     const char *name, // the full symbol name as seen in the symbol table
8624                       // (lldb::opaque_compiler_type_t type, "-[NString
8625                       // stringWithCString:]")
8626     const CompilerType &method_clang_type, lldb::AccessType access,
8627     bool is_artificial, bool is_variadic) {
8628   if (!type || !method_clang_type.IsValid())
8629     return nullptr;
8630
8631   clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
8632
8633   if (class_interface_decl == nullptr)
8634     return nullptr;
8635   ClangASTContext *lldb_ast =
8636       llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8637   if (lldb_ast == nullptr)
8638     return nullptr;
8639   clang::ASTContext *ast = lldb_ast->getASTContext();
8640
8641   const char *selector_start = ::strchr(name, ' ');
8642   if (selector_start == nullptr)
8643     return nullptr;
8644
8645   selector_start++;
8646   llvm::SmallVector<clang::IdentifierInfo *, 12> selector_idents;
8647
8648   size_t len = 0;
8649   const char *start;
8650   // printf ("name = '%s'\n", name);
8651
8652   unsigned num_selectors_with_args = 0;
8653   for (start = selector_start; start && *start != '\0' && *start != ']';
8654        start += len) {
8655     len = ::strcspn(start, ":]");
8656     bool has_arg = (start[len] == ':');
8657     if (has_arg)
8658       ++num_selectors_with_args;
8659     selector_idents.push_back(&ast->Idents.get(llvm::StringRef(start, len)));
8660     if (has_arg)
8661       len += 1;
8662   }
8663
8664   if (selector_idents.size() == 0)
8665     return nullptr;
8666
8667   clang::Selector method_selector = ast->Selectors.getSelector(
8668       num_selectors_with_args ? selector_idents.size() : 0,
8669       selector_idents.data());
8670
8671   clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
8672
8673   // Populate the method decl with parameter decls
8674   const clang::Type *method_type(method_qual_type.getTypePtr());
8675
8676   if (method_type == nullptr)
8677     return nullptr;
8678
8679   const clang::FunctionProtoType *method_function_prototype(
8680       llvm::dyn_cast<clang::FunctionProtoType>(method_type));
8681
8682   if (!method_function_prototype)
8683     return nullptr;
8684
8685   bool is_synthesized = false;
8686   bool is_defined = false;
8687   clang::ObjCMethodDecl::ImplementationControl imp_control =
8688       clang::ObjCMethodDecl::None;
8689
8690   const unsigned num_args = method_function_prototype->getNumParams();
8691
8692   if (num_args != num_selectors_with_args)
8693     return nullptr; // some debug information is corrupt.  We are not going to
8694                     // deal with it.
8695
8696   clang::ObjCMethodDecl *objc_method_decl = clang::ObjCMethodDecl::Create(
8697       *ast,
8698       clang::SourceLocation(), // beginLoc,
8699       clang::SourceLocation(), // endLoc,
8700       method_selector, method_function_prototype->getReturnType(),
8701       nullptr, // TypeSourceInfo *ResultTInfo,
8702       ClangASTContext::GetASTContext(ast)->GetDeclContextForType(
8703           ClangUtil::GetQualType(type)),
8704       name[0] == '-', is_variadic, is_synthesized,
8705       true, // is_implicitly_declared; we force this to true because we don't
8706             // have source locations
8707       is_defined, imp_control, false /*has_related_result_type*/);
8708
8709   if (objc_method_decl == nullptr)
8710     return nullptr;
8711
8712   if (num_args > 0) {
8713     llvm::SmallVector<clang::ParmVarDecl *, 12> params;
8714
8715     for (unsigned param_index = 0; param_index < num_args; ++param_index) {
8716       params.push_back(clang::ParmVarDecl::Create(
8717           *ast, objc_method_decl, clang::SourceLocation(),
8718           clang::SourceLocation(),
8719           nullptr, // anonymous
8720           method_function_prototype->getParamType(param_index), nullptr,
8721           clang::SC_Auto, nullptr));
8722     }
8723
8724     objc_method_decl->setMethodParams(
8725         *ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
8726         llvm::ArrayRef<clang::SourceLocation>());
8727   }
8728
8729   class_interface_decl->addDecl(objc_method_decl);
8730
8731 #ifdef LLDB_CONFIGURATION_DEBUG
8732   VerifyDecl(objc_method_decl);
8733 #endif
8734
8735   return objc_method_decl;
8736 }
8737
8738 bool ClangASTContext::GetHasExternalStorage(const CompilerType &type) {
8739   if (ClangUtil::IsClangType(type))
8740     return false;
8741
8742   clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
8743
8744   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8745   switch (type_class) {
8746   case clang::Type::Record: {
8747     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
8748     if (cxx_record_decl)
8749       return cxx_record_decl->hasExternalLexicalStorage() ||
8750              cxx_record_decl->hasExternalVisibleStorage();
8751   } break;
8752
8753   case clang::Type::Enum: {
8754     clang::EnumDecl *enum_decl =
8755         llvm::cast<clang::EnumType>(qual_type)->getDecl();
8756     if (enum_decl)
8757       return enum_decl->hasExternalLexicalStorage() ||
8758              enum_decl->hasExternalVisibleStorage();
8759   } break;
8760
8761   case clang::Type::ObjCObject:
8762   case clang::Type::ObjCInterface: {
8763     const clang::ObjCObjectType *objc_class_type =
8764         llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8765     assert(objc_class_type);
8766     if (objc_class_type) {
8767       clang::ObjCInterfaceDecl *class_interface_decl =
8768           objc_class_type->getInterface();
8769
8770       if (class_interface_decl)
8771         return class_interface_decl->hasExternalLexicalStorage() ||
8772                class_interface_decl->hasExternalVisibleStorage();
8773     }
8774   } break;
8775
8776   case clang::Type::Typedef:
8777     return GetHasExternalStorage(CompilerType(
8778         type.GetTypeSystem(), llvm::cast<clang::TypedefType>(qual_type)
8779                                   ->getDecl()
8780                                   ->getUnderlyingType()
8781                                   .getAsOpaquePtr()));
8782
8783   case clang::Type::Auto:
8784     return GetHasExternalStorage(CompilerType(
8785         type.GetTypeSystem(), llvm::cast<clang::AutoType>(qual_type)
8786                                   ->getDeducedType()
8787                                   .getAsOpaquePtr()));
8788
8789   case clang::Type::Elaborated:
8790     return GetHasExternalStorage(CompilerType(
8791         type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
8792                                   ->getNamedType()
8793                                   .getAsOpaquePtr()));
8794
8795   case clang::Type::Paren:
8796     return GetHasExternalStorage(CompilerType(
8797         type.GetTypeSystem(),
8798         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
8799
8800   default:
8801     break;
8802   }
8803   return false;
8804 }
8805
8806 bool ClangASTContext::SetHasExternalStorage(lldb::opaque_compiler_type_t type,
8807                                             bool has_extern) {
8808   if (!type)
8809     return false;
8810
8811   clang::QualType qual_type(GetCanonicalQualType(type));
8812
8813   const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8814   switch (type_class) {
8815   case clang::Type::Record: {
8816     clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
8817     if (cxx_record_decl) {
8818       cxx_record_decl->setHasExternalLexicalStorage(has_extern);
8819       cxx_record_decl->setHasExternalVisibleStorage(has_extern);
8820       return true;
8821     }
8822   } break;
8823
8824   case clang::Type::Enum: {
8825     clang::EnumDecl *enum_decl =
8826         llvm::cast<clang::EnumType>(qual_type)->getDecl();
8827     if (enum_decl) {
8828       enum_decl->setHasExternalLexicalStorage(has_extern);
8829       enum_decl->setHasExternalVisibleStorage(has_extern);
8830       return true;
8831     }
8832   } break;
8833
8834   case clang::Type::ObjCObject:
8835   case clang::Type::ObjCInterface: {
8836     const clang::ObjCObjectType *objc_class_type =
8837         llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8838     assert(objc_class_type);
8839     if (objc_class_type) {
8840       clang::ObjCInterfaceDecl *class_interface_decl =
8841           objc_class_type->getInterface();
8842
8843       if (class_interface_decl) {
8844         class_interface_decl->setHasExternalLexicalStorage(has_extern);
8845         class_interface_decl->setHasExternalVisibleStorage(has_extern);
8846         return true;
8847       }
8848     }
8849   } break;
8850
8851   case clang::Type::Typedef:
8852     return SetHasExternalStorage(llvm::cast<clang::TypedefType>(qual_type)
8853                                      ->getDecl()
8854                                      ->getUnderlyingType()
8855                                      .getAsOpaquePtr(),
8856                                  has_extern);
8857
8858   case clang::Type::Auto:
8859     return SetHasExternalStorage(llvm::cast<clang::AutoType>(qual_type)
8860                                      ->getDeducedType()
8861                                      .getAsOpaquePtr(),
8862                                  has_extern);
8863
8864   case clang::Type::Elaborated:
8865     return SetHasExternalStorage(llvm::cast<clang::ElaboratedType>(qual_type)
8866                                      ->getNamedType()
8867                                      .getAsOpaquePtr(),
8868                                  has_extern);
8869
8870   case clang::Type::Paren:
8871     return SetHasExternalStorage(
8872         llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr(),
8873         has_extern);
8874
8875   default:
8876     break;
8877   }
8878   return false;
8879 }
8880
8881 #pragma mark TagDecl
8882
8883 bool ClangASTContext::StartTagDeclarationDefinition(const CompilerType &type) {
8884   clang::QualType qual_type(ClangUtil::GetQualType(type));
8885   if (!qual_type.isNull()) {
8886     const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8887     if (tag_type) {
8888       clang::TagDecl *tag_decl = tag_type->getDecl();
8889       if (tag_decl) {
8890         tag_decl->startDefinition();
8891         return true;
8892       }
8893     }
8894
8895     const clang::ObjCObjectType *object_type =
8896         qual_type->getAs<clang::ObjCObjectType>();
8897     if (object_type) {
8898       clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface();
8899       if (interface_decl) {
8900         interface_decl->startDefinition();
8901         return true;
8902       }
8903     }
8904   }
8905   return false;
8906 }
8907
8908 bool ClangASTContext::CompleteTagDeclarationDefinition(
8909     const CompilerType &type) {
8910   clang::QualType qual_type(ClangUtil::GetQualType(type));
8911   if (!qual_type.isNull()) {
8912     // Make sure we use the same methodology as
8913     // ClangASTContext::StartTagDeclarationDefinition() as to how we start/end
8914     // the definition. Previously we were calling
8915     const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8916     if (tag_type) {
8917       clang::TagDecl *tag_decl = tag_type->getDecl();
8918       if (tag_decl) {
8919         clang::CXXRecordDecl *cxx_record_decl =
8920             llvm::dyn_cast_or_null<clang::CXXRecordDecl>(tag_decl);
8921
8922         if (cxx_record_decl) {
8923           if (!cxx_record_decl->isCompleteDefinition())
8924             cxx_record_decl->completeDefinition();
8925           cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
8926           cxx_record_decl->setHasExternalLexicalStorage(false);
8927           cxx_record_decl->setHasExternalVisibleStorage(false);
8928           return true;
8929         }
8930       }
8931     }
8932
8933     const clang::EnumType *enutype = qual_type->getAs<clang::EnumType>();
8934
8935     if (enutype) {
8936       clang::EnumDecl *enum_decl = enutype->getDecl();
8937
8938       if (enum_decl) {
8939         if (!enum_decl->isCompleteDefinition()) {
8940           ClangASTContext *lldb_ast =
8941               llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
8942           if (lldb_ast == nullptr)
8943             return false;
8944           clang::ASTContext *ast = lldb_ast->getASTContext();
8945
8946           /// TODO This really needs to be fixed.
8947
8948           QualType integer_type(enum_decl->getIntegerType());
8949           if (!integer_type.isNull()) {
8950             unsigned NumPositiveBits = 1;
8951             unsigned NumNegativeBits = 0;
8952
8953             clang::QualType promotion_qual_type;
8954             // If the enum integer type is less than an integer in bit width,
8955             // then we must promote it to an integer size.
8956             if (ast->getTypeSize(enum_decl->getIntegerType()) <
8957                 ast->getTypeSize(ast->IntTy)) {
8958               if (enum_decl->getIntegerType()->isSignedIntegerType())
8959                 promotion_qual_type = ast->IntTy;
8960               else
8961                 promotion_qual_type = ast->UnsignedIntTy;
8962             } else
8963               promotion_qual_type = enum_decl->getIntegerType();
8964
8965             enum_decl->completeDefinition(enum_decl->getIntegerType(),
8966                                           promotion_qual_type, NumPositiveBits,
8967                                           NumNegativeBits);
8968           }
8969         }
8970         return true;
8971       }
8972     }
8973   }
8974   return false;
8975 }
8976
8977 clang::EnumConstantDecl *ClangASTContext::AddEnumerationValueToEnumerationType(
8978     const CompilerType &enum_type, const Declaration &decl, const char *name,
8979     const llvm::APSInt &value) {
8980
8981   if (!enum_type || ConstString(name).IsEmpty())
8982     return nullptr;
8983
8984   lldbassert(enum_type.GetTypeSystem() == static_cast<TypeSystem *>(this));
8985
8986   lldb::opaque_compiler_type_t enum_opaque_compiler_type =
8987       enum_type.GetOpaqueQualType();
8988
8989   if (!enum_opaque_compiler_type)
8990     return nullptr;
8991
8992   clang::QualType enum_qual_type(
8993       GetCanonicalQualType(enum_opaque_compiler_type));
8994
8995   const clang::Type *clang_type = enum_qual_type.getTypePtr();
8996
8997   if (!clang_type)
8998     return nullptr;
8999
9000   const clang::EnumType *enutype = llvm::dyn_cast<clang::EnumType>(clang_type);
9001
9002   if (!enutype)
9003     return nullptr;
9004
9005   clang::EnumConstantDecl *enumerator_decl = clang::EnumConstantDecl::Create(
9006       *getASTContext(), enutype->getDecl(), clang::SourceLocation(),
9007       name ? &getASTContext()->Idents.get(name) : nullptr, // Identifier
9008       clang::QualType(enutype, 0), nullptr, value);
9009
9010   if (!enumerator_decl)
9011     return nullptr;
9012
9013   enutype->getDecl()->addDecl(enumerator_decl);
9014
9015 #ifdef LLDB_CONFIGURATION_DEBUG
9016   VerifyDecl(enumerator_decl);
9017 #endif
9018
9019   return enumerator_decl;
9020 }
9021
9022 clang::EnumConstantDecl *ClangASTContext::AddEnumerationValueToEnumerationType(
9023     const CompilerType &enum_type, const Declaration &decl, const char *name,
9024     int64_t enum_value, uint32_t enum_value_bit_size) {
9025   CompilerType underlying_type =
9026       GetEnumerationIntegerType(enum_type.GetOpaqueQualType());
9027   bool is_signed = false;
9028   underlying_type.IsIntegerType(is_signed);
9029
9030   llvm::APSInt value(enum_value_bit_size, is_signed);
9031   value = enum_value;
9032
9033   return AddEnumerationValueToEnumerationType(enum_type, decl, name, value);
9034 }
9035
9036 CompilerType
9037 ClangASTContext::GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) {
9038   clang::QualType enum_qual_type(GetCanonicalQualType(type));
9039   const clang::Type *clang_type = enum_qual_type.getTypePtr();
9040   if (clang_type) {
9041     const clang::EnumType *enutype =
9042         llvm::dyn_cast<clang::EnumType>(clang_type);
9043     if (enutype) {
9044       clang::EnumDecl *enum_decl = enutype->getDecl();
9045       if (enum_decl)
9046         return CompilerType(getASTContext(), enum_decl->getIntegerType());
9047     }
9048   }
9049   return CompilerType();
9050 }
9051
9052 CompilerType
9053 ClangASTContext::CreateMemberPointerType(const CompilerType &type,
9054                                          const CompilerType &pointee_type) {
9055   if (type && pointee_type.IsValid() &&
9056       type.GetTypeSystem() == pointee_type.GetTypeSystem()) {
9057     ClangASTContext *ast =
9058         llvm::dyn_cast<ClangASTContext>(type.GetTypeSystem());
9059     if (!ast)
9060       return CompilerType();
9061     return CompilerType(ast->getASTContext(),
9062                         ast->getASTContext()->getMemberPointerType(
9063                             ClangUtil::GetQualType(pointee_type),
9064                             ClangUtil::GetQualType(type).getTypePtr()));
9065   }
9066   return CompilerType();
9067 }
9068
9069 size_t
9070 ClangASTContext::ConvertStringToFloatValue(lldb::opaque_compiler_type_t type,
9071                                            const char *s, uint8_t *dst,
9072                                            size_t dst_size) {
9073   if (type) {
9074     clang::QualType qual_type(GetCanonicalQualType(type));
9075     uint32_t count = 0;
9076     bool is_complex = false;
9077     if (IsFloatingPointType(type, count, is_complex)) {
9078       // TODO: handle complex and vector types
9079       if (count != 1)
9080         return false;
9081
9082       llvm::StringRef s_sref(s);
9083       llvm::APFloat ap_float(getASTContext()->getFloatTypeSemantics(qual_type),
9084                              s_sref);
9085
9086       const uint64_t bit_size = getASTContext()->getTypeSize(qual_type);
9087       const uint64_t byte_size = bit_size / 8;
9088       if (dst_size >= byte_size) {
9089         Scalar scalar = ap_float.bitcastToAPInt().zextOrTrunc(
9090             llvm::NextPowerOf2(byte_size) * 8);
9091         lldb_private::Status get_data_error;
9092         if (scalar.GetAsMemoryData(dst, byte_size,
9093                                    lldb_private::endian::InlHostByteOrder(),
9094                                    get_data_error))
9095           return byte_size;
9096       }
9097     }
9098   }
9099   return 0;
9100 }
9101
9102 // Dumping types
9103 #define DEPTH_INCREMENT 2
9104
9105 #ifndef NDEBUG
9106 LLVM_DUMP_METHOD void
9107 ClangASTContext::dump(lldb::opaque_compiler_type_t type) const {
9108   if (!type)
9109     return;
9110   clang::QualType qual_type(GetQualType(type));
9111   qual_type.dump();
9112 }
9113 #endif
9114
9115 void ClangASTContext::Dump(Stream &s) {
9116   Decl *tu = Decl::castFromDeclContext(GetTranslationUnitDecl());
9117   tu->dump(s.AsRawOstream());
9118 }
9119
9120 void ClangASTContext::DumpValue(
9121     lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s,
9122     lldb::Format format, const DataExtractor &data,
9123     lldb::offset_t data_byte_offset, size_t data_byte_size,
9124     uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool show_types,
9125     bool show_summary, bool verbose, uint32_t depth) {
9126   if (!type)
9127     return;
9128
9129   clang::QualType qual_type(GetQualType(type));
9130   switch (qual_type->getTypeClass()) {
9131   case clang::Type::Record:
9132     if (GetCompleteType(type)) {
9133       const clang::RecordType *record_type =
9134           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
9135       const clang::RecordDecl *record_decl = record_type->getDecl();
9136       assert(record_decl);
9137       uint32_t field_bit_offset = 0;
9138       uint32_t field_byte_offset = 0;
9139       const clang::ASTRecordLayout &record_layout =
9140           getASTContext()->getASTRecordLayout(record_decl);
9141       uint32_t child_idx = 0;
9142
9143       const clang::CXXRecordDecl *cxx_record_decl =
9144           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
9145       if (cxx_record_decl) {
9146         // We might have base classes to print out first
9147         clang::CXXRecordDecl::base_class_const_iterator base_class,
9148             base_class_end;
9149         for (base_class = cxx_record_decl->bases_begin(),
9150             base_class_end = cxx_record_decl->bases_end();
9151              base_class != base_class_end; ++base_class) {
9152           const clang::CXXRecordDecl *base_class_decl =
9153               llvm::cast<clang::CXXRecordDecl>(
9154                   base_class->getType()->getAs<clang::RecordType>()->getDecl());
9155
9156           // Skip empty base classes
9157           if (!verbose && !ClangASTContext::RecordHasFields(base_class_decl))
9158             continue;
9159
9160           if (base_class->isVirtual())
9161             field_bit_offset =
9162                 record_layout.getVBaseClassOffset(base_class_decl)
9163                     .getQuantity() *
9164                 8;
9165           else
9166             field_bit_offset = record_layout.getBaseClassOffset(base_class_decl)
9167                                    .getQuantity() *
9168                                8;
9169           field_byte_offset = field_bit_offset / 8;
9170           assert(field_bit_offset % 8 == 0);
9171           if (child_idx == 0)
9172             s->PutChar('{');
9173           else
9174             s->PutChar(',');
9175
9176           clang::QualType base_class_qual_type = base_class->getType();
9177           std::string base_class_type_name(base_class_qual_type.getAsString());
9178
9179           // Indent and print the base class type name
9180           s->Format("\n{0}{1}", llvm::fmt_repeat(" ", depth + DEPTH_INCREMENT),
9181                     base_class_type_name);
9182
9183           clang::TypeInfo base_class_type_info =
9184               getASTContext()->getTypeInfo(base_class_qual_type);
9185
9186           // Dump the value of the member
9187           CompilerType base_clang_type(getASTContext(), base_class_qual_type);
9188           base_clang_type.DumpValue(
9189               exe_ctx,
9190               s, // Stream to dump to
9191               base_clang_type
9192                   .GetFormat(), // The format with which to display the member
9193               data, // Data buffer containing all bytes for this type
9194               data_byte_offset + field_byte_offset, // Offset into "data" where
9195                                                     // to grab value from
9196               base_class_type_info.Width / 8, // Size of this type in bytes
9197               0,                              // Bitfield bit size
9198               0,                              // Bitfield bit offset
9199               show_types,   // Boolean indicating if we should show the variable
9200                             // types
9201               show_summary, // Boolean indicating if we should show a summary
9202                             // for the current type
9203               verbose,      // Verbose output?
9204               depth + DEPTH_INCREMENT); // Scope depth for any types that have
9205                                         // children
9206
9207           ++child_idx;
9208         }
9209       }
9210       uint32_t field_idx = 0;
9211       clang::RecordDecl::field_iterator field, field_end;
9212       for (field = record_decl->field_begin(),
9213           field_end = record_decl->field_end();
9214            field != field_end; ++field, ++field_idx, ++child_idx) {
9215         // Print the starting squiggly bracket (if this is the first member) or
9216         // comma (for member 2 and beyond) for the struct/union/class member.
9217         if (child_idx == 0)
9218           s->PutChar('{');
9219         else
9220           s->PutChar(',');
9221
9222         // Indent
9223         s->Printf("\n%*s", depth + DEPTH_INCREMENT, "");
9224
9225         clang::QualType field_type = field->getType();
9226         // Print the member type if requested
9227         // Figure out the type byte size (field_type_info.first) and alignment
9228         // (field_type_info.second) from the AST context.
9229         clang::TypeInfo field_type_info =
9230             getASTContext()->getTypeInfo(field_type);
9231         assert(field_idx < record_layout.getFieldCount());
9232         // Figure out the field offset within the current struct/union/class
9233         // type
9234         field_bit_offset = record_layout.getFieldOffset(field_idx);
9235         field_byte_offset = field_bit_offset / 8;
9236         uint32_t field_bitfield_bit_size = 0;
9237         uint32_t field_bitfield_bit_offset = 0;
9238         if (ClangASTContext::FieldIsBitfield(getASTContext(), *field,
9239                                              field_bitfield_bit_size))
9240           field_bitfield_bit_offset = field_bit_offset % 8;
9241
9242         if (show_types) {
9243           std::string field_type_name(field_type.getAsString());
9244           if (field_bitfield_bit_size > 0)
9245             s->Printf("(%s:%u) ", field_type_name.c_str(),
9246                       field_bitfield_bit_size);
9247           else
9248             s->Printf("(%s) ", field_type_name.c_str());
9249         }
9250         // Print the member name and equal sign
9251         s->Printf("%s = ", field->getNameAsString().c_str());
9252
9253         // Dump the value of the member
9254         CompilerType field_clang_type(getASTContext(), field_type);
9255         field_clang_type.DumpValue(
9256             exe_ctx,
9257             s, // Stream to dump to
9258             field_clang_type
9259                 .GetFormat(), // The format with which to display the member
9260             data,             // Data buffer containing all bytes for this type
9261             data_byte_offset + field_byte_offset, // Offset into "data" where to
9262                                                   // grab value from
9263             field_type_info.Width / 8,            // Size of this type in bytes
9264             field_bitfield_bit_size,              // Bitfield bit size
9265             field_bitfield_bit_offset,            // Bitfield bit offset
9266             show_types,   // Boolean indicating if we should show the variable
9267                           // types
9268             show_summary, // Boolean indicating if we should show a summary for
9269                           // the current type
9270             verbose,      // Verbose output?
9271             depth + DEPTH_INCREMENT); // Scope depth for any types that have
9272                                       // children
9273       }
9274
9275       // Indent the trailing squiggly bracket
9276       if (child_idx > 0)
9277         s->Printf("\n%*s}", depth, "");
9278     }
9279     return;
9280
9281   case clang::Type::Enum:
9282     if (GetCompleteType(type)) {
9283       const clang::EnumType *enutype =
9284           llvm::cast<clang::EnumType>(qual_type.getTypePtr());
9285       const clang::EnumDecl *enum_decl = enutype->getDecl();
9286       assert(enum_decl);
9287       clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
9288       lldb::offset_t offset = data_byte_offset;
9289       const int64_t enum_value = data.GetMaxU64Bitfield(
9290           &offset, data_byte_size, bitfield_bit_size, bitfield_bit_offset);
9291       for (enum_pos = enum_decl->enumerator_begin(),
9292           enum_end_pos = enum_decl->enumerator_end();
9293            enum_pos != enum_end_pos; ++enum_pos) {
9294         if (enum_pos->getInitVal() == enum_value) {
9295           s->Printf("%s", enum_pos->getNameAsString().c_str());
9296           return;
9297         }
9298       }
9299       // If we have gotten here we didn't get find the enumerator in the enum
9300       // decl, so just print the integer.
9301       s->Printf("%" PRIi64, enum_value);
9302     }
9303     return;
9304
9305   case clang::Type::ConstantArray: {
9306     const clang::ConstantArrayType *array =
9307         llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr());
9308     bool is_array_of_characters = false;
9309     clang::QualType element_qual_type = array->getElementType();
9310
9311     const clang::Type *canonical_type =
9312         element_qual_type->getCanonicalTypeInternal().getTypePtr();
9313     if (canonical_type)
9314       is_array_of_characters = canonical_type->isCharType();
9315
9316     const uint64_t element_count = array->getSize().getLimitedValue();
9317
9318     clang::TypeInfo field_type_info =
9319         getASTContext()->getTypeInfo(element_qual_type);
9320
9321     uint32_t element_idx = 0;
9322     uint32_t element_offset = 0;
9323     uint64_t element_byte_size = field_type_info.Width / 8;
9324     uint32_t element_stride = element_byte_size;
9325
9326     if (is_array_of_characters) {
9327       s->PutChar('"');
9328       DumpDataExtractor(data, s, data_byte_offset, lldb::eFormatChar,
9329                         element_byte_size, element_count, UINT32_MAX,
9330                         LLDB_INVALID_ADDRESS, 0, 0);
9331       s->PutChar('"');
9332       return;
9333     } else {
9334       CompilerType element_clang_type(getASTContext(), element_qual_type);
9335       lldb::Format element_format = element_clang_type.GetFormat();
9336
9337       for (element_idx = 0; element_idx < element_count; ++element_idx) {
9338         // Print the starting squiggly bracket (if this is the first member) or
9339         // comman (for member 2 and beyong) for the struct/union/class member.
9340         if (element_idx == 0)
9341           s->PutChar('{');
9342         else
9343           s->PutChar(',');
9344
9345         // Indent and print the index
9346         s->Printf("\n%*s[%u] ", depth + DEPTH_INCREMENT, "", element_idx);
9347
9348         // Figure out the field offset within the current struct/union/class
9349         // type
9350         element_offset = element_idx * element_stride;
9351
9352         // Dump the value of the member
9353         element_clang_type.DumpValue(
9354             exe_ctx,
9355             s,              // Stream to dump to
9356             element_format, // The format with which to display the element
9357             data,           // Data buffer containing all bytes for this type
9358             data_byte_offset +
9359                 element_offset, // Offset into "data" where to grab value from
9360             element_byte_size,  // Size of this type in bytes
9361             0,                  // Bitfield bit size
9362             0,                  // Bitfield bit offset
9363             show_types,   // Boolean indicating if we should show the variable
9364                           // types
9365             show_summary, // Boolean indicating if we should show a summary for
9366                           // the current type
9367             verbose,      // Verbose output?
9368             depth + DEPTH_INCREMENT); // Scope depth for any types that have
9369                                       // children
9370       }
9371
9372       // Indent the trailing squiggly bracket
9373       if (element_idx > 0)
9374         s->Printf("\n%*s}", depth, "");
9375     }
9376   }
9377     return;
9378
9379   case clang::Type::Typedef: {
9380     clang::QualType typedef_qual_type =
9381         llvm::cast<clang::TypedefType>(qual_type)
9382             ->getDecl()
9383             ->getUnderlyingType();
9384
9385     CompilerType typedef_clang_type(getASTContext(), typedef_qual_type);
9386     lldb::Format typedef_format = typedef_clang_type.GetFormat();
9387     clang::TypeInfo typedef_type_info =
9388         getASTContext()->getTypeInfo(typedef_qual_type);
9389     uint64_t typedef_byte_size = typedef_type_info.Width / 8;
9390
9391     return typedef_clang_type.DumpValue(
9392         exe_ctx,
9393         s,                   // Stream to dump to
9394         typedef_format,      // The format with which to display the element
9395         data,                // Data buffer containing all bytes for this type
9396         data_byte_offset,    // Offset into "data" where to grab value from
9397         typedef_byte_size,   // Size of this type in bytes
9398         bitfield_bit_size,   // Bitfield bit size
9399         bitfield_bit_offset, // Bitfield bit offset
9400         show_types,   // Boolean indicating if we should show the variable types
9401         show_summary, // Boolean indicating if we should show a summary for the
9402                       // current type
9403         verbose,      // Verbose output?
9404         depth);       // Scope depth for any types that have children
9405   } break;
9406
9407   case clang::Type::Auto: {
9408     clang::QualType elaborated_qual_type =
9409         llvm::cast<clang::AutoType>(qual_type)->getDeducedType();
9410     CompilerType elaborated_clang_type(getASTContext(), elaborated_qual_type);
9411     lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
9412     clang::TypeInfo elaborated_type_info =
9413         getASTContext()->getTypeInfo(elaborated_qual_type);
9414     uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
9415
9416     return elaborated_clang_type.DumpValue(
9417         exe_ctx,
9418         s,                    // Stream to dump to
9419         elaborated_format,    // The format with which to display the element
9420         data,                 // Data buffer containing all bytes for this type
9421         data_byte_offset,     // Offset into "data" where to grab value from
9422         elaborated_byte_size, // Size of this type in bytes
9423         bitfield_bit_size,    // Bitfield bit size
9424         bitfield_bit_offset,  // Bitfield bit offset
9425         show_types,   // Boolean indicating if we should show the variable types
9426         show_summary, // Boolean indicating if we should show a summary for the
9427                       // current type
9428         verbose,      // Verbose output?
9429         depth);       // Scope depth for any types that have children
9430   } break;
9431
9432   case clang::Type::Elaborated: {
9433     clang::QualType elaborated_qual_type =
9434         llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
9435     CompilerType elaborated_clang_type(getASTContext(), elaborated_qual_type);
9436     lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
9437     clang::TypeInfo elaborated_type_info =
9438         getASTContext()->getTypeInfo(elaborated_qual_type);
9439     uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
9440
9441     return elaborated_clang_type.DumpValue(
9442         exe_ctx,
9443         s,                    // Stream to dump to
9444         elaborated_format,    // The format with which to display the element
9445         data,                 // Data buffer containing all bytes for this type
9446         data_byte_offset,     // Offset into "data" where to grab value from
9447         elaborated_byte_size, // Size of this type in bytes
9448         bitfield_bit_size,    // Bitfield bit size
9449         bitfield_bit_offset,  // Bitfield bit offset
9450         show_types,   // Boolean indicating if we should show the variable types
9451         show_summary, // Boolean indicating if we should show a summary for the
9452                       // current type
9453         verbose,      // Verbose output?
9454         depth);       // Scope depth for any types that have children
9455   } break;
9456
9457   case clang::Type::Paren: {
9458     clang::QualType desugar_qual_type =
9459         llvm::cast<clang::ParenType>(qual_type)->desugar();
9460     CompilerType desugar_clang_type(getASTContext(), desugar_qual_type);
9461
9462     lldb::Format desugar_format = desugar_clang_type.GetFormat();
9463     clang::TypeInfo desugar_type_info =
9464         getASTContext()->getTypeInfo(desugar_qual_type);
9465     uint64_t desugar_byte_size = desugar_type_info.Width / 8;
9466
9467     return desugar_clang_type.DumpValue(
9468         exe_ctx,
9469         s,                   // Stream to dump to
9470         desugar_format,      // The format with which to display the element
9471         data,                // Data buffer containing all bytes for this type
9472         data_byte_offset,    // Offset into "data" where to grab value from
9473         desugar_byte_size,   // Size of this type in bytes
9474         bitfield_bit_size,   // Bitfield bit size
9475         bitfield_bit_offset, // Bitfield bit offset
9476         show_types,   // Boolean indicating if we should show the variable types
9477         show_summary, // Boolean indicating if we should show a summary for the
9478                       // current type
9479         verbose,      // Verbose output?
9480         depth);       // Scope depth for any types that have children
9481   } break;
9482
9483   default:
9484     // We are down to a scalar type that we just need to display.
9485     DumpDataExtractor(data, s, data_byte_offset, format, data_byte_size, 1,
9486                       UINT32_MAX, LLDB_INVALID_ADDRESS, bitfield_bit_size,
9487                       bitfield_bit_offset);
9488
9489     if (show_summary)
9490       DumpSummary(type, exe_ctx, s, data, data_byte_offset, data_byte_size);
9491     break;
9492   }
9493 }
9494
9495 bool ClangASTContext::DumpTypeValue(
9496     lldb::opaque_compiler_type_t type, Stream *s, lldb::Format format,
9497     const DataExtractor &data, lldb::offset_t byte_offset, size_t byte_size,
9498     uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
9499     ExecutionContextScope *exe_scope) {
9500   if (!type)
9501     return false;
9502   if (IsAggregateType(type)) {
9503     return false;
9504   } else {
9505     clang::QualType qual_type(GetQualType(type));
9506
9507     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9508     switch (type_class) {
9509     case clang::Type::Typedef: {
9510       clang::QualType typedef_qual_type =
9511           llvm::cast<clang::TypedefType>(qual_type)
9512               ->getDecl()
9513               ->getUnderlyingType();
9514       CompilerType typedef_clang_type(getASTContext(), typedef_qual_type);
9515       if (format == eFormatDefault)
9516         format = typedef_clang_type.GetFormat();
9517       clang::TypeInfo typedef_type_info =
9518           getASTContext()->getTypeInfo(typedef_qual_type);
9519       uint64_t typedef_byte_size = typedef_type_info.Width / 8;
9520
9521       return typedef_clang_type.DumpTypeValue(
9522           s,
9523           format,            // The format with which to display the element
9524           data,              // Data buffer containing all bytes for this type
9525           byte_offset,       // Offset into "data" where to grab value from
9526           typedef_byte_size, // Size of this type in bytes
9527           bitfield_bit_size, // Size in bits of a bitfield value, if zero don't
9528                              // treat as a bitfield
9529           bitfield_bit_offset, // Offset in bits of a bitfield value if
9530                                // bitfield_bit_size != 0
9531           exe_scope);
9532     } break;
9533
9534     case clang::Type::Enum:
9535       // If our format is enum or default, show the enumeration value as its
9536       // enumeration string value, else just display it as requested.
9537       if ((format == eFormatEnum || format == eFormatDefault) &&
9538           GetCompleteType(type)) {
9539         const clang::EnumType *enutype =
9540             llvm::cast<clang::EnumType>(qual_type.getTypePtr());
9541         const clang::EnumDecl *enum_decl = enutype->getDecl();
9542         assert(enum_decl);
9543         clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
9544         const bool is_signed = qual_type->isSignedIntegerOrEnumerationType();
9545         lldb::offset_t offset = byte_offset;
9546         if (is_signed) {
9547           const int64_t enum_svalue = data.GetMaxS64Bitfield(
9548               &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
9549           for (enum_pos = enum_decl->enumerator_begin(),
9550               enum_end_pos = enum_decl->enumerator_end();
9551                enum_pos != enum_end_pos; ++enum_pos) {
9552             if (enum_pos->getInitVal().getSExtValue() == enum_svalue) {
9553               s->PutCString(enum_pos->getNameAsString());
9554               return true;
9555             }
9556           }
9557           // If we have gotten here we didn't get find the enumerator in the
9558           // enum decl, so just print the integer.
9559           s->Printf("%" PRIi64, enum_svalue);
9560         } else {
9561           const uint64_t enum_uvalue = data.GetMaxU64Bitfield(
9562               &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
9563           for (enum_pos = enum_decl->enumerator_begin(),
9564               enum_end_pos = enum_decl->enumerator_end();
9565                enum_pos != enum_end_pos; ++enum_pos) {
9566             if (enum_pos->getInitVal().getZExtValue() == enum_uvalue) {
9567               s->PutCString(enum_pos->getNameAsString());
9568               return true;
9569             }
9570           }
9571           // If we have gotten here we didn't get find the enumerator in the
9572           // enum decl, so just print the integer.
9573           s->Printf("%" PRIu64, enum_uvalue);
9574         }
9575         return true;
9576       }
9577       // format was not enum, just fall through and dump the value as
9578       // requested....
9579       LLVM_FALLTHROUGH;
9580
9581     default:
9582       // We are down to a scalar type that we just need to display.
9583       {
9584         uint32_t item_count = 1;
9585         // A few formats, we might need to modify our size and count for
9586         // depending
9587         // on how we are trying to display the value...
9588         switch (format) {
9589         default:
9590         case eFormatBoolean:
9591         case eFormatBinary:
9592         case eFormatComplex:
9593         case eFormatCString: // NULL terminated C strings
9594         case eFormatDecimal:
9595         case eFormatEnum:
9596         case eFormatHex:
9597         case eFormatHexUppercase:
9598         case eFormatFloat:
9599         case eFormatOctal:
9600         case eFormatOSType:
9601         case eFormatUnsigned:
9602         case eFormatPointer:
9603         case eFormatVectorOfChar:
9604         case eFormatVectorOfSInt8:
9605         case eFormatVectorOfUInt8:
9606         case eFormatVectorOfSInt16:
9607         case eFormatVectorOfUInt16:
9608         case eFormatVectorOfSInt32:
9609         case eFormatVectorOfUInt32:
9610         case eFormatVectorOfSInt64:
9611         case eFormatVectorOfUInt64:
9612         case eFormatVectorOfFloat32:
9613         case eFormatVectorOfFloat64:
9614         case eFormatVectorOfUInt128:
9615           break;
9616
9617         case eFormatChar:
9618         case eFormatCharPrintable:
9619         case eFormatCharArray:
9620         case eFormatBytes:
9621         case eFormatBytesWithASCII:
9622           item_count = byte_size;
9623           byte_size = 1;
9624           break;
9625
9626         case eFormatUnicode16:
9627           item_count = byte_size / 2;
9628           byte_size = 2;
9629           break;
9630
9631         case eFormatUnicode32:
9632           item_count = byte_size / 4;
9633           byte_size = 4;
9634           break;
9635         }
9636         return DumpDataExtractor(data, s, byte_offset, format, byte_size,
9637                                  item_count, UINT32_MAX, LLDB_INVALID_ADDRESS,
9638                                  bitfield_bit_size, bitfield_bit_offset,
9639                                  exe_scope);
9640       }
9641       break;
9642     }
9643   }
9644   return false;
9645 }
9646
9647 void ClangASTContext::DumpSummary(lldb::opaque_compiler_type_t type,
9648                                   ExecutionContext *exe_ctx, Stream *s,
9649                                   const lldb_private::DataExtractor &data,
9650                                   lldb::offset_t data_byte_offset,
9651                                   size_t data_byte_size) {
9652   uint32_t length = 0;
9653   if (IsCStringType(type, length)) {
9654     if (exe_ctx) {
9655       Process *process = exe_ctx->GetProcessPtr();
9656       if (process) {
9657         lldb::offset_t offset = data_byte_offset;
9658         lldb::addr_t pointer_address = data.GetMaxU64(&offset, data_byte_size);
9659         std::vector<uint8_t> buf;
9660         if (length > 0)
9661           buf.resize(length);
9662         else
9663           buf.resize(256);
9664
9665         DataExtractor cstr_data(&buf.front(), buf.size(),
9666                                 process->GetByteOrder(), 4);
9667         buf.back() = '\0';
9668         size_t bytes_read;
9669         size_t total_cstr_len = 0;
9670         Status error;
9671         while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(),
9672                                                  buf.size(), error)) > 0) {
9673           const size_t len = strlen((const char *)&buf.front());
9674           if (len == 0)
9675             break;
9676           if (total_cstr_len == 0)
9677             s->PutCString(" \"");
9678           DumpDataExtractor(cstr_data, s, 0, lldb::eFormatChar, 1, len,
9679                             UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0);
9680           total_cstr_len += len;
9681           if (len < buf.size())
9682             break;
9683           pointer_address += total_cstr_len;
9684         }
9685         if (total_cstr_len > 0)
9686           s->PutChar('"');
9687       }
9688     }
9689   }
9690 }
9691
9692 void ClangASTContext::DumpTypeDescription(lldb::opaque_compiler_type_t type) {
9693   StreamFile s(stdout, false);
9694   DumpTypeDescription(type, &s);
9695   ClangASTMetadata *metadata =
9696       ClangASTContext::GetMetadata(getASTContext(), type);
9697   if (metadata) {
9698     metadata->Dump(&s);
9699   }
9700 }
9701
9702 void ClangASTContext::DumpTypeDescription(lldb::opaque_compiler_type_t type,
9703                                           Stream *s) {
9704   if (type) {
9705     clang::QualType qual_type(GetQualType(type));
9706
9707     llvm::SmallVector<char, 1024> buf;
9708     llvm::raw_svector_ostream llvm_ostrm(buf);
9709
9710     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9711     switch (type_class) {
9712     case clang::Type::ObjCObject:
9713     case clang::Type::ObjCInterface: {
9714       GetCompleteType(type);
9715
9716       const clang::ObjCObjectType *objc_class_type =
9717           llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
9718       assert(objc_class_type);
9719       if (objc_class_type) {
9720         clang::ObjCInterfaceDecl *class_interface_decl =
9721             objc_class_type->getInterface();
9722         if (class_interface_decl) {
9723           clang::PrintingPolicy policy = getASTContext()->getPrintingPolicy();
9724           class_interface_decl->print(llvm_ostrm, policy, s->GetIndentLevel());
9725         }
9726       }
9727     } break;
9728
9729     case clang::Type::Typedef: {
9730       const clang::TypedefType *typedef_type =
9731           qual_type->getAs<clang::TypedefType>();
9732       if (typedef_type) {
9733         const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
9734         std::string clang_typedef_name(
9735             typedef_decl->getQualifiedNameAsString());
9736         if (!clang_typedef_name.empty()) {
9737           s->PutCString("typedef ");
9738           s->PutCString(clang_typedef_name);
9739         }
9740       }
9741     } break;
9742
9743     case clang::Type::Auto:
9744       CompilerType(getASTContext(),
9745                    llvm::cast<clang::AutoType>(qual_type)->getDeducedType())
9746           .DumpTypeDescription(s);
9747       return;
9748
9749     case clang::Type::Elaborated:
9750       CompilerType(getASTContext(),
9751                    llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType())
9752           .DumpTypeDescription(s);
9753       return;
9754
9755     case clang::Type::Paren:
9756       CompilerType(getASTContext(),
9757                    llvm::cast<clang::ParenType>(qual_type)->desugar())
9758           .DumpTypeDescription(s);
9759       return;
9760
9761     case clang::Type::Record: {
9762       GetCompleteType(type);
9763
9764       const clang::RecordType *record_type =
9765           llvm::cast<clang::RecordType>(qual_type.getTypePtr());
9766       const clang::RecordDecl *record_decl = record_type->getDecl();
9767       const clang::CXXRecordDecl *cxx_record_decl =
9768           llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
9769
9770       if (cxx_record_decl)
9771         cxx_record_decl->print(llvm_ostrm, getASTContext()->getPrintingPolicy(),
9772                                s->GetIndentLevel());
9773       else
9774         record_decl->print(llvm_ostrm, getASTContext()->getPrintingPolicy(),
9775                            s->GetIndentLevel());
9776     } break;
9777
9778     default: {
9779       const clang::TagType *tag_type =
9780           llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
9781       if (tag_type) {
9782         clang::TagDecl *tag_decl = tag_type->getDecl();
9783         if (tag_decl)
9784           tag_decl->print(llvm_ostrm, 0);
9785       } else {
9786         std::string clang_type_name(qual_type.getAsString());
9787         if (!clang_type_name.empty())
9788           s->PutCString(clang_type_name);
9789       }
9790     }
9791     }
9792
9793     if (buf.size() > 0) {
9794       s->Write(buf.data(), buf.size());
9795     }
9796   }
9797 }
9798
9799 void ClangASTContext::DumpTypeName(const CompilerType &type) {
9800   if (ClangUtil::IsClangType(type)) {
9801     clang::QualType qual_type(
9802         ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
9803
9804     const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9805     switch (type_class) {
9806     case clang::Type::Record: {
9807       const clang::CXXRecordDecl *cxx_record_decl =
9808           qual_type->getAsCXXRecordDecl();
9809       if (cxx_record_decl)
9810         printf("class %s", cxx_record_decl->getName().str().c_str());
9811     } break;
9812
9813     case clang::Type::Enum: {
9814       clang::EnumDecl *enum_decl =
9815           llvm::cast<clang::EnumType>(qual_type)->getDecl();
9816       if (enum_decl) {
9817         printf("enum %s", enum_decl->getName().str().c_str());
9818       }
9819     } break;
9820
9821     case clang::Type::ObjCObject:
9822     case clang::Type::ObjCInterface: {
9823       const clang::ObjCObjectType *objc_class_type =
9824           llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
9825       if (objc_class_type) {
9826         clang::ObjCInterfaceDecl *class_interface_decl =
9827             objc_class_type->getInterface();
9828         // We currently can't complete objective C types through the newly
9829         // added ASTContext because it only supports TagDecl objects right
9830         // now...
9831         if (class_interface_decl)
9832           printf("@class %s", class_interface_decl->getName().str().c_str());
9833       }
9834     } break;
9835
9836     case clang::Type::Typedef:
9837       printf("typedef %s", llvm::cast<clang::TypedefType>(qual_type)
9838                                ->getDecl()
9839                                ->getName()
9840                                .str()
9841                                .c_str());
9842       break;
9843
9844     case clang::Type::Auto:
9845       printf("auto ");
9846       return DumpTypeName(CompilerType(type.GetTypeSystem(),
9847                                        llvm::cast<clang::AutoType>(qual_type)
9848                                            ->getDeducedType()
9849                                            .getAsOpaquePtr()));
9850
9851     case clang::Type::Elaborated:
9852       printf("elaborated ");
9853       return DumpTypeName(CompilerType(
9854           type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
9855                                     ->getNamedType()
9856                                     .getAsOpaquePtr()));
9857
9858     case clang::Type::Paren:
9859       printf("paren ");
9860       return DumpTypeName(CompilerType(
9861           type.GetTypeSystem(),
9862           llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
9863
9864     default:
9865       printf("ClangASTContext::DumpTypeName() type_class = %u", type_class);
9866       break;
9867     }
9868   }
9869 }
9870
9871 clang::ClassTemplateDecl *ClangASTContext::ParseClassTemplateDecl(
9872     clang::DeclContext *decl_ctx, lldb::AccessType access_type,
9873     const char *parent_name, int tag_decl_kind,
9874     const ClangASTContext::TemplateParameterInfos &template_param_infos) {
9875   if (template_param_infos.IsValid()) {
9876     std::string template_basename(parent_name);
9877     template_basename.erase(template_basename.find('<'));
9878
9879     return CreateClassTemplateDecl(decl_ctx, access_type,
9880                                    template_basename.c_str(), tag_decl_kind,
9881                                    template_param_infos);
9882   }
9883   return nullptr;
9884 }
9885
9886 void ClangASTContext::CompleteTagDecl(void *baton, clang::TagDecl *decl) {
9887   ClangASTContext *ast = (ClangASTContext *)baton;
9888   SymbolFile *sym_file = ast->GetSymbolFile();
9889   if (sym_file) {
9890     CompilerType clang_type = GetTypeForDecl(decl);
9891     if (clang_type)
9892       sym_file->CompleteType(clang_type);
9893   }
9894 }
9895
9896 void ClangASTContext::CompleteObjCInterfaceDecl(
9897     void *baton, clang::ObjCInterfaceDecl *decl) {
9898   ClangASTContext *ast = (ClangASTContext *)baton;
9899   SymbolFile *sym_file = ast->GetSymbolFile();
9900   if (sym_file) {
9901     CompilerType clang_type = GetTypeForDecl(decl);
9902     if (clang_type)
9903       sym_file->CompleteType(clang_type);
9904   }
9905 }
9906
9907 DWARFASTParser *ClangASTContext::GetDWARFParser() {
9908   if (!m_dwarf_ast_parser_up)
9909     m_dwarf_ast_parser_up.reset(new DWARFASTParserClang(*this));
9910   return m_dwarf_ast_parser_up.get();
9911 }
9912
9913 #ifdef LLDB_ENABLE_ALL
9914 PDBASTParser *ClangASTContext::GetPDBParser() {
9915   if (!m_pdb_ast_parser_up)
9916     m_pdb_ast_parser_up.reset(new PDBASTParser(*this));
9917   return m_pdb_ast_parser_up.get();
9918 }
9919 #endif // LLDB_ENABLE_ALL
9920
9921 bool ClangASTContext::LayoutRecordType(
9922     void *baton, const clang::RecordDecl *record_decl, uint64_t &bit_size,
9923     uint64_t &alignment,
9924     llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
9925     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9926         &base_offsets,
9927     llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9928         &vbase_offsets) {
9929   ClangASTContext *ast = (ClangASTContext *)baton;
9930   lldb_private::ClangASTImporter *importer = nullptr;
9931   if (ast->m_dwarf_ast_parser_up)
9932     importer = &ast->m_dwarf_ast_parser_up->GetClangASTImporter();
9933 #ifdef LLDB_ENABLE_ALL
9934   if (!importer && ast->m_pdb_ast_parser_up)
9935     importer = &ast->m_pdb_ast_parser_up->GetClangASTImporter();
9936 #endif // LLDB_ENABLE_ALL
9937   if (!importer)
9938     return false;
9939
9940   return importer->LayoutRecordType(record_decl, bit_size, alignment,
9941                                     field_offsets, base_offsets, vbase_offsets);
9942 }
9943
9944 // CompilerDecl override functions
9945
9946 ConstString ClangASTContext::DeclGetName(void *opaque_decl) {
9947   if (opaque_decl) {
9948     clang::NamedDecl *nd =
9949         llvm::dyn_cast<NamedDecl>((clang::Decl *)opaque_decl);
9950     if (nd != nullptr)
9951       return ConstString(nd->getDeclName().getAsString());
9952   }
9953   return ConstString();
9954 }
9955
9956 ConstString ClangASTContext::DeclGetMangledName(void *opaque_decl) {
9957   if (opaque_decl) {
9958     clang::NamedDecl *nd =
9959         llvm::dyn_cast<clang::NamedDecl>((clang::Decl *)opaque_decl);
9960     if (nd != nullptr && !llvm::isa<clang::ObjCMethodDecl>(nd)) {
9961       clang::MangleContext *mc = getMangleContext();
9962       if (mc && mc->shouldMangleCXXName(nd)) {
9963         llvm::SmallVector<char, 1024> buf;
9964         llvm::raw_svector_ostream llvm_ostrm(buf);
9965         if (llvm::isa<clang::CXXConstructorDecl>(nd)) {
9966           mc->mangleCXXCtor(llvm::dyn_cast<clang::CXXConstructorDecl>(nd),
9967                             Ctor_Complete, llvm_ostrm);
9968         } else if (llvm::isa<clang::CXXDestructorDecl>(nd)) {
9969           mc->mangleCXXDtor(llvm::dyn_cast<clang::CXXDestructorDecl>(nd),
9970                             Dtor_Complete, llvm_ostrm);
9971         } else {
9972           mc->mangleName(nd, llvm_ostrm);
9973         }
9974         if (buf.size() > 0)
9975           return ConstString(buf.data(), buf.size());
9976       }
9977     }
9978   }
9979   return ConstString();
9980 }
9981
9982 CompilerDeclContext ClangASTContext::DeclGetDeclContext(void *opaque_decl) {
9983   if (opaque_decl)
9984     return CompilerDeclContext(this,
9985                                ((clang::Decl *)opaque_decl)->getDeclContext());
9986   else
9987     return CompilerDeclContext();
9988 }
9989
9990 CompilerType ClangASTContext::DeclGetFunctionReturnType(void *opaque_decl) {
9991   if (clang::FunctionDecl *func_decl =
9992           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9993     return CompilerType(this, func_decl->getReturnType().getAsOpaquePtr());
9994   if (clang::ObjCMethodDecl *objc_method =
9995           llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9996     return CompilerType(this, objc_method->getReturnType().getAsOpaquePtr());
9997   else
9998     return CompilerType();
9999 }
10000
10001 size_t ClangASTContext::DeclGetFunctionNumArguments(void *opaque_decl) {
10002   if (clang::FunctionDecl *func_decl =
10003           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
10004     return func_decl->param_size();
10005   if (clang::ObjCMethodDecl *objc_method =
10006           llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
10007     return objc_method->param_size();
10008   else
10009     return 0;
10010 }
10011
10012 CompilerType ClangASTContext::DeclGetFunctionArgumentType(void *opaque_decl,
10013                                                           size_t idx) {
10014   if (clang::FunctionDecl *func_decl =
10015           llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) {
10016     if (idx < func_decl->param_size()) {
10017       ParmVarDecl *var_decl = func_decl->getParamDecl(idx);
10018       if (var_decl)
10019         return CompilerType(this, var_decl->getOriginalType().getAsOpaquePtr());
10020     }
10021   } else if (clang::ObjCMethodDecl *objc_method =
10022                  llvm::dyn_cast<clang::ObjCMethodDecl>(
10023                      (clang::Decl *)opaque_decl)) {
10024     if (idx < objc_method->param_size())
10025       return CompilerType(
10026           this,
10027           objc_method->parameters()[idx]->getOriginalType().getAsOpaquePtr());
10028   }
10029   return CompilerType();
10030 }
10031
10032 // CompilerDeclContext functions
10033
10034 std::vector<CompilerDecl> ClangASTContext::DeclContextFindDeclByName(
10035     void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) {
10036   std::vector<CompilerDecl> found_decls;
10037   if (opaque_decl_ctx) {
10038     DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx;
10039     std::set<DeclContext *> searched;
10040     std::multimap<DeclContext *, DeclContext *> search_queue;
10041     SymbolFile *symbol_file = GetSymbolFile();
10042
10043     for (clang::DeclContext *decl_context = root_decl_ctx;
10044          decl_context != nullptr && found_decls.empty();
10045          decl_context = decl_context->getParent()) {
10046       search_queue.insert(std::make_pair(decl_context, decl_context));
10047
10048       for (auto it = search_queue.find(decl_context); it != search_queue.end();
10049            it++) {
10050         if (!searched.insert(it->second).second)
10051           continue;
10052         symbol_file->ParseDeclsForContext(
10053             CompilerDeclContext(this, it->second));
10054
10055         for (clang::Decl *child : it->second->decls()) {
10056           if (clang::UsingDirectiveDecl *ud =
10057                   llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
10058             if (ignore_using_decls)
10059               continue;
10060             clang::DeclContext *from = ud->getCommonAncestor();
10061             if (searched.find(ud->getNominatedNamespace()) == searched.end())
10062               search_queue.insert(
10063                   std::make_pair(from, ud->getNominatedNamespace()));
10064           } else if (clang::UsingDecl *ud =
10065                          llvm::dyn_cast<clang::UsingDecl>(child)) {
10066             if (ignore_using_decls)
10067               continue;
10068             for (clang::UsingShadowDecl *usd : ud->shadows()) {
10069               clang::Decl *target = usd->getTargetDecl();
10070               if (clang::NamedDecl *nd =
10071                       llvm::dyn_cast<clang::NamedDecl>(target)) {
10072                 IdentifierInfo *ii = nd->getIdentifier();
10073                 if (ii != nullptr &&
10074                     ii->getName().equals(name.AsCString(nullptr)))
10075                   found_decls.push_back(CompilerDecl(this, nd));
10076               }
10077             }
10078           } else if (clang::NamedDecl *nd =
10079                          llvm::dyn_cast<clang::NamedDecl>(child)) {
10080             IdentifierInfo *ii = nd->getIdentifier();
10081             if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr)))
10082               found_decls.push_back(CompilerDecl(this, nd));
10083           }
10084         }
10085       }
10086     }
10087   }
10088   return found_decls;
10089 }
10090
10091 // Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents,
10092 // and return the number of levels it took to find it, or
10093 // LLDB_INVALID_DECL_LEVEL if not found.  If the decl was imported via a using
10094 // declaration, its name and/or type, if set, will be used to check that the
10095 // decl found in the scope is a match.
10096 //
10097 // The optional name is required by languages (like C++) to handle using
10098 // declarations like:
10099 //
10100 //     void poo();
10101 //     namespace ns {
10102 //         void foo();
10103 //         void goo();
10104 //     }
10105 //     void bar() {
10106 //         using ns::foo;
10107 //         // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and
10108 //         // LLDB_INVALID_DECL_LEVEL for 'goo'.
10109 //     }
10110 //
10111 // The optional type is useful in the case that there's a specific overload
10112 // that we're looking for that might otherwise be shadowed, like:
10113 //
10114 //     void foo(int);
10115 //     namespace ns {
10116 //         void foo();
10117 //     }
10118 //     void bar() {
10119 //         using ns::foo;
10120 //         // CountDeclLevels returns 0 for { 'foo', void() },
10121 //         // 1 for { 'foo', void(int) }, and
10122 //         // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }.
10123 //     }
10124 //
10125 // NOTE: Because file statics are at the TranslationUnit along with globals, a
10126 // function at file scope will return the same level as a function at global
10127 // scope. Ideally we'd like to treat the file scope as an additional scope just
10128 // below the global scope.  More work needs to be done to recognise that, if
10129 // the decl we're trying to look up is static, we should compare its source
10130 // file with that of the current scope and return a lower number for it.
10131 uint32_t ClangASTContext::CountDeclLevels(clang::DeclContext *frame_decl_ctx,
10132                                           clang::DeclContext *child_decl_ctx,
10133                                           ConstString *child_name,
10134                                           CompilerType *child_type) {
10135   if (frame_decl_ctx) {
10136     std::set<DeclContext *> searched;
10137     std::multimap<DeclContext *, DeclContext *> search_queue;
10138     SymbolFile *symbol_file = GetSymbolFile();
10139
10140     // Get the lookup scope for the decl we're trying to find.
10141     clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent();
10142
10143     // Look for it in our scope's decl context and its parents.
10144     uint32_t level = 0;
10145     for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr;
10146          decl_ctx = decl_ctx->getParent()) {
10147       if (!decl_ctx->isLookupContext())
10148         continue;
10149       if (decl_ctx == parent_decl_ctx)
10150         // Found it!
10151         return level;
10152       search_queue.insert(std::make_pair(decl_ctx, decl_ctx));
10153       for (auto it = search_queue.find(decl_ctx); it != search_queue.end();
10154            it++) {
10155         if (searched.find(it->second) != searched.end())
10156           continue;
10157
10158         // Currently DWARF has one shared translation unit for all Decls at top
10159         // level, so this would erroneously find using statements anywhere.  So
10160         // don't look at the top-level translation unit.
10161         // TODO fix this and add a testcase that depends on it.
10162
10163         if (llvm::isa<clang::TranslationUnitDecl>(it->second))
10164           continue;
10165
10166         searched.insert(it->second);
10167         symbol_file->ParseDeclsForContext(
10168             CompilerDeclContext(this, it->second));
10169
10170         for (clang::Decl *child : it->second->decls()) {
10171           if (clang::UsingDirectiveDecl *ud =
10172                   llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
10173             clang::DeclContext *ns = ud->getNominatedNamespace();
10174             if (ns == parent_decl_ctx)
10175               // Found it!
10176               return level;
10177             clang::DeclContext *from = ud->getCommonAncestor();
10178             if (searched.find(ns) == searched.end())
10179               search_queue.insert(std::make_pair(from, ns));
10180           } else if (child_name) {
10181             if (clang::UsingDecl *ud =
10182                     llvm::dyn_cast<clang::UsingDecl>(child)) {
10183               for (clang::UsingShadowDecl *usd : ud->shadows()) {
10184                 clang::Decl *target = usd->getTargetDecl();
10185                 clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(target);
10186                 if (!nd)
10187                   continue;
10188                 // Check names.
10189                 IdentifierInfo *ii = nd->getIdentifier();
10190                 if (ii == nullptr ||
10191                     !ii->getName().equals(child_name->AsCString(nullptr)))
10192                   continue;
10193                 // Check types, if one was provided.
10194                 if (child_type) {
10195                   CompilerType clang_type = ClangASTContext::GetTypeForDecl(nd);
10196                   if (!AreTypesSame(clang_type, *child_type,
10197                                     /*ignore_qualifiers=*/true))
10198                     continue;
10199                 }
10200                 // Found it!
10201                 return level;
10202               }
10203             }
10204           }
10205         }
10206       }
10207       ++level;
10208     }
10209   }
10210   return LLDB_INVALID_DECL_LEVEL;
10211 }
10212
10213 bool ClangASTContext::DeclContextIsStructUnionOrClass(void *opaque_decl_ctx) {
10214   if (opaque_decl_ctx)
10215     return ((clang::DeclContext *)opaque_decl_ctx)->isRecord();
10216   else
10217     return false;
10218 }
10219
10220 ConstString ClangASTContext::DeclContextGetName(void *opaque_decl_ctx) {
10221   if (opaque_decl_ctx) {
10222     clang::NamedDecl *named_decl =
10223         llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
10224     if (named_decl)
10225       return ConstString(named_decl->getName());
10226   }
10227   return ConstString();
10228 }
10229
10230 ConstString
10231 ClangASTContext::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) {
10232   if (opaque_decl_ctx) {
10233     clang::NamedDecl *named_decl =
10234         llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
10235     if (named_decl)
10236       return ConstString(
10237           llvm::StringRef(named_decl->getQualifiedNameAsString()));
10238   }
10239   return ConstString();
10240 }
10241
10242 bool ClangASTContext::DeclContextIsClassMethod(
10243     void *opaque_decl_ctx, lldb::LanguageType *language_ptr,
10244     bool *is_instance_method_ptr, ConstString *language_object_name_ptr) {
10245   if (opaque_decl_ctx) {
10246     clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
10247     if (ObjCMethodDecl *objc_method =
10248             llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx)) {
10249       if (is_instance_method_ptr)
10250         *is_instance_method_ptr = objc_method->isInstanceMethod();
10251       if (language_ptr)
10252         *language_ptr = eLanguageTypeObjC;
10253       if (language_object_name_ptr)
10254         language_object_name_ptr->SetCString("self");
10255       return true;
10256     } else if (CXXMethodDecl *cxx_method =
10257                    llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx)) {
10258       if (is_instance_method_ptr)
10259         *is_instance_method_ptr = cxx_method->isInstance();
10260       if (language_ptr)
10261         *language_ptr = eLanguageTypeC_plus_plus;
10262       if (language_object_name_ptr)
10263         language_object_name_ptr->SetCString("this");
10264       return true;
10265     } else if (clang::FunctionDecl *function_decl =
10266                    llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
10267       ClangASTMetadata *metadata =
10268           GetMetadata(&decl_ctx->getParentASTContext(), function_decl);
10269       if (metadata && metadata->HasObjectPtr()) {
10270         if (is_instance_method_ptr)
10271           *is_instance_method_ptr = true;
10272         if (language_ptr)
10273           *language_ptr = eLanguageTypeObjC;
10274         if (language_object_name_ptr)
10275           language_object_name_ptr->SetCString(metadata->GetObjectPtrName());
10276         return true;
10277       }
10278     }
10279   }
10280   return false;
10281 }
10282
10283 bool ClangASTContext::DeclContextIsContainedInLookup(
10284     void *opaque_decl_ctx, void *other_opaque_decl_ctx) {
10285   auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
10286   auto *other = (clang::DeclContext *)other_opaque_decl_ctx;
10287
10288   do {
10289     // A decl context always includes its own contents in its lookup.
10290     if (decl_ctx == other)
10291       return true;
10292
10293     // If we have an inline namespace, then the lookup of the parent context
10294     // also includes the inline namespace contents.
10295   } while (other->isInlineNamespace() && (other = other->getParent()));
10296
10297   return false;
10298 }
10299
10300 clang::DeclContext *
10301 ClangASTContext::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) {
10302   if (dc.IsClang())
10303     return (clang::DeclContext *)dc.GetOpaqueDeclContext();
10304   return nullptr;
10305 }
10306
10307 ObjCMethodDecl *
10308 ClangASTContext::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) {
10309   if (dc.IsClang())
10310     return llvm::dyn_cast<clang::ObjCMethodDecl>(
10311         (clang::DeclContext *)dc.GetOpaqueDeclContext());
10312   return nullptr;
10313 }
10314
10315 CXXMethodDecl *
10316 ClangASTContext::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) {
10317   if (dc.IsClang())
10318     return llvm::dyn_cast<clang::CXXMethodDecl>(
10319         (clang::DeclContext *)dc.GetOpaqueDeclContext());
10320   return nullptr;
10321 }
10322
10323 clang::FunctionDecl *
10324 ClangASTContext::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) {
10325   if (dc.IsClang())
10326     return llvm::dyn_cast<clang::FunctionDecl>(
10327         (clang::DeclContext *)dc.GetOpaqueDeclContext());
10328   return nullptr;
10329 }
10330
10331 clang::NamespaceDecl *
10332 ClangASTContext::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) {
10333   if (dc.IsClang())
10334     return llvm::dyn_cast<clang::NamespaceDecl>(
10335         (clang::DeclContext *)dc.GetOpaqueDeclContext());
10336   return nullptr;
10337 }
10338
10339 ClangASTMetadata *
10340 ClangASTContext::DeclContextGetMetaData(const CompilerDeclContext &dc,
10341                                         const void *object) {
10342   clang::ASTContext *ast = DeclContextGetClangASTContext(dc);
10343   if (ast)
10344     return ClangASTContext::GetMetadata(ast, object);
10345   return nullptr;
10346 }
10347
10348 clang::ASTContext *
10349 ClangASTContext::DeclContextGetClangASTContext(const CompilerDeclContext &dc) {
10350   ClangASTContext *ast =
10351       llvm::dyn_cast_or_null<ClangASTContext>(dc.GetTypeSystem());
10352   if (ast)
10353     return ast->getASTContext();
10354   return nullptr;
10355 }
10356
10357 ClangASTContextForExpressions::ClangASTContextForExpressions(Target &target)
10358     : ClangASTContext(target.GetArchitecture().GetTriple().getTriple().c_str()),
10359       m_target_wp(target.shared_from_this()),
10360       m_persistent_variables(new ClangPersistentVariables) {}
10361
10362 UserExpression *ClangASTContextForExpressions::GetUserExpression(
10363     llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
10364     Expression::ResultType desired_type,
10365     const EvaluateExpressionOptions &options,
10366     ValueObject *ctx_obj) {
10367   TargetSP target_sp = m_target_wp.lock();
10368   if (!target_sp)
10369     return nullptr;
10370
10371   return new ClangUserExpression(*target_sp.get(), expr, prefix, language,
10372                                  desired_type, options, ctx_obj);
10373 }
10374
10375 FunctionCaller *ClangASTContextForExpressions::GetFunctionCaller(
10376     const CompilerType &return_type, const Address &function_address,
10377     const ValueList &arg_value_list, const char *name) {
10378   TargetSP target_sp = m_target_wp.lock();
10379   if (!target_sp)
10380     return nullptr;
10381
10382   Process *process = target_sp->GetProcessSP().get();
10383   if (!process)
10384     return nullptr;
10385
10386   return new ClangFunctionCaller(*process, return_type, function_address,
10387                                  arg_value_list, name);
10388 }
10389
10390 UtilityFunction *
10391 ClangASTContextForExpressions::GetUtilityFunction(const char *text,
10392                                                   const char *name) {
10393   TargetSP target_sp = m_target_wp.lock();
10394   if (!target_sp)
10395     return nullptr;
10396
10397   return new ClangUtilityFunction(*target_sp.get(), text, name);
10398 }
10399
10400 PersistentExpressionState *
10401 ClangASTContextForExpressions::GetPersistentExpressionState() {
10402   return m_persistent_variables.get();
10403 }
10404
10405 clang::ExternalASTMerger &
10406 ClangASTContextForExpressions::GetMergerUnchecked() {
10407   lldbassert(m_scratch_ast_source_up != nullptr);
10408   return m_scratch_ast_source_up->GetMergerUnchecked();
10409 }