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