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