hex_float.h 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. // Copyright (c) 2015-2016 The Khronos Group Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef SOURCE_UTIL_HEX_FLOAT_H_
  15. #define SOURCE_UTIL_HEX_FLOAT_H_
  16. #include <cassert>
  17. #include <cctype>
  18. #include <cmath>
  19. #include <cstdint>
  20. #include <iomanip>
  21. #include <limits>
  22. #include <sstream>
  23. #include <vector>
  24. #include "source/util/bitutils.h"
  25. #ifndef __GNUC__
  26. #define GCC_VERSION 0
  27. #else
  28. #define GCC_VERSION \
  29. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  30. #endif
  31. namespace spvtools {
  32. namespace utils {
  33. class Float16 {
  34. public:
  35. Float16(uint16_t v) : val(v) {}
  36. Float16() = default;
  37. static bool isNan(const Float16& val) {
  38. return ((val.val & 0x7C00) == 0x7C00) && ((val.val & 0x3FF) != 0);
  39. }
  40. // Returns true if the given value is any kind of infinity.
  41. static bool isInfinity(const Float16& val) {
  42. return ((val.val & 0x7C00) == 0x7C00) && ((val.val & 0x3FF) == 0);
  43. }
  44. Float16(const Float16& other) { val = other.val; }
  45. uint16_t get_value() const { return val; }
  46. // Returns the maximum normal value.
  47. static Float16 max() { return Float16(0x7bff); }
  48. // Returns the lowest normal value.
  49. static Float16 lowest() { return Float16(0xfbff); }
  50. private:
  51. uint16_t val;
  52. };
  53. // To specialize this type, you must override uint_type to define
  54. // an unsigned integer that can fit your floating point type.
  55. // You must also add a isNan function that returns true if
  56. // a value is Nan.
  57. template <typename T>
  58. struct FloatProxyTraits {
  59. using uint_type = void;
  60. };
  61. template <>
  62. struct FloatProxyTraits<float> {
  63. using uint_type = uint32_t;
  64. static bool isNan(float f) { return std::isnan(f); }
  65. // Returns true if the given value is any kind of infinity.
  66. static bool isInfinity(float f) { return std::isinf(f); }
  67. // Returns the maximum normal value.
  68. static float max() { return std::numeric_limits<float>::max(); }
  69. // Returns the lowest normal value.
  70. static float lowest() { return std::numeric_limits<float>::lowest(); }
  71. // Returns the value as the native floating point format.
  72. static float getAsFloat(const uint_type& t) { return BitwiseCast<float>(t); }
  73. // Returns the bits from the given floating pointer number.
  74. static uint_type getBitsFromFloat(const float& t) {
  75. return BitwiseCast<uint_type>(t);
  76. }
  77. // Returns the bitwidth.
  78. static uint32_t width() { return 32u; }
  79. };
  80. template <>
  81. struct FloatProxyTraits<double> {
  82. using uint_type = uint64_t;
  83. static bool isNan(double f) { return std::isnan(f); }
  84. // Returns true if the given value is any kind of infinity.
  85. static bool isInfinity(double f) { return std::isinf(f); }
  86. // Returns the maximum normal value.
  87. static double max() { return std::numeric_limits<double>::max(); }
  88. // Returns the lowest normal value.
  89. static double lowest() { return std::numeric_limits<double>::lowest(); }
  90. // Returns the value as the native floating point format.
  91. static double getAsFloat(const uint_type& t) {
  92. return BitwiseCast<double>(t);
  93. }
  94. // Returns the bits from the given floating pointer number.
  95. static uint_type getBitsFromFloat(const double& t) {
  96. return BitwiseCast<uint_type>(t);
  97. }
  98. // Returns the bitwidth.
  99. static uint32_t width() { return 64u; }
  100. };
  101. template <>
  102. struct FloatProxyTraits<Float16> {
  103. using uint_type = uint16_t;
  104. static bool isNan(Float16 f) { return Float16::isNan(f); }
  105. // Returns true if the given value is any kind of infinity.
  106. static bool isInfinity(Float16 f) { return Float16::isInfinity(f); }
  107. // Returns the maximum normal value.
  108. static Float16 max() { return Float16::max(); }
  109. // Returns the lowest normal value.
  110. static Float16 lowest() { return Float16::lowest(); }
  111. // Returns the value as the native floating point format.
  112. static Float16 getAsFloat(const uint_type& t) { return Float16(t); }
  113. // Returns the bits from the given floating pointer number.
  114. static uint_type getBitsFromFloat(const Float16& t) { return t.get_value(); }
  115. // Returns the bitwidth.
  116. static uint32_t width() { return 16u; }
  117. };
  118. // Since copying a floating point number (especially if it is NaN)
  119. // does not guarantee that bits are preserved, this class lets us
  120. // store the type and use it as a float when necessary.
  121. template <typename T>
  122. class FloatProxy {
  123. public:
  124. using uint_type = typename FloatProxyTraits<T>::uint_type;
  125. // Since this is to act similar to the normal floats,
  126. // do not initialize the data by default.
  127. FloatProxy() = default;
  128. // Intentionally non-explicit. This is a proxy type so
  129. // implicit conversions allow us to use it more transparently.
  130. FloatProxy(T val) { data_ = FloatProxyTraits<T>::getBitsFromFloat(val); }
  131. // Intentionally non-explicit. This is a proxy type so
  132. // implicit conversions allow us to use it more transparently.
  133. FloatProxy(uint_type val) { data_ = val; }
  134. // This is helpful to have and is guaranteed not to stomp bits.
  135. FloatProxy<T> operator-() const {
  136. return static_cast<uint_type>(data_ ^
  137. (uint_type(0x1) << (sizeof(T) * 8 - 1)));
  138. }
  139. // Returns the data as a floating point value.
  140. T getAsFloat() const { return FloatProxyTraits<T>::getAsFloat(data_); }
  141. // Returns the raw data.
  142. uint_type data() const { return data_; }
  143. // Returns a vector of words suitable for use in an Operand.
  144. std::vector<uint32_t> GetWords() const {
  145. std::vector<uint32_t> words;
  146. if (FloatProxyTraits<T>::width() == 64) {
  147. FloatProxyTraits<double>::uint_type d = data();
  148. words.push_back(static_cast<uint32_t>(d));
  149. words.push_back(static_cast<uint32_t>(d >> 32));
  150. } else {
  151. words.push_back(static_cast<uint32_t>(data()));
  152. }
  153. return words;
  154. }
  155. // Returns true if the value represents any type of NaN.
  156. bool isNan() { return FloatProxyTraits<T>::isNan(getAsFloat()); }
  157. // Returns true if the value represents any type of infinity.
  158. bool isInfinity() { return FloatProxyTraits<T>::isInfinity(getAsFloat()); }
  159. // Returns the maximum normal value.
  160. static FloatProxy<T> max() {
  161. return FloatProxy<T>(FloatProxyTraits<T>::max());
  162. }
  163. // Returns the lowest normal value.
  164. static FloatProxy<T> lowest() {
  165. return FloatProxy<T>(FloatProxyTraits<T>::lowest());
  166. }
  167. private:
  168. uint_type data_;
  169. };
  170. template <typename T>
  171. bool operator==(const FloatProxy<T>& first, const FloatProxy<T>& second) {
  172. return first.data() == second.data();
  173. }
  174. // Reads a FloatProxy value as a normal float from a stream.
  175. template <typename T>
  176. std::istream& operator>>(std::istream& is, FloatProxy<T>& value) {
  177. T float_val = static_cast<T>(0.0);
  178. is >> float_val;
  179. value = FloatProxy<T>(float_val);
  180. return is;
  181. }
  182. // This is an example traits. It is not meant to be used in practice, but will
  183. // be the default for any non-specialized type.
  184. template <typename T>
  185. struct HexFloatTraits {
  186. // Integer type that can store the bit representation of this hex-float.
  187. using uint_type = void;
  188. // Signed integer type that can store the bit representation of this
  189. // hex-float.
  190. using int_type = void;
  191. // The numerical type that this HexFloat represents.
  192. using underlying_type = void;
  193. // The type needed to construct the underlying type.
  194. using native_type = void;
  195. // The number of bits that are actually relevant in the uint_type.
  196. // This allows us to deal with, for example, 24-bit values in a 32-bit
  197. // integer.
  198. static const uint32_t num_used_bits = 0;
  199. // Number of bits that represent the exponent.
  200. static const uint32_t num_exponent_bits = 0;
  201. // Number of bits that represent the fractional part.
  202. static const uint32_t num_fraction_bits = 0;
  203. // The bias of the exponent. (How much we need to subtract from the stored
  204. // value to get the correct value.)
  205. static const uint32_t exponent_bias = 0;
  206. };
  207. // Traits for IEEE float.
  208. // 1 sign bit, 8 exponent bits, 23 fractional bits.
  209. template <>
  210. struct HexFloatTraits<FloatProxy<float>> {
  211. using uint_type = uint32_t;
  212. using int_type = int32_t;
  213. using underlying_type = FloatProxy<float>;
  214. using native_type = float;
  215. static const uint_type num_used_bits = 32;
  216. static const uint_type num_exponent_bits = 8;
  217. static const uint_type num_fraction_bits = 23;
  218. static const uint_type exponent_bias = 127;
  219. };
  220. // Traits for IEEE double.
  221. // 1 sign bit, 11 exponent bits, 52 fractional bits.
  222. template <>
  223. struct HexFloatTraits<FloatProxy<double>> {
  224. using uint_type = uint64_t;
  225. using int_type = int64_t;
  226. using underlying_type = FloatProxy<double>;
  227. using native_type = double;
  228. static const uint_type num_used_bits = 64;
  229. static const uint_type num_exponent_bits = 11;
  230. static const uint_type num_fraction_bits = 52;
  231. static const uint_type exponent_bias = 1023;
  232. };
  233. // Traits for IEEE half.
  234. // 1 sign bit, 5 exponent bits, 10 fractional bits.
  235. template <>
  236. struct HexFloatTraits<FloatProxy<Float16>> {
  237. using uint_type = uint16_t;
  238. using int_type = int16_t;
  239. using underlying_type = uint16_t;
  240. using native_type = uint16_t;
  241. static const uint_type num_used_bits = 16;
  242. static const uint_type num_exponent_bits = 5;
  243. static const uint_type num_fraction_bits = 10;
  244. static const uint_type exponent_bias = 15;
  245. };
  246. enum class round_direction {
  247. kToZero,
  248. kToNearestEven,
  249. kToPositiveInfinity,
  250. kToNegativeInfinity,
  251. max = kToNegativeInfinity
  252. };
  253. // Template class that houses a floating pointer number.
  254. // It exposes a number of constants based on the provided traits to
  255. // assist in interpreting the bits of the value.
  256. template <typename T, typename Traits = HexFloatTraits<T>>
  257. class HexFloat {
  258. public:
  259. using uint_type = typename Traits::uint_type;
  260. using int_type = typename Traits::int_type;
  261. using underlying_type = typename Traits::underlying_type;
  262. using native_type = typename Traits::native_type;
  263. explicit HexFloat(T f) : value_(f) {}
  264. T value() const { return value_; }
  265. void set_value(T f) { value_ = f; }
  266. // These are all written like this because it is convenient to have
  267. // compile-time constants for all of these values.
  268. // Pass-through values to save typing.
  269. static const uint32_t num_used_bits = Traits::num_used_bits;
  270. static const uint32_t exponent_bias = Traits::exponent_bias;
  271. static const uint32_t num_exponent_bits = Traits::num_exponent_bits;
  272. static const uint32_t num_fraction_bits = Traits::num_fraction_bits;
  273. // Number of bits to shift left to set the highest relevant bit.
  274. static const uint32_t top_bit_left_shift = num_used_bits - 1;
  275. // How many nibbles (hex characters) the fractional part takes up.
  276. static const uint32_t fraction_nibbles = (num_fraction_bits + 3) / 4;
  277. // If the fractional part does not fit evenly into a hex character (4-bits)
  278. // then we have to left-shift to get rid of leading 0s. This is the amount
  279. // we have to shift (might be 0).
  280. static const uint32_t num_overflow_bits =
  281. fraction_nibbles * 4 - num_fraction_bits;
  282. // The representation of the fraction, not the actual bits. This
  283. // includes the leading bit that is usually implicit.
  284. static const uint_type fraction_represent_mask =
  285. SetBits<uint_type, 0, num_fraction_bits + num_overflow_bits>::get;
  286. // The topmost bit in the nibble-aligned fraction.
  287. static const uint_type fraction_top_bit =
  288. uint_type(1) << (num_fraction_bits + num_overflow_bits - 1);
  289. // The least significant bit in the exponent, which is also the bit
  290. // immediately to the left of the significand.
  291. static const uint_type first_exponent_bit = uint_type(1)
  292. << (num_fraction_bits);
  293. // The mask for the encoded fraction. It does not include the
  294. // implicit bit.
  295. static const uint_type fraction_encode_mask =
  296. SetBits<uint_type, 0, num_fraction_bits>::get;
  297. // The bit that is used as a sign.
  298. static const uint_type sign_mask = uint_type(1) << top_bit_left_shift;
  299. // The bits that represent the exponent.
  300. static const uint_type exponent_mask =
  301. SetBits<uint_type, num_fraction_bits, num_exponent_bits>::get;
  302. // How far left the exponent is shifted.
  303. static const uint32_t exponent_left_shift = num_fraction_bits;
  304. // How far from the right edge the fraction is shifted.
  305. static const uint32_t fraction_right_shift =
  306. static_cast<uint32_t>(sizeof(uint_type) * 8) - num_fraction_bits;
  307. // The maximum representable unbiased exponent.
  308. static const int_type max_exponent =
  309. (exponent_mask >> num_fraction_bits) - exponent_bias;
  310. // The minimum representable exponent for normalized numbers.
  311. static const int_type min_exponent = -static_cast<int_type>(exponent_bias);
  312. // Returns the bits associated with the value.
  313. uint_type getBits() const { return value_.data(); }
  314. // Returns the bits associated with the value, without the leading sign bit.
  315. uint_type getUnsignedBits() const {
  316. return static_cast<uint_type>(value_.data() & ~sign_mask);
  317. }
  318. // Returns the bits associated with the exponent, shifted to start at the
  319. // lsb of the type.
  320. const uint_type getExponentBits() const {
  321. return static_cast<uint_type>((getBits() & exponent_mask) >>
  322. num_fraction_bits);
  323. }
  324. // Returns the exponent in unbiased form. This is the exponent in the
  325. // human-friendly form.
  326. const int_type getUnbiasedExponent() const {
  327. return static_cast<int_type>(getExponentBits() - exponent_bias);
  328. }
  329. // Returns just the significand bits from the value.
  330. const uint_type getSignificandBits() const {
  331. return getBits() & fraction_encode_mask;
  332. }
  333. // If the number was normalized, returns the unbiased exponent.
  334. // If the number was denormal, normalize the exponent first.
  335. const int_type getUnbiasedNormalizedExponent() const {
  336. if ((getBits() & ~sign_mask) == 0) { // special case if everything is 0
  337. return 0;
  338. }
  339. int_type exp = getUnbiasedExponent();
  340. if (exp == min_exponent) { // We are in denorm land.
  341. uint_type significand_bits = getSignificandBits();
  342. while ((significand_bits & (first_exponent_bit >> 1)) == 0) {
  343. significand_bits = static_cast<uint_type>(significand_bits << 1);
  344. exp = static_cast<int_type>(exp - 1);
  345. }
  346. significand_bits &= fraction_encode_mask;
  347. }
  348. return exp;
  349. }
  350. // Returns the signficand after it has been normalized.
  351. const uint_type getNormalizedSignificand() const {
  352. int_type unbiased_exponent = getUnbiasedNormalizedExponent();
  353. uint_type significand = getSignificandBits();
  354. for (int_type i = unbiased_exponent; i <= min_exponent; ++i) {
  355. significand = static_cast<uint_type>(significand << 1);
  356. }
  357. significand &= fraction_encode_mask;
  358. return significand;
  359. }
  360. // Returns true if this number represents a negative value.
  361. bool isNegative() const { return (getBits() & sign_mask) != 0; }
  362. // Sets this HexFloat from the individual components.
  363. // Note this assumes EVERY significand is normalized, and has an implicit
  364. // leading one. This means that the only way that this method will set 0,
  365. // is if you set a number so denormalized that it underflows.
  366. // Do not use this method with raw bits extracted from a subnormal number,
  367. // since subnormals do not have an implicit leading 1 in the significand.
  368. // The significand is also expected to be in the
  369. // lowest-most num_fraction_bits of the uint_type.
  370. // The exponent is expected to be unbiased, meaning an exponent of
  371. // 0 actually means 0.
  372. // If underflow_round_up is set, then on underflow, if a number is non-0
  373. // and would underflow, we round up to the smallest denorm.
  374. void setFromSignUnbiasedExponentAndNormalizedSignificand(
  375. bool negative, int_type exponent, uint_type significand,
  376. bool round_denorm_up) {
  377. bool significand_is_zero = significand == 0;
  378. if (exponent <= min_exponent) {
  379. // If this was denormalized, then we have to shift the bit on, meaning
  380. // the significand is not zero.
  381. significand_is_zero = false;
  382. significand |= first_exponent_bit;
  383. significand = static_cast<uint_type>(significand >> 1);
  384. }
  385. while (exponent < min_exponent) {
  386. significand = static_cast<uint_type>(significand >> 1);
  387. ++exponent;
  388. }
  389. if (exponent == min_exponent) {
  390. if (significand == 0 && !significand_is_zero && round_denorm_up) {
  391. significand = static_cast<uint_type>(0x1);
  392. }
  393. }
  394. uint_type new_value = 0;
  395. if (negative) {
  396. new_value = static_cast<uint_type>(new_value | sign_mask);
  397. }
  398. exponent = static_cast<int_type>(exponent + exponent_bias);
  399. assert(exponent >= 0);
  400. // put it all together
  401. exponent = static_cast<uint_type>((exponent << exponent_left_shift) &
  402. exponent_mask);
  403. significand = static_cast<uint_type>(significand & fraction_encode_mask);
  404. new_value = static_cast<uint_type>(new_value | (exponent | significand));
  405. value_ = T(new_value);
  406. }
  407. // Increments the significand of this number by the given amount.
  408. // If this would spill the significand into the implicit bit,
  409. // carry is set to true and the significand is shifted to fit into
  410. // the correct location, otherwise carry is set to false.
  411. // All significands and to_increment are assumed to be within the bounds
  412. // for a valid significand.
  413. static uint_type incrementSignificand(uint_type significand,
  414. uint_type to_increment, bool* carry) {
  415. significand = static_cast<uint_type>(significand + to_increment);
  416. *carry = false;
  417. if (significand & first_exponent_bit) {
  418. *carry = true;
  419. // The implicit 1-bit will have carried, so we should zero-out the
  420. // top bit and shift back.
  421. significand = static_cast<uint_type>(significand & ~first_exponent_bit);
  422. significand = static_cast<uint_type>(significand >> 1);
  423. }
  424. return significand;
  425. }
  426. #if GCC_VERSION == 40801
  427. // These exist because MSVC throws warnings on negative right-shifts
  428. // even if they are not going to be executed. Eg:
  429. // constant_number < 0? 0: constant_number
  430. // These convert the negative left-shifts into right shifts.
  431. template <int_type N>
  432. struct negatable_left_shift {
  433. static uint_type val(uint_type val) {
  434. if (N > 0) {
  435. return static_cast<uint_type>(val << N);
  436. } else {
  437. return static_cast<uint_type>(val >> N);
  438. }
  439. }
  440. };
  441. template <int_type N>
  442. struct negatable_right_shift {
  443. static uint_type val(uint_type val) {
  444. if (N > 0) {
  445. return static_cast<uint_type>(val >> N);
  446. } else {
  447. return static_cast<uint_type>(val << N);
  448. }
  449. }
  450. };
  451. #else
  452. // These exist because MSVC throws warnings on negative right-shifts
  453. // even if they are not going to be executed. Eg:
  454. // constant_number < 0? 0: constant_number
  455. // These convert the negative left-shifts into right shifts.
  456. template <int_type N, typename enable = void>
  457. struct negatable_left_shift {
  458. static uint_type val(uint_type val) {
  459. return static_cast<uint_type>(val >> -N);
  460. }
  461. };
  462. template <int_type N>
  463. struct negatable_left_shift<N, typename std::enable_if<N >= 0>::type> {
  464. static uint_type val(uint_type val) {
  465. return static_cast<uint_type>(val << N);
  466. }
  467. };
  468. template <int_type N, typename enable = void>
  469. struct negatable_right_shift {
  470. static uint_type val(uint_type val) {
  471. return static_cast<uint_type>(val << -N);
  472. }
  473. };
  474. template <int_type N>
  475. struct negatable_right_shift<N, typename std::enable_if<N >= 0>::type> {
  476. static uint_type val(uint_type val) {
  477. return static_cast<uint_type>(val >> N);
  478. }
  479. };
  480. #endif
  481. // Returns the significand, rounded to fit in a significand in
  482. // other_T. This is shifted so that the most significant
  483. // bit of the rounded number lines up with the most significant bit
  484. // of the returned significand.
  485. template <typename other_T>
  486. typename other_T::uint_type getRoundedNormalizedSignificand(
  487. round_direction dir, bool* carry_bit) {
  488. using other_uint_type = typename other_T::uint_type;
  489. static const int_type num_throwaway_bits =
  490. static_cast<int_type>(num_fraction_bits) -
  491. static_cast<int_type>(other_T::num_fraction_bits);
  492. static const uint_type last_significant_bit =
  493. (num_throwaway_bits < 0)
  494. ? 0
  495. : negatable_left_shift<num_throwaway_bits>::val(1u);
  496. static const uint_type first_rounded_bit =
  497. (num_throwaway_bits < 1)
  498. ? 0
  499. : negatable_left_shift<num_throwaway_bits - 1>::val(1u);
  500. static const uint_type throwaway_mask_bits =
  501. num_throwaway_bits > 0 ? num_throwaway_bits : 0;
  502. static const uint_type throwaway_mask =
  503. SetBits<uint_type, 0, throwaway_mask_bits>::get;
  504. *carry_bit = false;
  505. other_uint_type out_val = 0;
  506. uint_type significand = getNormalizedSignificand();
  507. // If we are up-casting, then we just have to shift to the right location.
  508. if (num_throwaway_bits <= 0) {
  509. out_val = static_cast<other_uint_type>(significand);
  510. uint_type shift_amount = static_cast<uint_type>(-num_throwaway_bits);
  511. out_val = static_cast<other_uint_type>(out_val << shift_amount);
  512. return out_val;
  513. }
  514. // If every non-representable bit is 0, then we don't have any casting to
  515. // do.
  516. if ((significand & throwaway_mask) == 0) {
  517. return static_cast<other_uint_type>(
  518. negatable_right_shift<num_throwaway_bits>::val(significand));
  519. }
  520. bool round_away_from_zero = false;
  521. // We actually have to narrow the significand here, so we have to follow the
  522. // rounding rules.
  523. switch (dir) {
  524. case round_direction::kToZero:
  525. break;
  526. case round_direction::kToPositiveInfinity:
  527. round_away_from_zero = !isNegative();
  528. break;
  529. case round_direction::kToNegativeInfinity:
  530. round_away_from_zero = isNegative();
  531. break;
  532. case round_direction::kToNearestEven:
  533. // Have to round down, round bit is 0
  534. if ((first_rounded_bit & significand) == 0) {
  535. break;
  536. }
  537. if (((significand & throwaway_mask) & ~first_rounded_bit) != 0) {
  538. // If any subsequent bit of the rounded portion is non-0 then we round
  539. // up.
  540. round_away_from_zero = true;
  541. break;
  542. }
  543. // We are exactly half-way between 2 numbers, pick even.
  544. if ((significand & last_significant_bit) != 0) {
  545. // 1 for our last bit, round up.
  546. round_away_from_zero = true;
  547. break;
  548. }
  549. break;
  550. }
  551. if (round_away_from_zero) {
  552. return static_cast<other_uint_type>(
  553. negatable_right_shift<num_throwaway_bits>::val(incrementSignificand(
  554. significand, last_significant_bit, carry_bit)));
  555. } else {
  556. return static_cast<other_uint_type>(
  557. negatable_right_shift<num_throwaway_bits>::val(significand));
  558. }
  559. }
  560. // Casts this value to another HexFloat. If the cast is widening,
  561. // then round_dir is ignored. If the cast is narrowing, then
  562. // the result is rounded in the direction specified.
  563. // This number will retain Nan and Inf values.
  564. // It will also saturate to Inf if the number overflows, and
  565. // underflow to (0 or min depending on rounding) if the number underflows.
  566. template <typename other_T>
  567. void castTo(other_T& other, round_direction round_dir) {
  568. other = other_T(static_cast<typename other_T::native_type>(0));
  569. bool negate = isNegative();
  570. if (getUnsignedBits() == 0) {
  571. if (negate) {
  572. other.set_value(-other.value());
  573. }
  574. return;
  575. }
  576. uint_type significand = getSignificandBits();
  577. bool carried = false;
  578. typename other_T::uint_type rounded_significand =
  579. getRoundedNormalizedSignificand<other_T>(round_dir, &carried);
  580. int_type exponent = getUnbiasedExponent();
  581. if (exponent == min_exponent) {
  582. // If we are denormal, normalize the exponent, so that we can encode
  583. // easily.
  584. exponent = static_cast<int_type>(exponent + 1);
  585. for (uint_type check_bit = first_exponent_bit >> 1; check_bit != 0;
  586. check_bit = static_cast<uint_type>(check_bit >> 1)) {
  587. exponent = static_cast<int_type>(exponent - 1);
  588. if (check_bit & significand) break;
  589. }
  590. }
  591. bool is_nan =
  592. (getBits() & exponent_mask) == exponent_mask && significand != 0;
  593. bool is_inf =
  594. !is_nan &&
  595. ((exponent + carried) > static_cast<int_type>(other_T::exponent_bias) ||
  596. (significand == 0 && (getBits() & exponent_mask) == exponent_mask));
  597. // If we are Nan or Inf we should pass that through.
  598. if (is_inf) {
  599. other.set_value(typename other_T::underlying_type(
  600. static_cast<typename other_T::uint_type>(
  601. (negate ? other_T::sign_mask : 0) | other_T::exponent_mask)));
  602. return;
  603. }
  604. if (is_nan) {
  605. typename other_T::uint_type shifted_significand;
  606. shifted_significand = static_cast<typename other_T::uint_type>(
  607. negatable_left_shift<
  608. static_cast<int_type>(other_T::num_fraction_bits) -
  609. static_cast<int_type>(num_fraction_bits)>::val(significand));
  610. // We are some sort of Nan. We try to keep the bit-pattern of the Nan
  611. // as close as possible. If we had to shift off bits so we are 0, then we
  612. // just set the last bit.
  613. other.set_value(typename other_T::underlying_type(
  614. static_cast<typename other_T::uint_type>(
  615. (negate ? other_T::sign_mask : 0) | other_T::exponent_mask |
  616. (shifted_significand == 0 ? 0x1 : shifted_significand))));
  617. return;
  618. }
  619. bool round_underflow_up =
  620. isNegative() ? round_dir == round_direction::kToNegativeInfinity
  621. : round_dir == round_direction::kToPositiveInfinity;
  622. using other_int_type = typename other_T::int_type;
  623. // setFromSignUnbiasedExponentAndNormalizedSignificand will
  624. // zero out any underflowing value (but retain the sign).
  625. other.setFromSignUnbiasedExponentAndNormalizedSignificand(
  626. negate, static_cast<other_int_type>(exponent), rounded_significand,
  627. round_underflow_up);
  628. return;
  629. }
  630. private:
  631. T value_;
  632. static_assert(num_used_bits ==
  633. Traits::num_exponent_bits + Traits::num_fraction_bits + 1,
  634. "The number of bits do not fit");
  635. static_assert(sizeof(T) == sizeof(uint_type), "The type sizes do not match");
  636. };
  637. // Returns 4 bits represented by the hex character.
  638. inline uint8_t get_nibble_from_character(int character) {
  639. const char* dec = "0123456789";
  640. const char* lower = "abcdef";
  641. const char* upper = "ABCDEF";
  642. const char* p = nullptr;
  643. if ((p = strchr(dec, character))) {
  644. return static_cast<uint8_t>(p - dec);
  645. } else if ((p = strchr(lower, character))) {
  646. return static_cast<uint8_t>(p - lower + 0xa);
  647. } else if ((p = strchr(upper, character))) {
  648. return static_cast<uint8_t>(p - upper + 0xa);
  649. }
  650. assert(false && "This was called with a non-hex character");
  651. return 0;
  652. }
  653. // Outputs the given HexFloat to the stream.
  654. template <typename T, typename Traits>
  655. std::ostream& operator<<(std::ostream& os, const HexFloat<T, Traits>& value) {
  656. using HF = HexFloat<T, Traits>;
  657. using uint_type = typename HF::uint_type;
  658. using int_type = typename HF::int_type;
  659. static_assert(HF::num_used_bits != 0,
  660. "num_used_bits must be non-zero for a valid float");
  661. static_assert(HF::num_exponent_bits != 0,
  662. "num_exponent_bits must be non-zero for a valid float");
  663. static_assert(HF::num_fraction_bits != 0,
  664. "num_fractin_bits must be non-zero for a valid float");
  665. const uint_type bits = value.value().data();
  666. const char* const sign = (bits & HF::sign_mask) ? "-" : "";
  667. const uint_type exponent = static_cast<uint_type>(
  668. (bits & HF::exponent_mask) >> HF::num_fraction_bits);
  669. uint_type fraction = static_cast<uint_type>((bits & HF::fraction_encode_mask)
  670. << HF::num_overflow_bits);
  671. const bool is_zero = exponent == 0 && fraction == 0;
  672. const bool is_denorm = exponent == 0 && !is_zero;
  673. // exponent contains the biased exponent we have to convert it back into
  674. // the normal range.
  675. int_type int_exponent = static_cast<int_type>(exponent - HF::exponent_bias);
  676. // If the number is all zeros, then we actually have to NOT shift the
  677. // exponent.
  678. int_exponent = is_zero ? 0 : int_exponent;
  679. // If we are denorm, then start shifting, and decreasing the exponent until
  680. // our leading bit is 1.
  681. if (is_denorm) {
  682. while ((fraction & HF::fraction_top_bit) == 0) {
  683. fraction = static_cast<uint_type>(fraction << 1);
  684. int_exponent = static_cast<int_type>(int_exponent - 1);
  685. }
  686. // Since this is denormalized, we have to consume the leading 1 since it
  687. // will end up being implicit.
  688. fraction = static_cast<uint_type>(fraction << 1); // eat the leading 1
  689. fraction &= HF::fraction_represent_mask;
  690. }
  691. uint_type fraction_nibbles = HF::fraction_nibbles;
  692. // We do not have to display any trailing 0s, since this represents the
  693. // fractional part.
  694. while (fraction_nibbles > 0 && (fraction & 0xF) == 0) {
  695. // Shift off any trailing values;
  696. fraction = static_cast<uint_type>(fraction >> 4);
  697. --fraction_nibbles;
  698. }
  699. const auto saved_flags = os.flags();
  700. const auto saved_fill = os.fill();
  701. os << sign << "0x" << (is_zero ? '0' : '1');
  702. if (fraction_nibbles) {
  703. // Make sure to keep the leading 0s in place, since this is the fractional
  704. // part.
  705. os << "." << std::setw(static_cast<int>(fraction_nibbles))
  706. << std::setfill('0') << std::hex << fraction;
  707. }
  708. os << "p" << std::dec << (int_exponent >= 0 ? "+" : "") << int_exponent;
  709. os.flags(saved_flags);
  710. os.fill(saved_fill);
  711. return os;
  712. }
  713. // Returns true if negate_value is true and the next character on the
  714. // input stream is a plus or minus sign. In that case we also set the fail bit
  715. // on the stream and set the value to the zero value for its type.
  716. template <typename T, typename Traits>
  717. inline bool RejectParseDueToLeadingSign(std::istream& is, bool negate_value,
  718. HexFloat<T, Traits>& value) {
  719. if (negate_value) {
  720. auto next_char = is.peek();
  721. if (next_char == '-' || next_char == '+') {
  722. // Fail the parse. Emulate standard behaviour by setting the value to
  723. // the zero value, and set the fail bit on the stream.
  724. value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type{0});
  725. is.setstate(std::ios_base::failbit);
  726. return true;
  727. }
  728. }
  729. return false;
  730. }
  731. // Parses a floating point number from the given stream and stores it into the
  732. // value parameter.
  733. // If negate_value is true then the number may not have a leading minus or
  734. // plus, and if it successfully parses, then the number is negated before
  735. // being stored into the value parameter.
  736. // If the value cannot be correctly parsed or overflows the target floating
  737. // point type, then set the fail bit on the stream.
  738. // TODO(dneto): Promise C++11 standard behavior in how the value is set in
  739. // the error case, but only after all target platforms implement it correctly.
  740. // In particular, the Microsoft C++ runtime appears to be out of spec.
  741. template <typename T, typename Traits>
  742. inline std::istream& ParseNormalFloat(std::istream& is, bool negate_value,
  743. HexFloat<T, Traits>& value) {
  744. if (RejectParseDueToLeadingSign(is, negate_value, value)) {
  745. return is;
  746. }
  747. T val;
  748. is >> val;
  749. if (negate_value) {
  750. val = -val;
  751. }
  752. value.set_value(val);
  753. // In the failure case, map -0.0 to 0.0.
  754. if (is.fail() && value.getUnsignedBits() == 0u) {
  755. value = HexFloat<T, Traits>(typename HexFloat<T, Traits>::uint_type{0});
  756. }
  757. if (val.isInfinity()) {
  758. // Fail the parse. Emulate standard behaviour by setting the value to
  759. // the closest normal value, and set the fail bit on the stream.
  760. value.set_value((value.isNegative() | negate_value) ? T::lowest()
  761. : T::max());
  762. is.setstate(std::ios_base::failbit);
  763. }
  764. return is;
  765. }
  766. // Specialization of ParseNormalFloat for FloatProxy<Float16> values.
  767. // This will parse the float as it were a 32-bit floating point number,
  768. // and then round it down to fit into a Float16 value.
  769. // The number is rounded towards zero.
  770. // If negate_value is true then the number may not have a leading minus or
  771. // plus, and if it successfully parses, then the number is negated before
  772. // being stored into the value parameter.
  773. // If the value cannot be correctly parsed or overflows the target floating
  774. // point type, then set the fail bit on the stream.
  775. // TODO(dneto): Promise C++11 standard behavior in how the value is set in
  776. // the error case, but only after all target platforms implement it correctly.
  777. // In particular, the Microsoft C++ runtime appears to be out of spec.
  778. template <>
  779. inline std::istream&
  780. ParseNormalFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>(
  781. std::istream& is, bool negate_value,
  782. HexFloat<FloatProxy<Float16>, HexFloatTraits<FloatProxy<Float16>>>& value) {
  783. // First parse as a 32-bit float.
  784. HexFloat<FloatProxy<float>> float_val(0.0f);
  785. ParseNormalFloat(is, negate_value, float_val);
  786. // Then convert to 16-bit float, saturating at infinities, and
  787. // rounding toward zero.
  788. float_val.castTo(value, round_direction::kToZero);
  789. // Overflow on 16-bit behaves the same as for 32- and 64-bit: set the
  790. // fail bit and set the lowest or highest value.
  791. if (Float16::isInfinity(value.value().getAsFloat())) {
  792. value.set_value(value.isNegative() ? Float16::lowest() : Float16::max());
  793. is.setstate(std::ios_base::failbit);
  794. }
  795. return is;
  796. }
  797. namespace detail {
  798. // Returns a new value formed from 'value' by setting 'bit' that is the
  799. // 'n'th most significant bit (where 0 is the most significant bit).
  800. // If 'bit' is zero or 'n' is more than the number of bits in the integer
  801. // type, then return the original value.
  802. template <typename UINT_TYPE>
  803. UINT_TYPE set_nth_most_significant_bit(UINT_TYPE value, UINT_TYPE bit,
  804. UINT_TYPE n) {
  805. constexpr UINT_TYPE max_position = std::numeric_limits<UINT_TYPE>::digits - 1;
  806. if ((bit != 0) && (n <= max_position)) {
  807. return static_cast<UINT_TYPE>(value | (bit << (max_position - n)));
  808. }
  809. return value;
  810. }
  811. // Attempts to increment the argument.
  812. // If it does not overflow, then increments the argument and returns true.
  813. // If it would overflow, returns false.
  814. template <typename INT_TYPE>
  815. bool saturated_inc(INT_TYPE& value) {
  816. if (value == std::numeric_limits<INT_TYPE>::max()) {
  817. return false;
  818. }
  819. value++;
  820. return true;
  821. }
  822. // Attempts to decrement the argument.
  823. // If it does not underflow, then decrements the argument and returns true.
  824. // If it would overflow, returns false.
  825. template <typename INT_TYPE>
  826. bool saturated_dec(INT_TYPE& value) {
  827. if (value == std::numeric_limits<INT_TYPE>::min()) {
  828. return false;
  829. }
  830. value--;
  831. return true;
  832. }
  833. } // namespace detail
  834. // Reads a HexFloat from the given stream.
  835. // If the float is not encoded as a hex-float then it will be parsed
  836. // as a regular float.
  837. // This may fail if your stream does not support at least one unget.
  838. // Nan values can be encoded with "0x1.<not zero>p+exponent_bias".
  839. // This would normally overflow a float and round to
  840. // infinity but this special pattern is the exact representation for a NaN,
  841. // and therefore is actually encoded as the correct NaN. To encode inf,
  842. // either 0x0p+exponent_bias can be specified or any exponent greater than
  843. // exponent_bias.
  844. // Examples using IEEE 32-bit float encoding.
  845. // 0x1.0p+128 (+inf)
  846. // -0x1.0p-128 (-inf)
  847. //
  848. // 0x1.1p+128 (+Nan)
  849. // -0x1.1p+128 (-Nan)
  850. //
  851. // 0x1p+129 (+inf)
  852. // -0x1p+129 (-inf)
  853. template <typename T, typename Traits>
  854. std::istream& operator>>(std::istream& is, HexFloat<T, Traits>& value) {
  855. using HF = HexFloat<T, Traits>;
  856. using uint_type = typename HF::uint_type;
  857. using int_type = typename HF::int_type;
  858. value.set_value(static_cast<typename HF::native_type>(0.f));
  859. if (is.flags() & std::ios::skipws) {
  860. // If the user wants to skip whitespace , then we should obey that.
  861. while (std::isspace(is.peek())) {
  862. is.get();
  863. }
  864. }
  865. auto next_char = is.peek();
  866. bool negate_value = false;
  867. if (next_char != '-' && next_char != '0') {
  868. return ParseNormalFloat(is, negate_value, value);
  869. }
  870. if (next_char == '-') {
  871. negate_value = true;
  872. is.get();
  873. next_char = is.peek();
  874. }
  875. if (next_char == '0') {
  876. is.get(); // We may have to unget this.
  877. auto maybe_hex_start = is.peek();
  878. if (maybe_hex_start != 'x' && maybe_hex_start != 'X') {
  879. is.unget();
  880. return ParseNormalFloat(is, negate_value, value);
  881. } else {
  882. is.get(); // Throw away the 'x';
  883. }
  884. } else {
  885. return ParseNormalFloat(is, negate_value, value);
  886. }
  887. // This "looks" like a hex-float so treat it as one.
  888. bool seen_p = false;
  889. bool seen_dot = false;
  890. // The mantissa bits, without the most significant 1 bit, and with the
  891. // the most recently read bits in the least significant positions.
  892. uint_type fraction = 0;
  893. // The number of mantissa bits that have been read, including the leading 1
  894. // bit that is not written into 'fraction'.
  895. uint_type fraction_index = 0;
  896. // TODO(dneto): handle overflow and underflow
  897. int_type exponent = HF::exponent_bias;
  898. // Strip off leading zeros so we don't have to special-case them later.
  899. while ((next_char = is.peek()) == '0') {
  900. is.get();
  901. }
  902. // Does the mantissa, as written, have non-zero digits to the left of
  903. // the decimal point. Assume no until proven otherwise.
  904. bool has_integer_part = false;
  905. bool bits_written = false; // Stays false until we write a bit.
  906. // Scan the mantissa hex digits until we see a '.' or the 'p' that
  907. // starts the exponent.
  908. while (!seen_p && !seen_dot) {
  909. // Handle characters that are left of the fractional part.
  910. if (next_char == '.') {
  911. seen_dot = true;
  912. } else if (next_char == 'p') {
  913. seen_p = true;
  914. } else if (::isxdigit(next_char)) {
  915. // We have stripped all leading zeroes and we have not yet seen a ".".
  916. has_integer_part = true;
  917. int number = get_nibble_from_character(next_char);
  918. for (int i = 0; i < 4; ++i, number <<= 1) {
  919. uint_type write_bit = (number & 0x8) ? 0x1 : 0x0;
  920. if (bits_written) {
  921. // If we are here the bits represented belong in the fractional
  922. // part of the float, and we have to adjust the exponent accordingly.
  923. fraction = detail::set_nth_most_significant_bit(fraction, write_bit,
  924. fraction_index);
  925. // Increment the fraction index. If the input has bizarrely many
  926. // significant digits, then silently drop them.
  927. detail::saturated_inc(fraction_index);
  928. if (!detail::saturated_inc(exponent)) {
  929. // Overflow failure
  930. is.setstate(std::ios::failbit);
  931. return is;
  932. }
  933. }
  934. // Since this updated after setting fraction bits, this effectively
  935. // drops the leading 1 bit.
  936. bits_written |= write_bit != 0;
  937. }
  938. } else {
  939. // We have not found our exponent yet, so we have to fail.
  940. is.setstate(std::ios::failbit);
  941. return is;
  942. }
  943. is.get();
  944. next_char = is.peek();
  945. }
  946. // Finished reading the part preceding any '.' or 'p'.
  947. bits_written = false;
  948. while (seen_dot && !seen_p) {
  949. // Handle only fractional parts now.
  950. if (next_char == 'p') {
  951. seen_p = true;
  952. } else if (::isxdigit(next_char)) {
  953. int number = get_nibble_from_character(next_char);
  954. for (int i = 0; i < 4; ++i, number <<= 1) {
  955. uint_type write_bit = (number & 0x8) ? 0x01 : 0x00;
  956. bits_written |= write_bit != 0;
  957. if ((!has_integer_part) && !bits_written) {
  958. // Handle modifying the exponent here this way we can handle
  959. // an arbitrary number of hex values without overflowing our
  960. // integer.
  961. if (!detail::saturated_dec(exponent)) {
  962. // Overflow failure
  963. is.setstate(std::ios::failbit);
  964. return is;
  965. }
  966. } else {
  967. fraction = detail::set_nth_most_significant_bit(fraction, write_bit,
  968. fraction_index);
  969. // Increment the fraction index. If the input has bizarrely many
  970. // significant digits, then silently drop them.
  971. detail::saturated_inc(fraction_index);
  972. }
  973. }
  974. } else {
  975. // We still have not found our 'p' exponent yet, so this is not a valid
  976. // hex-float.
  977. is.setstate(std::ios::failbit);
  978. return is;
  979. }
  980. is.get();
  981. next_char = is.peek();
  982. }
  983. // Finished reading the part preceding 'p'.
  984. // In hex floats syntax, the binary exponent is required.
  985. bool seen_exponent_sign = false;
  986. int8_t exponent_sign = 1;
  987. bool seen_written_exponent_digits = false;
  988. // The magnitude of the exponent, as written, or the sentinel value to signal
  989. // overflow.
  990. int_type written_exponent = 0;
  991. // A sentinel value signalling overflow of the magnitude of the written
  992. // exponent. We'll assume that -written_exponent_overflow is valid for the
  993. // type. Later we may add 1 or subtract 1 from the adjusted exponent, so leave
  994. // room for an extra 1.
  995. const int_type written_exponent_overflow =
  996. std::numeric_limits<int_type>::max() - 1;
  997. while (true) {
  998. if (!seen_written_exponent_digits &&
  999. (next_char == '-' || next_char == '+')) {
  1000. if (seen_exponent_sign) {
  1001. is.setstate(std::ios::failbit);
  1002. return is;
  1003. }
  1004. seen_exponent_sign = true;
  1005. exponent_sign = (next_char == '-') ? -1 : 1;
  1006. } else if (::isdigit(next_char)) {
  1007. seen_written_exponent_digits = true;
  1008. // Hex-floats express their exponent as decimal.
  1009. int_type digit =
  1010. static_cast<int_type>(static_cast<int_type>(next_char) - '0');
  1011. if (written_exponent >= (written_exponent_overflow - digit) / 10) {
  1012. // The exponent is very big. Saturate rather than overflow the exponent.
  1013. // signed integer, which would be undefined behaviour.
  1014. written_exponent = written_exponent_overflow;
  1015. } else {
  1016. written_exponent = static_cast<int_type>(
  1017. static_cast<int_type>(written_exponent * 10) + digit);
  1018. }
  1019. } else {
  1020. break;
  1021. }
  1022. is.get();
  1023. next_char = is.peek();
  1024. }
  1025. if (!seen_written_exponent_digits) {
  1026. // Binary exponent had no digits.
  1027. is.setstate(std::ios::failbit);
  1028. return is;
  1029. }
  1030. written_exponent = static_cast<int_type>(written_exponent * exponent_sign);
  1031. // Now fold in the exponent bias into the written exponent, updating exponent.
  1032. // But avoid undefined behaviour that would result from overflowing int_type.
  1033. if (written_exponent >= 0 && exponent >= 0) {
  1034. // Saturate up to written_exponent_overflow.
  1035. if (written_exponent_overflow - exponent > written_exponent) {
  1036. exponent = static_cast<int_type>(written_exponent + exponent);
  1037. } else {
  1038. exponent = written_exponent_overflow;
  1039. }
  1040. } else if (written_exponent < 0 && exponent < 0) {
  1041. // Saturate down to -written_exponent_overflow.
  1042. if (written_exponent_overflow + exponent > -written_exponent) {
  1043. exponent = static_cast<int_type>(written_exponent + exponent);
  1044. } else {
  1045. exponent = static_cast<int_type>(-written_exponent_overflow);
  1046. }
  1047. } else {
  1048. // They're of opposing sign, so it's safe to add.
  1049. exponent = static_cast<int_type>(written_exponent + exponent);
  1050. }
  1051. bool is_zero = (!has_integer_part) && (fraction == 0);
  1052. if ((!has_integer_part) && !is_zero) {
  1053. fraction = static_cast<uint_type>(fraction << 1);
  1054. exponent = static_cast<int_type>(exponent - 1);
  1055. } else if (is_zero) {
  1056. exponent = 0;
  1057. }
  1058. if (exponent <= 0 && !is_zero) {
  1059. fraction = static_cast<uint_type>(fraction >> 1);
  1060. fraction |= static_cast<uint_type>(1) << HF::top_bit_left_shift;
  1061. }
  1062. fraction = (fraction >> HF::fraction_right_shift) & HF::fraction_encode_mask;
  1063. const int_type max_exponent =
  1064. SetBits<uint_type, 0, HF::num_exponent_bits>::get;
  1065. // Handle denorm numbers
  1066. while (exponent < 0 && !is_zero) {
  1067. fraction = static_cast<uint_type>(fraction >> 1);
  1068. exponent = static_cast<int_type>(exponent + 1);
  1069. fraction &= HF::fraction_encode_mask;
  1070. if (fraction == 0) {
  1071. // We have underflowed our fraction. We should clamp to zero.
  1072. is_zero = true;
  1073. exponent = 0;
  1074. }
  1075. }
  1076. // We have overflowed so we should be inf/-inf.
  1077. if (exponent > max_exponent) {
  1078. exponent = max_exponent;
  1079. fraction = 0;
  1080. }
  1081. uint_type output_bits = static_cast<uint_type>(
  1082. static_cast<uint_type>(negate_value ? 1 : 0) << HF::top_bit_left_shift);
  1083. output_bits |= fraction;
  1084. uint_type shifted_exponent = static_cast<uint_type>(
  1085. static_cast<uint_type>(exponent << HF::exponent_left_shift) &
  1086. HF::exponent_mask);
  1087. output_bits |= shifted_exponent;
  1088. T output_float(output_bits);
  1089. value.set_value(output_float);
  1090. return is;
  1091. }
  1092. // Writes a FloatProxy value to a stream.
  1093. // Zero and normal numbers are printed in the usual notation, but with
  1094. // enough digits to fully reproduce the value. Other values (subnormal,
  1095. // NaN, and infinity) are printed as a hex float.
  1096. template <typename T>
  1097. std::ostream& operator<<(std::ostream& os, const FloatProxy<T>& value) {
  1098. auto float_val = value.getAsFloat();
  1099. switch (std::fpclassify(float_val)) {
  1100. case FP_ZERO:
  1101. case FP_NORMAL: {
  1102. auto saved_precision = os.precision();
  1103. os.precision(std::numeric_limits<T>::max_digits10);
  1104. os << float_val;
  1105. os.precision(saved_precision);
  1106. } break;
  1107. default:
  1108. os << HexFloat<FloatProxy<T>>(value);
  1109. break;
  1110. }
  1111. return os;
  1112. }
  1113. template <>
  1114. inline std::ostream& operator<<<Float16>(std::ostream& os,
  1115. const FloatProxy<Float16>& value) {
  1116. os << HexFloat<FloatProxy<Float16>>(value);
  1117. return os;
  1118. }
  1119. } // namespace utils
  1120. } // namespace spvtools
  1121. #endif // SOURCE_UTIL_HEX_FLOAT_H_