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
9#include "llvm/Support/NativeFormatting.h"
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/StringExtras.h"
13#include "llvm/Support/Format.h"
14#include "llvm/Support/MathExtras.h"
15#include "llvm/Support/raw_ostream.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
37static void writeWithCommas(raw_ostream &S, ArrayRef<char> Buffer) {
38 assert(!Buffer.empty());
39
40 ArrayRef<char> ThisGroup;
41 int InitialDigits = ((Buffer.size() - 1) % 3) + 1;
42 ThisGroup = Buffer.take_front(N: InitialDigits);
43 S.write(Ptr: ThisGroup.data(), Size: ThisGroup.size());
44
45 Buffer = Buffer.drop_front(N: InitialDigits);
46 assert(Buffer.size() % 3 == 0);
47 while (!Buffer.empty()) {
48 S << ',';
49 ThisGroup = Buffer.take_front(N: 3);
50 S.write(Ptr: ThisGroup.data(), Size: 3);
51 Buffer = Buffer.drop_front(N: 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, Buffer: ArrayRef<char>(std::end(arr&: NumberBuffer) - Len, Len));
73 } else {
74 S.write(Ptr: std::end(arr&: NumberBuffer) - Len, Size: 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, N: 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
135void llvm::write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style,
136 std::optional<size_t> Width) {
137 const size_t kMaxWidth = 128u;
138
139 size_t W = std::min(a: kMaxWidth, b: Width.value_or(u: 0u));
140
141 unsigned Nibbles = (llvm::bit_width(Value: 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(a: static_cast<unsigned>(W), b: std::max(a: 1u, b: Nibbles) + PrefixChars);
149
150 char NumberBuffer[kMaxWidth];
151 ::memset(s: NumberBuffer, c: '0', n: 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: x, LowerCase: !Upper);
159 N /= 16;
160 }
161
162 S.write(Ptr: NumberBuffer, Size: NumChars);
163}
164
165void llvm::write_double(raw_ostream &S, double N, FloatStyle Style,
166 std::optional<size_t> Precision) {
167 size_t Prec = Precision.value_or(u: getDefaultPrecision(Style));
168
169 if (std::isnan(x: N)) {
170 S << "nan";
171 return;
172 } else if (std::isinf(x: N)) {
173 S << (std::signbit(x: 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
185 SmallString<8> Spec;
186 llvm::raw_svector_ostream Out(Spec);
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(Fmt: Spec.c_str(), Vals: N).snprint(Buffer: Buf, BufferSize: sizeof(Buf));
246 S << Buf;
247 if (Style == FloatStyle::Percent)
248 S << '%';
249}
250
251bool llvm::isPrefixedHexStyle(HexPrintStyle S) {
252 return (S == HexPrintStyle::PrefixLower || S == HexPrintStyle::PrefixUpper);
253}
254
255size_t llvm::getDefaultPrecision(FloatStyle Style) {
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}
266