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