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