1 //===-- Type.cpp ------------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include <stdio.h>
11 
12 #include "lldb/Core/Module.h"
13 #include "lldb/Utility/DataBufferHeap.h"
14 #include "lldb/Utility/DataExtractor.h"
15 #include "lldb/Utility/Scalar.h"
16 #include "lldb/Utility/StreamString.h"
17 
18 #include "lldb/Symbol/CompilerType.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Symbol/SymbolContextScope.h"
21 #include "lldb/Symbol/SymbolFile.h"
22 #include "lldb/Symbol/SymbolVendor.h"
23 #include "lldb/Symbol/Type.h"
24 #include "lldb/Symbol/TypeList.h"
25 #include "lldb/Symbol/TypeSystem.h"
26 
27 #include "lldb/Target/ExecutionContext.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/Target.h"
30 
31 #include "llvm/ADT/StringRef.h"
32 
33 #include "clang/AST/Decl.h"
34 #include "clang/AST/DeclObjC.h"
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 void CompilerContext::Dump() const {
40   switch (type) {
41   case CompilerContextKind::Invalid:
42     printf("Invalid");
43     break;
44   case CompilerContextKind::TranslationUnit:
45     printf("TranslationUnit");
46     break;
47   case CompilerContextKind::Module:
48     printf("Module");
49     break;
50   case CompilerContextKind::Namespace:
51     printf("Namespace");
52     break;
53   case CompilerContextKind::Class:
54     printf("Class");
55     break;
56   case CompilerContextKind::Structure:
57     printf("Structure");
58     break;
59   case CompilerContextKind::Union:
60     printf("Union");
61     break;
62   case CompilerContextKind::Function:
63     printf("Function");
64     break;
65   case CompilerContextKind::Variable:
66     printf("Variable");
67     break;
68   case CompilerContextKind::Enumeration:
69     printf("Enumeration");
70     break;
71   case CompilerContextKind::Typedef:
72     printf("Typedef");
73     break;
74   }
75   printf("(\"%s\")\n", name.GetCString());
76 }
77 
78 class TypeAppendVisitor {
79 public:
80   TypeAppendVisitor(TypeListImpl &type_list) : m_type_list(type_list) {}
81 
82   bool operator()(const lldb::TypeSP &type) {
83     m_type_list.Append(TypeImplSP(new TypeImpl(type)));
84     return true;
85   }
86 
87 private:
88   TypeListImpl &m_type_list;
89 };
90 
91 void TypeListImpl::Append(const lldb_private::TypeList &type_list) {
92   TypeAppendVisitor cb(*this);
93   type_list.ForEach(cb);
94 }
95 
96 SymbolFileType::SymbolFileType(SymbolFile &symbol_file,
97                                const lldb::TypeSP &type_sp)
98     : UserID(type_sp ? type_sp->GetID() : LLDB_INVALID_UID),
99       m_symbol_file(symbol_file), m_type_sp(type_sp) {}
100 
101 Type *SymbolFileType::GetType() {
102   if (!m_type_sp) {
103     Type *resolved_type = m_symbol_file.ResolveTypeUID(GetID());
104     if (resolved_type)
105       m_type_sp = resolved_type->shared_from_this();
106   }
107   return m_type_sp.get();
108 }
109 
110 Type::Type(lldb::user_id_t uid, SymbolFile *symbol_file,
111            const ConstString &name, uint64_t byte_size,
112            SymbolContextScope *context, user_id_t encoding_uid,
113            EncodingDataType encoding_uid_type, const Declaration &decl,
114            const CompilerType &compiler_type,
115            ResolveState compiler_type_resolve_state)
116     : std::enable_shared_from_this<Type>(), UserID(uid), m_name(name),
117       m_symbol_file(symbol_file), m_context(context), m_encoding_type(nullptr),
118       m_encoding_uid(encoding_uid), m_encoding_uid_type(encoding_uid_type),
119       m_byte_size(byte_size), m_decl(decl), m_compiler_type(compiler_type) {
120   m_flags.compiler_type_resolve_state =
121       (compiler_type ? compiler_type_resolve_state : eResolveStateUnresolved);
122   m_flags.is_complete_objc_class = false;
123 }
124 
125 Type::Type()
126     : std::enable_shared_from_this<Type>(), UserID(0), m_name("<INVALID TYPE>"),
127       m_symbol_file(nullptr), m_context(nullptr), m_encoding_type(nullptr),
128       m_encoding_uid(LLDB_INVALID_UID), m_encoding_uid_type(eEncodingInvalid),
129       m_byte_size(0), m_decl(), m_compiler_type() {
130   m_flags.compiler_type_resolve_state = eResolveStateUnresolved;
131   m_flags.is_complete_objc_class = false;
132 }
133 
134 Type::Type(const Type &rhs)
135     : std::enable_shared_from_this<Type>(rhs), UserID(rhs), m_name(rhs.m_name),
136       m_symbol_file(rhs.m_symbol_file), m_context(rhs.m_context),
137       m_encoding_type(rhs.m_encoding_type), m_encoding_uid(rhs.m_encoding_uid),
138       m_encoding_uid_type(rhs.m_encoding_uid_type),
139       m_byte_size(rhs.m_byte_size), m_decl(rhs.m_decl),
140       m_compiler_type(rhs.m_compiler_type), m_flags(rhs.m_flags) {}
141 
142 const Type &Type::operator=(const Type &rhs) {
143   if (this != &rhs) {
144   }
145   return *this;
146 }
147 
148 void Type::GetDescription(Stream *s, lldb::DescriptionLevel level,
149                           bool show_name) {
150   *s << "id = " << (const UserID &)*this;
151 
152   // Call the name accessor to make sure we resolve the type name
153   if (show_name) {
154     const ConstString &type_name = GetName();
155     if (type_name) {
156       *s << ", name = \"" << type_name << '"';
157       ConstString qualified_type_name(GetQualifiedName());
158       if (qualified_type_name != type_name) {
159         *s << ", qualified = \"" << qualified_type_name << '"';
160       }
161     }
162   }
163 
164   // Call the get byte size accesor so we resolve our byte size
165   if (GetByteSize())
166     s->Printf(", byte-size = %" PRIu64, m_byte_size);
167   bool show_fullpaths = (level == lldb::eDescriptionLevelVerbose);
168   m_decl.Dump(s, show_fullpaths);
169 
170   if (m_compiler_type.IsValid()) {
171     *s << ", compiler_type = \"";
172     GetForwardCompilerType().DumpTypeDescription(s);
173     *s << '"';
174   } else if (m_encoding_uid != LLDB_INVALID_UID) {
175     s->Printf(", type_uid = 0x%8.8" PRIx64, m_encoding_uid);
176     switch (m_encoding_uid_type) {
177     case eEncodingInvalid:
178       break;
179     case eEncodingIsUID:
180       s->PutCString(" (unresolved type)");
181       break;
182     case eEncodingIsConstUID:
183       s->PutCString(" (unresolved const type)");
184       break;
185     case eEncodingIsRestrictUID:
186       s->PutCString(" (unresolved restrict type)");
187       break;
188     case eEncodingIsVolatileUID:
189       s->PutCString(" (unresolved volatile type)");
190       break;
191     case eEncodingIsTypedefUID:
192       s->PutCString(" (unresolved typedef)");
193       break;
194     case eEncodingIsPointerUID:
195       s->PutCString(" (unresolved pointer)");
196       break;
197     case eEncodingIsLValueReferenceUID:
198       s->PutCString(" (unresolved L value reference)");
199       break;
200     case eEncodingIsRValueReferenceUID:
201       s->PutCString(" (unresolved R value reference)");
202       break;
203     case eEncodingIsSyntheticUID:
204       s->PutCString(" (synthetic type)");
205       break;
206     }
207   }
208 }
209 
210 void Type::Dump(Stream *s, bool show_context) {
211   s->Printf("%p: ", static_cast<void *>(this));
212   s->Indent();
213   *s << "Type" << static_cast<const UserID &>(*this) << ' ';
214   if (m_name)
215     *s << ", name = \"" << m_name << "\"";
216 
217   if (m_byte_size != 0)
218     s->Printf(", size = %" PRIu64, m_byte_size);
219 
220   if (show_context && m_context != nullptr) {
221     s->PutCString(", context = ( ");
222     m_context->DumpSymbolContext(s);
223     s->PutCString(" )");
224   }
225 
226   bool show_fullpaths = false;
227   m_decl.Dump(s, show_fullpaths);
228 
229   if (m_compiler_type.IsValid()) {
230     *s << ", compiler_type = " << m_compiler_type.GetOpaqueQualType() << ' ';
231     GetForwardCompilerType().DumpTypeDescription(s);
232   } else if (m_encoding_uid != LLDB_INVALID_UID) {
233     *s << ", type_data = " << (uint64_t)m_encoding_uid;
234     switch (m_encoding_uid_type) {
235     case eEncodingInvalid:
236       break;
237     case eEncodingIsUID:
238       s->PutCString(" (unresolved type)");
239       break;
240     case eEncodingIsConstUID:
241       s->PutCString(" (unresolved const type)");
242       break;
243     case eEncodingIsRestrictUID:
244       s->PutCString(" (unresolved restrict type)");
245       break;
246     case eEncodingIsVolatileUID:
247       s->PutCString(" (unresolved volatile type)");
248       break;
249     case eEncodingIsTypedefUID:
250       s->PutCString(" (unresolved typedef)");
251       break;
252     case eEncodingIsPointerUID:
253       s->PutCString(" (unresolved pointer)");
254       break;
255     case eEncodingIsLValueReferenceUID:
256       s->PutCString(" (unresolved L value reference)");
257       break;
258     case eEncodingIsRValueReferenceUID:
259       s->PutCString(" (unresolved R value reference)");
260       break;
261     case eEncodingIsSyntheticUID:
262       s->PutCString(" (synthetic type)");
263       break;
264     }
265   }
266 
267   //
268   //  if (m_access)
269   //      s->Printf(", access = %u", m_access);
270   s->EOL();
271 }
272 
273 const ConstString &Type::GetName() {
274   if (!m_name)
275     m_name = GetForwardCompilerType().GetConstTypeName();
276   return m_name;
277 }
278 
279 void Type::DumpTypeName(Stream *s) { GetName().Dump(s, "<invalid-type-name>"); }
280 
281 void Type::DumpValue(ExecutionContext *exe_ctx, Stream *s,
282                      const DataExtractor &data, uint32_t data_byte_offset,
283                      bool show_types, bool show_summary, bool verbose,
284                      lldb::Format format) {
285   if (ResolveClangType(eResolveStateForward)) {
286     if (show_types) {
287       s->PutChar('(');
288       if (verbose)
289         s->Printf("Type{0x%8.8" PRIx64 "} ", GetID());
290       DumpTypeName(s);
291       s->PutCString(") ");
292     }
293 
294     GetForwardCompilerType().DumpValue(
295         exe_ctx, s, format == lldb::eFormatDefault ? GetFormat() : format, data,
296         data_byte_offset, GetByteSize(),
297         0, // Bitfield bit size
298         0, // Bitfield bit offset
299         show_types, show_summary, verbose, 0);
300   }
301 }
302 
303 Type *Type::GetEncodingType() {
304   if (m_encoding_type == nullptr && m_encoding_uid != LLDB_INVALID_UID)
305     m_encoding_type = m_symbol_file->ResolveTypeUID(m_encoding_uid);
306   return m_encoding_type;
307 }
308 
309 uint64_t Type::GetByteSize() {
310   if (m_byte_size == 0) {
311     switch (m_encoding_uid_type) {
312     case eEncodingInvalid:
313     case eEncodingIsSyntheticUID:
314       break;
315     case eEncodingIsUID:
316     case eEncodingIsConstUID:
317     case eEncodingIsRestrictUID:
318     case eEncodingIsVolatileUID:
319     case eEncodingIsTypedefUID: {
320       Type *encoding_type = GetEncodingType();
321       if (encoding_type)
322         m_byte_size = encoding_type->GetByteSize();
323       if (m_byte_size == 0)
324         m_byte_size = GetLayoutCompilerType().GetByteSize(nullptr);
325     } break;
326 
327     // If we are a pointer or reference, then this is just a pointer size;
328     case eEncodingIsPointerUID:
329     case eEncodingIsLValueReferenceUID:
330     case eEncodingIsRValueReferenceUID: {
331       if (ArchSpec arch = m_symbol_file->GetObjectFile()->GetArchitecture())
332         m_byte_size = arch.GetAddressByteSize();
333     } break;
334     }
335   }
336   return m_byte_size;
337 }
338 
339 uint32_t Type::GetNumChildren(bool omit_empty_base_classes) {
340   return GetForwardCompilerType().GetNumChildren(omit_empty_base_classes, nullptr);
341 }
342 
343 bool Type::IsAggregateType() {
344   return GetForwardCompilerType().IsAggregateType();
345 }
346 
347 lldb::TypeSP Type::GetTypedefType() {
348   lldb::TypeSP type_sp;
349   if (IsTypedef()) {
350     Type *typedef_type = m_symbol_file->ResolveTypeUID(m_encoding_uid);
351     if (typedef_type)
352       type_sp = typedef_type->shared_from_this();
353   }
354   return type_sp;
355 }
356 
357 lldb::Format Type::GetFormat() { return GetForwardCompilerType().GetFormat(); }
358 
359 lldb::Encoding Type::GetEncoding(uint64_t &count) {
360   // Make sure we resolve our type if it already hasn't been.
361   return GetForwardCompilerType().GetEncoding(count);
362 }
363 
364 bool Type::DumpValueInMemory(ExecutionContext *exe_ctx, Stream *s,
365                              lldb::addr_t address, AddressType address_type,
366                              bool show_types, bool show_summary, bool verbose) {
367   if (address != LLDB_INVALID_ADDRESS) {
368     DataExtractor data;
369     Target *target = nullptr;
370     if (exe_ctx)
371       target = exe_ctx->GetTargetPtr();
372     if (target)
373       data.SetByteOrder(target->GetArchitecture().GetByteOrder());
374     if (ReadFromMemory(exe_ctx, address, address_type, data)) {
375       DumpValue(exe_ctx, s, data, 0, show_types, show_summary, verbose);
376       return true;
377     }
378   }
379   return false;
380 }
381 
382 bool Type::ReadFromMemory(ExecutionContext *exe_ctx, lldb::addr_t addr,
383                           AddressType address_type, DataExtractor &data) {
384   if (address_type == eAddressTypeFile) {
385     // Can't convert a file address to anything valid without more context
386     // (which Module it came from)
387     return false;
388   }
389 
390   const uint64_t byte_size = GetByteSize();
391   if (data.GetByteSize() < byte_size) {
392     lldb::DataBufferSP data_sp(new DataBufferHeap(byte_size, '\0'));
393     data.SetData(data_sp);
394   }
395 
396   uint8_t *dst = const_cast<uint8_t *>(data.PeekData(0, byte_size));
397   if (dst != nullptr) {
398     if (address_type == eAddressTypeHost) {
399       // The address is an address in this process, so just copy it
400       if (addr == 0)
401         return false;
402       memcpy(dst, reinterpret_cast<uint8_t *>(addr), byte_size);
403       return true;
404     } else {
405       if (exe_ctx) {
406         Process *process = exe_ctx->GetProcessPtr();
407         if (process) {
408           Status error;
409           return exe_ctx->GetProcessPtr()->ReadMemory(addr, dst, byte_size,
410                                                       error) == byte_size;
411         }
412       }
413     }
414   }
415   return false;
416 }
417 
418 bool Type::WriteToMemory(ExecutionContext *exe_ctx, lldb::addr_t addr,
419                          AddressType address_type, DataExtractor &data) {
420   return false;
421 }
422 
423 TypeList *Type::GetTypeList() { return GetSymbolFile()->GetTypeList(); }
424 
425 const Declaration &Type::GetDeclaration() const { return m_decl; }
426 
427 bool Type::ResolveClangType(ResolveState compiler_type_resolve_state) {
428   // TODO: This needs to consider the correct type system to use.
429   Type *encoding_type = nullptr;
430   if (!m_compiler_type.IsValid()) {
431     encoding_type = GetEncodingType();
432     if (encoding_type) {
433       switch (m_encoding_uid_type) {
434       case eEncodingIsUID: {
435         CompilerType encoding_compiler_type =
436             encoding_type->GetForwardCompilerType();
437         if (encoding_compiler_type.IsValid()) {
438           m_compiler_type = encoding_compiler_type;
439           m_flags.compiler_type_resolve_state =
440               encoding_type->m_flags.compiler_type_resolve_state;
441         }
442       } break;
443 
444       case eEncodingIsConstUID:
445         m_compiler_type =
446             encoding_type->GetForwardCompilerType().AddConstModifier();
447         break;
448 
449       case eEncodingIsRestrictUID:
450         m_compiler_type =
451             encoding_type->GetForwardCompilerType().AddRestrictModifier();
452         break;
453 
454       case eEncodingIsVolatileUID:
455         m_compiler_type =
456             encoding_type->GetForwardCompilerType().AddVolatileModifier();
457         break;
458 
459       case eEncodingIsTypedefUID:
460         m_compiler_type = encoding_type->GetForwardCompilerType().CreateTypedef(
461             m_name.AsCString("__lldb_invalid_typedef_name"),
462             GetSymbolFile()->GetDeclContextContainingUID(GetID()));
463         m_name.Clear();
464         break;
465 
466       case eEncodingIsPointerUID:
467         m_compiler_type =
468             encoding_type->GetForwardCompilerType().GetPointerType();
469         break;
470 
471       case eEncodingIsLValueReferenceUID:
472         m_compiler_type =
473             encoding_type->GetForwardCompilerType().GetLValueReferenceType();
474         break;
475 
476       case eEncodingIsRValueReferenceUID:
477         m_compiler_type =
478             encoding_type->GetForwardCompilerType().GetRValueReferenceType();
479         break;
480 
481       default:
482         llvm_unreachable("Unhandled encoding_data_type.");
483       }
484     } else {
485       // We have no encoding type, return void?
486       TypeSystem *type_system =
487           m_symbol_file->GetTypeSystemForLanguage(eLanguageTypeC);
488       CompilerType void_compiler_type =
489           type_system->GetBasicTypeFromAST(eBasicTypeVoid);
490       switch (m_encoding_uid_type) {
491       case eEncodingIsUID:
492         m_compiler_type = void_compiler_type;
493         break;
494 
495       case eEncodingIsConstUID:
496         m_compiler_type = void_compiler_type.AddConstModifier();
497         break;
498 
499       case eEncodingIsRestrictUID:
500         m_compiler_type = void_compiler_type.AddRestrictModifier();
501         break;
502 
503       case eEncodingIsVolatileUID:
504         m_compiler_type = void_compiler_type.AddVolatileModifier();
505         break;
506 
507       case eEncodingIsTypedefUID:
508         m_compiler_type = void_compiler_type.CreateTypedef(
509             m_name.AsCString("__lldb_invalid_typedef_name"),
510             GetSymbolFile()->GetDeclContextContainingUID(GetID()));
511         break;
512 
513       case eEncodingIsPointerUID:
514         m_compiler_type = void_compiler_type.GetPointerType();
515         break;
516 
517       case eEncodingIsLValueReferenceUID:
518         m_compiler_type = void_compiler_type.GetLValueReferenceType();
519         break;
520 
521       case eEncodingIsRValueReferenceUID:
522         m_compiler_type = void_compiler_type.GetRValueReferenceType();
523         break;
524 
525       default:
526         llvm_unreachable("Unhandled encoding_data_type.");
527       }
528     }
529 
530     // When we have a EncodingUID, our "m_flags.compiler_type_resolve_state" is
531     // set to eResolveStateUnresolved so we need to update it to say that we
532     // now have a forward declaration since that is what we created above.
533     if (m_compiler_type.IsValid())
534       m_flags.compiler_type_resolve_state = eResolveStateForward;
535   }
536 
537   // Check if we have a forward reference to a class/struct/union/enum?
538   if (compiler_type_resolve_state == eResolveStateLayout ||
539       compiler_type_resolve_state == eResolveStateFull) {
540     // Check if we have a forward reference to a class/struct/union/enum?
541     if (m_compiler_type.IsValid() &&
542         m_flags.compiler_type_resolve_state < compiler_type_resolve_state) {
543       m_flags.compiler_type_resolve_state = eResolveStateFull;
544       if (!m_compiler_type.IsDefined()) {
545         // We have a forward declaration, we need to resolve it to a complete
546         // definition.
547         m_symbol_file->CompleteType(m_compiler_type);
548       }
549     }
550   }
551 
552   // If we have an encoding type, then we need to make sure it is resolved
553   // appropriately.
554   if (m_encoding_uid != LLDB_INVALID_UID) {
555     if (encoding_type == nullptr)
556       encoding_type = GetEncodingType();
557     if (encoding_type) {
558       ResolveState encoding_compiler_type_resolve_state =
559           compiler_type_resolve_state;
560 
561       if (compiler_type_resolve_state == eResolveStateLayout) {
562         switch (m_encoding_uid_type) {
563         case eEncodingIsPointerUID:
564         case eEncodingIsLValueReferenceUID:
565         case eEncodingIsRValueReferenceUID:
566           encoding_compiler_type_resolve_state = eResolveStateForward;
567           break;
568         default:
569           break;
570         }
571       }
572       encoding_type->ResolveClangType(encoding_compiler_type_resolve_state);
573     }
574   }
575   return m_compiler_type.IsValid();
576 }
577 uint32_t Type::GetEncodingMask() {
578   uint32_t encoding_mask = 1u << m_encoding_uid_type;
579   Type *encoding_type = GetEncodingType();
580   assert(encoding_type != this);
581   if (encoding_type)
582     encoding_mask |= encoding_type->GetEncodingMask();
583   return encoding_mask;
584 }
585 
586 CompilerType Type::GetFullCompilerType() {
587   ResolveClangType(eResolveStateFull);
588   return m_compiler_type;
589 }
590 
591 CompilerType Type::GetLayoutCompilerType() {
592   ResolveClangType(eResolveStateLayout);
593   return m_compiler_type;
594 }
595 
596 CompilerType Type::GetForwardCompilerType() {
597   ResolveClangType(eResolveStateForward);
598   return m_compiler_type;
599 }
600 
601 int Type::Compare(const Type &a, const Type &b) {
602   // Just compare the UID values for now...
603   lldb::user_id_t a_uid = a.GetID();
604   lldb::user_id_t b_uid = b.GetID();
605   if (a_uid < b_uid)
606     return -1;
607   if (a_uid > b_uid)
608     return 1;
609   return 0;
610 }
611 
612 ConstString Type::GetQualifiedName() {
613   return GetForwardCompilerType().GetConstTypeName();
614 }
615 
616 bool Type::GetTypeScopeAndBasename(const llvm::StringRef& name,
617                                    llvm::StringRef &scope,
618                                    llvm::StringRef &basename,
619                                    TypeClass &type_class) {
620   type_class = eTypeClassAny;
621 
622   if (name.empty())
623     return false;
624 
625   basename = name;
626   if (basename.consume_front("struct "))
627     type_class = eTypeClassStruct;
628   else if (basename.consume_front("class "))
629     type_class = eTypeClassClass;
630   else if (basename.consume_front("union "))
631     type_class = eTypeClassUnion;
632   else if (basename.consume_front("enum "))
633     type_class = eTypeClassEnumeration;
634   else if (basename.consume_front("typedef "))
635     type_class = eTypeClassTypedef;
636 
637   size_t namespace_separator = basename.find("::");
638   if (namespace_separator == llvm::StringRef::npos)
639     return false;
640 
641   size_t template_begin = basename.find('<');
642   while (namespace_separator != llvm::StringRef::npos) {
643     if (template_begin != llvm::StringRef::npos &&
644         namespace_separator > template_begin) {
645       size_t template_depth = 1;
646       llvm::StringRef template_arg =
647           basename.drop_front(template_begin + 1);
648       while (template_depth > 0 && !template_arg.empty()) {
649         if (template_arg.front() == '<')
650           template_depth++;
651         else if (template_arg.front() == '>')
652           template_depth--;
653         template_arg = template_arg.drop_front(1);
654       }
655       if (template_depth != 0)
656         return false; // We have an invalid type name. Bail out.
657       if (template_arg.empty())
658         break; // The template ends at the end of the full name.
659       basename = template_arg;
660     } else {
661       basename = basename.drop_front(namespace_separator + 2);
662     }
663     template_begin = basename.find('<');
664     namespace_separator = basename.find("::");
665   }
666   if (basename.size() < name.size()) {
667     scope = name.take_front(name.size() - basename.size());
668     return true;
669   }
670   return false;
671 }
672 
673 ModuleSP Type::GetModule() {
674   if (m_symbol_file)
675     return m_symbol_file->GetObjectFile()->GetModule();
676   return ModuleSP();
677 }
678 
679 TypeAndOrName::TypeAndOrName() : m_type_pair(), m_type_name() {}
680 
681 TypeAndOrName::TypeAndOrName(TypeSP &in_type_sp) : m_type_pair(in_type_sp) {
682   if (in_type_sp)
683     m_type_name = in_type_sp->GetName();
684 }
685 
686 TypeAndOrName::TypeAndOrName(const char *in_type_str)
687     : m_type_name(in_type_str) {}
688 
689 TypeAndOrName::TypeAndOrName(const TypeAndOrName &rhs)
690     : m_type_pair(rhs.m_type_pair), m_type_name(rhs.m_type_name) {}
691 
692 TypeAndOrName::TypeAndOrName(ConstString &in_type_const_string)
693     : m_type_name(in_type_const_string) {}
694 
695 TypeAndOrName &TypeAndOrName::operator=(const TypeAndOrName &rhs) {
696   if (this != &rhs) {
697     m_type_name = rhs.m_type_name;
698     m_type_pair = rhs.m_type_pair;
699   }
700   return *this;
701 }
702 
703 bool TypeAndOrName::operator==(const TypeAndOrName &other) const {
704   if (m_type_pair != other.m_type_pair)
705     return false;
706   if (m_type_name != other.m_type_name)
707     return false;
708   return true;
709 }
710 
711 bool TypeAndOrName::operator!=(const TypeAndOrName &other) const {
712   return !(*this == other);
713 }
714 
715 ConstString TypeAndOrName::GetName() const {
716   if (m_type_name)
717     return m_type_name;
718   if (m_type_pair)
719     return m_type_pair.GetName();
720   return ConstString("<invalid>");
721 }
722 
723 void TypeAndOrName::SetName(const ConstString &type_name) {
724   m_type_name = type_name;
725 }
726 
727 void TypeAndOrName::SetName(const char *type_name_cstr) {
728   m_type_name.SetCString(type_name_cstr);
729 }
730 
731 void TypeAndOrName::SetTypeSP(lldb::TypeSP type_sp) {
732   m_type_pair.SetType(type_sp);
733   if (m_type_pair)
734     m_type_name = m_type_pair.GetName();
735 }
736 
737 void TypeAndOrName::SetCompilerType(CompilerType compiler_type) {
738   m_type_pair.SetType(compiler_type);
739   if (m_type_pair)
740     m_type_name = m_type_pair.GetName();
741 }
742 
743 bool TypeAndOrName::IsEmpty() const {
744   return !((bool)m_type_name || (bool)m_type_pair);
745 }
746 
747 void TypeAndOrName::Clear() {
748   m_type_name.Clear();
749   m_type_pair.Clear();
750 }
751 
752 bool TypeAndOrName::HasName() const { return (bool)m_type_name; }
753 
754 bool TypeAndOrName::HasTypeSP() const {
755   return m_type_pair.GetTypeSP().get() != nullptr;
756 }
757 
758 bool TypeAndOrName::HasCompilerType() const {
759   return m_type_pair.GetCompilerType().IsValid();
760 }
761 
762 TypeImpl::TypeImpl() : m_module_wp(), m_static_type(), m_dynamic_type() {}
763 
764 TypeImpl::TypeImpl(const TypeImpl &rhs)
765     : m_module_wp(rhs.m_module_wp), m_static_type(rhs.m_static_type),
766       m_dynamic_type(rhs.m_dynamic_type) {}
767 
768 TypeImpl::TypeImpl(const lldb::TypeSP &type_sp)
769     : m_module_wp(), m_static_type(), m_dynamic_type() {
770   SetType(type_sp);
771 }
772 
773 TypeImpl::TypeImpl(const CompilerType &compiler_type)
774     : m_module_wp(), m_static_type(), m_dynamic_type() {
775   SetType(compiler_type);
776 }
777 
778 TypeImpl::TypeImpl(const lldb::TypeSP &type_sp, const CompilerType &dynamic)
779     : m_module_wp(), m_static_type(type_sp), m_dynamic_type(dynamic) {
780   SetType(type_sp, dynamic);
781 }
782 
783 TypeImpl::TypeImpl(const CompilerType &static_type,
784                    const CompilerType &dynamic_type)
785     : m_module_wp(), m_static_type(), m_dynamic_type() {
786   SetType(static_type, dynamic_type);
787 }
788 
789 TypeImpl::TypeImpl(const TypePair &pair, const CompilerType &dynamic)
790     : m_module_wp(), m_static_type(), m_dynamic_type() {
791   SetType(pair, dynamic);
792 }
793 
794 void TypeImpl::SetType(const lldb::TypeSP &type_sp) {
795   m_static_type.SetType(type_sp);
796   if (type_sp)
797     m_module_wp = type_sp->GetModule();
798   else
799     m_module_wp = lldb::ModuleWP();
800 }
801 
802 void TypeImpl::SetType(const CompilerType &compiler_type) {
803   m_module_wp = lldb::ModuleWP();
804   m_static_type.SetType(compiler_type);
805 }
806 
807 void TypeImpl::SetType(const lldb::TypeSP &type_sp,
808                        const CompilerType &dynamic) {
809   SetType(type_sp);
810   m_dynamic_type = dynamic;
811 }
812 
813 void TypeImpl::SetType(const CompilerType &compiler_type,
814                        const CompilerType &dynamic) {
815   m_module_wp = lldb::ModuleWP();
816   m_static_type.SetType(compiler_type);
817   m_dynamic_type = dynamic;
818 }
819 
820 void TypeImpl::SetType(const TypePair &pair, const CompilerType &dynamic) {
821   m_module_wp = pair.GetModule();
822   m_static_type = pair;
823   m_dynamic_type = dynamic;
824 }
825 
826 TypeImpl &TypeImpl::operator=(const TypeImpl &rhs) {
827   if (rhs != *this) {
828     m_module_wp = rhs.m_module_wp;
829     m_static_type = rhs.m_static_type;
830     m_dynamic_type = rhs.m_dynamic_type;
831   }
832   return *this;
833 }
834 
835 bool TypeImpl::CheckModule(lldb::ModuleSP &module_sp) const {
836   // Check if we have a module for this type. If we do and the shared pointer
837   // is can be successfully initialized with m_module_wp, return true. Else
838   // return false if we didn't have a module, or if we had a module and it has
839   // been deleted. Any functions doing anything with a TypeSP in this TypeImpl
840   // class should call this function and only do anything with the ivars if
841   // this function returns true. If we have a module, the "module_sp" will be
842   // filled in with a strong reference to the module so that the module will at
843   // least stay around long enough for the type query to succeed.
844   module_sp = m_module_wp.lock();
845   if (!module_sp) {
846     lldb::ModuleWP empty_module_wp;
847     // If either call to "std::weak_ptr::owner_before(...) value returns true,
848     // this indicates that m_module_wp once contained (possibly still does) a
849     // reference to a valid shared pointer. This helps us know if we had a
850     // valid reference to a section which is now invalid because the module it
851     // was in was deleted
852     if (empty_module_wp.owner_before(m_module_wp) ||
853         m_module_wp.owner_before(empty_module_wp)) {
854       // m_module_wp had a valid reference to a module, but all strong
855       // references have been released and the module has been deleted
856       return false;
857     }
858   }
859   // We either successfully locked the module, or didn't have one to begin with
860   return true;
861 }
862 
863 bool TypeImpl::operator==(const TypeImpl &rhs) const {
864   return m_static_type == rhs.m_static_type &&
865          m_dynamic_type == rhs.m_dynamic_type;
866 }
867 
868 bool TypeImpl::operator!=(const TypeImpl &rhs) const {
869   return !(*this == rhs);
870 }
871 
872 bool TypeImpl::IsValid() const {
873   // just a name is not valid
874   ModuleSP module_sp;
875   if (CheckModule(module_sp))
876     return m_static_type.IsValid() || m_dynamic_type.IsValid();
877   return false;
878 }
879 
880 TypeImpl::operator bool() const { return IsValid(); }
881 
882 void TypeImpl::Clear() {
883   m_module_wp = lldb::ModuleWP();
884   m_static_type.Clear();
885   m_dynamic_type.Clear();
886 }
887 
888 ConstString TypeImpl::GetName() const {
889   ModuleSP module_sp;
890   if (CheckModule(module_sp)) {
891     if (m_dynamic_type)
892       return m_dynamic_type.GetTypeName();
893     return m_static_type.GetName();
894   }
895   return ConstString();
896 }
897 
898 ConstString TypeImpl::GetDisplayTypeName() const {
899   ModuleSP module_sp;
900   if (CheckModule(module_sp)) {
901     if (m_dynamic_type)
902       return m_dynamic_type.GetDisplayTypeName();
903     return m_static_type.GetDisplayTypeName();
904   }
905   return ConstString();
906 }
907 
908 TypeImpl TypeImpl::GetPointerType() const {
909   ModuleSP module_sp;
910   if (CheckModule(module_sp)) {
911     if (m_dynamic_type.IsValid()) {
912       return TypeImpl(m_static_type.GetPointerType(),
913                       m_dynamic_type.GetPointerType());
914     }
915     return TypeImpl(m_static_type.GetPointerType());
916   }
917   return TypeImpl();
918 }
919 
920 TypeImpl TypeImpl::GetPointeeType() const {
921   ModuleSP module_sp;
922   if (CheckModule(module_sp)) {
923     if (m_dynamic_type.IsValid()) {
924       return TypeImpl(m_static_type.GetPointeeType(),
925                       m_dynamic_type.GetPointeeType());
926     }
927     return TypeImpl(m_static_type.GetPointeeType());
928   }
929   return TypeImpl();
930 }
931 
932 TypeImpl TypeImpl::GetReferenceType() const {
933   ModuleSP module_sp;
934   if (CheckModule(module_sp)) {
935     if (m_dynamic_type.IsValid()) {
936       return TypeImpl(m_static_type.GetReferenceType(),
937                       m_dynamic_type.GetLValueReferenceType());
938     }
939     return TypeImpl(m_static_type.GetReferenceType());
940   }
941   return TypeImpl();
942 }
943 
944 TypeImpl TypeImpl::GetTypedefedType() const {
945   ModuleSP module_sp;
946   if (CheckModule(module_sp)) {
947     if (m_dynamic_type.IsValid()) {
948       return TypeImpl(m_static_type.GetTypedefedType(),
949                       m_dynamic_type.GetTypedefedType());
950     }
951     return TypeImpl(m_static_type.GetTypedefedType());
952   }
953   return TypeImpl();
954 }
955 
956 TypeImpl TypeImpl::GetDereferencedType() const {
957   ModuleSP module_sp;
958   if (CheckModule(module_sp)) {
959     if (m_dynamic_type.IsValid()) {
960       return TypeImpl(m_static_type.GetDereferencedType(),
961                       m_dynamic_type.GetNonReferenceType());
962     }
963     return TypeImpl(m_static_type.GetDereferencedType());
964   }
965   return TypeImpl();
966 }
967 
968 TypeImpl TypeImpl::GetUnqualifiedType() const {
969   ModuleSP module_sp;
970   if (CheckModule(module_sp)) {
971     if (m_dynamic_type.IsValid()) {
972       return TypeImpl(m_static_type.GetUnqualifiedType(),
973                       m_dynamic_type.GetFullyUnqualifiedType());
974     }
975     return TypeImpl(m_static_type.GetUnqualifiedType());
976   }
977   return TypeImpl();
978 }
979 
980 TypeImpl TypeImpl::GetCanonicalType() const {
981   ModuleSP module_sp;
982   if (CheckModule(module_sp)) {
983     if (m_dynamic_type.IsValid()) {
984       return TypeImpl(m_static_type.GetCanonicalType(),
985                       m_dynamic_type.GetCanonicalType());
986     }
987     return TypeImpl(m_static_type.GetCanonicalType());
988   }
989   return TypeImpl();
990 }
991 
992 CompilerType TypeImpl::GetCompilerType(bool prefer_dynamic) {
993   ModuleSP module_sp;
994   if (CheckModule(module_sp)) {
995     if (prefer_dynamic) {
996       if (m_dynamic_type.IsValid())
997         return m_dynamic_type;
998     }
999     return m_static_type.GetCompilerType();
1000   }
1001   return CompilerType();
1002 }
1003 
1004 TypeSystem *TypeImpl::GetTypeSystem(bool prefer_dynamic) {
1005   ModuleSP module_sp;
1006   if (CheckModule(module_sp)) {
1007     if (prefer_dynamic) {
1008       if (m_dynamic_type.IsValid())
1009         return m_dynamic_type.GetTypeSystem();
1010     }
1011     return m_static_type.GetCompilerType().GetTypeSystem();
1012   }
1013   return NULL;
1014 }
1015 
1016 bool TypeImpl::GetDescription(lldb_private::Stream &strm,
1017                               lldb::DescriptionLevel description_level) {
1018   ModuleSP module_sp;
1019   if (CheckModule(module_sp)) {
1020     if (m_dynamic_type.IsValid()) {
1021       strm.Printf("Dynamic:\n");
1022       m_dynamic_type.DumpTypeDescription(&strm);
1023       strm.Printf("\nStatic:\n");
1024     }
1025     m_static_type.GetCompilerType().DumpTypeDescription(&strm);
1026   } else {
1027     strm.PutCString("Invalid TypeImpl module for type has been deleted\n");
1028   }
1029   return true;
1030 }
1031 
1032 bool TypeMemberFunctionImpl::IsValid() {
1033   return m_type.IsValid() && m_kind != lldb::eMemberFunctionKindUnknown;
1034 }
1035 
1036 ConstString TypeMemberFunctionImpl::GetName() const { return m_name; }
1037 
1038 ConstString TypeMemberFunctionImpl::GetMangledName() const {
1039   return m_decl.GetMangledName();
1040 }
1041 
1042 CompilerType TypeMemberFunctionImpl::GetType() const { return m_type; }
1043 
1044 lldb::MemberFunctionKind TypeMemberFunctionImpl::GetKind() const {
1045   return m_kind;
1046 }
1047 
1048 bool TypeMemberFunctionImpl::GetDescription(Stream &stream) {
1049   switch (m_kind) {
1050   case lldb::eMemberFunctionKindUnknown:
1051     return false;
1052   case lldb::eMemberFunctionKindConstructor:
1053     stream.Printf("constructor for %s",
1054                   m_type.GetTypeName().AsCString("<unknown>"));
1055     break;
1056   case lldb::eMemberFunctionKindDestructor:
1057     stream.Printf("destructor for %s",
1058                   m_type.GetTypeName().AsCString("<unknown>"));
1059     break;
1060   case lldb::eMemberFunctionKindInstanceMethod:
1061     stream.Printf("instance method %s of type %s", m_name.AsCString(),
1062                   m_decl.GetDeclContext().GetName().AsCString());
1063     break;
1064   case lldb::eMemberFunctionKindStaticMethod:
1065     stream.Printf("static method %s of type %s", m_name.AsCString(),
1066                   m_decl.GetDeclContext().GetName().AsCString());
1067     break;
1068   }
1069   return true;
1070 }
1071 
1072 CompilerType TypeMemberFunctionImpl::GetReturnType() const {
1073   if (m_type)
1074     return m_type.GetFunctionReturnType();
1075   return m_decl.GetFunctionReturnType();
1076 }
1077 
1078 size_t TypeMemberFunctionImpl::GetNumArguments() const {
1079   if (m_type)
1080     return m_type.GetNumberOfFunctionArguments();
1081   else
1082     return m_decl.GetNumFunctionArguments();
1083 }
1084 
1085 CompilerType TypeMemberFunctionImpl::GetArgumentAtIndex(size_t idx) const {
1086   if (m_type)
1087     return m_type.GetFunctionArgumentAtIndex(idx);
1088   else
1089     return m_decl.GetFunctionArgumentType(idx);
1090 }
1091 
1092 TypeEnumMemberImpl::TypeEnumMemberImpl(const lldb::TypeImplSP &integer_type_sp,
1093                                        const ConstString &name,
1094                                        const llvm::APSInt &value)
1095     : m_integer_type_sp(integer_type_sp), m_name(name), m_value(value),
1096       m_valid((bool)name && (bool)integer_type_sp)
1097 
1098 {}
1099