APFloat.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951
  1. //===-- APFloat.cpp - Implement APFloat class -----------------------------===//
  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 implements a class to represent arbitrary precision floating
  11. // point values and provide a variety of arithmetic operations on them.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/FoldingSet.h"
  16. #include "llvm/Support/ErrorHandling.h"
  17. #include "llvm/Support/MathExtras.h"
  18. #include <cstring>
  19. using namespace llvm;
  20. #define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
  21. /* Assumed in hexadecimal significand parsing, and conversion to
  22. hexadecimal strings. */
  23. #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
  24. COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
  25. namespace llvm {
  26. /* Represents floating point arithmetic semantics. */
  27. struct fltSemantics {
  28. /* The largest E such that 2^E is representable; this matches the
  29. definition of IEEE 754. */
  30. exponent_t maxExponent;
  31. /* The smallest E such that 2^E is a normalized number; this
  32. matches the definition of IEEE 754. */
  33. exponent_t minExponent;
  34. /* Number of bits in the significand. This includes the integer
  35. bit. */
  36. unsigned int precision;
  37. /* True if arithmetic is supported. */
  38. unsigned int arithmeticOK;
  39. };
  40. const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
  41. const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
  42. const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
  43. const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
  44. const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
  45. // The PowerPC format consists of two doubles. It does not map cleanly
  46. // onto the usual format above. For now only storage of constants of
  47. // this type is supported, no arithmetic.
  48. const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
  49. /* A tight upper bound on number of parts required to hold the value
  50. pow(5, power) is
  51. power * 815 / (351 * integerPartWidth) + 1
  52. However, whilst the result may require only this many parts,
  53. because we are multiplying two values to get it, the
  54. multiplication may require an extra part with the excess part
  55. being zero (consider the trivial case of 1 * 1, tcFullMultiply
  56. requires two parts to hold the single-part result). So we add an
  57. extra one to guarantee enough space whilst multiplying. */
  58. const unsigned int maxExponent = 16383;
  59. const unsigned int maxPrecision = 113;
  60. const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
  61. const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
  62. / (351 * integerPartWidth));
  63. }
  64. /* A bunch of private, handy routines. */
  65. static inline unsigned int
  66. partCountForBits(unsigned int bits)
  67. {
  68. return ((bits) + integerPartWidth - 1) / integerPartWidth;
  69. }
  70. /* Returns 0U-9U. Return values >= 10U are not digits. */
  71. static inline unsigned int
  72. decDigitValue(unsigned int c)
  73. {
  74. return c - '0';
  75. }
  76. static unsigned int
  77. hexDigitValue(unsigned int c)
  78. {
  79. unsigned int r;
  80. r = c - '0';
  81. if(r <= 9)
  82. return r;
  83. r = c - 'A';
  84. if(r <= 5)
  85. return r + 10;
  86. r = c - 'a';
  87. if(r <= 5)
  88. return r + 10;
  89. return -1U;
  90. }
  91. static inline void
  92. assertArithmeticOK(const llvm::fltSemantics &semantics) {
  93. assert(semantics.arithmeticOK
  94. && "Compile-time arithmetic does not support these semantics");
  95. }
  96. /* Return the value of a decimal exponent of the form
  97. [+-]ddddddd.
  98. If the exponent overflows, returns a large exponent with the
  99. appropriate sign. */
  100. static int
  101. readExponent(const char *p)
  102. {
  103. bool isNegative;
  104. unsigned int absExponent;
  105. const unsigned int overlargeExponent = 24000; /* FIXME. */
  106. isNegative = (*p == '-');
  107. if (*p == '-' || *p == '+')
  108. p++;
  109. absExponent = decDigitValue(*p++);
  110. assert (absExponent < 10U);
  111. for (;;) {
  112. unsigned int value;
  113. value = decDigitValue(*p);
  114. if (value >= 10U)
  115. break;
  116. p++;
  117. value += absExponent * 10;
  118. if (absExponent >= overlargeExponent) {
  119. absExponent = overlargeExponent;
  120. break;
  121. }
  122. absExponent = value;
  123. }
  124. if (isNegative)
  125. return -(int) absExponent;
  126. else
  127. return (int) absExponent;
  128. }
  129. /* This is ugly and needs cleaning up, but I don't immediately see
  130. how whilst remaining safe. */
  131. static int
  132. totalExponent(const char *p, int exponentAdjustment)
  133. {
  134. int unsignedExponent;
  135. bool negative, overflow;
  136. int exponent;
  137. /* Move past the exponent letter and sign to the digits. */
  138. p++;
  139. negative = *p == '-';
  140. if(*p == '-' || *p == '+')
  141. p++;
  142. unsignedExponent = 0;
  143. overflow = false;
  144. for(;;) {
  145. unsigned int value;
  146. value = decDigitValue(*p);
  147. if(value >= 10U)
  148. break;
  149. p++;
  150. unsignedExponent = unsignedExponent * 10 + value;
  151. if(unsignedExponent > 65535)
  152. overflow = true;
  153. }
  154. if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
  155. overflow = true;
  156. if(!overflow) {
  157. exponent = unsignedExponent;
  158. if(negative)
  159. exponent = -exponent;
  160. exponent += exponentAdjustment;
  161. if(exponent > 65535 || exponent < -65536)
  162. overflow = true;
  163. }
  164. if(overflow)
  165. exponent = negative ? -65536: 65535;
  166. return exponent;
  167. }
  168. static const char *
  169. skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
  170. {
  171. *dot = 0;
  172. while(*p == '0')
  173. p++;
  174. if(*p == '.') {
  175. *dot = p++;
  176. while(*p == '0')
  177. p++;
  178. }
  179. return p;
  180. }
  181. /* Given a normal decimal floating point number of the form
  182. dddd.dddd[eE][+-]ddd
  183. where the decimal point and exponent are optional, fill out the
  184. structure D. Exponent is appropriate if the significand is
  185. treated as an integer, and normalizedExponent if the significand
  186. is taken to have the decimal point after a single leading
  187. non-zero digit.
  188. If the value is zero, V->firstSigDigit points to a non-digit, and
  189. the return exponent is zero.
  190. */
  191. struct decimalInfo {
  192. const char *firstSigDigit;
  193. const char *lastSigDigit;
  194. int exponent;
  195. int normalizedExponent;
  196. };
  197. static void
  198. interpretDecimal(const char *p, decimalInfo *D)
  199. {
  200. const char *dot;
  201. p = skipLeadingZeroesAndAnyDot (p, &dot);
  202. D->firstSigDigit = p;
  203. D->exponent = 0;
  204. D->normalizedExponent = 0;
  205. for (;;) {
  206. if (*p == '.') {
  207. assert(dot == 0);
  208. dot = p++;
  209. }
  210. if (decDigitValue(*p) >= 10U)
  211. break;
  212. p++;
  213. }
  214. /* If number is all zerooes accept any exponent. */
  215. if (p != D->firstSigDigit) {
  216. if (*p == 'e' || *p == 'E')
  217. D->exponent = readExponent(p + 1);
  218. /* Implied decimal point? */
  219. if (!dot)
  220. dot = p;
  221. /* Drop insignificant trailing zeroes. */
  222. do
  223. do
  224. p--;
  225. while (*p == '0');
  226. while (*p == '.');
  227. /* Adjust the exponents for any decimal point. */
  228. D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
  229. D->normalizedExponent = (D->exponent +
  230. static_cast<exponent_t>((p - D->firstSigDigit)
  231. - (dot > D->firstSigDigit && dot < p)));
  232. }
  233. D->lastSigDigit = p;
  234. }
  235. /* Return the trailing fraction of a hexadecimal number.
  236. DIGITVALUE is the first hex digit of the fraction, P points to
  237. the next digit. */
  238. static lostFraction
  239. trailingHexadecimalFraction(const char *p, unsigned int digitValue)
  240. {
  241. unsigned int hexDigit;
  242. /* If the first trailing digit isn't 0 or 8 we can work out the
  243. fraction immediately. */
  244. if(digitValue > 8)
  245. return lfMoreThanHalf;
  246. else if(digitValue < 8 && digitValue > 0)
  247. return lfLessThanHalf;
  248. /* Otherwise we need to find the first non-zero digit. */
  249. while(*p == '0')
  250. p++;
  251. hexDigit = hexDigitValue(*p);
  252. /* If we ran off the end it is exactly zero or one-half, otherwise
  253. a little more. */
  254. if(hexDigit == -1U)
  255. return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
  256. else
  257. return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
  258. }
  259. /* Return the fraction lost were a bignum truncated losing the least
  260. significant BITS bits. */
  261. static lostFraction
  262. lostFractionThroughTruncation(const integerPart *parts,
  263. unsigned int partCount,
  264. unsigned int bits)
  265. {
  266. unsigned int lsb;
  267. lsb = APInt::tcLSB(parts, partCount);
  268. /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
  269. if(bits <= lsb)
  270. return lfExactlyZero;
  271. if(bits == lsb + 1)
  272. return lfExactlyHalf;
  273. if(bits <= partCount * integerPartWidth
  274. && APInt::tcExtractBit(parts, bits - 1))
  275. return lfMoreThanHalf;
  276. return lfLessThanHalf;
  277. }
  278. /* Shift DST right BITS bits noting lost fraction. */
  279. static lostFraction
  280. shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
  281. {
  282. lostFraction lost_fraction;
  283. lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
  284. APInt::tcShiftRight(dst, parts, bits);
  285. return lost_fraction;
  286. }
  287. /* Combine the effect of two lost fractions. */
  288. static lostFraction
  289. combineLostFractions(lostFraction moreSignificant,
  290. lostFraction lessSignificant)
  291. {
  292. if(lessSignificant != lfExactlyZero) {
  293. if(moreSignificant == lfExactlyZero)
  294. moreSignificant = lfLessThanHalf;
  295. else if(moreSignificant == lfExactlyHalf)
  296. moreSignificant = lfMoreThanHalf;
  297. }
  298. return moreSignificant;
  299. }
  300. /* The error from the true value, in half-ulps, on multiplying two
  301. floating point numbers, which differ from the value they
  302. approximate by at most HUE1 and HUE2 half-ulps, is strictly less
  303. than the returned value.
  304. See "How to Read Floating Point Numbers Accurately" by William D
  305. Clinger. */
  306. static unsigned int
  307. HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
  308. {
  309. assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
  310. if (HUerr1 + HUerr2 == 0)
  311. return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
  312. else
  313. return inexactMultiply + 2 * (HUerr1 + HUerr2);
  314. }
  315. /* The number of ulps from the boundary (zero, or half if ISNEAREST)
  316. when the least significant BITS are truncated. BITS cannot be
  317. zero. */
  318. static integerPart
  319. ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
  320. {
  321. unsigned int count, partBits;
  322. integerPart part, boundary;
  323. assert (bits != 0);
  324. bits--;
  325. count = bits / integerPartWidth;
  326. partBits = bits % integerPartWidth + 1;
  327. part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
  328. if (isNearest)
  329. boundary = (integerPart) 1 << (partBits - 1);
  330. else
  331. boundary = 0;
  332. if (count == 0) {
  333. if (part - boundary <= boundary - part)
  334. return part - boundary;
  335. else
  336. return boundary - part;
  337. }
  338. if (part == boundary) {
  339. while (--count)
  340. if (parts[count])
  341. return ~(integerPart) 0; /* A lot. */
  342. return parts[0];
  343. } else if (part == boundary - 1) {
  344. while (--count)
  345. if (~parts[count])
  346. return ~(integerPart) 0; /* A lot. */
  347. return -parts[0];
  348. }
  349. return ~(integerPart) 0; /* A lot. */
  350. }
  351. /* Place pow(5, power) in DST, and return the number of parts used.
  352. DST must be at least one part larger than size of the answer. */
  353. static unsigned int
  354. powerOf5(integerPart *dst, unsigned int power)
  355. {
  356. static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
  357. 15625, 78125 };
  358. integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
  359. pow5s[0] = 78125 * 5;
  360. unsigned int partsCount[16] = { 1 };
  361. integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
  362. unsigned int result;
  363. assert(power <= maxExponent);
  364. p1 = dst;
  365. p2 = scratch;
  366. *p1 = firstEightPowers[power & 7];
  367. power >>= 3;
  368. result = 1;
  369. pow5 = pow5s;
  370. for (unsigned int n = 0; power; power >>= 1, n++) {
  371. unsigned int pc;
  372. pc = partsCount[n];
  373. /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
  374. if (pc == 0) {
  375. pc = partsCount[n - 1];
  376. APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
  377. pc *= 2;
  378. if (pow5[pc - 1] == 0)
  379. pc--;
  380. partsCount[n] = pc;
  381. }
  382. if (power & 1) {
  383. integerPart *tmp;
  384. APInt::tcFullMultiply(p2, p1, pow5, result, pc);
  385. result += pc;
  386. if (p2[result - 1] == 0)
  387. result--;
  388. /* Now result is in p1 with partsCount parts and p2 is scratch
  389. space. */
  390. tmp = p1, p1 = p2, p2 = tmp;
  391. }
  392. pow5 += pc;
  393. }
  394. if (p1 != dst)
  395. APInt::tcAssign(dst, p1, result);
  396. return result;
  397. }
  398. /* Zero at the end to avoid modular arithmetic when adding one; used
  399. when rounding up during hexadecimal output. */
  400. static const char hexDigitsLower[] = "0123456789abcdef0";
  401. static const char hexDigitsUpper[] = "0123456789ABCDEF0";
  402. static const char infinityL[] = "infinity";
  403. static const char infinityU[] = "INFINITY";
  404. static const char NaNL[] = "nan";
  405. static const char NaNU[] = "NAN";
  406. /* Write out an integerPart in hexadecimal, starting with the most
  407. significant nibble. Write out exactly COUNT hexdigits, return
  408. COUNT. */
  409. static unsigned int
  410. partAsHex (char *dst, integerPart part, unsigned int count,
  411. const char *hexDigitChars)
  412. {
  413. unsigned int result = count;
  414. assert (count != 0 && count <= integerPartWidth / 4);
  415. part >>= (integerPartWidth - 4 * count);
  416. while (count--) {
  417. dst[count] = hexDigitChars[part & 0xf];
  418. part >>= 4;
  419. }
  420. return result;
  421. }
  422. /* Write out an unsigned decimal integer. */
  423. static char *
  424. writeUnsignedDecimal (char *dst, unsigned int n)
  425. {
  426. char buff[40], *p;
  427. p = buff;
  428. do
  429. *p++ = '0' + n % 10;
  430. while (n /= 10);
  431. do
  432. *dst++ = *--p;
  433. while (p != buff);
  434. return dst;
  435. }
  436. /* Write out a signed decimal integer. */
  437. static char *
  438. writeSignedDecimal (char *dst, int value)
  439. {
  440. if (value < 0) {
  441. *dst++ = '-';
  442. dst = writeUnsignedDecimal(dst, -(unsigned) value);
  443. } else
  444. dst = writeUnsignedDecimal(dst, value);
  445. return dst;
  446. }
  447. /* Constructors. */
  448. void
  449. APFloat::initialize(const fltSemantics *ourSemantics)
  450. {
  451. unsigned int count;
  452. semantics = ourSemantics;
  453. count = partCount();
  454. if(count > 1)
  455. significand.parts = new integerPart[count];
  456. }
  457. void
  458. APFloat::freeSignificand()
  459. {
  460. if(partCount() > 1)
  461. delete [] significand.parts;
  462. }
  463. void
  464. APFloat::assign(const APFloat &rhs)
  465. {
  466. assert(semantics == rhs.semantics);
  467. sign = rhs.sign;
  468. category = rhs.category;
  469. exponent = rhs.exponent;
  470. sign2 = rhs.sign2;
  471. exponent2 = rhs.exponent2;
  472. if(category == fcNormal || category == fcNaN)
  473. copySignificand(rhs);
  474. }
  475. void
  476. APFloat::copySignificand(const APFloat &rhs)
  477. {
  478. assert(category == fcNormal || category == fcNaN);
  479. assert(rhs.partCount() >= partCount());
  480. APInt::tcAssign(significandParts(), rhs.significandParts(),
  481. partCount());
  482. }
  483. /* Make this number a NaN, with an arbitrary but deterministic value
  484. for the significand. If double or longer, this is a signalling NaN,
  485. which may not be ideal. If float, this is QNaN(0). */
  486. void
  487. APFloat::makeNaN(unsigned type)
  488. {
  489. category = fcNaN;
  490. // FIXME: Add double and long double support for QNaN(0).
  491. if (semantics->precision == 24 && semantics->maxExponent == 127) {
  492. type |= 0x7fc00000U;
  493. type &= ~0x80000000U;
  494. } else
  495. type = ~0U;
  496. APInt::tcSet(significandParts(), type, partCount());
  497. }
  498. APFloat &
  499. APFloat::operator=(const APFloat &rhs)
  500. {
  501. if(this != &rhs) {
  502. if(semantics != rhs.semantics) {
  503. freeSignificand();
  504. initialize(rhs.semantics);
  505. }
  506. assign(rhs);
  507. }
  508. return *this;
  509. }
  510. bool
  511. APFloat::bitwiseIsEqual(const APFloat &rhs) const {
  512. if (this == &rhs)
  513. return true;
  514. if (semantics != rhs.semantics ||
  515. category != rhs.category ||
  516. sign != rhs.sign)
  517. return false;
  518. if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
  519. sign2 != rhs.sign2)
  520. return false;
  521. if (category==fcZero || category==fcInfinity)
  522. return true;
  523. else if (category==fcNormal && exponent!=rhs.exponent)
  524. return false;
  525. else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
  526. exponent2!=rhs.exponent2)
  527. return false;
  528. else {
  529. int i= partCount();
  530. const integerPart* p=significandParts();
  531. const integerPart* q=rhs.significandParts();
  532. for (; i>0; i--, p++, q++) {
  533. if (*p != *q)
  534. return false;
  535. }
  536. return true;
  537. }
  538. }
  539. APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
  540. {
  541. assertArithmeticOK(ourSemantics);
  542. initialize(&ourSemantics);
  543. sign = 0;
  544. zeroSignificand();
  545. exponent = ourSemantics.precision - 1;
  546. significandParts()[0] = value;
  547. normalize(rmNearestTiesToEven, lfExactlyZero);
  548. }
  549. APFloat::APFloat(const fltSemantics &ourSemantics,
  550. fltCategory ourCategory, bool negative, unsigned type)
  551. {
  552. assertArithmeticOK(ourSemantics);
  553. initialize(&ourSemantics);
  554. category = ourCategory;
  555. sign = negative;
  556. if (category == fcNormal)
  557. category = fcZero;
  558. else if (ourCategory == fcNaN)
  559. makeNaN(type);
  560. }
  561. APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
  562. {
  563. assertArithmeticOK(ourSemantics);
  564. initialize(&ourSemantics);
  565. convertFromString(text, rmNearestTiesToEven);
  566. }
  567. APFloat::APFloat(const APFloat &rhs)
  568. {
  569. initialize(rhs.semantics);
  570. assign(rhs);
  571. }
  572. APFloat::~APFloat()
  573. {
  574. freeSignificand();
  575. }
  576. // Profile - This method 'profiles' an APFloat for use with FoldingSet.
  577. void APFloat::Profile(FoldingSetNodeID& ID) const {
  578. ID.Add(bitcastToAPInt());
  579. }
  580. unsigned int
  581. APFloat::partCount() const
  582. {
  583. return partCountForBits(semantics->precision + 1);
  584. }
  585. unsigned int
  586. APFloat::semanticsPrecision(const fltSemantics &semantics)
  587. {
  588. return semantics.precision;
  589. }
  590. const integerPart *
  591. APFloat::significandParts() const
  592. {
  593. return const_cast<APFloat *>(this)->significandParts();
  594. }
  595. integerPart *
  596. APFloat::significandParts()
  597. {
  598. assert(category == fcNormal || category == fcNaN);
  599. if(partCount() > 1)
  600. return significand.parts;
  601. else
  602. return &significand.part;
  603. }
  604. void
  605. APFloat::zeroSignificand()
  606. {
  607. category = fcNormal;
  608. APInt::tcSet(significandParts(), 0, partCount());
  609. }
  610. /* Increment an fcNormal floating point number's significand. */
  611. void
  612. APFloat::incrementSignificand()
  613. {
  614. integerPart carry;
  615. carry = APInt::tcIncrement(significandParts(), partCount());
  616. /* Our callers should never cause us to overflow. */
  617. assert(carry == 0);
  618. }
  619. /* Add the significand of the RHS. Returns the carry flag. */
  620. integerPart
  621. APFloat::addSignificand(const APFloat &rhs)
  622. {
  623. integerPart *parts;
  624. parts = significandParts();
  625. assert(semantics == rhs.semantics);
  626. assert(exponent == rhs.exponent);
  627. return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
  628. }
  629. /* Subtract the significand of the RHS with a borrow flag. Returns
  630. the borrow flag. */
  631. integerPart
  632. APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
  633. {
  634. integerPart *parts;
  635. parts = significandParts();
  636. assert(semantics == rhs.semantics);
  637. assert(exponent == rhs.exponent);
  638. return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
  639. partCount());
  640. }
  641. /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
  642. on to the full-precision result of the multiplication. Returns the
  643. lost fraction. */
  644. lostFraction
  645. APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
  646. {
  647. unsigned int omsb; // One, not zero, based MSB.
  648. unsigned int partsCount, newPartsCount, precision;
  649. integerPart *lhsSignificand;
  650. integerPart scratch[4];
  651. integerPart *fullSignificand;
  652. lostFraction lost_fraction;
  653. bool ignored;
  654. assert(semantics == rhs.semantics);
  655. precision = semantics->precision;
  656. newPartsCount = partCountForBits(precision * 2);
  657. if(newPartsCount > 4)
  658. fullSignificand = new integerPart[newPartsCount];
  659. else
  660. fullSignificand = scratch;
  661. lhsSignificand = significandParts();
  662. partsCount = partCount();
  663. APInt::tcFullMultiply(fullSignificand, lhsSignificand,
  664. rhs.significandParts(), partsCount, partsCount);
  665. lost_fraction = lfExactlyZero;
  666. omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
  667. exponent += rhs.exponent;
  668. if(addend) {
  669. Significand savedSignificand = significand;
  670. const fltSemantics *savedSemantics = semantics;
  671. fltSemantics extendedSemantics;
  672. opStatus status;
  673. unsigned int extendedPrecision;
  674. /* Normalize our MSB. */
  675. extendedPrecision = precision + precision - 1;
  676. if(omsb != extendedPrecision)
  677. {
  678. APInt::tcShiftLeft(fullSignificand, newPartsCount,
  679. extendedPrecision - omsb);
  680. exponent -= extendedPrecision - omsb;
  681. }
  682. /* Create new semantics. */
  683. extendedSemantics = *semantics;
  684. extendedSemantics.precision = extendedPrecision;
  685. if(newPartsCount == 1)
  686. significand.part = fullSignificand[0];
  687. else
  688. significand.parts = fullSignificand;
  689. semantics = &extendedSemantics;
  690. APFloat extendedAddend(*addend);
  691. status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
  692. assert(status == opOK);
  693. lost_fraction = addOrSubtractSignificand(extendedAddend, false);
  694. /* Restore our state. */
  695. if(newPartsCount == 1)
  696. fullSignificand[0] = significand.part;
  697. significand = savedSignificand;
  698. semantics = savedSemantics;
  699. omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
  700. }
  701. exponent -= (precision - 1);
  702. if(omsb > precision) {
  703. unsigned int bits, significantParts;
  704. lostFraction lf;
  705. bits = omsb - precision;
  706. significantParts = partCountForBits(omsb);
  707. lf = shiftRight(fullSignificand, significantParts, bits);
  708. lost_fraction = combineLostFractions(lf, lost_fraction);
  709. exponent += bits;
  710. }
  711. APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
  712. if(newPartsCount > 4)
  713. delete [] fullSignificand;
  714. return lost_fraction;
  715. }
  716. /* Multiply the significands of LHS and RHS to DST. */
  717. lostFraction
  718. APFloat::divideSignificand(const APFloat &rhs)
  719. {
  720. unsigned int bit, i, partsCount;
  721. const integerPart *rhsSignificand;
  722. integerPart *lhsSignificand, *dividend, *divisor;
  723. integerPart scratch[4];
  724. lostFraction lost_fraction;
  725. assert(semantics == rhs.semantics);
  726. lhsSignificand = significandParts();
  727. rhsSignificand = rhs.significandParts();
  728. partsCount = partCount();
  729. if(partsCount > 2)
  730. dividend = new integerPart[partsCount * 2];
  731. else
  732. dividend = scratch;
  733. divisor = dividend + partsCount;
  734. /* Copy the dividend and divisor as they will be modified in-place. */
  735. for(i = 0; i < partsCount; i++) {
  736. dividend[i] = lhsSignificand[i];
  737. divisor[i] = rhsSignificand[i];
  738. lhsSignificand[i] = 0;
  739. }
  740. exponent -= rhs.exponent;
  741. unsigned int precision = semantics->precision;
  742. /* Normalize the divisor. */
  743. bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
  744. if(bit) {
  745. exponent += bit;
  746. APInt::tcShiftLeft(divisor, partsCount, bit);
  747. }
  748. /* Normalize the dividend. */
  749. bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
  750. if(bit) {
  751. exponent -= bit;
  752. APInt::tcShiftLeft(dividend, partsCount, bit);
  753. }
  754. /* Ensure the dividend >= divisor initially for the loop below.
  755. Incidentally, this means that the division loop below is
  756. guaranteed to set the integer bit to one. */
  757. if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
  758. exponent--;
  759. APInt::tcShiftLeft(dividend, partsCount, 1);
  760. assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
  761. }
  762. /* Long division. */
  763. for(bit = precision; bit; bit -= 1) {
  764. if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
  765. APInt::tcSubtract(dividend, divisor, 0, partsCount);
  766. APInt::tcSetBit(lhsSignificand, bit - 1);
  767. }
  768. APInt::tcShiftLeft(dividend, partsCount, 1);
  769. }
  770. /* Figure out the lost fraction. */
  771. int cmp = APInt::tcCompare(dividend, divisor, partsCount);
  772. if(cmp > 0)
  773. lost_fraction = lfMoreThanHalf;
  774. else if(cmp == 0)
  775. lost_fraction = lfExactlyHalf;
  776. else if(APInt::tcIsZero(dividend, partsCount))
  777. lost_fraction = lfExactlyZero;
  778. else
  779. lost_fraction = lfLessThanHalf;
  780. if(partsCount > 2)
  781. delete [] dividend;
  782. return lost_fraction;
  783. }
  784. unsigned int
  785. APFloat::significandMSB() const
  786. {
  787. return APInt::tcMSB(significandParts(), partCount());
  788. }
  789. unsigned int
  790. APFloat::significandLSB() const
  791. {
  792. return APInt::tcLSB(significandParts(), partCount());
  793. }
  794. /* Note that a zero result is NOT normalized to fcZero. */
  795. lostFraction
  796. APFloat::shiftSignificandRight(unsigned int bits)
  797. {
  798. /* Our exponent should not overflow. */
  799. assert((exponent_t) (exponent + bits) >= exponent);
  800. exponent += bits;
  801. return shiftRight(significandParts(), partCount(), bits);
  802. }
  803. /* Shift the significand left BITS bits, subtract BITS from its exponent. */
  804. void
  805. APFloat::shiftSignificandLeft(unsigned int bits)
  806. {
  807. assert(bits < semantics->precision);
  808. if(bits) {
  809. unsigned int partsCount = partCount();
  810. APInt::tcShiftLeft(significandParts(), partsCount, bits);
  811. exponent -= bits;
  812. assert(!APInt::tcIsZero(significandParts(), partsCount));
  813. }
  814. }
  815. APFloat::cmpResult
  816. APFloat::compareAbsoluteValue(const APFloat &rhs) const
  817. {
  818. int compare;
  819. assert(semantics == rhs.semantics);
  820. assert(category == fcNormal);
  821. assert(rhs.category == fcNormal);
  822. compare = exponent - rhs.exponent;
  823. /* If exponents are equal, do an unsigned bignum comparison of the
  824. significands. */
  825. if(compare == 0)
  826. compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
  827. partCount());
  828. if(compare > 0)
  829. return cmpGreaterThan;
  830. else if(compare < 0)
  831. return cmpLessThan;
  832. else
  833. return cmpEqual;
  834. }
  835. /* Handle overflow. Sign is preserved. We either become infinity or
  836. the largest finite number. */
  837. APFloat::opStatus
  838. APFloat::handleOverflow(roundingMode rounding_mode)
  839. {
  840. /* Infinity? */
  841. if(rounding_mode == rmNearestTiesToEven
  842. || rounding_mode == rmNearestTiesToAway
  843. || (rounding_mode == rmTowardPositive && !sign)
  844. || (rounding_mode == rmTowardNegative && sign))
  845. {
  846. category = fcInfinity;
  847. return (opStatus) (opOverflow | opInexact);
  848. }
  849. /* Otherwise we become the largest finite number. */
  850. category = fcNormal;
  851. exponent = semantics->maxExponent;
  852. APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
  853. semantics->precision);
  854. return opInexact;
  855. }
  856. /* Returns TRUE if, when truncating the current number, with BIT the
  857. new LSB, with the given lost fraction and rounding mode, the result
  858. would need to be rounded away from zero (i.e., by increasing the
  859. signficand). This routine must work for fcZero of both signs, and
  860. fcNormal numbers. */
  861. bool
  862. APFloat::roundAwayFromZero(roundingMode rounding_mode,
  863. lostFraction lost_fraction,
  864. unsigned int bit) const
  865. {
  866. /* NaNs and infinities should not have lost fractions. */
  867. assert(category == fcNormal || category == fcZero);
  868. /* Current callers never pass this so we don't handle it. */
  869. assert(lost_fraction != lfExactlyZero);
  870. switch (rounding_mode) {
  871. default:
  872. llvm_unreachable();
  873. case rmNearestTiesToAway:
  874. return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
  875. case rmNearestTiesToEven:
  876. if(lost_fraction == lfMoreThanHalf)
  877. return true;
  878. /* Our zeroes don't have a significand to test. */
  879. if(lost_fraction == lfExactlyHalf && category != fcZero)
  880. return APInt::tcExtractBit(significandParts(), bit);
  881. return false;
  882. case rmTowardZero:
  883. return false;
  884. case rmTowardPositive:
  885. return sign == false;
  886. case rmTowardNegative:
  887. return sign == true;
  888. }
  889. }
  890. APFloat::opStatus
  891. APFloat::normalize(roundingMode rounding_mode,
  892. lostFraction lost_fraction)
  893. {
  894. unsigned int omsb; /* One, not zero, based MSB. */
  895. int exponentChange;
  896. if(category != fcNormal)
  897. return opOK;
  898. /* Before rounding normalize the exponent of fcNormal numbers. */
  899. omsb = significandMSB() + 1;
  900. if(omsb) {
  901. /* OMSB is numbered from 1. We want to place it in the integer
  902. bit numbered PRECISON if possible, with a compensating change in
  903. the exponent. */
  904. exponentChange = omsb - semantics->precision;
  905. /* If the resulting exponent is too high, overflow according to
  906. the rounding mode. */
  907. if(exponent + exponentChange > semantics->maxExponent)
  908. return handleOverflow(rounding_mode);
  909. /* Subnormal numbers have exponent minExponent, and their MSB
  910. is forced based on that. */
  911. if(exponent + exponentChange < semantics->minExponent)
  912. exponentChange = semantics->minExponent - exponent;
  913. /* Shifting left is easy as we don't lose precision. */
  914. if(exponentChange < 0) {
  915. assert(lost_fraction == lfExactlyZero);
  916. shiftSignificandLeft(-exponentChange);
  917. return opOK;
  918. }
  919. if(exponentChange > 0) {
  920. lostFraction lf;
  921. /* Shift right and capture any new lost fraction. */
  922. lf = shiftSignificandRight(exponentChange);
  923. lost_fraction = combineLostFractions(lf, lost_fraction);
  924. /* Keep OMSB up-to-date. */
  925. if(omsb > (unsigned) exponentChange)
  926. omsb -= exponentChange;
  927. else
  928. omsb = 0;
  929. }
  930. }
  931. /* Now round the number according to rounding_mode given the lost
  932. fraction. */
  933. /* As specified in IEEE 754, since we do not trap we do not report
  934. underflow for exact results. */
  935. if(lost_fraction == lfExactlyZero) {
  936. /* Canonicalize zeroes. */
  937. if(omsb == 0)
  938. category = fcZero;
  939. return opOK;
  940. }
  941. /* Increment the significand if we're rounding away from zero. */
  942. if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
  943. if(omsb == 0)
  944. exponent = semantics->minExponent;
  945. incrementSignificand();
  946. omsb = significandMSB() + 1;
  947. /* Did the significand increment overflow? */
  948. if(omsb == (unsigned) semantics->precision + 1) {
  949. /* Renormalize by incrementing the exponent and shifting our
  950. significand right one. However if we already have the
  951. maximum exponent we overflow to infinity. */
  952. if(exponent == semantics->maxExponent) {
  953. category = fcInfinity;
  954. return (opStatus) (opOverflow | opInexact);
  955. }
  956. shiftSignificandRight(1);
  957. return opInexact;
  958. }
  959. }
  960. /* The normal case - we were and are not denormal, and any
  961. significand increment above didn't overflow. */
  962. if(omsb == semantics->precision)
  963. return opInexact;
  964. /* We have a non-zero denormal. */
  965. assert(omsb < semantics->precision);
  966. /* Canonicalize zeroes. */
  967. if(omsb == 0)
  968. category = fcZero;
  969. /* The fcZero case is a denormal that underflowed to zero. */
  970. return (opStatus) (opUnderflow | opInexact);
  971. }
  972. APFloat::opStatus
  973. APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
  974. {
  975. switch (convolve(category, rhs.category)) {
  976. default:
  977. llvm_unreachable();
  978. case convolve(fcNaN, fcZero):
  979. case convolve(fcNaN, fcNormal):
  980. case convolve(fcNaN, fcInfinity):
  981. case convolve(fcNaN, fcNaN):
  982. case convolve(fcNormal, fcZero):
  983. case convolve(fcInfinity, fcNormal):
  984. case convolve(fcInfinity, fcZero):
  985. return opOK;
  986. case convolve(fcZero, fcNaN):
  987. case convolve(fcNormal, fcNaN):
  988. case convolve(fcInfinity, fcNaN):
  989. category = fcNaN;
  990. copySignificand(rhs);
  991. return opOK;
  992. case convolve(fcNormal, fcInfinity):
  993. case convolve(fcZero, fcInfinity):
  994. category = fcInfinity;
  995. sign = rhs.sign ^ subtract;
  996. return opOK;
  997. case convolve(fcZero, fcNormal):
  998. assign(rhs);
  999. sign = rhs.sign ^ subtract;
  1000. return opOK;
  1001. case convolve(fcZero, fcZero):
  1002. /* Sign depends on rounding mode; handled by caller. */
  1003. return opOK;
  1004. case convolve(fcInfinity, fcInfinity):
  1005. /* Differently signed infinities can only be validly
  1006. subtracted. */
  1007. if(((sign ^ rhs.sign)!=0) != subtract) {
  1008. makeNaN();
  1009. return opInvalidOp;
  1010. }
  1011. return opOK;
  1012. case convolve(fcNormal, fcNormal):
  1013. return opDivByZero;
  1014. }
  1015. }
  1016. /* Add or subtract two normal numbers. */
  1017. lostFraction
  1018. APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
  1019. {
  1020. integerPart carry;
  1021. lostFraction lost_fraction;
  1022. int bits;
  1023. /* Determine if the operation on the absolute values is effectively
  1024. an addition or subtraction. */
  1025. subtract ^= (sign ^ rhs.sign) ? true : false;
  1026. /* Are we bigger exponent-wise than the RHS? */
  1027. bits = exponent - rhs.exponent;
  1028. /* Subtraction is more subtle than one might naively expect. */
  1029. if(subtract) {
  1030. APFloat temp_rhs(rhs);
  1031. bool reverse;
  1032. if (bits == 0) {
  1033. reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
  1034. lost_fraction = lfExactlyZero;
  1035. } else if (bits > 0) {
  1036. lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
  1037. shiftSignificandLeft(1);
  1038. reverse = false;
  1039. } else {
  1040. lost_fraction = shiftSignificandRight(-bits - 1);
  1041. temp_rhs.shiftSignificandLeft(1);
  1042. reverse = true;
  1043. }
  1044. if (reverse) {
  1045. carry = temp_rhs.subtractSignificand
  1046. (*this, lost_fraction != lfExactlyZero);
  1047. copySignificand(temp_rhs);
  1048. sign = !sign;
  1049. } else {
  1050. carry = subtractSignificand
  1051. (temp_rhs, lost_fraction != lfExactlyZero);
  1052. }
  1053. /* Invert the lost fraction - it was on the RHS and
  1054. subtracted. */
  1055. if(lost_fraction == lfLessThanHalf)
  1056. lost_fraction = lfMoreThanHalf;
  1057. else if(lost_fraction == lfMoreThanHalf)
  1058. lost_fraction = lfLessThanHalf;
  1059. /* The code above is intended to ensure that no borrow is
  1060. necessary. */
  1061. assert(!carry);
  1062. } else {
  1063. if(bits > 0) {
  1064. APFloat temp_rhs(rhs);
  1065. lost_fraction = temp_rhs.shiftSignificandRight(bits);
  1066. carry = addSignificand(temp_rhs);
  1067. } else {
  1068. lost_fraction = shiftSignificandRight(-bits);
  1069. carry = addSignificand(rhs);
  1070. }
  1071. /* We have a guard bit; generating a carry cannot happen. */
  1072. assert(!carry);
  1073. }
  1074. return lost_fraction;
  1075. }
  1076. APFloat::opStatus
  1077. APFloat::multiplySpecials(const APFloat &rhs)
  1078. {
  1079. switch (convolve(category, rhs.category)) {
  1080. default:
  1081. llvm_unreachable();
  1082. case convolve(fcNaN, fcZero):
  1083. case convolve(fcNaN, fcNormal):
  1084. case convolve(fcNaN, fcInfinity):
  1085. case convolve(fcNaN, fcNaN):
  1086. return opOK;
  1087. case convolve(fcZero, fcNaN):
  1088. case convolve(fcNormal, fcNaN):
  1089. case convolve(fcInfinity, fcNaN):
  1090. category = fcNaN;
  1091. copySignificand(rhs);
  1092. return opOK;
  1093. case convolve(fcNormal, fcInfinity):
  1094. case convolve(fcInfinity, fcNormal):
  1095. case convolve(fcInfinity, fcInfinity):
  1096. category = fcInfinity;
  1097. return opOK;
  1098. case convolve(fcZero, fcNormal):
  1099. case convolve(fcNormal, fcZero):
  1100. case convolve(fcZero, fcZero):
  1101. category = fcZero;
  1102. return opOK;
  1103. case convolve(fcZero, fcInfinity):
  1104. case convolve(fcInfinity, fcZero):
  1105. makeNaN();
  1106. return opInvalidOp;
  1107. case convolve(fcNormal, fcNormal):
  1108. return opOK;
  1109. }
  1110. }
  1111. APFloat::opStatus
  1112. APFloat::divideSpecials(const APFloat &rhs)
  1113. {
  1114. switch (convolve(category, rhs.category)) {
  1115. default:
  1116. llvm_unreachable();
  1117. case convolve(fcNaN, fcZero):
  1118. case convolve(fcNaN, fcNormal):
  1119. case convolve(fcNaN, fcInfinity):
  1120. case convolve(fcNaN, fcNaN):
  1121. case convolve(fcInfinity, fcZero):
  1122. case convolve(fcInfinity, fcNormal):
  1123. case convolve(fcZero, fcInfinity):
  1124. case convolve(fcZero, fcNormal):
  1125. return opOK;
  1126. case convolve(fcZero, fcNaN):
  1127. case convolve(fcNormal, fcNaN):
  1128. case convolve(fcInfinity, fcNaN):
  1129. category = fcNaN;
  1130. copySignificand(rhs);
  1131. return opOK;
  1132. case convolve(fcNormal, fcInfinity):
  1133. category = fcZero;
  1134. return opOK;
  1135. case convolve(fcNormal, fcZero):
  1136. category = fcInfinity;
  1137. return opDivByZero;
  1138. case convolve(fcInfinity, fcInfinity):
  1139. case convolve(fcZero, fcZero):
  1140. makeNaN();
  1141. return opInvalidOp;
  1142. case convolve(fcNormal, fcNormal):
  1143. return opOK;
  1144. }
  1145. }
  1146. APFloat::opStatus
  1147. APFloat::modSpecials(const APFloat &rhs)
  1148. {
  1149. switch (convolve(category, rhs.category)) {
  1150. default:
  1151. llvm_unreachable();
  1152. case convolve(fcNaN, fcZero):
  1153. case convolve(fcNaN, fcNormal):
  1154. case convolve(fcNaN, fcInfinity):
  1155. case convolve(fcNaN, fcNaN):
  1156. case convolve(fcZero, fcInfinity):
  1157. case convolve(fcZero, fcNormal):
  1158. case convolve(fcNormal, fcInfinity):
  1159. return opOK;
  1160. case convolve(fcZero, fcNaN):
  1161. case convolve(fcNormal, fcNaN):
  1162. case convolve(fcInfinity, fcNaN):
  1163. category = fcNaN;
  1164. copySignificand(rhs);
  1165. return opOK;
  1166. case convolve(fcNormal, fcZero):
  1167. case convolve(fcInfinity, fcZero):
  1168. case convolve(fcInfinity, fcNormal):
  1169. case convolve(fcInfinity, fcInfinity):
  1170. case convolve(fcZero, fcZero):
  1171. makeNaN();
  1172. return opInvalidOp;
  1173. case convolve(fcNormal, fcNormal):
  1174. return opOK;
  1175. }
  1176. }
  1177. /* Change sign. */
  1178. void
  1179. APFloat::changeSign()
  1180. {
  1181. /* Look mummy, this one's easy. */
  1182. sign = !sign;
  1183. }
  1184. void
  1185. APFloat::clearSign()
  1186. {
  1187. /* So is this one. */
  1188. sign = 0;
  1189. }
  1190. void
  1191. APFloat::copySign(const APFloat &rhs)
  1192. {
  1193. /* And this one. */
  1194. sign = rhs.sign;
  1195. }
  1196. /* Normalized addition or subtraction. */
  1197. APFloat::opStatus
  1198. APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
  1199. bool subtract)
  1200. {
  1201. opStatus fs;
  1202. assertArithmeticOK(*semantics);
  1203. fs = addOrSubtractSpecials(rhs, subtract);
  1204. /* This return code means it was not a simple case. */
  1205. if(fs == opDivByZero) {
  1206. lostFraction lost_fraction;
  1207. lost_fraction = addOrSubtractSignificand(rhs, subtract);
  1208. fs = normalize(rounding_mode, lost_fraction);
  1209. /* Can only be zero if we lost no fraction. */
  1210. assert(category != fcZero || lost_fraction == lfExactlyZero);
  1211. }
  1212. /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
  1213. positive zero unless rounding to minus infinity, except that
  1214. adding two like-signed zeroes gives that zero. */
  1215. if(category == fcZero) {
  1216. if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
  1217. sign = (rounding_mode == rmTowardNegative);
  1218. }
  1219. return fs;
  1220. }
  1221. /* Normalized addition. */
  1222. APFloat::opStatus
  1223. APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
  1224. {
  1225. return addOrSubtract(rhs, rounding_mode, false);
  1226. }
  1227. /* Normalized subtraction. */
  1228. APFloat::opStatus
  1229. APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
  1230. {
  1231. return addOrSubtract(rhs, rounding_mode, true);
  1232. }
  1233. /* Normalized multiply. */
  1234. APFloat::opStatus
  1235. APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
  1236. {
  1237. opStatus fs;
  1238. assertArithmeticOK(*semantics);
  1239. sign ^= rhs.sign;
  1240. fs = multiplySpecials(rhs);
  1241. if(category == fcNormal) {
  1242. lostFraction lost_fraction = multiplySignificand(rhs, 0);
  1243. fs = normalize(rounding_mode, lost_fraction);
  1244. if(lost_fraction != lfExactlyZero)
  1245. fs = (opStatus) (fs | opInexact);
  1246. }
  1247. return fs;
  1248. }
  1249. /* Normalized divide. */
  1250. APFloat::opStatus
  1251. APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
  1252. {
  1253. opStatus fs;
  1254. assertArithmeticOK(*semantics);
  1255. sign ^= rhs.sign;
  1256. fs = divideSpecials(rhs);
  1257. if(category == fcNormal) {
  1258. lostFraction lost_fraction = divideSignificand(rhs);
  1259. fs = normalize(rounding_mode, lost_fraction);
  1260. if(lost_fraction != lfExactlyZero)
  1261. fs = (opStatus) (fs | opInexact);
  1262. }
  1263. return fs;
  1264. }
  1265. /* Normalized remainder. This is not currently correct in all cases. */
  1266. APFloat::opStatus
  1267. APFloat::remainder(const APFloat &rhs)
  1268. {
  1269. opStatus fs;
  1270. APFloat V = *this;
  1271. unsigned int origSign = sign;
  1272. assertArithmeticOK(*semantics);
  1273. fs = V.divide(rhs, rmNearestTiesToEven);
  1274. if (fs == opDivByZero)
  1275. return fs;
  1276. int parts = partCount();
  1277. integerPart *x = new integerPart[parts];
  1278. bool ignored;
  1279. fs = V.convertToInteger(x, parts * integerPartWidth, true,
  1280. rmNearestTiesToEven, &ignored);
  1281. if (fs==opInvalidOp)
  1282. return fs;
  1283. fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
  1284. rmNearestTiesToEven);
  1285. assert(fs==opOK); // should always work
  1286. fs = V.multiply(rhs, rmNearestTiesToEven);
  1287. assert(fs==opOK || fs==opInexact); // should not overflow or underflow
  1288. fs = subtract(V, rmNearestTiesToEven);
  1289. assert(fs==opOK || fs==opInexact); // likewise
  1290. if (isZero())
  1291. sign = origSign; // IEEE754 requires this
  1292. delete[] x;
  1293. return fs;
  1294. }
  1295. /* Normalized llvm frem (C fmod).
  1296. This is not currently correct in all cases. */
  1297. APFloat::opStatus
  1298. APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
  1299. {
  1300. opStatus fs;
  1301. assertArithmeticOK(*semantics);
  1302. fs = modSpecials(rhs);
  1303. if (category == fcNormal && rhs.category == fcNormal) {
  1304. APFloat V = *this;
  1305. unsigned int origSign = sign;
  1306. fs = V.divide(rhs, rmNearestTiesToEven);
  1307. if (fs == opDivByZero)
  1308. return fs;
  1309. int parts = partCount();
  1310. integerPart *x = new integerPart[parts];
  1311. bool ignored;
  1312. fs = V.convertToInteger(x, parts * integerPartWidth, true,
  1313. rmTowardZero, &ignored);
  1314. if (fs==opInvalidOp)
  1315. return fs;
  1316. fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
  1317. rmNearestTiesToEven);
  1318. assert(fs==opOK); // should always work
  1319. fs = V.multiply(rhs, rounding_mode);
  1320. assert(fs==opOK || fs==opInexact); // should not overflow or underflow
  1321. fs = subtract(V, rounding_mode);
  1322. assert(fs==opOK || fs==opInexact); // likewise
  1323. if (isZero())
  1324. sign = origSign; // IEEE754 requires this
  1325. delete[] x;
  1326. }
  1327. return fs;
  1328. }
  1329. /* Normalized fused-multiply-add. */
  1330. APFloat::opStatus
  1331. APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
  1332. const APFloat &addend,
  1333. roundingMode rounding_mode)
  1334. {
  1335. opStatus fs;
  1336. assertArithmeticOK(*semantics);
  1337. /* Post-multiplication sign, before addition. */
  1338. sign ^= multiplicand.sign;
  1339. /* If and only if all arguments are normal do we need to do an
  1340. extended-precision calculation. */
  1341. if(category == fcNormal
  1342. && multiplicand.category == fcNormal
  1343. && addend.category == fcNormal) {
  1344. lostFraction lost_fraction;
  1345. lost_fraction = multiplySignificand(multiplicand, &addend);
  1346. fs = normalize(rounding_mode, lost_fraction);
  1347. if(lost_fraction != lfExactlyZero)
  1348. fs = (opStatus) (fs | opInexact);
  1349. /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
  1350. positive zero unless rounding to minus infinity, except that
  1351. adding two like-signed zeroes gives that zero. */
  1352. if(category == fcZero && sign != addend.sign)
  1353. sign = (rounding_mode == rmTowardNegative);
  1354. } else {
  1355. fs = multiplySpecials(multiplicand);
  1356. /* FS can only be opOK or opInvalidOp. There is no more work
  1357. to do in the latter case. The IEEE-754R standard says it is
  1358. implementation-defined in this case whether, if ADDEND is a
  1359. quiet NaN, we raise invalid op; this implementation does so.
  1360. If we need to do the addition we can do so with normal
  1361. precision. */
  1362. if(fs == opOK)
  1363. fs = addOrSubtract(addend, rounding_mode, false);
  1364. }
  1365. return fs;
  1366. }
  1367. /* Comparison requires normalized numbers. */
  1368. APFloat::cmpResult
  1369. APFloat::compare(const APFloat &rhs) const
  1370. {
  1371. cmpResult result;
  1372. assertArithmeticOK(*semantics);
  1373. assert(semantics == rhs.semantics);
  1374. switch (convolve(category, rhs.category)) {
  1375. default:
  1376. llvm_unreachable();
  1377. case convolve(fcNaN, fcZero):
  1378. case convolve(fcNaN, fcNormal):
  1379. case convolve(fcNaN, fcInfinity):
  1380. case convolve(fcNaN, fcNaN):
  1381. case convolve(fcZero, fcNaN):
  1382. case convolve(fcNormal, fcNaN):
  1383. case convolve(fcInfinity, fcNaN):
  1384. return cmpUnordered;
  1385. case convolve(fcInfinity, fcNormal):
  1386. case convolve(fcInfinity, fcZero):
  1387. case convolve(fcNormal, fcZero):
  1388. if(sign)
  1389. return cmpLessThan;
  1390. else
  1391. return cmpGreaterThan;
  1392. case convolve(fcNormal, fcInfinity):
  1393. case convolve(fcZero, fcInfinity):
  1394. case convolve(fcZero, fcNormal):
  1395. if(rhs.sign)
  1396. return cmpGreaterThan;
  1397. else
  1398. return cmpLessThan;
  1399. case convolve(fcInfinity, fcInfinity):
  1400. if(sign == rhs.sign)
  1401. return cmpEqual;
  1402. else if(sign)
  1403. return cmpLessThan;
  1404. else
  1405. return cmpGreaterThan;
  1406. case convolve(fcZero, fcZero):
  1407. return cmpEqual;
  1408. case convolve(fcNormal, fcNormal):
  1409. break;
  1410. }
  1411. /* Two normal numbers. Do they have the same sign? */
  1412. if(sign != rhs.sign) {
  1413. if(sign)
  1414. result = cmpLessThan;
  1415. else
  1416. result = cmpGreaterThan;
  1417. } else {
  1418. /* Compare absolute values; invert result if negative. */
  1419. result = compareAbsoluteValue(rhs);
  1420. if(sign) {
  1421. if(result == cmpLessThan)
  1422. result = cmpGreaterThan;
  1423. else if(result == cmpGreaterThan)
  1424. result = cmpLessThan;
  1425. }
  1426. }
  1427. return result;
  1428. }
  1429. /// APFloat::convert - convert a value of one floating point type to another.
  1430. /// The return value corresponds to the IEEE754 exceptions. *losesInfo
  1431. /// records whether the transformation lost information, i.e. whether
  1432. /// converting the result back to the original type will produce the
  1433. /// original value (this is almost the same as return value==fsOK, but there
  1434. /// are edge cases where this is not so).
  1435. APFloat::opStatus
  1436. APFloat::convert(const fltSemantics &toSemantics,
  1437. roundingMode rounding_mode, bool *losesInfo)
  1438. {
  1439. lostFraction lostFraction;
  1440. unsigned int newPartCount, oldPartCount;
  1441. opStatus fs;
  1442. assertArithmeticOK(*semantics);
  1443. assertArithmeticOK(toSemantics);
  1444. lostFraction = lfExactlyZero;
  1445. newPartCount = partCountForBits(toSemantics.precision + 1);
  1446. oldPartCount = partCount();
  1447. /* Handle storage complications. If our new form is wider,
  1448. re-allocate our bit pattern into wider storage. If it is
  1449. narrower, we ignore the excess parts, but if narrowing to a
  1450. single part we need to free the old storage.
  1451. Be careful not to reference significandParts for zeroes
  1452. and infinities, since it aborts. */
  1453. if (newPartCount > oldPartCount) {
  1454. integerPart *newParts;
  1455. newParts = new integerPart[newPartCount];
  1456. APInt::tcSet(newParts, 0, newPartCount);
  1457. if (category==fcNormal || category==fcNaN)
  1458. APInt::tcAssign(newParts, significandParts(), oldPartCount);
  1459. freeSignificand();
  1460. significand.parts = newParts;
  1461. } else if (newPartCount < oldPartCount) {
  1462. /* Capture any lost fraction through truncation of parts so we get
  1463. correct rounding whilst normalizing. */
  1464. if (category==fcNormal)
  1465. lostFraction = lostFractionThroughTruncation
  1466. (significandParts(), oldPartCount, toSemantics.precision);
  1467. if (newPartCount == 1) {
  1468. integerPart newPart = 0;
  1469. if (category==fcNormal || category==fcNaN)
  1470. newPart = significandParts()[0];
  1471. freeSignificand();
  1472. significand.part = newPart;
  1473. }
  1474. }
  1475. if(category == fcNormal) {
  1476. /* Re-interpret our bit-pattern. */
  1477. exponent += toSemantics.precision - semantics->precision;
  1478. semantics = &toSemantics;
  1479. fs = normalize(rounding_mode, lostFraction);
  1480. *losesInfo = (fs != opOK);
  1481. } else if (category == fcNaN) {
  1482. int shift = toSemantics.precision - semantics->precision;
  1483. // Do this now so significandParts gets the right answer
  1484. const fltSemantics *oldSemantics = semantics;
  1485. semantics = &toSemantics;
  1486. *losesInfo = false;
  1487. // No normalization here, just truncate
  1488. if (shift>0)
  1489. APInt::tcShiftLeft(significandParts(), newPartCount, shift);
  1490. else if (shift < 0) {
  1491. unsigned ushift = -shift;
  1492. // Figure out if we are losing information. This happens
  1493. // if are shifting out something other than 0s, or if the x87 long
  1494. // double input did not have its integer bit set (pseudo-NaN), or if the
  1495. // x87 long double input did not have its QNan bit set (because the x87
  1496. // hardware sets this bit when converting a lower-precision NaN to
  1497. // x87 long double).
  1498. if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
  1499. *losesInfo = true;
  1500. if (oldSemantics == &APFloat::x87DoubleExtended &&
  1501. (!(*significandParts() & 0x8000000000000000ULL) ||
  1502. !(*significandParts() & 0x4000000000000000ULL)))
  1503. *losesInfo = true;
  1504. APInt::tcShiftRight(significandParts(), newPartCount, ushift);
  1505. }
  1506. // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
  1507. // does not give you back the same bits. This is dubious, and we
  1508. // don't currently do it. You're really supposed to get
  1509. // an invalid operation signal at runtime, but nobody does that.
  1510. fs = opOK;
  1511. } else {
  1512. semantics = &toSemantics;
  1513. fs = opOK;
  1514. *losesInfo = false;
  1515. }
  1516. return fs;
  1517. }
  1518. /* Convert a floating point number to an integer according to the
  1519. rounding mode. If the rounded integer value is out of range this
  1520. returns an invalid operation exception and the contents of the
  1521. destination parts are unspecified. If the rounded value is in
  1522. range but the floating point number is not the exact integer, the C
  1523. standard doesn't require an inexact exception to be raised. IEEE
  1524. 854 does require it so we do that.
  1525. Note that for conversions to integer type the C standard requires
  1526. round-to-zero to always be used. */
  1527. APFloat::opStatus
  1528. APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
  1529. bool isSigned,
  1530. roundingMode rounding_mode,
  1531. bool *isExact) const
  1532. {
  1533. lostFraction lost_fraction;
  1534. const integerPart *src;
  1535. unsigned int dstPartsCount, truncatedBits;
  1536. assertArithmeticOK(*semantics);
  1537. *isExact = false;
  1538. /* Handle the three special cases first. */
  1539. if(category == fcInfinity || category == fcNaN)
  1540. return opInvalidOp;
  1541. dstPartsCount = partCountForBits(width);
  1542. if(category == fcZero) {
  1543. APInt::tcSet(parts, 0, dstPartsCount);
  1544. // Negative zero can't be represented as an int.
  1545. *isExact = !sign;
  1546. return opOK;
  1547. }
  1548. src = significandParts();
  1549. /* Step 1: place our absolute value, with any fraction truncated, in
  1550. the destination. */
  1551. if (exponent < 0) {
  1552. /* Our absolute value is less than one; truncate everything. */
  1553. APInt::tcSet(parts, 0, dstPartsCount);
  1554. /* For exponent -1 the integer bit represents .5, look at that.
  1555. For smaller exponents leftmost truncated bit is 0. */
  1556. truncatedBits = semantics->precision -1U - exponent;
  1557. } else {
  1558. /* We want the most significant (exponent + 1) bits; the rest are
  1559. truncated. */
  1560. unsigned int bits = exponent + 1U;
  1561. /* Hopelessly large in magnitude? */
  1562. if (bits > width)
  1563. return opInvalidOp;
  1564. if (bits < semantics->precision) {
  1565. /* We truncate (semantics->precision - bits) bits. */
  1566. truncatedBits = semantics->precision - bits;
  1567. APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
  1568. } else {
  1569. /* We want at least as many bits as are available. */
  1570. APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
  1571. APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
  1572. truncatedBits = 0;
  1573. }
  1574. }
  1575. /* Step 2: work out any lost fraction, and increment the absolute
  1576. value if we would round away from zero. */
  1577. if (truncatedBits) {
  1578. lost_fraction = lostFractionThroughTruncation(src, partCount(),
  1579. truncatedBits);
  1580. if (lost_fraction != lfExactlyZero
  1581. && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
  1582. if (APInt::tcIncrement(parts, dstPartsCount))
  1583. return opInvalidOp; /* Overflow. */
  1584. }
  1585. } else {
  1586. lost_fraction = lfExactlyZero;
  1587. }
  1588. /* Step 3: check if we fit in the destination. */
  1589. unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
  1590. if (sign) {
  1591. if (!isSigned) {
  1592. /* Negative numbers cannot be represented as unsigned. */
  1593. if (omsb != 0)
  1594. return opInvalidOp;
  1595. } else {
  1596. /* It takes omsb bits to represent the unsigned integer value.
  1597. We lose a bit for the sign, but care is needed as the
  1598. maximally negative integer is a special case. */
  1599. if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
  1600. return opInvalidOp;
  1601. /* This case can happen because of rounding. */
  1602. if (omsb > width)
  1603. return opInvalidOp;
  1604. }
  1605. APInt::tcNegate (parts, dstPartsCount);
  1606. } else {
  1607. if (omsb >= width + !isSigned)
  1608. return opInvalidOp;
  1609. }
  1610. if (lost_fraction == lfExactlyZero) {
  1611. *isExact = true;
  1612. return opOK;
  1613. } else
  1614. return opInexact;
  1615. }
  1616. /* Same as convertToSignExtendedInteger, except we provide
  1617. deterministic values in case of an invalid operation exception,
  1618. namely zero for NaNs and the minimal or maximal value respectively
  1619. for underflow or overflow.
  1620. The *isExact output tells whether the result is exact, in the sense
  1621. that converting it back to the original floating point type produces
  1622. the original value. This is almost equivalent to result==opOK,
  1623. except for negative zeroes.
  1624. */
  1625. APFloat::opStatus
  1626. APFloat::convertToInteger(integerPart *parts, unsigned int width,
  1627. bool isSigned,
  1628. roundingMode rounding_mode, bool *isExact) const
  1629. {
  1630. opStatus fs;
  1631. fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
  1632. isExact);
  1633. if (fs == opInvalidOp) {
  1634. unsigned int bits, dstPartsCount;
  1635. dstPartsCount = partCountForBits(width);
  1636. if (category == fcNaN)
  1637. bits = 0;
  1638. else if (sign)
  1639. bits = isSigned;
  1640. else
  1641. bits = width - isSigned;
  1642. APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
  1643. if (sign && isSigned)
  1644. APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
  1645. }
  1646. return fs;
  1647. }
  1648. /* Convert an unsigned integer SRC to a floating point number,
  1649. rounding according to ROUNDING_MODE. The sign of the floating
  1650. point number is not modified. */
  1651. APFloat::opStatus
  1652. APFloat::convertFromUnsignedParts(const integerPart *src,
  1653. unsigned int srcCount,
  1654. roundingMode rounding_mode)
  1655. {
  1656. unsigned int omsb, precision, dstCount;
  1657. integerPart *dst;
  1658. lostFraction lost_fraction;
  1659. assertArithmeticOK(*semantics);
  1660. category = fcNormal;
  1661. omsb = APInt::tcMSB(src, srcCount) + 1;
  1662. dst = significandParts();
  1663. dstCount = partCount();
  1664. precision = semantics->precision;
  1665. /* We want the most significant PRECISON bits of SRC. There may not
  1666. be that many; extract what we can. */
  1667. if (precision <= omsb) {
  1668. exponent = omsb - 1;
  1669. lost_fraction = lostFractionThroughTruncation(src, srcCount,
  1670. omsb - precision);
  1671. APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
  1672. } else {
  1673. exponent = precision - 1;
  1674. lost_fraction = lfExactlyZero;
  1675. APInt::tcExtract(dst, dstCount, src, omsb, 0);
  1676. }
  1677. return normalize(rounding_mode, lost_fraction);
  1678. }
  1679. APFloat::opStatus
  1680. APFloat::convertFromAPInt(const APInt &Val,
  1681. bool isSigned,
  1682. roundingMode rounding_mode)
  1683. {
  1684. unsigned int partCount = Val.getNumWords();
  1685. APInt api = Val;
  1686. sign = false;
  1687. if (isSigned && api.isNegative()) {
  1688. sign = true;
  1689. api = -api;
  1690. }
  1691. return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
  1692. }
  1693. /* Convert a two's complement integer SRC to a floating point number,
  1694. rounding according to ROUNDING_MODE. ISSIGNED is true if the
  1695. integer is signed, in which case it must be sign-extended. */
  1696. APFloat::opStatus
  1697. APFloat::convertFromSignExtendedInteger(const integerPart *src,
  1698. unsigned int srcCount,
  1699. bool isSigned,
  1700. roundingMode rounding_mode)
  1701. {
  1702. opStatus status;
  1703. assertArithmeticOK(*semantics);
  1704. if (isSigned
  1705. && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
  1706. integerPart *copy;
  1707. /* If we're signed and negative negate a copy. */
  1708. sign = true;
  1709. copy = new integerPart[srcCount];
  1710. APInt::tcAssign(copy, src, srcCount);
  1711. APInt::tcNegate(copy, srcCount);
  1712. status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
  1713. delete [] copy;
  1714. } else {
  1715. sign = false;
  1716. status = convertFromUnsignedParts(src, srcCount, rounding_mode);
  1717. }
  1718. return status;
  1719. }
  1720. /* FIXME: should this just take a const APInt reference? */
  1721. APFloat::opStatus
  1722. APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
  1723. unsigned int width, bool isSigned,
  1724. roundingMode rounding_mode)
  1725. {
  1726. unsigned int partCount = partCountForBits(width);
  1727. APInt api = APInt(width, partCount, parts);
  1728. sign = false;
  1729. if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
  1730. sign = true;
  1731. api = -api;
  1732. }
  1733. return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
  1734. }
  1735. APFloat::opStatus
  1736. APFloat::convertFromHexadecimalString(const char *p,
  1737. roundingMode rounding_mode)
  1738. {
  1739. lostFraction lost_fraction;
  1740. integerPart *significand;
  1741. unsigned int bitPos, partsCount;
  1742. const char *dot, *firstSignificantDigit;
  1743. zeroSignificand();
  1744. exponent = 0;
  1745. category = fcNormal;
  1746. significand = significandParts();
  1747. partsCount = partCount();
  1748. bitPos = partsCount * integerPartWidth;
  1749. /* Skip leading zeroes and any (hexa)decimal point. */
  1750. p = skipLeadingZeroesAndAnyDot(p, &dot);
  1751. firstSignificantDigit = p;
  1752. for(;;) {
  1753. integerPart hex_value;
  1754. if(*p == '.') {
  1755. assert(dot == 0);
  1756. dot = p++;
  1757. }
  1758. hex_value = hexDigitValue(*p);
  1759. if(hex_value == -1U) {
  1760. lost_fraction = lfExactlyZero;
  1761. break;
  1762. }
  1763. p++;
  1764. /* Store the number whilst 4-bit nibbles remain. */
  1765. if(bitPos) {
  1766. bitPos -= 4;
  1767. hex_value <<= bitPos % integerPartWidth;
  1768. significand[bitPos / integerPartWidth] |= hex_value;
  1769. } else {
  1770. lost_fraction = trailingHexadecimalFraction(p, hex_value);
  1771. while(hexDigitValue(*p) != -1U)
  1772. p++;
  1773. break;
  1774. }
  1775. }
  1776. /* Hex floats require an exponent but not a hexadecimal point. */
  1777. assert(*p == 'p' || *p == 'P');
  1778. /* Ignore the exponent if we are zero. */
  1779. if(p != firstSignificantDigit) {
  1780. int expAdjustment;
  1781. /* Implicit hexadecimal point? */
  1782. if(!dot)
  1783. dot = p;
  1784. /* Calculate the exponent adjustment implicit in the number of
  1785. significant digits. */
  1786. expAdjustment = static_cast<int>(dot - firstSignificantDigit);
  1787. if(expAdjustment < 0)
  1788. expAdjustment++;
  1789. expAdjustment = expAdjustment * 4 - 1;
  1790. /* Adjust for writing the significand starting at the most
  1791. significant nibble. */
  1792. expAdjustment += semantics->precision;
  1793. expAdjustment -= partsCount * integerPartWidth;
  1794. /* Adjust for the given exponent. */
  1795. exponent = totalExponent(p, expAdjustment);
  1796. }
  1797. return normalize(rounding_mode, lost_fraction);
  1798. }
  1799. APFloat::opStatus
  1800. APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
  1801. unsigned sigPartCount, int exp,
  1802. roundingMode rounding_mode)
  1803. {
  1804. unsigned int parts, pow5PartCount;
  1805. fltSemantics calcSemantics = { 32767, -32767, 0, true };
  1806. integerPart pow5Parts[maxPowerOfFiveParts];
  1807. bool isNearest;
  1808. isNearest = (rounding_mode == rmNearestTiesToEven
  1809. || rounding_mode == rmNearestTiesToAway);
  1810. parts = partCountForBits(semantics->precision + 11);
  1811. /* Calculate pow(5, abs(exp)). */
  1812. pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
  1813. for (;; parts *= 2) {
  1814. opStatus sigStatus, powStatus;
  1815. unsigned int excessPrecision, truncatedBits;
  1816. calcSemantics.precision = parts * integerPartWidth - 1;
  1817. excessPrecision = calcSemantics.precision - semantics->precision;
  1818. truncatedBits = excessPrecision;
  1819. APFloat decSig(calcSemantics, fcZero, sign);
  1820. APFloat pow5(calcSemantics, fcZero, false);
  1821. sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
  1822. rmNearestTiesToEven);
  1823. powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
  1824. rmNearestTiesToEven);
  1825. /* Add exp, as 10^n = 5^n * 2^n. */
  1826. decSig.exponent += exp;
  1827. lostFraction calcLostFraction;
  1828. integerPart HUerr, HUdistance;
  1829. unsigned int powHUerr;
  1830. if (exp >= 0) {
  1831. /* multiplySignificand leaves the precision-th bit set to 1. */
  1832. calcLostFraction = decSig.multiplySignificand(pow5, NULL);
  1833. powHUerr = powStatus != opOK;
  1834. } else {
  1835. calcLostFraction = decSig.divideSignificand(pow5);
  1836. /* Denormal numbers have less precision. */
  1837. if (decSig.exponent < semantics->minExponent) {
  1838. excessPrecision += (semantics->minExponent - decSig.exponent);
  1839. truncatedBits = excessPrecision;
  1840. if (excessPrecision > calcSemantics.precision)
  1841. excessPrecision = calcSemantics.precision;
  1842. }
  1843. /* Extra half-ulp lost in reciprocal of exponent. */
  1844. powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
  1845. }
  1846. /* Both multiplySignificand and divideSignificand return the
  1847. result with the integer bit set. */
  1848. assert (APInt::tcExtractBit
  1849. (decSig.significandParts(), calcSemantics.precision - 1) == 1);
  1850. HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
  1851. powHUerr);
  1852. HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
  1853. excessPrecision, isNearest);
  1854. /* Are we guaranteed to round correctly if we truncate? */
  1855. if (HUdistance >= HUerr) {
  1856. APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
  1857. calcSemantics.precision - excessPrecision,
  1858. excessPrecision);
  1859. /* Take the exponent of decSig. If we tcExtract-ed less bits
  1860. above we must adjust our exponent to compensate for the
  1861. implicit right shift. */
  1862. exponent = (decSig.exponent + semantics->precision
  1863. - (calcSemantics.precision - excessPrecision));
  1864. calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
  1865. decSig.partCount(),
  1866. truncatedBits);
  1867. return normalize(rounding_mode, calcLostFraction);
  1868. }
  1869. }
  1870. }
  1871. APFloat::opStatus
  1872. APFloat::convertFromDecimalString(const char *p, roundingMode rounding_mode)
  1873. {
  1874. decimalInfo D;
  1875. opStatus fs;
  1876. /* Scan the text. */
  1877. interpretDecimal(p, &D);
  1878. /* Handle the quick cases. First the case of no significant digits,
  1879. i.e. zero, and then exponents that are obviously too large or too
  1880. small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
  1881. definitely overflows if
  1882. (exp - 1) * L >= maxExponent
  1883. and definitely underflows to zero where
  1884. (exp + 1) * L <= minExponent - precision
  1885. With integer arithmetic the tightest bounds for L are
  1886. 93/28 < L < 196/59 [ numerator <= 256 ]
  1887. 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
  1888. */
  1889. if (decDigitValue(*D.firstSigDigit) >= 10U) {
  1890. category = fcZero;
  1891. fs = opOK;
  1892. } else if ((D.normalizedExponent + 1) * 28738
  1893. <= 8651 * (semantics->minExponent - (int) semantics->precision)) {
  1894. /* Underflow to zero and round. */
  1895. zeroSignificand();
  1896. fs = normalize(rounding_mode, lfLessThanHalf);
  1897. } else if ((D.normalizedExponent - 1) * 42039
  1898. >= 12655 * semantics->maxExponent) {
  1899. /* Overflow and round. */
  1900. fs = handleOverflow(rounding_mode);
  1901. } else {
  1902. integerPart *decSignificand;
  1903. unsigned int partCount;
  1904. /* A tight upper bound on number of bits required to hold an
  1905. N-digit decimal integer is N * 196 / 59. Allocate enough space
  1906. to hold the full significand, and an extra part required by
  1907. tcMultiplyPart. */
  1908. partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
  1909. partCount = partCountForBits(1 + 196 * partCount / 59);
  1910. decSignificand = new integerPart[partCount + 1];
  1911. partCount = 0;
  1912. /* Convert to binary efficiently - we do almost all multiplication
  1913. in an integerPart. When this would overflow do we do a single
  1914. bignum multiplication, and then revert again to multiplication
  1915. in an integerPart. */
  1916. do {
  1917. integerPart decValue, val, multiplier;
  1918. val = 0;
  1919. multiplier = 1;
  1920. do {
  1921. if (*p == '.')
  1922. p++;
  1923. decValue = decDigitValue(*p++);
  1924. multiplier *= 10;
  1925. val = val * 10 + decValue;
  1926. /* The maximum number that can be multiplied by ten with any
  1927. digit added without overflowing an integerPart. */
  1928. } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
  1929. /* Multiply out the current part. */
  1930. APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
  1931. partCount, partCount + 1, false);
  1932. /* If we used another part (likely but not guaranteed), increase
  1933. the count. */
  1934. if (decSignificand[partCount])
  1935. partCount++;
  1936. } while (p <= D.lastSigDigit);
  1937. category = fcNormal;
  1938. fs = roundSignificandWithExponent(decSignificand, partCount,
  1939. D.exponent, rounding_mode);
  1940. delete [] decSignificand;
  1941. }
  1942. return fs;
  1943. }
  1944. APFloat::opStatus
  1945. APFloat::convertFromString(const char *p, roundingMode rounding_mode)
  1946. {
  1947. assertArithmeticOK(*semantics);
  1948. /* Handle a leading minus sign. */
  1949. if(*p == '-')
  1950. sign = 1, p++;
  1951. else
  1952. sign = 0;
  1953. if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
  1954. return convertFromHexadecimalString(p + 2, rounding_mode);
  1955. return convertFromDecimalString(p, rounding_mode);
  1956. }
  1957. /* Write out a hexadecimal representation of the floating point value
  1958. to DST, which must be of sufficient size, in the C99 form
  1959. [-]0xh.hhhhp[+-]d. Return the number of characters written,
  1960. excluding the terminating NUL.
  1961. If UPPERCASE, the output is in upper case, otherwise in lower case.
  1962. HEXDIGITS digits appear altogether, rounding the value if
  1963. necessary. If HEXDIGITS is 0, the minimal precision to display the
  1964. number precisely is used instead. If nothing would appear after
  1965. the decimal point it is suppressed.
  1966. The decimal exponent is always printed and has at least one digit.
  1967. Zero values display an exponent of zero. Infinities and NaNs
  1968. appear as "infinity" or "nan" respectively.
  1969. The above rules are as specified by C99. There is ambiguity about
  1970. what the leading hexadecimal digit should be. This implementation
  1971. uses whatever is necessary so that the exponent is displayed as
  1972. stored. This implies the exponent will fall within the IEEE format
  1973. range, and the leading hexadecimal digit will be 0 (for denormals),
  1974. 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
  1975. any other digits zero).
  1976. */
  1977. unsigned int
  1978. APFloat::convertToHexString(char *dst, unsigned int hexDigits,
  1979. bool upperCase, roundingMode rounding_mode) const
  1980. {
  1981. char *p;
  1982. assertArithmeticOK(*semantics);
  1983. p = dst;
  1984. if (sign)
  1985. *dst++ = '-';
  1986. switch (category) {
  1987. case fcInfinity:
  1988. memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
  1989. dst += sizeof infinityL - 1;
  1990. break;
  1991. case fcNaN:
  1992. memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
  1993. dst += sizeof NaNU - 1;
  1994. break;
  1995. case fcZero:
  1996. *dst++ = '0';
  1997. *dst++ = upperCase ? 'X': 'x';
  1998. *dst++ = '0';
  1999. if (hexDigits > 1) {
  2000. *dst++ = '.';
  2001. memset (dst, '0', hexDigits - 1);
  2002. dst += hexDigits - 1;
  2003. }
  2004. *dst++ = upperCase ? 'P': 'p';
  2005. *dst++ = '0';
  2006. break;
  2007. case fcNormal:
  2008. dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
  2009. break;
  2010. }
  2011. *dst = 0;
  2012. return static_cast<unsigned int>(dst - p);
  2013. }
  2014. /* Does the hard work of outputting the correctly rounded hexadecimal
  2015. form of a normal floating point number with the specified number of
  2016. hexadecimal digits. If HEXDIGITS is zero the minimum number of
  2017. digits necessary to print the value precisely is output. */
  2018. char *
  2019. APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
  2020. bool upperCase,
  2021. roundingMode rounding_mode) const
  2022. {
  2023. unsigned int count, valueBits, shift, partsCount, outputDigits;
  2024. const char *hexDigitChars;
  2025. const integerPart *significand;
  2026. char *p;
  2027. bool roundUp;
  2028. *dst++ = '0';
  2029. *dst++ = upperCase ? 'X': 'x';
  2030. roundUp = false;
  2031. hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
  2032. significand = significandParts();
  2033. partsCount = partCount();
  2034. /* +3 because the first digit only uses the single integer bit, so
  2035. we have 3 virtual zero most-significant-bits. */
  2036. valueBits = semantics->precision + 3;
  2037. shift = integerPartWidth - valueBits % integerPartWidth;
  2038. /* The natural number of digits required ignoring trailing
  2039. insignificant zeroes. */
  2040. outputDigits = (valueBits - significandLSB () + 3) / 4;
  2041. /* hexDigits of zero means use the required number for the
  2042. precision. Otherwise, see if we are truncating. If we are,
  2043. find out if we need to round away from zero. */
  2044. if (hexDigits) {
  2045. if (hexDigits < outputDigits) {
  2046. /* We are dropping non-zero bits, so need to check how to round.
  2047. "bits" is the number of dropped bits. */
  2048. unsigned int bits;
  2049. lostFraction fraction;
  2050. bits = valueBits - hexDigits * 4;
  2051. fraction = lostFractionThroughTruncation (significand, partsCount, bits);
  2052. roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
  2053. }
  2054. outputDigits = hexDigits;
  2055. }
  2056. /* Write the digits consecutively, and start writing in the location
  2057. of the hexadecimal point. We move the most significant digit
  2058. left and add the hexadecimal point later. */
  2059. p = ++dst;
  2060. count = (valueBits + integerPartWidth - 1) / integerPartWidth;
  2061. while (outputDigits && count) {
  2062. integerPart part;
  2063. /* Put the most significant integerPartWidth bits in "part". */
  2064. if (--count == partsCount)
  2065. part = 0; /* An imaginary higher zero part. */
  2066. else
  2067. part = significand[count] << shift;
  2068. if (count && shift)
  2069. part |= significand[count - 1] >> (integerPartWidth - shift);
  2070. /* Convert as much of "part" to hexdigits as we can. */
  2071. unsigned int curDigits = integerPartWidth / 4;
  2072. if (curDigits > outputDigits)
  2073. curDigits = outputDigits;
  2074. dst += partAsHex (dst, part, curDigits, hexDigitChars);
  2075. outputDigits -= curDigits;
  2076. }
  2077. if (roundUp) {
  2078. char *q = dst;
  2079. /* Note that hexDigitChars has a trailing '0'. */
  2080. do {
  2081. q--;
  2082. *q = hexDigitChars[hexDigitValue (*q) + 1];
  2083. } while (*q == '0');
  2084. assert (q >= p);
  2085. } else {
  2086. /* Add trailing zeroes. */
  2087. memset (dst, '0', outputDigits);
  2088. dst += outputDigits;
  2089. }
  2090. /* Move the most significant digit to before the point, and if there
  2091. is something after the decimal point add it. This must come
  2092. after rounding above. */
  2093. p[-1] = p[0];
  2094. if (dst -1 == p)
  2095. dst--;
  2096. else
  2097. p[0] = '.';
  2098. /* Finally output the exponent. */
  2099. *dst++ = upperCase ? 'P': 'p';
  2100. return writeSignedDecimal (dst, exponent);
  2101. }
  2102. // For good performance it is desirable for different APFloats
  2103. // to produce different integers.
  2104. uint32_t
  2105. APFloat::getHashValue() const
  2106. {
  2107. if (category==fcZero) return sign<<8 | semantics->precision ;
  2108. else if (category==fcInfinity) return sign<<9 | semantics->precision;
  2109. else if (category==fcNaN) return 1<<10 | semantics->precision;
  2110. else {
  2111. uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
  2112. const integerPart* p = significandParts();
  2113. for (int i=partCount(); i>0; i--, p++)
  2114. hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
  2115. return hash;
  2116. }
  2117. }
  2118. // Conversion from APFloat to/from host float/double. It may eventually be
  2119. // possible to eliminate these and have everybody deal with APFloats, but that
  2120. // will take a while. This approach will not easily extend to long double.
  2121. // Current implementation requires integerPartWidth==64, which is correct at
  2122. // the moment but could be made more general.
  2123. // Denormals have exponent minExponent in APFloat, but minExponent-1 in
  2124. // the actual IEEE respresentations. We compensate for that here.
  2125. APInt
  2126. APFloat::convertF80LongDoubleAPFloatToAPInt() const
  2127. {
  2128. assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
  2129. assert (partCount()==2);
  2130. uint64_t myexponent, mysignificand;
  2131. if (category==fcNormal) {
  2132. myexponent = exponent+16383; //bias
  2133. mysignificand = significandParts()[0];
  2134. if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
  2135. myexponent = 0; // denormal
  2136. } else if (category==fcZero) {
  2137. myexponent = 0;
  2138. mysignificand = 0;
  2139. } else if (category==fcInfinity) {
  2140. myexponent = 0x7fff;
  2141. mysignificand = 0x8000000000000000ULL;
  2142. } else {
  2143. assert(category == fcNaN && "Unknown category");
  2144. myexponent = 0x7fff;
  2145. mysignificand = significandParts()[0];
  2146. }
  2147. uint64_t words[2];
  2148. words[0] = mysignificand;
  2149. words[1] = ((uint64_t)(sign & 1) << 15) |
  2150. (myexponent & 0x7fffLL);
  2151. return APInt(80, 2, words);
  2152. }
  2153. APInt
  2154. APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
  2155. {
  2156. assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
  2157. assert (partCount()==2);
  2158. uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
  2159. if (category==fcNormal) {
  2160. myexponent = exponent + 1023; //bias
  2161. myexponent2 = exponent2 + 1023;
  2162. mysignificand = significandParts()[0];
  2163. mysignificand2 = significandParts()[1];
  2164. if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
  2165. myexponent = 0; // denormal
  2166. if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
  2167. myexponent2 = 0; // denormal
  2168. } else if (category==fcZero) {
  2169. myexponent = 0;
  2170. mysignificand = 0;
  2171. myexponent2 = 0;
  2172. mysignificand2 = 0;
  2173. } else if (category==fcInfinity) {
  2174. myexponent = 0x7ff;
  2175. myexponent2 = 0;
  2176. mysignificand = 0;
  2177. mysignificand2 = 0;
  2178. } else {
  2179. assert(category == fcNaN && "Unknown category");
  2180. myexponent = 0x7ff;
  2181. mysignificand = significandParts()[0];
  2182. myexponent2 = exponent2;
  2183. mysignificand2 = significandParts()[1];
  2184. }
  2185. uint64_t words[2];
  2186. words[0] = ((uint64_t)(sign & 1) << 63) |
  2187. ((myexponent & 0x7ff) << 52) |
  2188. (mysignificand & 0xfffffffffffffLL);
  2189. words[1] = ((uint64_t)(sign2 & 1) << 63) |
  2190. ((myexponent2 & 0x7ff) << 52) |
  2191. (mysignificand2 & 0xfffffffffffffLL);
  2192. return APInt(128, 2, words);
  2193. }
  2194. APInt
  2195. APFloat::convertDoubleAPFloatToAPInt() const
  2196. {
  2197. assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
  2198. assert (partCount()==1);
  2199. uint64_t myexponent, mysignificand;
  2200. if (category==fcNormal) {
  2201. myexponent = exponent+1023; //bias
  2202. mysignificand = *significandParts();
  2203. if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
  2204. myexponent = 0; // denormal
  2205. } else if (category==fcZero) {
  2206. myexponent = 0;
  2207. mysignificand = 0;
  2208. } else if (category==fcInfinity) {
  2209. myexponent = 0x7ff;
  2210. mysignificand = 0;
  2211. } else {
  2212. assert(category == fcNaN && "Unknown category!");
  2213. myexponent = 0x7ff;
  2214. mysignificand = *significandParts();
  2215. }
  2216. return APInt(64, ((((uint64_t)(sign & 1) << 63) |
  2217. ((myexponent & 0x7ff) << 52) |
  2218. (mysignificand & 0xfffffffffffffLL))));
  2219. }
  2220. APInt
  2221. APFloat::convertFloatAPFloatToAPInt() const
  2222. {
  2223. assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
  2224. assert (partCount()==1);
  2225. uint32_t myexponent, mysignificand;
  2226. if (category==fcNormal) {
  2227. myexponent = exponent+127; //bias
  2228. mysignificand = (uint32_t)*significandParts();
  2229. if (myexponent == 1 && !(mysignificand & 0x800000))
  2230. myexponent = 0; // denormal
  2231. } else if (category==fcZero) {
  2232. myexponent = 0;
  2233. mysignificand = 0;
  2234. } else if (category==fcInfinity) {
  2235. myexponent = 0xff;
  2236. mysignificand = 0;
  2237. } else {
  2238. assert(category == fcNaN && "Unknown category!");
  2239. myexponent = 0xff;
  2240. mysignificand = (uint32_t)*significandParts();
  2241. }
  2242. return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
  2243. (mysignificand & 0x7fffff)));
  2244. }
  2245. // This function creates an APInt that is just a bit map of the floating
  2246. // point constant as it would appear in memory. It is not a conversion,
  2247. // and treating the result as a normal integer is unlikely to be useful.
  2248. APInt
  2249. APFloat::bitcastToAPInt() const
  2250. {
  2251. if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
  2252. return convertFloatAPFloatToAPInt();
  2253. if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
  2254. return convertDoubleAPFloatToAPInt();
  2255. if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
  2256. return convertPPCDoubleDoubleAPFloatToAPInt();
  2257. assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
  2258. "unknown format!");
  2259. return convertF80LongDoubleAPFloatToAPInt();
  2260. }
  2261. float
  2262. APFloat::convertToFloat() const
  2263. {
  2264. assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
  2265. APInt api = bitcastToAPInt();
  2266. return api.bitsToFloat();
  2267. }
  2268. double
  2269. APFloat::convertToDouble() const
  2270. {
  2271. assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
  2272. APInt api = bitcastToAPInt();
  2273. return api.bitsToDouble();
  2274. }
  2275. /// Integer bit is explicit in this format. Intel hardware (387 and later)
  2276. /// does not support these bit patterns:
  2277. /// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
  2278. /// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
  2279. /// exponent = 0, integer bit 1 ("pseudodenormal")
  2280. /// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
  2281. /// At the moment, the first two are treated as NaNs, the second two as Normal.
  2282. void
  2283. APFloat::initFromF80LongDoubleAPInt(const APInt &api)
  2284. {
  2285. assert(api.getBitWidth()==80);
  2286. uint64_t i1 = api.getRawData()[0];
  2287. uint64_t i2 = api.getRawData()[1];
  2288. uint64_t myexponent = (i2 & 0x7fff);
  2289. uint64_t mysignificand = i1;
  2290. initialize(&APFloat::x87DoubleExtended);
  2291. assert(partCount()==2);
  2292. sign = static_cast<unsigned int>(i2>>15);
  2293. if (myexponent==0 && mysignificand==0) {
  2294. // exponent, significand meaningless
  2295. category = fcZero;
  2296. } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
  2297. // exponent, significand meaningless
  2298. category = fcInfinity;
  2299. } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
  2300. // exponent meaningless
  2301. category = fcNaN;
  2302. significandParts()[0] = mysignificand;
  2303. significandParts()[1] = 0;
  2304. } else {
  2305. category = fcNormal;
  2306. exponent = myexponent - 16383;
  2307. significandParts()[0] = mysignificand;
  2308. significandParts()[1] = 0;
  2309. if (myexponent==0) // denormal
  2310. exponent = -16382;
  2311. }
  2312. }
  2313. void
  2314. APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
  2315. {
  2316. assert(api.getBitWidth()==128);
  2317. uint64_t i1 = api.getRawData()[0];
  2318. uint64_t i2 = api.getRawData()[1];
  2319. uint64_t myexponent = (i1 >> 52) & 0x7ff;
  2320. uint64_t mysignificand = i1 & 0xfffffffffffffLL;
  2321. uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
  2322. uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
  2323. initialize(&APFloat::PPCDoubleDouble);
  2324. assert(partCount()==2);
  2325. sign = static_cast<unsigned int>(i1>>63);
  2326. sign2 = static_cast<unsigned int>(i2>>63);
  2327. if (myexponent==0 && mysignificand==0) {
  2328. // exponent, significand meaningless
  2329. // exponent2 and significand2 are required to be 0; we don't check
  2330. category = fcZero;
  2331. } else if (myexponent==0x7ff && mysignificand==0) {
  2332. // exponent, significand meaningless
  2333. // exponent2 and significand2 are required to be 0; we don't check
  2334. category = fcInfinity;
  2335. } else if (myexponent==0x7ff && mysignificand!=0) {
  2336. // exponent meaningless. So is the whole second word, but keep it
  2337. // for determinism.
  2338. category = fcNaN;
  2339. exponent2 = myexponent2;
  2340. significandParts()[0] = mysignificand;
  2341. significandParts()[1] = mysignificand2;
  2342. } else {
  2343. category = fcNormal;
  2344. // Note there is no category2; the second word is treated as if it is
  2345. // fcNormal, although it might be something else considered by itself.
  2346. exponent = myexponent - 1023;
  2347. exponent2 = myexponent2 - 1023;
  2348. significandParts()[0] = mysignificand;
  2349. significandParts()[1] = mysignificand2;
  2350. if (myexponent==0) // denormal
  2351. exponent = -1022;
  2352. else
  2353. significandParts()[0] |= 0x10000000000000LL; // integer bit
  2354. if (myexponent2==0)
  2355. exponent2 = -1022;
  2356. else
  2357. significandParts()[1] |= 0x10000000000000LL; // integer bit
  2358. }
  2359. }
  2360. void
  2361. APFloat::initFromDoubleAPInt(const APInt &api)
  2362. {
  2363. assert(api.getBitWidth()==64);
  2364. uint64_t i = *api.getRawData();
  2365. uint64_t myexponent = (i >> 52) & 0x7ff;
  2366. uint64_t mysignificand = i & 0xfffffffffffffLL;
  2367. initialize(&APFloat::IEEEdouble);
  2368. assert(partCount()==1);
  2369. sign = static_cast<unsigned int>(i>>63);
  2370. if (myexponent==0 && mysignificand==0) {
  2371. // exponent, significand meaningless
  2372. category = fcZero;
  2373. } else if (myexponent==0x7ff && mysignificand==0) {
  2374. // exponent, significand meaningless
  2375. category = fcInfinity;
  2376. } else if (myexponent==0x7ff && mysignificand!=0) {
  2377. // exponent meaningless
  2378. category = fcNaN;
  2379. *significandParts() = mysignificand;
  2380. } else {
  2381. category = fcNormal;
  2382. exponent = myexponent - 1023;
  2383. *significandParts() = mysignificand;
  2384. if (myexponent==0) // denormal
  2385. exponent = -1022;
  2386. else
  2387. *significandParts() |= 0x10000000000000LL; // integer bit
  2388. }
  2389. }
  2390. void
  2391. APFloat::initFromFloatAPInt(const APInt & api)
  2392. {
  2393. assert(api.getBitWidth()==32);
  2394. uint32_t i = (uint32_t)*api.getRawData();
  2395. uint32_t myexponent = (i >> 23) & 0xff;
  2396. uint32_t mysignificand = i & 0x7fffff;
  2397. initialize(&APFloat::IEEEsingle);
  2398. assert(partCount()==1);
  2399. sign = i >> 31;
  2400. if (myexponent==0 && mysignificand==0) {
  2401. // exponent, significand meaningless
  2402. category = fcZero;
  2403. } else if (myexponent==0xff && mysignificand==0) {
  2404. // exponent, significand meaningless
  2405. category = fcInfinity;
  2406. } else if (myexponent==0xff && mysignificand!=0) {
  2407. // sign, exponent, significand meaningless
  2408. category = fcNaN;
  2409. *significandParts() = mysignificand;
  2410. } else {
  2411. category = fcNormal;
  2412. exponent = myexponent - 127; //bias
  2413. *significandParts() = mysignificand;
  2414. if (myexponent==0) // denormal
  2415. exponent = -126;
  2416. else
  2417. *significandParts() |= 0x800000; // integer bit
  2418. }
  2419. }
  2420. /// Treat api as containing the bits of a floating point number. Currently
  2421. /// we infer the floating point type from the size of the APInt. The
  2422. /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
  2423. /// when the size is anything else).
  2424. void
  2425. APFloat::initFromAPInt(const APInt& api, bool isIEEE)
  2426. {
  2427. if (api.getBitWidth() == 32)
  2428. return initFromFloatAPInt(api);
  2429. else if (api.getBitWidth()==64)
  2430. return initFromDoubleAPInt(api);
  2431. else if (api.getBitWidth()==80)
  2432. return initFromF80LongDoubleAPInt(api);
  2433. else if (api.getBitWidth()==128 && !isIEEE)
  2434. return initFromPPCDoubleDoubleAPInt(api);
  2435. else
  2436. llvm_unreachable();
  2437. }
  2438. APFloat::APFloat(const APInt& api, bool isIEEE)
  2439. {
  2440. initFromAPInt(api, isIEEE);
  2441. }
  2442. APFloat::APFloat(float f)
  2443. {
  2444. APInt api = APInt(32, 0);
  2445. initFromAPInt(api.floatToBits(f));
  2446. }
  2447. APFloat::APFloat(double d)
  2448. {
  2449. APInt api = APInt(64, 0);
  2450. initFromAPInt(api.doubleToBits(d));
  2451. }