1 //===- llvm/Support/LEB128.h - [SU]LEB128 utility functions -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares some utility functions for encoding SLEB128 and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_SUPPORT_LEB128_H
16 #define LLVM_SUPPORT_LEB128_H
18 #include "llvm/Support/raw_ostream.h"
22 /// Utility function to encode a SLEB128 value to an output stream.
23 inline void encodeSLEB128(int64_t Value, raw_ostream &OS) {
26 uint8_t Byte = Value & 0x7f;
27 // NOTE: this assumes that this signed shift is an arithmetic right shift.
29 More = !((((Value == 0 ) && ((Byte & 0x40) == 0)) ||
30 ((Value == -1) && ((Byte & 0x40) != 0))));
32 Byte |= 0x80; // Mark this byte to show that more bytes will follow.
37 /// Utility function to encode a ULEB128 value to an output stream.
38 inline void encodeULEB128(uint64_t Value, raw_ostream &OS,
39 unsigned Padding = 0) {
41 uint8_t Byte = Value & 0x7f;
43 if (Value != 0 || Padding != 0)
44 Byte |= 0x80; // Mark this byte to show that more bytes will follow.
48 // Pad with 0x80 and emit a null byte at the end.
50 for (; Padding != 1; --Padding)
56 /// Utility function to encode a ULEB128 value to a buffer. Returns
57 /// the length in bytes of the encoded value.
58 inline unsigned encodeULEB128(uint64_t Value, uint8_t *p,
59 unsigned Padding = 0) {
62 uint8_t Byte = Value & 0x7f;
64 if (Value != 0 || Padding != 0)
65 Byte |= 0x80; // Mark this byte to show that more bytes will follow.
69 // Pad with 0x80 and emit a null byte at the end.
71 for (; Padding != 1; --Padding)
75 return (unsigned)(p - orig_p);
79 /// Utility function to decode a ULEB128 value.
80 inline uint64_t decodeULEB128(const uint8_t *p, unsigned *n = 0) {
81 const uint8_t *orig_p = p;
85 Value += (*p & 0x7f) << Shift;
87 } while (*p++ >= 128);
89 *n = (unsigned)(p - orig_p);
93 /// Utility function to get the size of the ULEB128-encoded value.
94 inline unsigned getULEB128Size(uint64_t Value) {
98 Size += sizeof(int8_t);
103 /// Utility function to get the size of the SLEB128-encoded value.
104 inline unsigned getSLEB128Size(int64_t Value) {
106 int Sign = Value >> (8 * sizeof(Value) - 1);
110 unsigned Byte = Value & 0x7f;
112 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
113 Size += sizeof(int8_t);
120 #endif // LLVM_SYSTEM_LEB128_H