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