initial checkin of Neil's APFloat work.
[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
67     indeterminate and meaningless.  For QNaNs the sign bit, as well as
68     the exponent and significand are indeterminate and meaningless.
69
70     TODO
71     ====
72
73     Some features that may or may not be worth adding:
74
75     Conversions to and from decimal strings (hard).
76
77     Conversions to hexadecimal string.
78
79     Read and write IEEE-format in-memory representations.
80
81     Optional ability to detect underflow tininess before rounding.
82
83     New formats: x87 in single and double precision mode (IEEE apart
84     from extended exponent range) and IBM two-double extended
85     precision (hard).
86
87     New operations: sqrt, copysign, nextafter, nexttoward.
88 */
89
90 #ifndef LLVM_FLOAT_H
91 #define LLVM_FLOAT_H
92
93 // APInt contains static functions implementing bignum arithmetic.
94 #include "llvm/ADT/APInt.h"
95
96 namespace llvm {
97
98   /* Exponents are stored as signed numbers.  */
99   typedef signed short exponent_t;
100
101   struct fltSemantics;
102
103   /* When bits of a floating point number are truncated, this enum is
104      used to indicate what fraction of the LSB those bits represented.
105      It essentially combines the roles of guard and sticky bits.  */
106   enum lostFraction {           // Example of truncated bits:
107     lfExactlyZero,              // 000000
108     lfLessThanHalf,             // 0xxxxx  x's not all zero
109     lfExactlyHalf,              // 100000
110     lfMoreThanHalf              // 1xxxxx  x's not all zero
111   };
112
113   class APFloat {
114   public:
115
116     /* We support the following floating point semantics.  */
117     static const fltSemantics IEEEsingle;
118     static const fltSemantics IEEEdouble;
119     static const fltSemantics IEEEquad;
120     static const fltSemantics x87DoubleExtended;
121
122     static unsigned int semanticsPrecision(const fltSemantics &);
123
124     /* Floating point numbers have a four-state comparison relation.  */
125     enum cmpResult {
126       cmpLessThan,
127       cmpEqual,
128       cmpGreaterThan,
129       cmpUnordered
130     };
131
132     /* IEEE-754R gives five rounding modes.  */
133     enum roundingMode {
134       rmNearestTiesToEven,
135       rmTowardPositive,
136       rmTowardNegative,
137       rmTowardZero,
138       rmNearestTiesToAway
139     };
140
141     /* Operation status.  opUnderflow or opOverflow are always returned
142        or-ed with opInexact.  */
143     enum opStatus {
144       opOK          = 0x00,
145       opInvalidOp   = 0x01,
146       opDivByZero   = 0x02,
147       opOverflow    = 0x04,
148       opUnderflow   = 0x08,
149       opInexact     = 0x10
150     };
151
152     /* Category of internally-represented number.  */
153     enum fltCategory {
154       fcInfinity,
155       fcQNaN,
156       fcNormal,
157       fcZero
158     };
159
160     /* Constructors.  */
161     APFloat(const fltSemantics &, const char *);
162     APFloat(const fltSemantics &, integerPart);
163     APFloat(const fltSemantics &, fltCategory, bool negative);
164     APFloat(const APFloat &);
165     ~APFloat();
166
167     /* Arithmetic.  */
168     opStatus add(const APFloat &, roundingMode);
169     opStatus subtract(const APFloat &, roundingMode);
170     opStatus multiply(const APFloat &, roundingMode);
171     opStatus divide(const APFloat &, roundingMode);
172     opStatus fusedMultiplyAdd(const APFloat &, const APFloat &, roundingMode);
173     void changeSign();
174
175     /* Conversions.  */
176     opStatus convert(const fltSemantics &, roundingMode);
177     opStatus convertToInteger(integerPart *, unsigned int, bool,
178                               roundingMode) const;
179     opStatus convertFromInteger(const integerPart *, unsigned int, bool,
180                                 roundingMode);
181     opStatus convertFromString(const char *, roundingMode);
182
183     /* Comparison with another floating point number.  */
184     cmpResult compare(const APFloat &) const;
185
186     /* Simple queries.  */
187     fltCategory getCategory() const { return category; }
188     const fltSemantics &getSemantics() const { return *semantics; }
189     bool isZero() const { return category == fcZero; }
190     bool isNonZero() const { return category != fcZero; }
191     bool isNegative() const { return sign; }
192
193     APFloat& operator=(const APFloat &);
194
195   private:
196
197     /* Trivial queries.  */
198     integerPart *significandParts();
199     const integerPart *significandParts() const;
200     unsigned int partCount() const;
201
202     /* Significand operations.  */
203     integerPart addSignificand(const APFloat &);
204     integerPart subtractSignificand(const APFloat &, integerPart);
205     lostFraction addOrSubtractSignificand(const APFloat &, bool subtract);
206     lostFraction multiplySignificand(const APFloat &, const APFloat *);
207     lostFraction divideSignificand(const APFloat &);
208     void incrementSignificand();
209     void initialize(const fltSemantics *);
210     void shiftSignificandLeft(unsigned int);
211     lostFraction shiftSignificandRight(unsigned int);
212     unsigned int significandLSB() const;
213     unsigned int significandMSB() const;
214     void zeroSignificand();
215
216     /* Arithmetic on special values.  */
217     opStatus addOrSubtractSpecials(const APFloat &, bool subtract);
218     opStatus divideSpecials(const APFloat &);
219     opStatus multiplySpecials(const APFloat &);
220
221     /* Miscellany.  */
222     opStatus normalize(roundingMode, lostFraction);
223     opStatus addOrSubtract(const APFloat &, roundingMode, bool subtract);
224     cmpResult compareAbsoluteValue(const APFloat &) const;
225     opStatus handleOverflow(roundingMode);
226     bool roundAwayFromZero(roundingMode, lostFraction);
227     opStatus convertFromUnsignedInteger(integerPart *, unsigned int,
228                                         roundingMode);
229     lostFraction combineLostFractions(lostFraction, lostFraction);
230     opStatus convertFromHexadecimalString(const char *, roundingMode);
231
232     void assign(const APFloat &);
233     void copySignificand(const APFloat &);
234     void freeSignificand();
235
236     /* What kind of semantics does this value obey?  */
237     const fltSemantics *semantics;
238
239     /* Significand - the fraction with an explicit integer bit.  Must be
240        at least one bit wider than the target precision.  */
241     union Significand
242     {
243       integerPart part;
244       integerPart *parts;
245     } significand;
246
247     /* The exponent - a signed number.  */
248     exponent_t exponent;
249
250     /* What kind of floating point number this is.  */
251     fltCategory category: 2;
252
253     /* The sign bit of this number.  */
254     unsigned int sign: 1;
255   };
256 } /* namespace llvm */
257
258 #endif /* LLVM_FLOAT_H */