c6b62dc7f8cba2d03bce6839634f17a93986d975
[oota-llvm.git] / include / llvm / ADT / APFloat.h
1 //== llvm/Support/APFloat.h - Arbitrary Precision Floating Point -*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Neil Booth and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares a class to represent arbitrary precision floating
11 // point values and provide a variety of arithmetic operations on them.
12 //
13 //===----------------------------------------------------------------------===//
14
15 /*  A self-contained host- and target-independent arbitrary-precision
16     floating-point software implementation using bignum integer
17     arithmetic, as provided by static functions in the APInt class.
18     The library will work with bignum integers whose parts are any
19     unsigned type at least 16 bits wide.  64 bits is recommended.
20
21     Written for clarity rather than speed, in particular with a view
22     to use in the front-end of a cross compiler so that target
23     arithmetic can be correctly performed on the host.  Performance
24     should nonetheless be reasonable, particularly for its intended
25     use.  It may be useful as a base implementation for a run-time
26     library during development of a faster target-specific one.
27
28     All 5 rounding modes in the IEEE-754R draft are handled correctly
29     for all implemented operations.  Currently implemented operations
30     are add, subtract, multiply, divide, fused-multiply-add,
31     conversion-to-float, conversion-to-integer and
32     conversion-from-integer.  New rounding modes (e.g. away from zero)
33     can be added with three or four lines of code.  The library reads
34     and correctly rounds hexadecimal floating point numbers as per
35     C99; syntax is required to have been validated by the caller.
36     Conversion from decimal is not currently implemented.
37
38     Four formats are built-in: IEEE single precision, double
39     precision, quadruple precision, and x87 80-bit extended double
40     (when operating with full extended precision).  Adding a new
41     format that obeys IEEE semantics only requires adding two lines of
42     code: a declaration and definition of the format.
43
44     All operations return the status of that operation as an exception
45     bit-mask, so multiple operations can be done consecutively with
46     their results or-ed together.  The returned status can be useful
47     for compiler diagnostics; e.g., inexact, underflow and overflow
48     can be easily diagnosed on constant folding, and compiler
49     optimizers can determine what exceptions would be raised by
50     folding operations and optimize, or perhaps not optimize,
51     accordingly.
52
53     At present, underflow tininess is detected after rounding; it
54     should be straight forward to add support for the before-rounding
55     case too.
56
57     Non-zero finite numbers are represented internally as a sign bit,
58     a 16-bit signed exponent, and the significand as an array of
59     integer parts.  After normalization of a number of precision P the
60     exponent is within the range of the format, and if the number is
61     not denormal the P-th bit of the significand is set as an explicit
62     integer bit.  For denormals the most significant bit is shifted
63     right so that the exponent is maintained at the format's minimum,
64     so that the smallest denormal has just the least significant bit
65     of the significand set.  The sign of zeroes and infinities is
66     significant; the exponent and significand of such numbers is not
67     stored, but has a known implicit (deterministic) value: 0 for the
68     significands, 0 for zero exponent, all 1 bits for infinity
69     exponent.  For NaNs the sign and significand are deterministic,
70     although not really meaningful, and preserved in non-conversion
71     operations.  The exponent is implicitly all 1 bits.
72
73     TODO
74     ====
75
76     Some features that may or may not be worth adding:
77
78     Conversions to and from decimal strings (hard).
79
80     Conversions to hexadecimal string.
81
82     Read and write IEEE-format in-memory representations.
83
84     Optional ability to detect underflow tininess before rounding.
85
86     New formats: x87 in single and double precision mode (IEEE apart
87     from extended exponent range) and IBM two-double extended
88     precision (hard).
89
90     New operations: sqrt, nextafter, nexttoward.
91 */
92
93 #ifndef LLVM_FLOAT_H
94 #define LLVM_FLOAT_H
95
96 // APInt contains static functions implementing bignum arithmetic.
97 #include "llvm/ADT/APInt.h"
98 #include "llvm/CodeGen/ValueTypes.h"
99
100 namespace llvm {
101
102   /* Exponents are stored as signed numbers.  */
103   typedef signed short exponent_t;
104
105   struct fltSemantics;
106
107   /* When bits of a floating point number are truncated, this enum is
108      used to indicate what fraction of the LSB those bits represented.
109      It essentially combines the roles of guard and sticky bits.  */
110   enum lostFraction {           // Example of truncated bits:
111     lfExactlyZero,              // 000000
112     lfLessThanHalf,             // 0xxxxx  x's not all zero
113     lfExactlyHalf,              // 100000
114     lfMoreThanHalf              // 1xxxxx  x's not all zero
115   };
116
117   class APFloat {
118   public:
119
120     /* We support the following floating point semantics.  */
121     static const fltSemantics IEEEsingle;
122     static const fltSemantics IEEEdouble;
123     static const fltSemantics IEEEquad;
124     static const fltSemantics x87DoubleExtended;
125     /* And this psuedo, used to construct APFloats that cannot
126        conflict with anything real. */
127     static const fltSemantics Bogus;
128
129     static unsigned int semanticsPrecision(const fltSemantics &);
130
131     /* Floating point numbers have a four-state comparison relation.  */
132     enum cmpResult {
133       cmpLessThan,
134       cmpEqual,
135       cmpGreaterThan,
136       cmpUnordered
137     };
138
139     /* IEEE-754R gives five rounding modes.  */
140     enum roundingMode {
141       rmNearestTiesToEven,
142       rmTowardPositive,
143       rmTowardNegative,
144       rmTowardZero,
145       rmNearestTiesToAway
146     };
147
148     /* Operation status.  opUnderflow or opOverflow are always returned
149        or-ed with opInexact.  */
150     enum opStatus {
151       opOK          = 0x00,
152       opInvalidOp   = 0x01,
153       opDivByZero   = 0x02,
154       opOverflow    = 0x04,
155       opUnderflow   = 0x08,
156       opInexact     = 0x10
157     };
158
159     /* Category of internally-represented number.  */
160     enum fltCategory {
161       fcInfinity,
162       fcNaN,
163       fcNormal,
164       fcZero
165     };
166
167     /* Constructors.  */
168     APFloat(const fltSemantics &, const char *);
169     APFloat(const fltSemantics &, integerPart);
170     APFloat(const fltSemantics &, fltCategory, bool negative);
171     explicit APFloat(double d);
172     explicit APFloat(float f);
173     explicit APFloat(const APInt &);
174     APFloat(const APFloat &);
175     ~APFloat();
176
177     /* Arithmetic.  */
178     opStatus add(const APFloat &, roundingMode);
179     opStatus subtract(const APFloat &, roundingMode);
180     opStatus multiply(const APFloat &, roundingMode);
181     opStatus divide(const APFloat &, roundingMode);
182     opStatus mod(const APFloat &, roundingMode);
183     void copySign(const APFloat &);
184     opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
185     void changeSign();    // neg
186     void clearSign();     // abs
187
188     /* Conversions.  */
189     opStatus convert(const fltSemantics &, roundingMode);
190     opStatus convertToInteger(integerPart *, unsigned int, bool,
191                               roundingMode) const;
192     opStatus convertFromInteger(const integerPart *, unsigned int, bool,
193                                 roundingMode);
194     opStatus convertFromString(const char *, roundingMode);
195     APInt convertToAPInt() const;
196     double convertToDouble() const;
197     float convertToFloat() const;
198
199     /* The definition of equality is not straightforward for floating point,
200        so we won't use operator==.  Use one of the following, or write
201        whatever it is you really mean. */
202     // bool operator==(const APFloat &) const;     // DO NOT IMPLEMENT
203
204     /* IEEE comparison with another floating point number (NaNs
205        compare unordered, 0==-0). */
206     cmpResult compare(const APFloat &) const;
207
208     /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */
209     bool bitwiseIsEqual(const APFloat &) const;
210
211     /* Simple queries.  */
212     fltCategory getCategory() const { return category; }
213     const fltSemantics &getSemantics() const { return *semantics; }
214     bool isZero() const { return category == fcZero; }
215     bool isNonZero() const { return category != fcZero; }
216     bool isNegative() const { return sign; }
217     bool isPosZero() const { return isZero() && !isNegative(); }
218     bool isNegZero() const { return isZero() && isNegative(); }
219
220     APFloat& operator=(const APFloat &);
221
222     /* Return an arbitrary integer value usable for hashing. */
223     uint32_t getHashValue() const;
224
225   private:
226
227     /* Trivial queries.  */
228     integerPart *significandParts();
229     const integerPart *significandParts() const;
230     unsigned int partCount() const;
231
232     /* Significand operations.  */
233     integerPart addSignificand(const APFloat &);
234     integerPart subtractSignificand(const APFloat &, integerPart);
235     lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
236     lostFraction multiplySignificand(const APFloat &, const APFloat *);
237     lostFraction divideSignificand(const APFloat &);
238     void incrementSignificand();
239     void initialize(const fltSemantics *);
240     void shiftSignificandLeft(unsigned int);
241     lostFraction shiftSignificandRight(unsigned int);
242     unsigned int significandLSB() const;
243     unsigned int significandMSB() const;
244     void zeroSignificand();
245
246     /* Arithmetic on special values.  */
247     opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
248     opStatus divideSpecials(const APFloat &);
249     opStatus multiplySpecials(const APFloat &);
250
251     /* Miscellany.  */
252     opStatus normalize(roundingMode, lostFraction);
253     opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
254     cmpResult compareAbsoluteValue(const APFloat &) const;
255     opStatus handleOverflow(roundingMode);
256     bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
257     opStatus convertFromUnsignedInteger(integerPart *, unsigned int,
258                                         roundingMode);
259     lostFraction combineLostFractions(lostFraction, lostFraction);
260     opStatus convertFromHexadecimalString(const char *, roundingMode);
261     APInt convertFloatAPFloatToAPInt() const;
262     APInt convertDoubleAPFloatToAPInt() const;
263     APInt convertF80LongDoubleAPFloatToAPInt() const;
264     void initFromAPInt(const APInt& api);
265     void initFromFloatAPInt(const APInt& api);
266     void initFromDoubleAPInt(const APInt& api);
267     void initFromF80LongDoubleAPInt(const APInt& api);
268
269     void assign(const APFloat &);
270     void copySignificand(const APFloat &);
271     void freeSignificand();
272
273     /* What kind of semantics does this value obey?  */
274     const fltSemantics *semantics;
275
276     /* Significand - the fraction with an explicit integer bit.  Must be
277        at least one bit wider than the target precision.  */
278     union Significand
279     {
280       integerPart part;
281       integerPart *parts;
282     } significand;
283
284     /* The exponent - a signed number.  */
285     exponent_t exponent;
286
287     /* What kind of floating point number this is.  */
288     /* Only 2 bits are required, but VisualStudio incorrectly sign extends
289        it.  Using the extra bit keeps it from failing under VisualStudio */
290     fltCategory category: 3;
291
292     /* The sign bit of this number.  */
293     unsigned int sign: 1;
294   };
295 } /* namespace llvm */
296
297 #endif /* LLVM_FLOAT_H */