add convenience 'constructors'
[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 is distributed under the University of Illinois Open Source
6 // 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.  It uses 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, but 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.
34
35     Four formats are built-in: IEEE single precision, double
36     precision, quadruple precision, and x87 80-bit extended double
37     (when operating with full extended precision).  Adding a new
38     format that obeys IEEE semantics only requires adding two lines of
39     code: a declaration and definition of the format.
40
41     All operations return the status of that operation as an exception
42     bit-mask, so multiple operations can be done consecutively with
43     their results or-ed together.  The returned status can be useful
44     for compiler diagnostics; e.g., inexact, underflow and overflow
45     can be easily diagnosed on constant folding, and compiler
46     optimizers can determine what exceptions would be raised by
47     folding operations and optimize, or perhaps not optimize,
48     accordingly.
49
50     At present, underflow tininess is detected after rounding; it
51     should be straight forward to add support for the before-rounding
52     case too.
53
54     The library reads hexadecimal floating point numbers as per C99,
55     and correctly rounds if necessary according to the specified
56     rounding mode.  Syntax is required to have been validated by the
57     caller.  It also converts floating point numbers to hexadecimal
58     text as per the C99 %a and %A conversions.  The output precision
59     (or alternatively the natural minimal precision) can be specified;
60     if the requested precision is less than the natural precision the
61     output is correctly rounded for the specified rounding mode.
62
63     It also reads decimal floating point numbers and correctly rounds
64     according to the specified rounding mode.
65
66     Conversion to decimal text is not currently implemented.
67
68     Non-zero finite numbers are represented internally as a sign bit,
69     a 16-bit signed exponent, and the significand as an array of
70     integer parts.  After normalization of a number of precision P the
71     exponent is within the range of the format, and if the number is
72     not denormal the P-th bit of the significand is set as an explicit
73     integer bit.  For denormals the most significant bit is shifted
74     right so that the exponent is maintained at the format's minimum,
75     so that the smallest denormal has just the least significant bit
76     of the significand set.  The sign of zeroes and infinities is
77     significant; the exponent and significand of such numbers is not
78     stored, but has a known implicit (deterministic) value: 0 for the
79     significands, 0 for zero exponent, all 1 bits for infinity
80     exponent.  For NaNs the sign and significand are deterministic,
81     although not really meaningful, and preserved in non-conversion
82     operations.  The exponent is implicitly all 1 bits.
83
84     TODO
85     ====
86
87     Some features that may or may not be worth adding:
88
89     Binary to decimal conversion (hard).
90
91     Optional ability to detect underflow tininess before rounding.
92
93     New formats: x87 in single and double precision mode (IEEE apart
94     from extended exponent range) (hard).
95
96     New operations: sqrt, IEEE remainder, C90 fmod, nextafter,
97     nexttoward.
98 */
99
100 #ifndef LLVM_FLOAT_H
101 #define LLVM_FLOAT_H
102
103 // APInt contains static functions implementing bignum arithmetic.
104 #include "llvm/ADT/APInt.h"
105
106 namespace llvm {
107
108   /* Exponents are stored as signed numbers.  */
109   typedef signed short exponent_t;
110
111   struct fltSemantics;
112
113   /* When bits of a floating point number are truncated, this enum is
114      used to indicate what fraction of the LSB those bits represented.
115      It essentially combines the roles of guard and sticky bits.  */
116   enum lostFraction {           // Example of truncated bits:
117     lfExactlyZero,              // 000000
118     lfLessThanHalf,             // 0xxxxx  x's not all zero
119     lfExactlyHalf,              // 100000
120     lfMoreThanHalf              // 1xxxxx  x's not all zero
121   };
122
123   class APFloat {
124   public:
125
126     /* We support the following floating point semantics.  */
127     static const fltSemantics IEEEsingle;
128     static const fltSemantics IEEEdouble;
129     static const fltSemantics IEEEquad;
130     static const fltSemantics PPCDoubleDouble;
131     static const fltSemantics x87DoubleExtended;
132     /* And this psuedo, used to construct APFloats that cannot
133        conflict with anything real. */
134     static const fltSemantics Bogus;
135
136     static unsigned int semanticsPrecision(const fltSemantics &);
137
138     /* Floating point numbers have a four-state comparison relation.  */
139     enum cmpResult {
140       cmpLessThan,
141       cmpEqual,
142       cmpGreaterThan,
143       cmpUnordered
144     };
145
146     /* IEEE-754R gives five rounding modes.  */
147     enum roundingMode {
148       rmNearestTiesToEven,
149       rmTowardPositive,
150       rmTowardNegative,
151       rmTowardZero,
152       rmNearestTiesToAway
153     };
154
155     // Operation status.  opUnderflow or opOverflow are always returned
156     // or-ed with opInexact.
157     enum opStatus {
158       opOK          = 0x00,
159       opInvalidOp   = 0x01,
160       opDivByZero   = 0x02,
161       opOverflow    = 0x04,
162       opUnderflow   = 0x08,
163       opInexact     = 0x10
164     };
165
166     // Category of internally-represented number.
167     enum fltCategory {
168       fcInfinity,
169       fcNaN,
170       fcNormal,
171       fcZero
172     };
173
174     // Constructors.
175     APFloat(const fltSemantics &, const char *);
176     APFloat(const fltSemantics &, integerPart);
177     APFloat(const fltSemantics &, fltCategory, bool negative);
178     explicit APFloat(double d);
179     explicit APFloat(float f);
180     explicit APFloat(const APInt &, bool isIEEE = false);
181     APFloat(const APFloat &);
182     ~APFloat();
183
184     // Convenience "constructors"
185     static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
186       return APFloat(Sem, fcZero, Negative);
187     }
188     static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
189       return APFloat(Sem, fcInfinity, Negative);
190     }
191     static APFloat getNaN(const fltSemantics &Sem, bool Negative = false) {
192       return APFloat(Sem, fcNaN, Negative);
193     }
194     
195     /// Profile - Used to insert APFloat objects, or objects that contain
196     ///  APFloat objects, into FoldingSets.
197     void Profile(FoldingSetNodeID& NID) const;
198     
199     /// @brief Used by the Bitcode serializer to emit APInts to Bitcode.
200     void Emit(Serializer& S) const;
201     
202     /// @brief Used by the Bitcode deserializer to deserialize APInts.
203     static APFloat ReadVal(Deserializer& D);
204
205     /* Arithmetic.  */
206     opStatus add(const APFloat &, roundingMode);
207     opStatus subtract(const APFloat &, roundingMode);
208     opStatus multiply(const APFloat &, roundingMode);
209     opStatus divide(const APFloat &, roundingMode);
210     opStatus mod(const APFloat &, roundingMode);
211     opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
212
213     /* Sign operations.  */
214     void changeSign();
215     void clearSign();
216     void copySign(const APFloat &);
217
218     /* Conversions.  */
219     opStatus convert(const fltSemantics &, roundingMode);
220     opStatus convertToInteger(integerPart *, unsigned int, bool,
221                               roundingMode) const;
222     opStatus convertFromAPInt(const APInt &,
223                               bool, roundingMode);
224     opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int,
225                                             bool, roundingMode);
226     opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int,
227                                             bool, roundingMode);
228     opStatus convertFromString(const char *, roundingMode);
229     APInt convertToAPInt() const;
230     double convertToDouble() const;
231     float convertToFloat() const;
232
233     /* The definition of equality is not straightforward for floating point,
234        so we won't use operator==.  Use one of the following, or write
235        whatever it is you really mean. */
236     // bool operator==(const APFloat &) const;     // DO NOT IMPLEMENT
237
238     /* IEEE comparison with another floating point number (NaNs
239        compare unordered, 0==-0). */
240     cmpResult compare(const APFloat &) const;
241
242     /* Write out a hexadecimal representation of the floating point
243        value to DST, which must be of sufficient size, in the C99 form
244        [-]0xh.hhhhp[+-]d.  Return the number of characters written,
245        excluding the terminating NUL.  */
246     unsigned int convertToHexString(char *dst, unsigned int hexDigits,
247                                     bool upperCase, roundingMode) const;
248
249     /* Bitwise comparison for equality (QNaNs compare equal, 0!=-0). */
250     bool bitwiseIsEqual(const APFloat &) const;
251
252     /* Simple queries.  */
253     fltCategory getCategory() const { return category; }
254     const fltSemantics &getSemantics() const { return *semantics; }
255     bool isZero() const { return category == fcZero; }
256     bool isNonZero() const { return category != fcZero; }
257     bool isNaN() const { return category == fcNaN; }
258     bool isInfinity() const { return category == fcInfinity; }
259     bool isNegative() const { return sign; }
260     bool isPosZero() const { return isZero() && !isNegative(); }
261     bool isNegZero() const { return isZero() && isNegative(); }
262
263     APFloat& operator=(const APFloat &);
264
265     /* Return an arbitrary integer value usable for hashing. */
266     uint32_t getHashValue() const;
267
268   private:
269
270     /* Trivial queries.  */
271     integerPart *significandParts();
272     const integerPart *significandParts() const;
273     unsigned int partCount() const;
274
275     /* Significand operations.  */
276     integerPart addSignificand(const APFloat &);
277     integerPart subtractSignificand(const APFloat &, integerPart);
278     lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
279     lostFraction multiplySignificand(const APFloat &, const APFloat *);
280     lostFraction divideSignificand(const APFloat &);
281     void incrementSignificand();
282     void initialize(const fltSemantics *);
283     void shiftSignificandLeft(unsigned int);
284     lostFraction shiftSignificandRight(unsigned int);
285     unsigned int significandLSB() const;
286     unsigned int significandMSB() const;
287     void zeroSignificand();
288
289     /* Arithmetic on special values.  */
290     opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
291     opStatus divideSpecials(const APFloat &);
292     opStatus multiplySpecials(const APFloat &);
293
294     /* Miscellany.  */
295     void makeNaN(void);
296     opStatus normalize(roundingMode, lostFraction);
297     opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
298     cmpResult compareAbsoluteValue(const APFloat &) const;
299     opStatus handleOverflow(roundingMode);
300     bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
301     opStatus convertToSignExtendedInteger(integerPart *, unsigned int, bool,
302                                           roundingMode) const;
303     opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
304                                       roundingMode);
305     opStatus convertFromHexadecimalString(const char *, roundingMode);
306     opStatus convertFromDecimalString (const char *, roundingMode);
307     char *convertNormalToHexString(char *, unsigned int, bool,
308                                    roundingMode) const;
309     opStatus roundSignificandWithExponent(const integerPart *, unsigned int,
310                                           int, roundingMode);
311
312     APInt convertFloatAPFloatToAPInt() const;
313     APInt convertDoubleAPFloatToAPInt() const;
314     APInt convertF80LongDoubleAPFloatToAPInt() const;
315     APInt convertPPCDoubleDoubleAPFloatToAPInt() const;
316     void initFromAPInt(const APInt& api, bool isIEEE = false);
317     void initFromFloatAPInt(const APInt& api);
318     void initFromDoubleAPInt(const APInt& api);
319     void initFromF80LongDoubleAPInt(const APInt& api);
320     void initFromPPCDoubleDoubleAPInt(const APInt& api);
321
322     void assign(const APFloat &);
323     void copySignificand(const APFloat &);
324     void freeSignificand();
325
326     /* What kind of semantics does this value obey?  */
327     const fltSemantics *semantics;
328
329     /* Significand - the fraction with an explicit integer bit.  Must be
330        at least one bit wider than the target precision.  */
331     union Significand
332     {
333       integerPart part;
334       integerPart *parts;
335     } significand;
336
337     /* The exponent - a signed number.  */
338     exponent_t exponent;
339
340     /* What kind of floating point number this is.  */
341     /* Only 2 bits are required, but VisualStudio incorrectly sign extends
342        it.  Using the extra bit keeps it from failing under VisualStudio */
343     fltCategory category: 3;
344
345     /* The sign bit of this number.  */
346     unsigned int sign: 1;
347
348     /* For PPCDoubleDouble, we have a second exponent and sign (the second
349        significand is appended to the first one, although it would be wrong to
350        regard these as a single number for arithmetic purposes).  These fields
351        are not meaningful for any other type. */
352     exponent_t exponent2 : 11;
353     unsigned int sign2: 1;
354   };
355 } /* namespace llvm */
356
357 #endif /* LLVM_FLOAT_H */