1 //===-- DIERef.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 "DIERef.h"
10 #include "lldb/Utility/DataEncoder.h"
11 #include "lldb/Utility/DataExtractor.h"
12 #include "llvm/Support/Format.h"
13 
14 using namespace lldb;
15 using namespace lldb_private;
16 
17 void llvm::format_provider<DIERef>::format(const DIERef &ref, raw_ostream &OS,
18                                            StringRef Style) {
19   if (ref.dwo_num())
20     OS << format_hex_no_prefix(*ref.dwo_num(), 8) << "/";
21   OS << (ref.section() == DIERef::DebugInfo ? "INFO" : "TYPE");
22   OS << "/" << format_hex_no_prefix(ref.die_offset(), 8);
23 }
24 
25 constexpr uint32_t k_dwo_num_mask = 0x3FFFFFFF;
26 constexpr uint32_t k_dwo_num_valid_bitmask = (1u << 30);
27 constexpr uint32_t k_section_bitmask = (1u << 31);
28 
29 llvm::Optional<DIERef> DIERef::Decode(const DataExtractor &data,
30                                       lldb::offset_t *offset_ptr) {
31   const uint32_t bitfield_storage = data.GetU32(offset_ptr);
32   uint32_t dwo_num = bitfield_storage & k_dwo_num_mask;
33   bool dwo_num_valid = (bitfield_storage & (k_dwo_num_valid_bitmask)) != 0;
34   Section section = (Section)((bitfield_storage & (k_section_bitmask)) != 0);
35   // DIE offsets can't be zero and if we fail to decode something from data,
36   // it will return 0
37   dw_offset_t die_offset = data.GetU32(offset_ptr);
38   if (die_offset == 0)
39     return llvm::None;
40   if (dwo_num_valid)
41     return DIERef(dwo_num, section, die_offset);
42   else
43     return DIERef(llvm::None, section, die_offset);
44 }
45 
46 void DIERef::Encode(DataEncoder &encoder) const {
47   uint32_t bitfield_storage = m_dwo_num;
48   if (m_dwo_num_valid)
49     bitfield_storage |= k_dwo_num_valid_bitmask;
50   if (m_section)
51     bitfield_storage |= k_section_bitmask;
52   encoder.AppendU32(bitfield_storage);
53   static_assert(sizeof(m_die_offset) == 4, "m_die_offset must be 4 bytes");
54   encoder.AppendU32(m_die_offset);
55 }
56