fp_div_impl.inc (19189B)
1 //===-- fp_div_impl.inc - Floating point division -----------------*- 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 // This file implements soft-float division with the IEEE-754 default 10 // rounding (to nearest, ties to even). 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "fp_lib.h" 15 16 #define __divXf3__ _FP_NAME(__divXf3__) 17 18 #if defined SINGLE_PRECISION && !defined FP_DIV_SF_EMITTED 19 #define FP_DIV_SF_EMITTED 20 #define _FP_DIV_EMIT 1 21 #elif defined DOUBLE_PRECISION && !defined FP_DIV_DF_EMITTED 22 #define FP_DIV_DF_EMITTED 23 #define _FP_DIV_EMIT 1 24 #elif defined QUAD_PRECISION && !defined FP_DIV_TF_EMITTED 25 #define FP_DIV_TF_EMITTED 26 #define _FP_DIV_EMIT 1 27 #endif 28 29 #ifdef _FP_DIV_EMIT 30 #undef _FP_DIV_EMIT 31 32 // The __divXf3__ function implements Newton-Raphson floating point division. 33 // It uses 3 iterations for float32, 4 for float64 and 5 for float128, 34 // respectively. Due to number of significant bits being roughly doubled 35 // every iteration, the two modes are supported: N full-width iterations (as 36 // it is done for float32 by default) and (N-1) half-width iteration plus one 37 // final full-width iteration. It is expected that half-width integer 38 // operations (w.r.t rep_t size) can be performed faster for some hardware but 39 // they require error estimations to be computed separately due to larger 40 // computational errors caused by truncating intermediate results. 41 42 // Half the bit-size of rep_t 43 #define HW (typeWidth / 2) 44 // rep_t-sized bitmask with lower half of bits set to ones 45 #define loMask (REP_C(-1) >> HW) 46 47 #if NUMBER_OF_FULL_ITERATIONS < 1 48 #error At least one full iteration is required 49 #endif 50 51 static inline fp_t __divXf3__(fp_t a, fp_t b) { 52 53 const unsigned int aExponent = toRep(a) >> significandBits & maxExponent; 54 const unsigned int bExponent = toRep(b) >> significandBits & maxExponent; 55 const rep_t quotientSign = (toRep(a) ^ toRep(b)) & signBit; 56 57 rep_t aSignificand = toRep(a) & significandMask; 58 rep_t bSignificand = toRep(b) & significandMask; 59 int scale = 0; 60 61 // Detect if a or b is zero, denormal, infinity, or NaN. 62 if (aExponent - 1U >= maxExponent - 1U || 63 bExponent - 1U >= maxExponent - 1U) { 64 65 const rep_t aAbs = toRep(a) & absMask; 66 const rep_t bAbs = toRep(b) & absMask; 67 68 // NaN / anything = qNaN 69 if (aAbs > infRep) 70 return fromRep(toRep(a) | quietBit); 71 // anything / NaN = qNaN 72 if (bAbs > infRep) 73 return fromRep(toRep(b) | quietBit); 74 75 if (aAbs == infRep) { 76 // infinity / infinity = NaN 77 if (bAbs == infRep) 78 return fromRep(qnanRep); 79 // infinity / anything else = +/- infinity 80 else 81 return fromRep(aAbs | quotientSign); 82 } 83 84 // anything else / infinity = +/- 0 85 if (bAbs == infRep) 86 return fromRep(quotientSign); 87 88 if (!aAbs) { 89 // zero / zero = NaN 90 if (!bAbs) 91 return fromRep(qnanRep); 92 // zero / anything else = +/- zero 93 else 94 return fromRep(quotientSign); 95 } 96 // anything else / zero = +/- infinity 97 if (!bAbs) 98 return fromRep(infRep | quotientSign); 99 100 // One or both of a or b is denormal. The other (if applicable) is a 101 // normal number. Renormalize one or both of a and b, and set scale to 102 // include the necessary exponent adjustment. 103 if (aAbs < implicitBit) 104 scale += normalize(&aSignificand); 105 if (bAbs < implicitBit) 106 scale -= normalize(&bSignificand); 107 } 108 109 // Set the implicit significand bit. If we fell through from the 110 // denormal path it was already set by normalize( ), but setting it twice 111 // won't hurt anything. 112 aSignificand |= implicitBit; 113 bSignificand |= implicitBit; 114 115 int writtenExponent = (aExponent - bExponent + scale) + exponentBias; 116 117 const rep_t b_UQ1 = bSignificand << (typeWidth - significandBits - 1); 118 119 // Align the significand of b as a UQ1.(n-1) fixed-point number in the range 120 // [1.0, 2.0) and get a UQ0.n approximate reciprocal using a small minimax 121 // polynomial approximation: x0 = 3/4 + 1/sqrt(2) - b/2. 122 // The max error for this approximation is achieved at endpoints, so 123 // abs(x0(b) - 1/b) <= abs(x0(1) - 1/1) = 3/4 - 1/sqrt(2) = 0.04289..., 124 // which is about 4.5 bits. 125 // The initial approximation is between x0(1.0) = 0.9571... and x0(2.0) = 0.4571... 126 127 // Then, refine the reciprocal estimate using a quadratically converging 128 // Newton-Raphson iteration: 129 // x_{n+1} = x_n * (2 - x_n * b) 130 // 131 // Let b be the original divisor considered "in infinite precision" and 132 // obtained from IEEE754 representation of function argument (with the 133 // implicit bit set). Corresponds to rep_t-sized b_UQ1 represented in 134 // UQ1.(W-1). 135 // 136 // Let b_hw be an infinitely precise number obtained from the highest (HW-1) 137 // bits of divisor significand (with the implicit bit set). Corresponds to 138 // half_rep_t-sized b_UQ1_hw represented in UQ1.(HW-1) that is a **truncated** 139 // version of b_UQ1. 140 // 141 // Let e_n := x_n - 1/b_hw 142 // E_n := x_n - 1/b 143 // abs(E_n) <= abs(e_n) + (1/b_hw - 1/b) 144 // = abs(e_n) + (b - b_hw) / (b*b_hw) 145 // <= abs(e_n) + 2 * 2^-HW 146 147 // rep_t-sized iterations may be slower than the corresponding half-width 148 // variant depending on the handware and whether single/double/quad precision 149 // is selected. 150 // NB: Using half-width iterations increases computation errors due to 151 // rounding, so error estimations have to be computed taking the selected 152 // mode into account! 153 #if NUMBER_OF_HALF_ITERATIONS > 0 154 // Starting with (n-1) half-width iterations 155 const half_rep_t b_UQ1_hw = bSignificand >> (significandBits + 1 - HW); 156 157 // C is (3/4 + 1/sqrt(2)) - 1 truncated to W0 fractional bits as UQ0.HW 158 // with W0 being either 16 or 32 and W0 <= HW. 159 // That is, C is the aforementioned 3/4 + 1/sqrt(2) constant (from which 160 // b/2 is subtracted to obtain x0) wrapped to [0, 1) range. 161 #if defined(SINGLE_PRECISION) 162 // Use 16-bit initial estimation in case we are using half-width iterations 163 // for float32 division. This is expected to be useful for some 16-bit 164 // targets. Not used by default as it requires performing more work during 165 // rounding and would hardly help on regular 32- or 64-bit targets. 166 const half_rep_t C_hw = HALF_REP_C(0x7504); 167 #else 168 // HW is at least 32. Shifting into the highest bits if needed. 169 const half_rep_t C_hw = HALF_REP_C(0x7504F333) << (HW - 32); 170 #endif 171 172 // b >= 1, thus an upper bound for 3/4 + 1/sqrt(2) - b/2 is about 0.9572, 173 // so x0 fits to UQ0.HW without wrapping. 174 half_rep_t x_UQ0_hw = C_hw - (b_UQ1_hw /* exact b_hw/2 as UQ0.HW */); 175 // An e_0 error is comprised of errors due to 176 // * x0 being an inherently imprecise first approximation of 1/b_hw 177 // * C_hw being some (irrational) number **truncated** to W0 bits 178 // Please note that e_0 is calculated against the infinitely precise 179 // reciprocal of b_hw (that is, **truncated** version of b). 180 // 181 // e_0 <= 3/4 - 1/sqrt(2) + 2^-W0 182 183 // By construction, 1 <= b < 2 184 // f(x) = x * (2 - b*x) = 2*x - b*x^2 185 // f'(x) = 2 * (1 - b*x) 186 // 187 // On the [0, 1] interval, f(0) = 0, 188 // then it increses until f(1/b) = 1 / b, maximum on (0, 1), 189 // then it decreses to f(1) = 2 - b 190 // 191 // Let g(x) = x - f(x) = b*x^2 - x. 192 // On (0, 1/b), g(x) < 0 <=> f(x) > x 193 // On (1/b, 1], g(x) > 0 <=> f(x) < x 194 // 195 // For half-width iterations, b_hw is used instead of b. 196 REPEAT_N_TIMES(NUMBER_OF_HALF_ITERATIONS, { 197 // corr_UQ1_hw can be **larger** than 2 - b_hw*x by at most 1*Ulp 198 // of corr_UQ1_hw. 199 // "0.0 - (...)" is equivalent to "2.0 - (...)" in UQ1.(HW-1). 200 // On the other hand, corr_UQ1_hw should not overflow from 2.0 to 0.0 provided 201 // no overflow occurred earlier: ((rep_t)x_UQ0_hw * b_UQ1_hw >> HW) is 202 // expected to be strictly positive because b_UQ1_hw has its highest bit set 203 // and x_UQ0_hw should be rather large (it converges to 1/2 < 1/b_hw <= 1). 204 half_rep_t corr_UQ1_hw = 0 - ((rep_t)x_UQ0_hw * b_UQ1_hw >> HW); 205 206 // Now, we should multiply UQ0.HW and UQ1.(HW-1) numbers, naturally 207 // obtaining an UQ1.(HW-1) number and proving its highest bit could be 208 // considered to be 0 to be able to represent it in UQ0.HW. 209 // From the above analysis of f(x), if corr_UQ1_hw would be represented 210 // without any intermediate loss of precision (that is, in twice_rep_t) 211 // x_UQ0_hw could be at most [1.]000... if b_hw is exactly 1.0 and strictly 212 // less otherwise. On the other hand, to obtain [1.]000..., one have to pass 213 // 1/b_hw == 1.0 to f(x), so this cannot occur at all without overflow (due 214 // to 1.0 being not representable as UQ0.HW). 215 // The fact corr_UQ1_hw was virtually round up (due to result of 216 // multiplication being **first** truncated, then negated - to improve 217 // error estimations) can increase x_UQ0_hw by up to 2*Ulp of x_UQ0_hw. 218 x_UQ0_hw = (rep_t)x_UQ0_hw * corr_UQ1_hw >> (HW - 1); 219 // Now, either no overflow occurred or x_UQ0_hw is 0 or 1 in its half_rep_t 220 // representation. In the latter case, x_UQ0_hw will be either 0 or 1 after 221 // any number of iterations, so just subtract 2 from the reciprocal 222 // approximation after last iteration. 223 224 // In infinite precision, with 0 <= eps1, eps2 <= U = 2^-HW: 225 // corr_UQ1_hw = 2 - (1/b_hw + e_n) * b_hw + 2*eps1 226 // = 1 - e_n * b_hw + 2*eps1 227 // x_UQ0_hw = (1/b_hw + e_n) * (1 - e_n*b_hw + 2*eps1) - eps2 228 // = 1/b_hw - e_n + 2*eps1/b_hw + e_n - e_n^2*b_hw + 2*e_n*eps1 - eps2 229 // = 1/b_hw + 2*eps1/b_hw - e_n^2*b_hw + 2*e_n*eps1 - eps2 230 // e_{n+1} = -e_n^2*b_hw + 2*eps1/b_hw + 2*e_n*eps1 - eps2 231 // = 2*e_n*eps1 - (e_n^2*b_hw + eps2) + 2*eps1/b_hw 232 // \------ >0 -------/ \-- >0 ---/ 233 // abs(e_{n+1}) <= 2*abs(e_n)*U + max(2*e_n^2 + U, 2 * U) 234 }) 235 // For initial half-width iterations, U = 2^-HW 236 // Let abs(e_n) <= u_n * U, 237 // then abs(e_{n+1}) <= 2 * u_n * U^2 + max(2 * u_n^2 * U^2 + U, 2 * U) 238 // u_{n+1} <= 2 * u_n * U + max(2 * u_n^2 * U + 1, 2) 239 240 // Account for possible overflow (see above). For an overflow to occur for the 241 // first time, for "ideal" corr_UQ1_hw (that is, without intermediate 242 // truncation), the result of x_UQ0_hw * corr_UQ1_hw should be either maximum 243 // value representable in UQ0.HW or less by 1. This means that 1/b_hw have to 244 // be not below that value (see g(x) above), so it is safe to decrement just 245 // once after the final iteration. On the other hand, an effective value of 246 // divisor changes after this point (from b_hw to b), so adjust here. 247 x_UQ0_hw -= 1U; 248 rep_t x_UQ0 = (rep_t)x_UQ0_hw << HW; 249 x_UQ0 -= 1U; 250 251 #else 252 // C is (3/4 + 1/sqrt(2)) - 1 truncated to 32 fractional bits as UQ0.n 253 const rep_t C = REP_C(0x7504F333) << (typeWidth - 32); 254 rep_t x_UQ0 = C - b_UQ1; 255 // E_0 <= 3/4 - 1/sqrt(2) + 2 * 2^-32 256 #endif 257 258 // Error estimations for full-precision iterations are calculated just 259 // as above, but with U := 2^-W and taking extra decrementing into account. 260 // We need at least one such iteration. 261 262 #ifdef USE_NATIVE_FULL_ITERATIONS 263 REPEAT_N_TIMES(NUMBER_OF_FULL_ITERATIONS, { 264 rep_t corr_UQ1 = 0 - ((twice_rep_t)x_UQ0 * b_UQ1 >> typeWidth); 265 x_UQ0 = (twice_rep_t)x_UQ0 * corr_UQ1 >> (typeWidth - 1); 266 }) 267 #else 268 #if NUMBER_OF_FULL_ITERATIONS != 1 269 #error Only a single emulated full iteration is supported 270 #endif 271 #if !(NUMBER_OF_HALF_ITERATIONS > 0) 272 // Cannot normally reach here: only one full-width iteration is requested and 273 // the total number of iterations should be at least 3 even for float32. 274 #error Check NUMBER_OF_HALF_ITERATIONS, NUMBER_OF_FULL_ITERATIONS and USE_NATIVE_FULL_ITERATIONS. 275 #endif 276 // Simulating operations on a twice_rep_t to perform a single final full-width 277 // iteration. Using ad-hoc multiplication implementations to take advantage 278 // of particular structure of operands. 279 rep_t blo = b_UQ1 & loMask; 280 // x_UQ0 = x_UQ0_hw * 2^HW - 1 281 // x_UQ0 * b_UQ1 = (x_UQ0_hw * 2^HW) * (b_UQ1_hw * 2^HW + blo) - b_UQ1 282 // 283 // <--- higher half ---><--- lower half ---> 284 // [x_UQ0_hw * b_UQ1_hw] 285 // + [ x_UQ0_hw * blo ] 286 // - [ b_UQ1 ] 287 // = [ result ][.... discarded ...] 288 rep_t corr_UQ1 = 0U - ( (rep_t)x_UQ0_hw * b_UQ1_hw 289 + ((rep_t)x_UQ0_hw * blo >> HW) 290 - REP_C(1)); // account for *possible* carry 291 rep_t lo_corr = corr_UQ1 & loMask; 292 rep_t hi_corr = corr_UQ1 >> HW; 293 // x_UQ0 * corr_UQ1 = (x_UQ0_hw * 2^HW) * (hi_corr * 2^HW + lo_corr) - corr_UQ1 294 x_UQ0 = ((rep_t)x_UQ0_hw * hi_corr << 1) 295 + ((rep_t)x_UQ0_hw * lo_corr >> (HW - 1)) 296 - REP_C(2); // 1 to account for the highest bit of corr_UQ1 can be 1 297 // 1 to account for possible carry 298 // Just like the case of half-width iterations but with possibility 299 // of overflowing by one extra Ulp of x_UQ0. 300 x_UQ0 -= 1U; 301 // ... and then traditional fixup by 2 should work 302 303 // On error estimation: 304 // abs(E_{N-1}) <= (u_{N-1} + 2 /* due to conversion e_n -> E_n */) * 2^-HW 305 // + (2^-HW + 2^-W)) 306 // abs(E_{N-1}) <= (u_{N-1} + 3.01) * 2^-HW 307 308 // Then like for the half-width iterations: 309 // With 0 <= eps1, eps2 < 2^-W 310 // E_N = 4 * E_{N-1} * eps1 - (E_{N-1}^2 * b + 4 * eps2) + 4 * eps1 / b 311 // abs(E_N) <= 2^-W * [ 4 * abs(E_{N-1}) + max(2 * abs(E_{N-1})^2 * 2^W + 4, 8)) ] 312 // abs(E_N) <= 2^-W * [ 4 * (u_{N-1} + 3.01) * 2^-HW + max(4 + 2 * (u_{N-1} + 3.01)^2, 8) ] 313 #endif 314 315 // Finally, account for possible overflow, as explained above. 316 x_UQ0 -= 2U; 317 318 // u_n for different precisions (with N-1 half-width iterations): 319 // W0 is the precision of C 320 // u_0 = (3/4 - 1/sqrt(2) + 2^-W0) * 2^HW 321 322 // Estimated with bc: 323 // define half1(un) { return 2.0 * (un + un^2) / 2.0^hw + 1.0; } 324 // define half2(un) { return 2.0 * un / 2.0^hw + 2.0; } 325 // define full1(un) { return 4.0 * (un + 3.01) / 2.0^hw + 2.0 * (un + 3.01)^2 + 4.0; } 326 // define full2(un) { return 4.0 * (un + 3.01) / 2.0^hw + 8.0; } 327 328 // | f32 (0 + 3) | f32 (2 + 1) | f64 (3 + 1) | f128 (4 + 1) 329 // u_0 | < 184224974 | < 2812.1 | < 184224974 | < 791240234244348797 330 // u_1 | < 15804007 | < 242.7 | < 15804007 | < 67877681371350440 331 // u_2 | < 116308 | < 2.81 | < 116308 | < 499533100252317 332 // u_3 | < 7.31 | | < 7.31 | < 27054456580 333 // u_4 | | | | < 80.4 334 // Final (U_N) | same as u_3 | < 72 | < 218 | < 13920 335 336 // Add 2 to U_N due to final decrement. 337 338 #if defined(SINGLE_PRECISION) && NUMBER_OF_HALF_ITERATIONS == 2 && NUMBER_OF_FULL_ITERATIONS == 1 339 #define RECIPROCAL_PRECISION REP_C(74) 340 #elif defined(SINGLE_PRECISION) && NUMBER_OF_HALF_ITERATIONS == 0 && NUMBER_OF_FULL_ITERATIONS == 3 341 #define RECIPROCAL_PRECISION REP_C(10) 342 #elif defined(DOUBLE_PRECISION) && NUMBER_OF_HALF_ITERATIONS == 3 && NUMBER_OF_FULL_ITERATIONS == 1 343 #define RECIPROCAL_PRECISION REP_C(220) 344 #elif defined(QUAD_PRECISION) && NUMBER_OF_HALF_ITERATIONS == 4 && NUMBER_OF_FULL_ITERATIONS == 1 345 #define RECIPROCAL_PRECISION REP_C(13922) 346 #else 347 #error Invalid number of iterations 348 #endif 349 350 // Suppose 1/b - P * 2^-W < x < 1/b + P * 2^-W 351 x_UQ0 -= RECIPROCAL_PRECISION; 352 // Now 1/b - (2*P) * 2^-W < x < 1/b 353 // FIXME Is x_UQ0 still >= 0.5? 354 355 rep_t quotient_UQ1, dummy; 356 wideMultiply(x_UQ0, aSignificand << 1, "ient_UQ1, &dummy); 357 // Now, a/b - 4*P * 2^-W < q < a/b for q=<quotient_UQ1:dummy> in UQ1.(SB+1+W). 358 359 // quotient_UQ1 is in [0.5, 2.0) as UQ1.(SB+1), 360 // adjust it to be in [1.0, 2.0) as UQ1.SB. 361 rep_t residualLo; 362 if (quotient_UQ1 < (implicitBit << 1)) { 363 // Highest bit is 0, so just reinterpret quotient_UQ1 as UQ1.SB, 364 // effectively doubling its value as well as its error estimation. 365 residualLo = (aSignificand << (significandBits + 1)) - quotient_UQ1 * bSignificand; 366 writtenExponent -= 1; 367 aSignificand <<= 1; 368 } else { 369 // Highest bit is 1 (the UQ1.(SB+1) value is in [1, 2)), convert it 370 // to UQ1.SB by right shifting by 1. Least significant bit is omitted. 371 quotient_UQ1 >>= 1; 372 residualLo = (aSignificand << significandBits) - quotient_UQ1 * bSignificand; 373 } 374 // NB: residualLo is calculated above for the normal result case. 375 // It is re-computed on denormal path that is expected to be not so 376 // performance-sensitive. 377 378 // Now, q cannot be greater than a/b and can differ by at most 8*P * 2^-W + 2^-SB 379 // Each NextAfter() increments the floating point value by at least 2^-SB 380 // (more, if exponent was incremented). 381 // Different cases (<---> is of 2^-SB length, * = a/b that is shown as a midpoint): 382 // q 383 // | | * | | | | | 384 // <---> 2^t 385 // | | | | | * | | 386 // q 387 // To require at most one NextAfter(), an error should be less than 1.5 * 2^-SB. 388 // (8*P) * 2^-W + 2^-SB < 1.5 * 2^-SB 389 // (8*P) * 2^-W < 0.5 * 2^-SB 390 // P < 2^(W-4-SB) 391 // Generally, for at most R NextAfter() to be enough, 392 // P < (2*R - 1) * 2^(W-4-SB) 393 // For f32 (0+3): 10 < 32 (OK) 394 // For f32 (2+1): 32 < 74 < 32 * 3, so two NextAfter() are required 395 // For f64: 220 < 256 (OK) 396 // For f128: 4096 * 3 < 13922 < 4096 * 5 (three NextAfter() are required) 397 398 // If we have overflowed the exponent, return infinity 399 if (writtenExponent >= maxExponent) 400 return fromRep(infRep | quotientSign); 401 402 // Now, quotient_UQ1_SB <= the correctly-rounded result 403 // and may need taking NextAfter() up to 3 times (see error estimates above) 404 // r = a - b * q 405 rep_t absResult; 406 if (writtenExponent > 0) { 407 // Clear the implicit bit 408 absResult = quotient_UQ1 & significandMask; 409 // Insert the exponent 410 absResult |= (rep_t)writtenExponent << significandBits; 411 residualLo <<= 1; 412 } else { 413 // Prevent shift amount from being negative 414 if (significandBits + writtenExponent < 0) 415 return fromRep(quotientSign); 416 417 absResult = quotient_UQ1 >> (-writtenExponent + 1); 418 419 // multiplied by two to prevent shift amount to be negative 420 residualLo = (aSignificand << (significandBits + writtenExponent)) - (absResult * bSignificand << 1); 421 } 422 423 // Round 424 residualLo += absResult & 1; // tie to even 425 // The above line conditionally turns the below LT comparison into LTE 426 absResult += residualLo > bSignificand; 427 #if defined(QUAD_PRECISION) || (defined(SINGLE_PRECISION) && NUMBER_OF_HALF_ITERATIONS > 0) 428 // Do not round Infinity to NaN 429 absResult += absResult < infRep && residualLo > (2 + 1) * bSignificand; 430 #endif 431 #if defined(QUAD_PRECISION) 432 absResult += absResult < infRep && residualLo > (4 + 1) * bSignificand; 433 #endif 434 return fromRep(absResult | quotientSign); 435 } 436 437 #undef HW 438 #undef loMask 439 #undef RECIPROCAL_PRECISION 440 441 #endif // _FP_DIV_EMIT