LLVM 20.0.0git
NativeFormatting.cpp
Go to the documentation of this file.
1//===- NativeFormatting.cpp - Low level formatting helpers -------*- 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
10#include "llvm/ADT/ArrayRef.h"
13#include "llvm/Support/Format.h"
16
17#include <cmath>
18
19#if defined(_WIN32) && !defined(__MINGW32__)
20#include <float.h> // For _fpclass in llvm::write_double.
21#endif
22
23using namespace llvm;
24
25template<typename T, std::size_t N>
26static int format_to_buffer(T Value, char (&Buffer)[N]) {
27 char *EndPtr = std::end(Buffer);
28 char *CurPtr = EndPtr;
29
30 do {
31 *--CurPtr = '0' + char(Value % 10);
32 Value /= 10;
33 } while (Value);
34 return EndPtr - CurPtr;
35}
36
38 assert(!Buffer.empty());
39
40 ArrayRef<char> ThisGroup;
41 int InitialDigits = ((Buffer.size() - 1) % 3) + 1;
42 ThisGroup = Buffer.take_front(InitialDigits);
43 S.write(ThisGroup.data(), ThisGroup.size());
44
45 Buffer = Buffer.drop_front(InitialDigits);
46 assert(Buffer.size() % 3 == 0);
47 while (!Buffer.empty()) {
48 S << ',';
49 ThisGroup = Buffer.take_front(3);
50 S.write(ThisGroup.data(), 3);
51 Buffer = Buffer.drop_front(3);
52 }
53}
54
55template <typename T>
56static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits,
57 IntegerStyle Style, bool IsNegative) {
58 static_assert(std::is_unsigned_v<T>, "Value is not unsigned!");
59
60 char NumberBuffer[128];
61 size_t Len = format_to_buffer(N, NumberBuffer);
62
63 if (IsNegative)
64 S << '-';
65
66 if (Len < MinDigits && Style != IntegerStyle::Number) {
67 for (size_t I = Len; I < MinDigits; ++I)
68 S << '0';
69 }
70
71 if (Style == IntegerStyle::Number) {
72 writeWithCommas(S, ArrayRef<char>(std::end(NumberBuffer) - Len, Len));
73 } else {
74 S.write(std::end(NumberBuffer) - Len, Len);
75 }
76}
77
78template <typename T>
79static void write_unsigned(raw_ostream &S, T N, size_t MinDigits,
80 IntegerStyle Style, bool IsNegative = false) {
81 // Output using 32-bit div/mod if possible.
82 if (N == static_cast<uint32_t>(N))
83 write_unsigned_impl(S, static_cast<uint32_t>(N), MinDigits, Style,
84 IsNegative);
85 else
86 write_unsigned_impl(S, N, MinDigits, Style, IsNegative);
87}
88
89template <typename T>
90static void write_signed(raw_ostream &S, T N, size_t MinDigits,
91 IntegerStyle Style) {
92 static_assert(std::is_signed_v<T>, "Value is not signed!");
93
94 using UnsignedT = std::make_unsigned_t<T>;
95
96 if (N >= 0) {
97 write_unsigned(S, static_cast<UnsignedT>(N), MinDigits, Style);
98 return;
99 }
100
101 UnsignedT UN = -(UnsignedT)N;
102 write_unsigned(S, UN, MinDigits, Style, true);
103}
104
105void llvm::write_integer(raw_ostream &S, unsigned int N, size_t MinDigits,
106 IntegerStyle Style) {
107 write_unsigned(S, N, MinDigits, Style);
108}
109
110void llvm::write_integer(raw_ostream &S, int N, size_t MinDigits,
111 IntegerStyle Style) {
112 write_signed(S, N, MinDigits, Style);
113}
114
115void llvm::write_integer(raw_ostream &S, unsigned long N, size_t MinDigits,
116 IntegerStyle Style) {
117 write_unsigned(S, N, MinDigits, Style);
118}
119
120void llvm::write_integer(raw_ostream &S, long N, size_t MinDigits,
121 IntegerStyle Style) {
122 write_signed(S, N, MinDigits, Style);
123}
124
125void llvm::write_integer(raw_ostream &S, unsigned long long N, size_t MinDigits,
126 IntegerStyle Style) {
127 write_unsigned(S, N, MinDigits, Style);
128}
129
130void llvm::write_integer(raw_ostream &S, long long N, size_t MinDigits,
131 IntegerStyle Style) {
132 write_signed(S, N, MinDigits, Style);
133}
134
136 std::optional<size_t> Width) {
137 const size_t kMaxWidth = 128u;
138
139 size_t W = std::min(kMaxWidth, Width.value_or(0u));
140
141 unsigned Nibbles = (llvm::bit_width(N) + 3) / 4;
142 bool Prefix = (Style == HexPrintStyle::PrefixLower ||
143 Style == HexPrintStyle::PrefixUpper);
144 bool Upper =
145 (Style == HexPrintStyle::Upper || Style == HexPrintStyle::PrefixUpper);
146 unsigned PrefixChars = Prefix ? 2 : 0;
147 unsigned NumChars =
148 std::max(static_cast<unsigned>(W), std::max(1u, Nibbles) + PrefixChars);
149
150 char NumberBuffer[kMaxWidth];
151 ::memset(NumberBuffer, '0', std::size(NumberBuffer));
152 if (Prefix)
153 NumberBuffer[1] = 'x';
154 char *EndPtr = NumberBuffer + NumChars;
155 char *CurPtr = EndPtr;
156 while (N) {
157 unsigned char x = static_cast<unsigned char>(N) % 16;
158 *--CurPtr = hexdigit(x, !Upper);
159 N /= 16;
160 }
161
162 S.write(NumberBuffer, NumChars);
163}
164
166 std::optional<size_t> Precision) {
167 size_t Prec = Precision.value_or(getDefaultPrecision(Style));
168
169 if (std::isnan(N)) {
170 S << "nan";
171 return;
172 } else if (std::isinf(N)) {
173 S << (std::signbit(N) ? "-INF" : "INF");
174 return;
175 }
176
177 char Letter;
178 if (Style == FloatStyle::Exponent)
179 Letter = 'e';
180 else if (Style == FloatStyle::ExponentUpper)
181 Letter = 'E';
182 else
183 Letter = 'f';
184
187 Out << "%." << Prec << Letter;
188
189 if (Style == FloatStyle::Exponent || Style == FloatStyle::ExponentUpper) {
190#ifdef _WIN32
191// On MSVCRT and compatible, output of %e is incompatible to Posix
192// by default. Number of exponent digits should be at least 2. "%+03d"
193// FIXME: Implement our formatter to here or Support/Format.h!
194#if defined(__MINGW32__)
195 // FIXME: It should be generic to C++11.
196 if (N == 0.0 && std::signbit(N)) {
197 char NegativeZero[] = "-0.000000e+00";
198 if (Style == FloatStyle::ExponentUpper)
199 NegativeZero[strlen(NegativeZero) - 4] = 'E';
200 S << NegativeZero;
201 return;
202 }
203#else
204 int fpcl = _fpclass(N);
205
206 // negative zero
207 if (fpcl == _FPCLASS_NZ) {
208 char NegativeZero[] = "-0.000000e+00";
209 if (Style == FloatStyle::ExponentUpper)
210 NegativeZero[strlen(NegativeZero) - 4] = 'E';
211 S << NegativeZero;
212 return;
213 }
214#endif
215
216 char buf[32];
217 unsigned len;
218 len = format(Spec.c_str(), N).snprint(buf, sizeof(buf));
219 if (len <= sizeof(buf) - 2) {
220 if (len >= 5 && (buf[len - 5] == 'e' || buf[len - 5] == 'E') &&
221 buf[len - 3] == '0') {
222 int cs = buf[len - 4];
223 if (cs == '+' || cs == '-') {
224 int c1 = buf[len - 2];
225 int c0 = buf[len - 1];
226 if (isdigit(static_cast<unsigned char>(c1)) &&
227 isdigit(static_cast<unsigned char>(c0))) {
228 // Trim leading '0': "...e+012" -> "...e+12\0"
229 buf[len - 3] = c1;
230 buf[len - 2] = c0;
231 buf[--len] = 0;
232 }
233 }
234 }
235 S << buf;
236 return;
237 }
238#endif
239 }
240
241 if (Style == FloatStyle::Percent)
242 N *= 100.0;
243
244 char Buf[32];
245 format(Spec.c_str(), N).snprint(Buf, sizeof(Buf));
246 S << Buf;
247 if (Style == FloatStyle::Percent)
248 S << '%';
249}
250
252 return (S == HexPrintStyle::PrefixLower || S == HexPrintStyle::PrefixUpper);
253}
254
256 switch (Style) {
257 case FloatStyle::Exponent:
258 case FloatStyle::ExponentUpper:
259 return 6; // Number of decimal places.
260 case FloatStyle::Fixed:
261 case FloatStyle::Percent:
262 return 2; // Number of decimal places.
263 }
264 llvm_unreachable("Unknown FloatStyle enum");
265}
#define I(x, y, z)
Definition: MD5.cpp:58
static void write_unsigned(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative=false)
static int format_to_buffer(T Value, char(&Buffer)[N])
static void write_signed(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style)
static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits, IntegerStyle Style, bool IsNegative)
static void writeWithCommas(raw_ostream &S, ArrayRef< char > Buffer)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
ArrayRef< T > take_front(size_t N=1) const
Return a copy of *this with only the first N elements.
Definition: ArrayRef.h:228
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:204
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
const T * data() const
Definition: ArrayRef.h:162
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition: bit.h:317
void write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, IntegerStyle Style)
size_t getDefaultPrecision(FloatStyle Style)
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
void write_double(raw_ostream &S, double D, FloatStyle Style, std::optional< size_t > Precision=std::nullopt)
bool isPrefixedHexStyle(HexPrintStyle S)
#define N